Skip to main content
Glama
KazKozDev
by KazKozDev

Undo Last Changes

undo

Reverts recent editing operations in Markdown documents to correct mistakes or restore previous content states.

Instructions

Reverts the last N operations on the document.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
file_pathYes
countNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
successNo
reverted_countNoNumber of operations reverted

Implementation Reference

  • MCP tool registration for 'undo' including input schema (file_path required, count optional) and output schema.
    Tool(
        name="undo",
        title="Undo Last Changes",
        description="Reverts the last N operations on the document.",
        inputSchema={
            "type": "object",
            "properties": {
                "file_path": {"type": "string", "examples": ["./document.md"]},
                "count": {"type": "integer", "default": 1, "examples": [1, 2, 5]},
            },
            "required": ["file_path"],
            "additionalProperties": False,
        },
        outputSchema={
            "type": "object",
            "properties": {
                "success": {"type": "boolean"},
                "reverted_count": {
                    "type": "integer",
                    "description": "Number of operations reverted",
                },
            },
        },
    ),
  • Dispatch logic in MCP server's call_tool method for the 'undo' tool.
    elif name == "undo":
        res = await undo_changes(file_path, arguments.get("count", 1))
        return CallToolResult(
            content=[TextContent(type="text", text="Undo performed")],
            structuredContent=res,
            isError="error" in res,
        )
  • Exported async handler function 'undo_changes' called by the MCP server for 'undo' tool invocations.
    async def undo_changes(file_path: str, count: int = 1):
        return await _instance.undo(file_path, count)
  • EditTool.undo method: handles file locking, invokes Document.undo, performs atomic file write, and manages cache/journal.
    async def undo(self, file_path: str, count: int = 1) -> Dict[str, Any]:
        abs_path = resolve_path(file_path)
        with FileLock(abs_path):
            doc = self.get_doc(file_path)
            result = doc.undo(count)
            if "success" in result:
                try:
                    self._atomic_write(file_path, doc.get_content())
                    self._update_cache_mtime(abs_path)
                    doc.confirm_journal()
                except Exception as e:
                    self.invalidate_cache(file_path)
                    return {"error": f"Failed to write file: {e}"}
        return result
  • Core Document class undo method: reverses the last N journaled operations (replace, delete, insert, metadata) by popping journal and applying inverse actions.
    def undo(self, count: int = 1) -> Dict[str, Any]:
        """Undo last operations"""
        if not self.journal:
            return {"error": "Journal is empty"}
    
        undone = []
        errors = []
    
        for _ in range(min(count, len(self.journal))):
            entry = self.journal.pop()
            success = False
    
            # Apply reverse operation
            if entry.operation == "replace":
                # Prefer ID-based lookup for reliability
                element = None
                if entry.element_id:
                    element = self.find_by_id(entry.element_id)
                if not element:
                    element = self.find_by_path(entry.path)
    
                if element and entry.old_value is not None:
                    element.content = entry.old_value
                    success = True
                else:
                    errors.append(
                        f"Cannot undo replace: element not found at {entry.path}"
                    )
    
            elif entry.operation == "delete":
                # Restore deleted element at its original position
                success = self._restore_element_at_position(entry)
                if not success:
                    errors.append(
                        f"Cannot undo delete: failed to restore element at {entry.path}"
                    )
    
            elif entry.operation in ("insert_after", "insert_before"):
                # Remove the inserted element
                success = self._remove_inserted_element(entry)
                if not success:
                    errors.append(
                        f"Cannot undo {entry.operation}: element not found at {entry.path}"
                    )
    
            elif entry.operation == "update_metadata":
                # Restore old metadata
                if entry.old_value:
                    try:
                        old_metadata = json.loads(entry.old_value)
                        self.metadata = old_metadata
                        success = True
                    except (json.JSONDecodeError, TypeError):
                        errors.append("Cannot undo update_metadata: invalid old value")
                else:
                    errors.append("Cannot undo update_metadata: no old value stored")
    
            if success:
                undone.append(entry.operation)
    
        self._rebuild_raw_content()
        self._save_journal()
    
        result = {"success": True, "undone_operations": undone}
        if errors:
            result["warnings"] = errors
    
        return result
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 of behavioral disclosure. While 'reverts' implies a mutation that changes document state, it doesn't specify whether this is destructive (e.g., irreversible), has side effects (e.g., affects other tools), requires specific permissions, or details error conditions (e.g., what happens if N exceeds available operations). For a mutation tool with zero annotation coverage, this is a significant gap in transparency.

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

Conciseness5/5

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

The description is a single, efficient sentence that front-loads the core action ('reverts') and key parameters ('last N operations'). There is no wasted wording, making it easy to parse quickly while conveying essential information.

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 tool's complexity (a mutation with 2 parameters, no annotations, but with an output schema), the description is minimally adequate. The output schema likely covers return values, reducing the need for that in the description. However, for a tool that modifies document state, more details on behavior, constraints, and usage context would improve completeness, especially with no annotations to fill gaps.

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?

The description adds some meaning by explaining that 'count' refers to 'last N operations,' which clarifies the parameter's purpose beyond the schema's basic type and examples. However, with 0% schema description coverage, it doesn't fully compensate for the lack of details on 'file_path' (e.g., format requirements or path validity) or constraints on 'count' (e.g., maximum value). The baseline is 3 due to partial compensation.

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 verb ('reverts') and resource ('operations on the document'), making the purpose understandable. However, it doesn't explicitly differentiate from sibling tools like 'replace_content' or 'update_metadata' that might also modify documents, leaving some ambiguity about when to use undo versus other modification tools.

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 provides no guidance on when to use this tool versus alternatives. It doesn't mention prerequisites (e.g., requires an open document), exclusions (e.g., cannot undo after saving), or compare to siblings like 'replace_content' for specific edits. This lack of context makes it harder for an agent to choose appropriately.

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/KazKozDev/markdown-editor-mcp-server'

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