Skip to main content
Glama

undo

Restore previous file states by removing the latest checkpoint from the undo stack. Call repeatedly to revert multiple changes and recover earlier versions.

Instructions

Undo the last checkpoint (pops from stack and restores files). Each call removes the latest checkpoint from the stack. To undo multiple changes, call this function repeatedly until the desired state is reached.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • Core handler function that executes the undo logic: pops the latest checkpoint from the stack, restores modified files to their previous state, removes newly created files, manages errors by pushing back the checkpoint if partial failure, and returns detailed success/failure info.
    async undo(): Promise<{
      success: boolean;
      message?: string;
      restoredFiles?: string[];
      description?: string;
    }> {
      // Deduplicate checkpoints before proceeding
      this.deduplicateCheckpoints();
      
      if (this.undoStack.length === 0) {
        return { success: false, message: "No checkpoints to undo" };
      }
    
      const checkpoint = this.undoStack.pop()!;
      const restoredFiles: string[] = [];
      const errors: string[] = [];
    
      console.error(`[DEBUG] Starting undo for checkpoint: ${checkpoint.description}`);
      console.error(`[DEBUG] Files to restore: ${Array.from(checkpoint.files.keys()).join(', ')}`);
      console.error(`[DEBUG] Files to remove: ${Array.from(checkpoint.createdFiles).join(', ') || 'none'}`);
    
      try {
        // First, restore existing files
        for (const [filepath, content] of checkpoint.files.entries()) {
          try {
            console.error(`[DEBUG] Restoring file: ${filepath}`);
            console.error(`[DEBUG] Content length: ${content.length}`);
            
            // If file doesn't exist, it was deleted - restore it
            const wasDeleted = !existsSync(filepath);
            if (wasDeleted) {
              console.error(`[DEBUG] File was deleted, restoring: ${filepath}`);
              // Ensure directory exists before creating file
              const dir = dirname(filepath);
              if (!existsSync(dir)) {
                mkdirSync(dir, { recursive: true });
              }
            }
            
            writeFileSync(filepath, content, "utf-8");
            restoredFiles.push(wasDeleted ? `${filepath} (restored from deletion)` : filepath);
            console.error(`[DEBUG] Successfully restored: ${filepath}`);
          } catch (fileError) {
            const errorMsg = `Failed to restore ${filepath}: ${fileError}`;
            errors.push(errorMsg);
            console.error(`[DEBUG] Error restoring ${filepath}:`, fileError);
            console.error(`[DEBUG] Full error details:`, {
              filepath,
              contentLength: content.length,
              fileExists: existsSync(filepath),
              dirExists: existsSync(dirname(filepath)),
              error: fileError
            });
          }
        }
    
        // Then, remove files that were created (undo file creation)
        for (const filepath of checkpoint.createdFiles) {
          try {
            console.error(`[DEBUG] Removing created file: ${filepath}`);
            
            if (existsSync(filepath)) {
              unlinkSync(filepath);
              restoredFiles.push(`${filepath} (deleted)`);
              console.error(`[DEBUG] Successfully removed: ${filepath}`);
            } else {
              console.error(`[DEBUG] Created file ${filepath} already doesn't exist`);
            }
          } catch (fileError) {
            errors.push(`Failed to remove created file ${filepath}: ${fileError}`);
            console.error(`[DEBUG] Error removing ${filepath}:`, fileError);
          }
        }
    
        if (errors.length > 0) {
          // Put checkpoint back if any files failed
          this.undoStack.push(checkpoint);
          return {
            success: false,
            message: `Some files failed to restore: ${errors.join('; ')}`,
          };
        }
    
        console.error(`[DEBUG] Undo completed successfully. Restored ${restoredFiles.length} files`);
        return {
          success: true,
          restoredFiles,
          description: checkpoint.description,
        };
      } catch (error) {
        // Put checkpoint back if restore failed
        this.undoStack.push(checkpoint);
        console.error(`[DEBUG] Undo failed with error:`, error);
        return {
          success: false,
          message: `Failed to restore checkpoint: ${error}`,
        };
      }
    }
  • src/index.ts:45-52 (registration)
    Tool registration entry in the TOOLS array, including name, description, and empty input schema. This is returned by listTools.
    {
      name: "undo",
      description: "Undo the last checkpoint (pops from stack and restores files). Each call removes the latest checkpoint from the stack. To undo multiple changes, call this function repeatedly until the desired state is reached.",
      inputSchema: {
        type: "object",
        properties: {},
      },
    },
  • MCP CallToolRequestSchema handler case for 'undo': calls changeTracker.undo() and formats the text response for the MCP protocol.
    case "undo": {
      const result = await changeTracker.undo();
      return {
        content: [
          {
            type: "text",
            text: result.success
              ? `✅ Undone: "${result.description}"\nRestored files:\n${result.restoredFiles?.map(f => `  - ${f}`).join('\n')}`
              : result.message || "Failed to undo",
          },
        ],
      };
    }
  • TypeScript interface defining the structure of each undo checkpoint stored in the stack, used by the undo handler.
    interface UndoCheckpoint {
      files: Map<string, string>; // filepath -> content
      createdFiles: Set<string>; // files that were created (didn't exist before)
      timestamp: Date;
      description: string;
    }
Behavior4/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 effectively describes the tool's behavior: it's a destructive operation (removes from stack, restores files), operates on a stack-based checkpoint system, and requires repeated calls for multiple undos. It doesn't mention error cases (e.g., what happens if the stack is empty) or side effects, but covers core behavior well.

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 highly concise and well-structured: two sentences that front-load the core action ('undo the last checkpoint') followed by operational details. Every sentence earns its place by explaining how it works and how to use it for multiple undos, with zero wasted words.

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

Completeness4/5

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

Given the tool's complexity (destructive undo operation), lack of annotations, and no output schema, the description is mostly complete. It explains what the tool does, how to use it, and the stack mechanism. It could improve by mentioning error handling (e.g., empty stack) or what 'restores files' entails, but it's sufficient for an agent to use it correctly.

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

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The input schema has 0 parameters with 100% coverage, so the baseline is 4. The description adds no parameter-specific information (as there are none), which is appropriate. It does imply the tool operates on an implicit stack state, but this is behavioral rather than parameter semantics.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the specific action ('undo the last checkpoint'), the mechanism ('pops from stack and restores files'), and distinguishes it from siblings like 'checkpoint' (which creates checkpoints) and 'list_undos' (which lists them). It goes beyond just restating the tool name by explaining the stack-based behavior.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description explicitly provides usage guidance: 'Each call removes the latest checkpoint from the stack' and 'To undo multiple changes, call this function repeatedly until the desired state is reached.' This tells the agent exactly how to use it versus alternatives (like calling multiple times vs. other tools).

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/khalilbalaree/undo-mcp'

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