Skip to content

Add index-based child operations and fix sibling chain integrity #338

Closed

Description

@malibio

Add Index-Based Child Operations and Fix Sibling Chain Integrity

Overview

This issue addresses critical gaps in the MCP API for hierarchical node manipulation and fixes a data integrity bug in node deletion. We need to add intuitive index-based operations for child node management and ensure sibling chains remain intact during deletions.

Background

Current Limitations

  1. No hierarchy visualization - Agents can't see parent-child relationships or sibling ordering
  2. No intuitive insertion - Agents must understand linked-list pointers (before_sibling_id)
  3. No deletion preview - Agents don't know what children will be cascade-deleted
  4. Broken sibling chains - Deleting a node leaves dangling before_sibling_id references (DATA INTEGRITY BUG 🔴)

Current Data Structure

NodeSpace uses a linked-list structure for siblings:

Node 1 (before_sibling_id = None)        ← First child
Node 2 (before_sibling_id = "node-1")    ← Points to previous sibling
Node 3 (before_sibling_id = "node-2")    ← Points to previous sibling

This is efficient for the database but unintuitive for AI agents who think in array indexes.

Problem Statement

Problem 1: Sibling Chain Integrity Bug 🔴 CRITICAL

Current behavior:

Before deletion:
- uuid-1 (before_sibling_id=None)
- uuid-2 (before_sibling_id="uuid-1")  ← Deleting this
- uuid-3 (before_sibling_id="uuid-2")

After deletion:
- uuid-1 (before_sibling_id=None)
- uuid-3 (before_sibling_id="uuid-2")  ← BROKEN! Points to deleted node

Impact:

  • Orphaned references to deleted nodes
  • Broken tree traversal
  • Incorrect sibling ordering in UI
  • Potential crashes when dereferencing deleted IDs
  • Data corruption

Root cause:
packages/core/src/services/node_service.rs:552-575 - delete_node() only does:

conn.execute("DELETE FROM nodes WHERE id = ?", [id]).await

It doesn't update the next sibling's before_sibling_id to maintain chain integrity.

Problem 2: No Index-Based Operations

AI agents naturally think: "Insert at position 3" or "Move to first position"

Current workaround (cumbersome):

// Agent wants: "Insert at position 3"
// Must do:
1. get_markdown_from_node_id(parent) → Get content
2. Infer structure from markdown
3. Guess sibling IDs from node ID comments
4. create_node(parent_id, before_sibling_id="uuid-???", ...)

This is error-prone and requires understanding linked-list implementation details.

Problem 3: No Hierarchy Visibility

Current tools:

  • get_markdown_from_node_id - Returns flattened markdown with node IDs in comments
  • query_nodes - Returns nodes but not hierarchical structure

Missing:

  • Parent-child relationships
  • Sibling ordering
  • Tree depth information
  • Child count

Solution Design

Part 1: Fix Sibling Chain Integrity (CRITICAL - Do First)

Location: packages/core/src/operations/mod.rs::delete_node()

Algorithm:

pub async fn delete_node(&self, node_id: &str) -> Result<DeleteResult, NodeOperationError> {
    // 1. Get the node being deleted
    let node = self.get_node(node_id).await?
        .ok_or_else(|| NodeOperationError::node_not_found(node_id.to_string()))?;
    
    // 2. Fix sibling chain BEFORE deletion
    if let Some(parent_id) = &node.parent_id {
        // Find the node that points to this one (next sibling)
        let next_sibling = self.node_service
            .query_nodes(
                NodeQueryFilter::new()
                    .with_parent_id(parent_id.clone())
            )
            .await?
            .into_iter()
            .find(|n| n.before_sibling_id.as_deref() == Some(node_id));
        
        // Update next sibling to skip over the deleted node
        if let Some(next) = next_sibling {
            let mut update = NodeUpdate::default();
            update.before_sibling_id = node.before_sibling_id.clone();
            
            self.node_service.update_node(&next.id, update).await?;
        }
    }
    
    // 3. Now safe to delete (children cascade via DB foreign key)
    self.node_service.delete_node(node_id).await
}

