An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Address MCP document targets by parent identity https://github.com/siyuan-note/siyuan/issues/20840
Danield86195e1fa3e
diff --git a/docs/DOCUMENT-ADDRESSING.md b/docs/DOCUMENT-ADDRESSING.mdindex 1d767b7aba..1f5843e0e6 100644--- a/docs/DOCUMENT-ADDRESSING.md+++ b/docs/DOCUMENT-ADDRESSING.md@@ -212,6 +212,7 @@ Configuration-derived previews retain the source notebook, workflow purpose, eff| Shorthands | Distinguish appending to an explicit target from creating a new target; clear the source only after destination persistence succeeds || New database items | Preserve attribute values, bindings, and sorting; retain the final document ID in the creation plan || Template document trees | Preserve previews, ID remapping, insertion order, and grouped undo and redo; validate path, name, and configuration conditions on commit and expose partial completion |+| MCP and built-in Agent | `document.create/list/move` and `inbox.convert` use notebook + `parentID`; an empty string explicitly selects root, and creation accepts an independent literal title. Mode `2` rejects legacy `path=hPath` before lookup; tools and Agent instructions share this contract || Desktop, browser, and mobile | Inspect menus, shortcuts, dialogs, and handlers separately; shared utility migration does not replace platform verification |Daily-note reuse is an explicit existing business rule. The generic resolver's ambiguity policy must not turn every multiple-date match into an error; template-target preference compares structured identity chains instead.@@ -518,6 +519,7 @@ CI runs `go test -tags "fts5 sqlcipher" ./documentaddressing ./filesys ./model .| Creation entry points and save path parsing | [`util/newFile.ts`](../app/src/util/newFile.ts), [`util/configuredDocument.ts`](../app/src/util/configuredDocument.ts), [`mobile/util/initFramework.ts`](../app/src/mobile/util/initFramework.ts) || Templates, new database items, and shorthands | [`model/template_doc_tree.go`](../kernel/model/template_doc_tree.go), [`model/attribute_view_new_item.go`](../kernel/model/attribute_view_new_item.go), [`model/shortcuts.go`](../kernel/model/shortcuts.go) || Daily-note reuse and legacy creation regressions | [`model/daily_note.go`](../kernel/model/daily_note.go), [`model/file_test.go`](../kernel/model/file_test.go) |+| MCP and built-in Agent document targets | [`mcp/tools/document.go`](../kernel/mcp/tools/document.go), [`mcp/tools/inbox.go`](../kernel/mcp/tools/inbox.go), [`agent/agent.go`](../kernel/agent/agent.go) || Import and export | [`model/import.go`](../kernel/model/import.go), [`model/import_obsidian.go`](../kernel/model/import_obsidian.go), [`model/export.go`](../kernel/model/export.go) || Reusable rich-source validation pattern | [`treenode/table_cell_rich.go`](../kernel/treenode/table_cell_rich.go) || Heading/document conversion | [`model/heading.go`](../kernel/model/heading.go), [`model/heading_doc_test.go`](../kernel/model/heading_doc_test.go) |diff --git a/docs/DOCUMENT-ADDRESSING.zh-CN.md b/docs/DOCUMENT-ADDRESSING.zh-CN.mdindex 1af218d050..115cf1c130 100644--- a/docs/DOCUMENT-ADDRESSING.zh-CN.md+++ b/docs/DOCUMENT-ADDRESSING.zh-CN.md@@ -212,6 +212,7 @@| 速记 | 明确追加目标或新建目标;目标持久化成功后才清理来源 || 数据库新建条目 | 保留属性值、绑定关系和排序;创建计划保存最终文档 ID || 模板文档树 | 保留预览、ID 重映射、插入顺序及整组撤销和重做;提交校验路径、名称与配置条件并展示部分完成结果 |+| MCP 与内置 Agent | `document.create/list/move` 和 `inbox.convert` 使用笔记本及 `parentID`;空字符串显式表示根位置,创建接受独立的标题原文。模式 `2` 在查询前拒绝旧 `path=hPath`,工具与 Agent 提示词保持相同契约 || 桌面、浏览器和移动端 | 分别检查菜单、快捷键、对话框及事件处理;共享工具函数迁移不能代替各端验证 |日记的既有复用策略是明确的业务规则,不因通用解析器拒绝歧义而改成所有同日期情况均报错;模板目标优先匹配改为结构化身份链比较。@@ -518,6 +519,7 @@| 新建入口与保存路径解析 | [`util/newFile.ts`](../app/src/util/newFile.ts)、[`util/configuredDocument.ts`](../app/src/util/configuredDocument.ts)、[`mobile/util/initFramework.ts`](../app/src/mobile/util/initFramework.ts) || 模板、数据库新建及速记 | [`model/template_doc_tree.go`](../kernel/model/template_doc_tree.go)、[`model/attribute_view_new_item.go`](../kernel/model/attribute_view_new_item.go)、[`model/shortcuts.go`](../kernel/model/shortcuts.go) || 日记复用及旧创建回归 | [`model/daily_note.go`](../kernel/model/daily_note.go)、[`model/file_test.go`](../kernel/model/file_test.go) |+| MCP 与内置 Agent 文档目标 | [`mcp/tools/document.go`](../kernel/mcp/tools/document.go)、[`mcp/tools/inbox.go`](../kernel/mcp/tools/inbox.go)、[`agent/agent.go`](../kernel/agent/agent.go) || 导入与导出 | [`model/import.go`](../kernel/model/import.go)、[`model/import_obsidian.go`](../kernel/model/import_obsidian.go)、[`model/export.go`](../kernel/model/export.go) || 可复用的富文本来源校验模式 | [`treenode/table_cell_rich.go`](../kernel/treenode/table_cell_rich.go) || 标题块与文档转换 | [`model/heading.go`](../kernel/model/heading.go)、[`model/heading_doc_test.go`](../kernel/model/heading_doc_test.go) |diff --git a/kernel/agent/agent.go b/kernel/agent/agent.goindex fc71ff64aa..b54c62a280 100644--- a/kernel/agent/agent.go+++ b/kernel/agent/agent.go@@ -54,16 +54,16 @@ const systemPrompt = `You are a SiYuan AI assistant. You help users manage their- Heading hierarchy: headings (h1-h6) are leaf blocks. Blocks that appear "under" a heading in the UI are its *following siblings* in the AST, not its children.- Native structured blocks: use native capabilities and preserve existing structure, block IDs, and metadata unless the user explicitly requests a conversion. Follow the relevant tool descriptions for block-specific syntax and operations.- Notebook: a top-level container holding documents. Use notebook.list to enumerate; pass notebook ID when creating documents.-- hPath (human-readable path): the title-based path shown in the document tree, e.g. "/Diary/2024/June". The "path" parameter in document.create/move/list refers to hPath, not the internal ID-based filesystem path. A rename changes hPath but not the ID.-- Document vs block move: document.move relocates an entire document (and children) to a new hPath within a notebook — needs id, notebook (from document.get field "Box"), and path. block.move repositions a single content block under a new parent block.+- hPath (human-readable path): display text only. A literal title can contain "/", so identical hPaths can refer to different document hierarchies. Never split an hPath or use it to recover identity. Document create/list/move and inbox.convert use notebook + parentID; parentID="" explicitly selects the notebook root. Legacy path=hPath is only available in compatibility-mode notebooks and returns legacyPathUnsupported in structured-title notebooks. Obtain document IDs from document.list/search_docs/get; a rename changes display text but not ID.+- Document vs block move: document.move relocates an entire document (and children) — needs id, notebook (from document.get field "Box"), and target parentID. block.move repositions a single content block under a new parent block.- Dailynote (daily note/diary/journal): a special document on the notebook's daily-note save path. For diary/daily note/journal requests, use dailynote.create (not document.create) to open today's note, then dailynote.append/prepend to add content.## Tool Usage Patterns- Find: search.fulltext (keyword) → block.get (by ID). For semantic search use search.semantic.- Structural search: for block types, inline formats, ancestry or statistics, first fetch sql.schema, then use sql.query. To show matching blocks in the frontend, use native/frontend/open_search(query, method=2) with SELECT b.* FROM blocks b; use projections and aggregates only with sql.query.- Dynamic SQL in documents: reuse a complete-block query in a native {{SQL}} embed via block.insert/append/prepend. For single-line embeds, read block.get_kramdown, preserve ID and IAL, and update that block with lockType=true. For multiline SQL or -- comments, read block.dom and write dataType=dom with preserved metadata. Consult sql.schema for the workflow; never replace a dynamic embed with static results unless requested.-- Explore structure: document.list (children under an hPath) → document.get → block.get_children → block.get. Use block breadcrumb to trace a block's location.-- Create content: document.create (notebook + hPath) → block.append/prepend/insert.+- Explore structure: document.list (notebook + parentID, omitted parentID lists the notebook root) → document.get → block.get_children → block.get. Use block breadcrumb to trace a block's location.+- Create content: document.create (notebook + parentID + independent literal title) → block.append/prepend/insert. Title slashes are text, never implicit parent segments.- Modify: block.update replaces ONE block's content — it does NOT create or append new blocks. To both modify and add, call block.update first, then block.append/prepend/insert as separate calls.- Organize: document.move (full document), document.rename (title), block.move (single content block), document.delete.- Inbox (cloud-synced clippings, messages, and audio/video/file attachments; requires subscription): inbox.list (paged, summaries only) → inbox.get (read full content to judge how to file it) → inbox.convert (move one or many into local documents under a notebook, auto-deleting the cloud originals on success). Failed conversions are left in the inbox for retry. If a request fails with an auth/subscription error, report it honestly — do not retry.diff --git a/kernel/mcp/tools/document.go b/kernel/mcp/tools/document.goindex 0c763974f5..c148ecba0d 100644--- a/kernel/mcp/tools/document.go+++ b/kernel/mcp/tools/document.go@@ -17,11 +17,13 @@package toolsimport (+ "errors""fmt""path""strings""github.com/88250/lute/ast"+ "github.com/siyuan-note/siyuan/kernel/documentaddressing""github.com/siyuan-note/siyuan/kernel/model""github.com/siyuan-note/siyuan/kernel/treenode""github.com/siyuan-note/siyuan/kernel/util"@@ -29,14 +31,15 @@ import (var DocumentTool = &Tool{Name: "document",- Description: "Document operations. Actions: get(id), create(notebook, path=hPath, title, markdown?), list(notebook, path=hPath default /), delete(id), rename(id, title), move(id, notebook, path=target hPath), duplicate(id), search_docs(keyword), info(id).",+ Description: "Document operations. Actions: get(id), create(notebook, parentID, title, markdown?), list(notebook, parentID=notebook root by default), delete(id), rename(id, title), move(id, notebook, parentID), duplicate(id), search_docs(keyword), info(id). Use parentID=\"\" for the notebook root. Titles are independent literal text. The legacy path=hPath parameter works only in compatibility-mode notebooks; never derive identity or hierarchy from a display hPath.",InputSchema: ToolSchema{Type: "object",Properties: map[string]Property{"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."},+ "parentID": {Type: "string", Description: "Target parent document ID (for create, list, move); an empty string explicitly selects the notebook root. Do not combine with path. Obtain IDs from list, search_docs or get."},+ "path": {Type: "string", Description: "Legacy hPath for compatibility-mode notebooks only (for create, list, move). Structured-title notebooks reject this parameter with legacyPathUnsupported; use parentID instead."},"markdown": {Type: "string", Description: "Initial markdown content (for create).\n\n" + markdownContentSyntax},"keyword": {Type: "string", Description: "Search keyword (for search_docs)"},"notebook": {Type: "string", Description: "Notebook ID (required for create, list, move)"},@@ -105,12 +108,24 @@ func documentCreate(args map[string]any) (CallToolResult, error) {if notebook == "" {return CallToolResult{Content: []ContentItem{{Type: "text", Text: "notebook is required"}}, IsError: true}, nil}- hPath, _ := args["path"].(string)- if hPath == "" {- return CallToolResult{Content: []ContentItem{{Type: "text", Text: "path is required"}}, IsError: true}, nil+ target, err := resolveDocumentTarget(notebook, args, true, false)+ if err != nil {+ return documentTargetFailure(err), nil}markdown, _ := args["markdown"].(string)title, _ := args["title"].(string)+ if target.structured {+ if _, ok := args["title"].(string); !ok {+ return documentTargetFailure(errors.New("title is required with parentID")), nil+ }+ doc, err := model.CreateDocByParent(model.DocumentCreateRequest{Notebook: notebook, ParentID: target.id,+ ID: ast.NewNodeID(), TitleFormat: "plain", Title: title, Markdown: markdown})+ if err != nil {+ return documentTargetFailure(fmt.Errorf("create doc failed: %w", err)), nil+ }+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: fmt.Sprintf("document created: %s (hPath: %s)", doc.ID, doc.DisplayPath)}}}, nil+ }+ hPath, _ := args["path"].(string)if title == "" {title = hPathif strings.Contains(title, "/") {@@ -119,18 +134,8 @@ func documentCreate(args map[string]any) (CallToolResult, error) {}}- parentPath := "/"- parentDir := parentDir(hPath)- if parentDir != "/" {- bt := treenode.GetBlockTreeRootByHPath(notebook, parentDir)- if bt == nil {- return CallToolResult{Content: []ContentItem{{Type: "text", Text: "parent path not found: " + parentDir}}, IsError: true}, nil- }- parentPath = strings.TrimSuffix(bt.Path, ".sy")- }-id := ast.NewNodeID()- docPath := strings.TrimRight(parentPath, "/") + "/" + id + ".sy"+ docPath := strings.TrimSuffix(strings.TrimRight(target.path, "/"), ".sy") + "/" + id + ".sy"tree, err := model.CreateDocByMd(notebook, docPath, title, markdown, nil, nil)if err != nil {return CallToolResult{Content: []ContentItem{{Type: "text", Text: fmt.Sprintf("create doc failed: %s", err)}}, IsError: true}, nil@@ -139,6 +144,71 @@ func documentCreate(args map[string]any) (CallToolResult, error) {return CallToolResult{Content: []ContentItem{{Type: "text", Text: fmt.Sprintf("document created: %s (hPath: %s)", tree.Root.ID, hPath)}}}, nil}+type documentTarget struct {+ id *string+ path string+ hPath string+ structured bool+}++func documentTargetFailure(err error) CallToolResult {+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: err.Error()}}, IsError: true}+}++// resolveDocumentTarget 在任何旧 hPath 查询前检查整本模式,父身份只通过结构化模型解析。+func resolveDocumentTarget(notebook string, args map[string]any, create, defaultRoot bool) (*documentTarget, error) {+ parent, hasParent := args["parentID"]+ legacy, hasPath := args["path"]+ if hasParent && hasPath {+ return nil, errors.New("parentID and path cannot be combined")+ }+ if text, ok := legacy.(string); ok && text == "" && defaultRoot {+ hasPath = false+ }+ if hasParent || !hasPath && defaultRoot {+ parentID, ok := parent.(string)+ if hasParent && !ok {+ return nil, errors.New("parentID must be a string; use an empty string for the notebook root")+ }+ kind := "root"+ var id *string+ if parentID != "" {+ kind, id = "document", &parentID+ }+ resolved, err := model.ResolveDocPath(notebook, kind, id, nil)+ if err != nil {+ return nil, err+ }+ target := &documentTarget{path: "/", hPath: "/", structured: true}+ if resolved.Resolved != nil {+ target.id, target.path, target.hPath = &resolved.Resolved.ID, resolved.Resolved.Path, resolved.Resolved.DisplayPath+ }+ return target, nil+ }+ hPath, ok := legacy.(string)+ if !hasPath || !ok || hPath == "" {+ return nil, errors.New("parentID or path is required")+ }+ if err := model.CheckLegacyDocumentPath(notebook); err != nil {+ if errors.Is(err, documentaddressing.ErrLegacyPathUnsupported) {+ return nil, fmt.Errorf("legacyPathUnsupported: %w; use parentID (empty string for the notebook root), or resolveDocPath/createDocByParent via the HTTP API", err)+ }+ return nil, err+ }+ if create {+ hPath = parentDir(hPath)+ }+ target := &documentTarget{path: "/", hPath: hPath}+ if hPath != "/" {+ bt := treenode.GetBlockTreeRootByHPath(notebook, hPath)+ if bt == nil {+ return nil, fmt.Errorf("target path not found: %s", hPath)+ }+ target.path, target.id = bt.Path, &bt.ID+ }+ return target, nil+}+func parentDir(p string) string {i := strings.LastIndex(p, "/")if i <= 0 {@@ -152,29 +222,20 @@ func documentList(args map[string]any) (CallToolResult, error) {if notebook == "" {return CallToolResult{Content: []ContentItem{{Type: "text", Text: "notebook is required"}}, IsError: true}, nil}- hPath, _ := args["path"].(string)- if hPath == "" {- hPath = "/"- }-- fsPath := hPath- if hPath != "/" {- bt := treenode.GetBlockTreeRootByHPath(notebook, hPath)- if bt == nil {- return CallToolResult{Content: []ContentItem{{Type: "text", Text: "target path not found: " + hPath}}, IsError: true}, nil- }- fsPath = bt.Path+ target, err := resolveDocumentTarget(notebook, args, false, true)+ if err != nil {+ return documentTargetFailure(err), nil}- files, _, err := model.ListDocTree(notebook, fsPath, 0, false, false, 128)+ files, _, err := model.ListDocTree(notebook, target.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- fmt.Fprintf(&sb, "Documents in %s (hPath: %s):\n\n", notebook, hPath)+ fmt.Fprintf(&sb, "Documents in %s (hPath: %s):\n\n", notebook, target.hPath)for _, f := range files {- fmt.Fprintf(&sb, "- %s (id: %s, hPath: %s)\n", f.Name, f.ID, strings.TrimRight(hPath, "/")+"/"+f.Name)+ fmt.Fprintf(&sb, "- %s (id: %s, hPath: %s)\n", f.Name, f.ID, strings.TrimRight(target.hPath, "/")+"/"+f.Name)}return CallToolResult{Content: []ContentItem{{Type: "text", Text: sb.String()}}}, nil}@@ -218,30 +279,23 @@ func documentRename(args map[string]any) (CallToolResult, error) {func documentMove(args map[string]any) (CallToolResult, error) {id, _ := args["id"].(string)notebook, _ := args["notebook"].(string)- hPath, _ := args["path"].(string)- if id == "" || notebook == "" || hPath == "" {- return CallToolResult{Content: []ContentItem{{Type: "text", Text: "id, notebook and path are required"}}, IsError: true}, nil+ if id == "" || notebook == "" {+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "id and notebook are required"}}, IsError: true}, nil+ }+ target, err := resolveDocumentTarget(notebook, args, false, false)+ if err != nil {+ return documentTargetFailure(err), 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}- fsPath := hPath- if hPath != "/" {- bt := treenode.GetBlockTreeRootByHPath(notebook, hPath)- if bt == nil {- return CallToolResult{Content: []ContentItem{{Type: "text", Text: "target path not found: " + hPath}}, IsError: true}, nil- }- fsPath = bt.Path- }-- if err := model.MoveDocs([]string{tree.Path}, notebook, fsPath, nil); err != nil {+ if err := model.MoveDocs([]string{tree.Path}, notebook, target.path, nil); err != nil {return CallToolResult{Content: []ContentItem{{Type: "text", Text: fmt.Sprintf("move doc failed: %s", err)}}, IsError: true}, nil}- return CallToolResult{Content: []ContentItem{{Type: "text", Text: fmt.Sprintf("document moved: %s -> %s (hPath: %s)", id, notebook, hPath)}}}, nil+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: fmt.Sprintf("document moved: %s -> %s (hPath: %s)", id, notebook, target.hPath)}}}, nil}func documentDuplicate(args map[string]any) (CallToolResult, error) {diff --git a/kernel/mcp/tools/document_addressing_fts5_test.go b/kernel/mcp/tools/document_addressing_fts5_test.gonew file mode 100644index 0000000000..f3a9410ca0--- /dev/null+++ b/kernel/mcp/tools/document_addressing_fts5_test.go@@ -0,0 +1,186 @@+//go:build fts5++package tools++import (+ "bytes"+ "os"+ "os/exec"+ "path"+ "path/filepath"+ "strings"+ "testing"++ "github.com/88250/lute/ast"+ "github.com/88250/lute/parse"+ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/filesys"+ "github.com/siyuan-note/siyuan/kernel/model"+ "github.com/siyuan-note/siyuan/kernel/sql"+ "github.com/siyuan-note/siyuan/kernel/treenode"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestDocumentStructuredAddressing(t *testing.T) {+ const childEnv = "SIYUAN_TEST_MCP_DOCUMENT_ADDRESSING"+ if os.Getenv(childEnv) != "1" {+ cmd := exec.Command(os.Args[0], "-test.run=^TestDocumentStructuredAddressing$", "-test.v")+ cmd.Env = append(os.Environ(), childEnv+"=1")+ if output, err := cmd.CombinedOutput(); err != nil {+ t.Fatalf("document addressing subprocess: %v\n%s", err, output)+ }+ return+ }+ root := t.TempDir()+ util.WorkspaceDir = root+ util.DataDir, util.TempDir = filepath.Join(root, "data"), filepath.Join(root, "temp")+ util.ConfDir, util.HistoryDir = filepath.Join(root, "conf"), filepath.Join(root, "history")+ util.QueueDir = filepath.Join(util.TempDir, "queue")+ util.DBPath, util.BlockTreeDBPath = filepath.Join(util.TempDir, "siyuan.db"), filepath.Join(util.TempDir, "blocktree.db")+ util.HistoryDBPath, util.AssetContentDBPath = filepath.Join(util.TempDir, "history.db"), filepath.Join(util.TempDir, "asset_content.db")+ for _, dir := range []string{util.DataDir, util.TempDir, util.ConfDir, util.HistoryDir, util.QueueDir} {+ if err := os.MkdirAll(dir, 0755); err != nil {+ t.Fatal(err)+ }+ }+ model.Conf = model.NewAppConf()+ model.Conf.Lang = "mcp-document-test"+ util.TimeLangs[model.Conf.Lang] = map[string]any{+ "albl": "ago", "blbl": "from now", "now": "now", "1s": "1 second %s", "xs": "%d seconds %s",+ "1m": "1 minute %s", "xm": "%d minutes %s", "1h": "1 hour %s", "xh": "%d hours %s", "1d": "1 day %s",+ "xd": "%d days %s", "1w": "1 week %s", "xw": "%d weeks %s", "1M": "1 month %s", "xM": "%d months %s",+ "1y": "1 year %s", "2y": "2 years %s", "xy": "%d years %s", "max": "a long while %s",+ }+ model.Conf.FileTree.Store(conf.NewFileTree())+ model.Conf.NotebookCrypto = conf.NewNotebookCrypto()+ model.Conf.Sync.Store(conf.NewSync())+ model.Conf.Editor.Store(conf.NewEditor())+ model.Conf.Export.Store(conf.NewExport())+ model.Conf.Search.Store(conf.NewSearch())+ sql.InitDatabase(true)+ sql.InitHistoryDatabase(true)+ sql.InitAssetContentDatabase(true)+ defer sql.CloseDatabase()+ defer treenode.CloseDatabase()+ box := &model.Box{ID: ast.NewNodeID()}+ boxConf := conf.NewBoxConf()+ boxConf.Name, boxConf.Closed = "MCP documents", false+ if err := box.SaveConf(boxConf); err != nil {+ t.Fatal(err)+ }+ if err := treenode.SetDocumentMetadataState(box.ID, "ready"); err != nil {+ t.Fatal(err)+ }+ createFixture := func(parent *parse.Tree, title string) *parse.Tree {+ id, folder, hPath := ast.NewNodeID(), "/", ""+ if parent != nil {+ folder, hPath = strings.TrimSuffix(parent.Path, ".sy"), parent.HPath+ }+ tree := treenode.NewTree(box.ID, path.Join(folder, id+".sy"), hPath+"/"+title, title)+ if err := os.MkdirAll(filepath.Dir(filepath.Join(util.DataDir, box.ID, tree.Path)), 0755); err != nil {+ t.Fatal(err)+ }+ if _, err := filesys.WriteTree(tree); err != nil {+ t.Fatal(err)+ }+ treenode.UpsertBlockTree(tree)+ sql.UpsertTreeQueue(tree)+ sql.FlushQueue()+ return tree+ }+ literal := createFixture(nil, "A/B")+ parent := createFixture(nil, "A")+ child := createFixture(parent, "B")+ source := createFixture(nil, "Move me")+ if literal.HPath != child.HPath {+ t.Fatal("fixture does not contain a display-path collision")+ }+ before, _ := os.ReadFile(filepath.Join(util.DataDir, box.ID, source.Path))+ for _, action := range []string{"create", "list", "move"} {+ for _, hPath := range []string{"/A/B", "/"} {+ args := map[string]any{"action": action, "notebook": box.ID, "path": hPath, "id": source.ID, "title": "New"}+ result, err := documentHandler(args)+ if err != nil || !result.IsError || !strings.Contains(result.Content[0].Text, "legacyPathUnsupported") {+ t.Fatalf("%s accepted a legacy path: %+v, %v", action, result, err)+ }+ }+ }+ after, _ := os.ReadFile(filepath.Join(util.DataDir, box.ID, source.Path))+ if !bytes.Equal(before, after) {+ t.Fatal("rejected move changed the source")+ }+ for _, selected := range []*parse.Tree{literal, child} {+ target, err := resolveDocumentTarget(box.ID, map[string]any{"parentID": selected.ID}, false, false)+ if err != nil || target.path != selected.Path || target.id == nil || *target.id != selected.ID {+ t.Fatalf("parent identity was resolved through its display path: %+v, %v", target, err)+ }+ }+ for _, invalid := range []map[string]any{+ {"parentID": literal.ID, "path": "/A/B"}, {"parentID": nil}, {"parentID": 1},+ {"parentID": "invalid"}, {"parentID": ast.NewNodeID()}, {"parentID": literal.Root.FirstChild.ID},+ } {+ if target, err := resolveDocumentTarget(box.ID, invalid, false, false); err == nil {+ t.Fatalf("invalid target silently selected a parent: %+v", target)+ }+ }+ result, err := documentCreate(map[string]any{"notebook": box.ID, "parentID": literal.ID, "title": "Literal/child", "markdown": "Body"})+ if err != nil || result.IsError {+ t.Fatalf("structured creation failed: %+v, %v", result, err)+ }+ created := strings.Fields(result.Content[0].Text)[2]+ docs, missing, err := model.GetDocPaths(box.ID, []string{created})+ if err != nil || len(missing) != 0 || len(docs) != 1 || docs[0].ParentID == nil || *docs[0].ParentID != literal.ID || docs[0].Title.Text != "Literal/child" {+ t.Fatalf("created in the wrong location: %+v, %v", docs, err)+ }+ listed, err := documentList(map[string]any{"notebook": box.ID, "parentID": literal.ID})+ if err != nil || listed.IsError || !strings.Contains(listed.Content[0].Text, created) {+ t.Fatalf("ID-based listing failed: %+v, %v", listed, err)+ }+ moved, err := documentMove(map[string]any{"notebook": box.ID, "parentID": child.ID, "id": source.ID})+ if err != nil || moved.IsError {+ t.Fatalf("ID-based move failed: %+v, %v", moved, err)+ }+ docs, _, err = model.GetDocPaths(box.ID, []string{source.ID})+ if err != nil || len(docs) != 1 || docs[0].ParentID == nil || *docs[0].ParentID != child.ID {+ t.Fatalf("moved to the wrong colliding parent: %+v, %v", docs, err)+ }+ rootTarget, err := resolveDocumentTarget(box.ID, map[string]any{"parentID": ""}, false, false)+ if err != nil || rootTarget.path != "/" || rootTarget.id != nil {+ t.Fatalf("explicit root target failed: %+v, %v", rootTarget, err)+ }+ defaultTarget, err := resolveDocumentTarget(box.ID, map[string]any{}, false, true)+ if err != nil || defaultTarget.path != "/" {+ t.Fatalf("default root listing failed: %+v, %v", defaultTarget, err)+ }+ if result, err = documentCreate(map[string]any{"notebook": box.ID, "parentID": ""}); err != nil || !result.IsError {+ t.Fatal("structured creation without an explicit title was accepted", result, err)+ }+ if _, err := resolveDocumentTarget(box.ID, map[string]any{"path": ""}, false, true); err != nil {+ t.Fatal("empty listing path no longer selects root", err)+ }+ foreign := &model.Box{ID: ast.NewNodeID()}+ if err := foreign.SaveConf(boxConf); err != nil {+ t.Fatal(err)+ }+ if _, err := resolveDocumentTarget(foreign.ID, map[string]any{"parentID": literal.ID}, false, false); err == nil {+ t.Fatal("parent from a different notebook was accepted")+ }+ // 缺少配置的旧模式夹具不触发自动升级,保留旧路径的父目录解释。+ legacyBox := ast.NewNodeID()+ legacyDoc := treenode.NewTree(legacyBox, "/"+ast.NewNodeID()+".sy", "/Legacy", "Legacy")+ treenode.UpsertBlockTree(legacyDoc)+ for _, create := range []bool{false, true} {+ hPath := "/Legacy"+ if create {+ hPath += "/New"+ }+ target, err := resolveDocumentTarget(legacyBox, map[string]any{"path": hPath}, create, false)+ if err != nil || target.structured || target.path != legacyDoc.Path {+ t.Fatalf("legacy path behavior changed: %+v, %v", target, err)+ }+ }+ if result, err = inboxConvert(map[string]any{"notebook": box.ID, "path": "/A/B/New", "ids": "1"}); err != nil || !result.IsError ||+ !strings.Contains(result.Content[0].Text, "legacyPathUnsupported") {+ t.Fatalf("inbox reached cloud conversion before rejecting the legacy path: %+v, %v", result, err)+ }+}diff --git a/kernel/mcp/tools/inbox.go b/kernel/mcp/tools/inbox.goindex 81139b12b5..066049f42c 100644--- a/kernel/mcp/tools/inbox.go+++ b/kernel/mcp/tools/inbox.go@@ -21,7 +21,6 @@ import ("strings""github.com/siyuan-note/siyuan/kernel/model"- "github.com/siyuan-note/siyuan/kernel/treenode""github.com/siyuan-note/siyuan/kernel/util""github.com/88250/lute/ast"@@ -31,7 +30,7 @@ import (// 收集箱数据存放在思源云端,需要订阅会员;底层复用 model 层的云端 shorthand 读写函数。var InboxTool = &Tool{Name: "inbox",- Description: "Inbox management (cloud-clipped web pages, messages, and audio/video/file attachments; requires subscription). Actions: list(page=1), get(id), convert(ids, notebook, path=/, remove_after=true) — converts one or more shorthands into local documents under the target notebook, deleting the cloud originals on success.",+ Description: "Inbox management (cloud-clipped web pages, messages, and audio/video/file attachments; requires subscription). Actions: list(page=1), get(id), convert(ids, notebook, parentID=notebook root by default, remove_after=true) — converts one or more shorthands into local documents, deleting the cloud originals on success. Use parentID=\"\" for root. Legacy path is available only in compatibility-mode notebooks.",InputSchema: ToolSchema{Type: "object",Properties: map[string]Property{@@ -40,7 +39,8 @@ var InboxTool = &Tool{"id": {Type: "string", Description: "Shorthand ID (for get)"},"ids": {Type: "string", Description: "Comma-separated shorthand IDs (for convert), e.g. \"1700000000000,1700000000001\""},"notebook": {Type: "string", Description: "Target non-encrypted notebook ID (for convert)"},- "path": {Type: "string", Description: "Target hPath in the notebook for the new documents (default \"/\", the notebook root). Parent path must already exist."},+ "parentID": DocumentTool.InputSchema.Properties["parentID"],+ "path": {Type: "string", Description: "Legacy hPath in compatibility-mode notebooks only. Its parent must already exist. Do not combine with parentID; structured-title notebooks require parentID instead."},"remove_after": {Type: "boolean", Description: "Whether to delete the cloud shorthand after a successful conversion (default true)"},},Required: []string{"action"},@@ -162,9 +162,9 @@ func inboxConvert(args map[string]any) (CallToolResult, error) {return CallToolResult{Content: []ContentItem{{Type: "text", Text: "ids is required"}}, IsError: true}, nil}- hPath, _ := args["path"].(string)- if hPath == "" {- hPath = "/"+ target, err := resolveDocumentTarget(notebook, args, true, true)+ if err != nil {+ return documentTargetFailure(err), nil}removeAfter := trueif v, ok := args["remove_after"]; ok {@@ -173,19 +173,8 @@ func inboxConvert(args map[string]any) (CallToolResult, error) {}}- // 解析目标父路径(与 document.create 保持一致的 hPath→fsPath 解析逻辑)。- parentPath := "/"- parentDir := parentDir(hPath)- if parentDir != "/" {- bt := treenode.GetBlockTreeRootByHPath(notebook, parentDir)- if bt == nil {- return CallToolResult{Content: []ContentItem{{Type: "text", Text: "parent path not found: " + parentDir}}, IsError: true}, nil- }- parentPath = strings.TrimSuffix(bt.Path, ".sy")- }-var sb strings.Builder- fmt.Fprintf(&sb, "Converting %d shorthand(s) -> notebook %s (hPath: %s):\n\n", len(ids), notebook, hPath)+ fmt.Fprintf(&sb, "Converting %d shorthand(s) -> notebook %s (hPath: %s):\n\n", len(ids), notebook, target.hPath)successIDs := make([]string, 0, len(ids))failed := 0@@ -212,15 +201,20 @@ func inboxConvert(args map[string]any) (CallToolResult, error) {}docID := ast.NewNodeID()- docPath := strings.TrimRight(parentPath, "/") + "/" + docID + ".sy"- tree, err := model.CreateDocByMdSync(notebook, docPath, title, md, nil, nil)+ if target.structured {+ _, err = model.CreateDocByParent(model.DocumentCreateRequest{Notebook: notebook, ParentID: target.id,+ ID: docID, TitleFormat: "plain", Title: title, Markdown: md})+ } else {+ docPath := strings.TrimSuffix(strings.TrimRight(target.path, "/"), ".sy") + "/" + docID + ".sy"+ _, err = model.CreateDocByMdSync(notebook, docPath, title, md, nil, nil)+ }if err != nil {fmt.Fprintf(&sb, "- [%s] %s -> FAILED: %s\n", id, title, err.Error())failed++continue}successIDs = append(successIDs, id)- fmt.Fprintf(&sb, "- [%s] %s -> created %s\n", id, title, tree.Root.ID)+ fmt.Fprintf(&sb, "- [%s] %s -> created %s\n", id, title, docID)}// 仅在全部转换成功的条目上清理云端原件;失败条目保留以便重试。