feat: add MCP prompt templates for PyPI package analysis and decision-making

- Add comprehensive prompt templates for package analysis, dependency management, and migration planning
- Implement 8 prompt templates covering quality analysis, package comparison, alternatives suggestion, dependency conflicts, version upgrades, security audits, and migration planning
- Add detailed documentation in PROMPT_TEMPLATES.md with usage examples
- Include demo script and test coverage for prompt template functionality
- Update README.md to highlight new prompt template features
- Templates provide structured guidance for common PyPI package scenarios

Signed-off-by: longhao <hal.long@outlook.com>
This commit is contained in:
longhao 2025-05-29 15:52:44 +08:00 committed by Hal
parent ed0cf45c18
commit e481711053
11 changed files with 1811 additions and 0 deletions

View file

@ -0,0 +1,34 @@
"""MCP prompt templates for PyPI package queries.
This package contains FastMCP prompt implementations that provide
reusable templates for common PyPI package analysis and decision-making scenarios.
"""
from .dependency_management import (
audit_security_risks,
plan_version_upgrade,
resolve_dependency_conflicts,
)
from .migration_guidance import (
generate_migration_checklist,
plan_package_migration,
)
from .package_analysis import (
analyze_package_quality,
compare_packages,
suggest_alternatives,
)
__all__ = [
# Package Analysis
"analyze_package_quality",
"compare_packages",
"suggest_alternatives",
# Dependency Management
"resolve_dependency_conflicts",
"plan_version_upgrade",
"audit_security_risks",
# Migration Guidance
"plan_package_migration",
"generate_migration_checklist",
]

View file