Test cases needed:

  1. Delete middle node → verify chain intact
  2. Delete first node → verify next becomes first (before_sibling_id=None)
  3. Delete last node → verify no updates needed
  4. Delete node with children → verify cascade works + chain fixed
  5. Delete root/container node → verify appropriate error

Part 2: Add Index-Based MCP Tools

Add 4 new MCP tools with index-based APIs that internally translate to pointer operations.

Tool 1: get_children (Enhanced)

Purpose: Get all children with their indexes

MCP Schema:

{
    "name": "get_children",
    "description": "Get all children of a parent node in order with their positions (0-based indexes). Returns minimal info by default - use include_content=true to see node content.",
    "inputSchema": {
        "type": "object",
        "properties": {
            "parent_id": {
                "type": "string",
                "description": "Parent node ID (any node ID, or YYYY-MM-DD for date containers)"
            },
            "include_content": {
                "type": "boolean",
                "description": "Include node content in response (default: false). Set to true only if you need content and don't already have it from get_markdown_from_node_id.",
                "default": false
            }
        },
        "required": ["parent_id"]
    }
}

Response format:

{
  "parent_id": "2025-10-23",
  "child_count": 3,
  "children": [
    {
      "index": 0,
      "node_id": "uuid-1",
      "node_type": "header",
      "content": "# Project Alpha"  // Only if include_content=true
    },
    {
      "index": 1,
      "node_id": "uuid-4",
      "node_type": "text"
    },
    {
      "index": 2,
      "node_id": "uuid-7",
      "node_type": "task"
    }
  ]
}

Implementation location: packages/core/src/mcp/handlers/nodes.rs

Helper function needed:

async fn get_children_ordered(
    operations: &Arc<NodeOperations>,
    parent_id: &str,
    include_content: bool,
) -> Result<Vec<ChildInfo>, MCPError> {
    // 1. Query all children with parent_id
    let mut children = operations
        .query_nodes(NodeQueryFilter::new().with_parent_id(parent_id.to_string()))
        .await?;
    
    // 2. Build ordered list by following before_sibling_id chain
    let mut ordered = Vec::new();
    let mut current_before: Option<String> = None;  // Start with first (before_sibling_id=None)
    
    // 3. Follow the linked list from first to last
    while let Some(node) = children.iter().find(|n| n.before_sibling_id == current_before) {
        ordered.push(ChildInfo {
            index: ordered.len(),
            node_id: node.id.clone(),
            node_type: node.node_type.clone(),
            content: if include_content { Some(node.content.clone()) } else { None },
        });
        current_before = Some(node.id.clone());
        
        // Infinite loop protection
        if ordered.len() > children.len() {
            return Err(MCPError::internal_error(
                "Circular sibling chain detected - data corruption".to_string()
            ));
        }
    }
    
    Ok(ordered)
}

Tool 2: insert_child_at_index

Purpose: Insert new child at specific position

MCP Schema:

{
    "name": "insert_child_at_index",
    "description": "Insert a new child node at a specific position (0-based index) under a parent. Index 0 = first child, index 1 = second child, etc. If index >= child count, appends at end.\n\nDATE NODES: If parent_id is in YYYY-MM-DD format, it references a date container which auto-exists. You don't need to create date nodes first.\n\nExample: parent_id='2025-10-23' automatically uses that date's container.",
    "inputSchema": {
        "type": "object",
        "properties": {
            "parent_id": {
                "type": "string",
                "description": "Parent node ID (any node ID, or YYYY-MM-DD for date containers)"
            },
            "index": {
                "type": "number",
                "description": "Position to insert at (0-based). 0=first, 1=second, etc. Use large number (e.g., 999) to append at end.",
                "minimum": 0
            },
            "node_type": {
                "type": "string",
                "enum": ["text", "header", "task", "date", "code-block", "quote-block", "ordered-list"],
                "description": "Type of node to create"
            },
            "content": {
                "type": "string",
                "description": "Node content"
            },
            "properties": {
                "type": "object",
                "description": "Additional type-specific properties (JSON object)"
            }
        },
        "required": ["parent_id", "index", "node_type", "content"]
    }
}

