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

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

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
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries full burden and does well by disclosing key behavioral traits: it automatically creates the page if missing, uses Roam's standard date format, maintains block relationships, and describes the return structure. It doesn't mention error conditions, rate limits, or authentication requirements, but provides substantial operational context.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is well-structured with clear sections (purpose, behavior, args, returns, examples) and every sentence adds value. It's appropriately sized for a tool with one parameter but complex behavior, with no redundant information.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's complexity (automatic page creation, hierarchical content processing) and the presence of an output schema, the description provides excellent context. It explains the tool's behavior, parameter requirements, return structure, and includes practical examples, making it complete enough for effective use despite having no annotations.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters5/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The schema has 0% description coverage for its single parameter, but the description comprehensively explains the 'content' parameter with format details, examples, and hierarchical structure requirements. It adds significant value beyond the bare schema by specifying the markdown format, indentation rules, and providing concrete examples.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose with specific verbs ('write hierarchical markdown content', 'automatically creates today's daily page') and identifies the target resource ('today's daily page in Roam Research'). It distinguishes from sibling tools like 'write_to_page' by specifying the date-specific nature of this operation.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides clear context about when to use this tool (for writing to today's daily page in Roam Research) and implicitly distinguishes it from 'write_to_page' which likely writes to arbitrary pages. However, it doesn't explicitly state when NOT to use this tool or mention alternatives like 'get_page_content' for reading operations.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

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