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)

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