CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-fastmcp

The fast, Pythonic way to build MCP servers and clients with minimal boilerplate code.

Pending
Overview
Eval results
Files

prompts.mddocs/

Prompts System

Prompts define reusable message templates to guide LLM interactions with parameter support and message formatting. The FastMCP prompts system provides structured ways to create and manage prompt templates that can be dynamically populated with parameters.

Capabilities

Prompt Classes

Base classes for creating and managing prompts with parameter support and message formatting.

class Prompt:
    def __init__(
        self,
        name: str,
        description: str,
        func: Callable,
        schema: dict | None = None
    ):
        """
        Base prompt class.
        
        Parameters:
        - name: Prompt name for client reference
        - description: Prompt description for LLM understanding
        - func: Python function that generates prompt content
        - schema: Optional custom JSON schema for parameters
        """

Prompt Manager

Manages prompt registration, retrieval, and execution within a FastMCP server.

class PromptManager:
    def add_prompt(self, prompt: Prompt) -> None:
        """
        Add a prompt to the manager.
        
        Parameters:
        - prompt: Prompt instance to add
        """
    
    def get_prompt(self, name: str) -> Prompt | None:
        """
        Get a prompt by name.
        
        Parameters:
        - name: Name of prompt to retrieve
        
        Returns:
        Prompt instance or None if not found
        """
    
    def list_prompts(self) -> list[Prompt]:
        """
        List all registered prompts.
        
        Returns:
        List of all prompt instances
        """

Message Helper

Helper function for creating structured message objects for LLM interactions.

def Message(
    role: Literal["user", "assistant", "system"],
    content: str | dict,
    name: str | None = None
) -> dict:
    """
    Create a structured message for LLM interactions.
    
    Parameters:
    - role: Message role (user, assistant, system)
    - content: Message content as string or structured data
    - name: Optional name for the message sender
    
    Returns:
    Formatted message dictionary
    """

Prompt Message Type

Type definition for prompt messages with role and content structure.

class PromptMessage:
    """Type for structured prompt messages with role-based content."""
    role: Literal["user", "assistant", "system"]
    content: str | dict
    name: str | None = None

Usage Examples

Basic Prompt Templates

from fastmcp import FastMCP

mcp = FastMCP("Prompt Server")

@mcp.prompt
def summarize_text(text: str, max_length: int = 100) -> str:
    """
    Generate a prompt for text summarization.
    
    Parameters:
    - text: Text to summarize
    - max_length: Maximum length of summary in words
    
    Returns:
    Summarization prompt
    """
    return f"""Please provide a concise summary of the following text in no more than {max_length} words:

Text to summarize:
{text}

Summary:"""

@mcp.prompt
def analyze_sentiment(text: str) -> str:
    """
    Generate a prompt for sentiment analysis.
    
    Parameters:
    - text: Text to analyze for sentiment
    
    Returns:
    Sentiment analysis prompt
    """
    return f"""Analyze the sentiment of the following text and classify it as positive, negative, or neutral. Provide a brief explanation for your classification.

Text: "{text}"

Sentiment analysis:"""

@mcp.prompt
def translate_text(text: str, target_language: str, source_language: str = "auto") -> str:
    """
    Generate a prompt for text translation.
    
    Parameters:
    - text: Text to translate
    - target_language: Target language for translation
    - source_language: Source language (defaults to auto-detect)
    
    Returns:
    Translation prompt
    """
    source_info = f" from {source_language}" if source_language != "auto" else ""
    
    return f"""Translate the following text{source_info} to {target_language}:

Original text: "{text}"

Translation:"""

Structured Message Prompts

from fastmcp import FastMCP
from fastmcp.prompts import Message

mcp = FastMCP("Advanced Prompt Server")

@mcp.prompt
def code_review(code: str, language: str, focus_areas: list[str] = None) -> list[dict]:
    """
    Generate a structured prompt for code review.
    
    Parameters:
    - code: Code to review
    - language: Programming language
    - focus_areas: Optional list of areas to focus on
    
    Returns:
    List of message objects for code review conversation
    """
    focus_text = ""
    if focus_areas:
        focus_text = f"\n\nPlease pay special attention to: {', '.join(focus_areas)}"
    
    return [
        Message(
            role="system",
            content=f"""You are an expert {language} code reviewer. Provide constructive feedback on code quality, best practices, potential issues, and suggestions for improvement.{focus_text}"""
        ),
        Message(
            role="user", 
            content=f"""Please review the following {language} code:

```{language}
{code}

Provide your review covering:

  1. Code quality and readability
  2. Potential bugs or issues
  3. Performance considerations
  4. Best practice recommendations
  5. Security concerns (if applicable)""" ) ]

@mcp.prompt def data_analysis_prompt( data_description: str, analysis_type: str, context: str = "", output_format: str = "detailed report" ) -> list[dict]: """ Generate a structured prompt for data analysis.

Parameters:
- data_description: Description of the data to analyze
- analysis_type: Type of analysis to perform
- context: Additional context about the data or goals  
- output_format: Desired format for the analysis output

Returns:
List of message objects for data analysis conversation
"""
context_text = f"\n\nContext: {context}" if context else ""

