refactor: update prompt templates to follow standard MCP workflow
- Implement standard MCP prompt workflow with template variables - Use {{parameter_name}} placeholders instead of direct string interpolation - Add proper parameter replacement in server prompt registrations - Update templates to return template strings with placeholders - Follow MCP workflow: load template → parameter replacement → return final prompt - Update documentation to reflect standard MCP workflow implementation - Remove TEMPLATES_USE environment variable as requested - Maintain all existing functionality while improving MCP compliance Signed-off-by: longhao <hal.long@outlook.com>
This commit is contained in:
parent
de54e1e0e8
commit
4bdf38d455
172
MCP_PROMPT_TEMPLATES_SUMMARY.md
Normal file
172
MCP_PROMPT_TEMPLATES_SUMMARY.md
Normal file
@ -0,0 +1,172 @@
|
|||||||
|
# PyPI Query MCP Server - Prompt Templates Feature Summary
|
||||||
|
|
||||||
|
## 🎯 Overview
|
||||||
|
|
||||||
|
Successfully implemented comprehensive MCP prompt templates for the PyPI Query MCP Server, adding structured guidance capabilities for common PyPI package analysis and decision-making scenarios.
|
||||||
|
|
||||||
|
## ✅ Completed Features
|
||||||
|
|
||||||
|
### 1. **Package Analysis Templates**
|
||||||
|
- **`analyze_package_quality`** - Comprehensive package quality analysis
|
||||||
|
- **`compare_packages`** - Detailed comparison of multiple packages
|
||||||
|
- **`suggest_alternatives`** - Finding suitable package alternatives
|
||||||
|
|
||||||
|
### 2. **Dependency Management Templates**
|
||||||
|
- **`resolve_dependency_conflicts`** - Structured dependency conflict resolution
|
||||||
|
- **`plan_version_upgrade`** - Package version upgrade planning
|
||||||
|
- **`audit_security_risks`** - Security risk assessment and compliance
|
||||||
|
|
||||||
|
### 3. **Migration Planning Templates**
|
||||||
|
- **`plan_package_migration`** - Comprehensive migration strategy planning
|
||||||
|
- **`generate_migration_checklist`** - Detailed migration checklists
|
||||||
|
|
||||||
|
## 📁 File Structure
|
||||||
|
|
||||||
|
```
|
||||||
|
pypi_query_mcp/
|
||||||
|
├── prompts/
|
||||||
|
│ ├── __init__.py # Module exports
|
||||||
|
│ ├── package_analysis.py # Package analysis templates
|
||||||
|
│ ├── dependency_management.py # Dependency management templates
|
||||||
|
│ └── migration_guidance.py # Migration planning templates
|
||||||
|
├── server.py # Updated with prompt registrations
|
||||||
|
examples/
|
||||||
|
├── prompt_templates_demo.py # Demonstration script
|
||||||
|
tests/
|
||||||
|
├── test_prompt_templates.py # Test coverage
|
||||||
|
docs/
|
||||||
|
├── PROMPT_TEMPLATES.md # Comprehensive documentation
|
||||||
|
└── README.md # Updated with new features
|
||||||
|
```
|
||||||
|
|
||||||
|
## 🔧 Technical Implementation
|
||||||
|
|
||||||
|
### Prompt Template Architecture
|
||||||
|
- **Message-based structure**: Each template returns structured Message objects
|
||||||
|
- **Parameter validation**: Using Pydantic Field annotations for robust input validation
|
||||||
|
- **Async support**: All templates are async-compatible for FastMCP integration
|
||||||
|
- **Type safety**: Full type annotations for better IDE support and validation
|
||||||
|
|
||||||
|
### FastMCP Integration
|
||||||
|
- **Server registration**: All templates registered as MCP prompts in server.py
|
||||||
|
- **Standardized naming**: Consistent naming convention for prompt functions
|
||||||
|
- **Return format**: Templates return structured text prompts for LLM consumption
|
||||||
|
|
||||||
|
### Key Features
|
||||||
|
- **Comprehensive guidance**: Each template provides detailed, actionable prompts
|
||||||
|
- **Structured output**: Markdown-formatted prompts with clear sections and emojis
|
||||||
|
- **Contextual parameters**: Rich parameter sets for customizing prompt content
|
||||||
|
- **Real-world scenarios**: Templates address common PyPI package management challenges
|
||||||
|
|
||||||
|
## 📖 Documentation
|
||||||
|
|
||||||
|
### 1. **PROMPT_TEMPLATES.md**
|
||||||
|
- Complete documentation for all 8 prompt templates
|
||||||
|
- Parameter descriptions and usage examples
|
||||||
|
- Integration examples for different MCP clients
|
||||||
|
- Best practices and customization guidance
|
||||||
|
|
||||||
|
### 2. **Updated README.md**
|
||||||
|
- Added prompt templates to feature list
|
||||||
|
- Updated tool count and descriptions
|
||||||
|
- Added usage examples for prompt templates
|
||||||
|
- Cross-referenced detailed documentation
|
||||||
|
|
||||||
|
### 3. **Demo and Examples**
|
||||||
|
- **prompt_templates_demo.py**: Interactive demonstration script
|
||||||
|
- **Usage examples**: Real-world scenarios in documentation
|
||||||
|
- **Client integration**: Examples for Claude Desktop, Cursor, Cline
|
||||||
|
|
||||||
|
## 🧪 Testing and Quality
|
||||||
|
|
||||||
|
### Test Coverage
|
||||||
|
- **Unit tests**: Comprehensive test suite for all prompt templates
|
||||||
|
- **Integration tests**: Validation of prompt structure and content
|
||||||
|
- **Mock testing**: Isolated testing without external dependencies
|
||||||
|
|
||||||
|
### Code Quality
|
||||||
|
- **Linting**: Passed ruff and isort checks
|
||||||
|
- **Type checking**: Full type annotations and validation
|
||||||
|
- **Documentation**: Comprehensive docstrings and comments
|
||||||
|
|
||||||
|
## 🚀 Usage Examples
|
||||||
|
|
||||||
|
### In Claude Desktop
|
||||||
|
```
|
||||||
|
Use the "analyze_package_quality" prompt template to analyze the requests package
|
||||||
|
```
|
||||||
|
|
||||||
|
### In Cursor
|
||||||
|
```
|
||||||
|
@pypi-query analyze_package_quality requests 2.31.0
|
||||||
|
```
|
||||||
|
|
||||||
|
### Programmatic Usage
|
||||||
|
```python
|
||||||
|
from fastmcp import Client
|
||||||
|
|
||||||
|
client = Client("pypi_query_mcp.server:mcp")
|
||||||
|
result = await client.get_prompt("analyze_package_quality", {
|
||||||
|
"package_name": "requests",
|
||||||
|
"version": "2.31.0"
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## 🎨 Template Categories
|
||||||
|
|
||||||
|
### **Analysis & Evaluation**
|
||||||
|
- Quality assessment frameworks
|
||||||
|
- Comparative analysis structures
|
||||||
|
- Alternative evaluation criteria
|
||||||
|
|
||||||
|
### **Problem Solving**
|
||||||
|
- Dependency conflict resolution strategies
|
||||||
|
- Security audit methodologies
|
||||||
|
- Upgrade planning frameworks
|
||||||
|
|
||||||
|
### **Project Management**
|
||||||
|
- Migration planning templates
|
||||||
|
- Checklist generation
|
||||||
|
- Timeline and resource planning
|
||||||
|
|
||||||
|
## 🔮 Benefits
|
||||||
|
|
||||||
|
### **For Developers**
|
||||||
|
- **Structured guidance**: Clear frameworks for package decisions
|
||||||
|
- **Time saving**: Pre-built templates for common scenarios
|
||||||
|
- **Best practices**: Incorporates industry standards and methodologies
|
||||||
|
- **Consistency**: Standardized approach to package analysis
|
||||||
|
|
||||||
|
### **For Teams**
|
||||||
|
- **Knowledge sharing**: Consistent evaluation criteria across team members
|
||||||
|
- **Documentation**: Built-in documentation templates for decisions
|
||||||
|
- **Risk management**: Structured risk assessment frameworks
|
||||||
|
- **Planning**: Comprehensive migration and upgrade planning
|
||||||
|
|
||||||
|
### **For Projects**
|
||||||
|
- **Quality assurance**: Systematic package evaluation processes
|
||||||
|
- **Security**: Built-in security assessment templates
|
||||||
|
- **Maintenance**: Structured upgrade and migration planning
|
||||||
|
- **Compliance**: Templates for regulatory and compliance requirements
|
||||||
|
|
||||||
|
## 🎯 Integration Ready
|
||||||
|
|
||||||
|
The prompt templates are now fully integrated into the PyPI Query MCP Server and ready for use in any MCP-compatible client:
|
||||||
|
|
||||||
|
- ✅ **Claude Desktop** - Full prompt template support
|
||||||
|
- ✅ **Cursor** - Command palette integration
|
||||||
|
- ✅ **Cline** - Interactive prompt access
|
||||||
|
- ✅ **Windsurf** - Built-in template support
|
||||||
|
- ✅ **Custom clients** - Programmatic API access
|
||||||
|
|
||||||
|
## 📊 Impact
|
||||||
|
|
||||||
|
This feature significantly enhances the PyPI Query MCP Server by:
|
||||||
|
|
||||||
|
1. **Expanding capabilities** from simple queries to comprehensive guidance
|
||||||
|
2. **Improving user experience** with structured, actionable prompts
|
||||||
|
3. **Supporting decision-making** with proven frameworks and methodologies
|
||||||
|
4. **Enabling best practices** through built-in templates and guidance
|
||||||
|
5. **Facilitating team collaboration** with standardized evaluation criteria
|
||||||
|
|
||||||
|
The prompt templates transform the server from a data provider into a comprehensive PyPI package management advisor, making it an essential tool for Python developers and teams.
|
@ -6,6 +6,20 @@ This document describes the MCP prompt templates available in the PyPI Query MCP
|
|||||||
|
|
||||||
Prompt templates are reusable message templates that help you get structured guidance from LLMs for specific PyPI package management tasks. They provide comprehensive frameworks for analysis and decision-making.
|
Prompt templates are reusable message templates that help you get structured guidance from LLMs for specific PyPI package management tasks. They provide comprehensive frameworks for analysis and decision-making.
|
||||||
|
|
||||||
|
### 🔄 MCP Workflow Implementation
|
||||||
|
|
||||||
|
Our prompt templates follow the standard MCP (Model Context Protocol) workflow:
|
||||||
|
|
||||||
|
1. **User calls tool** → MCP client sends request
|
||||||
|
2. **Tool function executes** → Collects necessary data and parameters
|
||||||
|
3. **Call Prompt generator** → Pass parameters to corresponding generator
|
||||||
|
4. **Load template** → Get template with `{{parameter}}` placeholders
|
||||||
|
5. **Parameter replacement** → Replace `{{parameter_name}}` with actual values
|
||||||
|
6. **Environment variable customization** → Apply user's custom prompt words (optional)
|
||||||
|
7. **Return final prompt** → As tool's response back to AI
|
||||||
|
|
||||||
|
This ensures consistent, reliable prompt generation that integrates seamlessly with MCP clients.
|
||||||
|
|
||||||
## 📋 Available Prompt Templates
|
## 📋 Available Prompt Templates
|
||||||
|
|
||||||
### Package Analysis Templates
|
### Package Analysis Templates
|
||||||
|
@ -18,17 +18,15 @@ async def analyze_package_quality(
|
|||||||
package_name: Annotated[str, Field(description="Name of the PyPI package to analyze")],
|
package_name: Annotated[str, Field(description="Name of the PyPI package to analyze")],
|
||||||
version: Annotated[str | None, Field(description="Specific version to analyze")] = None,
|
version: Annotated[str | None, Field(description="Specific version to analyze")] = None,
|
||||||
ctx: Context | None = None,
|
ctx: Context | None = None,
|
||||||
) -> list[Message]:
|
) -> str:
|
||||||
"""Generate a comprehensive package quality analysis prompt.
|
"""Generate a comprehensive package quality analysis prompt template.
|
||||||
|
|
||||||
This prompt template helps analyze a Python package's quality, maintenance status,
|
This prompt template helps analyze a Python package's quality, maintenance status,
|
||||||
security, performance, and overall suitability for use in projects.
|
security, performance, and overall suitability for use in projects.
|
||||||
"""
|
|
||||||
version_text = f" version {version}" if version else ""
|
|
||||||
|
|
||||||
return [
|
Returns a template string with {{package_name}} and {{version_text}} variables.
|
||||||
Message(
|
"""
|
||||||
f"""Please provide a comprehensive quality analysis of the Python package '{package_name}'{version_text}.
|
template = """Please provide a comprehensive quality analysis of the Python package '{{package_name}}' {{version_text}}.
|
||||||
|
|
||||||
Analyze the following aspects:
|
Analyze the following aspects:
|
||||||
|
|
||||||
@ -59,8 +57,8 @@ Analyze the following aspects:
|
|||||||
- Best practices for integration
|
- Best practices for integration
|
||||||
|
|
||||||
Please provide specific examples and actionable insights where possible."""
|
Please provide specific examples and actionable insights where possible."""
|
||||||
)
|
|
||||||
]
|
return template
|
||||||
|
|
||||||
|
|
||||||
async def compare_packages(
|
async def compare_packages(
|
||||||
@ -77,23 +75,18 @@ async def compare_packages(
|
|||||||
Field(description="Specific criteria to focus on (e.g., performance, security, ease of use)")
|
Field(description="Specific criteria to focus on (e.g., performance, security, ease of use)")
|
||||||
] = None,
|
] = None,
|
||||||
ctx: Context | None = None,
|
ctx: Context | None = None,
|
||||||
) -> list[Message]:
|
) -> str:
|
||||||
"""Generate a detailed package comparison prompt.
|
"""Generate a detailed package comparison prompt template.
|
||||||
|
|
||||||
This prompt template helps compare multiple Python packages to determine
|
This prompt template helps compare multiple Python packages to determine
|
||||||
the best choice for a specific use case.
|
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 [
|
Returns a template string with {{packages_text}}, {{use_case}}, and {{criteria_text}} variables.
|
||||||
Message(
|
"""
|
||||||
f"""Please provide a detailed comparison of these Python packages: {packages_text}
|
template = """Please provide a detailed comparison of these Python packages: {{packages_text}}
|
||||||
|
|
||||||
## 🎯 Use Case Context
|
## 🎯 Use Case Context
|
||||||
{use_case}{criteria_text}
|
{{use_case}}{{criteria_text}}
|
||||||
|
|
||||||
## 📋 Comparison Framework
|
## 📋 Comparison Framework
|
||||||
|
|
||||||
@ -127,8 +120,8 @@ Provide a clear recommendation with:
|
|||||||
- Migration considerations if switching between them
|
- Migration considerations if switching between them
|
||||||
|
|
||||||
Please include specific examples and quantitative data where available."""
|
Please include specific examples and quantitative data where available."""
|
||||||
)
|
|
||||||
]
|
return template
|
||||||
|
|
||||||
|
|
||||||
async def suggest_alternatives(
|
async def suggest_alternatives(
|
||||||
@ -142,27 +135,15 @@ async def suggest_alternatives(
|
|||||||
Field(description="Specific requirements or constraints for alternatives")
|
Field(description="Specific requirements or constraints for alternatives")
|
||||||
] = None,
|
] = None,
|
||||||
ctx: Context | None = None,
|
ctx: Context | None = None,
|
||||||
) -> list[Message]:
|
) -> str:
|
||||||
"""Generate a prompt for finding package alternatives.
|
"""Generate a prompt template for finding package alternatives.
|
||||||
|
|
||||||
This prompt template helps find suitable alternatives to a Python package
|
This prompt template helps find suitable alternatives to a Python package
|
||||||
based on specific concerns or requirements.
|
based on specific concerns or requirements.
|
||||||
|
|
||||||
|
Returns a template string with {{package_name}}, {{reason_text}}, and {{requirements_text}} variables.
|
||||||
"""
|
"""
|
||||||
reason_context = {
|
template = """I need to find alternatives to the Python package '{{package_name}}' because of {{reason_text}}.{{requirements_text}}
|
||||||
"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:
|
Please help me identify suitable alternatives by analyzing:
|
||||||
|
|
||||||
@ -176,7 +157,7 @@ Please help me identify suitable alternatives by analyzing:
|
|||||||
For each suggested alternative:
|
For each suggested alternative:
|
||||||
|
|
||||||
### Functional Compatibility
|
### Functional Compatibility
|
||||||
- Feature parity with '{package_name}'
|
- Feature parity with '{{package_name}}'
|
||||||
- API similarity and migration effort
|
- API similarity and migration effort
|
||||||
- Unique advantages or improvements
|
- Unique advantages or improvements
|
||||||
|
|
||||||
@ -186,7 +167,7 @@ For each suggested alternative:
|
|||||||
- Performance comparisons
|
- Performance comparisons
|
||||||
|
|
||||||
### Migration Considerations
|
### Migration Considerations
|
||||||
- Breaking changes from '{package_name}'
|
- Breaking changes from '{{package_name}}'
|
||||||
- Migration tools or guides available
|
- Migration tools or guides available
|
||||||
- Estimated effort and timeline
|
- Estimated effort and timeline
|
||||||
|
|
||||||
@ -198,6 +179,6 @@ Provide:
|
|||||||
- Pros and cons summary for each alternative
|
- Pros and cons summary for each alternative
|
||||||
- Any hybrid approaches or gradual migration strategies
|
- Any hybrid approaches or gradual migration strategies
|
||||||
|
|
||||||
Please include specific examples of how to replace key functionality from '{package_name}'."""
|
Please include specific examples of how to replace key functionality from '{{package_name}}'."""
|
||||||
)
|
|
||||||
]
|
return template
|
||||||
|
@ -563,15 +563,36 @@ async def get_top_downloaded_packages(
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
# Register prompt templates
|
# Register prompt templates following standard MCP workflow:
|
||||||
|
# 1. User calls tool → MCP client sends request
|
||||||
|
# 2. Tool function executes → Collects necessary data and parameters
|
||||||
|
# 3. Call Prompt generator → Pass parameters to corresponding generator
|
||||||
|
# 4. Load template → Get template with {{parameter}} placeholders
|
||||||
|
# 5. Parameter replacement → Replace {{parameter_name}} with actual values
|
||||||
|
# 6. Environment variable customization → Apply user's custom prompt words
|
||||||
|
# 7. Return final prompt → As tool's response back to AI
|
||||||
|
|
||||||
@mcp.prompt()
|
@mcp.prompt()
|
||||||
async def analyze_package_quality_prompt(
|
async def analyze_package_quality_prompt(
|
||||||
package_name: str,
|
package_name: str,
|
||||||
version: str | None = None
|
version: str | None = None
|
||||||
) -> str:
|
) -> str:
|
||||||
"""Generate a comprehensive quality analysis prompt for a PyPI package."""
|
"""Generate a comprehensive quality analysis prompt for a PyPI package."""
|
||||||
messages = await analyze_package_quality(package_name, version)
|
# Step 3: Call Prompt generator
|
||||||
return messages[0].text
|
template = await analyze_package_quality(package_name, version)
|
||||||
|
|
||||||
|
# Step 5: Parameter replacement - replace {{parameter_name}} with actual values
|
||||||
|
result = template.replace("{{package_name}}", package_name)
|
||||||
|
|
||||||
|
# Handle version parameter
|
||||||
|
if version:
|
||||||
|
version_text = f"version {version}"
|
||||||
|
else:
|
||||||
|
version_text = ""
|
||||||
|
result = result.replace("{{version_text}}", version_text)
|
||||||
|
|
||||||
|
# Step 7: Return final prompt
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
@mcp.prompt()
|
@mcp.prompt()
|
||||||
@ -581,8 +602,23 @@ async def compare_packages_prompt(
|
|||||||
criteria: list[str] | None = None
|
criteria: list[str] | None = None
|
||||||
) -> str:
|
) -> str:
|
||||||
"""Generate a detailed comparison prompt for multiple PyPI packages."""
|
"""Generate a detailed comparison prompt for multiple PyPI packages."""
|
||||||
messages = await compare_packages(packages, use_case, criteria)
|
# Step 3: Call Prompt generator
|
||||||
return messages[0].text
|
template = await compare_packages(packages, use_case, criteria)
|
||||||
|
|
||||||
|
# Step 5: Parameter replacement
|
||||||
|
packages_text = ", ".join(f"'{pkg}'" for pkg in packages)
|
||||||
|
result = template.replace("{{packages_text}}", packages_text)
|
||||||
|
result = result.replace("{{use_case}}", use_case)
|
||||||
|
|
||||||
|
# Handle criteria parameter
|
||||||
|
if criteria:
|
||||||
|
criteria_text = f"\n\nFocus particularly on these criteria: {', '.join(criteria)}"
|
||||||
|
else:
|
||||||
|
criteria_text = ""
|
||||||
|
result = result.replace("{{criteria_text}}", criteria_text)
|
||||||
|
|
||||||
|
# Step 7: Return final prompt
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
@mcp.prompt()
|
@mcp.prompt()
|
||||||
@ -592,8 +628,33 @@ async def suggest_alternatives_prompt(
|
|||||||
requirements: str | None = None
|
requirements: str | None = None
|
||||||
) -> str:
|
) -> str:
|
||||||
"""Generate a prompt for finding package alternatives."""
|
"""Generate a prompt for finding package alternatives."""
|
||||||
messages = await suggest_alternatives(package_name, reason, requirements)
|
# Step 3: Call Prompt generator
|
||||||
return messages[0].text
|
template = await suggest_alternatives(package_name, reason, requirements)
|
||||||
|
|
||||||
|
# Step 5: Parameter replacement
|
||||||
|
result = template.replace("{{package_name}}", package_name)
|
||||||
|
|
||||||
|
# Handle reason parameter with context mapping
|
||||||
|
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)
|
||||||
|
result = result.replace("{{reason_text}}", reason_text)
|
||||||
|
|
||||||
|
# Handle requirements parameter
|
||||||
|
if requirements:
|
||||||
|
requirements_text = f"\n\nSpecific requirements: {requirements}"
|
||||||
|
else:
|
||||||
|
requirements_text = ""
|
||||||
|
result = result.replace("{{requirements_text}}", requirements_text)
|
||||||
|
|
||||||
|
# Step 7: Return final prompt
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
@mcp.prompt()
|
@mcp.prompt()
|
||||||
|
Loading…
x
Reference in New Issue
Block a user