Skip to main content
Glama
AstroMined

PyGithub MCP Server

by AstroMined

list_issue_comments

Retrieve and display comments from a specific GitHub issue by providing repository details and issue number, enabling review of discussion history.

Instructions

List comments on an issue.

Args:
    params: Parameters for listing comments including:
        - owner: Repository owner (user or organization)
        - repo: Repository name
        - issue_number: Issue number
        - since: Filter by date (optional)
        - page: Page number (optional)
        - per_page: Results per page (optional)

Returns:
    List of comments from GitHub API

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
paramsYes

Implementation Reference

  • MCP tool handler for list_issue_comments. Validates input using ListIssueCommentsParams, calls the operations function, formats JSON response, handles errors.
    @tool()
    def list_issue_comments(params: ListIssueCommentsParams) -> dict:
        """List comments on an issue.
        
        Args:
            params: Parameters for listing comments including:
                - owner: Repository owner (user or organization)
                - repo: Repository name
                - issue_number: Issue number
                - since: Filter by date (optional)
                - page: Page number (optional)
                - per_page: Results per page (optional)
        
        Returns:
            List of comments from GitHub API
        """
        try:
            logger.debug(f"list_issue_comments called with params: {params}")
            # Pass the Pydantic model directly to the operation
            result = issues.list_issue_comments(params)
            logger.debug(f"Got result: {result}")
            return {"content": [{"type": "text", "text": json.dumps(result, indent=2)}]}
        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 ListIssueCommentsParams for input validation. Inherits from RepositoryRef (owner/repo), adds issue_number, since, page, per_page with validators.
    class ListIssueCommentsParams(RepositoryRef):
        """Parameters for listing comments on an issue."""
    
        model_config = ConfigDict(strict=True)
        
        issue_number: int = Field(..., description="Issue number to list comments for")
        since: Optional[datetime] = Field(
            None, 
            description="Filter by date (ISO 8601 format with timezone: YYYY-MM-DDThh:mm:ssZ)"
        )
        page: Optional[int] = Field(
            None, 
            description="Page number for pagination (1-based)"
        )
        per_page: Optional[int] = Field(
            None, 
            description="Results per page (max 100)"
        )
        
        @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 number must be a positive integer")
            return v
        
        @field_validator('per_page')
        @classmethod
        def validate_per_page(cls, v):
            """Validate that per_page is a positive integer <= 100."""
            if v is not None:
                if v < 1:
                    raise ValueError("Results per page must be a positive integer")
                if v > 100:
                    raise ValueError("Results per page cannot exceed 100")
            return v
        
        @field_validator('since', mode='before')
        @classmethod
        def validate_since(cls, v):
            """Convert string dates to datetime objects.
            
            Accepts:
            - ISO 8601 format strings with timezone (e.g., "2020-01-01T00:00:00Z")
            - ISO 8601 format strings with timezone without colon (e.g., "2020-01-01T12:30:45-0500")
            - ISO 8601 format strings with short timezone (e.g., "2020-01-01T12:30:45+05")
            - ISO 8601 format strings with single digit timezone (e.g., "2020-01-01T12:30:45-5")
            - datetime objects
            
            Returns:
            - datetime object
            
            Raises:
            - ValueError: If the string cannot be converted to a valid datetime object
            """
            if isinstance(v, str):
                # Basic validation - must have 'T' and some form of timezone indicator
                if not ('T' in v and ('+' in v or 'Z' in v or '-' in v.split('T')[1])):
                    raise ValueError(
                        f"Invalid ISO format datetime: {v}. "
                        f"Must include date, time with 'T' separator, and timezone."
                    )
                
                try:
                    # Try to convert using our flexible converter
                    return convert_iso_string_to_datetime(v)
                except ValueError as e:
                    # Only raise if conversion actually fails
                    raise ValueError(f"Invalid ISO format datetime: {v}. {str(e)}")
            return v
  • Registration function that includes list_issue_comments in the issue_tools list and calls register_tools to register with MCP server using function name as tool name.
    def register(mcp: FastMCP) -> None:
        """Register all issue tools with the MCP server.
        
        Args:
            mcp: The MCP server instance
        """
        from pygithub_mcp_server.tools import register_tools
        
        # List of all issue tools to register
        issue_tools = [
            create_issue,
            list_issues,
            get_issue,
            update_issue,
            add_issue_comment,
            list_issue_comments,
            update_issue_comment,
            delete_issue_comment,
            add_issue_labels,
            remove_issue_label,
        ]
        
        register_tools(mcp, issue_tools)
        logger.debug(f"Registered {len(issue_tools)} issue tools")
  • Core implementation: fetches issue comments using PyGithub, handles pagination, converts to dicts using convert_issue_comment.
    def list_issue_comments(params: ListIssueCommentsParams) -> List[Dict[str, Any]]:
        """List comments on an issue.
    
        Args:
            params: Validated parameters for listing comments
    
        Returns:
            List of comments from GitHub API
    
        Raises:
            GitHubError: If the API request fails
        """
        try:
            client = GitHubClient.get_instance()
            repository = client.get_repo(f"{params.owner}/{params.repo}")
            issue = repository.get_issue(params.issue_number)
    
            # Build kwargs for get_comments
            kwargs = {}
            if params.since is not None:
                logger.debug(f"Using UTC since parameter: {params.since.isoformat()}")
                kwargs["since"] = params.since
    
            # Get paginated comments with only provided parameters
            paginated_comments = issue.get_comments(**kwargs)
            
            # Use our pagination utility for consistent pagination handling
            comments = get_paginated_items(paginated_comments, params.page, params.per_page)
    
            logger.debug(f"Retrieved {len(comments)} comments")
    
            # Convert each comment to our schema
            converted_comments = [convert_issue_comment(comment) for comment in comments]
            return converted_comments
    
        except GithubException as e:
            raise GitHubClient.get_instance()._handle_github_exception(e)
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. While 'List comments' implies a read-only operation, the description doesn't specify authentication requirements, rate limits, pagination behavior (beyond listing parameters), error conditions, or what format the 'List of comments from GitHub API' actually contains. For a tool with 6 parameters and no annotation coverage, this is insufficient.

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 well-structured with clear sections (Args, Returns) and uses bullet points for parameters. It's appropriately sized for a tool with multiple parameters. The first sentence states the purpose clearly. However, the 'Args' section could be more concise by integrating parameter descriptions into the main text rather than a separate bulleted list.

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 read-only listing tool with 6 parameters and no output schema, the description is moderately complete. It covers the purpose and parameters adequately but lacks behavioral context (authentication, rate limits, pagination details) and doesn't describe the return value format beyond 'List of comments from GitHub API'. Given the complexity and lack of annotations/output schema, it should provide more operational guidance.

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 provides a comprehensive parameter list with brief explanations for all 6 parameters (owner, repo, issue_number, since, page, per_page). Since schema description coverage is 0% (the schema has no descriptions at the top level), this description adds significant value by documenting all parameters. However, it doesn't provide format details (like ISO 8601 for 'since') or constraints (like 'max 100' for per_page) that appear in the schema.

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 comments on an issue' - a specific verb (list) and resource (comments on an issue). It distinguishes from siblings like 'get_issue' (which retrieves issue metadata) or 'add_issue_comment' (which creates comments). However, it doesn't explicitly differentiate from 'update_issue_comment' or 'delete_issue_comment' which also involve comments.

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 when to use 'list_issue_comments' versus 'get_issue' (which might include some comments), or when to use it versus 'search_repositories' for broader searches. There's no context about prerequisites or typical use cases.

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