return [
    Message(
        role="system",
        content=f"""You are a data analyst expert. Provide thorough analysis based on the given data and requirements. Format your response as a {output_format}.{context_text}"""
    ),
    Message(
        role="user",
        content=f"""Please perform a {analysis_type} analysis on the following data:

Data Description: {data_description}

Please provide:

  1. Key insights and findings
  2. Statistical summary (if applicable)
  3. Trends and patterns identified
  4. Recommendations based on the analysis
  5. Any limitations or considerations

Format the output as: {output_format}""" ) ]

@mcp.prompt def creative_writing( genre: str, theme: str, length: str = "short story", style: str = "narrative", characters: list[str] = None ) -> list[dict]: """ Generate a creative writing prompt with detailed instructions.

Parameters:
- genre: Writing genre (sci-fi, mystery, romance, etc.)
- theme: Central theme or topic
- length: Desired length (short story, novel chapter, etc.)
- style: Writing style (narrative, dialogue-heavy, etc.)
- characters: Optional list of character descriptions

Returns:
List of message objects for creative writing
"""
char_text = ""
if characters:
    char_text = f"\n\nCharacters to include:\n" + "\n".join([f"- {char}" for char in characters])

return [
    Message(
        role="system",
        content=f"""You are a creative writer specializing in {genre} fiction. Write engaging, well-structured content that captures the reader's attention and develops the given theme effectively.{char_text}"""
    ),
    Message(
        role="user",
        content=f"""Write a {length} in the {genre} genre with a {style} style.

Theme: {theme}

Requirements:

  1. Develop the theme throughout the story
  2. Use vivid descriptions and engaging dialogue
  3. Create compelling characters and conflicts
  4. Maintain consistency in tone and style
  5. Provide a satisfying conclusion

Begin writing:""" ) ]

### Contextual and Dynamic Prompts

