Repository navigation
Description
Overview
Add get_markdown_from_node_id MCP method to export NodeSpace content as clean, readable markdown with minimal metadata. This enables AI agents to read and understand node hierarchies naturally, complementing the existing create_nodes_from_markdown import functionality (Issue #296).
Background
The Use Case: AI Semantic Search Workflow
// 1. AI searches for relevant content
containers = search_containers("Q4 planning tasks")
// → ["container-abc", "container-def", "container-ghi"]
// 2. AI needs to READ the content to analyze
markdown = get_markdown_from_node_id("container-abc")
// → Returns clean, scannable markdown for AI comprehension
// 3. AI identifies specific nodes to update
// (sees node IDs in comments, can call update_node later)Why Markdown Instead of JSON?
For AI reading/understanding, markdown is superior:
❌ JSON Tree (Hard to scan):
{
"id": "container-123",
"content": "# Q4 Planning",
"children": [
{
"id": "header-1",
"content": "## Marketing",
"children": [
{"id": "task-1", "content": "- [x] Launch campaign", "children": []},
{"id": "task-2", "content": "- [ ] Finalize budget", "children": []}
]
}
]
}
// AI has to mentally parse nested structure✅ Clean Markdown (Natural reading):
<!-- container-123 -->
# Q4 Planning
<!-- header-1 -->
## Marketing
<!-- task-1 -->
- [x] Launch campaign
<!-- task-2 -->
- [ ] Finalize budgetKey Principle: Markdown for reading, JSON for manipulation (see Issue #310 for JSON batch operations).
Implementation Tasks
1. Create Markdown Export Handler
File: packages/core/src/mcp/handlers/markdown.rs
Add to existing file (already has create_nodes_from_markdown):
use crate::mcp::types::MCPError;
use crate::services::NodeService;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::sync::Arc;
/// Parameters for get_markdown_from_node_id method
#[derive(Debug, Deserialize)]
pub struct GetMarkdownParams {
/// Root node ID to export
pub node_id: String,
/// Include children recursively (default: true)
#[serde(default = "default_include_children")]
pub include_children: bool,
/// Maximum recursion depth to prevent infinite loops (default: 20)
#[serde(default = "default_max_depth")]
pub max_depth: usize,
}
fn default_include_children() -> bool { true }
fn default_max_depth() -> usize { 20 }
/// Export node hierarchy as markdown with minimal metadata
///
/// Returns clean markdown with HTML comments containing only node IDs.
/// This format is optimized for AI reading and understanding.
///
/// # Example Output
///
/// \`\`\`markdown
/// <!-- container-abc123 -->
/// # Project Plan
///
/// <!-- header-def456 -->
/// ## Phase 1
///
/// <!-- task-ghi789 -->
/// - [ ] Review architecture
/// \`\`\`
pub async fn handle_get_markdown_from_node_id(
service: &Arc<NodeService>,
params: Value,
) -> Result<Value, MCPError> {
// Parse parameters
let params: GetMarkdownParams = serde_json::from_value(params)
.map_err(|e| MCPError::invalid_params(format!("Invalid parameters: {}", e)))?;
// Validate node exists
let root_node = service
.get_node(¶ms.node_id)
.await
.map_err(|e| MCPError::internal_error(format!("Failed to get node: {}", e)))?
.ok_or_else(|| MCPError::node_not_found(¶ms.node_id))?;
// Build markdown recursively
let mut markdown = String::new();
export_node_to_markdown(
service,
&root_node.id,
&mut markdown,
0, // Current depth
params.max_depth,
params.include_children,
)
.await?;
// Return result
Ok(json!({
"markdown": markdown,
"root_node_id": params.node_id,
"node_count": count_nodes_in_markdown(&markdown)
}))
}
/// Recursively export node and its children to markdown
async fn export_node_to_markdown(
service: &Arc<NodeService>,
node_id: &str,
output: &mut String,
current_depth: usize,
max_depth: usize,
include_children: bool,
) -> Result<(), MCPError> {
// Prevent infinite recursion
if current_depth >= max_depth {
tracing::warn!("Max depth {} reached at node {}", max_depth, node_id);
return Ok(());
}
// Get node
let node = service
.get_node(node_id)
.await
.map_err(|e| MCPError::internal_error(format!("Failed to get node: {}", e)))?
.ok_or_else(|| MCPError::node_not_found(node_id))?;
// Add minimal metadata comment (just ID)
output.push_str(&format!("<!-- {} -->\n", node.id));
// Add content
output.push_str(&node.content);
output.push_str("\n\n");
// Recursively export children (if enabled)
if include_children {
// Query children of this node (ordered by before_sibling_id chain)
let children = service
.get_children(&node.id)
.await
.map_err(|e| MCPError::internal_error(format!("Failed to get children: {}", e)))?;
for child in children {
export_node_to_markdown(
service,
&child.id,
output,
current_depth + 1,
max_depth,
include_children,
)
.await?;
}
}
Ok(())
}
/// Count number of nodes in markdown (by counting HTML comments)
fn count_nodes_in_markdown(markdown: &str) -> usize {
markdown.matches("<!--").count()
}2. Register Handler in MCP Server
File: packages/core/src/mcp/server.rs
Add to handle_request match statement:
async fn handle_request(service: &Arc<NodeService>, request: MCPRequest) -> MCPResponse {
let result = match request.method.as_str() {
"initialize" => { /* ... */ }
"create_node" => { /* ... */ }
"get_node" => { /* ... */ }
// NEW: Markdown export
"get_markdown_from_node_id" => {
crate::mcp::handlers::markdown::handle_get_markdown_from_node_id(
service,
request.params,
)
.await
}
// Existing markdown import
"create_nodes_from_markdown" => { /* ... */ }
_ => Err(MCPError::method_not_found(&request.method)),
};
// ...
}3. Add Method to Initialize Capabilities
File: packages/core/src/mcp/handlers/initialize.rs
Add to get_tool_schemas() array:
{
"name": "get_markdown_from_node_id",
"description": "Export node and its children as clean markdown for reading and analysis",
"inputSchema": {
"type": "object",
"properties": {
"node_id": {
"type": "string",
"description": "Root node ID to export"
},
"include_children": {
"type": "boolean",
"description": "Include child nodes recursively (default: true)",
"default": true
},
"max_depth": {
"type": "number",
"description": "Maximum recursion depth (default: 20)",
"default": 20
}
},
"required": ["node_id"]
}
}4. Add Tests
File: packages/core/src/mcp/handlers/markdown_test.rs
Add test cases to existing test file:
#[tokio::test]
async fn test_get_markdown_simple() {
let service = setup_test_service().await;
// Create test nodes
let root = create_test_node(&service, "text", "# Hello World", None).await;
let child = create_test_node(&service, "text", "- Item 1", Some(&root.id)).await;
// Export markdown
let params = json!({
"node_id": root.id,
"include_children": true
});
let result = handle_get_markdown_from_node_id(&service, params).await.unwrap();
let markdown = result["markdown"].as_str().unwrap();
// Verify output
assert!(markdown.contains(&format!("<!-- {} -->", root.id)));
assert!(markdown.contains("# Hello World"));
assert!(markdown.contains(&format!("<!-- {} -->", child.id)));
assert!(markdown.contains("- Item 1"));
// Verify node count
assert_eq!(result["node_count"].as_u64().unwrap(), 2);
}
#[tokio::test]
async fn test_get_markdown_max_depth() {
let service = setup_test_service().await;
// Create deep hierarchy
let root = create_test_node(&service, "text", "Root", None).await;
let child1 = create_test_node(&service, "text", "Child 1", Some(&root.id)).await;
let child2 = create_test_node(&service, "text", "Child 2", Some(&child1.id)).await;
let child3 = create_test_node(&service, "text", "Child 3", Some(&child2.id)).await;
// Export with max_depth=2
let params = json!({
"node_id": root.id,
"max_depth": 2
});
let result = handle_get_markdown_from_node_id(&service, params).await.unwrap();
let markdown = result["markdown"].as_str().unwrap();
// Should include root and child1, but NOT child2 or child3
assert!(markdown.contains(&root.id));
assert!(markdown.contains(&child1.id));
assert!(!markdown.contains(&child2.id)); // Beyond max_depth
assert!(!markdown.contains(&child3.id)); // Beyond max_depth
}
#[tokio::test]
async fn test_get_markdown_no_children() {
let service = setup_test_service().await;
let root = create_test_node(&service, "text", "# Root", None).await;
let _child = create_test_node(&service, "text", "Child", Some(&root.id)).await;
// Export WITHOUT children
let params = json!({
"node_id": root.id,
"include_children": false
});
let result = handle_get_markdown_from_node_id(&service, params).await.unwrap();
let markdown = result["markdown"].as_str().unwrap();
// Should only include root
assert!(markdown.contains(&root.id));
assert!(!markdown.contains("Child"));
assert_eq!(result["node_count"].as_u64().unwrap(), 1);
}
#[tokio::test]
async fn test_roundtrip_import_export() {
let service = setup_test_service().await;
// Original markdown
let original = "# Heading\n\n- Item 1\n- Item 2\n\n- [ ] Task";
// Import
let import_params = json!({
"markdown_content": original,
"container_title": "Test"
});
let import_result = handle_create_nodes_from_markdown(&service, import_params).await.unwrap();
let container_id = import_result["nodes"][0]["id"].as_str().unwrap();
// Export
let export_params = json!({
"node_id": container_id,
"include_children": true
});
let export_result = handle_get_markdown_from_node_id(&service, export_params).await.unwrap();
let exported = export_result["markdown"].as_str().unwrap();
// Remove HTML comments for comparison
let clean_exported = exported
.lines()
.filter(|line| !line.starts_with("<!--"))
.collect::<Vec<_>>()
.join("\n")
.trim()
.to_string();
// Should match original (modulo whitespace)
assert_eq!(normalize_whitespace(&clean_exported), normalize_whitespace(original));
}Design Decisions
Minimal Metadata: Just IDs
What we include:
<!-- node-id-here -->
Content hereWhat we DON'T include:
- ❌ Node type (inferred from content syntax)
- ❌ Parent ID (implicit in hierarchy)
- ❌ before_sibling_id (visual ordering, not semantic)
- ❌ Properties (use get_node for details)
Rationale: Keep markdown clean and scannable for AI. If AI needs more details, it can call get_node(id) or get_nodes_batch([ids]) (see Issue #310).
Traversal Order
Use depth-first traversal following parent-child relationships:
Container
├─ Header 1
│ ├─ Task 1
│ └─ Task 2
└─ Header 2
└─ Task 3
Output order:
1. Container
2. Header 1
3. Task 1
4. Task 2
5. Header 2
6. Task 3
Note: We use get_children() which already returns children in sibling order (via before_sibling_id chain). This ensures consistent output.
Max Depth Protection
Default max_depth: 20 prevents:
- ❌ Infinite loops from circular references
- ❌ Stack overflow from deeply nested structures
- ❌ Massive exports consuming too much memory
If user needs deeper hierarchies, they can increase max_depth parameter.
Use Case Examples
Example 1: AI Reading for Summary
// User: "Summarize my Q4 planning notes"
// AI workflow:
containers = search_containers("Q4 planning")
markdown = get_markdown_from_node_id(containers[0])
// AI sees clean markdown, can summarize naturally:
/*
# Q4 Planning
## Marketing Goals
- Launch new campaign
- Increase social media presence
## Engineering Goals
- Deploy feature X
- Refactor legacy code
*/
// AI returns: "Your Q4 plan focuses on marketing (campaign launch, social media)
// and engineering (feature deployment, code refactoring)."Example 2: AI Identifying Nodes to Update
// User: "Mark all completed tasks as done"
// AI workflow:
markdown = get_markdown_from_node_id("container-123")
/*
<!-- task-1 -->
- [x] Review architecture ← already done
<!-- task-2 -->
- [ ] Write docs ← NEEDS UPDATE
<!-- task-3 -->
- [x] Deploy ← already done
*/
// AI extracts IDs to update: ["task-2"]
update_node("task-2", { content: "- [x] Write docs" })Example 3: Export for External Processing
// User: "Export this document to share with my team"
markdown = get_markdown_from_node_id("container-abc", { include_children: true })
// AI can:
// - Save to file
// - Send via email
// - Post to Slack
// - Copy to clipboardTesting Strategy
Manual Testing
# 1. Create some test nodes via MCP
echo '{"jsonrpc":"2.0","id":1,"method":"create_nodes_from_markdown","params":{"markdown_content":"# Test\n- Item 1\n- Item 2","container_title":"Test Doc"}}' | cargo run --bin nodespace-app
# 2. Export markdown
echo '{"jsonrpc":"2.0","id":2,"method":"get_markdown_from_node_id","params":{"node_id":"<container-id-from-step-1>"}}' | cargo run --bin nodespace-app
# Expected output:
{
"jsonrpc": "2.0",
"id": 2,
"result": {
"markdown": "<!-- container-123 -->\n# Test\n\n<!-- item-1 -->\n- Item 1\n\n<!-- item-2 -->\n- Item 2\n\n",
"root_node_id": "container-123",
"node_count": 3
}
}Integration Testing
- Use Claude Code to search containers (once Issue Expose semantic search via MCP (search_containers method) #321 is done)
- Export markdown and verify readability
- Test max_depth limiting
- Test include_children flag
- Verify round-trip (import → export → compare)
Acceptance Criteria
-
get_markdown_from_node_idhandler implemented - Returns clean markdown with minimal HTML comment metadata (IDs only)
- Supports
include_childrenparameter (default: true) - Supports
max_depthparameter (default: 20) - Depth-first traversal preserves hierarchy
- Uses
get_children()to maintain sibling order - Returns
markdown,root_node_id, andnode_countin result - Error handling for missing nodes
- Max depth prevents infinite loops
- Registered in MCP server handler
- Added to initialize capabilities schema
- Comprehensive tests (simple, max_depth, no_children, roundtrip)
- Manual testing passes
- Works with Claude Code MCP client
References
- Related Issue: Add create_nodes_from_markdown MCP method #296 (create_nodes_from_markdown - import functionality)
- Related Issue: Add batch node operations and bulk container update MCP methods #310 (batch operations and JSON tree export - for manipulation)
- Related Issue: Implement MCP initialization handshake and capability discovery #308 (MCP initialization - for capability discovery)
- Related Issue: Expose semantic search via MCP (search_containers method) #321 (semantic search - completes search → read workflow)
- Current Implementation:
packages/core/src/mcp/handlers/markdown.rs - MCP Server:
packages/core/src/mcp/server.rs
Future Enhancements (Not in This Issue)
- Optional metadata modes (include type, parent_id, etc.)
- Filtering options (only specific node types)
- Format options (GitHub-flavored markdown, CommonMark, etc.)
- Compression for large exports
Activity
Add get_markdown_from_node_id MCP method for exporting nodes to markdown
Fix remaining markdown import tests - first element is container
Add get_markdown_from_node_id MCP method for exporting nodes to markdown
Fix remaining markdown import tests - first element is container
Address code review feedback - improve implementation quality
Add get_markdown_from_node_id MCP method for exporting nodes to markd…
Add get_markdown_from_node_id MCP method for exporting nodes to markd…
Add get_markdown_from_node_id MCP method for exporting nodes to markd…
Add get_markdown_from_node_id MCP method for exporting nodes to markd…