chore: 为部分文件添加注释

This commit is contained in:
2026-10-05 21:09:39 +08:00
parent 4811a2d48a
commit adf5fdb6f4
5 changed files with 294 additions and 101 deletions

View File

@@ -43,22 +43,25 @@ type SkillTool struct {
}
// NewToolFactory 创建 ToolFactory.
// router 用于将构建出的 MCP 工具注册并展开为 LLM 可调用的工具列表,可为 nil.
//
// router 用于将构建出的 MCP 工具注册并展开为 LLM 可调用的工具列表, 可为 nil.
func NewToolFactory(router *MCPToolRouter) *ToolFactory {
return &ToolFactory{router: router}
}
// NewSkillFactory 创建 SkillFactory.
// SkillFactory 是无状态的,所有技能信息均从磁盘上的 SKILL.md 扫描获得.
//
// SkillFactory 是无状态的, 所有技能信息均从磁盘上的 SKILL.md 扫描获得.
func NewSkillFactory() *SkillFactory {
return &SkillFactory{}
}
// ports.MCPToolFactory 接口方法实现.
// BuildTools 根据 model.ToolMCPConfig 构建工具列表.
// 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
@@ -67,6 +70,7 @@ func (f *ToolFactory) BuildTools(_ context.Context, config model.ToolMCPConfig)
var (
tools []ports.Tool
)
// 按传输类型构建工具, 兼容 type 为空时直接依据非空字段判断的历史配置
switch {
case kind == "local":
tools, err = buildLocalMCPTools(config.Local)
@@ -84,6 +88,7 @@ func (f *ToolFactory) BuildTools(_ context.Context, config model.ToolMCPConfig)
if err != nil {
return nil, err
}
// 有 router 时注册并展开工具, 例如把 SSE 配置展开为服务端真实工具列表
if f.router != nil {
expanded := make([]ports.Tool, 0, len(tools))
for _, t := range tools {
@@ -93,6 +98,7 @@ func (f *ToolFactory) BuildTools(_ context.Context, config model.ToolMCPConfig)
}
expanded = append(expanded, ts...)
}
// 展开结果为空说明注册失败, 回退到原始工具列表以保证启动不中断
if len(expanded) > 0 {
return expanded, nil
}
@@ -100,15 +106,16 @@ func (f *ToolFactory) BuildTools(_ context.Context, config model.ToolMCPConfig)
return tools, nil
}
// ports.Tool 接口方法实现
// Name 返回工具名.
// Name 返回工具名, 实现 ports.Tool 接口.
func (t MCPTool) Name() string {
return t.ToolName
}
// ports.SkillFactory 接口方法实现
// BuildTools 根据 model.ToolSkillsConfig 扫描目录下的 SKILL.md,构建技能工具列表.
// 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"
@@ -122,10 +129,12 @@ func (f *SkillFactory) BuildTools(_ context.Context, config model.ToolSkillsConf
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
@@ -134,9 +143,10 @@ func (f *SkillFactory) BuildTools(_ context.Context, config model.ToolSkillsConf
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(root, manifest)
tool, err := loadSkillTool(manifest)
if err != nil {
return nil, err
}
@@ -145,16 +155,16 @@ func (f *SkillFactory) BuildTools(_ context.Context, config model.ToolSkillsConf
return tools, nil
}
// ports.Tool 接口方法实现
// Name 返回工具名
// Name 返回工具名, 实现 ports.Tool 接口.
func (t SkillTool) Name() string {
return t.ToolName
}
// resolveSkillRoot
// 将配置中的技能路径解析为实际存在的根路径.
// 支持绝对路径,也支持从当前工作目录逐级向上查找多个相对路径候选.
// resolveSkillRoot 将配置中的技能路径解析为实际存在的根路径.
//
// 支持绝对路径, 也支持从当前工作目录逐级向上查找多个相对路径候选.
func resolveSkillRoot(skillType, rawPath string) (string, error) {
// 绝对路径直接校验
if filepath.IsAbs(rawPath) {
return existingPath(rawPath, rawPath)
}
@@ -164,6 +174,7 @@ func resolveSkillRoot(skillType, rawPath string) (string, error) {
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 {
@@ -173,10 +184,12 @@ func resolveSkillRoot(skillType, rawPath string) (string, error) {
return "", fmt.Errorf("skill path %q cannot be resolved", rawPath)
}
// skillPathCandidates
// 从当前工作目录逐级向上生成技能路径候选,并做去重.
// skillPathCandidates 从当前工作目录逐级向上生成技能路径候选, 并做去重.
//
// 同时兼容直接使用原始相对路径、configs 前缀以及仓库目录名三种常见布局.
func skillPathCandidates(cwd, skillType, rawPath string) []string {
var candidates []string
// 去重后加入候选列表, 避免重复路径被多次校验
add := func(path string) {
clean := filepath.Clean(path)
for _, candidate := range candidates {
@@ -187,6 +200,7 @@ func skillPathCandidates(cwd, skillType, rawPath string) []string {
candidates = append(candidates, clean)
}
// 从当前目录逐级向上尝试, 直到文件系统根目录
for dir := cwd; ; dir = filepath.Dir(dir) {
add(filepath.Join(dir, rawPath))
add(filepath.Join(dir, "configs", rawPath))
@@ -204,8 +218,7 @@ func skillPathCandidates(cwd, skillType, rawPath string) []string {
return candidates
}
// existingPath
// 校验候选路径是否存在,且必须是目录或 SKILL.md 文件.
// existingPath 校验候选路径是否存在, 且必须是目录或 SKILL.md 文件.
func existingPath(candidate, original string) (string, error) {
info, err := os.Stat(candidate)
if err != nil {
@@ -217,17 +230,18 @@ func existingPath(candidate, original string) (string, error) {
return candidate, nil
}
// findSkillManifests
// 在技能根路径下递归查找所有 SKILL.md,并按路径排序保证结果稳定.
// 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 {
@@ -248,9 +262,10 @@ func findSkillManifests(root string) ([]string, error) {
return manifests, nil
}
// loadSkillTool
// 读取并解析单个 SKILL.md,构建 SkillTool.
func loadSkillTool(root, manifest string) (SkillTool, error) {
// 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)
@@ -261,6 +276,7 @@ func loadSkillTool(root, manifest string) (SkillTool, error) {
}
skillDir := filepath.Dir(manifest)
// name 缺失时回退为目录名
name := strings.TrimSpace(meta["name"])
if name == "" {
name = filepath.Base(skillDir)
@@ -276,9 +292,9 @@ func loadSkillTool(root, manifest string) (SkillTool, error) {
}, nil
}
// sanitizeToolName
// 清洗工具名,仅保留字母、数字、下划线和连字符,并限制长度不超过 64 个字符.
// sanitizeToolName 清洗工具名, 仅保留字母、数字、下划线和连字符, 并限制长度不超过 64 个字符.
func sanitizeToolName(name string) string {
// 非法字符统一替换为下划线
var b strings.Builder
for _, r := range name {
switch {
@@ -298,10 +314,12 @@ func sanitizeToolName(name string) string {
return out
}
// parseSkillFrontMatter
// 解析 SKILL.md 头部的 YAML front matter,返回元数据键值对.
// 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
}
@@ -319,9 +337,9 @@ func parseSkillFrontMatter(content string) (map[string]string, error) {
return result, nil
}
// validateMCPConfig
// 校验 MCP 配置必须且只能指定 local、sse、stdio 中的一种,并返回其类型.
// validateMCPConfig 校验 MCP 配置必须且只能指定 local、sse、stdio 中的一种, 并返回其类型.
func validateMCPConfig(config model.ToolMCPConfig) (string, error) {
// 统计非空传输字段, 数量必须恰好为 1
count := 0
kind := ""
if config.Local != nil {
@@ -347,8 +365,7 @@ func validateMCPConfig(config model.ToolMCPConfig) (string, error) {
}
}
// buildLocalMCPTools
// 根据本地工具配置构建 MCPTool,目前仅支持内置的 echoLocalTool.
// buildLocalMCPTools 根据本地工具配置构建 MCPTool, 目前仅支持内置的 echoLocalTool.
func buildLocalMCPTools(config *model.LocalToolParameters) ([]ports.Tool, error) {
name := strings.TrimSpace(config.Name)
if name == "" {
@@ -363,8 +380,9 @@ func buildLocalMCPTools(config *model.LocalToolParameters) ([]ports.Tool, error)
}
}
// buildSSEMCPTools
// 根据 SSE 配置构建 MCPTool,并规范化 base-uri 与 sse-endpoint.
// buildSSEMCPTools 根据 SSE 配置构建 MCPTool, 并规范化 base-uri 与 sse-endpoint.
//
// 返回的工具只保存连接信息, 真正的工具列表由 MCPToolRouter 在注册时从服务端自动发现.
func buildSSEMCPTools(config *model.SSEServerParameters) ([]ports.Tool, error) {
name := strings.TrimSpace(config.Name)
if name == "" {
@@ -375,10 +393,12 @@ func buildSSEMCPTools(config *model.SSEServerParameters) ([]ports.Tool, error) {
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{
@@ -390,8 +410,7 @@ func buildSSEMCPTools(config *model.SSEServerParameters) ([]ports.Tool, error) {
}}, nil
}
// buildStdioMCPTools
// 根据 stdio 配置构建 MCPTool,并拷贝命令参数与环境变量.
// buildStdioMCPTools 根据 stdio 配置构建 MCPTool, 并拷贝命令参数与环境变量.
func buildStdioMCPTools(config *model.StdioServerParameters) ([]ports.Tool, error) {
name := strings.TrimSpace(config.Name)
if name == "" {
@@ -403,6 +422,7 @@ func buildStdioMCPTools(config *model.StdioServerParameters) ([]ports.Tool, erro
}
timeout := normalizeTimeout(config.RequestTimeout)
// Args 与 Env 都做拷贝, 避免运行时对象与配置共享底层数据
return []ports.Tool{MCPTool{
ToolName: name,
TransportType: "stdio",
@@ -413,17 +433,20 @@ func buildStdioMCPTools(config *model.StdioServerParameters) ([]ports.Tool, erro
}}, nil
}
// normalizeSSETarget
// 规范化 SSE 目标地址,将 base-uri 与 endpoint 合并为 (scheme://host, path) 两部分.
// 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 == "" {
@@ -431,6 +454,7 @@ func normalizeSSETarget(baseURI, endpoint string) (string, string, error) {
}
baseQuery := parsed.RawQuery
// endpoint 为空时从 base-uri 的 path 推断
if endpoint == "" {
if basePath == "" || basePath == "/" {
return host, "/sse", nil
@@ -442,6 +466,7 @@ func normalizeSSETarget(baseURI, endpoint string) (string, string, error) {
return host, normalizeEndpoint(merged), nil
}
// 合并 path 与 query, query 部分直接拼接
endpointPath, endpointQuery := splitPathQuery(endpoint)
mergedPath := joinPaths(basePath, endpointPath)
mergedQuery := mergeQueries(baseQuery, endpointQuery)
@@ -451,8 +476,7 @@ func normalizeSSETarget(baseURI, endpoint string) (string, string, error) {
return host, normalizeEndpoint(mergedPath), nil
}
// splitPathQuery
// 将 URL 路径与查询串按第一个 '?' 拆开.
// splitPathQuery 将 URL 路径与查询串按第一个 '?' 拆开.
func splitPathQuery(raw string) (string, string) {
if idx := strings.Index(raw, "?"); idx >= 0 {
return raw[:idx], raw[idx+1:]
@@ -460,8 +484,7 @@ func splitPathQuery(raw string) (string, string) {
return raw, ""
}
// joinPaths
// 拼接 URL 路径,处理空路径、绝对路径和重复斜杠.
// joinPaths 拼接 URL 路径, 处理空路径、绝对路径和重复斜杠.
func joinPaths(base, extra string) string {
if extra == "" {
if base == "" {
@@ -481,8 +504,7 @@ func joinPaths(base, extra string) string {
return base + "/" + extra
}
// mergeQueries
// 合并两段查询串.
// mergeQueries 合并两段查询串.
func mergeQueries(base, extra string) string {
switch {
case base == "" && extra == "":
@@ -496,8 +518,7 @@ func mergeQueries(base, extra string) string {
}
}
// normalizeEndpoint
// 确保端点以 '/' 开头,空值回退为 /sse.
// normalizeEndpoint 确保端点以 '/' 开头, 空值回退为 /sse.
func normalizeEndpoint(endpoint string) string {
trimmed := strings.TrimSpace(endpoint)
if trimmed == "" {
@@ -509,8 +530,7 @@ func normalizeEndpoint(endpoint string) string {
return "/" + trimmed
}
// normalizeTimeout
// 规范化超时毫秒数,非正数时返回默认值 300000(5 分钟).
// normalizeTimeout 规范化超时毫秒数, 非正数时返回默认值 300000(5 分钟).
func normalizeTimeout(timeout int) int {
if timeout > 0 {
return timeout
@@ -518,8 +538,7 @@ func normalizeTimeout(timeout int) int {
return 300000
}
// cloneEnv
// 拷贝环境变量 map,避免运行时对象与配置共享底层数据.
// cloneEnv 拷贝环境变量 map, 避免运行时对象与配置共享底层数据.
func cloneEnv(values map[string]string) map[string]string {
if len(values) == 0 {
return nil
@@ -531,8 +550,9 @@ func cloneEnv(values map[string]string) map[string]string {
return cloned
}
// maskSecretPath
// 对 URL 查询参数中疑似密钥的值进行脱敏,用于日志输出.
// maskSecretPath 对 URL 查询参数中疑似密钥的值进行脱敏, 用于日志输出.
//
// 参数名包含 KEY、TOKEN 或 SECRET 时, 其值会被替换为 ${VAR} 形式的占位符.
func maskSecretPath(raw string) string {
if strings.TrimSpace(raw) == "" {
return raw
@@ -550,6 +570,7 @@ func maskSecretPath(raw string) string {
changed = true
}
}
// 没有敏感参数时原样返回
if !changed {
return raw
}
@@ -557,8 +578,7 @@ func maskSecretPath(raw string) string {
return parsed.String()
}
// mcpTimeoutString
// 将超时毫秒数规范化为字符串.
// mcpTimeoutString 将超时毫秒数规范化为字符串.
func mcpTimeoutString(timeout int) string {
return strconv.Itoa(normalizeTimeout(timeout))
}