Skip to main content
Glama

add_note

Create flashcards in Anki with formatted content for code and math equations to enhance learning through spaced repetition.

Instructions

Add a flashcard to Anki. Ensure you have looked at examples before you do this, and that you have got approval from the user to add the flashcard.

For code examples, use <code> tags to format your code.
e.g. <code>def fibonacci(n):
if n <= 1:
    return n
return fibonacci(n-1) + fibonacci(n-2)</code>

For MathJax, use the <math> tag to format your math equations. This will automatically render the math equations in Anki.
# e.g. <math>\frac{d}{dx}[3\sin(5x)] = 15\cos(5x)</math>

Args:
    deckName: str - The target deck name.
    modelName: str - The note type (model) name.
    fields: dict - Dictionary of field names and their string content.
    tags: List[str] - Optional list of tags.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
deckNameYes
modelNameYes
fieldsYes
tagsNo

Implementation Reference

  • The primary handler for the 'add_note' tool. Decorated with @mcp.tool() for registration. Processes fields, builds payload, calls AnkiConnectClient.add_note, returns success/error.
    @mcp.tool()
    @handle_anki_connection_error # Apply decorator
    async def add_note(
        deckName: str,
        modelName: str,
        fields: dict[str, str],
        tags: Optional[List[str]] = None) -> str: # Use standard optional list with None default
        """Add a flashcard to Anki. Ensure you have looked at examples before you do this, and that you have got approval from the user to add the flashcard.
    
        For code examples, use <code> tags to format your code.
        e.g. <code>def fibonacci(n):
        if n <= 1:
            return n
        return fibonacci(n-1) + fibonacci(n-2)</code>
    
        For MathJax, use the <math> tag to format your math equations. This will automatically render the math equations in Anki.
        # e.g. <math>\\frac{d}{dx}[3\\sin(5x)] = 15\\cos(5x)</math>
    
        Args:
            deckName: str - The target deck name.
            modelName: str - The note type (model) name.
            fields: dict - Dictionary of field names and their string content.
            tags: List[str] - Optional list of tags.
        """
        # Process fields using the helper function
        processed_fields = {
            name: _process_field_content(value) for name, value in fields.items()
        }
    
        note_payload = {
            "deckName": deckName,
            "modelName": modelName,
            "fields": processed_fields, # Use processed fields
            "tags": tags if tags is not None else [],
            "options": {
                "allowDuplicate": False,
                "duplicateScope": "deck",
                # "checkClobber": True # Optional: check if adding would overwrite based on first field
            }
        }
    
        async with get_anki_client() as anki:
            logger.info(f"Attempting to add note to deck '{deckName}' with model '{modelName}'.")
            logger.debug(f"Note Payload: {json.dumps(note_payload, indent=2)}") # Log the payload for debugging
    
            # Invoke addNote - errors (like duplicate, missing fields) will be caught
            # by the ValueError check in invoke or the decorator
            note_id = await anki.add_note(note=note_payload)
    
            # add_note returns the new note ID on success, or raises error/returns None/0 on failure
            if note_id:
                success_message = f"Successfully created note with ID: {note_id} in deck '{deckName}'."
                logger.info(success_message)
                return success_message
            else:
                # This case might occur if allowDuplicate=True and a duplicate was added,
                # or if the API behaves unexpectedly without raising an error.
                fail_message = f"Failed to add note to deck '{deckName}'. AnkiConnect did not return a note ID or indicated failure."
                logger.error(fail_message)
                # Return an error message for the LLM
                return f"SYSTEM_ERROR: {fail_message}"
  • Helper function used by add_note to transform field content: MathJax tags to LaTeX delimiters, code blocks to HTML <pre><code>, inline code to <code>.
    def _process_field_content(content: str) -> str:
        """Processes field content for MathJax and code blocks before sending to Anki."""
        if not isinstance(content, str):
            logger.warning(f"Field content is not a string (type: {type(content)}). Returning as-is.")
            return content # Return non-strings unmodified
    
        # 1. MathJax: <math>...</math> -> \(...\)
        processed_value = content.replace("<math>", "\\(").replace("</math>", "\\)")
    
        # 2. Code Blocks: ```lang\n...\n``` -> <pre><code class="language-lang">...</code></pre>
        processed_value = re.sub(
            r'```(\w+)?\s*\n?(.*?)```',
            lambda m: f'<pre><code class="language-{m.group(1)}">{m.group(2)}</code></pre>' if m.group(1) else f'<pre><code>{m.group(2)}</code></pre>',
            processed_value,
            flags=re.DOTALL
        )
    
        # 3. Inline Code: `...` -> <code>...</code>
        processed_value = re.sub(r'`([^`]+)`', r'<code>\1</code>', processed_value)
    
        return processed_value
  • AnkiConnectClient helper method invoked by the tool handler to perform the actual 'addNote' API call.
    async def add_note(self, note: dict) -> int:
        # Note structure should match AnkiConnect requirements:
        # {"deckName": ..., "modelName": ..., "fields": {...}, "tags": [...], "options": {...}}
        return await self.invoke(AnkiAction.ADD_NOTE, note=note)
  • Input schema for the tool: parameters with types and descriptions in docstring.
    async def add_note(
        deckName: str,
        modelName: str,
        fields: dict[str, str],
        tags: Optional[List[str]] = None) -> str: # Use standard optional list with None default
        """Add a flashcard to Anki. Ensure you have looked at examples before you do this, and that you have got approval from the user to add the flashcard.
    
        For code examples, use <code> tags to format your code.
        e.g. <code>def fibonacci(n):
        if n <= 1:
            return n
        return fibonacci(n-1) + fibonacci(n-2)</code>
    
        For MathJax, use the <math> tag to format your math equations. This will automatically render the math equations in Anki.
        # e.g. <math>\\frac{d}{dx}[3\\sin(5x)] = 15\\cos(5x)</math>
    
        Args:
            deckName: str - The target deck name.
            modelName: str - The note type (model) name.
            fields: dict - Dictionary of field names and their string content.
            tags: List[str] - Optional list of tags.
        """
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. It mentions the tool adds a flashcard (implying a write operation) and includes formatting guidelines for code and math, but lacks critical behavioral details such as error handling, permissions required, whether the operation is idempotent, or what happens on failure. For a mutation tool with zero annotation coverage, this is insufficient.

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