Implementation:

pub async fn handle_insert_child_at_index(
    operations: &Arc<NodeOperations>,
    params: Value,
) -> Result<Value, MCPError> {
    let parent_id = params["parent_id"].as_str()
        .ok_or_else(|| MCPError::invalid_params("Missing parent_id".to_string()))?;
    let index = params["index"].as_u64()
        .ok_or_else(|| MCPError::invalid_params("Missing index".to_string()))? as usize;
    let node_type = params["node_type"].as_str()
        .ok_or_else(|| MCPError::invalid_params("Missing node_type".to_string()))?;
    let content = params["content"].as_str()
        .ok_or_else(|| MCPError::invalid_params("Missing content".to_string()))?;
    let properties = params.get("properties").cloned().unwrap_or(json!({}));
    
    // 1. Ensure parent exists (auto-create if date format)
    ensure_parent_exists(operations, parent_id).await?;
    
    // 2. Get parent to determine container_node_id
    let parent = operations.get_node(parent_id).await?
        .ok_or_else(|| MCPError::invalid_params(format!("Parent node '{}' not found", parent_id)))?;
    
    // 3. Get all siblings in order
    let children_info = get_children_ordered(operations, parent_id, false).await?;
    
    // 4. Calculate before_sibling_id based on index
    let before_sibling_id = if index >= children_info.len() {
        None  // Append at end
    } else {
        Some(children_info[index].node_id.clone())  // Insert before node at index
    };
    
    // 5. Determine container_node_id (from parent or parent itself if container)
    let container_node_id = if parent.is_root() {
        Some(parent.id.clone())  // Parent is the container
    } else {
        parent.container_node_id  // Inherit parent's container
    };
    
    // 6. Create node using pointer-based operation
    let node_id = operations.create_node(
        node_type.to_string(),
        content.to_string(),
        Some(parent_id.to_string()),
        container_node_id,
        before_sibling_id,
        properties,
    ).await?;
    
    Ok(json!({
        "node_id": node_id,
        "parent_id": parent_id,
        "index": index
    }))
}

Helper function:

async fn ensure_parent_exists(
    operations: &Arc<NodeOperations>,
    parent_id: &str,
) -> Result<(), MCPError> {
    // If parent_id looks like a date (YYYY-MM-DD), auto-create date node
    if is_valid_date_format(parent_id) {
        // Try to create - ignore if already exists
        let _ = operations.create_node(
            "date".to_string(),
            parent_id.to_string(),
            None,
            None,
            None,
            json!({}),
        ).await;
    }
    Ok(())
}

fn is_valid_date_format(s: &str) -> bool {
    use chrono::NaiveDate;
    NaiveDate::parse_from_str(s, "%Y-%m-%d").is_ok()
}

Tool 3: move_child_to_index

Purpose: Reorder existing child to new position

MCP Schema:

{
    "name": "move_child_to_index",
    "description": "Move an existing child node to a different position among its siblings. The node stays under the same parent, only the position changes. Index 0 = first position, 1 = second, etc.",
    "inputSchema": {
        "type": "object",
        "properties": {
            "node_id": {
                "type": "string",
                "description": "Child node to reorder"
            },
            "index": {
                "type": "number",
                "description": "New position (0-based). Node will be moved to this position among siblings. If index >= sibling count, moves to end.",
                "minimum": 0
            }
        },
        "required": ["node_id", "index"]
    }
}

Implementation:

