Skip to main content
Glama
AstroMined

PyGithub MCP Server

by AstroMined

push_files

Push multiple files to a GitHub repository in a single commit, enabling batch file management through the PyGithub MCP Server for efficient repository updates.

Instructions

Push multiple files to a GitHub repository in a single commit.

Args:
    params: Dictionary with file parameters
        - owner: Repository owner (username or organization)
        - repo: Repository name
        - branch: Branch to push to
        - files: List of files to push, each with path and content
        - message: Commit message

Returns:
    MCP response with file push result

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
paramsYes

Implementation Reference

  • MCP tool handler for 'push_files', decorated with @tool(). Validates input with PushFilesParams, delegates to repositories.push_files, and formats response for MCP.
    @tool()
    def push_files(params: Dict) -> Dict:
        """Push multiple files to a GitHub repository in a single commit.
    
        Args:
            params: Dictionary with file parameters
                - owner: Repository owner (username or organization)
                - repo: Repository name
                - branch: Branch to push to
                - files: List of files to push, each with path and content
                - message: Commit message
    
        Returns:
            MCP response with file push result
        """
        try:
            logger.debug(f"push_files called with params: {params}")
            # Convert dict to Pydantic model
            push_params = PushFilesParams(**params)
            
            # Call operation
            result = repositories.push_files(push_params)
            
            logger.debug(f"Pushed {len(push_params.files)} files")
            return {
                "content": [{"type": "text", "text": json.dumps(result, indent=2)}]
            }
        except ValidationError as e:
            logger.error(f"Validation error: {e}")
            return {
                "content": [{"type": "error", "text": f"Validation error: {str(e)}"}],
                "is_error": True
            }
        except GitHubError as e:
            logger.error(f"GitHub error: {e}")
            return {
                "content": [{"type": "error", "text": format_github_error(e)}],
                "is_error": True
            }
        except Exception as e:
            logger.error(f"Unexpected error: {e}")
            logger.error(traceback.format_exc())
            error_msg = str(e) if str(e) else "An unexpected error occurred"
            return {
                "content": [{"type": "error", "text": f"Internal server error: {error_msg}"}],
                "is_error": True
            }
  • Pydantic schema PushFilesParams defining input parameters (owner/repo from RepositoryRef, branch, files list, message) with field validators for non-empty values.
    class PushFilesParams(RepositoryRef):
        """Parameters for pushing multiple files in a single commit."""
    
        model_config = ConfigDict(strict=True)
        
        branch: str = Field(..., description="Branch to push to")
        files: List[FileContent] = Field(..., description="Files to push")
        message: str = Field(..., description="Commit message")
    
        @field_validator('branch')
        @classmethod
        def validate_branch(cls, v):
            """Validate that branch is not empty."""
            if not v.strip():
                raise ValueError("branch cannot be empty")
            return v
    
        @field_validator('files')
        @classmethod
        def validate_files(cls, v):
            """Validate that files list is not empty."""
            if not v:
                raise ValueError("files list cannot be empty")
            return v
    
        @field_validator('message')
        @classmethod
        def validate_message(cls, v):
            """Validate that message is not empty."""
            if not v.strip():
                raise ValueError("message cannot be empty")
            return v
  • Core business logic for pushing multiple files: fetches existing SHAs, creates/updates each file via GitHub API's create_file (with SHA for updates), collects results.
    def push_files(params: PushFilesParams) -> Dict[str, Any]:
        """Push multiple files to a repository in a single commit.
        
        This is a convenience wrapper around multiple create_file operations.
        Note: This does not support directories or binary files yet.
    
        Args:
            params: Parameters for pushing multiple files
    
        Returns:
            Result including commit info
    
        Raises:
            GitHubError: If file push fails
        """
        logger.debug(f"Pushing {len(params.files)} files to {params.owner}/{params.repo}")
        
        # Validate file content first
        for file_content in params.files:
            if not file_content.content:
                raise GitHubError("File content cannot be empty")
        
        try:
            client = GitHubClient.get_instance()
            repository = client.get_repo(f"{params.owner}/{params.repo}")
            
            # Get current file SHAs if they exist
            file_shas = {}
            for file_content in params.files:
                try:
                    existing_file = repository.get_contents(
                        path=file_content.path, 
                        ref=params.branch
                    )
                    if not isinstance(existing_file, list):
                        file_shas[file_content.path] = existing_file.sha
                except GithubException:
                    # File doesn't exist yet, no SHA needed
                    pass
            
            # Create a commit for each file
            results = []
            for file_content in params.files:
                kwargs = {
                    "path": file_content.path,
                    "message": params.message,
                    "content": file_content.content,
                    "branch": params.branch
                }
                
                # Add SHA if updating an existing file
                if file_content.path in file_shas:
                    kwargs["sha"] = file_shas[file_content.path]
                
                result = repository.create_file(**kwargs)
                
                # Extract content SHA safely
                content_sha = None
                try:
                    if hasattr(result["content"], "sha"):
                        content_sha = result["content"].sha
                    elif isinstance(result["content"], dict) and "sha" in result["content"]:
                        content_sha = result["content"]["sha"]
                except (AttributeError, KeyError, TypeError) as e:
                    logger.warning(f"Error extracting content SHA for {file_content.path}: {e}")
                    # If we can't get the SHA, we'll proceed without it
                
                results.append({
                    "path": file_content.path,
                    "sha": content_sha
                })
            
            logger.debug(f"Files pushed successfully to {params.owner}/{params.repo}")
            return {
                "message": params.message,
                "branch": params.branch,
                "files": results
            }
        except GithubException as e:
            logger.error(f"GitHub exception when pushing files: {str(e)}")
            raise client._handle_github_exception(e, resource_hint="content_file")
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 mentions the single-commit behavior. It doesn't disclose critical behavioral traits like authentication requirements, error handling, rate limits, whether it overwrites existing files, or what 'file push result' contains. The description is insufficient 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?

Perfectly structured with a clear purpose statement followed by organized Args and Returns sections. Every sentence adds value with zero redundancy. The two-sentence format is highly efficient.

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 complex mutation tool with 5 effective parameters, no annotations, and no output schema, the description provides basic purpose and parameter semantics but lacks behavioral context, error information, and output details. It's minimally adequate but has significant gaps given the tool's complexity.

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 schema has 0% description coverage with only one undocumented 'params' object. The description compensates by detailing all 5 nested parameters (owner, repo, branch, files, message) with clear semantics, though it doesn't specify data formats or constraints for 'files' list structure.

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 ('push multiple files') and resource ('to a GitHub repository'), distinguishing it from sibling tools like create_or_update_file (single file) or list_commits (read-only). The verb 'push' combined with 'in a single commit' provides precise scope.

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

Usage Guidelines3/5

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

The description implies usage for batch file operations but doesn't explicitly state when to use this vs. alternatives like create_or_update_file (for single files) or create_branch (for branch creation). No guidance on prerequisites or exclusions is provided.

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/AstroMined/pygithub-mcp-server'

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