Conciseness3/5

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

The description is front-loaded with the core purpose but includes extensive formatting examples that, while helpful, could be more concise. Sentences like 'Ensure you have looked at examples before you do this' are somewhat redundant with the formatting guidelines. It's structured but includes some unnecessary elaboration.

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?

Given the complexity (4 parameters, nested objects, no output schema, and no annotations), the description covers the basics but lacks depth. It explains parameters and formatting but misses details on return values, error cases, or integration with sibling tools. For a tool with significant contextual needs, it's adequate but incomplete.

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 lists all parameters with brief explanations (e.g., 'deckName: str - The target deck name'), adding meaning beyond the bare schema. However, it doesn't provide examples of valid values, constraints, or how 'fields' should be structured beyond 'Dictionary of field names and their string content,' leaving gaps in understanding.

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: 'Add a flashcard to Anki.' It specifies the verb ('Add') and resource ('flashcard to Anki'), making the action clear. However, it doesn't explicitly differentiate from sibling tools like 'search_notes' or 'submit_reviews', which is why it doesn't reach a score of 5.

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

Usage Guidelines3/5

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

The description provides some usage context: 'Ensure you have looked at examples before you do this, and that you have got approval from the user to add the flashcard.' This implies prerequisites but doesn't explicitly state when to use this tool versus alternatives like 'list_decks_and_notes' for checking decks or 'submit_reviews' for other actions. It offers implied guidance rather than clear alternatives.

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/samefarrar/mcp-ankiconnect'

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