pub async fn handle_move_child_to_index(
    operations: &Arc<NodeOperations>,
    params: Value,
) -> Result<Value, MCPError> {
    let node_id = params["node_id"].as_str()
        .ok_or_else(|| MCPError::invalid_params("Missing node_id".to_string()))?;
    let target_index = params["index"].as_u64()
        .ok_or_else(|| MCPError::invalid_params("Missing index".to_string()))? as usize;
    
    // 1. Get the node to move
    let node = operations.get_node(node_id).await?
        .ok_or_else(|| MCPError::invalid_params(format!("Node '{}' not found", node_id)))?;
    
    let parent_id = node.parent_id
        .ok_or_else(|| MCPError::invalid_params("Node has no parent (cannot reorder root nodes)".to_string()))?;
    
    // 2. Get all siblings in current order (excluding the node being moved)
    let all_children = get_children_ordered(operations, &parent_id, false).await?;
    let siblings: Vec<_> = all_children.into_iter()
        .filter(|c| c.node_id != node_id)
        .collect();
    
    // 3. Calculate new before_sibling_id
    let before_sibling_id = if target_index >= siblings.len() {
        None  // Move to end
    } else {
        Some(siblings[target_index].node_id.clone())
    };
    
    // 4. Use existing reorder_node operation
    operations.reorder_node(node_id, before_sibling_id.as_deref()).await?;
    
    Ok(json!({
        "node_id": node_id,
        "new_index": target_index,
        "parent_id": parent_id
    }))
}

Tool 4: get_child_at_index

Purpose: Get specific child by position

MCP Schema:

{
    "name": "get_child_at_index",
    "description": "Get a specific child by its position under a parent. Returns the child node at the specified index (0-based).",
    "inputSchema": {
        "type": "object",
        "properties": {
            "parent_id": {
                "type": "string",
                "description": "Parent node ID"
            },
            "index": {
                "type": "number",
                "description": "Position of child to retrieve (0-based)",
                "minimum": 0
            },
            "include_content": {
                "type": "boolean",
                "description": "Include node content in response (default: true)",
                "default": true
            }
        },
        "required": ["parent_id", "index"]
    }
}

Implementation:

pub async fn handle_get_child_at_index(
    operations: &Arc<NodeOperations>,
    params: Value,
) -> Result<Value, MCPError> {
    let parent_id = params["parent_id"].as_str()
        .ok_or_else(|| MCPError::invalid_params("Missing parent_id".to_string()))?;
    let index = params["index"].as_u64()
        .ok_or_else(|| MCPError::invalid_params("Missing index".to_string()))? as usize;
    let include_content = params.get("include_content")
        .and_then(|v| v.as_bool())
        .unwrap_or(true);
    
    // Get all children in order
    let children = get_children_ordered(operations, parent_id, include_content).await?;
    
    // Get child at index
    let child = children.get(index)
        .ok_or_else(|| MCPError::invalid_params(format!(
            "Index {} out of bounds (parent has {} children)",
            index,
            children.len()
        )))?;
    
    Ok(json!({
        "index": child.index,
        "node_id": &child.node_id,
        "node_type": &child.node_type,
        "content": child.content,
        "parent_id": parent_id
    }))
}

Part 3: Update Tool Registration

Location: packages/core/src/mcp/handlers/tools.rs

Add to handle_tools_call() routing (line 99):

match tool_name {
    "create_node" => nodes::handle_create_node(node_operations, arguments).await,
    "get_node" => nodes::handle_get_node(node_operations, arguments).await,
    "update_node" => nodes::handle_update_node(node_operations, arguments).await,
    "delete_node" => nodes::handle_delete_node(node_operations, arguments).await,
    "query_nodes" => nodes::handle_query_nodes(node_operations, arguments).await,
    
    // NEW: Index-based child operations
    "get_children" => nodes::handle_get_children(node_operations, arguments).await,
    "insert_child_at_index" => nodes::handle_insert_child_at_index(node_operations, arguments).await,
    "move_child_to_index" => nodes::handle_move_child_to_index(node_operations, arguments).await,
    "get_child_at_index" => nodes::handle_get_child_at_index(node_operations, arguments).await,
    
    "create_nodes_from_markdown" => markdown::handle_create_nodes_from_markdown(node_operations, arguments).await,
    "get_markdown_from_node_id" => markdown::handle_get_markdown_from_node_id(node_operations, arguments).await,
    "search_containers" => search::handle_search_containers(embedding_service, arguments).await,
    _ => {
        return Err(MCPError::invalid_params(format!("Unknown tool: {}", tool_name)))
    }
}

