Skip to content

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

:recycle: Centralize native block instructions in tool descriptions https://github.com/siyuan-note/siyuan/issues/20163

Daniela5bfee84fcf4
diff --git a/kernel/agent/agent.go b/kernel/agent/agent.go
index ed07486fe0..b63caacb6f 100644
--- a/kernel/agent/agent.go
+++ b/kernel/agent/agent.go
@@ -64,27 +64,7 @@ second paragraph
}}}
Use {{{row for a vertical super-block. Never use data-layout in raw block DOM. If raw DOM is unavoidable, the outer block must use data-type="NodeSuperBlock" and data-sb-layout="row" or data-sb-layout="col", and every child must be complete block DOM with an explicit data-type; otherwise content may become an HTML block.
-- Tabs and Mindmap are native, editable SiYuan blocks supported by the block tool; do not substitute HTML widgets, Mermaid diagrams, or plugins unless requested.
-- Tabs: NodeTabs contains only NodeTabItem; each item contains body blocks and may contain nested tabs. Create with block.insert/append/prepend and dataType="markdown":
-
-::: tabs
-@tab First
-
-First body
-
-@tab:active Second
-
-Second body
-
-:::
-
- The opening fence requires a space before tabs; never write :::tabs or :::tab. Nested groups require longer outer colon fences. To add tabs to an existing NodeTabs, pass a group containing only the new items; the tool inserts those items and preserves the target group's attributes. Use attr.set for tabs-position (top/left) and tabs-active-id (an existing direct item ID). Use block.move/delete on item IDs for reordering/removal, and edit body blocks individually.
-- Mindmap: NodeMindmap contains only NodeMindmapItem. Each item contains content blocks and may contain a nested NodeMindmap for child branches; never put a plain NodeList, NodeListItem, or a bare NodeMindmapItem directly inside an item. Create with block.insert/append/prepend and dataType="dom", for example:
-
-<div data-type="NodeMindmap" data-subtype="u" class="mindmap"><div data-type="NodeMindmapItem" data-subtype="u" data-marker="-" class="mindmap-item"><div data-type="NodeParagraph" class="p"><div contenteditable="true">Root</div></div><div data-type="NodeMindmap" data-subtype="u" class="mindmap"><div data-type="NodeMindmapItem" data-subtype="u" data-marker="-" class="mindmap-item"><div data-type="NodeParagraph" class="p"><div contenteditable="true">Child</div></div></div></div></div></div>
-
- Every block requires an explicit data-type; the tool generates IDs for new native DOM blocks that omit data-node-id. A mindmap code fence creates an ordinary code block, not a native mindmap. To add siblings to an existing NodeMindmap, pass a group containing only the new items; to add a child branch, insert a NodeMindmap under a NodeMindmapItem. Use block.move/delete on item IDs and edit their content blocks individually.
-- Structural edits: block.get/get_kramdown/batch_kramdown return reading Markdown that flattens Tabs and renders Mindmap as ordinary lists. Before editing either container, call block.dom and preserve all existing data-node-id values and attributes, including active tabs and mindmap metadata. Use dataType="dom" and lockType=true for updates unless the user explicitly requests a type conversion. Never rebuild these containers from their reading Markdown.
+- 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.
@@ -93,8 +73,8 @@ Second body
## Tool Usage Patterns
- Find: search.fulltext (keyword) → block.get (by ID). For semantic search use search.semantic.
- 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 (dataType "markdown").
-- Modify: block.update replaces ONE block's content with new markdown — 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.
+- Create content: document.create (notebook + hPath) → block.append/prepend/insert.
+- 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.
- Attributes: attr.get/set on any block. Database/attribute views: database.create (database block with ordered fields), database.item_add (rows), database.key_add (columns), database.key_update (field configuration: name/type/icon/description, number/date format, display template, date defaults, select options, relation and rollup settings; inspect keys first, send exactly one config setting per call, and render to verify), database.key_set_template (existing template field formulas; use .action{add .Number 1} for a number field plus one, then render to verify; do not write computed template cells with item_update), database.render (view). Create database blocks via database.create, never via the file tool or generic block insertion.
diff --git a/kernel/agent/capability_test.go b/kernel/agent/capability_test.go
index 0b0180a36f..f14695e653 100644
--- a/kernel/agent/capability_test.go
+++ b/kernel/agent/capability_test.go
@@ -9,6 +9,7 @@
package agent
import (
+ "encoding/json"
"testing"
"github.com/siyuan-note/siyuan/kernel/conf"
@@ -30,6 +31,44 @@ func TestFrontendCapabilityModelNamesAreStableAndDistinct(t *testing.T) {
}
}
+func TestBlockCapabilityExposesSharedToolDescriptions(t *testing.T) {
+ originalConf := kernelModel.Conf
+ kernelModel.Conf = kernelModel.NewAppConf()
+ kernelModel.Conf.AI = conf.NewAI()
+ id := tools.CapabilityIDForTool(tools.BlockTool)
+ kernelModel.Conf.AI.Agent.CapabilityPolicy = &conf.CapabilityPolicy{
+ Default: "deny", Overrides: map[string]string{id: "allow"},
+ }
+ t.Cleanup(func() { kernelModel.Conf = originalConf })
+ set, err := buildCapabilitySet(nil, capabilityAccessContext{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(set.definitions) != 1 || set.definitions[0].Function.Name != "block" {
+ t.Fatal("block capability was not exposed independently")
+ }
+ definition := set.definitions[0].Function
+ if definition.Description != tools.BlockTool.Description {
+ t.Fatal("agent did not receive the shared block tool description")
+ }
+ data, err := json.Marshal(definition.Parameters)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var schema tools.ToolSchema
+ if err = json.Unmarshal(data, &schema); err != nil {
+ t.Fatal(err)
+ }
+ if schema.Properties["data"].Description != tools.BlockTool.InputSchema.Properties["data"].Description {
+ t.Fatal("agent did not receive the native block creation examples")
+ }
+ kernelModel.Conf.AI.Agent.CapabilityPolicy.Overrides[id] = "deny"
+ set, err = buildCapabilitySet(nil, capabilityAccessContext{})
+ if err != nil || len(set.definitions) != 0 {
+ t.Fatalf("disabled block tool descriptions were still exposed: %v", err)
+ }
+}
+
func TestCapabilityPolicyControlsExposureAndExecution(t *testing.T) {
const toolName = "test_capability_policy_tool"
const backendID = "native/backend/test_capability_policy_tool"
diff --git a/kernel/agent/prompt_test.go b/kernel/agent/prompt_test.go
index 65acc89aa1..815fddb637 100644
--- a/kernel/agent/prompt_test.go
+++ b/kernel/agent/prompt_test.go
@@ -109,21 +109,29 @@ func TestSystemPromptDocumentsSuperBlockLayout(t *testing.T) {
}
}
-func TestSystemPromptDocumentsNativeContainerEditing(t *testing.T) {
+func TestSystemPromptPreservesNativeStructure(t *testing.T) {
for _, instruction := range []string{
- "Tabs and Mindmap are native, editable SiYuan blocks",
- "::: tabs\n@tab First",
- "@tab:active Second",
- `data-type="NodeMindmap"`,
- `data-type="NodeMindmapItem"`,
- "block.move/delete on item IDs",
- "call block.dom and preserve all existing data-node-id values and attributes",
- "lockType=true",
- "Never rebuild these containers from their reading Markdown",
+ "use native capabilities and preserve existing structure, block IDs, and metadata",
+ "Follow the relevant tool descriptions for block-specific syntax and operations",
"Missing guide search results alone do not prove a feature is unsupported",
} {
if !strings.Contains(systemPrompt, instruction) {
- t.Fatalf("missing native container instruction %q", instruction)
+ t.Fatalf("missing native structure instruction %q", instruction)
+ }
+ }
+ for _, capabilities := range []*capabilitySet{
+ nil,
+ {registrations: map[string]*capabilityRegistration{"block": {ModelName: "block"}}},
+ {registrations: map[string]*capabilityRegistration{}},
+ } {
+ prompt := filterSystemPromptByCapabilities(systemPrompt, capabilities)
+ if !strings.Contains(prompt, "preserve existing structure, block IDs, and metadata") {
+ t.Fatal("native structure protection was removed by capability filtering")
+ }
+ for _, detail := range []string{"NodeTabs", "NodeTabItem", "NodeMindmap", "NodeMindmapItem", "::: tabs", "@tab", "tabs-position", "tabs-active-id"} {
+ if strings.Contains(prompt, detail) {
+ t.Fatalf("block-specific detail %q belongs in the tool description, not the system prompt", detail)
+ }
}
}
}
diff --git a/kernel/mcp/server_test.go b/kernel/mcp/server_test.go
index f40f85c818..8354b4adab 100644
--- a/kernel/mcp/server_test.go
+++ b/kernel/mcp/server_test.go
@@ -133,6 +133,42 @@ func TestModernProtocolClient(t *testing.T) {
}
}
+func TestBlockToolDescriptionsReachMCPClients(t *testing.T) {
+ server, httpServer := newTestHTTPServer(t)
+ syncTool(server, tools.BlockTool.Name, tools.BlockTool)
+ client := mcpsdk.NewClient(&mcpsdk.Implementation{Name: "block-description-test", Version: "1.0.0"}, nil)
+ session, err := client.Connect(t.Context(), &mcpsdk.StreamableClientTransport{Endpoint: httpServer.URL}, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { session.Close() })
+ result, err := session.ListTools(t.Context(), nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, tool := range result.Tools {
+ if tool.Name != tools.BlockTool.Name {
+ continue
+ }
+ if tool.Description != tools.BlockTool.Description {
+ t.Fatal("MCP client did not receive the shared native block rules")
+ }
+ data, err := json.Marshal(tool.InputSchema)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var schema tools.ToolSchema
+ if err = json.Unmarshal(data, &schema); err != nil {
+ t.Fatal(err)
+ }
+ if schema.Properties["data"].Description != tools.BlockTool.InputSchema.Properties["data"].Description {
+ t.Fatal("MCP client did not receive the native block creation examples")
+ }
+ return
+ }
+ t.Fatal("native block tool was not listed")
+}
+
func TestToolProjectionPolicyAndExecutionRecheck(t *testing.T) {
server := newServer()
allowed := true
diff --git a/kernel/mcp/tools/block.go b/kernel/mcp/tools/block.go
index ac3b7ff0d5..8ea84bbd39 100644
--- a/kernel/mcp/tools/block.go
+++ b/kernel/mcp/tools/block.go
@@ -29,16 +29,47 @@ import (
)
var BlockTool = &Tool{
- Name: "block",
- Description: "Block operations, including native Tabs (NodeTabs/NodeTabItem) and Mindmap (NodeMindmap/NodeMindmapItem). Actions: get(id), get_kramdown(id), get_children(id), tree_stat(id, by document), dom(id), insert(data, dataType, parentID?, nextID?, previousID?), append(data, dataType, parentID) / prepend(...) add a NEW child and return its ID — use after block.update when both modifying and adding, update(id, data, dataType, lockType?) replaces ONE block only (no append), delete(id), move(id, parentID, previousID?), breadcrumb(id), batch_get(ids) / batch_kramdown(ids) where ids is comma-separated. get/get_kramdown/batch_kramdown return Markdown for reading, which flattens tabs and renders mindmaps as lists; use dom before editing these containers, preserve IDs/attributes, and update with dataType=dom and lockType=true. Prefer editing body blocks individually and move/delete for structural changes.",
+ Name: "block",
+ Description: `Block operations, including native Tabs (NodeTabs/NodeTabItem) and Mindmap (NodeMindmap/NodeMindmapItem).
+Actions: get(id), get_kramdown(id), get_children(id), tree_stat(id, by document), dom(id), insert(data, dataType, parentID?, nextID?, previousID?), append(data, dataType, parentID) / prepend(...) add a NEW child and return its ID — use after block.update when both modifying and adding, update(id, data, dataType, lockType?) replaces ONE block only (no append), delete(id), move(id, parentID, previousID?), breadcrumb(id), batch_get(ids) / batch_kramdown(ids) where ids is comma-separated.
+
+Native container structure and operations:
+- These are native, editable blocks; do not substitute HTML widgets, Mermaid diagrams, or plugins unless requested.
+- Tabs: NodeTabs contains only NodeTabItem; each item contains at least one body block and may contain nested tabs. Use an empty paragraph for an empty body. Use attr.set for tabs-position (top/left) and tabs-active-id (an existing direct item ID).
+- Mindmap: NodeMindmap contains only NodeMindmapItem. Each item contains content blocks and may contain a nested NodeMindmap for child branches; never put a plain NodeList, NodeListItem, or a bare NodeMindmapItem directly inside an item. A mindmap code fence creates an ordinary code block, not a native mindmap.
+- To add tabs or sibling mindmap items, pass a group containing only the new items to insert/append/prepend. When the target container is of the same type, only the group's direct items are inserted and the target container's attributes are preserved. To add a child mindmap branch, insert a NodeMindmap under a NodeMindmapItem.
+- Use move/delete on existing item IDs for reordering/removal, and edit body blocks individually.
+
+Structural reads and updates:
+- get/get_kramdown/batch_kramdown return Markdown for reading, which flattens tabs and renders mindmaps as lists; use dom before editing these containers. Never rebuild these containers from their reading Markdown.
+- Preserve all existing data-node-id values and attributes, including active tabs and mindmap metadata. Update with dataType=dom and lockType=true unless the user explicitly requests a type conversion.`,
InputSchema: ToolSchema{
Type: "object",
Properties: map[string]Property{
- "action": {Type: "string", Description: "Operation", Enum: []string{"get", "get_kramdown", "get_children", "tree_stat", "dom", "insert", "append", "prepend", "update", "delete", "move", "breadcrumb", "batch_get", "batch_kramdown"}},
- "notebook": {Type: "string", Description: "Notebook ID that owns the target blocks; required for encrypted notebooks"},
- "id": {Type: "string", Description: "Block ID"},
- "ids": {Type: "string", Description: "Comma-separated block IDs (for batch_get, batch_kramdown)"},
- "data": {Type: "string", Description: "Content in markdown or block DOM. Prefer markdown for ordinary blocks. Native Tabs Markdown: ::: tabs\n@tab First\n\nBody\n\n@tab:active Second\n\nOther body\n\n::: (tabs requires a space). For nested tabs use a longer outer colon fence. Native Mindmap requires dataType=dom: <div data-type=\"NodeMindmap\" data-subtype=\"u\" class=\"mindmap\"><div data-type=\"NodeMindmapItem\" data-subtype=\"u\" data-marker=\"-\" class=\"mindmap-item\"><div data-type=\"NodeParagraph\" class=\"p\"><div contenteditable=\"true\">Root</div></div></div></div>. Nest NodeMindmap inside NodeMindmapItem for child branches; every block needs an explicit data-type. New native DOM blocks may omit data-node-id; the tool generates IDs. When inserting a Tabs or Mindmap group into an existing container of the same type, only its direct items are inserted; parent attributes remain unchanged. A horizontal super-block uses {{{col with blank-line-separated child blocks and }}} on its own line; col is horizontal and row is vertical. Raw super-block DOM uses data-type=\"NodeSuperBlock\" and data-sb-layout, never data-layout, and every child needs an explicit data-type. Markdown block references use ((blockID \"anchor text\")); never [[blockID]]"},
+ "action": {Type: "string", Description: "Operation", Enum: []string{"get", "get_kramdown", "get_children", "tree_stat", "dom", "insert", "append", "prepend", "update", "delete", "move", "breadcrumb", "batch_get", "batch_kramdown"}},
+ "notebook": {Type: "string", Description: "Notebook ID that owns the target blocks; required for encrypted notebooks"},
+ "id": {Type: "string", Description: "Block ID"},
+ "ids": {Type: "string", Description: "Comma-separated block IDs (for batch_get, batch_kramdown)"},
+ "data": {Type: "string", Description: `Content in markdown or block DOM. Prefer markdown for ordinary blocks. Use insert/append/prepend to create native containers.
+
+Native Tabs Markdown (dataType=markdown):
+::: tabs
+@tab First
+
+Body
+
+@tab:active Second
+
+Other body
+
+:::
+The opening fence requires a space before tabs; never write :::tabs or :::tab. Nested groups require longer outer colon fences.
+
+Native Mindmap DOM (dataType=dom):
+<div data-type="NodeMindmap" data-subtype="u" class="mindmap"><div data-type="NodeMindmapItem" data-subtype="u" data-marker="-" class="mindmap-item"><div data-type="NodeParagraph" class="p"><div contenteditable="true">Root</div></div><div data-type="NodeMindmap" data-subtype="u" class="mindmap"><div data-type="NodeMindmapItem" data-subtype="u" data-marker="-" class="mindmap-item"><div data-type="NodeParagraph" class="p"><div contenteditable="true">Child</div></div></div></div></div></div>
+Every block needs an explicit data-type. New native DOM blocks may omit data-node-id; the tool generates IDs.
+
+A horizontal super-block uses {{{col with blank-line-separated child blocks and }}} on its own line; col is horizontal and row is vertical. Raw super-block DOM uses data-type="NodeSuperBlock" and data-sb-layout, never data-layout, and every child needs an explicit data-type. Markdown block references use ((blockID "anchor text")); never [[blockID]].`},
"dataType": {Type: "string", Description: "Content type: markdown or dom", Enum: []string{"markdown", "dom"}},
"lockType": {Type: "boolean", Description: "Reject update when the parsed block type differs from the existing block type; defaults to true for native Tabs/Mindmap containers and items, false otherwise. Set false only for an intentional type conversion"},
"parentID": {Type: "string", Description: "Parent block ID"},
diff --git a/kernel/mcp/tools/block_test.go b/kernel/mcp/tools/block_test.go
index 0dcbc46807..aed4afccf4 100644
--- a/kernel/mcp/tools/block_test.go
+++ b/kernel/mcp/tools/block_test.go
@@ -86,13 +86,24 @@ func TestBlockWriteSuccessRejectsEmptyID(t *testing.T) {
const nativeMindmapTestDOM = `<div data-type="NodeMindmap" data-subtype="u" class="mindmap"><div data-type="NodeMindmapItem" data-subtype="u" data-marker="-" class="mindmap-item"><div data-type="NodeParagraph" class="p"><div contenteditable="true">Root</div></div><div data-type="NodeMindmap" data-subtype="u" class="mindmap"><div data-type="NodeMindmapItem" data-subtype="u" data-marker="-" class="mindmap-item"><div data-type="NodeParagraph" class="p"><div contenteditable="true">Child</div></div></div></div></div></div>`
func TestBlockToolCreatesNativeContainers(t *testing.T) {
+ description := BlockTool.InputSchema.Properties["data"].Description
+ tabsStart := strings.Index(description, "::: tabs\n")
+ tabsEnd := strings.Index(description, "\nThe opening fence")
+ if tabsStart < 0 || tabsEnd <= tabsStart {
+ t.Fatal("missing native tabs Markdown example")
+ }
+ _, mindmap, found := strings.Cut(description, "Native Mindmap DOM (dataType=dom):\n")
+ if !found {
+ t.Fatal("missing native mindmap DOM example")
+ }
+ mindmap, _, _ = strings.Cut(mindmap, "\n")
for _, tc := range []struct {
name, data, dataType string
want ast.NodeType
count int
}{
- {"tabs", "::: tabs\n@tab First\n\nBody\n\n@tab:active Second\n\nOther body\n\n:::\n", "markdown", ast.NodeTabs, 5},
- {"mindmap", nativeMindmapTestDOM, "dom", ast.NodeMindmap, 6},
+ {"tabs", description[tabsStart:tabsEnd], "markdown", ast.NodeTabs, 5},
+ {"mindmap", mindmap, "dom", ast.NodeMindmap, 6},
} {
t.Run(tc.name, func(t *testing.T) {
dom, err := prepareBlockWriteData(tc.data, tc.dataType)
@@ -147,9 +158,30 @@ func TestBlockToolPreservesNativeDOMIdentity(t *testing.T) {
}
func TestBlockToolDocumentsNativeContainerEditing(t *testing.T) {
- for _, instruction := range []string{"NodeTabs/NodeTabItem", "NodeMindmap/NodeMindmapItem", "use dom before editing", "lockType=true"} {
+ for _, instruction := range []string{
+ "NodeTabs/NodeTabItem", "NodeMindmap/NodeMindmapItem",
+ "native, editable blocks", "do not substitute HTML widgets, Mermaid diagrams, or plugins unless requested",
+ "NodeTabs contains only NodeTabItem", "at least one body block", "empty paragraph for an empty body",
+ "NodeMindmap contains only NodeMindmapItem", "nested NodeMindmap for child branches",
+ "never put a plain NodeList, NodeListItem, or a bare NodeMindmapItem directly inside an item",
+ "mindmap code fence creates an ordinary code block, not a native mindmap",
+ "only the group's direct items are inserted", "target container's attributes are preserved",
+ "move/delete on existing item IDs", "edit body blocks individually",
+ "tabs-position (top/left)", "tabs-active-id (an existing direct item ID)",
+ "use dom before editing", "Never rebuild these containers from their reading Markdown",
+ "Preserve all existing data-node-id values and attributes", "active tabs and mindmap metadata",
+ "dataType=dom and lockType=true", "unless the user explicitly requests a type conversion",
+ } {
if !strings.Contains(BlockTool.Description, instruction) {
t.Fatalf("missing native container instruction %q", instruction)
}
}
+ for _, instruction := range []string{
+ "never write :::tabs or :::tab", "Nested groups require longer outer colon fences",
+ "Every block needs an explicit data-type", "may omit data-node-id; the tool generates IDs",
+ } {
+ if !strings.Contains(BlockTool.InputSchema.Properties["data"].Description, instruction) {
+ t.Fatalf("missing native block data instruction %q", instruction)
+ }
+ }
}