Skip to main content
Glama
ergut

MCP server for LogSeq

by ergut

get_page_content

Retrieve content from LogSeq pages in text or JSON format to access and use page data programmatically.

Instructions

Get the content of a specific page from LogSeq.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
page_nameYesName of the page to retrieve
formatNoOutput format (text or json)text

Implementation Reference

  • The run_tool method of GetPageContentToolHandler executes the core tool logic: it validates input, fetches page data via LogSeq API, and formats the content (title, properties, blocks) as readable markdown or JSON.
    def run_tool(self, args: dict) -> list[TextContent]:
        """Get and format LogSeq page content."""
        logger.info(f"Getting page content with args: {args}")
        
        if "page_name" not in args:
            raise RuntimeError("page_name argument required")
    
        try:
            api = logseq.LogSeq(api_key=api_key)
            result = api.get_page_content(args["page_name"])
            
            if not result:
                return [TextContent(
                    type="text",
                    text=f"Page '{args['page_name']}' not found."
                )]
    
            # Handle JSON format request
            if args.get("format") == "json":
                return [TextContent(
                    type="text",
                    text=str(result)
                )]
    
            # Format as readable text
            content_parts = []
            
            # Get page info and blocks from the result structure
            page_info = result.get("page", {})
            blocks = result.get("blocks", [])
            
            # Title
            title = page_info.get("originalName", args["page_name"])
            content_parts.append(f"# {title}\n")
            
            # Properties
            properties = page_info.get("properties", {})
            if properties:
                content_parts.append("Properties:")
                for key, value in properties.items():
                    content_parts.append(f"- {key}: {value}")
                content_parts.append("")
            
            # Blocks content
            if blocks:
                content_parts.append("Content:")
                for block in blocks:
                    if isinstance(block, dict) and block.get("content"):
                        content_parts.append(f"- {block['content']}")
                    elif isinstance(block, str) and block.strip():
                        content_parts.append(f"- {block}")
            else:
                content_parts.append("No content blocks found.")
            
            return [TextContent(
                type="text",
                text="\n".join(content_parts)
            )]
    
        except Exception as e:
            logger.error(f"Failed to get page content: {str(e)}")
            raise
  • The get_tool_description method defines the tool schema including input validation for page_name (required) and optional format (text/json).
    def get_tool_description(self):
        return Tool(
            name=self.name,
            description="Get the content of a specific page from LogSeq.",
            inputSchema={
                "type": "object",
                "properties": {
                    "page_name": {
                        "type": "string",
                        "description": "Name of the page to retrieve"
                    },
                    "format": {
                        "type": "string",
                        "description": "Output format (text or json)",
                        "enum": ["text", "json"],
                        "default": "text"
                    }
                },
                "required": ["page_name"]
            }
        )
  • Registers the GetPageContentToolHandler instance with the MCP server during initialization.
    add_tool_handler(tools.GetPageContentToolHandler())
  • Core LogSeq API helper method that retrieves page metadata, blocks tree, and properties using LogSeq's Graph API endpoints and combines them into a structured result.
    def get_page_content(self, page_name: str) -> Any:
        """Get content of a LogSeq page including metadata and block content."""
        url = self.get_base_url()
        logger.info(f"Getting content for page '{page_name}'")
        
        try:
            # Step 1: Get page metadata (includes UUID)
            response = requests.post(
                url,
                headers=self._get_headers(),
                json={
                    "method": "logseq.Editor.getPage",
                    "args": [page_name]
                },
                verify=self.verify_ssl,
                timeout=self.timeout
            )
            response.raise_for_status()
            page_info = response.json()
            
            if not page_info:
                logger.error(f"Page '{page_name}' not found")
                return None
                
            # Step 2: Get page blocks using the page name
            response = requests.post(
                url,
                headers=self._get_headers(),
                json={
                    "method": "logseq.Editor.getPageBlocksTree",
                    "args": [page_name]
                },
                verify=self.verify_ssl,
                timeout=self.timeout
            )
            response.raise_for_status()
            blocks = response.json()
            
            # Step 3: Get page properties
            response = requests.post(
                url,
                headers=self._get_headers(),
                json={
                    "method": "logseq.Editor.getPageProperties",
                    "args": [page_name]
                },
                verify=self.verify_ssl,
                timeout=self.timeout
            )
            response.raise_for_status()
            properties = response.json() or {}
            
            return {
                "page": {
                    **page_info,
                    "properties": properties
                },
                "blocks": blocks or []
            }
            
        except Exception as e:
            logger.error(f"Error getting page content: {str(e)}")
            raise
Behavior2/5

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

With no annotations provided, the description carries full burden but only states the basic action without behavioral details. It doesn't disclose whether this requires authentication, has rate limits, what happens if the page doesn't exist, or the structure of returned content (especially for 'json' format). For a read operation with zero annotation coverage, this leaves significant gaps.

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 a single, direct sentence with zero wasted words. It's appropriately sized for a simple tool and front-loads the core purpose immediately.

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

Completeness2/5

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

Given no annotations and no output schema, the description is incomplete for a tool that retrieves content. It doesn't explain what 'content' includes (e.g., text, metadata, blocks), how formats differ, or error conditions. For a read tool with rich sibling context, it should provide more operational context.

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

Parameters3/5

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

Schema description coverage is 100%, with clear parameter documentation in the schema itself. The description adds no additional parameter information beyond implying retrieval of 'content', which aligns with the schema. This meets the baseline of 3 when the schema does the heavy lifting.

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

Purpose4/5

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

The description clearly states the action ('Get the content') and resource ('a specific page from LogSeq'), making the purpose immediately understandable. However, it doesn't differentiate this read operation from other page-related tools like 'list_pages' or 'search', which would require mentioning it retrieves full content rather than metadata or search results.

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

Usage Guidelines2/5

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

No guidance is provided about when to use this tool versus alternatives like 'list_pages' (for metadata) or 'search' (for finding content across pages). The description implies usage when you need content of a known page, but lacks explicit comparison or exclusion criteria for sibling tools.

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/ergut/mcp-logseq-server'

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