Skip to main content
Glama

insert_section

Add a new section with heading and content at a specific position in a Markdown document. Automatically saves the document after insertion when enabled.

Instructions

        Insert a new section at a specified location.
        The document will be saved after the operation if successful and auto_save is True.
        

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
document_pathYes
headingYes
contentYes
positionYes
auto_saveNo
backupNo
validation_levelNoNORMAL

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • Primary MCP tool handler and registration for 'insert_section'. Accepts document_path, heading, content, position, and delegates to SafeMarkdownEditor.insert_section_after via stateless processor.
    @self.mcp.tool()
    def insert_section(document_path: str, heading: str, content: str, position: int,
                      auto_save: bool = True, backup: bool = True,
                      validation_level: str = "NORMAL") -> Dict[str, Any]:
        """
        Insert a new section at a specified location.
        The document will be saved after the operation if successful and auto_save is True.
        """
        """
        Insert a new section at a specified location.
        
        Args:
            document_path: Path to the Markdown file
            heading: The section heading/title
            content: The section content
            position: Position to insert (0-based index)
            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):
            sections = editor.get_sections()
            
            if position == 0 or not sections:
                if sections:
                    after_section = sections[0]
                    return editor.insert_section_after(
                        after_section=after_section,
                        level=2,
                        title=heading,
                        content=content
                    )
                else:
                    # Handle empty document case
                    from .safe_editor_types import EditResult, OperationType
                    return EditResult(
                        success=False,
                        operation=OperationType.INSERT,
                        modified_sections=[],
                        errors=["Cannot insert into empty document"],
                        warnings=[]
                    )
            else:
                if position-1 < len(sections):
                    after_section = sections[position-1]
                    return editor.insert_section_after(
                        after_section=after_section,
                        level=2,
                        title=heading,
                        content=content
                    )
                else:
                    from .safe_editor_types import EditResult, OperationType
                    return EditResult(
                        success=False,
                        operation=OperationType.INSERT,
                        modified_sections=[],
                        errors=[f"Position {position} is out of range"],
                        warnings=[]
                    )
        
        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)
  • Variant MCP tool handler for 'insert_section' in enhanced server, similar to primary but with slight differences in error handling.
    def insert_section(document_path: str, heading: str, content: str, position: int,
                      auto_save: bool = True, backup: bool = True,
                      validation_level: str = "NORMAL") -> Dict[str, Any]:
        """Insert a new section (stateless only)."""
        def operation(editor: SafeMarkdownEditor):
            sections = editor.get_sections()
            if position == 0 or not sections:
                if sections:
                    after_section = sections[0]
                    return editor.insert_section_after(
                        after_section=after_section,
                        level=2,
                        title=heading,
                        content=content
                    )
                else:
                    from .safe_editor_types import EditResult
                    return EditResult(
                        success=False,
                        operation=EditOperation.INSERT_SECTION,
                        errors=["Cannot insert into empty document"]
                    )
            else:
                if position-1 < len(sections):
                    after_section = sections[position-1]
                    return editor.insert_section_after(
                        after_section=after_section,
                        level=2,
                        title=heading,
                        content=content
                    )
                else:
                    from .safe_editor_types import EditResult
                    return EditResult(
                        success=False,
                        operation=EditOperation.INSERT_SECTION,
                        errors=[f"Position {position} is out of range"]
                    )
        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 helper method implementing the section insertion logic by validating parameters, previewing changes, creating transactions for rollback, manipulating document lines, and updating parser state.
    def insert_section_after(self, 
                           after_section: SectionReference,
                           level: int,
                           title: str,
                           content: str = "",
                           auto_adjust_level: bool = True) -> EditResult:
        """
        Insert new section after specified section.
        
        Args:
            after_section: Reference section for insertion point
            level: Heading level for new section (1-6)
            title: Section title (plain text)
            content: Section content (markdown)
            auto_adjust_level: Auto-adjust level to maintain hierarchy
            
        Returns:
            EditResult with new section reference in modified_sections
        """
        with self._lock:
            try:
                # Validate parameters
                if not (1 <= level <= 6):
                    return EditResult(
                        success=False,
                        operation=EditOperation.INSERT_SECTION,
                        modified_sections=[],
                        errors=[SafeParseError(
                            message=f"Invalid heading level: {level}. Must be between 1 and 6.",
                            error_code="INVALID_LEVEL",
                            category=ErrorCategory.VALIDATION,
                            suggestions=["Use a heading level between 1 and 6"]
                        )],
                        warnings=[]
                    )
                
                if not title.strip():
                    return EditResult(
                        success=False,
                        operation=EditOperation.INSERT_SECTION,
                        modified_sections=[],
                        errors=[SafeParseError(
                            message="Section title cannot be empty",
                            error_code="EMPTY_TITLE",
                            category=ErrorCategory.VALIDATION,
                            suggestions=["Provide a non-empty title for the section"]
                        )],
                        warnings=[]
                    )
                
                # Auto-adjust level if requested
                if auto_adjust_level:
                    # Ensure the new section level makes sense in context
                    child_sections = self.get_child_sections(after_section)
                    if child_sections:
                        # If after_section has children, insert at child level
                        level = max(after_section.level + 1, min(s.level for s in child_sections))
                    else:
                        # No children, use level one below parent
                        level = min(level, after_section.level + 1)
                
                # Preview the operation first
                preview_result = self.preview_operation(
                    EditOperation.INSERT_SECTION,
                    after_section=after_section,
                    level=level,
                    title=title,
                    content=content
                )
                
                if not preview_result.success:
                    return preview_result
                
                # Create transaction
                transaction = self._create_transaction([{
                    'operation': EditOperation.INSERT_SECTION,
                    'after_section': after_section,
                    'level': level,
                    'title': title,
                    'content': content,
                    'auto_adjust_level': auto_adjust_level
                }])
                
                # Apply the changes
                lines = self._current_text.split('\n')
                insert_line = after_section.line_end + 1
                
                # Create new section lines
                new_section_lines = [
                    f"{'#' * level} {title}",
                    "",
                    content,
                    ""
                ]
                
                # Insert the new section
                new_lines = (lines[:insert_line] + 
                           new_section_lines + 
                           lines[insert_line:])
                
                # Update state
                self._current_text = '\n'.join(new_lines)
                self._current_result = self._parser.parse(self._current_text)
                self._wrapper = ASTWrapper(self._current_result)
                self._last_modified = datetime.now()
                self._version += 1
                
                # Add transaction to history
                self._transaction_history.append(transaction)
                self._trim_transaction_history()
                
                # Find the newly created section
                updated_sections = self._build_section_references()
                new_section = None
                for section in updated_sections:
                    if (section.title == title and 
                        section.level == level and 
                        section.line_start >= insert_line):
                        new_section = section
                        break
                
                return EditResult(
                    success=True,
                    operation=EditOperation.INSERT_SECTION,
                    modified_sections=[new_section] if new_section else [],
                    errors=[],
                    warnings=[],
                    metadata={
                        'transaction_id': transaction.transaction_id,
                        'version': self._version,
                        'auto_adjusted_level': auto_adjust_level,
                        'final_level': level
                    }
                )
                
            except Exception as e:
                return EditResult(
                    success=False,
                    operation=EditOperation.INSERT_SECTION,
                    modified_sections=[],
                    errors=[SafeParseError(
                        message=f"Insert section operation failed: {str(e)}",
                        error_code="INSERT_ERROR",
                        category=ErrorCategory.SYSTEM
                    )],
                    warnings=[]
                )
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It mentions the auto-save behavior, which is useful, but fails to cover critical aspects like required permissions, error handling, what happens if the position is invalid, or whether the operation is reversible. For a mutation tool with 7 parameters, this leaves significant gaps in understanding its behavior.

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 brief and front-loaded with the main action, consisting of two sentences. However, the second sentence about auto-save could be more integrated, and overall it lacks the depth needed for a tool with 7 parameters, making it somewhat under-specified rather than optimally concise.

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

Completeness2/5

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

Given the complexity (7 parameters, no annotations, but with an output schema), the description is incomplete. It doesn't address key contextual elements like what a 'section' entails, how 'position' is determined, or the implications of 'validation_level'. The presence of an output schema mitigates the need to describe return values, but other gaps remain significant.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters2/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 by explaining parameters. It only references 'auto_save' indirectly, without detailing what it does or how it interacts with other parameters like 'backup' or 'validation_level'. The core parameters (document_path, heading, content, position) are not explained at all, leaving their purpose and format unclear.

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 action ('Insert a new section') and the target ('at a specified location'), which distinguishes it from sibling tools like 'delete_section' or 'update_section'. However, it doesn't specify what kind of document or system it operates on, leaving some ambiguity about the resource context.

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 mentions that the document is saved if 'auto_save is True', which provides some operational context, but it doesn't explain when to use this tool versus alternatives like 'update_section' or 'move_section'. No explicit guidance on prerequisites or exclusions is provided.

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

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