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

Danielc0dda46b0a98
diff --git a/kernel/go.mod b/kernel/go.mod
index 8190d7e709..0742dfc522 100644
--- a/kernel/go.mod
+++ b/kernel/go.mod
@@ -7,7 +7,7 @@ require (
github.com/88250/clipboard v0.1.5
github.com/88250/epub v0.0.0-20230830085737-c19055cd1f48
github.com/88250/go-humanize v0.0.0-20240424102817-4f78fac47ea7
- github.com/88250/gulu v1.2.3-0.20260609080815-b53113e66541
+ github.com/88250/gulu v1.2.3-0.20260609090754-168309361d92
github.com/88250/lute v1.7.7-0.20260609015101-c1d6e480ca97
github.com/88250/vitess-sqlparser v0.0.0-20210205111146-56a2ded2aba1
github.com/ClarkThan/ahocorasick v0.0.0-20231011042242-30d1ef1347f4
diff --git a/kernel/go.sum b/kernel/go.sum
index d2434fa1d4..6355547931 100644
--- a/kernel/go.sum
+++ b/kernel/go.sum
@@ -12,8 +12,8 @@ github.com/88250/go-humanize v0.0.0-20240424102817-4f78fac47ea7 h1:MafIFwSS0x6A4
github.com/88250/go-humanize v0.0.0-20240424102817-4f78fac47ea7/go.mod h1:HrKCCTin3YNDSLBD02K0AOljjV6eNwc3/zyEI+xyV1I=
github.com/88250/go-sqlite3 v1.14.13-0.20231214121541-e7f54c482950 h1:Pa5hMiBceTVVqrYaDlLio2QSKbXMUmAZPbzCwT5eNCw=
github.com/88250/go-sqlite3 v1.14.13-0.20231214121541-e7f54c482950/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU=
-github.com/88250/gulu v1.2.3-0.20260609080815-b53113e66541 h1:u5cF1u1/rle/sVCR7/EqhV4y826It+SQoeyiH+k5IRU=
-github.com/88250/gulu v1.2.3-0.20260609080815-b53113e66541/go.mod h1:D+Db16m0N7r9MLZCMcj1a0ZsEGQAxDZkadOn79Gh0vI=
+github.com/88250/gulu v1.2.3-0.20260609090754-168309361d92 h1:/DtFVbsSdZLqbADVnFUz2vsNl8d1NPm98yxKdYnpB8I=
+github.com/88250/gulu v1.2.3-0.20260609090754-168309361d92/go.mod h1:D+Db16m0N7r9MLZCMcj1a0ZsEGQAxDZkadOn79Gh0vI=
github.com/88250/lute v1.7.7-0.20260609015101-c1d6e480ca97 h1:IqPqrGrv9D8a2ES79Z1sZoKCFwwZXhkHc9qmTWTB1M8=
github.com/88250/lute v1.7.7-0.20260609015101-c1d6e480ca97/go.mod h1:WYyUw//5yVw9BJnoVjx7rI/3szsISxNZCYGOqTIrV0o=
github.com/88250/pdfcpu v0.3.14-0.20250424122812-f10e8d9d8d46 h1:Bq1JsDfVbHKUxNL/B2JXd8cC/1h6aFjrlXpGycnh0Hk=
diff --git a/kernel/mcp/tools/document.go b/kernel/mcp/tools/document.go
index e86989bf46..2bbb2bc514 100644
--- a/kernel/mcp/tools/document.go
+++ b/kernel/mcp/tools/document.go
@@ -27,11 +27,11 @@ import (
var DocumentTool = &Tool{
Name: "document",
- Description: "Document operations for SiYuan.\n- get: Get document content by ID. Requires: id.\n- create: Create a new document. Requires: notebook, path (hPath, e.g. /folder/doc), title. Optional: markdown.\n- list: List documents at an hPath. Requires: notebook. Optional: path (hPath, default /).\n- delete: Delete a document by ID. Requires: id.\n- rename: Rename a document by ID. Requires: id, title.\n- move: Move a document to a different notebook/hPath. Requires: id, notebook, path (target hPath, e.g. /folder or / for root).\n- duplicate: Duplicate a document by ID. Requires: id.\n- search_docs: Search documents by keyword. Requires: keyword.",
+ Description: "Document operations for SiYuan.\n- get: Get document content by ID. Requires: id.\n- create: Create a new document. Requires: notebook, path (hPath, e.g. /folder/doc), title. Optional: markdown.\n- list: List documents at an hPath. Requires: notebook. Optional: path (hPath, default /).\n- delete: Delete a document by ID. Requires: id.\n- rename: Rename a document by ID. Requires: id, title.\n- move: Move a document to a different notebook/hPath. Requires: id, notebook, path (target hPath, e.g. /folder or / for root).\n- duplicate: Duplicate a document by ID. Requires: id.\n- search_docs: Search documents by keyword. Requires: keyword.\n- info: Get document metadata info by ID. Requires: id.",
InputSchema: ToolSchema{
Type: "object",
Properties: map[string]Property{
- "action": {Type: "string", Description: "Operation", Enum: []string{"get", "create", "list", "delete", "rename", "move", "duplicate", "search_docs"}},
+ "action": {Type: "string", Description: "Operation", Enum: []string{"get", "create", "list", "delete", "rename", "move", "duplicate", "search_docs", "info"}},
"id": {Type: "string", Description: "Document block ID"},
"title": {Type: "string", Description: "Document title (for create, rename)"},
"path": {Type: "string", Description: "Document hPath, the human-readable path shown in the document tree (e.g. /folder/doc). Used for create, list, move."},
@@ -67,9 +67,11 @@ func documentHandler(args map[string]interface{}) (CallToolResult, error) {
return documentDuplicate(args)
case "search_docs":
return documentSearchDocs(args)
+ case "info":
+ return documentInfo(args)
}
return CallToolResult{
- Content: []ContentItem{{Type: "text", Text: "unknown action '" + action + "', expected one of: [get, create, list, delete, rename, move, duplicate, search_docs]"}},
+ Content: []ContentItem{{Type: "text", Text: "unknown action '" + action + "', expected one of: [get, create, list, delete, rename, move, duplicate, search_docs, info]"}},
IsError: true,
}, nil
}
@@ -272,3 +274,20 @@ func documentSearchDocs(args map[string]interface{}) (CallToolResult, error) {
}
return CallToolResult{Content: []ContentItem{{Type: "text", Text: sb.String()}}}, nil
}
+
+func documentInfo(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
+ }
+
+ info, err := model.GetDocInfo(id)
+ if err != nil {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: fmt.Sprintf("get doc info failed: %s", err)}}, IsError: true}, nil
+ }
+
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: fmt.Sprintf(
+ "ID: %s\nRootID: %s\nName: %s\nRefCount: %d\nSubFileCount: %d",
+ info.ID, info.RootID, info.Name, info.RefCount, info.SubFileCount,
+ )}}}, nil
+}
diff --git a/kernel/mcp/tools/file.go b/kernel/mcp/tools/file.go
index 05f8251c14..a15cd491ed 100644
--- a/kernel/mcp/tools/file.go
+++ b/kernel/mcp/tools/file.go
@@ -44,6 +44,7 @@ var FileTool = &Tool{
"dst": {Type: "string", Description: "Destination path (for copy)"},
"pattern": {Type: "string", Description: "Regex pattern to search for (for grep)"},
"include": {Type: "string", Description: "File glob pattern to filter files (for grep, e.g. \"*.go\", \"*.{ts,tsx}\")"},
+ "context": {Type: "number", Description: "Number of context lines before and after each match (for grep, default 0)"},
},
Required: []string{"action"},
},
@@ -329,20 +330,25 @@ func fileGrep(args map[string]interface{}) (CallToolResult, error) {
}
include, _ := args["include"].(string)
+ ctx := int(getFloat64Arg(args, "context"))
- results, err := gulu.File.Grep(abs, include, pattern, 0)
+ results, err := gulu.File.Grep(abs, include, pattern, ctx, 0)
if err != nil {
return CallToolResult{Content: []ContentItem{{Type: "text", Text: "grep failed: " + err.Error()}}, IsError: true}, nil
}
var sb strings.Builder
- sb.WriteString(fmt.Sprintf("Found %d matches:\n\n", len(results)))
+ sb.WriteString(fmt.Sprintf("Found %d lines:\n\n", len(results)))
for _, r := range results {
rel, relErr := filepath.Rel(util.WorkspaceDir, r.File)
if relErr != nil {
rel = r.File
}
- sb.WriteString(fmt.Sprintf("%s:%d: %s\n", rel, r.Line, r.Text))
+ sep := ":"
+ if r.Context {
+ sep = "-:"
+ }
+ sb.WriteString(fmt.Sprintf("%s:%d%s %s\n", rel, r.Line, sep, r.Text))
}
return CallToolResult{Content: []ContentItem{{Type: "text", Text: sb.String()}}}, nil
diff --git a/kernel/mcp/tools/ref.go b/kernel/mcp/tools/ref.go
index 5148435e30..5ee2090d16 100644
--- a/kernel/mcp/tools/ref.go
+++ b/kernel/mcp/tools/ref.go
@@ -25,13 +25,14 @@ import (
var RefTool = &Tool{
Name: "ref",
- Description: "Reference and backlink operations for SiYuan.\n- backlinks: Get backlinks for a block/document. Requires: id. Optional: keyword.\n- mentions: Get mentions of a block/document. Requires: id. Optional: keyword.\n- refresh: Refresh backlink index for a block/document. Requires: id.",
+ Description: "Reference and backlink operations for SiYuan.\n- backlinks: Get backlinks for a block/document. Requires: id. Optional: keyword, sort.\n- mentions: Get mentions of a block/document. Requires: id. Optional: keyword, sort.\n- refresh: Refresh backlink index for a block/document. Requires: id.",
InputSchema: ToolSchema{
Type: "object",
Properties: map[string]Property{
"action": {Type: "string", Description: "Operation", Enum: []string{"backlinks", "mentions", "refresh"}},
"id": {Type: "string", Description: "Block ID"},
"keyword": {Type: "string", Description: "Filter by keyword"},
+ "sort": {Type: "number", Description: "Sort mode for backlinks and mentions: 0=updated-desc 1=updated-asc 2=created-desc 3=created-asc 4=name-desc 5=name-asc 6=alphanum-desc 7=alphanum-asc (default 0)"},
},
Required: []string{"action", "id"},
},
@@ -61,8 +62,12 @@ func refHandler(args map[string]interface{}) (CallToolResult, error) {
func refBacklinks(args map[string]interface{}) (CallToolResult, error) {
id, _ := args["id"].(string)
keyword, _ := args["keyword"].(string)
+ sortMode := 0
+ if v, ok := args["sort"].(float64); ok {
+ sortMode = int(v)
+ }
- _, backlinks, _, _, _ := model.GetBacklink2(id, keyword, "", 0, 0, model.Conf.Editor.BacklinkContainChildren)
+ _, backlinks, _, _, _ := model.GetBacklink2(id, keyword, "", sortMode, 0, model.Conf.Editor.BacklinkContainChildren)
if len(backlinks) == 0 {
return CallToolResult{Content: []ContentItem{{Type: "text", Text: "no backlinks found"}}}, nil
}
@@ -78,8 +83,12 @@ func refBacklinks(args map[string]interface{}) (CallToolResult, error) {
func refMentions(args map[string]interface{}) (CallToolResult, error) {
id, _ := args["id"].(string)
keyword, _ := args["keyword"].(string)
+ sortMode := 0
+ if v, ok := args["sort"].(float64); ok {
+ sortMode = int(v)
+ }
- _, _, mentions, _, _ := model.GetBacklink2(id, "", keyword, 0, 0, model.Conf.Editor.BacklinkContainChildren)
+ _, _, mentions, _, _ := model.GetBacklink2(id, "", keyword, 0, sortMode, model.Conf.Editor.BacklinkContainChildren)
if len(mentions) == 0 {
return CallToolResult{Content: []ContentItem{{Type: "text", Text: "no mentions found"}}}, nil
}
diff --git a/kernel/mcp/tools/search.go b/kernel/mcp/tools/search.go
index b4346d861e..799ac7784d 100644
--- a/kernel/mcp/tools/search.go
+++ b/kernel/mcp/tools/search.go
@@ -25,7 +25,7 @@ import (
var SearchTool = &Tool{
Name: "search",
- Description: "Search in SiYuan.\n- fulltext: Full-text keyword search. Required: query. Optional: page (default 1), pageSize (default 20).\n- semantic: Semantic (vector) search using AI embedding. Required: query. Optional: page (default 1), pageSize (default 20). Note: needs AI embedding configured in SiYuan settings.",
+ Description: "Search in SiYuan.\n- fulltext: Full-text keyword search. Required: query. Optional: page (default 1), pageSize (default 20), notebook, path, type, subtype, method, orderBy, groupBy.\n- semantic: Semantic (vector) search using AI embedding. Required: query. Optional: page (default 1), pageSize (default 20), notebook, path, type, subtype. Note: needs AI embedding configured in SiYuan settings.",
InputSchema: ToolSchema{
Type: "object",
Properties: map[string]Property{
@@ -33,6 +33,13 @@ var SearchTool = &Tool{
"query": {Type: "string", Description: "Search keywords"},
"page": {Type: "number", Description: "Page number (default 1)"},
"pageSize": {Type: "number", Description: "Results per page (default 20)"},
+ "notebook": {Type: "string", Description: "Comma-separated notebook IDs to filter (optional)"},
+ "path": {Type: "string", Description: "Comma-separated path prefixes to filter (optional)"},
+ "type": {Type: "string", Description: "Comma-separated block types to filter, e.g. 'document,heading,paragraph' (optional)"},
+ "subtype": {Type: "string", Description: "Comma-separated block subtypes to filter, e.g. 'o,u,t' (optional)"},
+ "method": {Type: "number", Description: "Search method (fulltext only): 0=keyword 1=query-syntax 2=sql 3=regex (default 0)"},
+ "orderBy": {Type: "number", Description: "Sort order (fulltext only): 0=type 1=created-asc 2=created-desc 3=updated-asc 4=updated-desc 5=content 6=relevance-asc 7=relevance-desc (default 0)"},
+ "groupBy": {Type: "number", Description: "Group by (fulltext only): 0=none 1=document (default 0)"},
},
Required: []string{"action", "query"},
},
@@ -74,17 +81,34 @@ func fulltextSearch(args map[string]interface{}) (CallToolResult, error) {
pageSize = 20
}
- blocks, matchedCount, _, pageCount, _ := model.FullTextSearchBlock(
- query, nil, nil, nil, nil, 0, 0, 0, page, pageSize,
+ notebooks := parseStringSlice(args["notebook"])
+ paths := parseStringSlice(args["path"])
+ types := parseStringSet(args["type"])
+ subtypes := parseStringSet(args["subtype"])
+ method := 0
+ if v, ok := args["method"].(float64); ok {
+ method = int(v)
+ }
+ orderBy := 0
+ if v, ok := args["orderBy"].(float64); ok {
+ orderBy = int(v)
+ }
+ groupBy := 0
+ if v, ok := args["groupBy"].(float64); ok {
+ groupBy = int(v)
+ }
+
+ blocks, matchedCount, matchedRootCount, pageCount, docMode := model.FullTextSearchBlock(
+ query, notebooks, paths, types, subtypes, method, orderBy, groupBy, page, pageSize,
)
+ if matchedCount == 0 {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "No results found."}}}, nil
+ }
+
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
@@ -92,7 +116,10 @@ func fulltextSearch(args map[string]interface{}) (CallToolResult, error) {
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))
+ sb.WriteString(fmt.Sprintf("- [%s] %s\n %s\n id: %s\n\n", b.HPath, b.Type, content, b.ID))
+ }
+ if docMode {
+ sb.WriteString(fmt.Sprintf("(grouped by document, %d documents matched)\n", matchedRootCount))
}
return CallToolResult{
Content: []ContentItem{{Type: "text", Text: sb.String()}},
@@ -116,8 +143,13 @@ func semanticSearch(args map[string]interface{}) (CallToolResult, error) {
pageSize = 20
}
- blocks, matchedCount, _, pageCount := model.SemanticSearchBlock(
- query, nil, nil, nil, nil, page, pageSize,
+ notebooks := parseStringSlice(args["notebook"])
+ paths := parseStringSlice(args["path"])
+ types := parseStringSet(args["type"])
+ subtypes := parseStringSet(args["subtype"])
+
+ blocks, matchedCount, matchedRootCount, pageCount := model.SemanticSearchBlock(
+ query, notebooks, paths, types, subtypes, page, pageSize,
)
if matchedCount == 0 {
@@ -127,10 +159,6 @@ func semanticSearch(args map[string]interface{}) (CallToolResult, error) {
var sb strings.Builder
sb.WriteString(fmt.Sprintf("Found %d semantic 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
@@ -138,9 +166,43 @@ func semanticSearch(args map[string]interface{}) (CallToolResult, error) {
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))
+ sb.WriteString(fmt.Sprintf("- [%s] %s\n %s\n id: %s\n\n", b.HPath, b.Type, content, b.ID))
+ }
+ if matchedRootCount > 0 {
+ sb.WriteString(fmt.Sprintf("(%d documents matched)\n", matchedRootCount))
}
return CallToolResult{
Content: []ContentItem{{Type: "text", Text: sb.String()}},
}, nil
}
+
+func parseStringSlice(v interface{}) []string {
+ s, ok := v.(string)
+ if !ok || s == "" {
+ return nil
+ }
+ parts := strings.Split(s, ",")
+ var result []string
+ for _, p := range parts {
+ p = strings.TrimSpace(p)
+ if p != "" {
+ result = append(result, p)
+ }
+ }
+ if len(result) == 0 {
+ return nil
+ }
+ return result
+}
+
+func parseStringSet(v interface{}) map[string]bool {
+ slice := parseStringSlice(v)
+ if len(slice) == 0 {
+ return nil
+ }
+ m := make(map[string]bool)
+ for _, s := range slice {
+ m[s] = true
+ }
+ return m
+}