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

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

With no annotations provided, the description carries full burden for behavioral disclosure. It states what the tool does but lacks important behavioral details: no information about permissions needed, rate limits, whether it searches all notes or specific ones, how results are sorted, or what happens when parameters are omitted. The return description is minimal.

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

Conciseness4/5

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

The description is appropriately concise with clear sections (purpose, args, returns). Each sentence serves a purpose, though the 'Args' and 'Returns' sections could be integrated more smoothly. No wasted words, but could be slightly more polished in structure.

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

Completeness3/5

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

For a 3-parameter search tool with no annotations and no output schema, the description provides basic purpose and parameter information but lacks important context. It doesn't explain the search scope, result format, error conditions, or how it differs from sibling tools. The return description is minimal ('Notes containing code examples with extracted code blocks').

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 0%, so the description must compensate. It provides basic semantic meaning for all three parameters (language, topic, limit) with examples for language and topic, which adds value beyond the bare schema. However, it doesn't explain parameter interactions, validation rules, or what happens with empty/default values.

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 tool's purpose: 'Find code examples in Bear notes' with specific parameters for language, topic, and limit. It distinguishes from siblings like 'find_notes_by_title' or 'search_bear_notes' by focusing on code examples, but doesn't explicitly differentiate from 'find_kubernetes_examples' which appears to be a specialized version.

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 like 'find_kubernetes_examples' (which seems related), 'search_bear_notes', or 'get_recent_notes'. It mentions parameters but gives no context about when this tool is appropriate versus other search methods.

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

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