An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Validate MCP tool schemas and structured results https://github.com/siyuan-note/siyuan/issues/13795
Daniel943e5eb03214
diff --git a/kernel/agent/tools.go b/kernel/agent/tools.goindex b9eab3ba6e..5933339b19 100644--- a/kernel/agent/tools.go+++ b/kernel/agent/tools.go@@ -232,7 +232,7 @@ func resultToString(result tools.CallToolResult) string {parts = append(parts, item.Text)}}- if len(parts) == 0 && result.StructuredContent != nil {+ if len(parts) == 0 && result.HasStructuredContent() {if data, err := json.Marshal(result.StructuredContent); err == nil {return string(data)}diff --git a/kernel/agent/tools_test.go b/kernel/agent/tools_test.goindex 01906ad2a3..ad72a57228 100644--- a/kernel/agent/tools_test.go+++ b/kernel/agent/tools_test.go@@ -112,16 +112,30 @@ func TestResultToStringUsesStructuredContent(t *testing.T) {}}+func TestResultToStringUsesExplicitNullStructuredContent(t *testing.T) {+ result := resultToString(tools.CallToolResult{StructuredContentSet: true})+ if result != "null" {+ t.Fatalf("unexpected explicit null result: %q", result)+ }+}+func TestNeedsConfirmScopesReadOnlyActionsByToolSource(t *testing.T) {const externalWrite = "test_external_write"const externalRead = "test_external_read"const nativeWrite = "test_native_write"const nativeExternalWrite = "test_native_external_write"- tools.SetTool(externalWrite, &tools.Tool{Name: externalWrite, Source: "mcp"})- tools.SetTool(externalRead, &tools.Tool{Name: externalRead, Source: "mcp", ReadOnlyHint: true})- tools.SetTool(nativeWrite, &tools.Tool{Name: nativeWrite, Source: "native"})+ tools.SetTool(externalWrite, &tools.Tool{+ Name: externalWrite, Source: "mcp", InputSchema: tools.ToolSchema{Type: "object"},+ })+ tools.SetTool(externalRead, &tools.Tool{+ Name: externalRead, Source: "mcp", ReadOnlyHint: true, InputSchema: tools.ToolSchema{Type: "object"},+ })+ tools.SetTool(nativeWrite, &tools.Tool{+ Name: nativeWrite, Source: "native", InputSchema: tools.ToolSchema{Type: "object"},+ })tools.SetTool(nativeExternalWrite, &tools.Tool{Name: nativeExternalWrite, Source: "native", EffectScope: tools.EffectScopeExternal,+ InputSchema: tools.ToolSchema{Type: "object"},})t.Cleanup(func() {tools.RemoveTool(externalWrite)@@ -300,8 +314,9 @@ func TestWaitCompletionKeepsConcurrentlyAcceptedResults(t *testing.T) {func TestExecuteToolPropagatesUnknownExecution(t *testing.T) {const toolName = "test_unknown_execution"tools.SetTool(toolName, &tools.Tool{- Name: toolName,- Source: "mcp",+ Name: toolName,+ Source: "mcp",+ InputSchema: tools.ToolSchema{Type: "object"},Handler: func(args map[string]any) (tools.CallToolResult, error) {return tools.CallToolResult{Content: []tools.ContentItem{{Type: "text", Text: "result unknown"}},@@ -325,7 +340,8 @@ func TestExecuteToolCancellationMarksExecutionUnknown(t *testing.T) {started := make(chan struct{})release := make(chan struct{})tools.SetTool(toolName, &tools.Tool{- Name: toolName,+ Name: toolName,+ InputSchema: tools.ToolSchema{Type: "object"},Handler: func(args map[string]any) (tools.CallToolResult, error) {close(started)<-release@@ -365,7 +381,8 @@ func TestExecuteToolDoesNotStartAfterCancellation(t *testing.T) {const toolName = "test_pre_cancelled_execution"invoked := falsetools.SetTool(toolName, &tools.Tool{- Name: toolName,+ Name: toolName,+ InputSchema: tools.ToolSchema{Type: "object"},Handler: func(args map[string]any) (tools.CallToolResult, error) {invoked = truereturn tools.CallToolResult{}, nildiff --git a/kernel/go.mod b/kernel/go.modindex 127418501a..ca41d395df 100644--- a/kernel/go.mod+++ b/kernel/go.mod@@ -153,7 +153,7 @@ require (github.com/goccy/go-yaml v1.18.0 // indirectgithub.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 // indirectgithub.com/google/go-querystring v1.2.0 // indirect- github.com/google/jsonschema-go v0.4.3 // indirect+ github.com/google/jsonschema-go v0.4.3github.com/google/pprof v0.0.0-20250607225305-033d6d78b36a // indirectgithub.com/gopherjs/gopherjs v1.21.0 // indirectgithub.com/gorilla/context v1.1.2 // indirectdiff --git a/kernel/mcp/client/mcp.go b/kernel/mcp/client/mcp.goindex 06a81ab6e0..e749be9208 100644--- a/kernel/mcp/client/mcp.go+++ b/kernel/mcp/client/mcp.go@@ -285,7 +285,7 @@ func connectOneServer(ctx context.Context, server conf.MCPServer, interactive bo}readOnlyHint := trustedReadOnlyHint(server, tool)- handler := mcpToolContextHandler(server.Name, tool.Name, serverTimeout(server))+ handler := mcpToolContextHandler(server.Name, tool.Name, serverTimeout(server), tool.OutputSchema != nil)var outputSchema *tools.ToolSchemaif tool.OutputSchema != nil {converted := convertMCPSchema(tool.OutputSchema)@@ -360,7 +360,10 @@ func registerMCPToolsForContext(ctx context.Context, registeredTools map[string]return false}for name, tool := range registeredTools {- tools.SetTool(name, tool)+ if err := tools.SetTool(name, tool); err != nil {+ logging.LogWarnf("mcp: skip invalid client tool [%s]: %v", name, err)+ delete(registeredTools, name)+ }}return true}@@ -476,7 +479,8 @@ func hasAuthorizationHeader(headers map[string]string) bool {return false}-func mcpToolContextHandler(serverName, toolName string, timeout time.Duration) func(context.Context, map[string]any) (tools.CallToolResult, error) {+func mcpToolContextHandler(serverName, toolName string, timeout time.Duration,+ structuredContentExpected bool) func(context.Context, map[string]any) (tools.CallToolResult, error) {return func(ctx context.Context, args map[string]any) (tools.CallToolResult, error) {result := callMCPToolOnce(func() (*mcp.CallToolResult, error) {result, err := callMCPTool(ctx, serverName, toolName, timeout, args)@@ -485,7 +489,7 @@ func mcpToolContextHandler(serverName, toolName string, timeout time.Duration) f}, func(err error) {logging.LogWarnf("mcp: server [%s] tool [%s] disconnected (%s), reconnecting", serverName, toolName, err)go reconnectMCP(serverName)- })+ }, structuredContentExpected)return result, nil}}@@ -528,7 +532,8 @@ func updateMCPRuntimeAfterToolCall(serverName string, callErr error) {}// callMCPToolOnce 保证一次工具请求最多发送一次。断线时只恢复后续调用所需的连接,不重放当前请求。-func callMCPToolOnce(call func() (*mcp.CallToolResult, error), reconnect func(error)) tools.CallToolResult {+func callMCPToolOnce(call func() (*mcp.CallToolResult, error), reconnect func(error),+ structuredContentExpected bool) tools.CallToolResult {result, err := call()if err != nil && isExecutionUnknownError(err) {if isReconnectableError(err) {@@ -569,9 +574,10 @@ func callMCPToolOnce(call func() (*mcp.CallToolResult, error), reconnect func(er}syr := tools.CallToolResult{- IsError: result.IsError,- Content: []tools.ContentItem{{Type: "text", Text: text}},- StructuredContent: result.StructuredContent,+ IsError: result.IsError,+ Content: []tools.ContentItem{{Type: "text", Text: text}},+ StructuredContent: result.StructuredContent,+ StructuredContentSet: result.StructuredContent != nil || (structuredContentExpected && !result.IsError),}return syr}diff --git a/kernel/mcp/client/mcp_test.go b/kernel/mcp/client/mcp_test.goindex 2559b568ad..2018454750 100644--- a/kernel/mcp/client/mcp_test.go+++ b/kernel/mcp/client/mcp_test.go@@ -46,7 +46,7 @@ func TestCallMCPToolOnceMarksTimeoutUnknownWithoutReconnect(t *testing.T) {return nil, context.DeadlineExceeded}, func(error) {reconnects++- })+ }, false)if calls != 1 || reconnects != 0 {t.Fatalf("unexpected call counts: calls=%d, reconnects=%d", calls, reconnects)}@@ -63,7 +63,7 @@ func TestCallMCPToolOnceDoesNotReplayDisconnectedCall(t *testing.T) {return nil, errors.New("connection closed after request")}, func(error) {reconnects++- })+ }, false)if calls != 1 || reconnects != 1 {t.Fatalf("unexpected call counts: calls=%d, reconnects=%d", calls, reconnects)}@@ -72,6 +72,17 @@ func TestCallMCPToolOnceDoesNotReplayDisconnectedCall(t *testing.T) {}}+func TestCallMCPToolOncePreservesExpectedNullStructuredContent(t *testing.T) {+ result := callMCPToolOnce(func() (*mcp.CallToolResult, error) {+ return &mcp.CallToolResult{+ Content: []mcp.Content{&mcp.TextContent{Text: "null"}},+ }, nil+ }, func(error) {}, true)+ if !result.HasStructuredContent() || result.StructuredContent != nil {+ t.Fatalf("expected explicit null structured content: %#v", result)+ }+}+func TestTrustedReadOnlyHint(t *testing.T) {tool := &mcp.Tool{Annotations: &mcp.ToolAnnotations{ReadOnlyHint: true}}if trustedReadOnlyHint(conf.MCPServer{}, tool) {diff --git a/kernel/mcp/server.go b/kernel/mcp/server.goindex 8a9f214a80..3da0f6b73b 100644--- a/kernel/mcp/server.go+++ b/kernel/mcp/server.go@@ -133,8 +133,15 @@ func syncTool(server *mcpsdk.Server, name string, tool *tools.Tool) {server.RemoveTools(name)return}+ validator, err := tools.CompileToolValidator(tool)+ if err != nil {+ server.RemoveTools(name)+ logging.LogWarnf("mcp: skip invalid server tool [%s]: %v", name, err)+ return+ }defer func() {if recovered := recover(); recovered != nil {+ server.RemoveTools(name)logging.LogWarnf("mcp: skip invalid server tool [%s]: %v", name, recovered)}}()@@ -160,6 +167,9 @@ func syncTool(server *mcpsdk.Server, name string, tool *tools.Tool) {if arguments == nil {arguments = map[string]any{}}+ if err := validator.ValidateInput(arguments); err != nil {+ return toolErrorResult(fmt.Sprintf("invalid tool arguments: %v", err)), nil+ }var (result tools.CallToolResult@@ -173,20 +183,31 @@ func syncTool(server *mcpsdk.Server, name string, tool *tools.Tool) {err = fmt.Errorf("tool handler is not configured")}if err != nil {- return &mcpsdk.CallToolResult{- Content: []mcpsdk.Content{&mcpsdk.TextContent{Text: err.Error()}},- IsError: true,- }, nil+ return toolErrorResult(err.Error()), nil+ }+ if err = validator.ValidateOutput(result); err != nil {+ return toolErrorResult(fmt.Sprintf("invalid tool output: %v", err)), nil}content := make([]mcpsdk.Content, 0, len(result.Content))for _, item := range result.Content {content = append(content, &mcpsdk.TextContent{Text: item.Text})}+ structuredContent := result.StructuredContent+ if result.HasStructuredContent() && structuredContent == nil {+ structuredContent = json.RawMessage("null")+ }return &mcpsdk.CallToolResult{Content: content,- StructuredContent: result.StructuredContent,+ StructuredContent: structuredContent,IsError: result.IsError,}, nil})}++func toolErrorResult(message string) *mcpsdk.CallToolResult {+ return &mcpsdk.CallToolResult{+ Content: []mcpsdk.Content{&mcpsdk.TextContent{Text: message}},+ IsError: true,+ }+}diff --git a/kernel/mcp/server_test.go b/kernel/mcp/server_test.goindex 2962aeb8b7..612f3fc038 100644--- a/kernel/mcp/server_test.go+++ b/kernel/mcp/server_test.go@@ -156,6 +156,121 @@ func TestInvalidDynamicToolDoesNotCrashServer(t *testing.T) {}}+func TestInvalidDynamicToolRemovesExistingServerTool(t *testing.T) {+ server, httpServer := newTestHTTPServer(t)+ syncTool(server, "echo", &tools.Tool{+ Name: "echo",+ Description: "Invalid replacement",+ InputSchema: tools.ToolSchema{Raw: map[string]any{}},+ })++ client := mcpsdk.NewClient(&mcpsdk.Implementation{Name: "test-client", Version: "1.0.0"}, nil)+ session, err := client.Connect(t.Context(), &mcpsdk.StreamableClientTransport{Endpoint: httpServer.URL}, nil)+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() {+ session.Close()+ })+ result, err := session.ListTools(t.Context(), nil)+ if err != nil {+ t.Fatal(err)+ }+ for _, tool := range result.Tools {+ if tool.Name == "echo" {+ t.Fatal("invalid replacement left the previous server tool exposed")+ }+ }+}++func TestToolInputAndOutputValidation(t *testing.T) {+ server, httpServer := newTestHTTPServer(t)+ inputHandlerCalled := false+ syncTool(server, "validated_input", &tools.Tool{+ Name: "validated_input",+ InputSchema: tools.ToolSchema{Raw: map[string]any{+ "type": "object",+ "required": []any{"text"},+ "properties": map[string]any{+ "text": map[string]any{"type": "string"},+ },+ }},+ Handler: func(map[string]any) (tools.CallToolResult, error) {+ inputHandlerCalled = true+ return tools.CallToolResult{}, nil+ },+ })+ syncTool(server, "validated_output", &tools.Tool{+ Name: "validated_output",+ InputSchema: tools.ToolSchema{Type: "object"},+ OutputSchema: &tools.ToolSchema{Raw: map[string]any{"type": "array"}},+ Handler: func(map[string]any) (tools.CallToolResult, error) {+ return tools.CallToolResult{+ StructuredContent: map[string]any{"wrong": true},+ StructuredContentSet: true,+ }, nil+ },+ })++ client := mcpsdk.NewClient(&mcpsdk.Implementation{Name: "test-client", Version: "1.0.0"}, nil)+ session, err := client.Connect(t.Context(), &mcpsdk.StreamableClientTransport{Endpoint: httpServer.URL}, nil)+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() {+ session.Close()+ })++ inputResult, err := session.CallTool(t.Context(), &mcpsdk.CallToolParams{Name: "validated_input"})+ if err != nil {+ t.Fatal(err)+ }+ if !inputResult.IsError || inputHandlerCalled {+ t.Fatalf("invalid input reached handler: result=%#v called=%v", inputResult, inputHandlerCalled)+ }++ outputResult, err := session.CallTool(t.Context(), &mcpsdk.CallToolParams{Name: "validated_output"})+ if err != nil {+ t.Fatal(err)+ }+ if !outputResult.IsError || outputResult.StructuredContent != nil {+ t.Fatalf("invalid output was returned: %#v", outputResult)+ }+}++func TestExplicitNullStructuredContent(t *testing.T) {+ server, httpServer := newTestHTTPServer(t)+ syncTool(server, "null_output", &tools.Tool{+ Name: "null_output",+ InputSchema: tools.ToolSchema{Type: "object"},+ OutputSchema: &tools.ToolSchema{Type: "null"},+ Handler: func(map[string]any) (tools.CallToolResult, error) {+ return tools.CallToolResult{+ Content: []tools.ContentItem{{Type: "text", Text: "null"}},+ StructuredContentSet: true,+ }, nil+ },+ })++ body := `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"null_output","arguments":{},"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}`+ response := postMCP(t, httpServer.URL, body, map[string]string{+ "MCP-Protocol-Version": protocolVersion20260728,+ "Mcp-Method": "tools/call",+ "Mcp-Name": "null_output",+ })+ if response.StatusCode != http.StatusOK {+ t.Fatalf("unexpected status: %d", response.StatusCode)+ }+ var callResponse struct {+ Result map[string]json.RawMessage `json:"result"`+ }+ decodeResponse(t, response, &callResponse)+ structured, ok := callResponse.Result["structuredContent"]+ if !ok || string(structured) != "null" {+ t.Fatalf("explicit null was not returned: %#v", callResponse.Result)+ }+}+func TestModernProtocolHeadersAndResult(t *testing.T) {_, httpServer := newTestHTTPServer(t)body := `{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}`diff --git a/kernel/mcp/tools/register.go b/kernel/mcp/tools/register.goindex 87935c17b9..fe47d272e9 100644--- a/kernel/mcp/tools/register.go+++ b/kernel/mcp/tools/register.go@@ -17,6 +17,7 @@package toolsimport (+ "fmt""sort""strings""sync"@@ -73,11 +74,15 @@ func GetAllTools() []*Tool {return result}-func SetTool(name string, t *Tool) {+func SetTool(name string, t *Tool) error {+ if _, err := CompileToolValidator(t); err != nil {+ return err+ }registryMu.Lock()defer registryMu.Unlock()Registry[name] = tnotifyRegistryObservers(name, t)+ return nil}func RemoveTool(name string) {@@ -129,5 +134,7 @@ func register(t *Tool) {if t.Source == "" {t.Source = "native"}- SetTool(t.Name, t)+ if err := SetTool(t.Name, t); err != nil {+ panic(fmt.Sprintf("register MCP tool [%s]: %v", t.Name, err))+ }}diff --git a/kernel/mcp/tools/register_test.go b/kernel/mcp/tools/register_test.goindex b5a34f6b9d..2133b90e92 100644--- a/kernel/mcp/tools/register_test.go+++ b/kernel/mcp/tools/register_test.go@@ -42,8 +42,10 @@ func TestObserveRegistry(t *testing.T) {RemoveTool(name)})- tool := &Tool{Name: name}- SetTool(name, tool)+ tool := &Tool{Name: name, InputSchema: ToolSchema{Type: "object"}}+ if err := SetTool(name, tool); err != nil {+ t.Fatal(err)+ }RemoveToolIf(name, &Tool{Name: name})RemoveToolIf(name, tool)@@ -51,3 +53,22 @@ func TestObserveRegistry(t *testing.T) {t.Fatalf("unexpected registry events: %#v", events)}}++func TestSetToolKeepsExistingToolWhenSchemaIsInvalid(t *testing.T) {+ const name = "registry_validation_test"+ original := &Tool{Name: name, InputSchema: ToolSchema{Type: "object"}}+ if err := SetTool(name, original); err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() {+ RemoveTool(name)+ })++ invalid := &Tool{Name: name, InputSchema: ToolSchema{Raw: map[string]any{}}}+ if err := SetTool(name, invalid); err == nil {+ t.Fatal("expected invalid schema")+ }+ if actual := LookupTool(name); actual != original {+ t.Fatalf("invalid replacement changed registry entry: %#v", actual)+ }+}diff --git a/kernel/mcp/tools/types.go b/kernel/mcp/tools/types.goindex 186f0eceb7..ed6eff3eb5 100644--- a/kernel/mcp/tools/types.go+++ b/kernel/mcp/tools/types.go@@ -117,10 +117,45 @@ type Property struct {}type CallToolResult struct {- Content []ContentItem `json:"content"`- StructuredContent any `json:"structuredContent,omitempty"`- IsError bool `json:"isError,omitempty"`- ExecutionUnknown bool `json:"-"`+ Content []ContentItem `json:"content"`+ StructuredContent any `json:"structuredContent,omitempty"`+ StructuredContentSet bool `json:"-"`+ IsError bool `json:"isError,omitempty"`+ ExecutionUnknown bool `json:"-"`+}++func (r CallToolResult) HasStructuredContent() bool {+ return r.StructuredContentSet || r.StructuredContent != nil+}++func (r CallToolResult) MarshalJSON() ([]byte, error) {+ type plain CallToolResult+ if r.StructuredContentSet && r.StructuredContent == nil {+ return json.Marshal(struct {+ plain+ StructuredContent json.RawMessage `json:"structuredContent"`+ }{+ plain: plain(r),+ StructuredContent: json.RawMessage("null"),+ })+ }+ return json.Marshal(plain(r))+}++func (r *CallToolResult) UnmarshalJSON(data []byte) error {+ type plain CallToolResult+ var decoded plain+ if err := json.Unmarshal(data, &decoded); err != nil {+ return err+ }+ *r = CallToolResult(decoded)++ var fields map[string]json.RawMessage+ if err := json.Unmarshal(data, &fields); err != nil {+ return err+ }+ _, r.StructuredContentSet = fields["structuredContent"]+ return nil}type ContentItem struct {diff --git a/kernel/mcp/tools/types_test.go b/kernel/mcp/tools/types_test.goindex e2c26332e3..1b1999324e 100644--- a/kernel/mcp/tools/types_test.go+++ b/kernel/mcp/tools/types_test.go@@ -51,3 +51,29 @@ func TestToolSchemaPreservesUnknownKeywords(t *testing.T) {t.Fatalf("schema changed during round trip:\ninput: %#v\noutput: %#v", input, output)}}++func TestCallToolResultPreservesExplicitNullStructuredContent(t *testing.T) {+ result := CallToolResult{+ Content: []ContentItem{{Type: "text", Text: "null"}},+ StructuredContentSet: true,+ }+ data, err := json.Marshal(result)+ if err != nil {+ t.Fatal(err)+ }+ var fields map[string]json.RawMessage+ if err = json.Unmarshal(data, &fields); err != nil {+ t.Fatal(err)+ }+ if structured, ok := fields["structuredContent"]; !ok || string(structured) != "null" {+ t.Fatalf("explicit null was not preserved: %s", data)+ }++ var decoded CallToolResult+ if err = json.Unmarshal(data, &decoded); err != nil {+ t.Fatal(err)+ }+ if !decoded.HasStructuredContent() || decoded.StructuredContent != nil {+ t.Fatalf("unexpected decoded result: %#v", decoded)+ }+}diff --git a/kernel/mcp/tools/validation.go b/kernel/mcp/tools/validation.gonew file mode 100644index 0000000000..f911fcc079--- /dev/null+++ b/kernel/mcp/tools/validation.go@@ -0,0 +1,88 @@+// SiYuan - Refactor your thinking+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package tools++import (+ "encoding/json"+ "fmt"++ "github.com/google/jsonschema-go/jsonschema"+)++type ToolValidator struct {+ input *jsonschema.Resolved+ output *jsonschema.Resolved+}++func CompileToolValidator(tool *Tool) (*ToolValidator, error) {+ if tool == nil {+ return nil, fmt.Errorf("tool is nil")+ }++ input, err := resolveToolSchema(tool.InputSchema, true)+ if err != nil {+ return nil, fmt.Errorf("invalid input schema: %w", err)+ }++ var output *jsonschema.Resolved+ if tool.OutputSchema != nil {+ if output, err = resolveToolSchema(*tool.OutputSchema, false); err != nil {+ return nil, fmt.Errorf("invalid output schema: %w", err)+ }+ }+ return &ToolValidator{input: input, output: output}, nil+}++func resolveToolSchema(schema ToolSchema, requireObject bool) (*jsonschema.Resolved, error) {+ data, err := json.Marshal(schema)+ if err != nil {+ return nil, err+ }+ var parsed jsonschema.Schema+ if err = json.Unmarshal(data, &parsed); err != nil {+ return nil, err+ }+ if requireObject && parsed.Type != "object" {+ return nil, fmt.Errorf(`root type must be "object"`)+ }+ return parsed.Resolve(nil)+}++func (validator *ToolValidator) ValidateInput(arguments map[string]any) error {+ if validator == nil || validator.input == nil {+ return nil+ }+ return validator.input.Validate(arguments)+}++func (validator *ToolValidator) ValidateOutput(result CallToolResult) error {+ if validator == nil || validator.output == nil || result.IsError {+ return nil+ }+ if !result.HasStructuredContent() {+ return fmt.Errorf("structured content is required when an output schema is defined")+ }+ data, err := json.Marshal(result.StructuredContent)+ if err != nil {+ return fmt.Errorf("marshal structured content: %w", err)+ }+ var value any+ if err = json.Unmarshal(data, &value); err != nil {+ return fmt.Errorf("unmarshal structured content: %w", err)+ }+ return validator.output.Validate(value)+}diff --git a/kernel/mcp/tools/validation_test.go b/kernel/mcp/tools/validation_test.gonew file mode 100644index 0000000000..349b2dafd5--- /dev/null+++ b/kernel/mcp/tools/validation_test.go@@ -0,0 +1,76 @@+// SiYuan - Refactor your thinking+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package tools++import "testing"++func TestToolValidatorValidatesInputAndOutput(t *testing.T) {+ validator, err := CompileToolValidator(&Tool{+ Name: "validated",+ InputSchema: ToolSchema{Raw: map[string]any{+ "type": "object",+ "required": []any{"value"},+ "properties": map[string]any{+ "value": map[string]any{"type": "string"},+ },+ }},+ OutputSchema: &ToolSchema{Raw: map[string]any{+ "type": "array",+ "items": map[string]any{+ "type": "string",+ },+ }},+ })+ if err != nil {+ t.Fatal(err)+ }+ if err = validator.ValidateInput(map[string]any{}); err == nil {+ t.Fatal("expected missing required input to fail")+ }+ if err = validator.ValidateInput(map[string]any{"value": "ok"}); err != nil {+ t.Fatal(err)+ }+ if err = validator.ValidateOutput(CallToolResult{}); err == nil {+ t.Fatal("expected missing structured content to fail")+ }+ if err = validator.ValidateOutput(CallToolResult{+ StructuredContent: []any{"ok"},+ StructuredContentSet: true,+ }); err != nil {+ t.Fatal(err)+ }+ if err = validator.ValidateOutput(CallToolResult{+ StructuredContent: map[string]any{"value": "wrong"},+ StructuredContentSet: true,+ }); err == nil {+ t.Fatal("expected invalid structured content to fail")+ }+}++func TestToolValidatorAcceptsExplicitNullOutput(t *testing.T) {+ validator, err := CompileToolValidator(&Tool{+ Name: "null",+ InputSchema: ToolSchema{Type: "object"},+ OutputSchema: &ToolSchema{Type: "null"},+ })+ if err != nil {+ t.Fatal(err)+ }+ if err = validator.ValidateOutput(CallToolResult{StructuredContentSet: true}); err != nil {+ t.Fatal(err)+ }+}diff --git a/kernel/plugin/api_mcp.go b/kernel/plugin/api_mcp.goindex 738d8e47f8..de79eafd35 100644--- a/kernel/plugin/api_mcp.go+++ b/kernel/plugin/api_mcp.go@@ -136,7 +136,9 @@ func injectMcp(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (err erro},}- p.registerMcpTool(name, tool)+ if err = p.registerMcpTool(name, tool); err != nil {+ return+ }result = map[string]any{"name": fullToolName,diff --git a/kernel/plugin/plugin.go b/kernel/plugin/plugin.goindex da5034a2a4..c5cb6af0b6 100644--- a/kernel/plugin/plugin.go+++ b/kernel/plugin/plugin.go@@ -373,8 +373,10 @@ func (p *KernelPlugin) unbindRpcMethod(name string) error {// registerMcpTool registers a tool to the global MCP registry with a plugin-specific prefix, and tracks it for cleanup on plugin stop.func (p *KernelPlugin) registerMcpTool(name string, tool *tools.Tool) error {+ if err := tools.SetTool(tool.Name, tool); err != nil {+ return err+ }p.mcpTools.Store(name, tool)- tools.SetTool(tool.Name, tool)return nil}@@ -424,7 +426,8 @@ func (p *KernelPlugin) invokeMcpTool(handler goja.Callable, args map[string]any)if taskResult.value == nil {return tools.CallToolResult{- Content: []tools.ContentItem{{Type: "text", Text: "null"}},+ Content: []tools.ContentItem{{Type: "text", Text: "null"}},+ StructuredContentSet: true,}, nil}@@ -437,8 +440,9 @@ func (p *KernelPlugin) invokeMcpTool(handler goja.Callable, args map[string]any)}return tools.CallToolResult{- Content: []tools.ContentItem{{Type: "text", Text: string(jsonBytes)}},- StructuredContent: taskResult.value,+ Content: []tools.ContentItem{{Type: "text", Text: string(jsonBytes)}},+ StructuredContent: taskResult.value,+ StructuredContentSet: true,}, nilcase <-p.context.Done():