Skip to content

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

:sparkles: Support Model Context Protocol (MCP) https://github.com/siyuan-note/siyuan/issues/13795

Danielfb32543ae69b
diff --git a/kernel/mcp/handler.go b/kernel/mcp/handler.go
new file mode 100644
index 0000000000..4329d86cbd
--- /dev/null
+++ b/kernel/mcp/handler.go
@@ -0,0 +1,170 @@
+// 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,
+}
+
+func processRequest(req *JsonRpcRequest, session *Session) 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]interface{}{},
+ 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 handleInitialize(req *JsonRpcRequest, session *Session) *JsonRpcResponse {
+ params, _ := req.Params.(map[string]interface{})
+
+ 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]interface{}{
+ "protocolVersion": serverVersion,
+ "capabilities": ServerCapabilities{
+ Tools: &ToolsCapability{ListChanged: false},
+ },
+ "serverInfo": ServerInfo{
+ Name: ServerName,
+ Version: util.Ver,
+ },
+ },
+ ID: req.ID,
+ }
+}
+
+func handleToolsList(id any) *JsonRpcResponse {
+ toolList := make([]*tools.Tool, 0, len(tools.Registry))
+ for _, t := range tools.Registry {
+ toolList = append(toolList, t)
+ }
+ return &JsonRpcResponse{
+ JsonRpc: "2.0",
+ Result: map[string]interface{}{"tools": toolList},
+ ID: id,
+ }
+}
+
+func handleToolsCall(req *JsonRpcRequest) any {
+ params, ok := req.Params.(map[string]interface{})
+ 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, exists := tools.Registry[toolName]
+ if !exists {
+ 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]interface{})
+ if toolArgs == nil {
+ toolArgs = map[string]interface{}{}
+ }
+
+ 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,
+ }
+}
diff --git a/kernel/mcp/server.go b/kernel/mcp/server.go
new file mode 100644
index 0000000000..a7f94ea79d
--- /dev/null
+++ b/kernel/mcp/server.go
@@ -0,0 +1,115 @@
+// 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 (
+ "encoding/json"
+ "io"
+ "net/http"
+
+ "github.com/gin-gonic/gin"
+ "github.com/siyuan-note/siyuan/kernel/model"
+)
+
+func Serve(ginServer *gin.Engine) {
+ ginServer.POST("/mcp", model.CheckAuth, handlePost)
+ ginServer.GET("/mcp", model.CheckAuth, func(c *gin.Context) {
+ c.Status(http.StatusMethodNotAllowed)
+ })
+ ginServer.DELETE("/mcp", model.CheckAuth, handleDelete)
+}
+
+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,
+ })
+ return
+ }
+
+ if req.JsonRpc != "2.0" {
+ c.JSON(http.StatusOK, JsonRpcErrorResponse{
+ JsonRpc: "2.0",
+ Error: RpcError{Code: -32600, Message: "Invalid Request"},
+ ID: req.ID,
+ })
+ return
+ }
+
+ if req.Method == "" {
+ c.JSON(http.StatusOK, JsonRpcErrorResponse{
+ JsonRpc: "2.0",
+ Error: RpcError{Code: -32600, Message: "Invalid Request"},
+ ID: req.ID,
+ })
+ return
+ }
+
+ 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
+ }
+ }
+
+ response := processRequest(&req, session)
+
+ if req.Method == "initialize" {
+ c.Header("Mcp-Session-Id", session.ID)
+ }
+
+ switch v := response.(type) {
+ case nil:
+ c.Status(http.StatusAccepted)
+ case *JsonRpcResponse:
+ c.JSON(http.StatusOK, v)
+ case *JsonRpcErrorResponse:
+ c.JSON(http.StatusOK, v)
+ }
+}
+
+func handleDelete(c *gin.Context) {
+ sessionID := c.GetHeader("Mcp-Session-Id")
+ if sessionID == "" {
+ c.Status(http.StatusBadRequest)
+ return
+ }
+ removeSession(sessionID)
+ c.Status(http.StatusOK)
+}
diff --git a/kernel/mcp/session.go b/kernel/mcp/session.go
new file mode 100644
index 0000000000..faf7c96830
--- /dev/null
+++ b/kernel/mcp/session.go
@@ -0,0 +1,57 @@
+// 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 (
+ "sync"
+
+ "github.com/88250/gulu"
+)
+
+type Session struct {
+ ID string
+ initialized bool
+ ready bool
+}
+
+var (
+ sessionsMu sync.RWMutex
+ sessions = map[string]*Session{}
+)
+
+func newSession() *Session {
+ s := &Session{
+ ID: gulu.Rand.String(16),
+ }
+ 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()
+}
diff --git a/kernel/mcp/tools/block.go b/kernel/mcp/tools/block.go
new file mode 100644
index 0000000000..7b9184406e
--- /dev/null
+++ b/kernel/mcp/tools/block.go
@@ -0,0 +1,303 @@
+// 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 (
+ "fmt"
+ "strings"
+
+ "github.com/siyuan-note/siyuan/kernel/model"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+var BlockTool = &Tool{
+ Name: "block",
+ Description: "Block operations for SiYuan notes.\n- get: Get block info by ID. Requires: id.\n- get_kramdown: Get block kramdown by ID. Requires: id.\n- get_children: Get child blocks by parent ID. Requires: id.\n- insert: Insert a new block. Requires: data, dataType (markdown or dom). Optional: parentID, nextID, previousID.\n- append: Append a child block. Requires: data, dataType, parentID.\n- prepend: Prepend a child block. Requires: data, dataType, parentID.\n- update: Update a block. Requires: id, data, dataType.\n- delete: Delete a block. Requires: id.",
+ InputSchema: ToolSchema{
+ Type: "object",
+ Properties: map[string]Property{
+ "action": {Type: "string", Description: "Operation", Enum: []string{"get", "get_kramdown", "get_children", "insert", "append", "prepend", "update", "delete"}},
+ "id": {Type: "string", Description: "Block ID"},
+ "data": {Type: "string", Description: "Content (markdown or dom)"},
+ "dataType": {Type: "string", Description: "Content type: markdown or dom", Enum: []string{"markdown", "dom"}},
+ "parentID": {Type: "string", Description: "Parent block ID"},
+ "nextID": {Type: "string", Description: "Next sibling block ID (for insert)"},
+ "previousID": {Type: "string", Description: "Previous sibling block ID (for insert)"},
+ },
+ Required: []string{"action"},
+ },
+ Handler: blockHandler,
+}
+
+func init() {
+ register(BlockTool)
+}
+
+func blockHandler(args map[string]interface{}) (CallToolResult, error) {
+ action, _ := args["action"].(string)
+ switch action {
+ case "get":
+ return blockGet(args)
+ case "get_kramdown":
+ return blockGetKramdown(args)
+ case "get_children":
+ return blockGetChildren(args)
+ case "insert":
+ return blockInsert(args)
+ case "append":
+ return blockAppend(args)
+ case "prepend":
+ return blockPrepend(args)
+ case "update":
+ return blockUpdate(args)
+ case "delete":
+ return blockDelete(args)
+ }
+ return CallToolResult{
+ Content: []ContentItem{{Type: "text", Text: "unknown action: " + action}},
+ IsError: true,
+ }, nil
+}
+
+func blockGet(args map[string]interface{}) (CallToolResult, error) {
+ id, _ := args["id"].(string)
+ if id == "" {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "id is required"}}, IsError: true}, nil
+ }
+
+ b, err := model.GetBlock(id, nil)
+ if err != nil {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: fmt.Sprintf("get block failed: %s", err)}}, IsError: true}, nil
+ }
+ if b == nil {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "block not found: " + id}}, IsError: true}, nil
+ }
+
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: fmt.Sprintf(
+ "ID: %s\nType: %s\nHPath: %s\nContent: %s\nMarkdown: %s\nTags: %s\nCreated: %s\nUpdated: %s",
+ b.ID, b.Type, b.HPath, b.Content, b.Markdown, b.Tag, b.Created, b.Updated,
+ )}}}, nil
+}
+
+func blockGetKramdown(args map[string]interface{}) (CallToolResult, error) {
+ id, _ := args["id"].(string)
+ if id == "" {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "id is required"}}, IsError: true}, nil
+ }
+
+ kramdown := model.GetBlockKramdown(id, "md")
+ if kramdown == "" {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "block not found or empty: " + id}}, IsError: true}, nil
+ }
+
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: kramdown}}}, nil
+}
+
+func blockGetChildren(args map[string]interface{}) (CallToolResult, error) {
+ id, _ := args["id"].(string)
+ if id == "" {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "id is required"}}, IsError: true}, nil
+ }
+
+ children := model.GetChildBlocks(id)
+ if len(children) == 0 {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "no child blocks found"}}}, nil
+ }
+
+ var sb strings.Builder
+ for _, c := range children {
+ content := c.Markdown
+ if content == "" {
+ content = c.Content
+ }
+ if len(content) > 200 {
+ content = content[:200] + "..."
+ }
+ sb.WriteString(fmt.Sprintf("- [%s] %s (%s)\n", c.Type, content, c.ID))
+ }
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: sb.String()}}}, nil
+}
+
+func blockInsert(args map[string]interface{}) (CallToolResult, error) {
+ data, dataType := getBlockData(args)
+ if data == "" {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "data is required"}}, IsError: true}, nil
+ }
+
+ var parentID, previousID, nextID string
+ if v, ok := args["parentID"].(string); ok {
+ parentID = v
+ }
+ if v, ok := args["previousID"].(string); ok {
+ previousID = v
+ }
+ if v, ok := args["nextID"].(string); ok {
+ nextID = v
+ }
+
+ if dataType == "markdown" {
+ var err error
+ data, err = markdownToBlockDOM(data)
+ if err != nil {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "convert markdown failed: " + err.Error()}}, IsError: true}, nil
+ }
+ }
+
+ transactions := []*model.Transaction{{
+ DoOperations: []*model.Operation{{
+ Action: "insert",
+ Data: data,
+ ParentID: parentID,
+ PreviousID: previousID,
+ NextID: nextID,
+ }},
+ }}
+
+ model.PerformTransactions(&transactions)
+ model.FlushTxQueue()
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "block inserted"}}}, nil
+}
+
+func blockAppend(args map[string]interface{}) (CallToolResult, error) {
+ data, dataType := getBlockData(args)
+ if data == "" {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "data is required"}}, IsError: true}, nil
+ }
+ parentID, _ := args["parentID"].(string)
+ if parentID == "" {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "parentID is required"}}, IsError: true}, nil
+ }
+
+ if dataType == "markdown" {
+ var err error
+ data, err = markdownToBlockDOM(data)
+ if err != nil {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "convert markdown failed: " + err.Error()}}, IsError: true}, nil
+ }
+ }
+
+ transactions := []*model.Transaction{{
+ DoOperations: []*model.Operation{{
+ Action: "appendInsert",
+ Data: data,
+ ParentID: parentID,
+ }},
+ }}
+
+ model.PerformTransactions(&transactions)
+ model.FlushTxQueue()
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "block appended"}}}, nil
+}
+
+func blockPrepend(args map[string]interface{}) (CallToolResult, error) {
+ data, dataType := getBlockData(args)
+ if data == "" {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "data is required"}}, IsError: true}, nil
+ }
+ parentID, _ := args["parentID"].(string)
+ if parentID == "" {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "parentID is required"}}, IsError: true}, nil
+ }
+
+ if dataType == "markdown" {
+ var err error
+ data, err = markdownToBlockDOM(data)
+ if err != nil {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "convert markdown failed: " + err.Error()}}, IsError: true}, nil
+ }
+ }
+
+ transactions := []*model.Transaction{{
+ DoOperations: []*model.Operation{{
+ Action: "prependInsert",
+ Data: data,
+ ParentID: parentID,
+ }},
+ }}
+
+ model.PerformTransactions(&transactions)
+ model.FlushTxQueue()
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "block prepended"}}}, nil
+}
+
+func blockUpdate(args map[string]interface{}) (CallToolResult, error) {
+ id, _ := args["id"].(string)
+ if id == "" {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "id is required"}}, IsError: true}, nil
+ }
+ data, dataType := getBlockData(args)
+ if data == "" {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "data is required"}}, IsError: true}, nil
+ }
+
+ if dataType == "markdown" {
+ var err error
+ data, err = markdownToBlockDOM(data)
+ if err != nil {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "convert markdown failed: " + err.Error()}}, IsError: true}, nil
+ }
+ }
+
+ transactions := []*model.Transaction{{
+ DoOperations: []*model.Operation{{
+ Action: "update",
+ ID: id,
+ Data: data,
+ }},
+ }}
+
+ model.PerformTransactions(&transactions)
+ model.FlushTxQueue()
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "block updated"}}}, nil
+}
+
+func blockDelete(args map[string]interface{}) (CallToolResult, error) {
+ id, _ := args["id"].(string)
+ if id == "" {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "id is required"}}, IsError: true}, nil
+ }
+
+ transactions := []*model.Transaction{{
+ DoOperations: []*model.Operation{{
+ Action: "delete",
+ ID: id,
+ }},
+ }}
+
+ model.PerformTransactions(&transactions)
+ model.FlushTxQueue()
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "block deleted: " + id}}}, nil
+}
+
+func getBlockData(args map[string]interface{}) (data, dataType string) {
+ data, _ = args["data"].(string)
+ dataType, _ = args["dataType"].(string)
+ if dataType == "" {
+ dataType = "markdown"
+ }
+ return
+}
+
+func markdownToBlockDOM(md string) (string, error) {
+ luteEngine := util.NewLute()
+ luteEngine.SetHTMLTag2TextMark(true)
+ result, _ := luteEngine.Md2BlockDOMTree(md, true)
+ if result == "" {
+ return "", fmt.Errorf("empty result")
+ }
+ return result, nil
+}
diff --git a/kernel/mcp/tools/document.go b/kernel/mcp/tools/document.go
new file mode 100644
index 0000000000..efbdfc8dcd
--- /dev/null
+++ b/kernel/mcp/tools/document.go
@@ -0,0 +1,172 @@
+// 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 (
+ "fmt"
+ "strings"
+
+ "github.com/siyuan-note/siyuan/kernel/model"
+)
+
+var DocumentTool = &Tool{
+ Name: "document",
+ Description: "Document operations for SiYuan notebooks.\n- get: Get document content by ID. Requires: id.\n- create: Create a new document. Requires: notebook, title, path (e.g. /folder/doc). Optional: markdown.\n- list: List documents in a notebook path. Requires: notebook. Optional: path (default /).\n- delete: Delete a document by ID. Requires: id.\n- rename: Rename a document by ID. Requires: id, title.",
+ InputSchema: ToolSchema{
+ Type: "object",
+ Properties: map[string]Property{
+ "action": {Type: "string", Description: "Operation", Enum: []string{"get", "create", "list", "delete", "rename"}},
+ "id": {Type: "string", Description: "Document block ID"},
+ "notebook": {Type: "string", Description: "Notebook ID (required for create, list)"},
+ "title": {Type: "string", Description: "Document title (for create, rename)"},
+ "path": {Type: "string", Description: "Document path like /folder/doc (for create, list)"},
+ "markdown": {Type: "string", Description: "Initial markdown content (for create)"},
+ },
+ Required: []string{"action"},
+ },
+ Handler: documentHandler,
+}
+
+func init() {
+ register(DocumentTool)
+}
+
+func documentHandler(args map[string]interface{}) (CallToolResult, error) {
+ action, _ := args["action"].(string)
+ switch action {
+ case "get":
+ return documentGet(args)
+ case "create":
+ return documentCreate(args)
+ case "list":
+ return documentList(args)
+ case "delete":
+ return documentDelete(args)
+ case "rename":
+ return documentRename(args)
+ }
+ return CallToolResult{
+ Content: []ContentItem{{Type: "text", Text: "unknown action: " + action}},
+ IsError: true,
+ }, nil
+}
+
+func documentGet(args map[string]interface{}) (CallToolResult, error) {
+ id, _ := args["id"].(string)
+ if id == "" {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "id is required"}}, IsError: true}, nil
+ }
+
+ tree, err := model.LoadTreeByBlockID(id)
+ if err != nil {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: fmt.Sprintf("load doc failed: %s", err)}}, IsError: true}, nil
+ }
+
+ b, _ := model.GetBlock(id, tree)
+ if b == nil {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "document not found: " + id}}, IsError: true}, nil
+ }
+
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: fmt.Sprintf(
+ "ID: %s\nTitle: %s\nHPath: %s\nBox: %s\nContent: %s\nMarkdown: %s\nType: %s\nCreated: %s\nUpdated: %s",
+ b.ID, b.Name, b.HPath, b.Box, b.Content, b.Markdown, b.Type, b.Created, b.Updated,
+ )}}}, nil
+}
+
+func documentCreate(args map[string]interface{}) (CallToolResult, error) {
+ notebook, _ := args["notebook"].(string)
+ if notebook == "" {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "notebook is required"}}, IsError: true}, nil
+ }
+ path, _ := args["path"].(string)
+ if path == "" {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "path is required"}}, IsError: true}, nil
+ }
+ markdown, _ := args["markdown"].(string)
+ title, _ := args["title"].(string)
+ if title == "" {
+ title = path
+ if strings.Contains(title, "/") {
+ parts := strings.Split(strings.TrimRight(title, "/"), "/")
+ title = parts[len(parts)-1]
+ }
+ }
+
+ tree, err := model.CreateDocByMd(notebook, path, title, markdown, nil, nil)
+ if err != nil {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: fmt.Sprintf("create doc failed: %s", err)}}, IsError: true}, nil
+ }
+
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: fmt.Sprintf("document created: %s (path: %s)", tree.Root.ID, path)}}}, nil
+}
+
+func documentList(args map[string]interface{}) (CallToolResult, error) {
+ notebook, _ := args["notebook"].(string)
+ if notebook == "" {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "notebook is required"}}, IsError: true}, nil
+ }
+ path, _ := args["path"].(string)
+ if path == "" {
+ path = "/"
+ }
+
+ files, _, err := model.ListDocTree(notebook, path, 0, false, false, 128)
+ if err != nil {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: fmt.Sprintf("list docs failed: %s", err)}}, IsError: true}, nil
+ }
+
+ var sb strings.Builder
+ sb.WriteString(fmt.Sprintf("Documents in %s%s:\n\n", notebook, path))
+ for _, f := range files {
+ sb.WriteString(fmt.Sprintf("- %s (id: %s, path: %s)\n", f.Name, f.ID, f.Path))
+ }
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: sb.String()}}}, nil
+}
+
+func documentDelete(args map[string]interface{}) (CallToolResult, error) {
+ id, _ := args["id"].(string)
+ if id == "" {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "id is required"}}, IsError: true}, nil
+ }
+
+ tree, err := model.LoadTreeByBlockID(id)
+ if err != nil {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: fmt.Sprintf("load doc failed: %s", err)}}, IsError: true}, nil
+ }
+
+ model.RemoveDoc(tree.Box, tree.Path)
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "document deleted: " + id}}}, nil
+}
+
+func documentRename(args map[string]interface{}) (CallToolResult, error) {
+ id, _ := args["id"].(string)
+ title, _ := args["title"].(string)
+ if id == "" || title == "" {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "id and title are required"}}, IsError: true}, nil
+ }
+
+ tree, err := model.LoadTreeByBlockID(id)
+ if err != nil {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: fmt.Sprintf("load doc failed: %s", err)}}, IsError: true}, nil
+ }
+
+ if err := model.RenameDoc(tree.Box, tree.Path, title); err != nil {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: fmt.Sprintf("rename doc failed: %s", err)}}, IsError: true}, nil
+ }
+
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: fmt.Sprintf("document renamed: %s -> %s", id, title)}}}, nil
+}
diff --git a/kernel/mcp/tools/notebook.go b/kernel/mcp/tools/notebook.go
new file mode 100644
index 0000000000..c445fb5631
--- /dev/null
+++ b/kernel/mcp/tools/notebook.go
@@ -0,0 +1,116 @@
+// 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 (
+ "fmt"
+ "strings"
+
+ "github.com/siyuan-note/siyuan/kernel/model"
+)
+
+var NotebookTool = &Tool{
+ Name: "notebook",
+ Description: "Notebook management for SiYuan.\n- list: List all notebooks.\n- create: Create a notebook. Requires: name.\n- rename: Rename a notebook. Requires: id, name.\n- remove: Remove a notebook. Requires: id.",
+ InputSchema: ToolSchema{
+ Type: "object",
+ Properties: map[string]Property{
+ "action": {Type: "string", Description: "Operation", Enum: []string{"list", "create", "rename", "remove"}},
+ "id": {Type: "string", Description: "Notebook ID (for rename, remove)"},
+ "name": {Type: "string", Description: "Notebook name (for create, rename)"},
+ },
+ Required: []string{"action"},
+ },
+ Handler: notebookHandler,
+}
+
+func init() {
+ register(NotebookTool)
+}
+
+func notebookHandler(args map[string]interface{}) (CallToolResult, error) {
+ action, _ := args["action"].(string)
+ switch action {
+ case "list":
+ return notebookList(args)
+ case "create":
+ return notebookCreate(args)
+ case "rename":
+ return notebookRename(args)
+ case "remove":
+ return notebookRemove(args)
+ }
+ return CallToolResult{
+ Content: []ContentItem{{Type: "text", Text: "unknown action: " + action}},
+ IsError: true,
+ }, nil
+}
+
+func notebookList(args map[string]interface{}) (CallToolResult, error) {
+ notebooks, err := model.ListNotebooks()
+ if err != nil {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "list notebooks failed: " + err.Error()}}, IsError: true}, nil
+ }
+
+ var sb strings.Builder
+ sb.WriteString(fmt.Sprintf("Notebooks (%d):\n\n", len(notebooks)))
+ for _, nb := range notebooks {
+ sb.WriteString(fmt.Sprintf("- %s (id: %s, icon: %s, closed: %v)\n", nb.Name, nb.ID, nb.Icon, nb.Closed))
+ }
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: sb.String()}}}, nil
+}
+
+func notebookCreate(args map[string]interface{}) (CallToolResult, error) {
+ name, _ := args["name"].(string)
+ if name == "" {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "name is required"}}, IsError: true}, nil
+ }
+
+ id, err := model.CreateBox(name)
+ if err != nil {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "create notebook failed: " + err.Error()}}, IsError: true}, nil
+ }
+
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "notebook created: " + name + " (id: " + id + ")"}}}, nil
+}
+
+func notebookRename(args map[string]interface{}) (CallToolResult, error) {
+ id, _ := args["id"].(string)
+ name, _ := args["name"].(string)
+ if id == "" || name == "" {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "id and name are required"}}, IsError: true}, nil
+ }
+
+ if err := model.RenameBox(id, name); err != nil {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "rename notebook failed: " + err.Error()}}, IsError: true}, nil
+ }
+
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "notebook renamed: " + id + " -> " + name}}}, nil
+}
+
+func notebookRemove(args map[string]interface{}) (CallToolResult, error) {
+ id, _ := args["id"].(string)
+ if id == "" {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "id is required"}}, IsError: true}, nil
+ }
+
+ if err := model.RemoveBox(id); err != nil {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "remove notebook failed: " + err.Error()}}, IsError: true}, nil
+ }
+
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "notebook removed: " + id}}}, nil
+}
diff --git a/kernel/mcp/tools/register.go b/kernel/mcp/tools/register.go
new file mode 100644
index 0000000000..9ad2f297a7
--- /dev/null
+++ b/kernel/mcp/tools/register.go
@@ -0,0 +1,23 @@
+// 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
+
+var Registry = map[string]*Tool{}
+
+func register(t *Tool) {
+ Registry[t.Name] = t
+}
diff --git a/kernel/mcp/tools/search.go b/kernel/mcp/tools/search.go
new file mode 100644
index 0000000000..1e2869f2ad
--- /dev/null
+++ b/kernel/mcp/tools/search.go
@@ -0,0 +1,98 @@
+// 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 (
+ "fmt"
+ "strings"
+
+ "github.com/siyuan-note/siyuan/kernel/model"
+)
+
+var SearchTool = &Tool{
+ Name: "search",
+ Description: "Full-text search in SiYuan notes.\n- fulltext: Search blocks by keywords. Required: query. Optional: page (default 1), pageSize (default 20).",
+ InputSchema: ToolSchema{
+ Type: "object",
+ Properties: map[string]Property{
+ "action": {Type: "string", Description: "Operation: fulltext", Enum: []string{"fulltext"}},
+ "query": {Type: "string", Description: "Search keywords"},
+ "page": {Type: "number", Description: "Page number (default 1)"},
+ "pageSize": {Type: "number", Description: "Results per page (default 20)"},
+ },
+ Required: []string{"action", "query"},
+ },
+ Handler: searchHandler,
+}
+
+func init() {
+ register(SearchTool)
+}
+
+func searchHandler(args map[string]interface{}) (CallToolResult, error) {
+ action, _ := args["action"].(string)
+ switch action {
+ case "fulltext":
+ return fulltextSearch(args)
+ }
+ return CallToolResult{
+ Content: []ContentItem{{Type: "text", Text: "unknown action: " + action}},
+ IsError: true,
+ }, nil
+}
+
+func fulltextSearch(args map[string]interface{}) (CallToolResult, error) {
+ query, _ := args["query"].(string)
+ page := 1
+ if v, ok := args["page"].(float64); ok {
+ page = int(v)
+ }
+ pageSize := 20
+ if v, ok := args["pageSize"].(float64); ok {
+ pageSize = int(v)
+ }
+ if page < 1 {
+ page = 1
+ }
+ if pageSize < 1 {
+ pageSize = 20
+ }
+
+ blocks, matchedCount, _, pageCount, _ := model.FullTextSearchBlock(
+ query, nil, nil, nil, nil, 0, 0, 0, page, pageSize,
+ )
+
+ var sb strings.Builder
+ sb.WriteString(fmt.Sprintf("Found %d results (page %d/%d):\n\n", matchedCount, page, pageCount))
+ for _, b := range blocks {
+ hPath := b.HPath
+ if hPath == "" {
+ hPath = "/"
+ }
+ content := b.Markdown
+ if content == "" {
+ content = b.Content
+ }
+ if len(content) > 200 {
+ content = content[:200] + "..."
+ }
+ sb.WriteString(fmt.Sprintf("- [%s] %s\n %s\n id: %s\n\n", hPath, b.Type, content, b.ID))
+ }
+ return CallToolResult{
+ Content: []ContentItem{{Type: "text", Text: sb.String()}},
+ }, nil
+}
diff --git a/kernel/mcp/tools/sql.go b/kernel/mcp/tools/sql.go
new file mode 100644
index 0000000000..5287e17756
--- /dev/null
+++ b/kernel/mcp/tools/sql.go
@@ -0,0 +1,107 @@
+// 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 (
+ "fmt"
+ "strings"
+
+ "github.com/siyuan-note/siyuan/kernel/sql"
+)
+
+var SQLTool = &Tool{
+ Name: "sql",
+ Description: "Execute read-only SQL queries on SiYuan's database.\n- query: Execute a SELECT-only SQL statement. Requires: stmt.",
+ InputSchema: ToolSchema{
+ Type: "object",
+ Properties: map[string]Property{
+ "action": {Type: "string", Description: "Operation", Enum: []string{"query"}},
+ "stmt": {Type: "string", Description: "SQL SELECT statement"},
+ },
+ Required: []string{"action", "stmt"},
+ },
+ Handler: sqlHandler,
+}
+
+func init() {
+ register(SQLTool)
+}
+
+func sqlHandler(args map[string]interface{}) (CallToolResult, error) {
+ action, _ := args["action"].(string)
+ switch action {
+ case "query":
+ return sqlQuery(args)
+ }
+ return CallToolResult{
+ Content: []ContentItem{{Type: "text", Text: "unknown action: " + action}},
+ IsError: true,
+ }, nil
+}
+
+func sqlQuery(args map[string]interface{}) (CallToolResult, error) {
+ stmt, _ := args["stmt"].(string)
+ if stmt == "" {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "stmt is required"}}, IsError: true}, nil
+ }
+
+ stmt = strings.TrimSpace(stmt)
+ upperStmt := strings.ToUpper(stmt)
+
+ if !strings.HasPrefix(upperStmt, "SELECT") {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "only SELECT statements are allowed"}}, IsError: true}, nil
+ }
+
+ if strings.Contains(upperStmt, "DROP") || strings.Contains(upperStmt, "CREATE") ||
+ strings.Contains(upperStmt, "ALTER") || strings.Contains(upperStmt, "TRUNCATE") {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "DDL statements are not allowed"}}, IsError: true}, nil
+ }
+
+ if err := sql.CheckSingleStatement(stmt); err != nil {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "invalid SQL: " + err.Error()}}, IsError: true}, nil
+ }
+
+ rows, err := sql.Query(stmt, 100)
+ if err != nil {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "query failed: " + err.Error()}}, IsError: true}, nil
+ }
+
+ if len(rows) == 0 {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "no results"}}}, nil
+ }
+
+ var sb strings.Builder
+ sb.WriteString(fmt.Sprintf("Query results (%d rows):\n\n", len(rows)))
+ sb.WriteString("| " + strings.Join(keysOf(rows[0]), " | ") + " |\n")
+ sb.WriteString("|" + strings.Repeat("---|", len(rows[0])) + "\n")
+ for _, row := range rows {
+ vals := make([]string, 0, len(row))
+ for _, k := range keysOf(row) {
+ vals = append(vals, fmt.Sprintf("%v", row[k]))
+ }
+ sb.WriteString("| " + strings.Join(vals, " | ") + " |\n")
+ }
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: sb.String()}}}, nil
+}
+
+func keysOf(m map[string]any) []string {
+ keys := make([]string, 0, len(m))
+ for k := range m {
+ keys = append(keys, k)
+ }
+ return keys
+}
diff --git a/kernel/mcp/tools/system.go b/kernel/mcp/tools/system.go
new file mode 100644
index 0000000000..a07c1c518a
--- /dev/null
+++ b/kernel/mcp/tools/system.go
@@ -0,0 +1,71 @@
+// 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 (
+ "fmt"
+ "time"
+
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+var SystemTool = &Tool{
+ Name: "system",
+ Description: "System information for SiYuan.\n- version: Get SiYuan version string.\n- current_time: Get current server time.\n- workspace: Get workspace directory path.",
+ InputSchema: ToolSchema{
+ Type: "object",
+ Properties: map[string]Property{
+ "action": {Type: "string", Description: "Operation", Enum: []string{"version", "current_time", "workspace"}},
+ },
+ Required: []string{"action"},
+ },
+ Handler: systemHandler,
+}
+
+func init() {
+ register(SystemTool)
+}
+
+func systemHandler(args map[string]interface{}) (CallToolResult, error) {
+ action, _ := args["action"].(string)
+ switch action {
+ case "version":
+ return systemVersion(args)
+ case "current_time":
+ return systemCurrentTime(args)
+ case "workspace":
+ return systemWorkspace(args)
+ }
+ return CallToolResult{
+ Content: []ContentItem{{Type: "text", Text: "unknown action: " + action}},
+ IsError: true,
+ }, nil
+}
+
+func systemVersion(args map[string]interface{}) (CallToolResult, error) {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: util.Ver}}}, nil
+}
+
+func systemCurrentTime(args map[string]interface{}) (CallToolResult, error) {
+ ms := util.CurrentTimeMillis()
+ t := time.UnixMilli(ms)
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: t.Format(time.RFC3339)}}}, nil
+}
+
+func systemWorkspace(args map[string]interface{}) (CallToolResult, error) {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: fmt.Sprintf("Workspace: %s\nVersion: %s\nContainer: %s", util.WorkspaceDir, util.Ver, util.Container)}}}, nil
+}
diff --git a/kernel/mcp/tools/tag.go b/kernel/mcp/tools/tag.go
new file mode 100644
index 0000000000..8b56b101b0
--- /dev/null
+++ b/kernel/mcp/tools/tag.go
@@ -0,0 +1,104 @@
+// 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 (
+ "fmt"
+ "strings"
+
+ "github.com/siyuan-note/siyuan/kernel/model"
+)
+
+var TagTool = &Tool{
+ Name: "tag",
+ Description: "Tag management for SiYuan.\n- list: List all tags or search by keyword. Optional: keyword.\n- rename: Rename a tag. Requires: old, new.\n- remove: Remove a tag. Requires: label.",
+ InputSchema: ToolSchema{
+ Type: "object",
+ Properties: map[string]Property{
+ "action": {Type: "string", Description: "Operation", Enum: []string{"list", "rename", "remove"}},
+ "keyword": {Type: "string", Description: "Search keyword (for list)"},
+ "old": {Type: "string", Description: "Old tag label (for rename)"},
+ "new": {Type: "string", Description: "New tag label (for rename)"},
+ "label": {Type: "string", Description: "Tag label (for remove)"},
+ },
+ Required: []string{"action"},
+ },
+ Handler: tagHandler,
+}
+
+func init() {
+ register(TagTool)
+}
+
+func tagHandler(args map[string]interface{}) (CallToolResult, error) {
+ action, _ := args["action"].(string)
+ switch action {
+ case "list":
+ return tagList(args)
+ case "rename":
+ return tagRename(args)
+ case "remove":
+ return tagRemove(args)
+ }
+ return CallToolResult{
+ Content: []ContentItem{{Type: "text", Text: "unknown action: " + action}},
+ IsError: true,
+ }, nil
+}
+
+func tagList(args map[string]interface{}) (CallToolResult, error) {
+ keyword, _ := args["keyword"].(string)
+ tags := model.SearchTags(keyword)
+
+ if len(tags) == 0 {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "no tags found"}}}, nil
+ }
+
+ var sb strings.Builder
+ sb.WriteString(fmt.Sprintf("Tags (%d):\n\n", len(tags)))
+ for _, t := range tags {
+ sb.WriteString(fmt.Sprintf("- #%s\n", t))
+ }
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: sb.String()}}}, nil
+}
+
+func tagRename(args map[string]interface{}) (CallToolResult, error) {
+ oldLabel, _ := args["old"].(string)
+ newLabel, _ := args["new"].(string)
+ if oldLabel == "" || newLabel == "" {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "old and new are required"}}, IsError: true}, nil
+ }
+
+ if err := model.RenameTag(oldLabel, newLabel); err != nil {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "rename tag failed: " + err.Error()}}, IsError: true}, nil
+ }
+
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "tag renamed: #" + oldLabel + " -> #" + newLabel}}}, nil
+}
+
+func tagRemove(args map[string]interface{}) (CallToolResult, error) {
+ label, _ := args["label"].(string)
+ if label == "" {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "label is required"}}, IsError: true}, nil
+ }
+
+ if err := model.RemoveTag(label); err != nil {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "remove tag failed: " + err.Error()}}, IsError: true}, nil
+ }
+
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "tag removed: #" + label}}}, nil
+}
diff --git a/kernel/mcp/tools/types.go b/kernel/mcp/tools/types.go
new file mode 100644
index 0000000000..8f1d50d048
--- /dev/null
+++ b/kernel/mcp/tools/types.go
@@ -0,0 +1,46 @@
+// 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
+
+type Tool struct {
+ Name string `json:"name"`
+ Description string `json:"description"`
+ InputSchema ToolSchema `json:"inputSchema"`
+ Handler func(args map[string]interface{}) (CallToolResult, error)
+}
+
+type ToolSchema struct {
+ Type string `json:"type"`
+ Properties map[string]Property `json:"properties"`
+ Required []string `json:"required,omitempty"`
+}
+
+type Property struct {
+ Type string `json:"type"`
+ Description string `json:"description,omitempty"`
+ Enum []string `json:"enum,omitempty"`
+}
+
+type CallToolResult struct {
+ Content []ContentItem `json:"content"`
+ IsError bool `json:"isError,omitempty"`
+}
+
+type ContentItem struct {
+ Type string `json:"type"`
+ Text string `json:"text"`
+}
diff --git a/kernel/mcp/types.go b/kernel/mcp/types.go
new file mode 100644
index 0000000000..4754229aa6
--- /dev/null
+++ b/kernel/mcp/types.go
@@ -0,0 +1,60 @@
+// 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"
+ ServerName = "SiYuan"
+)
+
+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/model/session.go b/kernel/model/session.go
index eaa5c04f36..f0b411a9c9 100644
--- a/kernel/model/session.go
+++ b/kernel/model/session.go
@@ -477,7 +477,8 @@ func ControlConcurrency(c *gin.Context) {
strings.HasPrefix(reqPath, "/api/search/") ||
strings.HasPrefix(reqPath, "/api/network/") ||
strings.HasPrefix(reqPath, "/api/broadcast/") ||
- strings.HasPrefix(reqPath, "/es/") {
+ strings.HasPrefix(reqPath, "/es/") ||
+ strings.HasPrefix(reqPath, "/mcp") {
c.Next()
return
}
diff --git a/kernel/server/serve.go b/kernel/server/serve.go
index 334cab62b3..bbf8b5c76f 100644
--- a/kernel/server/serve.go
+++ b/kernel/server/serve.go
@@ -44,6 +44,7 @@ import (
"github.com/siyuan-note/logging"
"github.com/siyuan-note/siyuan/kernel/api"
"github.com/siyuan-note/siyuan/kernel/cmd"
+ "github.com/siyuan-note/siyuan/kernel/mcp"
"github.com/siyuan-note/siyuan/kernel/model"
"github.com/siyuan-note/siyuan/kernel/server/proxy"
"github.com/siyuan-note/siyuan/kernel/util"
@@ -157,6 +158,7 @@ func Serve(fastMode bool, cookieKey string) {
serveAssets(ginServer)
serveAppearance(ginServer)
serveWebSocket(ginServer)
+ serveMCP(ginServer)
serveWebDAV(ginServer)
serveCalDAV(ginServer)
serveCardDAV(ginServer)
@@ -1087,6 +1089,10 @@ func jwtMiddleware(c *gin.Context) {
c.Next()
}
+func serveMCP(ginServer *gin.Engine) {
+ mcp.Serve(ginServer)
+}
+
func serveFixedStaticFiles(ginServer *gin.Engine) {
ginServer.StaticFile("favicon.ico", filepath.Join(util.WorkingDir, "stage", "icon.png"))