Add to get_tool_schemas() (line 170):

json!([
    // ... existing tools ...
    {
        "name": "get_children",
        "description": "Get all children of a parent node in order with their positions (0-based indexes). Returns minimal info by default - use include_content=true to see node content.",
        "inputSchema": { /* schema from above */ }
    },
    {
        "name": "insert_child_at_index",
        "description": "Insert a new child node at a specific position...",
        "inputSchema": { /* schema from above */ }
    },
    {
        "name": "move_child_to_index",
        "description": "Move an existing child node to a different position...",
        "inputSchema": { /* schema from above */ }
    },
    {
        "name": "get_child_at_index",
        "description": "Get a specific child by its position...",
        "inputSchema": { /* schema from above */ }
    }
])

Part 4: Update Initialize Response

Location: packages/core/src/mcp/handlers/initialize.rs

Add instructions about date nodes and hierarchy:

pub fn handle_initialize(_params: Value) -> Result<Value, MCPError> {
    Ok(json!({
        "protocolVersion": "2024-11-05",
        "serverInfo": {
            "name": "nodespace-mcp",
            "version": "0.1.0"
        },
        "capabilities": {
            "tools": {},
            "prompts": {},
        },
        "instructions": {
            "date_nodes": "Date nodes (YYYY-MM-DD) are virtual containers that auto-exist for any valid date. You don't need to create them explicitly - just reference them as parent_id or container_node_id and they'll be created automatically if needed. Example: insert_child_at_index(parent_id='2025-10-23', ...) automatically creates the date container.",
            "node_types": "Available node types: text, header, task, date, code-block, quote-block, ordered-list. Date nodes are special containers for daily notes.",
            "hierarchy": "Nodes can be nested. Use index-based operations (insert_child_at_index, move_child_to_index) for intuitive position control, or use low-level operations (create_node, reorder_node) for direct pointer manipulation."
        }
    }))
}

Implementation Checklist

Phase 1: Critical Bug Fix (Do First) 🔴

  • Update NodeOperations::delete_node() to fix sibling chain
  • Add helper to find next sibling (where before_sibling_id == deleted_id)
  • Update next sibling's before_sibling_id before deletion
  • Add comprehensive tests:
    • Delete middle node
    • Delete first node
    • Delete last node
    • Delete node with children
    • Delete with circular chain detection
  • Run full test suite
  • Manual testing with UI to verify no broken chains

Phase 2: Helper Functions

  • Implement get_children_ordered() with linked-list traversal
  • Add circular chain detection (infinite loop protection)
  • Implement ensure_parent_exists() with date auto-creation
  • Implement is_valid_date_format() checker
  • Add unit tests for helpers

Phase 3: New MCP Tools

  • Implement handle_get_children()
  • Implement handle_insert_child_at_index()
  • Implement handle_move_child_to_index()
  • Implement handle_get_child_at_index()
  • Add tool schemas to get_tool_schemas()
  • Add routing to handle_tools_call()
  • Update initialize response with instructions

Phase 4: Testing

  • Unit tests for each new handler
  • Integration tests for typical workflows:
    • Insert at beginning
    • Insert in middle
    • Insert at end
    • Move from end to beginning
    • Move from beginning to end
    • Get children with/without content
    • Date auto-creation
  • Edge case tests:
    • Index out of bounds
    • Parent doesn't exist
    • Invalid date format
    • Empty parent (no children)
    • Concurrent modifications