@ -0,0 +1,248 @@
"""Dependency management prompt templates for PyPI MCP server."""
from typing import Annotated
from fastmcp import Context
from pydantic import Field
class Message:
"""Simple message class for prompt templates."""
def __init__(self, text: str, role: str = "user"):
self.text = text
self.role = role
async def resolve_dependency_conflicts(
conflicts: Annotated[
list[str],
Field(description="List of conflicting dependencies or error messages", min_length=1)
],
python_version: Annotated[
str | None,
Field(description="Target Python version (e.g., '3.10', '3.11')")
] = None,
project_context: Annotated[
str | None,
Field(description="Brief description of the project and its requirements")
] = None,
ctx: Context | None = None,
) -> list[Message]:
"""Generate a prompt for resolving dependency conflicts.
This prompt template helps analyze and resolve Python package dependency conflicts
with specific strategies and recommendations.
"""
conflicts_text = "\n".join(f"- {conflict}" for conflict in conflicts)
python_text = f"\nPython version: {python_version}" if python_version else ""
context_text = f"\nProject context: {project_context}" if project_context else ""
return [
Message(
f"""I'm experiencing dependency conflicts in my Python project. Please help me resolve them.
## 🚨 Conflict Details
{conflicts_text}{python_text}{context_text}
## 🔧 Resolution Strategy
Please provide a comprehensive resolution plan:
### Conflict Analysis
- Identify the root cause of each conflict
- Explain why these dependencies are incompatible
- Assess the severity and impact of each conflict
### Resolution Options
1. **Version Pinning Strategy**
- Specific version combinations that work together
- Version ranges that maintain compatibility
- Lock file recommendations
2. **Alternative Packages**
- Drop-in replacements for conflicting packages
- Packages with better compatibility profiles
- Lighter alternatives with fewer dependencies
3. **Environment Isolation**
- Virtual environment strategies
- Docker containerization approaches
- Dependency grouping techniques
### Implementation Steps
- Step-by-step resolution commands
- Testing procedures to verify fixes
- Preventive measures for future conflicts
## 🛡️ Best Practices
- Dependency management tools recommendations
- Version constraint strategies
- Monitoring and maintenance approaches
Please provide specific commands and configuration examples where applicable."""
)
]
async def plan_version_upgrade(
package_name: Annotated[str, Field(description="Name of the package to upgrade")],
current_version: Annotated[str, Field(description="Current version being used")],
target_version: Annotated[
str | None,
Field(description="Target version (if known), or 'latest' for newest")
] = None,
project_size: Annotated[
str | None,
Field(description="Project size context (small/medium/large/enterprise)")
] = None,
ctx: Context | None = None,
) -> list[Message]:
"""Generate a prompt for planning package version upgrades.
This prompt template helps create a comprehensive upgrade plan for Python packages,
including risk assessment and migration strategies.
"""
target_text = target_version or "latest available version"
size_text = f" ({project_size} project)" if project_size else ""
return [
Message(
f"""I need to upgrade '{package_name}' from version {current_version} to {target_text}{size_text}.
Please create a comprehensive upgrade plan:
## 📋 Pre-Upgrade Assessment
### Version Analysis
- Changes between {current_version} and {target_text}
- Breaking changes and deprecations
- New features and improvements
- Security fixes included
### Risk Assessment
- Compatibility with existing dependencies
- Potential breaking changes impact
- Testing requirements and scope
- Rollback complexity
## 🚀 Upgrade Strategy
### Preparation Phase
- Backup and version control recommendations
- Dependency compatibility checks
- Test environment setup
- Documentation review
### Migration Steps
1. **Incremental Upgrade Path**
- Intermediate versions to consider
- Step-by-step upgrade sequence
- Validation points between steps
2. **Code Changes Required**
- API changes to address
- Deprecated feature replacements
- Configuration updates needed
3. **Testing Strategy**
- Unit test updates required
- Integration test considerations
- Performance regression testing
### Post-Upgrade Validation
- Functionality verification checklist
- Performance monitoring points
- Error monitoring and alerting
## 🛡️ Risk Mitigation
- Rollback procedures
- Gradual deployment strategies
- Monitoring and alerting setup
Please provide specific commands, code examples, and timelines where applicable."""
)
]
async def audit_security_risks(
packages: Annotated[
list[str],
Field(description="List of packages to audit for security risks", min_length=1)
],
environment: Annotated[
str | None,
Field(description="Environment context (development/staging/production)")
] = None,
compliance_requirements: Annotated[
str | None,
Field(description="Specific compliance requirements (e.g., SOC2, HIPAA, PCI-DSS)")
] = None,
ctx: Context | None = None,
) -> list[Message]:
"""Generate a prompt for security risk auditing of packages.
This prompt template helps conduct comprehensive security audits of Python packages
and their dependencies.
"""
packages_text = ", ".join(f"'{pkg}'" for pkg in packages)
env_text = f"\nEnvironment: {environment}" if environment else ""
compliance_text = f"\nCompliance requirements: {compliance_requirements}" if compliance_requirements else ""
return [
Message(
f"""Please conduct a comprehensive security audit of these Python packages: {packages_text}{env_text}{compliance_text}
## 🔍 Security Assessment Framework
### Vulnerability Analysis
- Known CVEs and security advisories
- Severity levels and CVSS scores
- Affected versions and fix availability
- Exploit likelihood and impact assessment
### Dependency Security
- Transitive dependency vulnerabilities
- Dependency chain analysis
- Supply chain risk assessment
- License compliance issues
### Package Integrity
- Package authenticity verification
- Maintainer reputation and history
- Code review and audit history
- Distribution security (PyPI, mirrors)
## 🛡️ Risk Evaluation
### Critical Findings
- High-severity vulnerabilities requiring immediate action
- Packages with known malicious activity
- Unmaintained packages with security issues
### Medium Risk Issues
- Outdated packages with available security updates
- Packages with poor security practices
- Dependencies with concerning patterns
### Recommendations
- Immediate remediation steps
- Alternative secure packages
- Security monitoring setup
- Update and patching strategies
## 📋 Compliance Assessment
- Regulatory requirement alignment
- Security policy compliance
- Audit trail and documentation needs
- Reporting and monitoring requirements
## 🚀 Action Plan
- Prioritized remediation roadmap
- Timeline and resource requirements
- Monitoring and maintenance procedures
- Incident response preparations
Please provide specific vulnerability details, remediation commands, and compliance guidance."""
)
]

