feat: Complete PyPI Query MCP Server Implementation (#3)

Merge pull request implementing complete PyPI query MCP server with comprehensive features and CI/CD pipeline.
This commit is contained in:
Hal 2025-05-27 11:14:49 +08:00 committed by GitHub
parent b1a1a6866d
commit 030b3a2607
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
33 changed files with 3238 additions and 246 deletions

View file

@ -0,0 +1,27 @@
"""Core modules for PyPI Query MCP Server.
This package contains the core business logic for PyPI package queries,
including API clients, data processing, and utility functions.
"""
from .exceptions import (
InvalidPackageNameError,
NetworkError,
PackageNotFoundError,
PyPIError,
PyPIServerError,
RateLimitError,
)
from .pypi_client import PyPIClient
from .version_utils import VersionCompatibility
__all__ = [
"PyPIClient",
"VersionCompatibility",
"PyPIError",
"PackageNotFoundError",
"NetworkError",
"RateLimitError",
"InvalidPackageNameError",
"PyPIServerError",
]

View file

@ -0,0 +1,56 @@
"""Custom exceptions for PyPI Query MCP Server."""
class PyPIError(Exception):
"""Base exception for PyPI-related errors."""
def __init__(self, message: str, status_code: int = None):
super().__init__(message)
self.message = message
self.status_code = status_code
class PackageNotFoundError(PyPIError):
"""Raised when a package is not found on PyPI."""
def __init__(self, package_name: str):
message = f"Package '{package_name}' not found on PyPI"
super().__init__(message, status_code=404)
self.package_name = package_name
class NetworkError(PyPIError):
"""Raised when network-related errors occur."""
def __init__(self, message: str, original_error: Exception = None):
super().__init__(message)
self.original_error = original_error
class RateLimitError(PyPIError):
"""Raised when API rate limit is exceeded."""
def __init__(self, retry_after: int = None):
message = "PyPI API rate limit exceeded"
if retry_after:
message += f". Retry after {retry_after} seconds"
super().__init__(message, status_code=429)
self.retry_after = retry_after
class InvalidPackageNameError(PyPIError):
"""Raised when package name is invalid."""
def __init__(self, package_name: str):
message = f"Invalid package name: '{package_name}'"
super().__init__(message, status_code=400)
self.package_name = package_name
class PyPIServerError(PyPIError):
"""Raised when PyPI server returns a server error."""
def __init__(self, status_code: int, message: str = None):
if not message:
message = f"PyPI server error (HTTP {status_code})"
super().__init__(message, status_code=status_code)

View file

@ -0,0 +1,238 @@
"""PyPI API client for package information retrieval."""
import asyncio
import logging
import re
from typing import Any
from urllib.parse import quote
import httpx
from .exceptions import (
InvalidPackageNameError,
NetworkError,
PackageNotFoundError,
PyPIServerError,
RateLimitError,
)
logger = logging.getLogger(__name__)
class PyPIClient:
"""Async client for PyPI JSON API."""
def __init__(
self,
base_url: str = "https://pypi.org/pypi",
timeout: float = 30.0,
max_retries: int = 3,
retry_delay: float = 1.0,
):
"""Initialize PyPI client.
Args:
base_url: Base URL for PyPI API
timeout: Request timeout in seconds
max_retries: Maximum number of retry attempts
retry_delay: Delay between retries in seconds
"""
self.base_url = base_url.rstrip("/")
self.timeout = timeout
self.max_retries = max_retries
self.retry_delay = retry_delay
# Simple in-memory cache
self._cache: dict[str, dict[str, Any]] = {}
self._cache_ttl = 300 # 5 minutes
# HTTP client configuration
self._client = httpx.AsyncClient(
timeout=httpx.Timeout(timeout),
headers={
"User-Agent": "pypi-query-mcp-server/0.1.0",
"Accept": "application/json",
},
follow_redirects=True,
)
async def __aenter__(self):
"""Async context manager entry."""
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
"""Async context manager exit."""
await self.close()
async def close(self):
"""Close the HTTP client."""
await self._client.aclose()
def _validate_package_name(self, package_name: str) -> str:
"""Validate and normalize package name.
Args:
package_name: Package name to validate
Returns:
Normalized package name
Raises:
InvalidPackageNameError: If package name is invalid
"""
if not package_name or not package_name.strip():
raise InvalidPackageNameError(package_name)
# Normalize package name (convert to lowercase, replace _ with -)
normalized = re.sub(r"[-_.]+", "-", package_name.lower())
# Basic validation - package names should contain only alphanumeric, hyphens, dots, underscores
if not re.match(r"^[a-zA-Z0-9]([a-zA-Z0-9._-]*[a-zA-Z0-9])?$", package_name):
raise InvalidPackageNameError(package_name)
return normalized
def _get_cache_key(self, package_name: str, endpoint: str = "info") -> str:
"""Generate cache key for package data."""
return f"{endpoint}:{package_name}"
def _is_cache_valid(self, cache_entry: dict[str, Any]) -> bool:
"""Check if cache entry is still valid."""
import time
return time.time() - cache_entry.get("timestamp", 0) < self._cache_ttl
async def _make_request(self, url: str) -> dict[str, Any]:
"""Make HTTP request with retry logic.
Args:
url: URL to request
Returns:
JSON response data
Raises:
NetworkError: For network-related errors
PackageNotFoundError: When package is not found
RateLimitError: When rate limit is exceeded
PyPIServerError: For server errors
"""
last_exception = None
for attempt in range(self.max_retries + 1):
try:
logger.debug(f"Making request to {url} (attempt {attempt + 1})")
response = await self._client.get(url)
# Handle different HTTP status codes
if response.status_code == 200:
return response.json()
elif response.status_code == 404:
# Extract package name from URL for better error message
package_name = url.split("/")[-2] if "/" in url else "unknown"
raise PackageNotFoundError(package_name)
elif response.status_code == 429:
retry_after = response.headers.get("Retry-After")
retry_after_int = int(retry_after) if retry_after else None
raise RateLimitError(retry_after_int)
elif response.status_code >= 500:
raise PyPIServerError(response.status_code)
else:
raise PyPIServerError(
response.status_code,
f"Unexpected status code: {response.status_code}"
)
except httpx.TimeoutException as e:
last_exception = NetworkError(f"Request timeout: {e}", e)
except httpx.NetworkError as e:
last_exception = NetworkError(f"Network error: {e}", e)
except (PackageNotFoundError, RateLimitError, PyPIServerError):
# Don't retry these errors
raise
except Exception as e:
last_exception = NetworkError(f"Unexpected error: {e}", e)
# Wait before retry (except on last attempt)
if attempt < self.max_retries:
await asyncio.sleep(self.retry_delay * (2 ** attempt)) # Exponential backoff
# If we get here, all retries failed
raise last_exception
async def get_package_info(self, package_name: str, use_cache: bool = True) -> dict[str, Any]:
"""Get comprehensive package information from PyPI.
Args:
package_name: Name of the package to query
use_cache: Whether to use cached data if available
Returns:
Dictionary containing package information
Raises:
InvalidPackageNameError: If package name is invalid
PackageNotFoundError: If package is not found
NetworkError: For network-related errors
"""
normalized_name = self._validate_package_name(package_name)
cache_key = self._get_cache_key(normalized_name, "info")
# Check cache first
if use_cache and cache_key in self._cache:
cache_entry = self._cache[cache_key]
if self._is_cache_valid(cache_entry):
logger.debug(f"Using cached data for package: {normalized_name}")
return cache_entry["data"]
# Make API request
url = f"{self.base_url}/{quote(normalized_name)}/json"
logger.info(f"Fetching package info for: {normalized_name}")
try:
data = await self._make_request(url)
# Cache the result
import time
self._cache[cache_key] = {
"data": data,
"timestamp": time.time()
}
return data
except Exception as e:
logger.error(f"Failed to fetch package info for {normalized_name}: {e}")
raise
async def get_package_versions(self, package_name: str, use_cache: bool = True) -> list[str]:
"""Get list of available versions for a package.
Args:
package_name: Name of the package to query
use_cache: Whether to use cached data if available
Returns:
List of version strings
"""
package_info = await self.get_package_info(package_name, use_cache)
releases = package_info.get("releases", {})
return list(releases.keys())
async def get_latest_version(self, package_name: str, use_cache: bool = True) -> str:
"""Get the latest version of a package.
Args:
package_name: Name of the package to query
use_cache: Whether to use cached data if available
Returns:
Latest version string
"""
package_info = await self.get_package_info(package_name, use_cache)
return package_info.get("info", {}).get("version", "")
def clear_cache(self):
"""Clear the internal cache."""
self._cache.clear()
logger.debug("Cache cleared")

View file

@ -0,0 +1,274 @@
"""Version parsing and compatibility checking utilities."""
import logging
import re
from typing import Any
from packaging.specifiers import SpecifierSet
from packaging.version import InvalidVersion, Version
logger = logging.getLogger(__name__)
class VersionCompatibility:
"""Utility class for Python version compatibility checking."""
def __init__(self):
"""Initialize version compatibility checker."""
# Common Python version patterns in classifiers
self.python_classifier_pattern = re.compile(
r"Programming Language :: Python :: (\d+(?:\.\d+)*)"
)
# Implementation-specific classifiers
self.implementation_pattern = re.compile(
r"Programming Language :: Python :: Implementation :: (\w+)"
)
def parse_requires_python(self, requires_python: str) -> SpecifierSet | None:
"""Parse requires_python field into a SpecifierSet.
Args:
requires_python: The requires_python string from package metadata
Returns:
SpecifierSet object or None if parsing fails
"""
if not requires_python or not requires_python.strip():
return None
try:
# Clean up the version specification
cleaned = requires_python.strip()
return SpecifierSet(cleaned)
except Exception as e:
logger.warning(f"Failed to parse requires_python '{requires_python}': {e}")
return None
def extract_python_versions_from_classifiers(self, classifiers: list[str]) -> set[str]:
"""Extract Python version information from classifiers.
Args:
classifiers: List of classifier strings
Returns:
Set of Python version strings
"""
versions = set()
for classifier in classifiers:
match = self.python_classifier_pattern.search(classifier)
if match:
version = match.group(1)
versions.add(version)
return versions
def extract_python_implementations(self, classifiers: list[str]) -> set[str]:
"""Extract Python implementation information from classifiers.
Args:
classifiers: List of classifier strings
Returns:
Set of Python implementation names (CPython, PyPy, etc.)
"""
implementations = set()
for classifier in classifiers:
match = self.implementation_pattern.search(classifier)
if match:
implementation = match.group(1)
implementations.add(implementation)
return implementations
def check_version_compatibility(
self,
target_version: str,
requires_python: str | None = None,
classifiers: list[str] | None = None
) -> dict[str, Any]:
"""Check if a target Python version is compatible with package requirements.
Args:
target_version: Target Python version (e.g., "3.9", "3.10.5")
requires_python: The requires_python specification
classifiers: List of package classifiers
Returns:
Dictionary containing compatibility information
"""
result = {
"target_version": target_version,
"is_compatible": False,
"compatibility_source": None,
"details": {},
"warnings": [],
"suggestions": []
}
try:
target_ver = Version(target_version)
except InvalidVersion as e:
result["warnings"].append(f"Invalid target version format: {e}")
return result
# Check requires_python first (more authoritative)
if requires_python:
spec_set = self.parse_requires_python(requires_python)
if spec_set:
is_compatible = target_ver in spec_set
result.update({
"is_compatible": is_compatible,
"compatibility_source": "requires_python",
"details": {
"requires_python": requires_python,
"parsed_spec": str(spec_set),
"check_result": is_compatible
}
})
if not is_compatible:
result["suggestions"].append(
f"Package requires Python {requires_python}, "
f"but target is {target_version}"
)
return result
# Fall back to classifiers if no requires_python
if classifiers:
supported_versions = self.extract_python_versions_from_classifiers(classifiers)
implementations = self.extract_python_implementations(classifiers)
if supported_versions:
# Check if target version matches any supported version
target_major_minor = f"{target_ver.major}.{target_ver.minor}"
target_major = str(target_ver.major)
is_compatible = (
target_version in supported_versions or
target_major_minor in supported_versions or
target_major in supported_versions
)
result.update({
"is_compatible": is_compatible,
"compatibility_source": "classifiers",
"details": {
"supported_versions": sorted(supported_versions),
"implementations": sorted(implementations),
"target_major_minor": target_major_minor,
"check_result": is_compatible
}
})
if not is_compatible:
result["suggestions"].append(
f"Package supports Python versions: {', '.join(sorted(supported_versions))}, "
f"but target is {target_version}"
)
return result
# No version information available
result["warnings"].append(
"No Python version requirements found in package metadata"
)
result["suggestions"].append(
"Consider checking package documentation for Python version compatibility"
)
return result
def get_compatible_versions(
self,
requires_python: str | None = None,
classifiers: list[str] | None = None,
available_pythons: list[str] | None = None
) -> dict[str, Any]:
"""Get list of compatible Python versions for a package.
Args:
requires_python: The requires_python specification
classifiers: List of package classifiers
available_pythons: List of Python versions to check against
Returns:
Dictionary containing compatible versions and recommendations
"""
if available_pythons is None:
# Default Python versions to check
available_pythons = [
"3.7", "3.8", "3.9", "3.10", "3.11", "3.12", "3.13"
]
compatible = []
incompatible = []
for python_version in available_pythons:
result = self.check_version_compatibility(
python_version, requires_python, classifiers
)
if result["is_compatible"]:
compatible.append({
"version": python_version,
"source": result["compatibility_source"]
})
else:
incompatible.append({
"version": python_version,
"reason": result["suggestions"][0] if result["suggestions"] else "Unknown"
})
return {
"compatible_versions": compatible,
"incompatible_versions": incompatible,
"total_checked": len(available_pythons),
"compatibility_rate": len(compatible) / len(available_pythons) if available_pythons else 0,
"recommendations": self._generate_recommendations(compatible, incompatible)
}
def _generate_recommendations(
self,
compatible: list[dict[str, Any]],
incompatible: list[dict[str, Any]]
) -> list[str]:
"""Generate recommendations based on compatibility results.
Args:
compatible: List of compatible versions
incompatible: List of incompatible versions
Returns:
List of recommendation strings
"""
recommendations = []
if not compatible:
recommendations.append(
"⚠️ No compatible Python versions found. "
"Check package documentation for requirements."
)
elif len(compatible) == 1:
version = compatible[0]["version"]
recommendations.append(
f"📌 Only Python {version} is compatible with this package."
)
else:
versions = [v["version"] for v in compatible]
latest = max(versions, key=lambda x: tuple(map(int, x.split("."))))
recommendations.append(
f"✅ Compatible with Python {', '.join(versions)}. "
f"Recommended: Python {latest}"
)
if len(incompatible) > len(compatible):
recommendations.append(
"⚠️ This package has limited Python version support. "
"Consider using a more recent version of the package if available."
)
return recommendations