Skip to main content
Glama

delete_block

Remove a block from a Mnemosyne knowledge graph document by its ID, with an option to delete all related child blocks in a cascade operation.

Instructions

Delete a block by its ID. Use cascade=true to also delete all subsequent blocks with higher indent (indent-based children). Returns the list of deleted block IDs.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
graph_idYes
document_idYes
block_idYes
cascadeNo

Implementation Reference

  • The MCP tool handler for 'delete_block', including the @server.tool decorator that registers it. Handles authentication, input validation, document connection, transaction-based deletion via helper, and structured response.
    @server.tool(
        name="delete_block",
        title="Delete Block",
        description=(
            "Delete a block by its ID. Use cascade=true to also delete all subsequent blocks "
            "with higher indent (indent-based children). Returns the list of deleted block IDs."
        ),
    )
    async def delete_block_tool(
        graph_id: str,
        document_id: str,
        block_id: str,
        cascade: bool = False,
        context: Context | None = None,
    ) -> dict:
        """Delete a block and optionally its indent-children.
    
        Args:
            graph_id: The graph containing the document
            document_id: The document containing the block
            block_id: The block to delete
            cascade: If True, also delete indent-children
        """
        auth = MCPAuthContext.from_context(context)
        auth.require_auth()
    
        if not graph_id or not graph_id.strip():
            raise ValueError("graph_id is required")
        if not document_id or not document_id.strip():
            raise ValueError("document_id is required")
        if not block_id or not block_id.strip():
            raise ValueError("block_id is required")
    
        try:
            await hp_client.connect_document(graph_id.strip(), document_id.strip())
    
            deleted_ids: list[str] = []
    
            def perform_delete(doc: Any) -> None:
                nonlocal deleted_ids
                writer = DocumentWriter(doc)
                deleted_ids = writer.delete_block_by_id(
                    block_id.strip(), cascade_children=cascade
                )
    
            await hp_client.transact_document(
                graph_id.strip(),
                document_id.strip(),
                perform_delete,
            )
    
            result = {
                "success": True,
                "graph_id": graph_id.strip(),
                "document_id": document_id.strip(),
                "deleted_block_ids": deleted_ids,
                "cascade": cascade,
            }
            return result
    
        except Exception as e:
            logger.error(
                "Failed to delete block",
                extra_context={
                    "graph_id": graph_id,
                    "document_id": document_id,
                    "block_id": block_id,
                    "error": str(e),
                },
            )
            raise RuntimeError(f"Failed to delete block: {e}")
  • Core implementation of block deletion in DocumentWriter class, supporting optional cascade deletion of subsequent higher-indent child blocks. Called by the tool handler.
    def delete_block_by_id(self, block_id: str, cascade_children: bool = False) -> list[str]:
        """Delete a block by its ID, optionally cascading to indent-children.
    
        Args:
            block_id: The block ID to delete
            cascade_children: If True, also delete all subsequent blocks with
                             higher indent (indent-based children)
    
        Returns:
            List of deleted block IDs.
    
        Raises:
            ValueError: If block not found.
        """
        result = self.find_block_by_id(block_id)
        if result is None:
            raise ValueError(f"Block not found: {block_id}")
    
        index, elem = result
        deleted_ids = [block_id]
    
        fragment = self.get_content_fragment()
    
        with self._doc.transaction():
            if cascade_children:
                # Find children by indent
                parent_indent = _get_attr_safe(elem.attributes, "indent", 0)
                if isinstance(parent_indent, str):
                    try:
                        parent_indent = int(parent_indent)
                    except ValueError:
                        parent_indent = 0
    
                children = list(fragment.children)
                # Collect indices to delete (in reverse order to maintain positions)
                indices_to_delete = [index]
    
                for i in range(index + 1, len(children)):
                    child = children[i]
                    if not hasattr(child, "attributes"):
                        break
                    child_indent = _get_attr_safe(child.attributes, "indent", 0)
                    if isinstance(child_indent, str):
                        try:
                            child_indent = int(child_indent)
                        except ValueError:
                            child_indent = 0
    
                    if child_indent <= parent_indent:
                        break  # No longer a child
    
                    indices_to_delete.append(i)
                    child_id = _get_attr_safe(child.attributes, "data-block-id", None)
                    if child_id:
                        deleted_ids.append(child_id)
    
                # Delete in reverse order to maintain indices
                for idx in reversed(indices_to_delete):
                    del fragment.children[idx]
            else:
                del fragment.children[index]
    
        return deleted_ids
  • The @server.tool decorator registers the delete_block tool with the MCP server, defining its name, title, description (input/output schema), and handler function.
    @server.tool(
        name="delete_block",
        title="Delete Block",
        description=(
            "Delete a block by its ID. Use cascade=true to also delete all subsequent blocks "
            "with higher indent (indent-based children). Returns the list of deleted block IDs."
        ),
    )
    async def delete_block_tool(
        graph_id: str,
        document_id: str,
        block_id: str,
        cascade: bool = False,
        context: Context | None = None,
    ) -> dict:
        """Delete a block and optionally its indent-children.
    
        Args:
            graph_id: The graph containing the document
            document_id: The document containing the block
            block_id: The block to delete
            cascade: If True, also delete indent-children
        """
        auth = MCPAuthContext.from_context(context)
        auth.require_auth()
    
        if not graph_id or not graph_id.strip():
            raise ValueError("graph_id is required")
        if not document_id or not document_id.strip():
            raise ValueError("document_id is required")
        if not block_id or not block_id.strip():
            raise ValueError("block_id is required")
    
        try:
            await hp_client.connect_document(graph_id.strip(), document_id.strip())
    
            deleted_ids: list[str] = []
    
            def perform_delete(doc: Any) -> None:
                nonlocal deleted_ids
                writer = DocumentWriter(doc)
                deleted_ids = writer.delete_block_by_id(
                    block_id.strip(), cascade_children=cascade
                )
    
            await hp_client.transact_document(
                graph_id.strip(),
                document_id.strip(),
                perform_delete,
            )
    
            result = {
                "success": True,
                "graph_id": graph_id.strip(),
                "document_id": document_id.strip(),
                "deleted_block_ids": deleted_ids,
                "cascade": cascade,
            }
            return result
    
        except Exception as e:
            logger.error(
                "Failed to delete block",
                extra_context={
                    "graph_id": graph_id,
                    "document_id": document_id,
                    "block_id": block_id,
                    "error": str(e),
                },
            )
            raise RuntimeError(f"Failed to delete block: {e}")
    
    # -------------------------------------------------------------------------

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/sophia-labs/mnemosyne-mcp'

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