wcgw Documentation

repository·main·Indexed 20 days ago

https://github.com/rusiaaman/wcgw

A shell and coding agent for Claude and other MCP clients. wcgw implements a Model Context Protocol (MCP) server providing tools for bash execution, diff-based file editing using search-replace blocks, and repository exploration. It features operational modes (wcgw, architect, code_writer) to restrict agent capabilities, a Knowledge Transfer (KT) system for task resumption, and utilities for managing directory trees and file statistics.

Tokens
5.8K
Snippets
16
Records
26
Agent score
71%

What's inside wcgw

  1. Format search-replace blocks for file editing

    main

    To perform search-and-replace edits on a file, you must provide blocks of text using a specific marker syntax. Each block must follow this sequence on separate lines:

    1. A <<<<<<< SEARCH marker.
    2. The exact lines of text you want to find.
    3. A ======= divider.
    4. The new lines of text to replace them with.
    5. A >>>>>>> REPLACE marker.

    If the markers are not in the correct sequence or are missing, a SearchReplaceSyntaxError will be raised.

    <<<<<<< SEARCH
        example old
    =======
        example new
    >>>>>>> REPLACE
  2. Configure CodeWriterMode permissions

    main

    When using the code_writer mode, you must define the scope of allowed file edits and shell commands.

    • allowed_globs: A list of glob patterns for files the agent can edit, or the literal string 'all' to permit all files.
    • allowed_commands: A list of command patterns the agent can execute, or the literal string 'all' to permit all commands.

    Note: If you provide a list containing only the string ['all'], it is automatically normalized to the literal 'all'.

  3. Configure Agent Operational Modes

    main

    The wcgw agent operates in different modes that restrict its capabilities (bash execution, file editing, and file writing). You can configure these via ModesConfig.

    Available Modes

    • wcgw: The standard mode. Allows normal bash execution, file editing, and writing to all files.
    • architect: A read-only mode. Restricts bash to restricted_mode, and prohibits all file editing and writing. Designed for repository exploration.
    • code_writer: A customizable mode. By default, it behaves like wcgw, but allows for granular restrictions on which files can be edited or written to using glob patterns.

    Mode Configuration via modes_to_state

    You can convert a mode configuration into the internal state used by the agent. If you provide a string (e.g., "architect"), it uses the default settings for that mode. If you provide a ModesConfig object, it treats it as a customized code_writer mode.

    # Example of how modes are structured conceptually
    # Using 'architect' mode
    # bash_mode: "restricted_mode", allowed_commands: "all"
    # file_edit_mode: allowed_globs: []
    # write_if_empty_mode: allowed_globs: []
    
    # Using a custom 'code_writer' mode via ModesConfig
    # (Assuming ModesConfig is imported and available)
    # mode_config = ModesConfig(allowed_globs=["src/**/*.py"], allowed_commands=["pytest"])
    # bash_cmd, edit_mode, write_mode, mode_name = modes_to_state(mode_config)
  4. Use Knowledge Transfer (KT) for Task Resumption

    main

    The agent uses the ContextSave tool to perform a Knowledge Transfer (KT), which allows a task to be paused and resumed later. The format of the KT description depends on the active mode.

    KT Formats

    • wcgw / code_writer mode: Focuses on technical implementation details. The description must include:
      • # Objective
      • # All user instructions
      • # Current status of the task
      • # Pending issues with snippets (errors, tracebacks, etc.)
      • # Build and development instructions
    • architect mode: Focuses on design and exploration. The description must include:
      • # Objective
      • # All user instructions
      • # Designed plan

    Resuming a Task

    Once a KT is completed, the agent provides a task ID and a file path. You can resume the session by asking: "Resume wcgw task <generated id>".

  5. Use wcgw as an MCP Server

    main

    The wcgw project implements a Model Context Protocol (MCP) server that provides tools and prompts to an AI client (like Claude Desktop). The server runs using stdio transport, communicating via standard input and output streams.

    When running the server, it initializes a BashState which manages a sandboxed environment (typically in a temporary directory) where tools are executed. You can provide custom instructions to the server via the WCGW_SERVER_INSTRUCTIONS environment variable.

    # The server is designed to be run via an MCP client.
    # It uses stdio for communication.
    # You can configure behavior using environment variables:
    
    export WCGW_SERVER_INSTRUCTIONS="Your custom instructions here"
    
    # Then start the server (typically via your MCP client configuration)
    # e.g., in Claude Desktop config:
    # "mcpServers": {
    #   "wcgw": {
    #     "command": "python",
    #     "args": ["-m", "wcgw.client.mcp_server.server"]
    #   }
    # }
  6. Configure wcgw via WCGW_SERVER_INSTRUCTIONS

    main

    You can inject custom instructions into the server's tool outputs by setting the WCGW_SERVER_INSTRUCTIONS environment variable.

    When a tool call results in an Initialize type operation, the server will append these custom instructions, followed by a hardcoded safety note, to the tool's output. This ensures the AI model receives your specific constraints or guidance alongside the tool execution results.

  7. Handle SearchReplaceMatchError during file edits

    main

    When performing diff-based file edits, a SearchReplaceMatchError is raised if the search/replace blocks cannot be applied. This error provides specific recommendations to resolve the failure:

    • Retry immediately with the same percentage_to_change using search/replace blocks that fix the reported error.
    • Re-read the file to ensure your search blocks account for recent changes made by the user.

    If the error occurred because the file content changed, you must update your search blocks to match the current state of the file.

    raise SearchReplaceMatchError("message")
  8. Troubleshoot ambiguous search-replace matches

    main

    If a search-replace block matches multiple locations in a file, the system will raise a SearchReplaceMatchError. This is a safety mechanism to prevent incorrect edits.

    Common Error Scenarios:

    • Ambiguous Match: The error message will explicitly show the block that matched more than once and suggest adding more context (lines before or after the block) to make the match unique.
    • Syntax Error: If markers like <<<<<<< SEARCH, =======, or >>>>>>> REPLACE are malformed, missing, or out of order, a SearchReplaceSyntaxError is raised.
    • Empty Blocks: A SEARCH block cannot be empty.
  9. Use `search_replace_edit` to apply edits to content

    main

    The search_replace_edit function parses a list of lines containing search-replace blocks and applies them to the original_content. It returns a tuple containing the edited_file (string) and comments (string) describing the result of the operation.

    Parameters:

    • lines: A list[str] containing the lines of the file, including the search-replace markers.
    • original_content: The str representing the current state of the file before edits.
    • logger: A Callable[[str], object] used to log the search and replace operations (e.g., printing the lines being matched).

    Returns:

    • tuple[str, str]: (edited_file_content, status_comments)
    from wcgw.client.file_ops.search_replace import search_replace_edit
    
    # lines contains the text with <<<<<< SEARCH ... >>>>>> REPLACE blocks
    # original_content is the current file content
    def my_logger(msg: str):
        print(msg)
    
    edited_file, comments = search_replace_edit(lines, original_content, my_logger)
    print(comments)
  10. Initialize a session with the Initialize schema

    main

    To start or resume a session, use the Initialize schema. This defines the initial state, including the session type, workspace, and mode.

    Key Fields:

    • type: One of first_call, user_asked_mode_change, reset_shell, or user_asked_change_workspace.
    • any_workspace_path: The workspace path (use an empty string instead of ~).
    • initial_files_to_read: A list of files to read immediately. Provide [] if none.
    • task_id_to_resume: The ID of the task to resume.
    • mode_name: The operational mode: wcgw, architect, or code_writer.
    • thread_id: The ID created during first_call. Leave as an empty string if this is the first_call.
    • allowed_globs & allowed_commands: Required only if mode_name is code_writer. Can be set to 'all' or a list of patterns.
    # Example initialization for a new code_writer session
    init_data = {
        "type": "first_call",
        "any_workspace_path": "/path/to/project",
        "initial_files_to_read": ["README.md"],
        "task_id_to_resume": "task_123",
        "mode_name": "code_writer",
        "thread_id": "",
        "allowed_globs": ["src/**/*.py"],
        "allowed_commands": ["ls", "pytest"]
    }
  11. Write or edit files using FileWriteOrEdit

    main

    The FileWriteOrEdit schema is used to modify file content. It requires a specific field order for the LLM backend to process correctly.

    Required Fields:

    1. file_path: The absolute path to the file.
    2. percentage_to_change: An integer representing the predicted percentage of existing lines that will be part of the diff (calculated as lines_with_diff / total_existing_lines).
    3. text_or_search_replace_blocks: The actual content or search-and-replace blocks to apply.
    4. thread_id: The current session thread ID.
    # Example FileWriteOrEdit payload
    edit_action = {
        "file_path": "/abs/path/to/file.py",
        "percentage_to_change": 25,
        "text_or_search_replace_blocks": "# new content",
        "thread_id": "thread_abc"
    }
  12. Determine the stats file path for a workspace

    main

    The get_stats_path(workspace_path) function calculates the absolute path where a workspace's statistics are stored.

    It follows these steps:

    1. Normalizes the workspace_path.
    2. Generates a filename using the pattern {workspace_basename}_{md5_hash_of_full_path}.json.
    3. Locates the storage directory in XDG_DATA_HOME/wcgw/workspace_stats (defaulting to ~/.local/share/wcgw/workspace_stats).
    4. Ensures the directory exists.