```python
from fastmcp import FastMCP, Context
from fastmcp.prompts import Message

mcp = FastMCP("Dynamic Prompt Server")

@mcp.prompt
async def research_prompt(
    topic: str,
    depth: str = "comprehensive",
    sources_required: bool = True,
    ctx: Context = None
) -> list[dict]:
    """
    Generate a research prompt with dynamic context awareness.
    
    Parameters:
    - topic: Research topic
    - depth: Research depth (basic, comprehensive, expert)
    - sources_required: Whether to require source citations
    - ctx: Execution context for additional capabilities
    
    Returns:
    List of message objects for research task
    """
    if ctx:
        await ctx.info(f"Generating research prompt for topic: {topic}")
    
    depth_instructions = {
        "basic": "Provide a general overview with key points",
        "comprehensive": "Provide detailed analysis with examples and explanations",
        "expert": "Provide in-depth analysis with technical details and expert insights"
    }
    
    sources_text = ""
    if sources_required:
        sources_text = "\n\nIMPORTANT: Include citations and references for all claims and information."
    
    return [
        Message(
            role="system",
            content=f"""You are a research expert. Provide {depth} research on the requested topic. {depth_instructions[depth]}{sources_text}"""
        ),
        Message(
            role="user",
            content=f"""Research the following topic: {topic}

Please provide:
1. Executive summary
2. Key findings and insights
3. Supporting evidence and examples
4. Current trends and developments
5. Implications and recommendations
6. Areas for further research

Research depth: {depth}"""
        )
    ]

@mcp.prompt
async def meeting_prep(
    meeting_type: str,
    participants: list[str],
    agenda_items: list[str],
    duration: int = 60,
    ctx: Context = None
) -> str:
    """
    Generate meeting preparation prompt.
    
    Parameters:
    - meeting_type: Type of meeting (standup, planning, review, etc.)
    - participants: List of participant names/roles
    - agenda_items: List of agenda items to cover
    - duration: Meeting duration in minutes
    - ctx: Execution context
    
    Returns:
    Meeting preparation prompt
    """
    if ctx:
        await ctx.info(f"Preparing {meeting_type} meeting for {len(participants)} participants")
    
    participants_text = "\n".join([f"- {p}" for p in participants])
    agenda_text = "\n".join([f"{i+1}. {item}" for i, item in enumerate(agenda_items)])
    
    return f"""Prepare for a {meeting_type} meeting with the following details:

Duration: {duration} minutes
Participants:
{participants_text}

Agenda:
{agenda_text}

Please help me prepare by providing:
1. Key talking points for each agenda item
2. Potential questions that might arise
3. Time allocation suggestions
4. Action items template
5. Follow-up tasks to consider

Meeting preparation notes:"""

@mcp.prompt
def learning_plan(
    subject: str,
    current_level: str,
    target_level: str,
    timeframe: str = "3 months",
    learning_style: str = "mixed"
) -> list[dict]:
    """
    Generate a personalized learning plan prompt.
    
    Parameters:
    - subject: Subject to learn
    - current_level: Current skill level (beginner, intermediate, advanced)
    - target_level: Target skill level
    - timeframe: Available time for learning
    - learning_style: Preferred learning style (visual, hands-on, mixed)
    
    Returns:
    List of message objects for learning plan generation
    """
    return [
        Message(
            role="system",
            content=f"""You are an educational expert and learning coach. Create personalized learning plans that are practical, achievable, and tailored to the learner's style and goals."""
        ),
        Message(
            role="user",
            content=f"""Create a learning plan for the following:

Subject: {subject}
Current Level: {current_level}
Target Level: {target_level}
Timeframe: {timeframe}
Learning Style: {learning_style}

Please provide:
1. Learning objectives and milestones
2. Recommended resources (books, courses, videos, etc.)
3. Practice exercises and projects
4. Weekly schedule and time allocation
5. Assessment methods to track progress
6. Tips for staying motivated
7. Common challenges and how to overcome them

Learning Plan:"""
        )
    ]

Multi-Language and Specialized Prompts

from fastmcp import FastMCP
from fastmcp.prompts import Message

mcp = FastMCP("Specialized Prompt Server")

@mcp.prompt
def multilingual_prompt(
    task: str,
    languages: list[str],
    content: str,
    output_language: str = "English"
) -> str:
    """
    Generate multilingual processing prompt.
    
    Parameters:
    - task: Task to perform (translate, analyze, compare)
    - languages: List of languages involved
    - content: Content to process
    - output_language: Language for the output
    
    Returns:
    Multilingual processing prompt
    """
    languages_text = ", ".join(languages)
    
    return f"""Perform the following task: {task}

Languages involved: {languages_text}
Output language: {output_language}

Content to process:
{content}

Instructions:
- Process the content according to the specified task
- Consider cultural and linguistic nuances
- Provide output in {output_language}
- Explain any cultural or linguistic considerations

Result:"""

@mcp.prompt  
def technical_documentation(
    component: str,
    audience: str = "developers",
    format: str = "API documentation",
    include_examples: bool = True
) -> list[dict]:
    """
    Generate technical documentation writing prompt.
    
    Parameters:
    - component: Component or system to document
    - audience: Target audience (developers, users, administrators)
    - format: Documentation format (API docs, user guide, tutorial)
    - include_examples: Whether to include code examples
    
    Returns:
    List of message objects for technical documentation
    """
    examples_text = ""
    if include_examples:
        examples_text = "\n- Include practical code examples and usage scenarios"
    
    return [
        Message(
            role="system",
            content=f"""You are a technical writer specializing in {format}. Write clear, comprehensive documentation for {audience}. Use appropriate technical language and structure.{examples_text}"""
        ),
        Message(
            role="user",
            content=f"""Create {format} for the following component: {component}

Target audience: {audience}

Please include:
1. Overview and purpose
2. Installation/setup instructions (if applicable)
3. Configuration options
4. API reference or feature descriptions
5. Usage examples and best practices
6. Troubleshooting common issues
7. Related resources or references

Documentation:"""
        )
    ]

@mcp.prompt
def business_analysis(
    business_scenario: str,
    analysis_framework: str = "SWOT",
    stakeholders: list[str] = None,
    constraints: list[str] = None
) -> list[dict]:
    """
    Generate business analysis prompt using specified framework.
    
    Parameters:
    - business_scenario: Business situation to analyze
    - analysis_framework: Framework to use (SWOT, Porter's Five Forces, etc.)
    - stakeholders: List of stakeholder groups
    - constraints: List of constraints or limitations
    
    Returns:  
    List of message objects for business analysis
    """
    stakeholder_text = ""
    if stakeholders:
        stakeholder_text = f"\n\nStakeholders: {', '.join(stakeholders)}"
    
    constraints_text = ""
    if constraints:
        constraints_text = f"\n\nConstraints: {', '.join(constraints)}"
    
    return [
        Message(
            role="system", 
            content=f"""You are a business analyst expert. Conduct thorough analysis using the {analysis_framework} framework. Provide actionable insights and recommendations.{stakeholder_text}{constraints_text}"""
        ),
        Message(
            role="user",
            content=f"""Analyze the following business scenario using {analysis_framework} analysis:

Scenario:
{business_scenario}

Please provide:
1. {analysis_framework} analysis breakdown
2. Key insights and findings
3. Strategic recommendations
4. Risk assessment
5. Implementation considerations
6. Success metrics and KPIs

Analysis:"""
        )
    ]

Prompt Return Types

Prompts can return different formats:

# Simple string prompt
@mcp.prompt
def simple_prompt(topic: str) -> str:
    return f"Write about {topic}"

# List of message dictionaries  
@mcp.prompt
def structured_prompt(query: str) -> list[dict]:
    return [
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": query}
    ]

# Using Message helper
@mcp.prompt
def helper_prompt(task: str) -> list[dict]:
    return [
        Message("system", "You are an expert consultant."),
        Message("user", f"Help me with: {task}")
    ]

Install with Tessl CLI

npx tessl i tessl/pypi-fastmcp

docs

authentication.md

client.md

context.md

index.md

prompts.md

resources.md

server.md

tools.md

transports.md

utilities.md

tile.json