Phase 5: Documentation

  • Update MCP tool documentation
  • Add examples to docs/architecture/
  • Update CLAUDE.md if needed
  • Add inline code comments

Phase 6: Quality & Review

  • Run bun run quality:fix
  • All tests passing
  • Create PR
  • Code review
  • Merge

Testing Strategy

Unit Tests

Location: packages/core/src/mcp/handlers/nodes_test.rs (create if needed)

#[tokio::test]
async fn test_get_children_ordered() {
    // Setup: Create parent with 3 children in specific order
    // Test: get_children returns them in correct order with indexes
    // Verify: index 0, 1, 2 match expected order
}

#[tokio::test]
async fn test_insert_child_at_beginning() {
    // Setup: Parent with 2 children
    // Action: insert_child_at_index(parent, index=0, ...)
    // Verify: New node is first (index 0), others shifted
}

#[tokio::test]
async fn test_insert_child_at_middle() {
    // Setup: Parent with 3 children
    // Action: insert_child_at_index(parent, index=2, ...)
    // Verify: New node at index 2, others adjusted
}

#[tokio::test]
async fn test_move_child_to_different_position() {
    // Setup: Parent with 4 children
    // Action: move_child_to_index(child[3], index=1)
    // Verify: Child moved from end to index 1
}

#[tokio::test]
async fn test_delete_node_fixes_sibling_chain() {
    // Setup: Create 3 siblings (A → B → C)
    // Action: delete_node(B)
    // Verify: C.before_sibling_id == A.id (chain intact)
}

#[tokio::test]
async fn test_date_auto_creation() {
    // Action: insert_child_at_index(parent_id="2025-12-25", ...)
    // Verify: Date node "2025-12-25" exists
    // Verify: Child successfully inserted
}

Integration Tests

Location: packages/desktop-app/src/tests/integration/mcp-hierarchy-operations.test.ts (new file)

import { describe, it, expect } from 'vitest';

describe('MCP Hierarchy Operations', () => {
  it('should insert and retrieve children by index', async () => {
    // Create parent
    // Insert 3 children using insert_child_at_index
    // Get children using get_children
    // Verify order and indexes
  });

  it('should reorder children correctly', async () => {
    // Create parent with 4 children
    // Move child from position 3 to position 0
    // Verify new order
  });

  it('should handle date node auto-creation', async () => {
    // Insert child with parent_id = future date
    // Verify date container created
    // Verify child exists under date
  });
});

Usage Examples for Documentation

Example 1: Building a Daily Note

// Agent workflow: "Add tasks to today's note"

// Step 1: Get today's date container (auto-creates if needed)
const today = "2025-10-23";

// Step 2: Insert header at beginning
await invoke("insert_child_at_index", {
  parent_id: today,
  index: 0,
  node_type: "header",
  content: "# Today's Tasks"
});

// Step 3: Add tasks
await invoke("insert_child_at_index", {
  parent_id: today,
  index: 1,
  node_type: "task",
  content: "- [ ] Review PR #335"
});

await invoke("insert_child_at_index", {
  parent_id: today,
  index: 2,
  node_type: "task",
  content: "- [ ] Update documentation"
});

// Step 4: View structure
const children = await invoke("get_children", {
  parent_id: today,
  include_content: false
});
// Returns: [{index: 0, node_id: "...", node_type: "header"}, ...]

Example 2: Reorganizing Content

// Agent workflow: "Move the 4th item to the top"

// Step 1: Get children to see structure
const children = await invoke("get_children", {
  parent_id: "project-alpha",
  include_content: true
});
// Returns: [{index: 0, ...}, {index: 1, ...}, {index: 2, ...}, {index: 3, ...}]

// Step 2: Move 4th item (index 3) to first position (index 0)
await invoke("move_child_to_index", {
  node_id: children[3].node_id,
  index: 0
});

