An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:art: Support Model Context Protocol (MCP) https://github.com/siyuan-note/siyuan/issues/13795
Danielddf8857742d0
diff --git a/kernel/cli/cmd/search.go b/kernel/cli/cmd/search.goindex f469dda4b3..26927c1e86 100644--- a/kernel/cli/cmd/search.go+++ b/kernel/cli/cmd/search.go@@ -29,19 +29,14 @@ import (var searchCmd = &cobra.Command{Use: "search <query>",- Short: "Full-text search",+ Short: "Full-text search (blocks, semantic, or asset file contents with --asset)",Args: cobra.MinimumNArgs(1),RunE: func(cmd *cobra.Command, args []string) error {query := args[0]- notebooks, _ := cmd.Flags().GetStringArray("notebook")- paths, _ := cmd.Flags().GetStringArray("path")- typeFlags, _ := cmd.Flags().GetStringArray("type")- subtypeFlags, _ := cmd.Flags().GetStringArray("subtype")method, _ := cmd.Flags().GetInt("method")orderBy, _ := cmd.Flags().GetInt("order-by")page, _ := cmd.Flags().GetInt("page")pageSize, _ := cmd.Flags().GetInt("page-size")- groupBy, _ := cmd.Flags().GetInt("group-by")if page < 1 {page = 1@@ -50,6 +45,17 @@ var searchCmd = &cobra.Command{pageSize = 32}+ // --asset 切换到资源文件内容搜索模式+ if assetMode, _ := cmd.Flags().GetBool("asset"); assetMode {+ return runAssetSearch(cmd, query, method, orderBy, page, pageSize)+ }++ notebooks, _ := cmd.Flags().GetStringArray("notebook")+ paths, _ := cmd.Flags().GetStringArray("path")+ typeFlags, _ := cmd.Flags().GetStringArray("type")+ subtypeFlags, _ := cmd.Flags().GetStringArray("subtype")+ groupBy, _ := cmd.Flags().GetInt("group-by")+types := stringSliceToMap(typeFlags)subTypes := stringSliceToMap(subtypeFlags)@@ -67,11 +73,11 @@ var searchCmd = &cobra.Command{switch outputFormat {case "json":result := map[string]any{- "blocks": blocks,- "matchedBlockCount": matchedBlockCount,- "matchedRootCount": matchedRootCount,- "pageCount": pageCount,- "docMode": docMode,+ "blocks": blocks,+ "matchedBlockCount": matchedBlockCount,+ "matchedRootCount": matchedRootCount,+ "pageCount": pageCount,+ "docMode": docMode,}data, _ := json.MarshalIndent(result, "", " ")fmt.Println(string(data))@@ -82,6 +88,45 @@ var searchCmd = &cobra.Command{},}+func runAssetSearch(cmd *cobra.Command, query string, method, orderBy, page, pageSize int) error {+ extFlags, _ := cmd.Flags().GetStringArray("ext")+ types := stringSliceToMap(extFlags)++ assetContents, matchedAssetCount, pageCount := model.FullTextSearchAssetContent(query, types, method, orderBy, page, pageSize)++ switch outputFormat {+ case "json":+ result := map[string]any{+ "assetContents": assetContents,+ "matchedAssetCount": matchedAssetCount,+ "pageCount": pageCount,+ }+ data, _ := json.MarshalIndent(result, "", " ")+ fmt.Println(string(data))+ default:+ printAssetSearchResult(assetContents, matchedAssetCount, pageCount, page, pageSize)+ }+ return nil+}++func printAssetSearchResult(assetContents []*model.AssetContent, matchedAssetCount, pageCount, page, pageSize int) {+ if len(assetContents) == 0 {+ fmt.Println("No asset content results found.")+ return+ }++ w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)+ fmt.Fprintln(w, "ID\tEXT\tNAME\tSIZE\tPATH\tCONTENT")+ for _, a := range assetContents {+ content := truncate(a.Content, 60)+ fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\t%s\n", a.ID, a.Ext, a.Name, a.HSize, a.Path, content)+ }+ w.Flush()++ fmt.Printf("\nShowing results %d-%d | %d asset matches, %d pages\n",+ (page-1)*pageSize+1, (page-1)*pageSize+len(assetContents), matchedAssetCount, pageCount)+}+func printSearchResult(blocks []*model.Block, matchedBlockCount, matchedRootCount, pageCount int, docMode bool, page, pageSize, groupBy int) {if len(blocks) == 0 {fmt.Println("No results found.")@@ -129,15 +174,17 @@ func stringSliceToMap(s []string) map[string]bool {}func init() {+ searchCmd.Flags().Bool("asset", false, "search asset file contents (PDF/Word/Excel/txt etc.) instead of blocks")+ searchCmd.Flags().StringArray("ext", nil, "asset file extension filter, repeatable, e.g. --ext pdf --ext docx (asset mode only)")searchCmd.Flags().StringArrayP("notebook", "n", nil, "notebook ID filter (repeatable)")searchCmd.Flags().StringArray("path", nil, "path prefix filter (repeatable)")searchCmd.Flags().StringArrayP("type", "t", nil, "block type filter, repeatable (document heading paragraph list listItem codeBlock mathBlock table blockquote superBlock htmlBlock embedBlock databaseBlock audioBlock videoBlock iframeBlock widgetBlock callout)")searchCmd.Flags().StringArray("subtype", nil, "block subtype filter, repeatable (o u t)")- searchCmd.Flags().IntP("method", "m", 0, "search method: 0=keyword 1=query-syntax 2=sql 3=regex 4=semantic")- searchCmd.Flags().IntP("order-by", "o", 0, "order: 0=type 1=created-asc 2=created-desc 3=updated-asc 4=updated-desc 5=content 6=relevance-asc 7=relevance-desc")+ searchCmd.Flags().IntP("method", "m", 0, "search method: 0=keyword 1=query-syntax 2=sql 3=regex 4=semantic (asset mode ignores 4=semantic; uses 0-3 with same meanings)")+ searchCmd.Flags().IntP("order-by", "o", 0, "order — blocks: 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")searchCmd.Flags().IntP("page", "p", 1, "page number")searchCmd.Flags().IntP("page-size", "s", 32, "results per page")- searchCmd.Flags().IntP("group-by", "g", 0, "group by: 0=none 1=document")+ searchCmd.Flags().IntP("group-by", "g", 0, "group by: 0=none 1=document (blocks mode only)")rootCmd.AddCommand(searchCmd)}diff --git a/kernel/mcp/tools/search.go b/kernel/mcp/tools/search.goindex f72d91d165..ffd1935543 100644--- a/kernel/mcp/tools/search.go+++ b/kernel/mcp/tools/search.go@@ -25,20 +25,21 @@ import (var SearchTool = &Tool{Name: "search",- Description: "Search. Actions: fulltext(query, page=1, pageSize=20, notebook?, path?, type?, subtype?, method?, orderBy?, groupBy?), semantic(query, page=1, pageSize=20, notebook?, path?, type?, subtype?) — semantic needs AI embedding configured.",+ Description: "Search. Actions: fulltext(query, page=1, pageSize=20, notebook?, path?, type?, subtype?, method?, orderBy?, groupBy?), semantic(query, page=1, pageSize=20, notebook?, path?, type?, subtype?) — semantic needs AI embedding configured; asset(query, page=1, pageSize=32, ext?, method?, orderBy?) — full-text search inside asset file contents (PDF/Word/Excel/txt etc.), returns matched snippets with <mark> tags.",InputSchema: ToolSchema{Type: "object",Properties: map[string]Property{- "action": {Type: "string", Description: "Operation: fulltext or semantic", Enum: []string{"fulltext", "semantic"}},+ "action": {Type: "string", Description: "Operation: fulltext, semantic, or asset", Enum: []string{"fulltext", "semantic", "asset"}},"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)"},+ "pageSize": {Type: "number", Description: "Results per page (default 20 for fulltext/semantic, 32 for asset)"},+ "notebook": {Type: "string", Description: "Comma-separated notebook IDs to filter (optional, fulltext/semantic only)"},+ "path": {Type: "string", Description: "Comma-separated path prefixes to filter (optional, fulltext/semantic only)"},+ "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. 'o,u,t' (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)"},+ "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)"},},Required: []string{"action", "query"},@@ -57,9 +58,11 @@ func searchHandler(args map[string]interface{}) (CallToolResult, error) {return fulltextSearch(args)case "semantic":return semanticSearch(args)+ case "asset":+ return assetSearch(args)}return CallToolResult{- Content: []ContentItem{{Type: "text", Text: "unknown action '" + action + "', expected one of: [fulltext, semantic]"}},+ Content: []ContentItem{{Type: "text", Text: "unknown action '" + action + "', expected one of: [fulltext, semantic, asset]"}},IsError: true,}, nil}@@ -176,6 +179,63 @@ func semanticSearch(args map[string]interface{}) (CallToolResult, error) {}, nil}+func assetSearch(args map[string]interface{}) (CallToolResult, error) {+ query, _ := args["query"].(string)+ page := 1+ if v, ok := args["page"].(float64); ok {+ page = int(v)+ }+ pageSize := 32+ if v, ok := args["pageSize"].(float64); ok {+ pageSize = int(v)+ }+ if page < 1 {+ page = 1+ }+ if pageSize < 1 {+ pageSize = 32+ }++ // ext 入参为逗号分隔的扩展名白名单,底层按 map[string]bool 接收+ extSlice := parseStringSlice(args["ext"])+ types := map[string]bool{}+ for _, e := range extSlice {+ types[e] = true+ }++ method := 0+ if v, ok := args["method"].(float64); ok {+ method = int(v)+ }+ orderBy := 0+ if v, ok := args["orderBy"].(float64); ok {+ orderBy = int(v)+ }++ assetContents, matchedAssetCount, pageCount := model.FullTextSearchAssetContent(query, types, method, orderBy, page, pageSize)++ if matchedAssetCount == 0 {+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "No asset content results found."}}}, nil+ }++ var sb strings.Builder+ sb.WriteString(fmt.Sprintf("Found %d asset matches (page %d/%d):\n\n", matchedAssetCount, page, pageCount))+ for _, a := range assetContents {+ content := a.Content+ if len(content) > 200 {+ content = content[:200] + "..."+ }+ sb.WriteString(fmt.Sprintf("- [%s] %s\n", a.Ext, a.Name))+ sb.WriteString(fmt.Sprintf(" path: %s\n", a.Path))+ sb.WriteString(fmt.Sprintf(" size: %s\n", a.HSize))+ sb.WriteString(fmt.Sprintf(" content: %s\n", content))+ sb.WriteString(fmt.Sprintf(" id: %s\n\n", a.ID))+ }+ return CallToolResult{+ Content: []ContentItem{{Type: "text", Text: sb.String()}},+ }, nil+}+func parseStringSlice(v interface{}) []string {s, ok := v.(string)if !ok || s == "" {diff --git a/kernel/model/asset_content.go b/kernel/model/asset_content.goindex fb08bcc6c1..73df47e402 100644--- a/kernel/model/asset_content.go+++ b/kernel/model/asset_content.go@@ -195,7 +195,7 @@ func searchAssetContentBySQL(stmt string, page, pageSize int) (ret []*AssetContestmt = strings.ReplaceAll(stmt, "select * ", "select COUNT(path) AS `assets` ")stmt = removeLimitClause(stmt)result, _ := sql.QueryAssetContentNoLimit(stmt)- if 1 > len(ret) {+ if 1 > len(result) {return}