Skip to main content
Glama
santoshray02

CSV Editor

by santoshray02

undo

Revert the last change made to your CSV data within the current editing session. Use this action to correct mistakes or restore previous states during data manipulation.

Instructions

Undo the last operation in a session.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
session_idYes

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • Registers the 'undo' MCP tool using @mcp.tool decorator. Provides type hints for input schema (session_id: str) and delegates to implementation.
    @mcp.tool
    async def undo(
        session_id: str,
        ctx: Context = None
    ) -> Dict[str, Any]:
        """Undo the last operation in a session."""
        return await _undo_operation(session_id, ctx)
  • Executes the undo tool logic: retrieves CSV session, invokes session.undo(), wraps result with OperationResult, handles errors and context logging.
    async def undo_operation(
        session_id: str,
        ctx: Context = None
    ) -> Dict[str, Any]:
        """
        Undo the last operation in a session.
        
        Args:
            session_id: Session identifier
            ctx: FastMCP context
            
        Returns:
            Dict with success status and undo result
        """
        try:
            manager = get_session_manager()
            session = manager.get_session(session_id)
            
            if not session:
                return OperationResult(
                    success=False,
                    message="Session not found",
                    error=f"No session with ID: {session_id}"
                ).model_dump()
            
            if ctx:
                await ctx.info(f"Undoing last operation for session {session_id}")
            
            result = await session.undo()
            
            if result["success"]:
                if ctx:
                    await ctx.info(f"Successfully undid operation: {result.get('message')}")
                
                return OperationResult(
                    success=True,
                    message=result["message"],
                    session_id=session_id,
                    data=result
                ).model_dump()
            else:
                return OperationResult(
                    success=False,
                    message="Failed to undo operation",
                    error=result.get("error")
                ).model_dump()
                
        except Exception as e:
            logger.error(f"Error undoing operation: {str(e)}")
            if ctx:
                await ctx.error(f"Failed to undo operation: {str(e)}")
            return OperationResult(
                success=False,
                message="Failed to undo operation",
                error=str(e)
            ).model_dump()
  • CSVSession class undo method: checks history, calls history_manager.undo(), restores dataframe snapshot, triggers auto-save, returns status.
    async def undo(self) -> Dict[str, Any]:
        """Undo the last operation."""
        if not self.history_manager:
            return {"success": False, "error": "History is not enabled"}
        
        if not self.history_manager.can_undo():
            return {"success": False, "error": "No operations to undo"}
        
        try:
            operation, data_snapshot = self.history_manager.undo()
            
            if data_snapshot is not None:
                self.df = data_snapshot
                
                # Trigger auto-save if configured
                if self.auto_save_manager.should_save_after_operation():
                    await self.auto_save_manager.trigger_save(self._save_callback, "undo")
                
                return {
                    "success": True,
                    "message": f"Undid operation: {operation.operation_type}",
                    "operation": operation.to_dict(),
                    "can_undo": self.history_manager.can_undo(),
                    "can_redo": self.history_manager.can_redo()
                }
            else:
                return {
                    "success": False,
                    "error": "No snapshot available for undo"
                }
                
        except Exception as e:
            logger.error(f"Error during undo: {str(e)}")
            return {"success": False, "error": str(e)}
  • Core HistoryManager.undo(): shifts current operation to redo stack, decrements history index, locates and returns prior data snapshot for restoration.
    def undo(self) -> Tuple[Optional[OperationHistory], Optional[pd.DataFrame]]:
        """Undo the last operation and return the previous state."""
        if not self.can_undo():
            return None, None
        
        # Move current operation to redo stack
        current_op = self.history[self.current_index]
        self.redo_stack.append(current_op)
        
        # Move index back
        self.current_index -= 1
        
        # Find the most recent snapshot before current position
        snapshot = None
        for i in range(self.current_index, -1, -1):
            if self.history[i].data_snapshot is not None:
                snapshot = self.history[i].data_snapshot.copy()
                break
        
        # Save state
        if self.storage_type != HistoryStorage.MEMORY:
            self._save_history()
        
        logger.info(f"Undid operation: {current_op.operation_type}")
        
        # Return the operation that was undone and the data to restore
        return current_op, snapshot
Behavior2/5

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

With no annotations provided, the description carries full burden but only states the basic action. It doesn't disclose behavioral traits such as whether undo is reversible, what happens if no operations exist, if it affects data permanently, or error conditions. This leaves significant gaps for a mutation tool.

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, clear sentence with no wasted words. It's front-loaded with the core action and context, making it easy to parse quickly.

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 (mutation with no annotations), the description is minimal. It states what it does but lacks details on behavior, parameters, or output. The presence of an output schema helps, but the description doesn't leverage it to explain return values or completion signals.

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 description doesn't mention parameters, but with only one parameter (session_id) and 0% schema description coverage, it implicitly suggests context without adding details. Since parameter count is low (1), the baseline is high, but it doesn't explain what 'session_id' represents or where to get it.

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 ('undo') and target ('last operation in a session'), making the purpose understandable. However, it doesn't explicitly differentiate from sibling 'redo' or 'restore_to_operation', which would require more specific language about scope or limitations.

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 like 'redo', 'clear_history', or 'restore_to_operation'. It mentions 'session' context but doesn't specify prerequisites, limitations, or typical scenarios for invocation.

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/santoshray02/csv-editor'

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