Skip to main content
Glama
AstroMined

PyGithub MCP Server

by AstroMined

list_commits

Retrieve commit history from GitHub repositories to track changes, review code evolution, and analyze development activity by specifying repository details and optional pagination or branch parameters.

Instructions

List commits in a GitHub repository.

Args:
    params: Dictionary with commit parameters
        - owner: Repository owner (username or organization)
        - repo: Repository name
        - page: Page number (optional)
        - per_page: Results per page (optional)
        - sha: Branch name or commit SHA (optional)

Returns:
    MCP response with list of commits

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
paramsYes

Implementation Reference

  • MCP tool handler for 'list_commits'. Validates input parameters using ListCommitsParams and delegates to the internal repositories.list_commits operation, formatting the response for MCP.
    @tool()
    def list_commits(params: Dict) -> Dict:
        """List commits in a GitHub repository.
    
        Args:
            params: Dictionary with commit parameters
                - owner: Repository owner (username or organization)
                - repo: Repository name
                - page: Page number (optional)
                - per_page: Results per page (optional)
                - sha: Branch name or commit SHA (optional)
    
        Returns:
            MCP response with list of commits
        """
        try:
            logger.debug(f"list_commits called with params: {params}")
            # Convert dict to Pydantic model
            commits_params = ListCommitsParams(**params)
            
            # Call operation
            result = repositories.list_commits(commits_params)
            
            logger.debug(f"Got {len(result)} commits")
            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
            }
  • Registration of the 'list_commits' tool along with other repository tools using register_tools in the MCP server.
    from .tools import (
        get_repository,
        create_repository,
        fork_repository,
        search_repositories,
        get_file_contents,
        create_or_update_file,
        push_files,
        create_branch,
        list_commits
    )
    
    # Register all repository tools
    register_tools(mcp, [
        get_repository,
        create_repository,
        fork_repository,
        search_repositories,
        get_file_contents,
        create_or_update_file,
        push_files,
        create_branch,
        list_commits
    ])
  • Pydantic schema for ListCommitsParams, extending RepositoryRef, with validation for pagination parameters.
    class ListCommitsParams(RepositoryRef):
        """Parameters for listing commits."""
    
        model_config = ConfigDict(strict=True)
        
        page: Optional[int] = Field(None, description="Page number")
        per_page: Optional[int] = Field(None, description="Results per page")
        sha: Optional[str] = Field(None, description="Branch name or commit SHA")
    
        @field_validator('page')
        @classmethod
        def validate_page(cls, v):
            """Validate that page is a positive integer."""
            if v is not None and v < 1:
                raise ValueError("page must be a positive integer")
            return v
    
        @field_validator('per_page')
        @classmethod
        def validate_per_page(cls, v):
            """Validate that per_page is within allowed range."""
            if v is not None:
                if v < 1:
                    raise ValueError("per_page must be a positive integer")
                if v > 100:
                    raise ValueError("per_page cannot exceed 100")
            return v
  • Internal helper function that performs the actual GitHub API call to list commits, handles pagination and conversion to schema.
    def list_commits(params: ListCommitsParams) -> List[Dict[str, Any]]:
        """List commits in a repository.
    
        Args:
            params: Parameters for listing commits
    
        Returns:
            List of commits in our schema
    
        Raises:
            GitHubError: If commit listing fails
        """
        logger.debug(f"Listing commits for {params.owner}/{params.repo}")
        try:
            client = GitHubClient.get_instance()
            repository = client.get_repo(f"{params.owner}/{params.repo}")
            
            # Build kwargs from Pydantic model
            kwargs = {}
            if params.sha:
                kwargs["sha"] = params.sha
            
            # Get commits
            paginated_commits = repository.get_commits(**kwargs)
            
            # Handle pagination
            commits = get_paginated_items(paginated_commits, params.page, params.per_page)
            
            # Convert commits to our schema
            return [{
                "sha": commit.sha,
                "message": commit.commit.message,
                "author": {
                    "name": commit.commit.author.name,
                    "email": commit.commit.author.email,
                    "date": commit.commit.author.date.isoformat()
                },
                "html_url": commit.html_url
            } for commit in commits]
        except GithubException as e:
            logger.error(f"GitHub exception when listing commits: {str(e)}")
            raise client._handle_github_exception(e, resource_hint="commit")
Behavior2/5

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. It mentions the tool lists commits but fails to describe key behaviors such as pagination details (implied by 'page' and 'per_page' but not explained), authentication requirements, rate limits, or what the response format includes (e.g., commit details). This is a significant gap for a tool with no annotation coverage.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is appropriately sized and front-loaded with the core purpose in the first sentence, followed by structured sections for Args and Returns. There's minimal waste, though the Returns section could be more informative given the lack of output schema.

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

Completeness2/5

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

Given the complexity (GitHub API interaction), no annotations, no output schema, and low schema description coverage, the description is incomplete. It lacks details on authentication, error handling, response structure, and behavioral traits, making it inadequate for a tool with nested parameters and no structured support.

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?

The description adds semantic details for parameters (owner, repo, page, per_page, sha) beyond the input schema, which has 0% description coverage and only shows a generic 'params' object. However, it doesn't fully compensate by explaining data types, constraints, or example values, leaving some ambiguity in parameter usage.

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 tool's purpose with 'List commits in a GitHub repository,' specifying the verb (list) and resource (commits in a GitHub repository). However, it doesn't explicitly differentiate from sibling tools like 'list_issues' or 'list_issue_comments,' which are also list operations but for different resources, so it lacks sibling differentiation.

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. It doesn't mention any prerequisites, context for usage, or comparisons to sibling tools like 'get_repository' or 'search_repositories,' leaving the agent without explicit usage instructions.

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