- 协议版本协商:initialize 先发最高版本(2025-11-25)并声明能力集合,遇 UnsupportedProtocolVersionError(-32022)/服务器不支持版本 → negotiateMutuallySupportedVersion 求出双方最高共同版本降级重试(最多2次);无共同版本→ErrUnsupportedProtocolVersion。 协商结果记 negotiatedVersion,HTTP 传输回填 Mcp-Protocol-Version 头。 - tools/list_changed 订阅:capabilities 声明 tools.listChanged:true;传输读无 id 帧路由到 handleServerNotification;refreshPending 原子旗标合并突发 + 新 goroutine 调 onToolListChanged (避免 stdio lineRPC 重入自锁);Registry 真差量刷新(重新 DiscoverTools→移除消失/注册新增, 跳过同名冲突保外来工具)。 - keepalive:WithKeepAlive(interval,failures) 起 goroutine 定时 Call(ping),连续失败≥阈值关 session(默认3,可配);服务器不支持 ping(-32601)停 keepalive 不误关;ctx+Close 取消不泄漏。 - Streamable HTTP 传输:newTransport 支持 TransportType=http|streamable(保留 stdio/SSE 推断, 空值走旧逻辑不破坏);Call POST+Accept json/event-stream 响应可单 JSON 或 SSE 流找匹配 id; Mcp-Session-Id 会话 + 独立 GET SSE 流收 server 通知;config 读 MCP_TRANSPORT。 - schema 缓存判定不做:客户端透传 map[string]any 无重复编译,SDK SchemaCache 是服务端 按 Go 类型反射场景,客户端无对应。 go build/vet/test 全绿(count=2 无 flaky) + windows/darwin 交叉编译。
54 lines
1.7 KiB
Go
54 lines
1.7 KiB
Go
package mcp
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
)
|
|
|
|
// rpcRequest is a JSON-RPC 2.0 request. Notifications omit ID so the field is
|
|
// tagged omitempty. Params is any so callers pass a struct or a JSON object.
|
|
type rpcRequest struct {
|
|
JSONRPC string `json:"jsonrpc"`
|
|
ID any `json:"id,omitempty"`
|
|
Method string `json:"method"`
|
|
Params any `json:"params,omitempty"`
|
|
}
|
|
|
|
// rpcResponse is a JSON-RPC 2.0 response. Result is kept raw until the caller
|
|
// decodes it into the concrete result type. Method is populated only for
|
|
// server-initiated notifications (no id), so transports can route them to the
|
|
// client's notification handler.
|
|
type rpcResponse struct {
|
|
JSONRPC string `json:"jsonrpc"`
|
|
ID any `json:"id,omitempty"`
|
|
Method string `json:"method,omitempty"`
|
|
Result json.RawMessage `json:"result,omitempty"`
|
|
Error *rpcError `json:"error,omitempty"`
|
|
}
|
|
|
|
// rpcError is a JSON-RPC error object. It satisfies error so it can be wrapped
|
|
// and surfaced with %w.
|
|
type rpcError struct {
|
|
Code int `json:"code"`
|
|
Message string `json:"message"`
|
|
Data any `json:"data,omitempty"`
|
|
}
|
|
|
|
// Error implements error.
|
|
func (e *rpcError) Error() string {
|
|
return fmt.Sprintf("code %d: %s", e.Code, e.Message)
|
|
}
|
|
|
|
// encodeRequest marshals a JSON-RPC request. An id of nil produces a
|
|
// notification (no id field).
|
|
func encodeRequest(id any, method string, params any) ([]byte, error) {
|
|
return json.Marshal(rpcRequest{JSONRPC: "2.0", ID: id, Method: method, Params: params})
|
|
}
|
|
|
|
// decodeIDString reports whether res carries the string id expected for a JSON
|
|
// string id request.
|
|
func decodeIDString(res rpcResponse, id string) bool {
|
|
s, ok := res.ID.(string)
|
|
return ok && s == id
|
|
}
|