Skip to main content
Glama

update_claudemd

Update CLAUDE.md file with learned user preferences by creating a backup first, then applying detected patterns from repeated corrections to maintain consistent AI configuration standards.

Instructions

Update CLAUDE.md file with learned preferences (creates backup first)

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
file_pathYesPath to CLAUDE.md file
min_confidenceNoMinimum confidence threshold
project_pathNoProject path for project-specific content (optional)

Implementation Reference

  • Main handler for 'update_claudemd' tool: performs security validation on file paths, audits the operation, calls ClaudeMdManager to update the file, logs the episode if successful.
    async def _update_claudemd(
        self, file_path: str, project_path: Optional[str] = None, min_confidence: float = 0.7
    ) -> Dict[str, Any]:
        """Update CLAUDE.md file with learned preferences"""
        try:
            file_path_obj = Path(file_path).resolve()
    
            # Security: Explicit path whitelist
            allowed_dirs = [
                Path.cwd(),  # Current working directory
                Path.home() / ".claude",  # Global Claude config
                Path.home(),  # User home (for any project)
            ]
    
            # Check if path is within allowed directories
            is_allowed = any(
                file_path_obj.is_relative_to(allowed_dir)
                for allowed_dir in allowed_dirs
            )
    
            if not is_allowed:
                # Audit failed attempt
                self._audit_log(
                    action="update_claudemd",
                    target_type="file",
                    target_path=str(file_path_obj),
                    details="Path not in whitelist",
                    success=False
                )
                return {
                    "success": False,
                    "error": f"Path not in allowed directories. File must be in: {', '.join(str(d) for d in allowed_dirs)}"
                }
    
            # Additional check: Only allow CLAUDE.md or .claude.md files
            allowed_names = ["CLAUDE.md", "CLAUDE.local.md", ".claude.md"]
            if file_path_obj.name not in allowed_names:
                # Audit failed attempt
                self._audit_log(
                    action="update_claudemd",
                    target_type="file",
                    target_path=str(file_path_obj),
                    details=f"Invalid filename: {file_path_obj.name}",
                    success=False
                )
                return {
                    "success": False,
                    "error": f"Only {', '.join(allowed_names)} files can be updated. Got: {file_path_obj.name}"
                }
    
            # Update the file
            success, message = self.claudemd_manager.update_claudemd_file(
                file_path_obj,
                project_path=project_path,
                min_confidence=min_confidence
            )
    
            # Audit the update attempt
            self._audit_log(
                action="update_claudemd",
                target_type="file",
                target_path=str(file_path_obj),
                details=f"min_confidence={min_confidence}, project_path={project_path or 'global'}",
                success=success
            )
    
            if success:
                # Store in memory that we updated CLAUDE.md
                await self._add_episode(
                    name=f"CLAUDE.md Updated - {file_path_obj.name}",
                    content=f"Updated {file_path} with learned preferences (min confidence: {min_confidence})",
                    source="claudemd_update"
                )
    
            return {
                "success": success,
                "message": message,
                "file_path": str(file_path_obj),
                "project_path": project_path or "global"
            }
        except Exception as e:
            # Audit exception
            self._audit_log(
                action="update_claudemd",
                target_type="file",
                target_path=file_path,
                details=f"Exception: {str(e)}",
                success=False
            )
            return {"success": False, "error": str(e)}
  • Tool registration in list_tools(), including name, description, and input schema definition.
    Tool(
        name="update_claudemd",
        description="Update CLAUDE.md file with learned preferences (creates backup first)",
        inputSchema={
            "type": "object",
            "properties": {
                "file_path": {"type": "string", "description": "Path to CLAUDE.md file"},
                "project_path": {"type": "string", "description": "Project path for project-specific content (optional)"},
                "min_confidence": {"type": "number", "description": "Minimum confidence threshold", "default": 0.7},
            },
            "required": ["file_path"],
        },
    ),
  • Input schema validation for the 'update_claudemd' tool parameters.
        "properties": {
            "file_path": {"type": "string", "description": "Path to CLAUDE.md file"},
            "project_path": {"type": "string", "description": "Project path for project-specific content (optional)"},
            "min_confidence": {"type": "number", "description": "Minimum confidence threshold", "default": 0.7},
        },
        "required": ["file_path"],
    },
  • Core helper function that generates CLAUDE.md content from database preferences, performs smart merging with existing file content, creates backups, and preserves manual edits.
    def update_claudemd_file(
        self,
        file_path: Path,
        project_path: Optional[str] = None,
        min_confidence: float = 0.7
    ) -> Tuple[bool, str]:
        """
        Update CLAUDE.md file with learned preferences
    
        Performs smart merging:
        1. Preserves manual edits
        2. Updates auto-generated sections
        3. Handles conflicts gracefully
    
        Args:
            file_path: Path to CLAUDE.md file
            project_path: Project path for project-specific file
            min_confidence: Minimum confidence for inclusion
    
        Returns:
            (success, message) tuple
        """
        # Generate new content
        new_content = self.generate_claudemd_content(project_path, min_confidence)
    
        # Check if file exists
        if not file_path.exists():
            # Create new file
            file_path.parent.mkdir(parents=True, exist_ok=True)
            file_path.write_text(new_content)
            return (True, f"Created {file_path}")
    
        # File exists - smart merge
        existing_content = file_path.read_text()
    
        # Check for manual edits marker
        if "<!-- MANUAL EDITS BELOW -->" in existing_content:
            # Preserve everything after the marker
            manual_section = existing_content.split("<!-- MANUAL EDITS BELOW -->")[1]
            merged_content = new_content + "\n<!-- MANUAL EDITS BELOW -->\n" + manual_section
        else:
            # No manual edits marker - append manual edits warning
            merged_content = (
                new_content +
                "\n<!-- MANUAL EDITS BELOW -->\n"
                "<!-- Your manual edits will be preserved below this line -->\n\n"
                + self._extract_manual_sections(existing_content, new_content)
            )
    
        # Write merged content
        # Create backup first
        backup_path = file_path.with_suffix(f".{datetime.now().strftime('%Y%m%d_%H%M%S')}.bak")
        backup_path.write_text(existing_content)
    
        file_path.write_text(merged_content)
    
        return (True, f"Updated {file_path} (backup: {backup_path})")
Behavior3/5

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

With no annotations, the description carries the full burden. It discloses a key behavioral trait ('creates backup first'), which is valuable for safety. However, it doesn't cover other important aspects like whether the update is reversible, potential side effects, or error handling, leaving 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, efficient sentence that front-loads the core purpose and includes a critical behavioral detail ('creates backup first') without any wasted words. Every part earns its place.

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?

For a mutation tool with no annotations and no output schema, the description is minimally adequate. It covers the basic action and a safety feature (backup), but lacks details on return values, error conditions, or integration with sibling tools, leaving room for improvement given the complexity.

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?

Schema description coverage is 100%, so the schema fully documents all parameters. The description adds no additional meaning about parameters beyond what's in the schema, such as explaining how 'min_confidence' or 'project_path' relate to the update process. Baseline 3 is appropriate.

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 ('Update CLAUDE.md file') and purpose ('with learned preferences'), and mentions a key behavioral detail ('creates backup first'). It doesn't explicitly differentiate from sibling tools like 'suggest_claudemd_update' or 'export_to_markdown', but the core purpose is well-defined.

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?

No guidance on when to use this tool versus alternatives like 'suggest_claudemd_update' or 'get_learned_preferences' is provided. The description implies usage for updating preferences but lacks context on prerequisites, timing, or exclusions.

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/airmcp-com/mcp-standards'

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