fix(mcpclient): 值级脱敏漏密钥值 + tools/list 字段名写错致 schema 恒为空

两个都是 AR23 支线测试先行逼出来的真实缺陷,不是测试期望过时:

1. redactSecretText:原键值正则把 Bearer 当"值"吃掉,
   "Authorization: Bearer sk-x" 掩成 "Authorization: [REDACTED] sk-x",
   密钥值原样残留;"header was: Bearer sk-x"(无键名裸形态)整句未匹配。
   改为先掩 Bearer 后的凭据值、再掩键值对(顺序反了值仍会残留)。

2. Tool.InputSchema 的 json tag 误写 input_schema,而 MCP 规范是 camelCase
   inputSchema。后果不只是测试形状:远端真实 tools/list 应答的 schema 从未被
   解析,ToolsJSON 缓存与透传给 LLM 的 Parameters 恒为空对象,模型拿不到参数结构。
   三处同链一并修正(mcpclient.Tool / registry.customToolEntry / 注释)。

测试:AR23 支线 mcpclient_test.go 收入为正式 mcpclient_test.go,
kernel/ai/mcp_tool_test.go 一并收入;两处改动前实测 FAIL、改后全绿。

Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
eaiadmin
2026-12-05 15:58:16 +08:00
co-authored by Claude Code
parent 4134e8b870
commit 059c240b17
6 changed files with 357 additions and 8 deletions
@@ -41,9 +41,11 @@ const (
// Tool 一只 MCP 工具的缓存/传输形状。InputSchema 为原始 JSON Schema,透传给 LLM。
type Tool struct {
Name string `json:"name"`
Description string `json:"description"`
InputSchema json.RawMessage `json:"input_schema,omitempty"`
Name string `json:"name"`
Description string `json:"description"`
// MCP 规范字段名是 camelCase 的 inputSchema(2026-12-05 修正:原写 input_schema,
// 导致远端真实应答的 schema 永远解析不出、透传给模型的参数恒为空对象)。
InputSchema json.RawMessage `json:"inputSchema,omitempty"`
}
// CallError 表示一次远端调用的分类错误(探测与工具执行共用)。
@@ -520,12 +522,20 @@ func isReservedHeader(name string) bool {
return false
}
// reSecret 覆盖 «Authorization: xxx»、裸 Bearer 值、api_key/token 参数等形式。
var reSecret = regexp.MustCompile(`(?i)\b(authorization|bearer|api[_-]?key|token|secret)(\s*[:=]\s*)("[^"]*"|'[^']*'|[^\s,;]+)`)
// reSecret 覆盖 «Authorization: xxx»、api_key/token/secret 参数等形式(键值对);
// 裸 Bearer 值另由 reBearerValue 处理——只靠键值正则时
// 「Authorization: Bearer sk-xxx」只会掩掉 scheme 词、密钥值仍在(2026-12-05 实测泄漏)。
var reSecret = regexp.MustCompile(`(?i)\b(authorization|api[_-]?key|token|secret)(\s*[:=]\s*)("[^"]*"|'[^']*'|[^\s,;]+)`)
// reBearerValue 匹配 Bearer 后的凭据值(含无键名的裸形态)。
var reBearerValue = regexp.MustCompile(`(?i)\bBearer\s+\S+`)
// redactSecretText 把远端回显里的凭据值掩掉再入库/回显
// (简易服务端常把请求头回打进 4xx 正文,AR01_16 §10.1)。
func redactSecretText(text string) string {
// 顺序:先脱 Bearer 后的凭据值,再脱键值对。
// 反过来会把「Authorization: Bearer sk-x」掩成「Authorization: [REDACTED] sk-x」,值仍在。
text = reBearerValue.ReplaceAllString(text, "Bearer [REDACTED]")
return reSecret.ReplaceAllString(text, "$1$2[REDACTED]")
}
@@ -0,0 +1,268 @@
package mcpclient
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
)
// ── 地址校验(AR20 AD9)─────────────────────────────────────
func TestValidateEndpoint(t *testing.T) {
cases := []struct {
name string
url string
wantErr bool
local bool
}{
{"loopback http", "http://127.0.0.1:8900/mcp", false, true},
{"localhost http", "http://localhost:9000/mcp", false, true},
{"私网 http", "http://10.20.30.40:8900/mcp", false, true},
{"172.16 私网", "http://172.16.5.5/mcp", false, true},
{"192.168 私网", "http://192.168.1.10/mcp", false, true},
{"CGNAT", "http://100.64.0.7/mcp", false, true},
{"公网 https", "https://mcp.example.com/mcp", false, false},
{"公网 http 拒绝", "http://mcp.example.com/mcp", true, false},
{"scheme 拒绝", "file:///tmp/mcp", true, false},
{"空地址", "", true, false},
{"缺主机", "http://", true, false},
{"userinfo 拒绝", "http://user:pass@127.0.0.1/mcp", true, false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
_, local, err := ValidateEndpoint(tc.url)
if tc.wantErr {
if err == nil {
t.Fatalf("期望拒绝 %q,实际通过", tc.url)
}
return
}
if err != nil {
t.Fatalf("期望通过 %q,实际拒绝:%v", tc.url, err)
}
if local != tc.local {
t.Fatalf("%q local 判定 = %v,期望 %v", tc.url, local, tc.local)
}
})
}
}
func TestRedactSecretText(t *testing.T) {
// 值级脱敏红线:远端把请求头回打进 4xx 正文时,落库/回显前必须掩掉(AR20 §10.1)
secret := "sk-very-secret-value-123"
for _, in := range []string{
"Authorization: Bearer " + secret, // 真实回显形态(含 scheme 词)
"Authorization: " + secret,
"token=" + secret,
"api_key: " + secret,
"header was: Bearer " + secret, // 无键名的裸 Bearer
} {
if out := redactSecretText(in); strings.Contains(out, secret) {
t.Errorf("redactSecretText 泄漏了值:%q -> %q", in, out)
}
}
if got := redactSecretText("plain error, nothing secret"); got != "plain error, nothing secret" {
t.Errorf("正常文本被误改:%q", got)
}
}
// ── 假 MCP 服务端(in-process,无真实网络)──────────────────
type fakeMCP struct {
t *testing.T
initializeHit int32
requests int32
lastSession atomic.Value
lastProtocol atomic.Value
failInit int // >0 时 initialize 直接返回该状态码
useSSE bool
}
func (f *fakeMCP) ServeHTTP(w http.ResponseWriter, r *http.Request) {
atomic.AddInt32(&f.requests, 1)
f.lastSession.Store(r.Header.Get("Mcp-Session-Id"))
f.lastProtocol.Store(r.Header.Get("MCP-Protocol-Version"))
accept := r.Header.Get("Accept")
if !strings.Contains(accept, "text/event-stream") || !strings.Contains(accept, "application/json") {
f.t.Errorf("Accept 头必须同时含 json 与 SSE:%q", accept)
}
body := map[string]any{}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
method, _ := body["method"].(string)
idRaw, hasID := body["id"]
if method == "initialize" {
atomic.AddInt32(&f.initializeHit, 1)
if f.failInit > 0 {
w.WriteHeader(f.failInit)
_, _ = w.Write([]byte("auth failed, header was Authorization: Bearer leaked-token"))
return
}
w.Header().Set("Mcp-Session-Id", "sess-42")
result := map[string]any{
"protocolVersion": ProtocolVersion,
"serverInfo": map[string]any{"name": "fake-mcp", "version": "0.1"},
"capabilities": map[string]any{},
}
f.reply(w, idRaw, result, hasID)
return
}
if method == "notifications/initialized" {
w.WriteHeader(http.StatusAccepted)
return
}
if method == "tools/list" {
result := map[string]any{"tools": []map[string]any{
{"name": "yzj_find_document", "description": "双层检索 命中行带 matched_in", "inputSchema": map[string]any{"type": "object", "properties": map[string]any{"keyword": map[string]any{"type": "string"}}}},
{"name": "yzj_get_document", "description": "读取文档正文", "inputSchema": map[string]any{"type": "object"}},
}}
f.reply(w, idRaw, result, hasID)
return
}
if method == "tools/call" {
params, _ := body["params"].(map[string]any)
name, _ := params["name"].(string)
args, _ := params["arguments"].(map[string]any)
if name == "yzj_find_document" {
kw, _ := args["keyword"].(string)
result := map[string]any{"content": []map[string]any{{"type": "text", "text": "锚点 978373 命中关键词 " + kw}}, "isError": false}
f.reply(w, idRaw, result, hasID)
return
}
result := map[string]any{"content": []map[string]any{{"type": "text", "text": "工具不存在"}}, "isError": true}
f.reply(w, idRaw, result, hasID)
return
}
w.WriteHeader(http.StatusNotFound)
}
func (f *fakeMCP) reply(w http.ResponseWriter, idRaw any, result map[string]any, hasID bool) {
resp := map[string]any{"jsonrpc": "2.0", "result": result}
if hasID {
resp["id"] = idRaw
}
if f.useSSE {
w.Header().Set("Content-Type", "text/event-stream")
_, _ = w.Write([]byte("event: message\ndata: {\"jsonrpc\":\"2.0\",\"method\":\"notifications/message\"}\n\n"))
payload, _ := json.Marshal(resp)
_, _ = fmt.Fprintf(w, "event: message\ndata: %s\n\n", payload)
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(resp)
}
func newFake(t *testing.T) (*fakeMCP, *httptest.Server) {
t.Helper()
fake := &fakeMCP{t: t}
srv := httptest.NewServer(fake)
t.Cleanup(srv.Close)
return fake, srv
}
// ── 探测 / 调用行为 ────────────────────────────────────────
func TestProbeSuccessAndSession(t *testing.T) {
fake, srv := newFake(t)
result, tools := Probe(context.Background(), srv.URL, map[string]string{"Authorization": "Bearer ok"}, 5*time.Second)
if !result.OK {
t.Fatalf("探测应成功,实际:%+v", result)
}
if result.ToolCount != 2 || len(tools) != 2 {
t.Fatalf("工具数 = %d/%d,期望 2", result.ToolCount, len(tools))
}
if tools[0].Name != "yzj_find_document" || len(tools[0].InputSchema) == 0 {
t.Fatalf("工具缓存形状不对:%+v", tools[0])
}
// 会话头:initialize 拿到 Mcp-Session-Id 后,同会话后续请求必须带上
if got, _ := fake.lastSession.Load().(string); got != "sess-42" {
t.Fatalf("后续请求缺少 Mcp-Session-Id:%q", got)
}
if got, _ := fake.lastProtocol.Load().(string); got != ProtocolVersion {
t.Fatalf("缺少 MCP-Protocol-Version:%q", got)
}
}
func TestProbeSSEFrames(t *testing.T) {
fake, srv := newFake(t)
fake.useSSE = true
result, tools := Probe(context.Background(), srv.URL, nil, 5*time.Second)
if !result.OK || len(tools) != 2 {
t.Fatalf("SSE 模式探测失败:%+v tools=%d", result, len(tools))
}
}
func TestProbeAuthErrorIsDefinitive(t *testing.T) {
fake, srv := newFake(t)
fake.failInit = http.StatusUnauthorized
result, _ := Probe(context.Background(), srv.URL, map[string]string{"Authorization": "Bearer bad"}, 5*time.Second)
if result.OK || result.ErrorType != ErrTypeAuth {
t.Fatalf("401 必须判为 auth 错,实际:%+v", result)
}
// 坏凭据不得被重试掩盖(pj0245 实测语义):initialize 只应命中一次
if n := atomic.LoadInt32(&fake.initializeHit); n != 1 {
t.Fatalf("401 后不应重试,initialize 命中 %d 次", n)
}
}
func TestProbeUnreachableRetriesOnce(t *testing.T) {
// 端口 1 无监听:unreachable 类错误重试一次后放弃
ctx, cancel := context.WithTimeout(context.Background(), 6*time.Second)
defer cancel()
result, _ := Probe(ctx, "http://127.0.0.1:1/mcp", nil, 2*time.Second)
if result.OK || result.ErrorType != ErrTypeUnreachable {
t.Fatalf("死端口应判 unreachable,实际:%+v", result)
}
}
func TestCallToolRoundTrip(t *testing.T) {
_, srv := newFake(t)
client := New(srv.URL, nil, 5*time.Second)
text, isErr, err := client.CallTool(context.Background(), "yzj_find_document", json.RawMessage(`{"keyword":"暗号"}`))
if err != nil || isErr {
t.Fatalf("tools/call 失败:isErr=%v err=%v", isErr, err)
}
if !strings.Contains(text, "978373") {
t.Fatalf("应答缺锚点:%q", text)
}
// 远端业务错(isError)必须走「内容」通道而不是 error 通道
text, isErr, err = client.CallTool(context.Background(), "nope", json.RawMessage(`{}`))
if err != nil || !isErr || !strings.Contains(text, "工具不存在") {
t.Fatalf("isError 语义不对:isErr=%v err=%v text=%q", isErr, err, text)
}
// 双重字符串化参数要能救回来
client2 := New(srv.URL, nil, 5*time.Second)
text, isErr, err = client2.CallTool(context.Background(), "yzj_find_document", json.RawMessage(`"{\"keyword\":\"救回\"}"`))
if err != nil || isErr || !strings.Contains(text, "救回") {
t.Fatalf("双重字符串参数未救回:err=%v isErr=%v text=%q", err, isErr, text)
}
}
func TestCallToolBadArgsVisible(t *testing.T) {
_, srv := newFake(t)
client := New(srv.URL, nil, 5*time.Second)
_, _, err := client.CallTool(context.Background(), "x", json.RawMessage(`["not-an-object"]`))
var ce *CallError
if err == nil || !asCallError(err, &ce) || ce.Type != ErrTypeValidation {
t.Fatalf("非对象参数应报 validation 错(G02),实际:%v", err)
}
}
func asCallError(err error, target **CallError) bool {
ce, ok := err.(*CallError)
if ok {
*target = ce
}
return ok
}
@@ -43,7 +43,7 @@ for line in sys.stdin:
pass
elif method == "tools/list":
send({"jsonrpc": "2.0", "id": mid, "result": {"tools": [
{"name": "echo", "description": "回显工具", "input_schema": {"type": "object"}}]}})
{"name": "echo", "description": "回显工具", "inputSchema": {"type": "object"}}]}})
elif method == "tools/call":
if mode == "hang":
time.sleep(30)
@@ -64,7 +64,7 @@ func GetCustomDefinition(key string) (connectorcontracts.Definition, bool) {
type customToolEntry struct {
Name string `json:"name"`
Description string `json:"description"`
InputSchema json.RawMessage `json:"input_schema,omitempty"`
InputSchema json.RawMessage `json:"inputSchema,omitempty"` // 与 mcpclient.Tool 同 tag,见其注释
}
func parseCustomTools(row model.ConnectorCustom) []customToolEntry {
@@ -0,0 +1,71 @@
package ai
import (
"context"
"encoding/json"
"regexp"
"strings"
"testing"
)
var reOpenAIToolName = regexp.MustCompile(`^[A-Za-z0-9_-]{1,64}$`)
func TestSanitizeMCPToolName(t *testing.T) {
// 常规名
if got := SanitizeMCPToolName("yzj_knowledge", "yzj_find_document"); got != "mcp__yzj_knowledge__yzj_find_document" {
t.Fatalf("常规命名不对:%s", got)
}
// 非法字符归一
if got := SanitizeMCPToolName("a.b/c", "get 文档"); !reOpenAIToolName.MatchString(got) {
t.Fatalf("非法字符未净化:%s", got)
}
// 超长必截且稳定、可区分
longTool := strings.Repeat("x", 120)
n1 := SanitizeMCPToolName("connector", longTool)
n2 := SanitizeMCPToolName("connector", longTool)
n3 := SanitizeMCPToolName("connector", longTool+"different-tail")
if len(n1) > 64 || !reOpenAIToolName.MatchString(n1) {
t.Fatalf("超长名不合约束:%s (len=%d)", n1, len(n1))
}
if n1 != n2 {
t.Fatal("同输入必须同输出")
}
if n1 == n3 {
t.Fatal("不同工具名不得撞同一个净化名")
}
}
func TestMCPToolSchemaAndExecute(t *testing.T) {
schema := json.RawMessage(`{"type":"object","properties":{"q":{"type":"string"}}}`)
called := false
tool := &MCPTool{
ToolName: "mcp__c__t",
Description: "desc",
InputSchema: schema,
Call: func(ctx context.Context, args json.RawMessage) (string, error) {
called = true
if string(args) != `{"q":"hi"}` {
t.Errorf("参数未透传:%s", args)
}
return "ok", nil
},
}
s := tool.Schema()
if s.Type != "function" || s.Function.Name != "mcp__c__t" {
t.Fatalf("schema 形状不对:%+v", s)
}
// Parameters 必须把 MCP inputSchema 原样交给模型
raw, err := json.Marshal(s.Function.Parameters)
if err != nil || !json.Valid(raw) || !strings.Contains(string(raw), `"q"`) {
t.Fatalf("inputSchema 未透传:%s err=%v", raw, err)
}
if out, err := tool.Execute(context.Background(), json.RawMessage(`{"q":"hi"}`)); err != nil || out != "ok" || !called {
t.Fatalf("Execute 委派失败:out=%q err=%v called=%v", out, err, called)
}
// 空 schema 回落通用对象
bare := &MCPTool{ToolName: "mcp__c__b", Call: func(context.Context, json.RawMessage) (string, error) { return "", nil }}
if params, err := json.Marshal(bare.Schema().Function.Parameters); err != nil || !strings.Contains(string(params), "properties") {
t.Fatalf("空 inputSchema 应回落通用对象:%s", params)
}
}
@@ -35,7 +35,7 @@ type ConnectorCustom struct {
LastProbeMessage string `gorm:"type:text" json:"last_probe_message"`
// LastProbeErrType: validation | unreachable | timeout | auth | protocol | disabled
LastProbeErrType string `gorm:"size:16" json:"last_probe_error_type"`
ToolsJSON string `gorm:"type:text" json:"-"` // [{name,description,input_schema}],tools/list 成功后整体覆盖
ToolsJSON string `gorm:"type:text" json:"-"` // [{name,description,inputSchema}],tools/list 成功后整体覆盖
ToolsSyncedAt int64 `gorm:"default:0" json:"tools_synced_at"`
CreatedBy string `gorm:"size:64" json:"created_by"`
UpdatedBy string `gorm:"size:64" json:"updated_by"`