// Result: Item that was at index 3 is now at index 0, others shift down

Example 3: Safe Deletion with Preview

// Agent workflow: "Delete this section but show me what will be removed"

// Step 1: Get children to preview impact
const children = await invoke("get_children", {
  parent_id: "section-to-delete",
  include_content: true
});

// Step 2: Inform user
console.log(`Deleting this will remove ${children.child_count} children:`, children);

// Step 3: User confirms, delete
await invoke("delete_node", {
  node_id: "section-to-delete"
});
// Result: Node and children deleted, sibling chain automatically fixed

Acceptance Criteria

Critical (Must Have)

  • delete_node fixes sibling chain (no dangling before_sibling_id references)
  • All 4 new index-based tools implemented and working
  • Date nodes auto-create when referenced as parent_id
  • Comprehensive test coverage (unit + integration)
  • All quality checks pass (oxlint, clippy, prettier, svelte-check)
  • No regressions in existing functionality

Important (Should Have)

  • Clear error messages for invalid indexes ("Index 5 out of bounds, parent has 3 children")
  • Circular chain detection with helpful error
  • Tool descriptions updated with date node info
  • Initialize response includes instructions
  • Documentation updated

Nice to Have (Could Have)

  • Performance optimization for large child lists
  • Batch operations (insert multiple children at once)
  • Get children with pagination

Technical Debt & Future Enhancements

Known Limitations

  1. O(n) complexity for index operations - Following linked list requires traversing all siblings. For large child lists (100+ children), this could be slow.

    • Mitigation: Most containers have < 50 children
    • Future: Add index cache or materialized view
  2. No atomic batch operations - Inserting 10 children = 10 separate calls

    • Future: Add insert_children_bulk tool
  3. No tree-wide operations - Can't "get all descendants" in one call

Follow-Up Issues

Consider creating these after this issue is complete:

  • Issue: Add get_node_tree for full hierarchy visualization
  • Issue: Add batch operations for bulk inserts
  • Issue: Expose move_node and reorder_node via MCP (currently Tauri-only)
  • Issue: Add index materialization for performance

Related Issues

Questions for Reviewer

  1. Should get_children return include_content=true by default? (Currently false)
  2. Should we add pagination to get_children for large lists?
  3. Should we expose low-level pointer operations (insert_after_node) via MCP, or keep them internal?
  4. Date auto-creation: Should we validate date format strictly, or be lenient?

References

