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

@@ -57,7 +57,14 @@ func Build(ctx context.Context, appCfg config.Application, logger *zap.Logger) (
agentFactory.UseToolRouter(toolRouter) agentFactory.UseToolRouter(toolRouter)
runnerFactory := agentFactory runnerFactory := agentFactory
armoryFactory := factory.NewDefaultFactory(modelProvider, mcpFactory, skillFactory, agentFactory, runnerFactory, registry) armoryFactory := factory.NewDefaultFactory(
modelProvider,
mcpFactory,
skillFactory,
agentFactory,
runnerFactory,
registry,
)
armoryService := armory.NewService(armoryFactory.ArmoryStrategyHandler()) armoryService := armory.NewService(armoryFactory.ArmoryStrategyHandler())
if err := armoryService.AcceptArmoryAgents(ctx, tables); err != nil { if err := armoryService.AcceptArmoryAgents(ctx, tables); err != nil {

View File

@@ -42,6 +42,9 @@ func NewFactory() *Factory {
return &Factory{plugins: defaultPlugins()} return &Factory{plugins: defaultPlugins()}
} }
// UseToolRouter 注入工具路由器.
//
// 该路由器会被后续创建的所有 Agent 共享, Agent 在模型请求工具调用时通过它执行工具.
func (f *Factory) UseToolRouter(router ports.ToolRouter) { func (f *Factory) UseToolRouter(router ports.ToolRouter) {
f.router = router f.router = router
} }
@@ -103,19 +106,28 @@ func newWorkflowAgent(kind string, config model.AgentWorkflowConfig, subAgents [
}, nil }, nil
} }
// Name 返回 Agent 名称, 实现 ports.Agent 接口.
func (a *Agent) Name() string { func (a *Agent) Name() string {
return a.name return a.name
} }
// Description 返回 Agent 描述信息, 主要用于日志和外部展示.
func (a *Agent) Description() string { func (a *Agent) Description() string {
return a.description return a.description
} }
// run 以空变量作用域执行 Agent.
//
// 包内普通执行入口, 调用 runWithVars 并传入空的模板变量表.
func (a *Agent) run(ctx context.Context, content model.ChatContent) (string, error) { func (a *Agent) run(ctx context.Context, content model.ChatContent) (string, error) {
return a.runWithVars(ctx, content, map[string]string{}) return a.runWithVars(ctx, content, map[string]string{})
} }
// runWithVars 根据 Agent 类型分派到具体执行逻辑.
//
// vars 保存 Sequential 工作流传入的模板变量, 供 instruction 中的 {output-key} 占位符替换使用.
func (a *Agent) runWithVars(ctx context.Context, content model.ChatContent, vars map[string]string) (string, error) { func (a *Agent) runWithVars(ctx context.Context, content model.ChatContent, vars map[string]string) (string, error) {
// 按 kind 分派到 LLM / 串行 / 并行 / 循环执行策略
switch a.kind { switch a.kind {
case "llm": case "llm":
return a.runLLM(ctx, content, vars) return a.runLLM(ctx, content, vars)
@@ -128,6 +140,10 @@ func (a *Agent) runWithVars(ctx context.Context, content model.ChatContent, vars
} }
} }
// stream 以流式方式执行 Agent.
//
// 仅 llm 类型支持真正的逐 token 流式输出;
// workflow 类型没有独立的模型流, 因此先完整执行, 再把最终结果一次性写入 out.
func (a *Agent) stream(ctx context.Context, content model.ChatContent, out chan<- string) error { func (a *Agent) stream(ctx context.Context, content model.ChatContent, out chan<- string) error {
switch a.kind { switch a.kind {
case "llm": case "llm":
@@ -148,36 +164,54 @@ func (a *Agent) stream(ctx context.Context, content model.ChatContent, out chan<
} }
} }
// runLLM 执行非流式 Tool-Calling Loop.
//
// 每次循环调用一次模型:
// 1. 模型未返回工具调用时, 直接返回最终文本;
// 2. 模型返回工具调用时, 先追加 assistant 消息, 再执行工具并把 tool 结果追加到消息列表;
// 3. 重复上述过程, 最多迭代 maxToolCallIterations 次.
func (a *Agent) runLLM(ctx context.Context, content model.ChatContent, vars map[string]string) (string, error) { func (a *Agent) runLLM(ctx context.Context, content model.ChatContent, vars map[string]string) (string, error) {
messages := initialMessages(applyVars(a.instruction, vars), firstText(content)) messages := initialMessages(applyVars(a.instruction, vars), firstText(content))
// 最多执行 maxToolCallIterations 轮 模型调用 -> 工具执行 -> 结果回灌
for iter := 0; iter < maxToolCallIterations; iter++ { for iter := 0; iter < maxToolCallIterations; iter++ {
reply, err := a.chatModel.Generate(ctx, messages) reply, err := a.chatModel.Generate(ctx, messages)
if err != nil { if err != nil {
return "", err return "", err
} }
// 没有工具调用, 模型已给出最终答案
if len(reply.ToolCalls) == 0 { if len(reply.ToolCalls) == 0 {
return reply.Content, nil return reply.Content, nil
} }
// 追加 assistant 消息, 保留模型请求的 tool_calls
messages = append(messages, ports.ChatMessage{Role: ports.ChatRoleAssistant, Content: reply.Content, ToolCalls: reply.ToolCalls}) messages = append(messages, ports.ChatMessage{Role: ports.ChatRoleAssistant, Content: reply.Content, ToolCalls: reply.ToolCalls})
toolMessages, err := a.executeToolCalls(ctx, reply.ToolCalls) toolMessages, err := a.executeToolCalls(ctx, reply.ToolCalls)
if err != nil { if err != nil {
return "", err return "", err
} }
// 把工具结果回灌到消息列表, 供下一轮模型使用
messages = append(messages, toolMessages...) messages = append(messages, toolMessages...)
} }
return "", fmt.Errorf("agent %q exceeded tool-call iteration limit %d", a.name, maxToolCallIterations) return "", fmt.Errorf("agent %q exceeded tool-call iteration limit %d", a.name, maxToolCallIterations)
} }
// streamLLM 执行流式 Tool-Calling Loop.
//
// 与 runLLM 的区别是: 模型返回的文本增量会实时写入 out;
// 同时使用 finalText 暂存本轮完整文本, 用于在模型请求工具调用时构造 assistant 消息.
// 工具调用执行完成后结果会被追加到消息列表, 并进入下一轮模型调用, 最多迭代 maxToolCallIterations 次.
func (a *Agent) streamLLM(ctx context.Context, content model.ChatContent, out chan<- string, vars map[string]string) error { func (a *Agent) streamLLM(ctx context.Context, content model.ChatContent, out chan<- string, vars map[string]string) error {
messages := initialMessages(applyVars(a.instruction, vars), firstText(content)) messages := initialMessages(applyVars(a.instruction, vars), firstText(content))
// 最多执行 maxToolCallIterations 轮流式 Tool-Calling
for iter := 0; iter < maxToolCallIterations; iter++ { for iter := 0; iter < maxToolCallIterations; iter++ {
events, errs := a.chatModel.Stream(ctx, messages) events, errs := a.chatModel.Stream(ctx, messages)
// finalText 暂存本轮完整文本; toolCalls 收集工具调用; done 标记流是否正常结束
var ( var (
finalText strings.Builder finalText strings.Builder
toolCalls []ports.ChatToolCall toolCalls []ports.ChatToolCall
done bool done bool
) )
streamErr := error(nil) streamErr := error(nil)
// 标签用于从嵌套 select 中直接跳出读取循环
streamLoop: streamLoop:
for { for {
select { select {
@@ -191,6 +225,7 @@ func (a *Agent) streamLLM(ctx context.Context, content model.ChatContent, out ch
if ev.Done { if ev.Done {
done = true done = true
} }
// 文本增量: 写入完整文本并转发给下游
if ev.Delta != "" { if ev.Delta != "" {
finalText.WriteString(ev.Delta) finalText.WriteString(ev.Delta)
select { select {
@@ -213,12 +248,15 @@ func (a *Agent) streamLLM(ctx context.Context, content model.ChatContent, out ch
if streamErr != nil { if streamErr != nil {
return streamErr return streamErr
} }
// 没有工具调用, 本轮文本就是最终答案
if len(toolCalls) == 0 { if len(toolCalls) == 0 {
// 缺少 Done 标记, 视为流异常关闭
if !done { if !done {
return fmt.Errorf("agent %q stream closed without completion", a.name) return fmt.Errorf("agent %q stream closed without completion", a.name)
} }
return nil return nil
} }
// 追加 assistant 消息, 保留文本和工具调用
messages = append(messages, ports.ChatMessage{Role: ports.ChatRoleAssistant, Content: finalText.String(), ToolCalls: toolCalls}) messages = append(messages, ports.ChatMessage{Role: ports.ChatRoleAssistant, Content: finalText.String(), ToolCalls: toolCalls})
toolMessages, err := a.executeToolCalls(ctx, toolCalls) toolMessages, err := a.executeToolCalls(ctx, toolCalls)
if err != nil { if err != nil {
@@ -229,7 +267,12 @@ func (a *Agent) streamLLM(ctx context.Context, content model.ChatContent, out ch
return fmt.Errorf("agent %q exceeded tool-call iteration limit %d", a.name, maxToolCallIterations) return fmt.Errorf("agent %q exceeded tool-call iteration limit %d", a.name, maxToolCallIterations)
} }
// executeToolCalls 依次执行模型请求的工具调用.
//
// 每个工具通过 ToolRouter 执行, 返回结果会被转换为 role=tool 的 ChatMessage,
// 并通过 ToolCallID 与 assistant 消息中的工具调用一一对应.
func (a *Agent) executeToolCalls(ctx context.Context, calls []ports.ChatToolCall) ([]ports.ChatMessage, error) { func (a *Agent) executeToolCalls(ctx context.Context, calls []ports.ChatToolCall) ([]ports.ChatMessage, error) {
// 模型请求了工具但未注入路由器, 属于非法状态
if a.router == nil { if a.router == nil {
return nil, fmt.Errorf("agent %q has no tool router but model requested tool calls", a.name) return nil, fmt.Errorf("agent %q has no tool router but model requested tool calls", a.name)
} }
@@ -239,6 +282,7 @@ func (a *Agent) executeToolCalls(ctx context.Context, calls []ports.ChatToolCall
if err != nil { if err != nil {
return nil, fmt.Errorf("tool %q: %w", call.Name, err) return nil, fmt.Errorf("tool %q: %w", call.Name, err)
} }
// 包装为 role=tool 的消息, 通过 ToolCallID 与 assistant 消息对应
out = append(out, ports.ChatMessage{ out = append(out, ports.ChatMessage{
Role: ports.ChatRoleTool, Role: ports.ChatRoleTool,
Content: result, Content: result,
@@ -249,19 +293,29 @@ func (a *Agent) executeToolCalls(ctx context.Context, calls []ports.ChatToolCall
return out, nil return out, nil
} }
// runSequential 执行串行工作流.
//
// 子 Agent 按配置顺序依次执行, 每个子 Agent 的输出在存在 output-key 时写入 scope;
// 后续子 Agent 的 instruction 可以通过 {output-key} 引用前面步骤的结果.
// 返回值是最后一个子 Agent 的输出.
func (a *Agent) runSequential(ctx context.Context, content model.ChatContent, vars map[string]string) (string, error) { func (a *Agent) runSequential(ctx context.Context, content model.ChatContent, vars map[string]string) (string, error) {
// 复制变量表, 避免污染外层作用域
scope := cloneVars(vars) scope := cloneVars(vars)
// 记录最后一个子 Agent 的输出作为工作流返回值
var last string var last string
for _, sub := range a.subAgents { for _, sub := range a.subAgents {
// 当前实现要求子 Agent 必须是 adk.Agent
impl, ok := sub.(*Agent) impl, ok := sub.(*Agent)
if !ok { if !ok {
return "", fmt.Errorf("sub-agent %q is not a runnable agent", sub.Name()) return "", fmt.Errorf("sub-agent %q is not a runnable agent", sub.Name())
} }
// 使用当前 scope 执行, 使 instruction 能读取已产生的变量
text, err := impl.runWithVars(ctx, content, scope) text, err := impl.runWithVars(ctx, content, scope)
if err != nil { if err != nil {
return "", err return "", err
} }
last = text last = text
// 配置了 output-key 时把输出写入变量表
if key := strings.TrimSpace(impl.outputKey); key != "" { if key := strings.TrimSpace(impl.outputKey); key != "" {
scope[key] = text scope[key] = text
} }
@@ -269,22 +323,33 @@ func (a *Agent) runSequential(ctx context.Context, content model.ChatContent, va
return last, nil return last, nil
} }
// runFanOut 执行并行/循环工作流的聚合逻辑.
//
// 当前实现会依次执行所有子 Agent, 并把每个子 Agent 的输出以 [AgentName] 前缀拼接返回.
// 注意: 当前 loop 和 parallel 都复用该逻辑, 并未真正实现并发或循环迭代.
func (a *Agent) runFanOut(ctx context.Context, content model.ChatContent, vars map[string]string) (string, error) { func (a *Agent) runFanOut(ctx context.Context, content model.ChatContent, vars map[string]string) (string, error) {
parts := make([]string, 0, len(a.subAgents)) parts := make([]string, 0, len(a.subAgents))
// 依次执行所有子 Agent (当前实现并未真正并发)
for _, sub := range a.subAgents { for _, sub := range a.subAgents {
// 同样要求子 Agent 必须是 adk.Agent
impl, ok := sub.(*Agent) impl, ok := sub.(*Agent)
if !ok { if !ok {
return "", fmt.Errorf("sub-agent %q is not a runnable agent", sub.Name()) return "", fmt.Errorf("sub-agent %q is not a runnable agent", sub.Name())
} }
// 所有子 Agent 共享同一份输入变量
text, err := impl.runWithVars(ctx, content, vars) text, err := impl.runWithVars(ctx, content, vars)
if err != nil { if err != nil {
return "", err return "", err
} }
// 输出带 Agent 名前缀, 方便上层区分来源
parts = append(parts, fmt.Sprintf("[%s] %s", sub.Name(), text)) parts = append(parts, fmt.Sprintf("[%s] %s", sub.Name(), text))
} }
return strings.Join(parts, "\n"), nil return strings.Join(parts, "\n"), nil
} }
// cloneVars 复制变量表.
//
// Sequential 工作流使用副本保存本步骤的输出, 避免修改调用方传入的原始变量.
func cloneVars(vars map[string]string) map[string]string { func cloneVars(vars map[string]string) map[string]string {
out := make(map[string]string, len(vars)+4) out := make(map[string]string, len(vars)+4)
for k, v := range vars { for k, v := range vars {
@@ -293,6 +358,9 @@ func cloneVars(vars map[string]string) map[string]string {
return out return out
} }
// applyVars 将模板中的 {key} 占位符替换为 vars 中对应的值.
//
// 模板为空或变量表为空时直接返回模板; 替换使用简单的字符串匹配, 不做转义处理.
func applyVars(template string, vars map[string]string) string { func applyVars(template string, vars map[string]string) string {
if template == "" || len(vars) == 0 { if template == "" || len(vars) == 0 {
return template return template
@@ -304,6 +372,10 @@ func applyVars(template string, vars map[string]string) string {
return out return out
} }
// initialMessages 构造一次模型调用的初始消息列表.
//
// instruction 非空时作为 system 消息; 用户输入始终作为 user 消息.
// 当前实现不保存跨轮对话历史, 每次执行都从 system + user 重新开始.
func initialMessages(instruction, userText string) []ports.ChatMessage { func initialMessages(instruction, userText string) []ports.ChatMessage {
messages := make([]ports.ChatMessage, 0, 2) messages := make([]ports.ChatMessage, 0, 2)
if strings.TrimSpace(instruction) != "" { if strings.TrimSpace(instruction) != "" {
@@ -313,14 +385,21 @@ func initialMessages(instruction, userText string) []ports.ChatMessage {
return messages return messages
} }
// CreateSession 根据用户 ID 和应用名生成会话 ID.
//
// 会话 ID 格式为 appName:userID:序号, 序号来自 Factory 的全局原子计数器.
func (r *Runner) CreateSession(userID string) (string, error) { func (r *Runner) CreateSession(userID string) (string, error) {
if strings.TrimSpace(userID) == "" { if strings.TrimSpace(userID) == "" {
return "", fmt.Errorf("user id is required") return "", fmt.Errorf("user id is required")
} }
// 全局原子自增, 保证所有 Runner 的会话序号不冲突
next := r.counter.Add(1) next := r.counter.Add(1)
return fmt.Sprintf("%s:%s:%d", r.appName, userID, next), nil return fmt.Sprintf("%s:%s:%d", r.appName, userID, next), nil
} }
// Run 以非流式方式执行 Runner 持有的入口 Agent.
//
// 执行前先通知插件, 然后把内容委托给 Agent.run, 并把最终文本包装为 []string 返回.
func (r *Runner) Run(userID, sessionID string, content model.ChatContent) ([]string, error) { func (r *Runner) Run(userID, sessionID string, content model.ChatContent) ([]string, error) {
if strings.TrimSpace(userID) == "" || strings.TrimSpace(sessionID) == "" { if strings.TrimSpace(userID) == "" || strings.TrimSpace(sessionID) == "" {
return nil, fmt.Errorf("user id and session id are required") return nil, fmt.Errorf("user id and session id are required")
@@ -328,6 +407,7 @@ func (r *Runner) Run(userID, sessionID string, content model.ChatContent) ([]str
if err := r.notifyPlugins(userID, sessionID, content); err != nil { if err := r.notifyPlugins(userID, sessionID, content); err != nil {
return nil, err return nil, err
} }
// Runner 只能运行 adk.Agent, 这里做类型断言
impl, ok := r.agent.(*Agent) impl, ok := r.agent.(*Agent)
if !ok { if !ok {
return nil, fmt.Errorf("runner agent %q is not runnable", r.agent.Name()) return nil, fmt.Errorf("runner agent %q is not runnable", r.agent.Name())
@@ -342,6 +422,10 @@ func (r *Runner) Run(userID, sessionID string, content model.ChatContent) ([]str
return []string{output}, nil return []string{output}, nil
} }
// Stream 以流式方式执行 Runner 持有的入口 Agent.
//
// 方法在 goroutine 中执行, 返回文本输出 channel 和错误 channel;
// 调用方通过这两个 channel 消费执行过程中的增量结果.
func (r *Runner) Stream(userID, sessionID string, content model.ChatContent) (<-chan string, <-chan error) { func (r *Runner) Stream(userID, sessionID string, content model.ChatContent) (<-chan string, <-chan error) {
outputs := make(chan string, 8) outputs := make(chan string, 8)
errs := make(chan error, 1) errs := make(chan error, 1)
@@ -356,6 +440,7 @@ func (r *Runner) Stream(userID, sessionID string, content model.ChatContent) (<-
errs <- err errs <- err
return return
} }
// Runner 只能运行 adk.Agent, 这里做类型断言
impl, ok := r.agent.(*Agent) impl, ok := r.agent.(*Agent)
if !ok { if !ok {
errs <- fmt.Errorf("runner agent %q is not runnable", r.agent.Name()) errs <- fmt.Errorf("runner agent %q is not runnable", r.agent.Name())
@@ -368,6 +453,10 @@ func (r *Runner) Stream(userID, sessionID string, content model.ChatContent) (<-
return outputs, errs return outputs, errs
} }
// notifyPlugins 按配置顺序通知所有 RunnerPlugin.
//
// 对每个插件依次触发 OnUserMessage 和 BeforeAgent 两个生命周期回调,
// 任一回调返回错误都会中止后续执行.
func (r *Runner) notifyPlugins(userID, sessionID string, content model.ChatContent) error { func (r *Runner) notifyPlugins(userID, sessionID string, content model.ChatContent) error {
for _, item := range r.plugins { for _, item := range r.plugins {
if err := item.OnUserMessage(context.Background(), r.appName, userID, sessionID, r.agent, content); err != nil { if err := item.OnUserMessage(context.Background(), r.appName, userID, sessionID, r.agent, content); err != nil {
@@ -380,6 +469,9 @@ func (r *Runner) notifyPlugins(userID, sessionID string, content model.ChatConte
return nil return nil
} }
// firstText 返回 ChatContent 中的第一段文本.
//
// 当前模型调用主要使用文本输入, 文件与内联数据暂未参与消息构造.
func firstText(content model.ChatContent) string { func firstText(content model.ChatContent) string {
if len(content.Texts) == 0 { if len(content.Texts) == 0 {
return "" return ""
@@ -387,6 +479,9 @@ func firstText(content model.ChatContent) string {
return content.Texts[0].Message return content.Texts[0].Message
} }
// defaultPlugins 返回内置的 RunnerPlugin 工厂表.
//
// key 是 YAML 中配置的插件名, value 用于按需创建插件实例.
func defaultPlugins() map[string]func() (ports.RunnerPlugin, error) { func defaultPlugins() map[string]func() (ports.RunnerPlugin, error) {
return map[string]func() (ports.RunnerPlugin, error){ return map[string]func() (ports.RunnerPlugin, error){
"myTestPlugin": newMyTestPlugin, "myTestPlugin": newMyTestPlugin,
@@ -400,6 +495,9 @@ func defaultPlugins() map[string]func() (ports.RunnerPlugin, error) {
} }
} }
// resolvePlugins 根据插件名列表解析并创建 RunnerPlugin 实例.
//
// 列表中不存在的插件名会直接返回错误, 保证装配阶段就能发现配置问题.
func (f *Factory) resolvePlugins(names []string) ([]ports.RunnerPlugin, error) { func (f *Factory) resolvePlugins(names []string) ([]ports.RunnerPlugin, error) {
if len(names) == 0 { if len(names) == 0 {
return nil, nil return nil, nil
@@ -411,6 +509,7 @@ func (f *Factory) resolvePlugins(names []string) ([]ports.RunnerPlugin, error) {
continue continue
} }
builder, ok := f.plugins[pluginName] builder, ok := f.plugins[pluginName]
// 未注册的插件名在装配阶段直接报错
if !ok { if !ok {
return nil, fmt.Errorf("runner plugin %q is not registered", pluginName) return nil, fmt.Errorf("runner plugin %q is not registered", pluginName)
} }
@@ -429,15 +528,18 @@ func newMyTestPlugin() (ports.RunnerPlugin, error) {
type myTestPlugin struct{} type myTestPlugin struct{}
// Name 返回插件名, 用于错误信息和日志展示.
func (myTestPlugin) Name() string { func (myTestPlugin) Name() string {
return "myTestPlugin" return "myTestPlugin"
} }
// OnUserMessage 在用户消息到达时打印调试信息.
func (myTestPlugin) OnUserMessage(_ context.Context, _, _, _ string, _ ports.Agent, content model.ChatContent) error { func (myTestPlugin) OnUserMessage(_ context.Context, _, _, _ string, _ ports.Agent, content model.ChatContent) error {
fmt.Printf("[myTestPlugin] 用户输入信息:%s\n", firstText(content)) fmt.Printf("[myTestPlugin] 用户输入信息:%s\n", firstText(content))
return nil return nil
} }
// BeforeAgent 在 Agent 开始执行前打印 Agent 名称.
func (myTestPlugin) BeforeAgent(_ context.Context, _, _, _ string, agent ports.Agent) error { func (myTestPlugin) BeforeAgent(_ context.Context, _, _, _ string, agent ports.Agent) error {
fmt.Printf("[myTestPlugin] 智能体名称:%s\n", agent.Name()) fmt.Printf("[myTestPlugin] 智能体名称:%s\n", agent.Name())
return nil return nil
@@ -448,10 +550,12 @@ type adkRunnerPlugin struct {
plugin *plugin.Plugin plugin *plugin.Plugin
} }
// Name 返回 ADK 插件包装器的名称.
func (p adkRunnerPlugin) Name() string { func (p adkRunnerPlugin) Name() string {
return p.name return p.name
} }
// OnUserMessage 在 ADK 插件注册了用户消息回调时打印调试信息.
func (p adkRunnerPlugin) OnUserMessage(_ context.Context, _, _, _ string, _ ports.Agent, content model.ChatContent) error { func (p adkRunnerPlugin) OnUserMessage(_ context.Context, _, _, _ string, _ ports.Agent, content model.ChatContent) error {
if p.plugin.OnUserMessageCallback() != nil { if p.plugin.OnUserMessageCallback() != nil {
fmt.Printf("[%s] USER MESSAGE RECEIVED %s\n", p.name, firstText(content)) fmt.Printf("[%s] USER MESSAGE RECEIVED %s\n", p.name, firstText(content))
@@ -459,6 +563,7 @@ func (p adkRunnerPlugin) OnUserMessage(_ context.Context, _, _, _ string, _ port
return nil return nil
} }
// BeforeAgent 在 ADK 插件注册了 Agent 开始回调时打印调试信息.
func (p adkRunnerPlugin) BeforeAgent(_ context.Context, _, _, _ string, agent ports.Agent) error { func (p adkRunnerPlugin) BeforeAgent(_ context.Context, _, _, _ string, agent ports.Agent) error {
if p.plugin.BeforeAgentCallback() != nil { if p.plugin.BeforeAgentCallback() != nil {
fmt.Printf("[%s] AGENT STARTING %s\n", p.name, agent.Name()) fmt.Printf("[%s] AGENT STARTING %s\n", p.name, agent.Name())

View File

@@ -39,8 +39,9 @@ type MCPSSEClient struct {
endpointSig chan struct{} endpointSig chan struct{}
} }
// NewMCPSSEClient // NewMCPSSEClient 创建一个 MCP SSE 客户端实例.
// 创建一个 MCP SSE 客户端实例. baseURI 为服务端基础地址, endpoint 为 SSE 端点路径, requestTimeoutMillis 为单次 RPC 调用的超时毫秒数. //
// baseURI 为服务端基础地址, endpoint 为 SSE 端点路径, requestTimeoutMillis 为单次 RPC 调用的超时毫秒数.
// 该函数只初始化配置, 不会建立连接, 连接会在首次调用工具或列出工具时按需建立. // 该函数只初始化配置, 不会建立连接, 连接会在首次调用工具或列出工具时按需建立.
func NewMCPSSEClient(baseURI, endpoint string, requestTimeoutMillis int) *MCPSSEClient { func NewMCPSSEClient(baseURI, endpoint string, requestTimeoutMillis int) *MCPSSEClient {
timeout := time.Duration(requestTimeoutMillis) * time.Millisecond timeout := time.Duration(requestTimeoutMillis) * time.Millisecond
@@ -55,9 +56,10 @@ func NewMCPSSEClient(baseURI, endpoint string, requestTimeoutMillis int) *MCPSSE
} }
} }
// ensureStarted // ensureStarted 确保 SSE 连接已经建立.
// 确保 SSE 连接已经建立. //
// 若尚未启动, 则依次完成: 发起 SSE 长连接、等待服务端下发 endpoint 事件、完成 JSON-RPC 初始化握手; 失败时调用 shutdown 重置状态. // 若尚未启动, 则依次完成: 发起 SSE 长连接、等待服务端下发 endpoint 事件、完成 JSON-RPC 初始化握手;
// 失败时调用 shutdown 重置状态.
func (c *MCPSSEClient) ensureStarted(ctx context.Context) error { func (c *MCPSSEClient) ensureStarted(ctx context.Context) error {
c.mu.Lock() c.mu.Lock()
if c.started { if c.started {
@@ -99,8 +101,9 @@ func (c *MCPSSEClient) ensureStarted(ctx context.Context) error {
return nil return nil
} }
// openSSE // openSSE 向服务端发起 GET 请求建立 SSE 长连接
// 向服务端发起 GET 请求建立 SSE 长连接, 并在成功后启动后台 readLoop goroutine 持续读取事件流. //
// 成功后会启动后台 readLoop goroutine 持续读取事件流.
func (c *MCPSSEClient) openSSE(ctx context.Context) error { func (c *MCPSSEClient) openSSE(ctx context.Context) error {
target := c.baseURI + c.endpoint target := c.baseURI + c.endpoint
req, err := http.NewRequestWithContext(ctx, http.MethodGet, target, nil) req, err := http.NewRequestWithContext(ctx, http.MethodGet, target, nil)
@@ -121,8 +124,9 @@ func (c *MCPSSEClient) openSSE(ctx context.Context) error {
return nil return nil
} }
// readLoop // readLoop 在后台 goroutine 中持续读取 SSE 事件流
// 在后台 goroutine 中持续读取 SSE 事件流, 按 event/data 行解析事件, 并在事件结束时根据事件类型分发处理; //
// 按 event/data 行解析事件, 并在事件结束时根据事件类型分发处理;
// 读取失败时会通知所有等待中的 RPC 调用. // 读取失败时会通知所有等待中的 RPC 调用.
func (c *MCPSSEClient) readLoop(resp *http.Response) { func (c *MCPSSEClient) readLoop(resp *http.Response) {
defer resp.Body.Close() defer resp.Body.Close()
@@ -172,8 +176,10 @@ func (c *MCPSSEClient) readLoop(resp *http.Response) {
} }
} }
// handleEndpoint // handleEndpoint 处理 SSE 的 endpoint 事件
// 处理 SSE 的 endpoint 事件, 解析并记录服务端下发的 POST 消息地址; 若已记录过地址, 则尝试将数据按普通 message 事件处理. //
// 解析并记录服务端下发的 POST 消息地址;
// 若已记录过地址, 则尝试将数据按普通 message 事件处理.
func (c *MCPSSEClient) handleEndpoint(data, eventName string) { func (c *MCPSSEClient) handleEndpoint(data, eventName string) {
if c.postURLAlreadySet() { if c.postURLAlreadySet() {
if eventName == "" { if eventName == "" {
@@ -190,16 +196,15 @@ func (c *MCPSSEClient) handleEndpoint(data, eventName string) {
c.mu.Unlock() c.mu.Unlock()
} }
// postURLAlreadySet // postURLAlreadySet 返回当前是否已经记录 POST 消息地址.
// 返回当前是否已经记录 POST 消息地址.
func (c *MCPSSEClient) postURLAlreadySet() bool { func (c *MCPSSEClient) postURLAlreadySet() bool {
c.mu.Lock() c.mu.Lock()
defer c.mu.Unlock() defer c.mu.Unlock()
return c.postURL != "" return c.postURL != ""
} }
// resolvePostURL // resolvePostURL 将服务端返回的 endpoint 数据解析为完整可用的 POST 地址;
// 将服务端返回的 endpoint 数据解析为完整可用的 POST 地址; //
// 若数据为相对路径, 则基于 baseURI 进行解析. // 若数据为相对路径, 则基于 baseURI 进行解析.
func (c *MCPSSEClient) resolvePostURL(raw string) string { func (c *MCPSSEClient) resolvePostURL(raw string) string {
parsed, err := url.Parse(raw) parsed, err := url.Parse(raw)
@@ -215,8 +220,9 @@ func (c *MCPSSEClient) resolvePostURL(raw string) string {
return raw return raw
} }
// handleMessage // handleMessage 处理 SSE 的 message 事件
// 处理 SSE 的 message 事件: 解析 JSON-RPC 2.0 响应, 根据响应 ID 找到对应的等待 channel 并投递结果或错误. //
// 解析 JSON-RPC 2.0 响应, 根据响应 ID 找到对应的等待 channel 并投递结果或错误.
func (c *MCPSSEClient) handleMessage(data string) { func (c *MCPSSEClient) handleMessage(data string) {
var resp struct { var resp struct {
ID json.Number `json:"id"` ID json.Number `json:"id"`
@@ -254,14 +260,16 @@ func (c *MCPSSEClient) handleMessage(data string) {
close(ch) close(ch)
} }
// mustJSON 将任意值序列化为 JSON 字节; // mustJSON 将任意值序列化为 JSON 字节
//
// 这里仅用于构造错误包装对象, 因此忽略序列化错误. // 这里仅用于构造错误包装对象, 因此忽略序列化错误.
func mustJSON(v any) json.RawMessage { func mustJSON(v any) json.RawMessage {
raw, _ := json.Marshal(v) raw, _ := json.Marshal(v)
return raw return raw
} }
// signalStreamErr // signalStreamErr 错误广播
//
// 在 SSE 流读取失败时向所有等待中的 RPC 调用广播错误, 并清理 pending 映射, 避免 goroutine 泄漏. // 在 SSE 流读取失败时向所有等待中的 RPC 调用广播错误, 并清理 pending 映射, 避免 goroutine 泄漏.
func (c *MCPSSEClient) signalStreamErr(err error) { func (c *MCPSSEClient) signalStreamErr(err error) {
c.mu.Lock() c.mu.Lock()
@@ -277,8 +285,9 @@ func (c *MCPSSEClient) signalStreamErr(err error) {
} }
} }
// shutdown // shutdown 取消后台读取 goroutine 并重置客户端状态
// 取消后台读取 goroutine 并重置客户端状态, 使客户端可以再次尝试启动. //
// 状态重置后客户端可以再次尝试启动.
func (c *MCPSSEClient) shutdown() { func (c *MCPSSEClient) shutdown() {
c.mu.Lock() c.mu.Lock()
defer c.mu.Unlock() defer c.mu.Unlock()
@@ -290,8 +299,9 @@ func (c *MCPSSEClient) shutdown() {
c.pending = nil c.pending = nil
} }
// initialize // initialize 执行 MCP 协议初始化握手
// 执行 MCP 协议初始化握手: 发送 initialize 请求, 随后发送 notifications/initialized 通知. //
// 发送 initialize 请求, 随后发送 notifications/initialized 通知.
func (c *MCPSSEClient) initialize(ctx context.Context) error { func (c *MCPSSEClient) initialize(ctx context.Context) error {
_, err := c.callRPC(ctx, "initialize", map[string]any{ _, err := c.callRPC(ctx, "initialize", map[string]any{
"protocolVersion": mcpProtocolVersion, "protocolVersion": mcpProtocolVersion,
@@ -310,8 +320,9 @@ func (c *MCPSSEClient) initialize(ctx context.Context) error {
return nil return nil
} }
// CallTool // CallTool 调用指定的 MCP 工具
// 调用指定的 MCP 工具: 确保连接已建立后, 将工具名与 JSON 参数通过 tools/call 发送给服务端, 并返回提取后的文本结果. //
// 确保连接已建立后, 将工具名与 JSON 参数通过 tools/call 发送给服务端, 并返回提取后的文本结果.
func (c *MCPSSEClient) CallTool(ctx context.Context, name, arguments string) (string, error) { func (c *MCPSSEClient) CallTool(ctx context.Context, name, arguments string) (string, error) {
if err := c.ensureStarted(ctx); err != nil { if err := c.ensureStarted(ctx); err != nil {
return "", err return "", err
@@ -333,8 +344,7 @@ func (c *MCPSSEClient) CallTool(ctx context.Context, name, arguments string) (st
return extractToolText(result), nil return extractToolText(result), nil
} }
// ListTools // ListTools 调用 tools/list 获取服务端暴露的工具列表, 并返回所有工具名.
// 调用 tools/list 获取服务端暴露的工具列表, 并返回所有工具名.
func (c *MCPSSEClient) ListTools(ctx context.Context) ([]string, error) { func (c *MCPSSEClient) ListTools(ctx context.Context) ([]string, error) {
if err := c.ensureStarted(ctx); err != nil { if err := c.ensureStarted(ctx); err != nil {
return nil, err return nil, err
@@ -366,8 +376,8 @@ type toolCallResult struct {
IsError bool `json:"isError"` IsError bool `json:"isError"`
} }
// extractToolText // extractToolText 从 MCP 工具调用的原始响应中提取文本内容
// 从 MCP 工具调用的原始响应中提取文本内容; //
// 若响应不符合标准结构, 则返回原始 JSON 字符串. // 若响应不符合标准结构, 则返回原始 JSON 字符串.
func extractToolText(raw json.RawMessage) string { func extractToolText(raw json.RawMessage) string {
var parsed toolCallResult var parsed toolCallResult
@@ -386,8 +396,9 @@ func extractToolText(raw json.RawMessage) string {
return strings.Join(parts, "\n") return strings.Join(parts, "\n")
} }
// callRPC // callRPC 发送 JSON-RPC 2.0 请求, 并通过 SSE 通道异步等待对应 ID 的响应,
// 发送一个 JSON-RPC 2.0 请求, 并通过 SSE 通道异步等待对应 ID 的响应, 支持 context 超时控制. //
// 支持 context 超时控制.
func (c *MCPSSEClient) callRPC(ctx context.Context, method string, params any) (json.RawMessage, error) { func (c *MCPSSEClient) callRPC(ctx context.Context, method string, params any) (json.RawMessage, error) {
id := c.nextID.Add(1) id := c.nextID.Add(1)
ch := make(chan json.RawMessage, 1) ch := make(chan json.RawMessage, 1)
@@ -441,8 +452,8 @@ func (c *MCPSSEClient) callRPC(ctx context.Context, method string, params any) (
} }
} }
// notify // notify 发送一个不带 ID 的 JSON-RPC 通知
// 发送一个不带 ID 的 JSON-RPC 通知; //
// 通知无需等待服务端响应. // 通知无需等待服务端响应.
func (c *MCPSSEClient) notify(ctx context.Context, method string, params any) error { func (c *MCPSSEClient) notify(ctx context.Context, method string, params any) error {
c.mu.Lock() c.mu.Lock()
@@ -481,8 +492,9 @@ type MCPToolRouter struct {
listFailures map[string]error listFailures map[string]error
} }
// NewMCPToolRouter // NewMCPToolRouter 创建一个 MCP 工具路由器
// 创建一个 MCP 工具路由器, 用于注册、自动发现并分发 MCP 工具调用. //
// 用于注册、自动发现并分发 MCP 工具调用.
func NewMCPToolRouter() *MCPToolRouter { func NewMCPToolRouter() *MCPToolRouter {
return &MCPToolRouter{ return &MCPToolRouter{
clients: make(map[string]*MCPSSEClient), clients: make(map[string]*MCPSSEClient),
@@ -492,15 +504,16 @@ func NewMCPToolRouter() *MCPToolRouter {
} }
} }
// Register // Register 注册一个工具
// 注册一个工具; //
// 内部直接委托给 RegisterAndExpand 处理. // 内部直接委托给 RegisterAndExpand 处理.
func (r *MCPToolRouter) Register(tool ports.Tool) { func (r *MCPToolRouter) Register(tool ports.Tool) {
r.RegisterAndExpand(tool) r.RegisterAndExpand(tool)
} }
// RegisterAndExpand // RegisterAndExpand 注册工具并对 SSE 类型的 MCP 工具进行自动展开
// 注册工具并对 SSE 类型的 MCP 工具进行自动展开: 创建共享客户端、调用 tools/list 发现所有工具并逐一注册; //
// 创建共享客户端、调用 tools/list 发现所有工具并逐一注册;
// 发现失败时降级保留原始工具. // 发现失败时降级保留原始工具.
func (r *MCPToolRouter) RegisterAndExpand(tool ports.Tool) []ports.Tool { func (r *MCPToolRouter) RegisterAndExpand(tool ports.Tool) []ports.Tool {
mcp, ok := tool.(MCPTool) mcp, ok := tool.(MCPTool)
@@ -540,14 +553,13 @@ func (r *MCPToolRouter) RegisterAndExpand(tool ports.Tool) []ports.Tool {
return expanded return expanded
} }
// Tools // Tools 返回当前已注册的所有工具.
// 返回当前已注册的所有工具.
func (r *MCPToolRouter) Tools() []ports.Tool { func (r *MCPToolRouter) Tools() []ports.Tool {
return r.tools return r.tools
} }
// CallTool // CallTool 根据工具名将调用分发给已注册的 MCP SSE 客户端;
// 根据工具名将调用分发给已注册的 MCP SSE 客户端; //
// 找不到可调用客户端时返回明确错误. // 找不到可调用客户端时返回明确错误.
func (r *MCPToolRouter) CallTool(ctx context.Context, name, arguments string) (string, error) { func (r *MCPToolRouter) CallTool(ctx context.Context, name, arguments string) (string, error) {
if client, ok := r.clients[name]; ok { if client, ok := r.clients[name]; ok {

View File

@@ -38,7 +38,12 @@ func NewOpenAIClient(completionsURL, apiKey, model string, requestTimeout time.D
} }
} }
// Generate 发送非流式 Chat Completions 请求,等待完整响应后返回文本内容与工具调用列表。
//
// 该请求使用 stream=false,服务端会一次性返回完整 JSON 响应。
// 返回的 ChatReply 包含模型最终文本内容;若模型决定调用工具,则同时包含工具调用列表。
func (c *OpenAIClient) Generate(ctx context.Context, messages []ports.ChatMessage, tools []OpenAIToolDef) (ports.ChatReply, error) { func (c *OpenAIClient) Generate(ctx context.Context, messages []ports.ChatMessage, tools []OpenAIToolDef) (ports.ChatReply, error) {
// stream=false,构造一次性返回完整响应的普通请求
body, err := buildRequestBody(c.model, messages, tools, false) body, err := buildRequestBody(c.model, messages, tools, false)
if err != nil { if err != nil {
return ports.ChatReply{}, err return ports.ChatReply{}, err
@@ -76,6 +81,11 @@ func (c *OpenAIClient) Generate(ctx context.Context, messages []ports.ChatMessag
return reply, nil return reply, nil
} }
// Stream 发送流式 Chat Completions 请求,并通过 channel 持续返回增量文本、工具调用和错误。
//
// 调用方通过 events 接收流式事件,通过 errs 接收错误;
// 当收到 Done=true 事件或 events channel 被关闭时,表示本次流式请求结束。
// 流式响应中 tool_calls 是分片到达的,因此内部使用 map[int]*ChatToolCall 按 index 累积完整工具调用。
func (c *OpenAIClient) Stream(ctx context.Context, messages []ports.ChatMessage, tools []OpenAIToolDef) (<-chan ports.ChatStreamEvent, <-chan error) { func (c *OpenAIClient) Stream(ctx context.Context, messages []ports.ChatMessage, tools []OpenAIToolDef) (<-chan ports.ChatStreamEvent, <-chan error) {
events := make(chan ports.ChatStreamEvent, 8) events := make(chan ports.ChatStreamEvent, 8)
errs := make(chan error, 1) errs := make(chan error, 1)
@@ -100,8 +110,9 @@ func (c *OpenAIClient) Stream(ctx context.Context, messages []ports.ChatMessage,
return return
} }
// 按 index 暂存流式 tool_call,用于跨多个 SSE chunk 累积完整参数
toolCallBuf := map[int]*ports.ChatToolCall{} toolCallBuf := map[int]*ports.ChatToolCall{}
reader := bufio.NewReader(resp.Body) reader := bufio.NewReader(resp.Body) // 带缓冲逐行读取 SSE 数据
for { for {
line, err := reader.ReadString('\n') line, err := reader.ReadString('\n')
if err != nil { if err != nil {
@@ -113,11 +124,11 @@ func (c *OpenAIClient) Stream(ctx context.Context, messages []ports.ChatMessage,
errs <- fmt.Errorf("openai stream read: %w", err) errs <- fmt.Errorf("openai stream read: %w", err)
return return
} }
line = strings.TrimRight(line, "\r\n") line = strings.TrimRight(line, "\r\n") // 去掉行尾换行符,兼容 \n 与 \r\n
if line == "" || !strings.HasPrefix(line, "data:") { if line == "" || !strings.HasPrefix(line, "data:") {
continue continue // 忽略空行和非 data: 的 SSE 行
} }
payload := strings.TrimSpace(strings.TrimPrefix(line, "data:")) payload := strings.TrimSpace(strings.TrimPrefix(line, "data:")) // 提取 data 内容
if payload == "[DONE]" { if payload == "[DONE]" {
emitToolCalls(events, toolCallBuf) emitToolCalls(events, toolCallBuf)
events <- ports.ChatStreamEvent{Done: true} events <- ports.ChatStreamEvent{Done: true}
@@ -153,6 +164,7 @@ func (c *OpenAIClient) Stream(ctx context.Context, messages []ports.ChatMessage,
current.Name = tc.Function.Name current.Name = tc.Function.Name
} }
if tc.Function.Arguments != "" { if tc.Function.Arguments != "" {
// arguments 是 JSON 增量片段,需要持续拼接成完整参数
current.Arguments += tc.Function.Arguments current.Arguments += tc.Function.Arguments
} }
} }
@@ -161,6 +173,10 @@ func (c *OpenAIClient) Stream(ctx context.Context, messages []ports.ChatMessage,
return events, errs return events, errs
} }
// emitToolCalls 将流式读取过程中累积的工具调用按 index 顺序发送到事件管道。
//
// OpenAI 流式协议中多个工具调用可能交错返回,因此内部先用 map 暂存;
// 发送时按 index 从 0 开始遍历,保证上层拿到的工具调用顺序稳定。
func emitToolCalls(events chan<- ports.ChatStreamEvent, buf map[int]*ports.ChatToolCall) { func emitToolCalls(events chan<- ports.ChatStreamEvent, buf map[int]*ports.ChatToolCall) {
if len(buf) == 0 { if len(buf) == 0 {
return return
@@ -176,6 +192,10 @@ func emitToolCalls(events chan<- ports.ChatStreamEvent, buf map[int]*ports.ChatT
} }
} }
// do 构造并发送 HTTP POST 请求,统一处理 Content-Type、Accept 和 Bearer 认证。
//
// 该方法只负责发送请求,不读取响应体;响应体由调用方负责关闭。
// 网络层错误会包装为带上下文的错误返回。
func (c *OpenAIClient) do(ctx context.Context, body []byte) (*http.Response, error) { func (c *OpenAIClient) do(ctx context.Context, body []byte) (*http.Response, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.completionsURL, bytes.NewReader(body)) req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.completionsURL, bytes.NewReader(body))
if err != nil { if err != nil {
@@ -193,6 +213,10 @@ func (c *OpenAIClient) do(ctx context.Context, body []byte) (*http.Response, err
return resp, nil return resp, nil
} }
// buildRequestBody 构造 OpenAI Chat Completions 请求体,并序列化为 JSON 字节。
//
// stream 为 true 时生成流式请求,为 false 时生成普通请求;
// 仅当 tools 非空时才写入 tools 字段,避免无工具时发送空数组。
func buildRequestBody(modelName string, messages []ports.ChatMessage, tools []OpenAIToolDef, stream bool) ([]byte, error) { func buildRequestBody(modelName string, messages []ports.ChatMessage, tools []OpenAIToolDef, stream bool) ([]byte, error) {
payload := map[string]any{ payload := map[string]any{
"model": modelName, "model": modelName,
@@ -209,6 +233,10 @@ func buildRequestBody(modelName string, messages []ports.ChatMessage, tools []Op
return raw, nil return raw, nil
} }
// encodeMessages 将领域层消息转换为 OpenAI Chat Completions 协议所需的消息格式。
//
// 支持普通 system/user 消息、assistant 工具调用消息、tool 执行结果消息;
// 当 assistant 消息带有 tool_calls 且 content 为空时,按 OpenAI 协议省略 content 字段。
func encodeMessages(messages []ports.ChatMessage) []map[string]any { func encodeMessages(messages []ports.ChatMessage) []map[string]any {
encoded := make([]map[string]any, 0, len(messages)) encoded := make([]map[string]any, 0, len(messages))
for _, m := range messages { for _, m := range messages {
@@ -243,6 +271,10 @@ func encodeMessages(messages []ports.ChatMessage) []map[string]any {
return encoded return encoded
} }
// encodeTools 将工具定义转换为 OpenAI 函数调用(Function Calling)协议格式。
//
// 当前实现把工具参数统一建模为 query 字符串,适合将 MCP/Skill 工具包装为自由文本输入;
// 若工具描述为空,会通过 fallbackDescription 生成默认描述。
func encodeTools(tools []OpenAIToolDef) []map[string]any { func encodeTools(tools []OpenAIToolDef) []map[string]any {
out := make([]map[string]any, 0, len(tools)) out := make([]map[string]any, 0, len(tools))
for _, t := range tools { for _, t := range tools {
@@ -266,6 +298,10 @@ func encodeTools(tools []OpenAIToolDef) []map[string]any {
return out return out
} }
// fallbackDescription 返回工具描述
//
// 当描述为空时,生成一个通用默认描述。
// 默认描述会包含工具名,提示模型该工具接收自由文本 query 参数。
func fallbackDescription(t OpenAIToolDef) string { func fallbackDescription(t OpenAIToolDef) string {
if strings.TrimSpace(t.Description) != "" { if strings.TrimSpace(t.Description) != "" {
return t.Description return t.Description
@@ -273,6 +309,9 @@ func fallbackDescription(t OpenAIToolDef) string {
return "外部工具 " + t.Name + ",参数 query 为自由文本" return "外部工具 " + t.Name + ",参数 query 为自由文本"
} }
// truncate 将过长的字符串截断到指定长度,用于控制错误信息中的响应体长度。
//
// 如果原始字符串长度不超过 max,则原样返回;否则截取前 max 个字符并追加省略号。
func truncate(s string, max int) string { func truncate(s string, max int) string {
if len(s) <= max { if len(s) <= max {
return s return s
@@ -280,6 +319,9 @@ func truncate(s string, max int) string {
return s[:max] + "..." return s[:max] + "..."
} }
// openaiCompletion 对应 OpenAI 非流式 Chat Completions 响应。
//
// 其中 choices[0].message 保存最终文本内容与模型请求的工具调用列表。
type openaiCompletion struct { type openaiCompletion struct {
Choices []struct { Choices []struct {
Message struct { Message struct {
@@ -289,6 +331,9 @@ type openaiCompletion struct {
} `json:"choices"` } `json:"choices"`
} }
// openaiStreamChunk 对应 OpenAI 流式响应中的单个 SSE data chunk。
//
// delta 中可能包含 content 文本增量,或 tool_calls 工具的增量片段。
type openaiStreamChunk struct { type openaiStreamChunk struct {
Choices []struct { Choices []struct {
Delta struct { Delta struct {
@@ -299,6 +344,7 @@ type openaiStreamChunk struct {
} `json:"choices"` } `json:"choices"`
} }
// openaiToolCallV1 对应 OpenAI 非流式响应中的完整工具调用。
type openaiToolCallV1 struct { type openaiToolCallV1 struct {
ID string `json:"id"` ID string `json:"id"`
Type string `json:"type"` Type string `json:"type"`
@@ -308,6 +354,9 @@ type openaiToolCallV1 struct {
} `json:"function"` } `json:"function"`
} }
// openaiStreamToolCall 对应 OpenAI 流式响应中的工具调用增量片段。
//
// Index 用于区分同一响应中的多个工具调用,Arguments 是需要跨 chunk 拼接的 JSON 增量。
type openaiStreamToolCall struct { type openaiStreamToolCall struct {
Index int `json:"index"` Index int `json:"index"`
ID string `json:"id"` ID string `json:"id"`

View File

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