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
| Name | Required | Description | Default |
|---|---|---|---|
| deckName | Yes | ||
| modelName | Yes | ||
| fields | Yes | ||
| tags | No |
Implementation Reference
- mcp_ankiconnect/server.py:469-530 (handler)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}"
- mcp_ankiconnect/server.py:217-238 (helper)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)
- mcp_ankiconnect/server.py:471-492 (schema)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. """