Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:bug: Harden MCP tool validation https://github.com/siyuan-note/siyuan/issues/13795

Danield992ed1cd39e
diff --git a/kernel/agent/tools.go b/kernel/agent/tools.go
index 5933339b19..9600131e28 100644
--- a/kernel/agent/tools.go
+++ b/kernel/agent/tools.go
@@ -45,7 +45,7 @@ func convertMCPToolsToOpenAI() []openai.Tool {
// executeTool 执行单次工具调用。
// 返回值:结果文本(已展平为字符串),isErr 表示工具是否返回错误结果,executionUnknown 表示副作用结果无法确定。
func executeTool(ctx context.Context, tc openai.ToolCall, sessionID string) (resultText string, isErr, executionUnknown bool) {
- t := tools.GetTool(tc.Function.Name)
+ t, validator := tools.LookupToolWithValidator(tc.Function.Name)
if t == nil {
return "unknown tool: " + tc.Function.Name, true, false
}
@@ -57,6 +57,9 @@ func executeTool(ctx context.Context, tc openai.ToolCall, sessionID string) (res
}
args := parseToolArgs(tc.Function.Arguments)
+ if err := validator.ValidateInputContext(ctx, args); err != nil {
+ return "invalid tool arguments: " + err.Error(), true, false
+ }
// _sessionID 和 _toolCallID 是原生工具专用的内部字段,用于关联会话状态和实现幂等操作。
// 仅注入给原生工具;MCP/插件工具的参数会原样转发给外部服务端,
// 严格校验(additionalProperties:false)的服务端(如 Flomo MCP)会因这个多余字段报错。
@@ -94,6 +97,9 @@ func executeTool(ctx context.Context, tc openai.ToolCall, sessionID string) (res
}
return "tool execution error: " + err.Error(), true, false
}
+ if err = validator.ValidateOutputContext(ctx, result); err != nil {
+ return "invalid tool output: " + err.Error(), true, false
+ }
return resultToString(result), result.IsError, result.ExecutionUnknown
}
diff --git a/kernel/agent/tools_test.go b/kernel/agent/tools_test.go
index ad72a57228..2bbb77d0c2 100644
--- a/kernel/agent/tools_test.go
+++ b/kernel/agent/tools_test.go
@@ -19,6 +19,7 @@ package agent
import (
"context"
"encoding/json"
+ "strings"
"testing"
"github.com/sashabaranov/go-openai"
@@ -335,6 +336,32 @@ func TestExecuteToolPropagatesUnknownExecution(t *testing.T) {
}
}
+func TestExecuteToolRejectsInvalidStructuredOutput(t *testing.T) {
+ const toolName = "test_invalid_structured_output"
+ if err := tools.SetTool(toolName, &tools.Tool{
+ Name: toolName,
+ Source: "mcp",
+ InputSchema: tools.ToolSchema{Type: "object"},
+ OutputSchema: &tools.ToolSchema{Raw: map[string]any{"type": "array"}},
+ Handler: func(args map[string]any) (tools.CallToolResult, error) {
+ return tools.CallToolResult{
+ StructuredContent: map[string]any{"wrong": true},
+ StructuredContentSet: true,
+ }, nil
+ },
+ }); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { tools.RemoveTool(toolName) })
+
+ result, isErr, executionUnknown := executeTool(context.Background(), openai.ToolCall{
+ Function: openai.FunctionCall{Name: toolName, Arguments: `{}`},
+ }, "")
+ if !isErr || executionUnknown || !strings.Contains(result, "invalid tool output") {
+ t.Fatalf("unexpected tool result: result=%q, isErr=%v, executionUnknown=%v", result, isErr, executionUnknown)
+ }
+}
+
func TestExecuteToolCancellationMarksExecutionUnknown(t *testing.T) {
const toolName = "test_cancelled_execution"
started := make(chan struct{})
diff --git a/kernel/mcp/client/mcp.go b/kernel/mcp/client/mcp.go
index e749be9208..ffb28a831e 100644
--- a/kernel/mcp/client/mcp.go
+++ b/kernel/mcp/client/mcp.go
@@ -572,12 +572,21 @@ func callMCPToolOnce(call func() (*mcp.CallToolResult, error), reconnect func(er
text = "(empty result)"
}
}
+ structuredContentSet := result.StructuredContent != nil
+ if !structuredContentSet && structuredContentExpected && !result.IsError {
+ for _, content := range result.Content {
+ if textContent, ok := content.(*mcp.TextContent); ok && strings.TrimSpace(textContent.Text) == "null" {
+ structuredContentSet = true
+ break
+ }
+ }
+ }
syr := tools.CallToolResult{
IsError: result.IsError,
Content: []tools.ContentItem{{Type: "text", Text: text}},
StructuredContent: result.StructuredContent,
- StructuredContentSet: result.StructuredContent != nil || (structuredContentExpected && !result.IsError),
+ StructuredContentSet: structuredContentSet,
}
return syr
}
diff --git a/kernel/mcp/client/mcp_test.go b/kernel/mcp/client/mcp_test.go
index 2018454750..6d1a7bdf09 100644
--- a/kernel/mcp/client/mcp_test.go
+++ b/kernel/mcp/client/mcp_test.go
@@ -83,6 +83,17 @@ func TestCallMCPToolOncePreservesExpectedNullStructuredContent(t *testing.T) {
}
}
+func TestCallMCPToolOnceDoesNotInventMissingStructuredContent(t *testing.T) {
+ result := callMCPToolOnce(func() (*mcp.CallToolResult, error) {
+ return &mcp.CallToolResult{
+ Content: []mcp.Content{&mcp.TextContent{Text: "completed without structured output"}},
+ }, nil
+ }, func(error) {}, true)
+ if result.HasStructuredContent() {
+ t.Fatalf("missing structured content was treated as explicit null: %#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.go
index 3da0f6b73b..3cfcb5784a 100644
--- a/kernel/mcp/server.go
+++ b/kernel/mcp/server.go
@@ -167,7 +167,7 @@ func syncTool(server *mcpsdk.Server, name string, tool *tools.Tool) {
if arguments == nil {
arguments = map[string]any{}
}
- if err := validator.ValidateInput(arguments); err != nil {
+ if err := validator.ValidateInputContext(ctx, arguments); err != nil {
return toolErrorResult(fmt.Sprintf("invalid tool arguments: %v", err)), nil
}
@@ -185,7 +185,7 @@ func syncTool(server *mcpsdk.Server, name string, tool *tools.Tool) {
if err != nil {
return toolErrorResult(err.Error()), nil
}
- if err = validator.ValidateOutput(result); err != nil {
+ if err = validator.ValidateOutputContext(ctx, result); err != nil {
return toolErrorResult(fmt.Sprintf("invalid tool output: %v", err)), nil
}
diff --git a/kernel/mcp/tools/register.go b/kernel/mcp/tools/register.go
index fe47d272e9..c3719a96da 100644
--- a/kernel/mcp/tools/register.go
+++ b/kernel/mcp/tools/register.go
@@ -25,27 +25,39 @@ import (
var registryMu sync.RWMutex
var Registry = map[string]*Tool{}
+var registryValidators = map[string]*ToolValidator{}
var registryObservers = map[uint64]func(string, *Tool){}
var registryObserverID uint64
func GetTool(name string) *Tool {
- return LookupTool(name)
+ tool, _ := LookupToolWithValidator(name)
+ return tool
}
func LookupTool(name string) *Tool {
+ tool, _ := LookupToolWithValidator(name)
+ return tool
+}
+
+func LookupToolWithValidator(name string) (*Tool, *ToolValidator) {
registryMu.RLock()
defer registryMu.RUnlock()
+ key, tool := lookupToolLocked(name)
+ return tool, registryValidators[key]
+}
+
+func lookupToolLocked(name string) (string, *Tool) {
name = strings.TrimSpace(name)
if t := Registry[name]; t != nil {
- return t
+ return name, t
}
lower := strings.ToLower(name)
for k, v := range Registry {
if strings.ToLower(k) == lower {
- return v
+ return k, v
}
}
@@ -53,12 +65,12 @@ func LookupTool(name string) *Tool {
base := strings.TrimPrefix(lower, prefix)
for k, v := range Registry {
if strings.ToLower(k) == base {
- return v
+ return k, v
}
}
}
- return nil
+ return "", nil
}
func GetAllTools() []*Tool {
@@ -75,12 +87,14 @@ func GetAllTools() []*Tool {
}
func SetTool(name string, t *Tool) error {
- if _, err := CompileToolValidator(t); err != nil {
+ validator, err := CompileToolValidator(t)
+ if err != nil {
return err
}
registryMu.Lock()
defer registryMu.Unlock()
Registry[name] = t
+ registryValidators[name] = validator
notifyRegistryObservers(name, t)
return nil
}
@@ -89,6 +103,7 @@ func RemoveTool(name string) {
registryMu.Lock()
defer registryMu.Unlock()
delete(Registry, name)
+ delete(registryValidators, name)
notifyRegistryObservers(name, nil)
}
@@ -97,6 +112,7 @@ func RemoveToolIf(name string, tool *Tool) {
defer registryMu.Unlock()
if Registry[name] == tool {
delete(Registry, name)
+ delete(registryValidators, name)
notifyRegistryObservers(name, nil)
}
}
diff --git a/kernel/mcp/tools/register_test.go b/kernel/mcp/tools/register_test.go
index 2133b90e92..3d81c08a6b 100644
--- a/kernel/mcp/tools/register_test.go
+++ b/kernel/mcp/tools/register_test.go
@@ -72,3 +72,33 @@ func TestSetToolKeepsExistingToolWhenSchemaIsInvalid(t *testing.T) {
t.Fatalf("invalid replacement changed registry entry: %#v", actual)
}
}
+
+func TestSetToolKeepsExistingToolWhenParamHeaderIsInvalid(t *testing.T) {
+ const name = "registry_header_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{
+ "type": "object",
+ "properties": map[string]any{
+ "value": map[string]any{
+ "type": "string",
+ "x-mcp-header": "",
+ },
+ },
+ }},
+ }
+ if err := SetTool(name, invalid); err == nil {
+ t.Fatal("expected invalid x-mcp-header annotation")
+ }
+ if actual := LookupTool(name); actual != original {
+ t.Fatalf("invalid replacement changed registry entry: %#v", actual)
+ }
+}
diff --git a/kernel/mcp/tools/validation.go b/kernel/mcp/tools/validation.go
index f911fcc079..fc0bcb1396 100644
--- a/kernel/mcp/tools/validation.go
+++ b/kernel/mcp/tools/validation.go
@@ -17,12 +17,27 @@
package tools
import (
+ "context"
"encoding/json"
"fmt"
+ "strings"
+ "time"
"github.com/google/jsonschema-go/jsonschema"
)
+const (
+ maxToolSchemaBytes = 1 << 20
+ maxToolSchemaDepth = 64
+ maxToolSchemaNodes = 16 << 10
+ maxToolValueBytes = 8 << 20
+ maxToolValueDepth = 128
+ maxToolValueNodes = 256 << 10
+ toolValidationTime = 2 * time.Second
+)
+
+var toolValidationSlots = make(chan struct{}, 4)
+
type ToolValidator struct {
input *jsonschema.Resolved
output *jsonschema.Resolved
@@ -48,10 +63,30 @@ func CompileToolValidator(tool *Tool) (*ToolValidator, error) {
}
func resolveToolSchema(schema ToolSchema, requireObject bool) (*jsonschema.Resolved, error) {
+ if schema.Raw != nil {
+ if err := validateJSONComplexity(schema.Raw, maxToolSchemaDepth, maxToolSchemaNodes); err != nil {
+ return nil, err
+ }
+ }
data, err := json.Marshal(schema)
if err != nil {
return nil, err
}
+ if len(data) > maxToolSchemaBytes {
+ return nil, fmt.Errorf("schema exceeds %d bytes", maxToolSchemaBytes)
+ }
+ var raw any
+ if err = json.Unmarshal(data, &raw); err != nil {
+ return nil, err
+ }
+ if err = validateJSONComplexity(raw, maxToolSchemaDepth, maxToolSchemaNodes); err != nil {
+ return nil, err
+ }
+ if requireObject {
+ if err = validateParamHeaderAnnotations(raw); err != nil {
+ return nil, err
+ }
+ }
var parsed jsonschema.Schema
if err = json.Unmarshal(data, &parsed); err != nil {
return nil, err
@@ -63,26 +98,181 @@ func resolveToolSchema(schema ToolSchema, requireObject bool) (*jsonschema.Resol
}
func (validator *ToolValidator) ValidateInput(arguments map[string]any) error {
+ return validator.ValidateInputContext(context.Background(), arguments)
+}
+
+func (validator *ToolValidator) ValidateInputContext(ctx context.Context, arguments map[string]any) error {
if validator == nil || validator.input == nil {
return nil
}
- return validator.input.Validate(arguments)
+ value, err := prepareValidationValue(arguments)
+ if err != nil {
+ return err
+ }
+ return validateResolved(ctx, validator.input, value)
}
func (validator *ToolValidator) ValidateOutput(result CallToolResult) error {
+ return validator.ValidateOutputContext(context.Background(), result)
+}
+
+func (validator *ToolValidator) ValidateOutputContext(ctx context.Context, 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)
+ value, err := prepareValidationValue(result.StructuredContent)
+ if err != nil {
+ return fmt.Errorf("prepare structured content: %w", err)
+ }
+ return validateResolved(ctx, validator.output, value)
+}
+
+func prepareValidationValue(value any) (any, error) {
+ if err := validateJSONComplexity(value, maxToolValueDepth, maxToolValueNodes); err != nil {
+ return nil, err
+ }
+ data, err := json.Marshal(value)
if err != nil {
- return fmt.Errorf("marshal structured content: %w", err)
+ return nil, err
+ }
+ if len(data) > maxToolValueBytes {
+ return nil, fmt.Errorf("value exceeds %d bytes", maxToolValueBytes)
+ }
+ var canonical any
+ if err = json.Unmarshal(data, &canonical); err != nil {
+ return nil, err
}
- var value any
- if err = json.Unmarshal(data, &value); err != nil {
- return fmt.Errorf("unmarshal structured content: %w", err)
+ if err = validateJSONComplexity(canonical, maxToolValueDepth, maxToolValueNodes); err != nil {
+ return nil, err
+ }
+ return canonical, nil
+}
+
+func validateResolved(ctx context.Context, schema *jsonschema.Resolved, value any) error {
+ if ctx == nil {
+ ctx = context.Background()
+ }
+ timer := time.NewTimer(toolValidationTime)
+ defer timer.Stop()
+
+ select {
+ case toolValidationSlots <- struct{}{}:
+ case <-ctx.Done():
+ return ctx.Err()
+ case <-timer.C:
+ return fmt.Errorf("validation did not start within %s", toolValidationTime)
+ }
+
+ result := make(chan error, 1)
+ go func() {
+ err := schema.Validate(value)
+ <-toolValidationSlots
+ result <- err
+ }()
+
+ select {
+ case err := <-result:
+ return err
+ case <-ctx.Done():
+ return ctx.Err()
+ case <-timer.C:
+ return fmt.Errorf("validation exceeded %s", toolValidationTime)
+ }
+}
+
+func validateJSONComplexity(value any, maxDepth, maxNodes int) error {
+ nodes := 0
+ var walk func(any, int) error
+ walk = func(current any, depth int) error {
+ if depth > maxDepth {
+ return fmt.Errorf("JSON depth exceeds %d", maxDepth)
+ }
+ nodes++
+ if nodes > maxNodes {
+ return fmt.Errorf("JSON node count exceeds %d", maxNodes)
+ }
+ switch typed := current.(type) {
+ case map[string]any:
+ for _, child := range typed {
+ if err := walk(child, depth+1); err != nil {
+ return err
+ }
+ }
+ case []any:
+ for _, child := range typed {
+ if err := walk(child, depth+1); err != nil {
+ return err
+ }
+ }
+ }
+ return nil
+ }
+ return walk(value, 0)
+}
+
+func validateParamHeaderAnnotations(schema any) error {
+ root, ok := schema.(map[string]any)
+ if !ok {
+ return nil
+ }
+ properties, _ := root["properties"].(map[string]any)
+ seen := map[string]bool{}
+ var walk func(map[string]any, string) error
+ walk = func(props map[string]any, prefix string) error {
+ for propertyName, rawProperty := range props {
+ property, ok := rawProperty.(map[string]any)
+ if !ok {
+ continue
+ }
+ path := propertyName
+ if prefix != "" {
+ path = prefix + "." + propertyName
+ }
+ if rawHeader, exists := property["x-mcp-header"]; exists {
+ header, ok := rawHeader.(string)
+ if !ok || header == "" {
+ return fmt.Errorf(`property %q: x-mcp-header must be a non-empty string`, path)
+ }
+ propertyType, _ := property["type"].(string)
+ if propertyType != "string" && propertyType != "integer" && propertyType != "boolean" {
+ return fmt.Errorf(
+ `property %q: x-mcp-header can only be applied to primitive types (integer, string, boolean), got %q`,
+ path, propertyType)
+ }
+ if !validHTTPFieldName(header) {
+ return fmt.Errorf(`property %q: x-mcp-header value %q is not a valid HTTP field name`, path, header)
+ }
+ normalized := strings.ToLower(header)
+ if seen[normalized] {
+ return fmt.Errorf(`property %q: duplicate x-mcp-header value %q`, path, header)
+ }
+ seen[normalized] = true
+ }
+ nested, _ := property["properties"].(map[string]any)
+ if err := walk(nested, path); err != nil {
+ return err
+ }
+ }
+ return nil
+ }
+ return walk(properties, "")
+}
+
+func validHTTPFieldName(name string) bool {
+ if name == "" {
+ return false
+ }
+ for _, character := range name {
+ if character > 127 ||
+ !((character >= 'a' && character <= 'z') ||
+ (character >= 'A' && character <= 'Z') ||
+ (character >= '0' && character <= '9') ||
+ strings.ContainsRune("!#$%&'*+-.^_`|~", character)) {
+ return false
+ }
}
- return validator.output.Validate(value)
+ return true
}
diff --git a/kernel/mcp/tools/validation_test.go b/kernel/mcp/tools/validation_test.go
index 349b2dafd5..c189bcd1f7 100644
--- a/kernel/mcp/tools/validation_test.go
+++ b/kernel/mcp/tools/validation_test.go
@@ -74,3 +74,59 @@ func TestToolValidatorAcceptsExplicitNullOutput(t *testing.T) {
t.Fatal(err)
}
}
+
+func TestCompileToolValidatorRejectsInvalidParamHeader(t *testing.T) {
+ _, err := CompileToolValidator(&Tool{
+ Name: "invalid_header",
+ InputSchema: ToolSchema{Raw: map[string]any{
+ "type": "object",
+ "properties": map[string]any{
+ "items": map[string]any{
+ "type": "array",
+ "x-mcp-header": "Items",
+ },
+ },
+ }},
+ })
+ if err == nil {
+ t.Fatal("expected invalid x-mcp-header annotation to fail")
+ }
+}
+
+func TestCompileToolValidatorRejectsExcessiveSchemaDepth(t *testing.T) {
+ var nested any = true
+ for range maxToolSchemaDepth + 1 {
+ nested = []any{nested}
+ }
+ _, err := CompileToolValidator(&Tool{
+ Name: "deep_schema",
+ InputSchema: ToolSchema{Raw: map[string]any{
+ "type": "object",
+ "x": nested,
+ }},
+ })
+ if err == nil {
+ t.Fatal("expected excessive schema depth to fail")
+ }
+}
+
+func TestToolValidatorRejectsExcessiveValueDepth(t *testing.T) {
+ validator, err := CompileToolValidator(&Tool{
+ Name: "deep_value",
+ InputSchema: ToolSchema{Type: "object"},
+ OutputSchema: &ToolSchema{},
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ var nested any = true
+ for range maxToolValueDepth + 1 {
+ nested = []any{nested}
+ }
+ if err = validator.ValidateOutput(CallToolResult{
+ StructuredContent: nested,
+ StructuredContentSet: true,
+ }); err == nil {
+ t.Fatal("expected excessive value depth to fail")
+ }
+}