2026-10-20 21:02:26 +08:00
<!DOCTYPE html>
< html lang = "zh-CN" data-theme = "light" >
< head >
< meta charset = "utf-8" >
< meta name = "viewport" content = "width=device-width, initial-scale=1" >
< title > 第 12 章 MCP 工具: SSE 客户端与全局路由 · AI Agent 脚手架项目学习< / title >
< meta name = "description" content = "讲清 GET /sse 建连、endpoint 事件、JSON-RPC 请求-响应匹配与 tools/list 自动发现,并复现全局 router 下同名工具冲突的故障。" >
< meta name = "keywords" content = "MCP,SSE,JSON-RPC,tools/list,工具路由,发现" >
< link rel = "stylesheet" href = "assets/doc.css" >
< / head >
< body >
< header class = "topbar" >
< div class = "tb-in" >
< a class = "brand" href = "index.html" > < span class = "logo" > AG< / span > < div > AI Agent 脚手架项目学习< small > Go + Agent · 源码拆解 / 装配链 / 面试模拟< / small > < / div > < / a >
< nav class = "partnav" id = "partnav" > < a class = "home" href = "index.html" > 学习地图< / a > < span class = "pn-sep" > < / span > < a href = "part-0.html" > 篇 0 前言< / a > < a href = "part-1.html" > 篇 1 知识学习< / a > < a href = "part-2.html" class = "on" > 篇 2 项目拆解< / a > < a href = "part-3.html" > 篇 3 缺陷与演进< / a > < a href = "part-4.html" > 篇 4 场景还原< / a > < a href = "part-5.html" > 篇 5 收尾< / a > < / nav >
< div class = "spacer" > < / div >
< button class = "btn" id = "tocToggle" > ☰ 导航< / button >
< button class = "btn" id = "themeBtn" title = "切换到深色主题" > 深色< / button >
< / div >
< / header >
< div class = "layout" id = "layout" >
< aside class = "sidebar" >
< h2 > 章节目录< / h2 >
< nav id = "chapters" > < div class = "toc-scope" > < span class = "ts-label" > 篇 2< / span > < span class = "ts-name" > 项目拆解< / span > < a class = "ts-all" href = "index.html" > 全部篇章 →< / a > < / div > < a class = "toc-a" href = "05-bootstrap.html" > < i class = "cn" > 5< / i > 启动与装配: main → bootstrap → Gin< / a > < a class = "toc-a" href = "06-config.html" > < i class = "cn" > 6< / i > 配置体系:三层配置怎么生效< / a > < a class = "toc-a" href = "07-domain-ports.html" > < i class = "cn" > 7< / i > 领域模型与端口:接口清单< / a > < a class = "toc-a" href = "08-armory.html" > < i class = "cn" > 8< / i > Armory 装配链:责任链把 YAML 变成 Agent< / a > < a class = "toc-a" href = "09-workflow.html" > < i class = "cn" > 9< / i > 工作流编排: sequential / parallel / loop< / a > < a class = "toc-a" href = "10-runtime.html" > < i class = "cn" > 10< / i > Agent 运行时:工具调用循环与流式< / a > < a class = "toc-a" href = "11-model-client.html" > < i class = "cn" > 11< / i > 模型层: OpenAI 兼容客户端< / a > < span class = "toc-a active" aria-current = "page" > < i class = "cn" > 12< / i > MCP 工具: SSE 客户端与全局路由< / span > < div class = "subnav current" > < a class = "toc-a lv3" href = "#sec-12-1" > 12.1 连接建立: GET /sse 与 endpoint 事件< / a > < a class = "toc-a lv3" href = "#sec-12-2" > 12.2 JSON-RPC 请求-响应匹配< / a > < a class = "toc-a lv3" href = "#sec-12-3" > 12.3 tools/list 自动发现与展开< / a > < a class = "toc-a lv3" href = "#sec-12-4" > 12.4 全局 router 与同名工具的冲突< / a > < a class = "toc-a lv3" href = "#sec-12-5" > 12.5 stdio 与 local: 配置能写、运行不通< / a > < / div > < a class = "toc-a" href = "13-skills.html" > < i class = "cn" > 13< / i > Skill 机制: SKILL.md 扫描与命名< / a > < a class = "toc-a" href = "14-http-api.html" > < i class = "cn" > 14< / i > HTTP 接口层:五个端点< / a > < a class = "toc-a" href = "15-frontend.html" > < i class = "cn" > 15< / i > 前端: Next.js + draw.io 交互绘图< / a > < a class = "toc-a" href = "16-infra-deploy.html" > < i class = "cn" > 16< / i > 基础设施与部署< / a > < / nav >
2026-10-22 21:59:12 +08:00
< div class = "side-foot" >
2026-10-20 21:02:26 +08:00
< a class = "btn" href = "index.html" > ← 学习地图< / a >
2026-10-22 21:59:12 +08:00
< a class = "btn" href = "23-cheatsheet.html" > 速查与自测< / a >
2026-10-20 21:02:26 +08:00
< / div >
< / aside >
< div class = "mask" id = "mask" > < / div >
< main class = "main-col" >
< article >
< p class = "chapnav" >
< a href = "index.html" > AI Agent 脚手架项目学习< / a >
< span > ·< / span >
< a href = "part-2.html" > 篇 2 项目拆解< / a >
< span > ·< / span >
2026-10-22 21:59:12 +08:00
< span > 第 < b class = "pos" > 12< / b > / 23 章< / span >
2026-10-20 21:02:26 +08:00
< / p >
< h2 id = "ch12" > < span class = "n" > 12< / span > MCP 工具: SSE 客户端与全局路由< / h2 >
< div class = "lead" >
2026-10-20 21:48:52 +08:00
< b > 这一章解决什么:< / b > MCP 是这个项目里唯一真正「对外通信」的能力。它要在启动时连上服务端、拿到一个会话地址、
完成 JSON-RPC 握手、列出工具、把工具注册进全局路由,运行期还要把模型的 function call 转发成 < code > tools/call< / code > 。
这一章按这个顺序拆 < code > mcp_sse_client.go< / code > ( 546 行),最后复现一个必现故障:< b > 两张表配同名 MCP 工具时,第二张表拿到一个调不动的占位工具< / b > 。
2026-10-20 21:02:26 +08:00
< / div >
< h3 id = "sec-12-1" > 12.1 连接建立: GET /sse 与 endpoint 事件< / h3 >
2026-10-20 21:48:52 +08:00
< p > 配置里 < code > base-uri< / code > 与 < code > sse-endpoint< / code > 会先被规范化(< code > tools.go:439-477< / code > ) : < code > base-uri< / code > 必须带 scheme 与 host,
合并后的 path 去掉多余斜杠;< code > sse-endpoint< / code > 为空时默认 < code > /sse< / code > ,可以带 query( 百度那个 < code > ?api_key=...< / code > 就是这么传的)。< / p >
< p > 真正的建连在 < code > ensureStarted< / code > 里,分四步:< / p >
< pre data-lang = "go" data-name = "internal/infrastructure/ai/mcp_sse_client.go:63-102( 结构) " > c.mu.Lock()
if c.started { c.mu.Unlock(); return nil } // 已经连过
c.pending = make(map[uint64]chan json.RawMessage)
c.endpointSig = make(chan struct{})
c.streamErr = make(chan error, 1)
streamCtx, cancel := context.WithCancel(context.Background()) // 注意: Background
c.cancelFn = cancel
c.started = true // 先置 true, 再开始 IO
c.mu.Unlock()
c.openSSE(streamCtx) // GET .../sse, Accept: text/event-stream, 起 readLoop
waitCtx, _ := context.WithTimeout(ctx, c.timeout)
select {
case < -c.endpointSig: // 等服务器推 event: endpoint
case err := < -c.streamErr: return err
case < -waitCtx.Done(): return fmt.Errorf("mcp sse endpoint event timeout: %w", waitCtx.Err())
}
c.initialize(ctx) // initialize + notifications/initialized< / pre >
< p > < code > readLoop< / code > 按 SSE 行格式解析(< code > :131-177< / code > ):遇到 < code > event:< / code > 记事件名,遇到 < code > data:< / code > 累加数据,
空行触发一次分发——< code > endpoint< / code > 事件交给 < code > handleEndpoint< / code > , < code > message< / code > 事件交给 < code > handleMessage< / code > 。
< code > handleEndpoint< / code > 把服务端给的相对地址按 < code > base-uri< / code > 解析成绝对 URL, 写入 < code > postURL< / code > 并 < code > close(endpointSig)< / code > 。< / p >
< div class = "box warn" >
< span class = "bt" > 第一个并发缺陷: started 先于连接建立< / span >
< p > < code > c.started = true< / code > 在第 74 行、锁内就设好了,而 < code > openSSE< / code > 与 < code > initialize< / code > 都在锁外。
如果两个请求同时触发 < code > ensureStarted< / code > ,第二个会看到 < code > started==true< / code > 直接返回 nil,
然后进 < code > callRPC< / code > 发现 < code > postURL< / code > 还是空的,报 < code > mcp post url is not set< / code > ( P0-5) 。
正确做法是用 < code > sync.Once< / code > 或「状态机 + 条件变量」,把 started 的置位放在握手成功之后。< br >
附带的第二个问题:< code > streamCtx< / code > 来自 < code > context.Background()< / code > ,调用方的 ctx 取消不了这条长连接,
只能靠 < code > shutdown()< / code > 里的 < code > cancelFn< / code > 。< / p >
< / div >
2026-10-20 21:02:26 +08:00
< h3 id = "sec-12-2" > 12.2 JSON-RPC 请求-响应匹配< / h3 >
2026-10-20 21:48:52 +08:00
< p > SSE 是单向的:请求从 POST 发出去,响应从 SSE 流里回来。所以必须自己维护「请求 ID → 等待通道」的映射:< / p >
< pre data-lang = "go" data-name = "internal/infrastructure/ai/mcp_sse_client.go:402-453( 结构) " > id := c.nextID.Add(1) // atomic, 全局递增
ch := make(chan json.RawMessage, 1)
c.mu.Lock(); postURL := c.postURL; c.pending[id] = ch; c.mu.Unlock()
if postURL == "" { return nil, fmt.Errorf("mcp post url is not set") } // ← 这里没有 delete(pending, id)
// POST {"jsonrpc":"2.0","id":id,"method":...,"params":...}
// 响应体直接丢弃,真正结果从 SSE 流回来
select {
case msg, ok := < -ch: // handleMessage 里投递,同时 delete(pending,id)
// 若 msg 是 {"__error__": ...} 则转成 error
return msg, nil
case < -waitCtx.Done(): // ← 这里也没有 delete(pending, id)
return nil, fmt.Errorf("mcp call %s timeout: %w", method, waitCtx.Err())
}< / pre >
< div class = "tablewrap" >
< table >
< thead > < tr > < th > 环节< / th > < th > 实现< / th > < th > 要点< / th > < / tr > < / thead >
< tbody >
< tr > < td > 发请求< / td > < td > POST 到 < code > postURL< / code > < / td > < td > 状态码 ≥400 直接报错;正常时把 body 读完丢掉< / td > < / tr >
< tr > < td > 收响应< / td > < td > < code > handleMessage< / code > ( < code > :226-261< / code > ) < / td > < td > 解析 < code > id< / code > 后从 < code > pending< / code > 取出通道并删除,然后投递 result 或包装过的 error< / td > < / tr >
< tr > < td > 失败广播< / td > < td > < code > signalStreamErr< / code > ( < code > :274-286< / code > ) < / td > < td > SSE 流断了 → 向所有 pending 投错误并清空,避免永久阻塞< / td > < / tr >
< tr > < td > 通知< / td > < td > < code > notify< / code > ( < code > :458-485< / code > ) < / td > < td > 不带 id, 不等待响应, 也不校验状态码< / td > < / tr >
< / tbody >
< / table >
< / div >
< p > 两条「提前 return」路径都< b > 没有< / b > < code > delete(c.pending, id)< / code > : < code > postURL< / code > 为空时和等待超时时。后者更常见——
当 MCP 服务端处理慢或干脆不回,每超时一次就泄漏一个 channel 与一个 map 条目, 长期运行会持续涨内存( P0-4) 。< / p >
2026-10-20 21:02:26 +08:00
< h3 id = "sec-12-3" > 12.3 tools/list 自动发现与展开< / h3 >
2026-10-20 21:48:52 +08:00
< p > 装配期每个 MCP 条目都会走一遍 < code > RegisterAndExpand< / code > ( < code > :518-554< / code > ),它的分支顺序很关键:< / p >
< pre data-lang = "go" data-name = "internal/infrastructure/ai/mcp_sse_client.go:518-554( 结构) " > mcp, ok := tool.(MCPTool)
if !ok { r.tools = append(r.tools, tool); return []ports.Tool{tool} } // 1. 非 MCP: 原样登记
if mcp.TransportType != "sse" { r.tools = append(r.tools, mcp); return []ports.Tool{mcp} } // 2. stdio/local: 只登记
if _, exists := r.clients[mcp.ToolName]; exists { return nil } // 3. 同名已注册:返回 nil
client := NewMCPSSEClient(mcp.BaseURI, mcp.SSEEndpoint, mcp.RequestTimeout)
r.clients[mcp.ToolName] = client
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) // 4. 发现超时固定 10s
names, err := client.ListTools(ctx)
if err != nil { // 5. 发现失败:降级
r.listFailures[mcp.ToolName] = err
r.tools = append(r.tools, mcp) // 只登记配置名
return []ports.Tool{mcp}
}
for _, n := range names { // 6. 成功:逐个展开
r.clients[n] = client // 真实工具名也指向同一 client
t := EinoTool{ToolName: n}
r.tools = append(r.tools, t)
expanded = append(expanded, t)
}< / pre >
< p > 然后 < code > ToolFactory.BuildTools< / code > 会拿展开结果替换原始列表(< code > tools.go:91-106< / code > ):展开非空就用展开的,
< b > 为空就回退到原始占位工具< / b > ,以保证启动不中断。这个「回退」是善意设计,但它掩盖了发现失败——
启动日志里只有注册数量,看不到 < code > listFailures< / code > (该字段只写不读)。< / p >
< p > 于是模型看到的工具列表会出现两种形态:正常时是服务端真实工具名(如 < code > baidu_search< / code > ) ,
失败时是配置里的别名(如 < code > baidu-search< / code > )——后者永远调不通。< / p >
2026-10-20 21:02:26 +08:00
< h3 id = "sec-12-4" > 12.4 全局 router 与同名工具的冲突< / h3 >
2026-10-20 21:48:52 +08:00
< p > < code > MCPToolRouter< / code > 在整个进程里只有一个实例(< code > bootstrap.go:53< / code > 创建,< code > :57< / code > 注入给 agentFactory) ,
所有 Agent 表共享它。而 < code > clients< / code > 这个 map 的键是< b > 工具名< / b > ,不是「地址 + 端点」。两个后果叠在一起就是必现故障:< / p >
< ol >
< li > 第一张表(< code > testAgent03< / code > )注册 < code > baidu-search< / code > :建 client、发现真实工具、把 < code > clients["baidu-search"]< / code > 指向该 client。< / li >
< li > 第二张表(< code > drawIoAgent< / code > )配了同名 < code > baidu-search< / code > :命中第 3 分支,< code > return nil< / code > ,
< code > BuildTools< / code > 拿到空展开结果,回退成占位工具 < code > MCPTool{ToolName:"baidu-search"}< / code > (无地址、无客户端)。< / li >
< li > 运行期模型调用 < code > baidu-search< / code > : < code > MCPToolRouter.CallTool< / code > 先查 < code > r.clients[name]< / code > ( < code > :564-567< / code > ) ,
< b > 查到了第一张表的 client< / b > ,于是发出 < code > tools/call< / code > , < code > name< / code > 是配置别名而不是真实工具名,
服务端返回「工具不存在」,整轮对话失败。< / li >
< / ol >
< div class = "box danger" >
< span class = "bt" > 为什么这个 bug 很难在演示时发现< / span >
< p > < code > only-one-agent.yaml< / code > 与 < code > agent-draw-io.yaml< / code > 都配了 < code > baidu-search< / code > ,
而默认 < code > config-paths< / code > 两份都加载。但只有< b > 用到工具< / b > 的那次对话才会暴露;
如果你演示的是 draw.io 绘图(模型往往直接生成 XML, 不调搜索) , 一切正常。< b > 一旦用户问「今天有什么新闻」< / b > ,
才会撞上 < code > tools/call< / code > 失败。< / p >
< / div >
< p > 修复有两个层次:轻的是把 < code > clients< / code > 的键改成 < code > baseURI + endpoint< / code > ,让同名不同源能共存;
重的是让 router 按表(或按 Agent) 隔离, 而不是全局单例——后者更符合「一个 Agent 一套工具」的直觉。< / p >
2026-10-20 21:02:26 +08:00
< h3 id = "sec-12-5" > 12.5 stdio 与 local: 配置能写、运行不通< / h3 >
2026-10-20 21:48:52 +08:00
< p > 配置校验对三种传输一视同仁(< code > loader.go:137-185< / code > ),构建函数也都实现了(< code > tools.go:369-434< / code > ) ,
但只有 SSE 有运行期实现:< / p >
< div class = "tablewrap" >
< table >
< thead > < tr > < th > 传输< / th > < th > 配置校验< / th > < th > 构建出的对象< / th > < th > 运行期调用< / th > < / tr > < / thead >
< tbody >
< tr > < td > < code > sse< / code > < / td > < td > name + base-uri< / td > < td > 建连、发现、展开< / td > < td > < b > 可用< / b > (走 < code > clients< / code > 里的 client) < / td > < / tr >
< tr > < td > < code > stdio< / code > < / td > < td > name + server-parameters.command< / td > < td > < code > MCPTool< / code > (存了 command/args/env) < / td > < td > 报 < code > transport not supported in runtime< / code > < / td > < / tr >
< tr > < td > < code > local< / code > < / td > < td > name( 只认 < code > echoLocalTool< / code > ) < / td > < td > < code > MCPTool< / code > (没有任何行为)< / td > < td > 同上< / td > < / tr >
< / tbody >
< / table >
< / div >
< p > 具体路径是 < code > CallTool< / code > 的第二段(< code > :568-579< / code > ):不在 < code > clients< / code > 里就遍历 < code > tools< / code > 找同名项,
命中 < code > MCPTool< / code > 就返回「transport not supported」, 命中其它类型返回「not callable」。
注意 < code > stdio< / code > 的 < code > Command< / code > 、< code > Args< / code > 、< code > Env< / code > 被完整保存下来(连 map 都做了拷贝),
说明作者留了实现意图,只是没写进程管理那一段。< / p >
< div class = "box tip" >
< span class = "bt" > 怎么判断一个 MCP 配置会不会工作< / span >
< p > 三问:① 是不是 < code > sse< / code > ?② < code > tools/list< / code > 在 10 秒内成功了吗(看返回的工具名是服务端真名还是配置别名)?
③ 这个别名有没有被别的表先注册过?三问都过,工具才真的可用。前两问看启动日志与工具列表,第三问只能查配置有没有重复的 < code > name< / code > 。< / p >
< / div >
2026-10-20 21:02:26 +08:00
< nav class = "pager" >
< a class = "prev" href = "11-model-client.html" > < span class = "k" > ← 上一章< / span > < span class = "v" > 第 11 章 · 模型层: OpenAI 兼容客户端< / span > < / a >
< a class = "next" href = "13-skills.html" > < span class = "k" > 下一章 →< / span > < span class = "v" > 第 13 章 · Skill 机制: SKILL.md 扫描与命名< / span > < / a >
< / nav >
< p class = "foot" >
AI Agent 脚手架项目学习 · 第 12 章 MCP 工具: SSE 客户端与全局路由< br >
2026-10-22 21:59:12 +08:00
< a href = "index.html" > 学习地图< / a > · < a href = "part-2.html" > 篇 2 项目拆解< / a > · < a href = "23-cheatsheet.html" > 速查与自测< / a >
2026-10-20 21:02:26 +08:00
< / p >
< / article >
< / main >
< / div >
< button id = "toTop" title = "回到顶部" > ↑< / button >
< script src = "assets/doc.js" > < / script >
< script src = "../../assets/back.js" data-portal-back = "project/ai-agent-scafford-go" data-portal-label = "工程项目 › AI Agent 脚手架项目学习( Go 智能体框架)" > < / script >
< / body >
< / html >