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

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