Skip to main content
Glama
mickm3n

Roam Research MCP Server

by mickm3n

write_to_today

Add hierarchical markdown content to today's daily page in Roam Research, automatically creating the page if needed while maintaining proper block relationships.

Instructions

Write hierarchical markdown content to today's daily page in Roam Research.

Automatically creates today's daily page if it doesn't exist, then adds the
provided content as a hierarchical block structure. Uses Roam's standard
date format (e.g., "July 28, 2025") and maintains proper block relationships.

Args:
    content: Hierarchical markdown content using '- ' prefix and indentation
            Format: "- Main topic
- Subtopic
    - Details"
            Supports any indentation level with automatic detection
            
Returns:
    JSON string containing:
    - result: "success" if completed
    - blocks_created: Total number of blocks created (including children) 
    - details: Array of individual block creation results
    
Examples:
    write_to_today("- Daily standup
- Completed: Bug fixes
- Next: Feature review")
    write_to_today("- [[會議/週會]]
- 參與者: @John, @Mary
- 議題: Q4 規劃")

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
contentYes

Implementation Reference

  • main.py:486-516 (handler)
    MCP tool handler for 'write_to_today'. Decorated with @mcp.tool() which serves as both registration and handler execution. Calls the underlying client method to perform the write operation.
    @mcp.tool()
    async def write_to_today(content: str) -> str:
        """Write hierarchical markdown content to today's daily page in Roam Research.
        
        Automatically creates today's daily page if it doesn't exist, then adds the
        provided content as a hierarchical block structure. Uses Roam's standard
        date format (e.g., "July 28, 2025") and maintains proper block relationships.
    
        Args:
            content: Hierarchical markdown content using '- ' prefix and indentation
                    Format: "- Main topic\n    - Subtopic\n        - Details"
                    Supports any indentation level with automatic detection
                    
        Returns:
            JSON string containing:
            - result: "success" if completed
            - blocks_created: Total number of blocks created (including children) 
            - details: Array of individual block creation results
            
        Examples:
            write_to_today("- Daily standup\n    - Completed: Bug fixes\n    - Next: Feature review")
            write_to_today("- [[會議/週會]]\n    - 參與者: @John, @Mary\n    - 議題: Q4 規劃")
        """
        try:
            client = get_roam_client()
            result = client.write_to_today_page(content)
            return f"Successfully wrote to today's page: {json.dumps(result, indent=2)}"
        except Exception as e:
            print(f"Error writing to today's page: {e}", file=sys.stderr)
            return f"Error: {str(e)}"
  • Core helper method implementing the logic to write content to today's Roam daily page, including page creation if needed, parsing, and recursive block creation.
    def write_to_today_page(self, content: str) -> Dict[str, Any]:
        """Write hierarchical content to today's daily page"""
        # Use the standard Roam date format
        today = datetime.now().strftime("%B %d, %Y")
        today_uid = datetime.now().strftime("%m-%d-%Y")
    
        # Try to get today's page by UID first
        page_query = f'''[:find ?e
                         :where
                         [?e :block/uid "{today_uid}"]
                         ]'''
    
        query_data = {"query": page_query}
    
        endpoint = f"/api/graph/{self.graph_name}/q"
        page_result = self._make_request("POST", endpoint, query_data)
    
        if not page_result.get("result") or not page_result["result"]:
            # Try to create today's page
            create_data = {
                "action": "create-page",
                "page": {"title": today, "uid": today_uid},
            }
    
            write_endpoint = f"/api/graph/{self.graph_name}/write"
            self._make_request("POST", write_endpoint, create_data)
    
        # Parse markdown content into hierarchical blocks
        blocks = self._parse_markdown_to_blocks(content)
        
        # Create the hierarchical structure
        results = self._create_block_hierarchy(today_uid, blocks)
        
        return {"result": "success", "blocks_created": len(results), "details": results}
  • Helper function that parses indented markdown content into a hierarchical block structure for Roam API.
    def _parse_markdown_to_blocks(self, content: str) -> list:
        """Parse markdown content into hierarchical block structure using dynamic indentation detection"""
        lines = [line.rstrip() for line in content.split('\n') if line.strip()]
        
        # Build indentation level mapping
        indent_map = {}  # {actual_indent: level}
        blocks = []
        stack = []  # Stack to track parent blocks at different levels
        
        for i, line in enumerate(lines):
            actual_indent = len(line) - len(line.lstrip())
            
            # Determine the level for this indentation
            if actual_indent not in indent_map:
                if actual_indent == 0:
                    indent_map[actual_indent] = 0
                else:
                    # Find the closest parent indentation level
                    parent_indents = [k for k in indent_map.keys() if k < actual_indent]
                    if parent_indents:
                        parent_indent = max(parent_indents)
                        indent_map[actual_indent] = indent_map[parent_indent] + 1
                    else:
                        indent_map[actual_indent] = 1
            
            level = indent_map[actual_indent]
            
            # Extract content (remove leading "- " if present)
            text = line.strip()
            if text.startswith('- '):
                text = text[2:]
            
            # Create block structure
            block = {
                "string": text,
                "uid": f"{datetime.now().strftime('%m-%d-%Y')}-{datetime.now().strftime('%H%M%S')}-{i}",
                "children": []
            }
            
            # Adjust stack to current level
            while len(stack) > level:
                stack.pop()
            
            if level == 0:
                # Top-level block
                blocks.append(block)
                stack = [block]
            else:
                # Child block - add to the parent at the appropriate level
                if stack and len(stack) >= level:
                    parent = stack[level - 1]
                    parent["children"].append(block)
                    # Extend stack to current level
                    while len(stack) <= level:
                        stack.append(block)
                    stack[level] = block
                else:
                    # Fallback: treat as top-level if stack is insufficient
                    blocks.append(block)
                    stack = [block]
        
        return blocks
  • Recursive helper that creates Roam blocks via API, handling hierarchical children.
    def _create_block_hierarchy(self, parent_uid: str, blocks: list) -> list:
        """Recursively create blocks with their children"""
        results = []
        
        for block in blocks:
            # Create the main block
            block_data = {
                "action": "create-block",
                "location": {"parent-uid": parent_uid, "order": "last"},
                "block": {
                    "string": block["string"],
                    "uid": block["uid"],
                },
            }
            
            write_endpoint = f"/api/graph/{self.graph_name}/write"
            result = self._make_request("POST", write_endpoint, block_data)
            results.append(result)
            
            # Create children if they exist
            if block["children"]:
                child_results = self._create_block_hierarchy(block["uid"], block["children"])
                results.extend(child_results)
        
        return results

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/mickm3n/roam-research-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server