Skip to main content
Glama
ergut

MCP server for LogSeq

by ergut

search

Search for content across LogSeq pages, blocks, and files to find specific information within your knowledge base.

Instructions

Search for content across LogSeq pages, blocks, and files

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYesSearch query text
limitNoMaximum number of results to return
include_blocksNoInclude block content results
include_pagesNoInclude page name results
include_filesNoInclude file name results

Implementation Reference

  • The run_tool method implements the core logic of the 'search' tool: it validates input arguments, calls the LogSeq API's search_content method, processes and formats the results into categorized sections (blocks, snippets, pages, files), handles pagination info, and returns formatted TextContent.
    def run_tool(self, args: dict) -> list[TextContent]:
        """Execute search and format results."""
        logger.info(f"Searching with args: {args}")
        
        if "query" not in args:
            raise RuntimeError("query argument required")
    
        query = args["query"]
        limit = args.get("limit", 20)
        include_blocks = args.get("include_blocks", True)
        include_pages = args.get("include_pages", True)
        include_files = args.get("include_files", False)
    
        try:
            # Prepare search options
            search_options = {"limit": limit}
            
            api = logseq.LogSeq(api_key=api_key)
            result = api.search_content(query, search_options)
            
            if not result:
                return [TextContent(
                    type="text",
                    text=f"No search results found for '{query}'"
                )]
    
            # Format results
            content_parts = []
            content_parts.append(f"# Search Results for '{query}'\n")
            
            # Block results
            if include_blocks and result.get("blocks"):
                blocks = result["blocks"]
                content_parts.append(f"## 📄 Content Blocks ({len(blocks)} found)")
                for i, block in enumerate(blocks[:limit]):
                    # LogSeq returns blocks with 'block/content' key
                    content = block.get("block/content", "").strip()
                    if content:
                        # Truncate long content
                        if len(content) > 150:
                            content = content[:150] + "..."
                        content_parts.append(f"{i+1}. {content}")
                content_parts.append("")
    
            # Page snippet results  
            if include_blocks and result.get("pages-content"):
                snippets = result["pages-content"]
                content_parts.append(f"## 📝 Page Snippets ({len(snippets)} found)")
                for i, snippet in enumerate(snippets[:limit]):
                    # LogSeq returns snippets with 'block/snippet' key  
                    snippet_text = snippet.get("block/snippet", "").strip()
                    if snippet_text:
                        # Clean up snippet text
                        snippet_text = snippet_text.replace("$pfts_2lqh>$", "").replace("$<pfts_2lqh$", "")
                        if len(snippet_text) > 200:
                            snippet_text = snippet_text[:200] + "..."
                        content_parts.append(f"{i+1}. {snippet_text}")
                content_parts.append("")
    
            # Page name results
            if include_pages and result.get("pages"):
                pages = result["pages"]
                content_parts.append(f"## 📑 Matching Pages ({len(pages)} found)")
                for page in pages:
                    content_parts.append(f"- {page}")
                content_parts.append("")
    
            # File results
            if include_files and result.get("files"):
                files = result["files"]
                content_parts.append(f"## 📁 Matching Files ({len(files)} found)")
                for file_path in files:
                    content_parts.append(f"- {file_path}")
                content_parts.append("")
    
            # Pagination info
            if result.get("has-more?"):
                content_parts.append("📌 *More results available - increase limit to see more*")
    
            # Summary
            total_results = len(result.get("blocks", [])) + len(result.get("pages", [])) + len(result.get("files", []))
            content_parts.append(f"\n**Total results found: {total_results}**")
    
            response_text = "\n".join(content_parts)
            
            return [TextContent(type="text", text=response_text)]
            
        except Exception as e:
            logger.error(f"Failed to search: {str(e)}")
            return [TextContent(
                type="text",
                text=f"❌ Search failed: {str(e)}"
            )]
  • The get_tool_description method returns the Tool object defining the schema for the 'search' tool, including input parameters: query (required), limit, include_blocks, include_pages, include_files.
    def get_tool_description(self):
        return Tool(
            name=self.name,
            description="Search for content across LogSeq pages, blocks, and files",
            inputSchema={
                "type": "object",
                "properties": {
                    "query": {
                        "type": "string",
                        "description": "Search query text"
                    },
                    "limit": {
                        "type": "integer",
                        "description": "Maximum number of results to return",
                        "default": 20
                    },
                    "include_blocks": {
                        "type": "boolean",
                        "description": "Include block content results",
                        "default": True
                    },
                    "include_pages": {
                        "type": "boolean", 
                        "description": "Include page name results",
                        "default": True
                    },
                    "include_files": {
                        "type": "boolean",
                        "description": "Include file name results", 
                        "default": False
                    }
                },
                "required": ["query"]
            }
        )
  • The registration block where all tool handlers are added to the tool_handlers dictionary, specifically including add_tool_handler(tools.SearchToolHandler()) on line 80.
    logger.info("Registering tool handlers...")
    add_tool_handler(tools.CreatePageToolHandler())
    add_tool_handler(tools.ListPagesToolHandler())
    add_tool_handler(tools.GetPageContentToolHandler())
    add_tool_handler(tools.DeletePageToolHandler())
    add_tool_handler(tools.UpdatePageToolHandler())
    add_tool_handler(tools.SearchToolHandler())
    logger.info("Tool handlers registration complete")
Behavior2/5

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. It mentions what is searched (pages, blocks, files) but lacks details on how results are returned (e.g., format, ordering, pagination), error handling, or performance considerations like rate limits. This is a significant gap for a search tool with multiple parameters.

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, efficient sentence that front-loads the core purpose without unnecessary words. It directly communicates the tool's function, making it easy to parse and understand quickly.

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 the complexity of a search tool with 5 parameters and no annotations or output schema, the description is insufficient. It doesn't cover behavioral aspects like result format, error cases, or usage trade-offs, leaving the agent with incomplete information for effective tool selection and invocation.

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%, so the schema fully documents all parameters. The description adds no additional meaning beyond the schema, such as explaining how the query syntax works or interactions between include parameters. This meets the baseline for high schema coverage.

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 ('Search for content') and the scope ('across LogSeq pages, blocks, and files'), which is specific and actionable. However, it doesn't explicitly differentiate from sibling tools like 'list_pages' or 'get_page_content', which might also retrieve content but through different mechanisms.

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?

The description provides no guidance on when to use this tool versus alternatives. For example, it doesn't explain when to prefer 'search' over 'list_pages' for finding content or how it complements other tools like 'get_page_content'. This lack of context leaves the agent to infer usage scenarios.

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