View file

@ -0,0 +1,253 @@
"""Migration guidance prompt templates for PyPI MCP server."""
from typing import Annotated, Literal
from fastmcp import Context
from pydantic import Field
class Message:
"""Simple message class for prompt templates."""
def __init__(self, text: str, role: str = "user"):
self.text = text
self.role = role
async def plan_package_migration(
from_package: Annotated[str, Field(description="Package to migrate from")],
to_package: Annotated[str, Field(description="Package to migrate to")],
codebase_size: Annotated[
Literal["small", "medium", "large", "enterprise"],
Field(description="Size of the codebase being migrated")
] = "medium",
timeline: Annotated[
str | None,
Field(description="Desired timeline for migration (e.g., '2 weeks', '1 month')")
] = None,
team_size: Annotated[
int | None,
Field(description="Number of developers involved in migration", ge=1, le=50)
] = None,
ctx: Context | None = None,
) -> list[Message]:
"""Generate a comprehensive package migration plan.
This prompt template helps create detailed migration plans when switching
from one Python package to another.
"""
timeline_text = f"\nTimeline: {timeline}" if timeline else ""
team_text = f"\nTeam size: {team_size} developers" if team_size else ""
return [
Message(
f"""I need to migrate from '{from_package}' to '{to_package}' in a {codebase_size} codebase.{timeline_text}{team_text}
Please create a comprehensive migration plan:
## 📊 Migration Assessment
### Package Comparison
- Feature mapping between '{from_package}' and '{to_package}'
- API differences and breaking changes
- Performance implications
- Dependency changes and conflicts
### Codebase Impact Analysis
- Estimated number of files affected
- Complexity of required changes
- Testing requirements and scope
- Documentation updates needed
## 🗺️ Migration Strategy
### Phase 1: Preparation
- Environment setup and tooling
- Dependency analysis and resolution
- Team training and knowledge transfer
- Migration tooling and automation setup
### Phase 2: Incremental Migration
- Module-by-module migration approach
- Parallel implementation strategy
- Feature flag and gradual rollout
- Testing and validation at each step
### Phase 3: Cleanup and Optimization
- Legacy code removal
- Performance optimization
- Documentation updates
- Final testing and validation
## 🔧 Technical Implementation
### Code Transformation
- Automated migration scripts and tools
- Manual code change patterns
- Import statement updates
- Configuration file changes
### Testing Strategy
- Unit test migration and updates
- Integration test modifications
- Performance regression testing
- End-to-end validation procedures
### Deployment Approach
- Staging environment validation
- Production deployment strategy
- Rollback procedures and contingencies
- Monitoring and alerting setup
## 📋 Project Management
### Timeline and Milestones
- Detailed phase breakdown with dates
- Critical path identification
- Risk mitigation checkpoints
- Go/no-go decision points
### Resource Allocation
- Developer time estimates
- Skill requirements and training needs
- External dependencies and blockers
- Budget and cost considerations
## 🛡️ Risk Management
- Technical risks and mitigation strategies
- Business continuity planning
- Communication and stakeholder management
- Success criteria and metrics
Please provide specific code examples, commands, and detailed timelines."""
)
]
async def generate_migration_checklist(
migration_type: Annotated[
Literal["package_replacement", "version_upgrade", "framework_migration", "dependency_cleanup"],
Field(description="Type of migration being performed")
],
packages_involved: Annotated[
list[str],
Field(description="List of packages involved in the migration", min_length=1)
],
environment: Annotated[
Literal["development", "staging", "production", "all"],
Field(description="Target environment for migration")
] = "all",
ctx: Context | None = None,
) -> list[Message]:
"""Generate a detailed migration checklist.
This prompt template creates comprehensive checklists for different types
of Python package migrations to ensure nothing is missed.
"""
packages_text = ", ".join(f"'{pkg}'" for pkg in packages_involved)
migration_contexts = {
"package_replacement": "replacing one package with another",
"version_upgrade": "upgrading package versions",
"framework_migration": "migrating between frameworks",
"dependency_cleanup": "cleaning up and optimizing dependencies"
}
context_text = migration_contexts.get(migration_type, migration_type)
return [
Message(
f"""Create a comprehensive migration checklist for {context_text} involving: {packages_text}
Target environment: {environment}
## ✅ Pre-Migration Checklist
### Planning & Assessment
- [ ] Document current package versions and configurations
- [ ] Identify all dependencies and their versions
- [ ] Map feature usage and API calls
- [ ] Assess codebase impact and complexity
- [ ] Create migration timeline and milestones
- [ ] Identify team members and responsibilities
- [ ] Set up communication channels and reporting
### Environment Preparation
- [ ] Create isolated development environment
- [ ] Set up version control branching strategy
- [ ] Prepare staging environment for testing
- [ ] Configure CI/CD pipeline updates
- [ ] Set up monitoring and logging
- [ ] Prepare rollback procedures
- [ ] Document current system performance baselines
### Dependency Management
- [ ] Analyze dependency tree and conflicts
- [ ] Test package compatibility in isolation
- [ ] Update requirements files and lock files
- [ ] Verify license compatibility
- [ ] Check for security vulnerabilities
- [ ] Validate Python version compatibility
## 🔄 Migration Execution Checklist
### Code Changes
- [ ] Update import statements
- [ ] Modify API calls and method signatures
- [ ] Update configuration files
- [ ] Refactor deprecated functionality
- [ ] Update error handling and exceptions
- [ ] Modify data structures and types
- [ ] Update logging and debugging code
### Testing & Validation
- [ ] Run existing unit tests
- [ ] Update failing tests for new APIs
- [ ] Add tests for new functionality
- [ ] Perform integration testing
- [ ] Execute performance regression tests
- [ ] Validate error handling and edge cases
- [ ] Test in staging environment
- [ ] Conduct user acceptance testing
### Documentation & Communication
- [ ] Update code documentation and comments
- [ ] Update README and setup instructions
- [ ] Document API changes and breaking changes
- [ ] Update deployment procedures
- [ ] Communicate changes to stakeholders
- [ ] Update training materials
- [ ] Create migration troubleshooting guide
## 🚀 Post-Migration Checklist
### Deployment & Monitoring
- [ ] Deploy to staging environment
- [ ] Validate staging deployment
- [ ] Deploy to production environment
- [ ] Monitor system performance and errors
- [ ] Verify all features are working
- [ ] Check logs for warnings or errors
- [ ] Validate data integrity and consistency
### Cleanup & Optimization
- [ ] Remove old package dependencies
- [ ] Clean up deprecated code and comments
- [ ] Optimize performance and resource usage
- [ ] Update security configurations
- [ ] Archive old documentation
- [ ] Update team knowledge base
- [ ] Conduct post-migration review
### Long-term Maintenance
- [ ] Set up automated dependency updates
- [ ] Schedule regular security audits
- [ ] Plan future upgrade strategies
- [ ] Document lessons learned
- [ ] Update migration procedures
- [ ] Train team on new package features
- [ ] Establish monitoring and alerting
Please customize this checklist based on your specific migration requirements and add any project-specific items."""
)
]