Activity

  1. added
    enhancement
    on Oct 23, 2025
  2. malibio commented on Oct 23, 2025

    @malibio
    CollaboratorAuthor

    Update: Adding get_node_tree and Clarifications

    Additional Tool: get_node_tree

    Adding get_node_tree to provide full hierarchical tree visualization (this was extensively discussed but accidentally omitted from the original issue).

    Tool 5: get_node_tree

    Purpose: Get hierarchical tree structure showing the complete node hierarchy from a root node

    MCP Schema:

    {
        "name": "get_node_tree",
        "description": "Get hierarchical tree structure of a node and its descendants. Returns minimal structure by default (IDs, types, relationships). Use include_content=true if you need to see node content.",
        "inputSchema": {
            "type": "object",
            "properties": {
                "node_id": {
                    "type": "string",
                    "description": "Root node ID to get tree from"
                },
                "max_depth": {
                    "type": "number",
                    "description": "Maximum depth to traverse (default: 10). Use lower values for performance with large trees.",
                    "default": 10,
                    "minimum": 1,
                    "maximum": 100
                },
                "include_content": {
                    "type": "boolean",
                    "description": "Include node content in response (default: false). Set to true only if you need content and don't have it from a previous get_markdown_from_node_id call.",
                    "default": false
                },
                "include_metadata": {
                    "type": "boolean",
                    "description": "Include created_at, modified_at, properties (default: false)",
                    "default": false
                }
            },
            "required": ["node_id"]
        }
    }

    Response Format (default - structure only):

    {
      "node_id": "2025-10-23",
      "node_type": "date",
      "depth": 0,
      "child_count": 2,
      "children": [
        {
          "node_id": "uuid-1",
          "node_type": "header",
          "depth": 1,
          "parent_id": "2025-10-23",
          "before_sibling_id": null,
          "child_count": 2,
          "children": [
            {
              "node_id": "uuid-2",
              "node_type": "text",
              "depth": 2,
              "parent_id": "uuid-1",
              "before_sibling_id": null,
              "child_count": 0,
              "children": []
            }
          ]
        }
      ]
    }

    Implementation:

    pub async fn handle_get_node_tree(
        operations: &Arc<NodeOperations>,
        params: Value,
    ) -> Result<Value, MCPError> {
        let node_id = params["node_id"].as_str()
            .ok_or_else(|| MCPError::invalid_params("Missing node_id".to_string()))?;
        let max_depth = params.get("max_depth")
            .and_then(|v| v.as_u64())
            .unwrap_or(10) as usize;
        let include_content = params.get("include_content")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);
        let include_metadata = params.get("include_metadata")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);
        
        let root = operations.get_node(node_id).await?
            .ok_or_else(|| MCPError::invalid_params(format!("Node '{}' not found", node_id)))?;
        
        let tree = build_tree_node(
            operations,
            root,
            0,
            max_depth,
            include_content,
            include_metadata,
        ).await?;
        
        Ok(json!(tree))
    }

    Answers to Implementation Questions

    1. Testing Scope

    Answer: Use the existing test structure - do NOT create a new nodes_test.rs file.

    Test Organization:

    • Rust unit tests: Add #[cfg(test)] mod tests { ... } at bottom of nodes.rs
    • Integration tests: Create packages/desktop-app/src/tests/integration/mcp-hierarchy-operations.test.ts

    2. Date Node Auto-Creation

    Answer: YYYY-MM-DD only for initial implementation.

    Rationale: Simple, unambiguous, covers primary use case (daily notes). Add YYYY-MM/YYYY later as enhancement.

    Implementation:

    fn is_valid_date_format(s: &str) -> bool {
        use chrono::NaiveDate;
        NaiveDate::parse_from_str(s, "%Y-%m-%d").is_ok()
    }

    3. Error Handling for Circular Chains

    Answer: Return an error and abort the deletion.

    Rationale: Data corruption should never be hidden. Fail loudly to identify root cause.

    Implementation:

    if has_circular_chain(&siblings) {
        return Err(NodeOperationError::internal_error(format!(
            "Circular sibling chain detected in parent '{}'. Database corruption - aborting deletion.",
            parent_id
        )));
    }

    4. Container Node ID Determination

    Answer: Yes, date nodes should be considered containers.

    Date nodes have is_root()=true, so the existing logic already works:

    let container_node_id = if parent.is_root() {
        Some(parent.id.clone())  // Parent IS the container
    } else {
        parent.container_node_id  // Inherit from parent
    };

    5. Tool Ordering in Tools List

    Answer: Group related tools together with logical sections.

    Recommended order:

    1. Core Node CRUD (create, get, update, delete, query)
    2. Hierarchy & Children (get_children, get_child_at_index, insert_child_at_index, move_child_to_index, get_node_tree)
    3. Markdown Import/Export
    4. Search

    Updated Checklist

    Phase 3: New MCP Tools

    • Implement handle_get_children()
    • Implement handle_insert_child_at_index()
    • Implement handle_move_child_to_index()
    • Implement handle_get_child_at_index()
    • Implement handle_get_node_tree() ← NEW
    • Implement build_tree_node() recursive helper ← NEW
    • Add tool schemas in logical order
    • Add routing to handle_tools_call()

    This completes the full hierarchy operations feature set!

  3. self-assigned this
    on Oct 23, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

criticalenhancementmcp

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions