Skip to content

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

:sparkles: Support MCP 2026-07-28 specification https://github.com/siyuan-note/siyuan/issues/13795

Daniel3083e41061f7
diff --git a/kernel/agent/tools.go b/kernel/agent/tools.go
index bd7ffcdf22..b9eab3ba6e 100644
--- a/kernel/agent/tools.go
+++ b/kernel/agent/tools.go
@@ -19,6 +19,7 @@ package agent
import (
"context"
"encoding/json"
+ "maps"
"strings"
"github.com/sashabaranov/go-openai"
@@ -98,6 +99,10 @@ func executeTool(ctx context.Context, tc openai.ToolCall, sessionID string) (res
}
func convertSchema(schema tools.ToolSchema) any {
+ if schema.Raw != nil {
+ return maps.Clone(schema.Raw)
+ }
+
// 根级 anyOf 常见于 Zod 生成的 schema,取第一个 object 变体展开。
if schema.Type == "" && len(schema.AnyOf) > 0 {
for _, variant := range schema.AnyOf {
@@ -227,6 +232,11 @@ func resultToString(result tools.CallToolResult) string {
parts = append(parts, item.Text)
}
}
+ if len(parts) == 0 && result.StructuredContent != nil {
+ if data, err := json.Marshal(result.StructuredContent); err == nil {
+ return string(data)
+ }
+ }
if len(parts) == 0 {
return "(empty result)"
}
diff --git a/kernel/agent/tools_test.go b/kernel/agent/tools_test.go
index 9942d01b29..01906ad2a3 100644
--- a/kernel/agent/tools_test.go
+++ b/kernel/agent/tools_test.go
@@ -92,6 +92,26 @@ func TestConvertSchemaRootAnyOf(t *testing.T) {
}
}
+func TestConvertSchemaPreservesRawJSONSchema(t *testing.T) {
+ raw := map[string]any{
+ "type": "object",
+ "unevaluatedProperties": false,
+ }
+ out := convertSchema(tools.ToolSchema{Raw: raw}).(map[string]any)
+ if out["unevaluatedProperties"] != false {
+ t.Fatalf("raw schema was not preserved: %#v", out)
+ }
+}
+
+func TestResultToStringUsesStructuredContent(t *testing.T) {
+ result := resultToString(tools.CallToolResult{
+ StructuredContent: map[string]any{"status": "ok"},
+ })
+ if result != `{"status":"ok"}` {
+ t.Fatalf("unexpected structured result: %q", result)
+ }
+}
+
func TestNeedsConfirmScopesReadOnlyActionsByToolSource(t *testing.T) {
const externalWrite = "test_external_write"
const externalRead = "test_external_read"
diff --git a/kernel/api/ai.go b/kernel/api/ai.go
index c2c1637a26..285a31b49d 100644
--- a/kernel/api/ai.go
+++ b/kernel/api/ai.go
@@ -295,7 +295,7 @@ func mcpOAuthCallback(c *gin.Context) {
c.Header("Referrer-Policy", "no-referrer")
c.Header("Content-Security-Policy", "default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; frame-ancestors 'none'")
callbackError := c.Query("error")
- if err := mcpclient.CompleteMCPOAuth(c.Param("flowID"), c.Query("code"), c.Query("state"), callbackError); err != nil {
+ if err := mcpclient.CompleteMCPOAuth(c.Param("flowID"), c.Query("code"), c.Query("state"), callbackError, c.Query("iss")); err != nil {
c.Data(http.StatusBadRequest, "text/html; charset=utf-8", renderMCPOAuthCallbackPage(
util.LangToBCP47(model.Conf.Lang), model.Conf.Language(327), model.Conf.Language(328), false))
return
diff --git a/kernel/go.mod b/kernel/go.mod
index 411724321b..127418501a 100644
--- a/kernel/go.mod
+++ b/kernel/go.mod
@@ -53,7 +53,7 @@ require (
github.com/mattn/go-sqlite3 v2.0.3+incompatible
github.com/microcosm-cc/bluemonday v1.0.27
github.com/mitchellh/go-ps v1.0.0
- github.com/modelcontextprotocol/go-sdk v1.6.1
+ github.com/modelcontextprotocol/go-sdk v1.7.0
github.com/mssola/useragent v1.0.0
github.com/olahol/melody v1.4.0
github.com/open-spaced-repetition/go-fsrs/v3 v3.3.1
diff --git a/kernel/go.sum b/kernel/go.sum
index bad6049059..b0695bacb7 100644
--- a/kernel/go.sum
+++ b/kernel/go.sum
@@ -310,8 +310,8 @@ github.com/mitchellh/go-ps v1.0.0 h1:i6ampVEEF4wQFF+bkYfwYgY+F/uYJDktmvLPf7qIgjc
github.com/mitchellh/go-ps v1.0.0/go.mod h1:J4lOc8z8yJs6vUwklHw2XEIiT4z4C40KtWVN3nvg8Pg=
github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ=
github.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=
-github.com/modelcontextprotocol/go-sdk v1.6.1 h1:0zOSupjKUxPKSocPT1Wtago+mUHU2/uZ4xSOY0FGReU=
-github.com/modelcontextprotocol/go-sdk v1.6.1/go.mod h1:kzm3kzFL1/+AziGOE0nUs3gvPoNxMCvkxokMkuFapXQ=
+github.com/modelcontextprotocol/go-sdk v1.7.0 h1:yqjY2dsbKAC0LSuWZVBMrHgiG8ukXv6NRo0JiALay44=
+github.com/modelcontextprotocol/go-sdk v1.7.0/go.mod h1:dL7u98E/zjJTGzEq+j30jQ8K2k1mb6LeAH4inEcSGts=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
diff --git a/kernel/mcp/client/convert.go b/kernel/mcp/client/convert.go
index 64d3180ee0..155ad41671 100644
--- a/kernel/mcp/client/convert.go
+++ b/kernel/mcp/client/convert.go
@@ -17,6 +17,8 @@
package client
import (
+ "maps"
+
"github.com/siyuan-note/siyuan/kernel/mcp/tools"
)
@@ -31,6 +33,7 @@ func convertMCPSchema(inputSchema any) tools.ToolSchema {
if !ok {
return schema
}
+ schema.Raw = maps.Clone(m)
if t, ok := m["type"].(string); ok && t != "" {
schema.Type = t
diff --git a/kernel/mcp/session.go b/kernel/mcp/client/convert_test.go
similarity index 50%
rename from kernel/mcp/session.go
rename to kernel/mcp/client/convert_test.go
index faf7c96830..2106a3cc3f 100644
--- a/kernel/mcp/session.go
+++ b/kernel/mcp/client/convert_test.go
@@ -14,44 +14,37 @@
// 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 mcp
+package client
import (
- "sync"
-
- "github.com/88250/gulu"
-)
-
-type Session struct {
- ID string
- initialized bool
- ready bool
-}
-
-var (
- sessionsMu sync.RWMutex
- sessions = map[string]*Session{}
+ "encoding/json"
+ "reflect"
+ "testing"
)
-func newSession() *Session {
- s := &Session{
- ID: gulu.Rand.String(16),
+func TestConvertMCPSchemaPreservesJSONSchema202012(t *testing.T) {
+ input := map[string]any{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "type": "object",
+ "unevaluatedProperties": false,
+ "properties": map[string]any{
+ "value": map[string]any{
+ "type": []any{"string", "null"},
+ "const": "fixed",
+ },
+ },
}
- sessionsMu.Lock()
- sessions[s.ID] = s
- sessionsMu.Unlock()
- return s
-}
-func getSession(id string) *Session {
- sessionsMu.RLock()
- s := sessions[id]
- sessionsMu.RUnlock()
- return s
-}
-
-func removeSession(id string) {
- sessionsMu.Lock()
- delete(sessions, id)
- sessionsMu.Unlock()
+ schema := convertMCPSchema(input)
+ data, err := json.Marshal(schema)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var output map[string]any
+ if err = json.Unmarshal(data, &output); err != nil {
+ t.Fatal(err)
+ }
+ if !reflect.DeepEqual(output, input) {
+ t.Fatalf("schema changed during conversion:\ninput: %#v\noutput: %#v", input, output)
+ }
}
diff --git a/kernel/mcp/client/mcp.go b/kernel/mcp/client/mcp.go
index 2ee1ab09a5..06a81ab6e0 100644
--- a/kernel/mcp/client/mcp.go
+++ b/kernel/mcp/client/mcp.go
@@ -19,6 +19,7 @@ package client
import (
"context"
"crypto/sha256"
+ "encoding/json"
"errors"
"fmt"
"io"
@@ -285,10 +286,17 @@ func connectOneServer(ctx context.Context, server conf.MCPServer, interactive bo
readOnlyHint := trustedReadOnlyHint(server, tool)
handler := mcpToolContextHandler(server.Name, tool.Name, serverTimeout(server))
+ var outputSchema *tools.ToolSchema
+ if tool.OutputSchema != nil {
+ converted := convertMCPSchema(tool.OutputSchema)
+ outputSchema = &converted
+ }
registeredTool := &tools.Tool{
Name: name,
+ Title: tool.Title,
Description: desc,
InputSchema: convertMCPSchema(tool.InputSchema),
+ OutputSchema: outputSchema,
Source: "mcp",
ReadOnlyHint: readOnlyHint,
EffectScope: tools.EffectScopeExternal,
@@ -550,12 +558,20 @@ func callMCPToolOnce(call func() (*mcp.CallToolResult, error), reconnect func(er
}
text := strings.Join(textParts, "\n")
if text == "" {
- text = "(empty result)"
+ if result.StructuredContent != nil {
+ if data, err := json.Marshal(result.StructuredContent); err == nil {
+ text = string(data)
+ }
+ }
+ if text == "" {
+ text = "(empty result)"
+ }
}
syr := tools.CallToolResult{
- IsError: result.IsError,
- Content: []tools.ContentItem{{Type: "text", Text: text}},
+ IsError: result.IsError,
+ Content: []tools.ContentItem{{Type: "text", Text: text}},
+ StructuredContent: result.StructuredContent,
}
return syr
}
diff --git a/kernel/mcp/client/oauth.go b/kernel/mcp/client/oauth.go
index ef50f3787c..6ab13c9f54 100644
--- a/kernel/mcp/client/oauth.go
+++ b/kernel/mcp/client/oauth.go
@@ -54,6 +54,7 @@ type oauthCallbackResult struct {
type oauthFlow struct {
State string
+ Issuer string
Result chan oauthCallbackResult
Expires time.Time
}
@@ -361,6 +362,7 @@ func (h *mcpOAuthHandler) Authorize(ctx context.Context, req *http.Request, resp
flow := &oauthFlow{
State: state,
+ Issuer: asm.Issuer,
Result: make(chan oauthCallbackResult, 1),
Expires: time.Now().Add(oauthAuthorizationTimeout),
}
@@ -581,7 +583,7 @@ func removeOAuthFlow(flowID string, flow *oauthFlow) {
oauthFlows.Unlock()
}
-func CompleteMCPOAuth(flowID, code, state, callbackError string) error {
+func CompleteMCPOAuth(flowID, code, state, callbackError, issuer string) error {
oauthFlows.Lock()
flow := oauthFlows.items[flowID]
if flow == nil || time.Now().After(flow.Expires) {
@@ -593,6 +595,10 @@ func CompleteMCPOAuth(flowID, code, state, callbackError string) error {
oauthFlows.Unlock()
return fmt.Errorf("OAuth state mismatch")
}
+ if issuer != "" && issuer != flow.Issuer {
+ oauthFlows.Unlock()
+ return fmt.Errorf("OAuth issuer mismatch")
+ }
delete(oauthFlows.items, flowID)
oauthFlows.Unlock()
select {
diff --git a/kernel/mcp/client/oauth_test.go b/kernel/mcp/client/oauth_test.go
index 70ebdcbf80..9aeff26663 100644
--- a/kernel/mcp/client/oauth_test.go
+++ b/kernel/mcp/client/oauth_test.go
@@ -49,16 +49,24 @@ func TestProtectedResourceURLs(t *testing.T) {
func TestCompleteMCPOAuth(t *testing.T) {
flowID := "test-flow"
- flow := &oauthFlow{State: "test-state", Result: make(chan oauthCallbackResult, 1), Expires: time.Now().Add(time.Minute)}
+ flow := &oauthFlow{
+ State: "test-state",
+ Issuer: "https://issuer.example",
+ Result: make(chan oauthCallbackResult, 1),
+ Expires: time.Now().Add(time.Minute),
+ }
oauthFlows.Lock()
oauthFlows.items[flowID] = flow
oauthFlows.Unlock()
t.Cleanup(func() { removeOAuthFlow(flowID, flow) })
- if err := CompleteMCPOAuth(flowID, "code", "wrong-state", ""); err == nil {
+ if err := CompleteMCPOAuth(flowID, "code", "wrong-state", "", "https://issuer.example"); err == nil {
t.Fatal("expected state mismatch")
}
- if err := CompleteMCPOAuth(flowID, "code", "test-state", ""); err != nil {
+ if err := CompleteMCPOAuth(flowID, "code", "test-state", "", "https://other.example"); err == nil {
+ t.Fatal("expected issuer mismatch")
+ }
+ if err := CompleteMCPOAuth(flowID, "code", "test-state", "", "https://issuer.example"); err != nil {
t.Fatal(err)
}
result := <-flow.Result
@@ -328,7 +336,7 @@ func TestMCPOAuthAuthorizationCodeFlow(t *testing.T) {
query.Get("resource") != server.URL+"/mcp" || query.Get("scope") != "todo.read offline_access" {
t.Fatalf("unexpected authorization URL: %s", authorizationURL)
}
- if err = CompleteMCPOAuth(flowID, "authorization-code", query.Get("state"), ""); err != nil {
+ if err = CompleteMCPOAuth(flowID, "authorization-code", query.Get("state"), "", ""); err != nil {
t.Fatal(err)
}
select {
diff --git a/kernel/mcp/handler.go b/kernel/mcp/handler.go
deleted file mode 100644
index 8da7d2aac7..0000000000
--- a/kernel/mcp/handler.go
+++ /dev/null
@@ -1,242 +0,0 @@
-// 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 mcp
-
-import (
- "github.com/siyuan-note/siyuan/kernel/mcp/tools"
- "github.com/siyuan-note/siyuan/kernel/util"
-)
-
-var supportedProtocolVersions = map[string]bool{
- "2025-06-18": true,
- "2024-11-05": true,
- "2026-07-28": true,
-}
-
-func processRequest(req *JsonRpcRequest, session *Session, protocolVersion string) any {
- isNotification := req.ID == nil
-
- switch req.Method {
- case "initialize":
- if isNotification {
- return nil
- }
- return handleInitialize(req, session)
-
- case "notifications/initialized":
- session.ready = true
- return nil
-
- case "ping":
- if isNotification {
- return nil
- }
- return &JsonRpcResponse{
- JsonRpc: "2.0",
- Result: map[string]any{},
- ID: req.ID,
- }
-
- case "tools/list":
- if isNotification {
- return nil
- }
- return handleToolsList(req.ID)
-
- case "tools/call":
- if isNotification {
- return nil
- }
- return handleToolsCall(req)
-
- default:
- if isNotification {
- return nil
- }
- return &JsonRpcErrorResponse{
- JsonRpc: "2.0",
- Error: RpcError{Code: -32601, Message: "Method not found"},
- ID: req.ID,
- }
- }
-}
-
-func processRequest2026(req *JsonRpcRequest) any {
- isNotification := req.ID == nil
-
- switch req.Method {
- case "server/discover":
- if isNotification {
- return nil
- }
- return handleDiscover(req)
-
- case "ping":
- if isNotification {
- return nil
- }
- return &JsonRpcResponse{
- JsonRpc: "2.0",
- Result: map[string]any{},
- ID: req.ID,
- }
-
- case "tools/list":
- if isNotification {
- return nil
- }
- return handleToolsList2026(req.ID)
-
- case "tools/call":
- if isNotification {
- return nil
- }
- return handleToolsCall(req)
-
- default:
- if isNotification {
- return nil
- }
- return &JsonRpcErrorResponse{
- JsonRpc: "2.0",
- Error: RpcError{Code: -32601, Message: "Method not found"},
- ID: req.ID,
- }
- }
-}
-
-func handleInitialize(req *JsonRpcRequest, session *Session) *JsonRpcResponse {
- params, _ := req.Params.(map[string]any)
-
- serverVersion := ProtocolVersion
- if clientVersion, ok := params["protocolVersion"].(string); ok {
- if supportedProtocolVersions[clientVersion] {
- serverVersion = clientVersion
- }
- }
-
- session.initialized = true
-
- return &JsonRpcResponse{
- JsonRpc: "2.0",
- Result: map[string]any{
- "protocolVersion": serverVersion,
- "capabilities": ServerCapabilities{
- Tools: &ToolsCapability{ListChanged: false},
- },
- "serverInfo": ServerInfo{
- Name: ServerName,
- Version: util.Ver,
- },
- },
- ID: req.ID,
- }
-}
-
-func handleToolsList(id any) *JsonRpcResponse {
- toolList := tools.GetAllTools()
- return &JsonRpcResponse{
- JsonRpc: "2.0",
- Result: map[string]any{"tools": toolList},
- ID: id,
- }
-}
-
-func handleToolsCall(req *JsonRpcRequest) any {
- params, ok := req.Params.(map[string]any)
- if !ok {
- return &JsonRpcErrorResponse{
- JsonRpc: "2.0",
- Error: RpcError{Code: -32602, Message: "Invalid params"},
- ID: req.ID,
- }
- }
-
- toolName, _ := params["name"].(string)
- if toolName == "" {
- return &JsonRpcErrorResponse{
- JsonRpc: "2.0",
- Error: RpcError{Code: -32602, Message: "Invalid params: name is required"},
- ID: req.ID,
- }
- }
-
- t := tools.LookupTool(toolName)
- if t == nil {
- return &JsonRpcResponse{
- JsonRpc: "2.0",
- Result: tools.CallToolResult{
- Content: []tools.ContentItem{{Type: "text", Text: "tool not found: " + toolName}},
- IsError: true,
- },
- ID: req.ID,
- }
- }
-
- toolArgs, _ := params["arguments"].(map[string]any)
- if toolArgs == nil {
- toolArgs = map[string]any{}
- }
-
- result, err := t.Handler(toolArgs)
- if err != nil {
- return &JsonRpcResponse{
- JsonRpc: "2.0",
- Result: tools.CallToolResult{
- Content: []tools.ContentItem{{Type: "text", Text: err.Error()}},
- IsError: true,
- },
- ID: req.ID,
- }
- }
-
- return &JsonRpcResponse{
- JsonRpc: "2.0",
- Result: result,
- ID: req.ID,
- }
-}
-
-func handleDiscover(req *JsonRpcRequest) *JsonRpcResponse {
- return &JsonRpcResponse{
- JsonRpc: "2.0",
- Result: map[string]any{
- "protocolVersion": ProtocolV20260728,
- "capabilities": ServerCapabilities{
- Tools: &ToolsCapability{ListChanged: false},
- },
- "serverInfo": ServerInfo{
- Name: ServerName,
- Version: util.Ver,
- },
- },
- ID: req.ID,
- }
-}
-
-func handleToolsList2026(id any) *JsonRpcResponse {
- toolList := tools.GetAllTools()
- return &JsonRpcResponse{
- JsonRpc: "2.0",
- Result: map[string]any{
- "tools": toolList,
- "ttlMs": 60000,
- "cacheScope": "user",
- },
- ID: id,
- }
-}
diff --git a/kernel/mcp/server.go b/kernel/mcp/server.go
index b97570574c..8a9f214a80 100644
--- a/kernel/mcp/server.go
+++ b/kernel/mcp/server.go
@@ -17,122 +17,176 @@
package mcp
import (
+ "context"
"encoding/json"
- "io"
+ "fmt"
"net/http"
+ "sync"
"github.com/gin-gonic/gin"
+ mcpsdk "github.com/modelcontextprotocol/go-sdk/mcp"
+ "github.com/siyuan-note/logging"
+ "github.com/siyuan-note/siyuan/kernel/mcp/tools"
"github.com/siyuan-note/siyuan/kernel/model"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+const protocolVersion20260728 = "2026-07-28"
+
+var (
+ httpHandlerOnce sync.Once
+ httpHandler http.Handler
)
func Serve(ginServer *gin.Engine) {
+ handler := getHTTPHandler()
+
// MCP 工具暴露任意工作区文件读写删、SQL、插件分发等管理级原语,必须要求管理员角色,
// 否则 Publish 匿名模式注入的 RoleReader JWT 可经此链路越权调用全部工具。
- ginServer.POST("/mcp", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, handlePost)
- ginServer.GET("/mcp", model.CheckAuth, model.CheckAdminRole, func(c *gin.Context) {
- c.Status(http.StatusMethodNotAllowed)
- })
- ginServer.DELETE("/mcp", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, handleDelete)
+ ginServer.POST("/mcp", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, serveHTTP(handler))
+ ginServer.GET("/mcp", model.CheckAuth, model.CheckAdminRole, serveHTTP(handler))
+ ginServer.DELETE("/mcp", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, serveHTTP(handler))
}
-func handlePost(c *gin.Context) {
- body, err := io.ReadAll(c.Request.Body)
- if err != nil {
- c.JSON(http.StatusOK, JsonRpcErrorResponse{
- JsonRpc: "2.0",
- Error: RpcError{Code: -32700, Message: "Parse error"},
- ID: nil,
- })
- return
- }
-
- var req JsonRpcRequest
- if err := json.Unmarshal(body, &req); err != nil {
- c.JSON(http.StatusOK, JsonRpcErrorResponse{
- JsonRpc: "2.0",
- Error: RpcError{Code: -32700, Message: "Parse error"},
- ID: nil,
+func getHTTPHandler() http.Handler {
+ httpHandlerOnce.Do(func() {
+ server := newServer()
+ tools.ObserveRegistry(func(name string, tool *tools.Tool) {
+ syncTool(server, name, tool)
})
- return
- }
+ httpHandler = newHTTPHandler(server)
+ })
+ return httpHandler
+}
- if req.JsonRpc != "2.0" {
- c.JSON(http.StatusOK, JsonRpcErrorResponse{
- JsonRpc: "2.0",
- Error: RpcError{Code: -32600, Message: "Invalid Request"},
- ID: req.ID,
- })
- return
- }
+func newServer() *mcpsdk.Server {
+ server := mcpsdk.NewServer(&mcpsdk.Implementation{
+ Name: "SiYuan",
+ Version: util.Ver,
+ }, &mcpsdk.ServerOptions{
+ Capabilities: &mcpsdk.ServerCapabilities{},
+ })
+ server.AddReceivingMiddleware(privateCacheMiddleware())
+ return server
+}
- if req.Method == "" {
- c.JSON(http.StatusOK, JsonRpcErrorResponse{
- JsonRpc: "2.0",
- Error: RpcError{Code: -32600, Message: "Invalid Request"},
- ID: req.ID,
- })
- return
+func privateCacheMiddleware() mcpsdk.Middleware {
+ return func(next mcpsdk.MethodHandler) mcpsdk.MethodHandler {
+ return func(ctx context.Context, method string, request mcpsdk.Request) (mcpsdk.Result, error) {
+ result, err := next(ctx, method, request)
+ switch cacheable := result.(type) {
+ case *mcpsdk.DiscoverResult:
+ cacheable.CacheScope = "private"
+ case *mcpsdk.ListToolsResult:
+ cacheable.CacheScope = "private"
+ case *mcpsdk.ListPromptsResult:
+ cacheable.CacheScope = "private"
+ case *mcpsdk.ListResourcesResult:
+ cacheable.CacheScope = "private"
+ case *mcpsdk.ListResourceTemplatesResult:
+ cacheable.CacheScope = "private"
+ case *mcpsdk.ReadResourceResult:
+ cacheable.CacheScope = "private"
+ }
+ return result, err
+ }
}
+}
- protoVersion := c.GetHeader("MCP-Protocol-Version")
- if protoVersion == ProtocolV20260728 {
- handlePost2026(c, &req)
- return
+func newHTTPHandler(server *mcpsdk.Server) http.Handler {
+ getServer := func(*http.Request) *mcpsdk.Server {
+ return server
}
+ modern := mcpsdk.NewStreamableHTTPHandler(getServer, &mcpsdk.StreamableHTTPOptions{
+ Stateless: true,
+ JSONResponse: true,
+ CrossOriginProtection: http.NewCrossOriginProtection(),
+ PropagateRequestCancellation: true,
+ })
+ legacy := mcpsdk.NewStreamableHTTPHandler(getServer, &mcpsdk.StreamableHTTPOptions{
+ JSONResponse: true,
+ CrossOriginProtection: http.NewCrossOriginProtection(),
+ })
- var session *Session
- if req.Method == "initialize" {
- session = newSession()
- } else {
- sessionID := c.GetHeader("Mcp-Session-Id")
- if sessionID == "" {
- c.JSON(http.StatusBadRequest, gin.H{"error": "Mcp-Session-Id required"})
- return
- }
- session = getSession(sessionID)
- if session == nil {
- c.JSON(http.StatusNotFound, gin.H{"error": "session not found"})
+ return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
+ if isModernRequest(request) {
+ modern.ServeHTTP(writer, request)
return
}
- }
+ legacy.ServeHTTP(writer, request)
+ })
+}
- response := processRequest(&req, session, protoVersion)
+func isModernRequest(request *http.Request) bool {
+ version := request.Header.Get("MCP-Protocol-Version")
+ return version >= protocolVersion20260728
+}
- if req.Method == "initialize" {
- c.Header("Mcp-Session-Id", session.ID)
+func serveHTTP(handler http.Handler) gin.HandlerFunc {
+ return func(context *gin.Context) {
+ handler.ServeHTTP(context.Writer, context.Request)
}
-
- writeResponse(c, response)
}
-func handlePost2026(c *gin.Context, req *JsonRpcRequest) {
- mcpMethod := c.GetHeader("Mcp-Method")
- if mcpMethod != "" && mcpMethod != req.Method {
- c.JSON(http.StatusBadRequest, gin.H{"error": "Mcp-Method header does not match body method"})
+func syncTool(server *mcpsdk.Server, name string, tool *tools.Tool) {
+ if tool == nil {
+ server.RemoveTools(name)
return
}
+ defer func() {
+ if recovered := recover(); recovered != nil {
+ logging.LogWarnf("mcp: skip invalid server tool [%s]: %v", name, recovered)
+ }
+ }()
+
+ sdkTool := &mcpsdk.Tool{
+ Name: name,
+ Title: tool.Title,
+ Description: tool.Description,
+ InputSchema: tool.InputSchema,
+ OutputSchema: tool.OutputSchema,
+ }
+ if tool.ReadOnlyHint {
+ sdkTool.Annotations = &mcpsdk.ToolAnnotations{ReadOnlyHint: true}
+ }
- response := processRequest2026(req)
- writeResponse(c, response)
-}
+ server.AddTool(sdkTool, func(ctx context.Context, request *mcpsdk.CallToolRequest) (*mcpsdk.CallToolResult, error) {
+ arguments := map[string]any{}
+ if len(request.Params.Arguments) > 0 {
+ if err := json.Unmarshal(request.Params.Arguments, &arguments); err != nil {
+ return nil, fmt.Errorf("invalid tool arguments: %w", err)
+ }
+ }
+ if arguments == nil {
+ arguments = map[string]any{}
+ }
-func writeResponse(c *gin.Context, response any) {
- switch v := response.(type) {
- case nil:
- c.Status(http.StatusAccepted)
- case *JsonRpcResponse:
- c.JSON(http.StatusOK, v)
- case *JsonRpcErrorResponse:
- c.JSON(http.StatusOK, v)
- }
-}
+ var (
+ result tools.CallToolResult
+ err error
+ )
+ if tool.ContextHandler != nil {
+ result, err = tool.ContextHandler(ctx, arguments)
+ } else if tool.Handler != nil {
+ result, err = tool.Handler(arguments)
+ } else {
+ 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
+ }
-func handleDelete(c *gin.Context) {
- sessionID := c.GetHeader("Mcp-Session-Id")
- if sessionID == "" {
- c.Status(http.StatusBadRequest)
- return
- }
- removeSession(sessionID)
- c.Status(http.StatusOK)
+ content := make([]mcpsdk.Content, 0, len(result.Content))
+ for _, item := range result.Content {
+ content = append(content, &mcpsdk.TextContent{Text: item.Text})
+ }
+ return &mcpsdk.CallToolResult{
+ Content: content,
+ StructuredContent: result.StructuredContent,
+ IsError: result.IsError,
+ }, nil
+ })
}
diff --git a/kernel/mcp/server_test.go b/kernel/mcp/server_test.go
new file mode 100644
index 0000000000..2962aeb8b7
--- /dev/null
+++ b/kernel/mcp/server_test.go
@@ -0,0 +1,326 @@
+// 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 mcp
+
+import (
+ "context"
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ mcpsdk "github.com/modelcontextprotocol/go-sdk/mcp"
+ "github.com/siyuan-note/siyuan/kernel/mcp/tools"
+)
+
+func newTestHTTPServer(t *testing.T) (*mcpsdk.Server, *httptest.Server) {
+ t.Helper()
+ server := newServer()
+ syncTool(server, "echo", &tools.Tool{
+ Name: "echo",
+ Description: "Echo text",
+ InputSchema: tools.ToolSchema{
+ Type: "object",
+ Properties: map[string]tools.Property{
+ "text": {Type: "string"},
+ },
+ },
+ Handler: func(arguments map[string]any) (tools.CallToolResult, error) {
+ text, _ := arguments["text"].(string)
+ return tools.CallToolResult{Content: []tools.ContentItem{{Type: "text", Text: text}}}, nil
+ },
+ })
+ httpServer := httptest.NewServer(newHTTPHandler(server))
+ t.Cleanup(httpServer.Close)
+ return server, httpServer
+}
+
+func TestModernProtocolClient(t *testing.T) {
+ server, httpServer := newTestHTTPServer(t)
+ 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()
+ })
+
+ if result := session.InitializeResult(); result == nil || result.ProtocolVersion != protocolVersion20260728 {
+ t.Fatalf("unexpected protocol version: %#v", result)
+ }
+ if session.ID() != "" {
+ t.Fatalf("modern protocol must not create a session ID: %q", session.ID())
+ }
+
+ callResult, err := session.CallTool(t.Context(), &mcpsdk.CallToolParams{
+ Name: "echo",
+ Arguments: map[string]any{"text": "hello"},
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(callResult.Content) != 1 {
+ t.Fatalf("unexpected tool content: %#v", callResult.Content)
+ }
+ text, ok := callResult.Content[0].(*mcpsdk.TextContent)
+ if !ok || text.Text != "hello" {
+ t.Fatalf("unexpected tool result: %#v", callResult.Content[0])
+ }
+
+ syncTool(server, "structured", &tools.Tool{
+ Name: "structured",
+ Description: "Return structured content",
+ InputSchema: tools.ToolSchema{Type: "object"},
+ OutputSchema: &tools.ToolSchema{Type: "object"},
+ Handler: func(map[string]any) (tools.CallToolResult, error) {
+ return tools.CallToolResult{
+ Content: []tools.ContentItem{{Type: "text", Text: `{"status":"ok"}`}},
+ StructuredContent: map[string]any{"status": "ok"},
+ }, nil
+ },
+ })
+ structuredResult, err := session.CallTool(t.Context(), &mcpsdk.CallToolParams{Name: "structured"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ structured, ok := structuredResult.StructuredContent.(map[string]any)
+ if !ok || structured["status"] != "ok" {
+ t.Fatalf("unexpected structured content: %#v", structuredResult.StructuredContent)
+ }
+
+ syncTool(server, "dynamic", &tools.Tool{
+ Name: "dynamic",
+ Description: "Dynamically registered tool",
+ InputSchema: tools.ToolSchema{Type: "object"},
+ Handler: func(map[string]any) (tools.CallToolResult, error) {
+ return tools.CallToolResult{}, nil
+ },
+ })
+ listResult, err := session.ListTools(t.Context(), nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ found := false
+ for _, tool := range listResult.Tools {
+ if tool.Name == "dynamic" {
+ found = true
+ break
+ }
+ }
+ if !found {
+ t.Fatal("dynamically registered tool was not listed")
+ }
+}
+
+func TestInvalidDynamicToolDoesNotCrashServer(t *testing.T) {
+ server, httpServer := newTestHTTPServer(t)
+ syncTool(server, "invalid", &tools.Tool{
+ Name: "invalid",
+ Description: "Invalid schema",
+ 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 == "invalid" {
+ t.Fatal("invalid dynamic tool was exposed")
+ }
+ }
+}
+
+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":{}}}}`
+
+ response := postMCP(t, httpServer.URL, body, map[string]string{
+ "MCP-Protocol-Version": protocolVersion20260728,
+ })
+ if response.StatusCode != http.StatusBadRequest {
+ t.Fatalf("unexpected status for missing Mcp-Method: %d", response.StatusCode)
+ }
+ var errorResponse struct {
+ Error struct {
+ Code int `json:"code"`
+ } `json:"error"`
+ }
+ decodeResponse(t, response, &errorResponse)
+ if errorResponse.Error.Code != mcpsdk.CodeHeaderMismatch {
+ t.Fatalf("unexpected error code: %d", errorResponse.Error.Code)
+ }
+
+ response = postMCP(t, httpServer.URL, body, map[string]string{
+ "MCP-Protocol-Version": protocolVersion20260728,
+ "Mcp-Method": "tools/list",
+ })
+ if response.StatusCode != http.StatusOK {
+ t.Fatalf("unexpected status: %d", response.StatusCode)
+ }
+ var listResponse struct {
+ Result struct {
+ ResultType string `json:"resultType"`
+ CacheScope string `json:"cacheScope"`
+ } `json:"result"`
+ }
+ decodeResponse(t, response, &listResponse)
+ if listResponse.Result.ResultType != "complete" || listResponse.Result.CacheScope != "private" {
+ t.Fatalf("unexpected modern result: %#v", listResponse.Result)
+ }
+}
+
+func TestLegacyProtocolSession(t *testing.T) {
+ _, httpServer := newTestHTTPServer(t)
+ initialize := `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"legacy","version":"1.0.0"}}}`
+ response := postMCP(t, httpServer.URL, initialize, nil)
+ if response.StatusCode != http.StatusOK {
+ t.Fatalf("unexpected initialize status: %d", response.StatusCode)
+ }
+ sessionID := response.Header.Get("Mcp-Session-Id")
+ if sessionID == "" {
+ t.Fatal("legacy initialize did not create a session ID")
+ }
+ var initializeResponse struct {
+ Result struct {
+ ProtocolVersion string `json:"protocolVersion"`
+ } `json:"result"`
+ }
+ decodeResponse(t, response, &initializeResponse)
+ if initializeResponse.Result.ProtocolVersion != "2025-11-25" {
+ t.Fatalf("unexpected legacy protocol version: %q", initializeResponse.Result.ProtocolVersion)
+ }
+
+ response = postMCP(t, httpServer.URL,
+ `{"jsonrpc":"2.0","method":"notifications/initialized","params":{}}`,
+ map[string]string{
+ "MCP-Protocol-Version": "2025-11-25",
+ "Mcp-Session-Id": sessionID,
+ })
+ if response.StatusCode != http.StatusAccepted {
+ t.Fatalf("unexpected initialized status: %d", response.StatusCode)
+ }
+ response.Body.Close()
+
+ response = postMCP(t, httpServer.URL,
+ `{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}`,
+ map[string]string{
+ "MCP-Protocol-Version": "2025-11-25",
+ "Mcp-Session-Id": sessionID,
+ })
+ if response.StatusCode != http.StatusOK {
+ t.Fatalf("unexpected tools/list status: %d", response.StatusCode)
+ }
+ var listResponse struct {
+ Result struct {
+ Tools []struct {
+ Name string `json:"name"`
+ } `json:"tools"`
+ } `json:"result"`
+ }
+ decodeResponse(t, response, &listResponse)
+ if len(listResponse.Result.Tools) != 1 || listResponse.Result.Tools[0].Name != "echo" {
+ t.Fatalf("unexpected legacy tool list: %#v", listResponse.Result.Tools)
+ }
+}
+
+func TestLegacyInitializeDoesNotNegotiateModernProtocol(t *testing.T) {
+ _, httpServer := newTestHTTPServer(t)
+ initialize := `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2026-07-28","capabilities":{},"clientInfo":{"name":"legacy","version":"1.0.0"}}}`
+ response := postMCP(t, httpServer.URL, initialize, nil)
+ if response.StatusCode != http.StatusOK {
+ t.Fatalf("unexpected initialize status: %d", response.StatusCode)
+ }
+ var initializeResponse struct {
+ Result struct {
+ ProtocolVersion string `json:"protocolVersion"`
+ } `json:"result"`
+ }
+ decodeResponse(t, response, &initializeResponse)
+ if initializeResponse.Result.ProtocolVersion != "2025-11-25" {
+ t.Fatalf("legacy initialize negotiated modern protocol: %q", initializeResponse.Result.ProtocolVersion)
+ }
+}
+
+func TestModernProtocolRejectsCrossOriginAndDelete(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":{}}}}`
+ response := postMCP(t, httpServer.URL, body, map[string]string{
+ "MCP-Protocol-Version": protocolVersion20260728,
+ "Mcp-Method": "tools/list",
+ "Origin": "https://example.com",
+ })
+ if response.StatusCode != http.StatusForbidden {
+ t.Fatalf("unexpected cross-origin status: %d", response.StatusCode)
+ }
+ response.Body.Close()
+
+ request, err := http.NewRequestWithContext(context.Background(), http.MethodDelete, httpServer.URL, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ request.Header.Set("MCP-Protocol-Version", protocolVersion20260728)
+ response, err = http.DefaultClient.Do(request)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer response.Body.Close()
+ if response.StatusCode != http.StatusMethodNotAllowed || response.Header.Get("Allow") != "POST" {
+ t.Fatalf("unexpected modern DELETE response: %d %q", response.StatusCode, response.Header.Get("Allow"))
+ }
+}
+
+func postMCP(t *testing.T, endpoint, body string, headers map[string]string) *http.Response {
+ t.Helper()
+ request, err := http.NewRequestWithContext(t.Context(), http.MethodPost, endpoint, strings.NewReader(body))
+ if err != nil {
+ t.Fatal(err)
+ }
+ request.Header.Set("Content-Type", "application/json")
+ request.Header.Set("Accept", "application/json, text/event-stream")
+ for name, value := range headers {
+ request.Header.Set(name, value)
+ }
+ response, err := http.DefaultClient.Do(request)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return response
+}
+
+func decodeResponse(t *testing.T, response *http.Response, target any) {
+ t.Helper()
+ defer response.Body.Close()
+ data, err := io.ReadAll(response.Body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = json.Unmarshal(data, target); err != nil {
+ t.Fatalf("decode response %q: %v", data, err)
+ }
+}
diff --git a/kernel/mcp/tools/register.go b/kernel/mcp/tools/register.go
index 529e7b6dc0..87935c17b9 100644
--- a/kernel/mcp/tools/register.go
+++ b/kernel/mcp/tools/register.go
@@ -24,6 +24,8 @@ import (
var registryMu sync.RWMutex
var Registry = map[string]*Tool{}
+var registryObservers = map[uint64]func(string, *Tool){}
+var registryObserverID uint64
func GetTool(name string) *Tool {
return LookupTool(name)
@@ -75,12 +77,14 @@ func SetTool(name string, t *Tool) {
registryMu.Lock()
defer registryMu.Unlock()
Registry[name] = t
+ notifyRegistryObservers(name, t)
}
func RemoveTool(name string) {
registryMu.Lock()
defer registryMu.Unlock()
delete(Registry, name)
+ notifyRegistryObservers(name, nil)
}
func RemoveToolIf(name string, tool *Tool) {
@@ -88,6 +92,36 @@ func RemoveToolIf(name string, tool *Tool) {
defer registryMu.Unlock()
if Registry[name] == tool {
delete(Registry, name)
+ notifyRegistryObservers(name, nil)
+ }
+}
+
+// ObserveRegistry 监听工具注册表变更,并在注册监听器时按名称顺序发送当前工具快照。
+func ObserveRegistry(observer func(string, *Tool)) (stop func()) {
+ registryMu.Lock()
+ registryObserverID++
+ id := registryObserverID
+ registryObservers[id] = observer
+ names := make([]string, 0, len(Registry))
+ for name := range Registry {
+ names = append(names, name)
+ }
+ sort.Strings(names)
+ for _, name := range names {
+ observer(name, Registry[name])
+ }
+ registryMu.Unlock()
+
+ return func() {
+ registryMu.Lock()
+ delete(registryObservers, id)
+ registryMu.Unlock()
+ }
+}
+
+func notifyRegistryObservers(name string, tool *Tool) {
+ for _, observer := range registryObservers {
+ observer(name, tool)
}
}
diff --git a/kernel/mcp/tools/register_test.go b/kernel/mcp/tools/register_test.go
index 8450a34214..b5a34f6b9d 100644
--- a/kernel/mcp/tools/register_test.go
+++ b/kernel/mcp/tools/register_test.go
@@ -26,3 +26,28 @@ func TestGetAllToolsSorted(t *testing.T) {
}
}
}
+
+func TestObserveRegistry(t *testing.T) {
+ const name = "registry_observer_test"
+ RemoveTool(name)
+
+ var events []*Tool
+ stop := ObserveRegistry(func(changedName string, tool *Tool) {
+ if changedName == name {
+ events = append(events, tool)
+ }
+ })
+ t.Cleanup(func() {
+ stop()
+ RemoveTool(name)
+ })
+
+ tool := &Tool{Name: name}
+ SetTool(name, tool)
+ RemoveToolIf(name, &Tool{Name: name})
+ RemoveToolIf(name, tool)
+
+ if len(events) != 2 || events[0] != tool || events[1] != nil {
+ t.Fatalf("unexpected registry events: %#v", events)
+ }
+}
diff --git a/kernel/mcp/tools/types.go b/kernel/mcp/tools/types.go
index d645374cf4..186f0eceb7 100644
--- a/kernel/mcp/tools/types.go
+++ b/kernel/mcp/tools/types.go
@@ -16,7 +16,10 @@
package tools
-import "context"
+import (
+ "context"
+ "encoding/json"
+)
const (
EffectScopeLocal = "local"
@@ -69,6 +72,35 @@ type ToolSchema struct {
AllOf []ToolSchema `json:"allOf,omitempty"`
Ref string `json:"$ref,omitempty"`
Defs map[string]ToolSchema `json:"$defs,omitempty"`
+ Raw map[string]any `json:"-"`
+}
+
+func (s ToolSchema) MarshalJSON() ([]byte, error) {
+ if s.Raw != nil {
+ return json.Marshal(s.Raw)
+ }
+ type plain ToolSchema
+ return json.Marshal(plain(s))
+}
+
+func (s *ToolSchema) UnmarshalJSON(data []byte) error {
+ raw := map[string]any{}
+ if err := json.Unmarshal(data, &raw); err != nil {
+ return err
+ }
+
+ type plain ToolSchema
+ var decoded plain
+ if err := json.Unmarshal(data, &decoded); err == nil {
+ *s = ToolSchema(decoded)
+ } else {
+ *s = ToolSchema{}
+ if schemaType, ok := raw["type"].(string); ok {
+ s.Type = schemaType
+ }
+ }
+ s.Raw = raw
+ return nil
}
type Property struct {
@@ -85,9 +117,10 @@ type Property struct {
}
type CallToolResult struct {
- Content []ContentItem `json:"content"`
- IsError bool `json:"isError,omitempty"`
- ExecutionUnknown bool `json:"-"`
+ Content []ContentItem `json:"content"`
+ StructuredContent any `json:"structuredContent,omitempty"`
+ IsError bool `json:"isError,omitempty"`
+ ExecutionUnknown bool `json:"-"`
}
type ContentItem struct {
diff --git a/kernel/mcp/tools/types_test.go b/kernel/mcp/tools/types_test.go
new file mode 100644
index 0000000000..e2c26332e3
--- /dev/null
+++ b/kernel/mcp/tools/types_test.go
@@ -0,0 +1,53 @@
+// 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"
+ "reflect"
+ "testing"
+)
+
+func TestToolSchemaPreservesUnknownKeywords(t *testing.T) {
+ input := map[string]any{
+ "type": "object",
+ "unevaluatedProperties": false,
+ "properties": map[string]any{
+ "value": map[string]any{"type": []any{"string", "null"}},
+ },
+ }
+ data, err := json.Marshal(input)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ var schema ToolSchema
+ if err = json.Unmarshal(data, &schema); err != nil {
+ t.Fatal(err)
+ }
+ data, err = json.Marshal(schema)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var output map[string]any
+ if err = json.Unmarshal(data, &output); err != nil {
+ t.Fatal(err)
+ }
+ if !reflect.DeepEqual(output, input) {
+ t.Fatalf("schema changed during round trip:\ninput: %#v\noutput: %#v", input, output)
+ }
+}
diff --git a/kernel/mcp/types.go b/kernel/mcp/types.go
deleted file mode 100644
index 32e3618591..0000000000
--- a/kernel/mcp/types.go
+++ /dev/null
@@ -1,65 +0,0 @@
-// 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 mcp
-
-const (
- ProtocolVersion = "2025-06-18"
- ProtocolV20260728 = "2026-07-28"
- ServerName = "SiYuan"
-)
-
-type Meta struct {
- ClientInfo *ServerInfo `json:"io.modelcontextprotocol/clientInfo,omitempty"`
-}
-
-type JsonRpcRequest struct {
- JsonRpc string `json:"jsonrpc"`
- Method string `json:"method"`
- Params any `json:"params,omitempty"`
- ID any `json:"id,omitempty"`
-}
-
-type JsonRpcResponse struct {
- JsonRpc string `json:"jsonrpc"`
- Result any `json:"result"`
- ID any `json:"id"`
-}
-
-type JsonRpcErrorResponse struct {
- JsonRpc string `json:"jsonrpc"`
- Error RpcError `json:"error"`
- ID any `json:"id"`
-}
-
-type RpcError struct {
- Code int `json:"code"`
- Message string `json:"message"`
- Data any `json:"data,omitempty"`
-}
-
-type ServerCapabilities struct {
- Tools *ToolsCapability `json:"tools,omitempty"`
-}
-
-type ToolsCapability struct {
- ListChanged bool `json:"listChanged"`
-}
-
-type ServerInfo struct {
- Name string `json:"name"`
- Version string `json:"version"`
-}
diff --git a/kernel/plugin/plugin.go b/kernel/plugin/plugin.go
index f9832c1c37..da5034a2a4 100644
--- a/kernel/plugin/plugin.go
+++ b/kernel/plugin/plugin.go
@@ -437,7 +437,8 @@ func (p *KernelPlugin) invokeMcpTool(handler goja.Callable, args map[string]any)
}
return tools.CallToolResult{
- Content: []tools.ContentItem{{Type: "text", Text: string(jsonBytes)}},
+ Content: []tools.ContentItem{{Type: "text", Text: string(jsonBytes)}},
+ StructuredContent: taskResult.value,
}, nil
case <-p.context.Done():