View file

@ -0,0 +1,203 @@
"""Package analysis prompt templates for PyPI MCP server."""
from typing import Annotated, Literal
from fastmcp import Context
from pydantic import Field
class Message:
"""Simple message class for prompt templates."""
def __init__(self, text: str, role: str = "user"):
self.text = text
self.role = role
async def analyze_package_quality(
package_name: Annotated[str, Field(description="Name of the PyPI package to analyze")],
version: Annotated[str | None, Field(description="Specific version to analyze")] = None,
ctx: Context | None = None,
) -> list[Message]:
"""Generate a comprehensive package quality analysis prompt.
This prompt template helps analyze a Python package's quality, maintenance status,
security, performance, and overall suitability for use in projects.
"""
version_text = f" version {version}" if version else ""
return [
Message(
f"""Please provide a comprehensive quality analysis of the Python package '{package_name}'{version_text}.
Analyze the following aspects:
## 📊 Package Overview
- Package purpose and functionality
- Current version and release history
- Maintenance status and activity
## 🔧 Technical Quality
- Code quality indicators
- Test coverage and CI/CD setup
- Documentation quality
- API design and usability
## 🛡️ Security & Reliability
- Known security vulnerabilities
- Dependency security assessment
- Stability and backward compatibility
## 📈 Community & Ecosystem
- Download statistics and popularity
- Community support and contributors
- Issue resolution and responsiveness
## 🎯 Recommendations
- Suitability for production use
- Alternative packages to consider
- Best practices for integration
Please provide specific examples and actionable insights where possible."""
)
]
async def compare_packages(
packages: Annotated[
list[str],
Field(description="List of package names to compare", min_length=2, max_length=5)
],
use_case: Annotated[
str,
Field(description="Specific use case or project context for comparison")
],
criteria: Annotated[
list[str] | None,
Field(description="Specific criteria to focus on (e.g., performance, security, ease of use)")
] = None,
ctx: Context | None = None,
) -> list[Message]:
"""Generate a detailed package comparison prompt.
This prompt template helps compare multiple Python packages to determine
the best choice for a specific use case.
"""
packages_text = ", ".join(f"'{pkg}'" for pkg in packages)
criteria_text = ""
if criteria:
criteria_text = f"\n\nFocus particularly on these criteria: {', '.join(criteria)}"
return [
Message(
f"""Please provide a detailed comparison of these Python packages: {packages_text}
## 🎯 Use Case Context
{use_case}{criteria_text}
## 📋 Comparison Framework
For each package, analyze:
### Core Functionality
- Feature completeness for the use case
- API design and ease of use
- Performance characteristics
### Ecosystem & Support
- Documentation quality
- Community size and activity
- Learning resources availability
### Technical Considerations
- Dependencies and compatibility
- Installation and setup complexity
- Integration with other tools
### Maintenance & Reliability
- Release frequency and versioning
- Bug fix responsiveness
- Long-term viability
## 🏆 Final Recommendation
Provide a clear recommendation with:
- Best overall choice and why
- Specific scenarios where each package excels
- Migration considerations if switching between them
Please include specific examples and quantitative data where available."""
)
]
async def suggest_alternatives(
package_name: Annotated[str, Field(description="Name of the package to find alternatives for")],
reason: Annotated[
Literal["deprecated", "security", "performance", "licensing", "maintenance", "features"],
Field(description="Reason for seeking alternatives")
],
requirements: Annotated[
str | None,
Field(description="Specific requirements or constraints for alternatives")
] = None,
ctx: Context | None = None,
) -> list[Message]:
"""Generate a prompt for finding package alternatives.
This prompt template helps find suitable alternatives to a Python package
based on specific concerns or requirements.
"""
reason_context = {
"deprecated": "the package is deprecated or no longer maintained",
"security": "security vulnerabilities or concerns",
"performance": "performance issues or requirements",
"licensing": "licensing conflicts or restrictions",
"maintenance": "poor maintenance or lack of updates",
"features": "missing features or functionality gaps"
}
reason_text = reason_context.get(reason, reason)
requirements_text = f"\n\nSpecific requirements: {requirements}" if requirements else ""
return [
Message(
f"""I need to find alternatives to the Python package '{package_name}' because of {reason_text}.{requirements_text}
Please help me identify suitable alternatives by analyzing:
## 🔍 Alternative Discovery
- Popular packages with similar functionality
- Emerging or newer solutions
- Enterprise or commercial alternatives if relevant
## 📊 Alternative Analysis
For each suggested alternative:
### Functional Compatibility
- Feature parity with '{package_name}'
- API similarity and migration effort
- Unique advantages or improvements
### Quality Assessment
- Maintenance status and community health
- Documentation and learning curve
- Performance comparisons
### Migration Considerations
- Breaking changes from '{package_name}'
- Migration tools or guides available
- Estimated effort and timeline
## 🎯 Recommendations
Provide:
- Top 3 recommended alternatives ranked by suitability
- Quick migration path for the best option
- Pros and cons summary for each alternative
- Any hybrid approaches or gradual migration strategies
Please include specific examples of how to replace key functionality from '{package_name}'."""
)
]

