Skip to main content
Glama
netologist

Bear Notes MCP Server

by netologist

find_code_examples

Search Bear notes for code examples by programming language and topic to find relevant code snippets for learning or implementation.

Instructions

Find code examples in Bear notes

Args: language: Programming language (python, javascript, go, etc.) topic: Topic to search for (docker, api, database, etc.) limit: Maximum number of results

Returns: Notes containing code examples with extracted code blocks

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
languageNo
topicNo
limitNo

Implementation Reference

  • main.py:247-305 (handler)
    The handler function for the 'find_code_examples' MCP tool. It is decorated with @mcp.tool() for registration. Searches Bear notes for code examples based on language and/or topic, extracts code blocks from matching notes, filters if necessary, and returns a list of relevant notes with code block metadata.
    @mcp.tool()
    def find_code_examples(language: str = "", topic: str = "", limit: int = 15) -> List[Dict[str, Any]]:
        """
        Find code examples in Bear notes
        
        Args:
            language: Programming language (python, javascript, go, etc.)
            topic: Topic to search for (docker, api, database, etc.)
            limit: Maximum number of results
        
        Returns:
            Notes containing code examples with extracted code blocks
        """
        try:
            search_terms = []
            
            if language:
                search_terms.extend([
                    f"```{language}",
                    f"#{language}",
                    language.lower()
                ])
            
            if topic:
                search_terms.append(topic.lower())
            
            # General code-related terms
            code_terms = ["```", "code", "example", "script", "function", "class"]
            
            results = []
            seen_ids = set()
            
            all_terms = search_terms + (code_terms if not search_terms else [])
            
            for term in all_terms:
                notes = search_notes(term, limit=10)
                for note in notes:
                    if note["id"] not in seen_ids:
                        # Extract and analyze code blocks
                        code_blocks = extract_code_blocks(note["content"])
                        
                        # Filter code blocks by language if specified
                        if language:
                            code_blocks = [
                                block for block in code_blocks 
                                if language.lower() in block["language"].lower()
                            ]
                        
                        note["code_blocks"] = code_blocks
                        note["code_block_count"] = len(code_blocks)
                        note["languages"] = list(set(block["language"] for block in code_blocks))
                        
                        results.append(note)
                        seen_ids.add(note["id"])
            
            return results[:limit]
            
        except Exception as e:
            return [{"error": f"Error searching code examples: {str(e)}"}]
  • Helper function used by find_code_examples to extract code blocks from note content using regex to match ```language\ncode``` fenced blocks.
    def extract_code_blocks(content: str) -> List[Dict[str, str]]:
        """Extract code blocks from note content"""
        import re
        
        # Find code blocks with language specification
        code_blocks = []
        pattern = r'```(\w+)?\n(.*?)```'
        matches = re.findall(pattern, content, re.DOTALL)
        
        for language, code in matches:
            code_blocks.append({
                "language": language or "text",
                "code": code.strip()
            })
        
        return code_blocks
  • main.py:28-79 (helper)
    Core helper function used by find_code_examples to query the Bear database for notes matching search terms.
    def search_notes(query: str = "", tag: str = "", limit: int = 20) -> List[Dict[str, Any]]:
        """Search Bear notes"""
        conn = get_bear_db_connection()
        
        try:
            # Base query
            sql = """
            SELECT 
                ZUNIQUEIDENTIFIER as id,
                ZTITLE as title,
                ZTEXT as content,
                ZCREATIONDATE as created_date,
                ZMODIFICATIONDATE as modified_date,
                ZTRASHED as is_trashed
            FROM ZSFNOTE 
            WHERE ZTRASHED = 0
            """
            
            params = []
            
            # Add search criteria
            if query:
                sql += " AND (ZTITLE LIKE ? OR ZTEXT LIKE ?)"
                params.extend([f"%{query}%", f"%{query}%"])
            
            # Add tag filter
            if tag:
                sql += " AND ZTEXT LIKE ?"
                params.append(f"%#{tag}%")
            
            sql += " ORDER BY ZMODIFICATIONDATE DESC LIMIT ?"
            params.append(limit)
            
            cursor = conn.execute(sql, params)
            results = []
            
            for row in cursor.fetchall():
                content = row["content"] or ""
                results.append({
                    "id": row["id"],
                    "title": row["title"] or "Untitled",
                    "content": content,
                    "created_date": row["created_date"],
                    "modified_date": row["modified_date"],
                    "preview": content[:200] + "..." if len(content) > 200 else content,
                    "word_count": len(content.split()) if content else 0
                })
            
            return results
            
        finally:
            conn.close()
  • main.py:19-26 (helper)
    Helper function to establish connection to the Bear App SQLite database, used indirectly via search_notes.
    def get_bear_db_connection():
        """Connect to Bear database"""
        if not os.path.exists(BEAR_DB_PATH):
            raise FileNotFoundError(f"Bear database not found: {BEAR_DB_PATH}")
        
        conn = sqlite3.connect(BEAR_DB_PATH)
        conn.row_factory = sqlite3.Row  # Enable column name access
        return conn

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/netologist/mcp-bear-notes'

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