Skip to main content
Glama

delete_section

Remove a specific section by ID or heading from a Markdown document. Automatically saves changes if enabled and ensures document integrity with optional backup and validation.

Instructions

Delete a section by ID or heading. The document will be saved after the operation if successful and auto_save is True.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
auto_saveNo
backupNo
document_pathYes
headingNo
section_idNo
validation_levelNoNORMAL

Implementation Reference

  • Primary MCP tool handler for 'delete_section'. Loads document, resolves section by ID or heading, executes deletion via SafeMarkdownEditor.delete_section, and handles saving/backup.
    @self.mcp.tool() def delete_section(document_path: str, section_id: Optional[str] = None, heading: Optional[str] = None, auto_save: bool = True, backup: bool = True, validation_level: str = "NORMAL") -> Dict[str, Any]: """ Delete a section by ID or heading. The document will be saved after the operation if successful and auto_save is True. """ """ Delete a section by ID or heading. Args: document_path: Path to the Markdown file section_id: The section ID to delete (optional) heading: The section heading to delete (optional) auto_save: Whether to automatically save the document backup: Whether to create a backup before saving validation_level: Validation strictness - "STRICT", "NORMAL", or "PERMISSIVE" """ def operation(editor): if section_id: # Find section by ID section_ref = editor.get_section_by_id(section_id) if not section_ref: from .safe_editor_types import EditResult, OperationType return EditResult( success=False, operation=OperationType.DELETE, modified_sections=[], errors=[f"Section with ID '{section_id}' not found"], warnings=[] ) elif heading: # Find section by heading sections = editor.get_sections() matching_sections = [s for s in sections if s.title == heading] if not matching_sections: from .safe_editor_types import EditResult, OperationType return EditResult( success=False, operation=OperationType.DELETE, modified_sections=[], errors=[f"Section with heading '{heading}' not found"], warnings=[] ) section_ref = matching_sections[0] else: from .safe_editor_types import EditResult, OperationType return EditResult( success=False, operation=OperationType.DELETE, modified_sections=[], errors=["Either section_id or heading must be provided"], warnings=[] ) return editor.delete_section(section_ref, preserve_subsections=False) validation_map = {"STRICT": ValidationLevel.STRICT, "NORMAL": ValidationLevel.NORMAL, "PERMISSIVE": ValidationLevel.PERMISSIVE} validation_enum = validation_map.get(validation_level.upper(), ValidationLevel.NORMAL) return self.processor.execute_operation(document_path, operation, auto_save, backup, validation_enum)
  • Core implementation of section deletion logic in SafeMarkdownEditor. Calculates deletion bounds, removes lines, updates parser state, records transaction for rollback.
    def delete_section(self, section_ref: SectionReference, preserve_subsections: bool = False) -> EditResult: """ Delete a section from the document. Args: section_ref: Reference to section to delete preserve_subsections: If True, promote subsections to parent level Returns: EditResult with operation details """ with self._lock: try: # Validate section exists if not self._is_valid_section_reference(section_ref): return EditResult( success=False, operation=EditOperation.DELETE_SECTION, modified_sections=[], errors=[SafeParseError( message=f"Section not found: {section_ref.title}", error_code="SECTION_NOT_FOUND", category=ErrorCategory.VALIDATION, suggestions=["Verify section ID", "Refresh section references"] )], warnings=[] ) # Store rollback data rollback_data = self._current_text # Get current sections current_sections = self.get_sections() # Find section to delete target_section = None for section in current_sections: if section.id == section_ref.id: target_section = section break if not target_section: return EditResult( success=False, operation=EditOperation.DELETE_SECTION, modified_sections=[], errors=[SafeParseError( message="Target section not found in current document", error_code="SECTION_NOT_FOUND", category=ErrorCategory.VALIDATION )], warnings=[] ) # Calculate deletion bounds lines = self._current_text.split('\n') # Find next section at same or higher level to determine end bound delete_end_line = len(lines) for section in current_sections: if (section.line_start > target_section.line_start and section.level <= target_section.level): delete_end_line = section.line_start - 1 break # Simple deletion - remove entire section and subsections new_lines = (lines[:target_section.line_start - 1] + lines[delete_end_line:]) # Update document new_text = '\n'.join(new_lines) self._current_text = new_text self._current_result = self._parser.parse(new_text) self._wrapper = ASTWrapper(self._current_result) # Record transaction operation_dict = { 'operation': EditOperation.DELETE_SECTION, 'section_id': section_ref.id, 'content': "", 'preserve_subsections': preserve_subsections, 'deleted_title': target_section.title } self._record_transaction([operation_dict], rollback_data) # Update version self._version += 1 self._last_modified = datetime.now() return EditResult( success=True, operation=EditOperation.DELETE_SECTION, modified_sections=[section_ref], errors=[], warnings=[], metadata={ 'preserve_subsections': preserve_subsections, 'version': self._version } ) except Exception as e: return EditResult( success=False, operation=EditOperation.DELETE_SECTION, modified_sections=[], errors=[SafeParseError( message=f"Delete operation failed: {str(e)}", error_code="DELETE_ERROR", category=ErrorCategory.SYSTEM )], warnings=[] )
  • Internal simplified handler for delete_section used in call_tool_sync method.
    def _delete_section_impl(self, document_path: str, section_id: str, auto_save: bool = True, backup: bool = True) -> Dict[str, Any]: """Implementation for delete_section tool.""" def operation(editor): section = editor.get_section_by_id(section_id) if not section: return {"success": False, "error": f"Section '{section_id}' not found"} return editor.delete_section(section) validation_enum = ValidationLevel.NORMAL return self.processor.execute_operation(document_path, operation, auto_save, backup, validation_enum)
  • Internal tool registration dictionary mapping 'delete_section' to its implementation for synchronous tool calling.
    tools = { "load_document": self._load_document_impl, "list_sections": self._list_sections_impl, "get_section": self._get_section_impl, "insert_section": self._insert_section_impl, "update_section": self._update_section_impl, "delete_section": self._delete_section_impl, "move_section": self._move_section_impl, "get_document": self._get_document_impl, "save_document": self._save_document_impl, "analyze_document": self._analyze_document_impl, }
  • Alternative/enhanced MCP tool handler for 'delete_section' in enhanced server.
    @self.mcp.tool() def delete_section(document_path: str, section_id: Optional[str] = None, heading: Optional[str] = None, auto_save: bool = True, backup: bool = True, validation_level: str = "NORMAL") -> Dict[str, Any]: """Delete a section (stateless only).""" def operation(editor: SafeMarkdownEditor): if section_id: section = editor.get_section_by_id(section_id) elif heading: sections = editor.get_sections() section = next((s for s in sections if s.title == heading), None) else: from .safe_editor_types import EditResult return EditResult( success=False, operation=EditOperation.DELETE_SECTION, errors=["Either section_id or heading must be provided"] ) if section: return editor.delete_section(section, preserve_subsections=False) else: from .safe_editor_types import EditResult return EditResult( success=False, operation=EditOperation.DELETE_SECTION, errors=["Section not found"] ) validation_map = {"STRICT": ValidationLevel.STRICT, "NORMAL": ValidationLevel.NORMAL, "PERMISSIVE": ValidationLevel.PERMISSIVE} validation_enum = validation_map.get(validation_level.upper(), ValidationLevel.NORMAL) return self.processor.execute_operation(document_path, operation, auto_save, backup, validation_enum)

Other Tools

Related 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/quantalogic/quantalogic_markdown_mcp'

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