An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:white_check_mark: Assert the MCP surface against the request contract
Jeffrey Chenddd5c5082d4c
diff --git a/kernel/mcp/tools/http_request.go b/kernel/mcp/tools/http_request.goindex 8adf967db5..3a72eec0a7 100644--- a/kernel/mcp/tools/http_request.go+++ b/kernel/mcp/tools/http_request.go@@ -19,6 +19,7 @@ package toolsimport ("fmt""net/url"+ "strconv""github.com/siyuan-note/siyuan/kernel/conf""github.com/siyuan-note/siyuan/kernel/model"@@ -66,9 +67,11 @@ func httpRequestHandler(args map[string]any) (CallToolResult, error) {headers := map[string]string{}if hs, ok := args["headers"].(map[string]any); ok {- for k, v := range hs {- headers[k] = fmt.Sprintf("%v", v)+ parsed, err := parseHeaderValues(hs)+ if err != nil {+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: err.Error()}}, IsError: true}, nil}+ headers = parsed}body, _ := args["body"].(string)@@ -102,3 +105,26 @@ func httpRequestHandler(args map[string]any) (CallToolResult, error) {Content: []ContentItem{{Type: "text", Text: result}},}, nil}++// parseHeaderValues 把请求头收敛成字符串。嵌套对象与数组必须报错:直接格式化会把 Go 的+// 内部表示(map[a:1]、[a b])当成头值发出去,调用方看到成功却发了一段自己没写过的内容。+// 标量按可读形式接受,与 attr 工具对属性值的处理保持一致。+func parseHeaderValues(values map[string]any) (map[string]string, error) {+ headers := make(map[string]string, len(values))+ for name, value := range values {+ switch typed := value.(type) {+ case string:+ headers[name] = typed+ case bool:+ headers[name] = strconv.FormatBool(typed)+ case float64:+ // JSON 数字统一解析为 float64,用最短往返表示避免出现 5.000000。+ headers[name] = strconv.FormatFloat(typed, 'f', -1, 64)+ case nil:+ return nil, fmt.Errorf("header %q must be a string, number or boolean (got null)", name)+ default:+ return nil, fmt.Errorf("header %q must be a string, number or boolean (got %T)", name, value)+ }+ }+ return headers, nil+}diff --git a/kernel/mcp/tools/schema_consistency_test.go b/kernel/mcp/tools/schema_consistency_test.gonew file mode 100644index 0000000000..e51c282e31--- /dev/null+++ b/kernel/mcp/tools/schema_consistency_test.go@@ -0,0 +1,66 @@+// SiYuan - https://github.com/siyuan-note/siyuan+// Copyright (c) 2020-present, b3log.org+// SPDX-License-Identifier: AGPL-3.0-or-later++package tools++import (+ "sort"+ "testing"+)++// 一个工具的对外契约由 schema 声明,实际能力由 handler 实现,效果声明由 ActionEffects 提供,三处独立维护。+// 这里只断言那些在所有工具上都成立的关系;不适用的维度在各自注释里说明为什么不断言,+// 避免为了统一而改造本来就是刻意不同的实现。+func TestToolSchemaDeclaresItsActions(t *testing.T) {+ names := sortedToolNames()+ for _, name := range names {+ tool := Registry[name]+ action, hasAction := tool.InputSchema.Properties["action"]+ if hasAction {+ if len(action.Enum) == 0 {+ t.Errorf("%s: declares an action property without an enum, so callers cannot know the accepted values", name)+ }+ // 不断言 action 必须出现在 required:http_request 的 action 是可省略的 HTTP 方法,+ // 文档与实现都按「默认 get」处理,强制必填反而会改变既有契约。+ }+ // 不断言 enum 必须与 handler 的 switch 分支一一对应:file、skill、snippet、sql 的 handler+ // 把分派委托给另一个函数,bazaar 用 isPluginProjectAction 走 if 分支,http_request 把 action+ // 直接作为 HTTP 方法传下去,mcp 用匿名 handler 注册。这些写法都有明确理由,静态匹配只会误报。+ }+}++// ActionEffects 按 action 声明本地读写、数据外发与外部计费,智能体据此决定确认与快照。+// 空串键是「未单独列出的动作」的兜底项(见 Tool.EffectsFor);除此之外的键不在 schema 的 enum 里+// 就永远不会被读到,是纯粹的死声明。+func TestActionEffectsOnlyDeclareReachableActions(t *testing.T) {+ for _, name := range sortedToolNames() {+ tool := Registry[name]+ if len(tool.ActionEffects) == 0 {+ continue+ }+ declared := map[string]bool{"": true}+ for _, value := range tool.InputSchema.Properties["action"].Enum {+ declared[value] = true+ }+ keys := make([]string, 0, len(tool.ActionEffects))+ for key := range tool.ActionEffects {+ keys = append(keys, key)+ }+ sort.Strings(keys)+ for _, key := range keys {+ if !declared[key] {+ t.Errorf("%s: declares effects for action %q, which the schema does not accept", name, key)+ }+ }+ }+}++func sortedToolNames() []string {+ names := make([]string, 0, len(Registry))+ for name := range Registry {+ names = append(names, name)+ }+ sort.Strings(names)+ return names+}diff --git a/kernel/mcp/tools/value_contract_test.go b/kernel/mcp/tools/value_contract_test.gonew file mode 100644index 0000000000..232e1dd0a3--- /dev/null+++ b/kernel/mcp/tools/value_contract_test.go@@ -0,0 +1,77 @@+// SiYuan - https://github.com/siyuan-note/siyuan+// Copyright (c) 2020-present, b3log.org+// SPDX-License-Identifier: AGPL-3.0-or-later++package tools++import (+ "encoding/json"+ "testing"++ "github.com/siyuan-note/siyuan/kernel/apicontract"+)++// MCP 工具与 REST 端点对同一个模型能力各自解析参数,两者必须给出同样的取舍:同一个值,+// 一边接受另一边拒绝,说明调用方按任一文档写都能通过其中一条路径而拿到不同结果。+// 这里用 REST 的请求结构体本身当判据,而不是在测试里复述一份规则——规则改了测试自动跟随。+func TestAttributeValuesFollowTheRequestContract(t *testing.T) {+ cases := []struct {+ name string+ value any+ json string+ }{+ {name: "string", value: "text", json: `"text"`},+ // null 在 REST 契约里是 *string 的零值,含义是删除该属性。+ {name: "null", value: nil, json: `null`},+ {name: "number", value: float64(5), json: `5`},+ {name: "boolean", value: true, json: `true`},+ {name: "object", value: map[string]any{"a": float64(1)}, json: `{"a":1}`},+ {name: "array", value: []any{"a"}, json: `["a"]`},+ }+ for _, testCase := range cases {+ t.Run(testCase.name, func(t *testing.T) {+ var request apicontract.SetBlockAttrsRequest+ restErr := json.Unmarshal([]byte(`{"id":"box","attrs":{"custom-x":`+testCase.json+`}}`), &request)+ values, mcpErr := parseAttrValues(map[string]any{"custom-x": testCase.value})+ if (restErr == nil) != (mcpErr == nil) {+ t.Fatalf("REST error = %v, MCP error = %v; both surfaces must accept or reject the same value",+ restErr, mcpErr)+ }+ if restErr != nil {+ return+ }+ // REST 用 nil 指针表示删除,MCP 用空字符串表示删除,这是两边的既有约定,取值必须一致。+ expected := ""+ if pointer := request.Attrs["custom-x"]; pointer != nil {+ expected = *pointer+ }+ if values["custom-x"] != expected {+ t.Fatalf("REST stores %q, MCP stores %q", expected, values["custom-x"])+ }+ })+ }+}++// 请求头没有删除语义,null 因此不像属性值那样可以折叠成空串;但嵌套结构必须与属性值一样拒绝,+// 否则格式化会把 Go 的内部表示当作头发出去。+func TestHeaderValuesRejectWhatCannotBeSent(t *testing.T) {+ accepted := map[string]any{"Authorization": "Bearer token", "X-Count": float64(5), "X-Debug": true}+ headers, err := parseHeaderValues(accepted)+ if err != nil {+ t.Fatalf("scalar headers must be accepted: %s", err)+ }+ if headers["Authorization"] != "Bearer token" || headers["X-Count"] != "5" || headers["X-Debug"] != "true" {+ t.Fatalf("unexpected header values: %v", headers)+ }+ for name, value := range map[string]any{+ "null": nil,+ "object": map[string]any{"a": float64(1)},+ "array": []any{"a"},+ } {+ t.Run(name, func(t *testing.T) {+ if _, err := parseHeaderValues(map[string]any{"X-Test": value}); err == nil {+ t.Fatalf("header value of type %T must be rejected", value)+ }+ })+ }+}