View file

@ -7,6 +7,16 @@ import click
from fastmcp import FastMCP
from .core.exceptions import InvalidPackageNameError, NetworkError, PackageNotFoundError
from .prompts import (
analyze_package_quality,
audit_security_risks,
compare_packages,
generate_migration_checklist,
plan_package_migration,
plan_version_upgrade,
resolve_dependency_conflicts,
suggest_alternatives,
)
from .tools import (
check_python_compatibility,
download_package_with_dependencies,
@ -553,6 +563,97 @@ async def get_top_downloaded_packages(
}
# Register prompt templates
@mcp.prompt()
async def analyze_package_quality_prompt(
package_name: str,
version: str | None = None
) -> str:
"""Generate a comprehensive quality analysis prompt for a PyPI package."""
messages = await analyze_package_quality(package_name, version)
return messages[0].text
@mcp.prompt()
async def compare_packages_prompt(
packages: list[str],
use_case: str,
criteria: list[str] | None = None
) -> str:
"""Generate a detailed comparison prompt for multiple PyPI packages."""
messages = await compare_packages(packages, use_case, criteria)
return messages[0].text
@mcp.prompt()
async def suggest_alternatives_prompt(
package_name: str,
reason: str,
requirements: str | None = None
) -> str:
"""Generate a prompt for finding package alternatives."""
messages = await suggest_alternatives(package_name, reason, requirements)
return messages[0].text
@mcp.prompt()
async def resolve_dependency_conflicts_prompt(
conflicts: list[str],
python_version: str | None = None,
project_context: str | None = None
) -> str:
"""Generate a prompt for resolving dependency conflicts."""
messages = await resolve_dependency_conflicts(conflicts, python_version, project_context)
return messages[0].text
@mcp.prompt()
async def plan_version_upgrade_prompt(
package_name: str,
current_version: str,
target_version: str | None = None,
project_size: str | None = None
) -> str:
"""Generate a prompt for planning package version upgrades."""
messages = await plan_version_upgrade(package_name, current_version, target_version, project_size)
return messages[0].text
@mcp.prompt()
async def audit_security_risks_prompt(
packages: list[str],
environment: str | None = None,
compliance_requirements: str | None = None
) -> str:
"""Generate a prompt for security risk auditing of packages."""
messages = await audit_security_risks(packages, environment, compliance_requirements)
return messages[0].text
@mcp.prompt()
async def plan_package_migration_prompt(
from_package: str,
to_package: str,
codebase_size: str = "medium",
timeline: str | None = None,
team_size: int | None = None
) -> str:
"""Generate a comprehensive package migration plan prompt."""
messages = await plan_package_migration(from_package, to_package, codebase_size, timeline, team_size)
return messages[0].text
@mcp.prompt()
async def generate_migration_checklist_prompt(
migration_type: str,
packages_involved: list[str],
environment: str = "all"
) -> str:
"""Generate a detailed migration checklist prompt."""
messages = await generate_migration_checklist(migration_type, packages_involved, environment)
return messages[0].text
@click.command()
@click.option(
"--log-level",