Skip to content

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

:bug: Return SQL rows from MCP search SQL mode https://github.com/siyuan-note/siyuan/issues/19528

Daniel6d3ee5f02e30
diff --git a/kernel/mcp/tools/search.go b/kernel/mcp/tools/search.go
index a8d1e0bf3b..1b7d627273 100644
--- a/kernel/mcp/tools/search.go
+++ b/kernel/mcp/tools/search.go
@@ -38,7 +38,7 @@ var SearchTool = &Tool{
"type": {Type: "string", Description: "Comma-separated block types to filter, e.g. 'document,heading,paragraph' (optional, fulltext/semantic only)"},
"subtype": {Type: "string", Description: "Comma-separated block subtypes to filter, e.g. 'h1,list:o,listItem:t' (heading: h1-h6; list/listItem: o=ordered, u=unordered, t=task) (optional, fulltext/semantic only)"},
"ext": {Type: "string", Description: "Comma-separated asset file extensions to filter, e.g. 'pdf,docx,xlsx' (optional, asset only)"},
- "method": {Type: "number", Description: "Search method: fulltext/asset 0=keyword 1=query-syntax 2=sql 3=regex (default 0)"},
+ "method": {Type: "number", Description: "Search method: fulltext/asset 0=keyword 1=query-syntax 2=sql 3=regex (default 0). fulltext method=2 delegates query to the sql tool and returns SQL rows, with the same read-only checks and default 100-row limit. Use SQL LIMIT/OFFSET for pagination; page, pageSize, path, type, subtype, orderBy and groupBy are ignored. notebook only selects an encrypted notebook database (exactly one notebook required when encrypted); filter ordinary notebooks in SQL"},
"orderBy": {Type: "number", Description: "Sort order — fulltext: 0=type 1=created-asc 2=created-desc 3=updated-asc 4=updated-desc 5=content 6=relevance-asc 7=relevance-desc; asset: 0=relevance-desc 1=relevance-asc 2=updated-asc 3=updated-desc (default 0)"},
"groupBy": {Type: "number", Description: "Group by (fulltext only): 0=none 1=document (default 0)"},
},
@@ -129,6 +129,12 @@ func fulltextSearch(args map[string]any) (CallToolResult, error) {
IsError: true,
}, nil
}
+ }
+ if method == 2 {
+ // SQL 模式复用通用行查询,笔记本读锁覆盖校验和查询过程。
+ return sqlQuery(map[string]any{"stmt": query, "notebook": encryptedNotebook})
+ }
+ if encryptedNotebook != "" {
blocks, matchedCount, matchedRootCount, pageCount, docMode = model.FullTextSearchBlockInBox(
query, notebooks, paths, types, subtypes, method, orderBy, groupBy, page, pageSize, encryptedNotebook,
)
diff --git a/kernel/mcp/tools/search_sql_fts5_test.go b/kernel/mcp/tools/search_sql_fts5_test.go
new file mode 100644
index 0000000000..fb8a2c9b46
--- /dev/null
+++ b/kernel/mcp/tools/search_sql_fts5_test.go
@@ -0,0 +1,88 @@
+//go:build fts5
+
+package tools
+
+import (
+ "os"
+ "os/exec"
+ "path/filepath"
+ "reflect"
+ "strings"
+ "testing"
+
+ "github.com/siyuan-note/siyuan/kernel/sql"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func TestSearchSQLQueries(t *testing.T) {
+ // 子进程隔离数据库连接和全局路径,所有数据写入临时目录。
+ const childEnv = "SIYUAN_TEST_MCP_SEARCH_SQL"
+ if os.Getenv(childEnv) != "1" {
+ cmd := exec.Command(os.Args[0], "-test.run=^TestSearchSQLQueries$", "-test.v")
+ cmd.Env = append(os.Environ(), childEnv+"=1")
+ if output, err := cmd.CombinedOutput(); err != nil {
+ t.Fatalf("search SQL subprocess failed: %v\n%s", err, output)
+ }
+ return
+ }
+ util.TempDir = t.TempDir()
+ util.DataDir = t.TempDir()
+ util.QueueDir = filepath.Join(util.TempDir, "queue")
+ util.DBPath = filepath.Join(util.TempDir, "siyuan.db")
+ util.BlockTreeDBPath = filepath.Join(util.TempDir, "blocktree.db")
+ util.HistoryDBPath = filepath.Join(util.TempDir, "history.db")
+ util.AssetContentDBPath = filepath.Join(util.TempDir, "asset_content.db")
+ sql.InitDatabase(true)
+ sql.InitHistoryDatabase(true)
+ sql.InitAssetContentDatabase(true)
+ t.Cleanup(sql.CloseDatabase)
+ if err := sql.Exec("INSERT INTO blocks (id, type, hpath) VALUES ('row-1', 'p', '/中文ABC'), ('row-2', 'h', '/Other'), ('row-3', 'd', '/Third')"); err != nil {
+ t.Fatal(err)
+ }
+ for _, tc := range []struct {
+ name, stmt, want string
+ isError bool
+ }{
+ {"projection", "SELECT id, type FROM blocks ORDER BY id LIMIT 3", "| row-1 | p |", false},
+ {"all columns", "SELECT * FROM blocks LIMIT 3", "row-1", false},
+ {"aggregate", "SELECT count(*) AS total FROM blocks", "| 3 |", false},
+ {"literal", "SELECT id FROM blocks WHERE hpath = '/中文ABC'", "| row-1 |", false},
+ {"offset", "SELECT id FROM blocks ORDER BY id LIMIT 1 OFFSET 1", "| row-2 |", false},
+ {"default limit", "WITH RECURSIVE numbers(n) AS (SELECT 1 UNION ALL SELECT n+1 FROM numbers WHERE n<101) SELECT n FROM numbers", "Query results (100 rows;", false},
+ {"empty", "SELECT id FROM blocks WHERE 0", "no results", false},
+ {"invalid", "SELECT missing FROM blocks", "readonly SQL required:", true},
+ {"write", "DELETE FROM blocks", "readonly SQL required:", true},
+ {"multiple", "SELECT id FROM blocks; DELETE FROM blocks", "invalid SQL:", true},
+ {"missing", "", "stmt is required", true},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ args := map[string]any{"action": "fulltext", "method": float64(2), "query": tc.stmt,
+ "page": float64(9), "pageSize": float64(1), "type": "heading", "path": "/ignored", "groupBy": float64(1)}
+ got, err := searchHandler(args)
+ if err != nil {
+ t.Fatal(err)
+ }
+ want, err := sqlHandler(map[string]any{"action": "query", "stmt": tc.stmt})
+ if err != nil || !reflect.DeepEqual(got, want) {
+ t.Fatalf("search and SQL differ: search=%+v SQL=%+v err=%v", got, want, err)
+ }
+ if got.IsError != tc.isError || len(got.Content) != 1 || !strings.Contains(got.Content[0].Text, tc.want) {
+ t.Fatalf("unexpected result: %+v", got)
+ }
+ })
+ }
+ const boxID = "20260915000000-mcpsql1"
+ boxDir := filepath.Join(util.DataDir, boxID, ".siyuan")
+ if err := os.MkdirAll(boxDir, 0755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(boxDir, "conf.json"), []byte(`{"encrypted":true}`), 0644); err != nil {
+ t.Fatal(err)
+ }
+ for _, notebooks := range []string{boxID, boxID + ",20260915000000-normal1"} {
+ got, err := searchHandler(map[string]any{"action": "fulltext", "method": float64(2), "query": "SELECT id FROM blocks", "notebook": notebooks})
+ if err != nil || !got.IsError || len(got.Content) != 1 || !strings.Contains(got.Content[0].Text, "encrypted") {
+ t.Fatalf("encrypted search was not rejected: %+v, %v", got, err)
+ }
+ }
+}