Spec Registry
Help your agents use open-source better. Learn more.
Find usage specs for your project’s dependencies
- Author
- tessl
- Last updated
- Spec files
pypi-fastmcp
Describes: pypi/fastmcp
- Description
- The fast, Pythonic way to build MCP servers and clients with minimal boilerplate code.
- Author
- tessl
- Last updated
prompts.md docs/
1# Prompts System23Prompts 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.45## Capabilities67### Prompt Classes89Base classes for creating and managing prompts with parameter support and message formatting.1011```python { .api }12class Prompt:13def __init__(14self,15name: str,16description: str,17func: Callable,18schema: dict | None = None19):20"""21Base prompt class.2223Parameters:24- name: Prompt name for client reference25- description: Prompt description for LLM understanding26- func: Python function that generates prompt content27- schema: Optional custom JSON schema for parameters28"""29```3031### Prompt Manager3233Manages prompt registration, retrieval, and execution within a FastMCP server.3435```python { .api }36class PromptManager:37def add_prompt(self, prompt: Prompt) -> None:38"""39Add a prompt to the manager.4041Parameters:42- prompt: Prompt instance to add43"""4445def get_prompt(self, name: str) -> Prompt | None:46"""47Get a prompt by name.4849Parameters:50- name: Name of prompt to retrieve5152Returns:53Prompt instance or None if not found54"""5556def list_prompts(self) -> list[Prompt]:57"""58List all registered prompts.5960Returns:61List of all prompt instances62"""63```6465### Message Helper6667Helper function for creating structured message objects for LLM interactions.6869```python { .api }70def Message(71role: Literal["user", "assistant", "system"],72content: str | dict,73name: str | None = None74) -> dict:75"""76Create a structured message for LLM interactions.7778Parameters:79- role: Message role (user, assistant, system)80- content: Message content as string or structured data81- name: Optional name for the message sender8283Returns:84Formatted message dictionary85"""86```8788### Prompt Message Type8990Type definition for prompt messages with role and content structure.9192```python { .api }93class PromptMessage:94"""Type for structured prompt messages with role-based content."""95role: Literal["user", "assistant", "system"]96content: str | dict97name: str | None = None98```99100## Usage Examples101102### Basic Prompt Templates103104```python105from fastmcp import FastMCP106107mcp = FastMCP("Prompt Server")108109@mcp.prompt110def summarize_text(text: str, max_length: int = 100) -> str:111"""112Generate a prompt for text summarization.113114Parameters:115- text: Text to summarize116- max_length: Maximum length of summary in words117118Returns:119Summarization prompt120"""121return f"""Please provide a concise summary of the following text in no more than {max_length} words:122123Text to summarize:124{text}125126Summary:"""127128@mcp.prompt129def analyze_sentiment(text: str) -> str:130"""131Generate a prompt for sentiment analysis.132133Parameters:134- text: Text to analyze for sentiment135136Returns:137Sentiment analysis prompt138"""139return f"""Analyze the sentiment of the following text and classify it as positive, negative, or neutral. Provide a brief explanation for your classification.140141Text: "{text}"142143Sentiment analysis:"""144145@mcp.prompt146def translate_text(text: str, target_language: str, source_language: str = "auto") -> str:147"""148Generate a prompt for text translation.149150Parameters:151- text: Text to translate152- target_language: Target language for translation153- source_language: Source language (defaults to auto-detect)154155Returns:156Translation prompt157"""158source_info = f" from {source_language}" if source_language != "auto" else ""159160return f"""Translate the following text{source_info} to {target_language}:161162Original text: "{text}"163164Translation:"""165```166167### Structured Message Prompts168169```python170from fastmcp import FastMCP171from fastmcp.prompts import Message172173mcp = FastMCP("Advanced Prompt Server")174175@mcp.prompt176def code_review(code: str, language: str, focus_areas: list[str] = None) -> list[dict]:177"""178Generate a structured prompt for code review.179180Parameters:181- code: Code to review182- language: Programming language183- focus_areas: Optional list of areas to focus on184185Returns:186List of message objects for code review conversation187"""188focus_text = ""189if focus_areas:190focus_text = f"\n\nPlease pay special attention to: {', '.join(focus_areas)}"191192return [193Message(194role="system",195content=f"""You are an expert {language} code reviewer. Provide constructive feedback on code quality, best practices, potential issues, and suggestions for improvement.{focus_text}"""196),197Message(198role="user",199content=f"""Please review the following {language} code:200201```{language}202{code}203```204205Provide your review covering:2061. Code quality and readability2072. Potential bugs or issues2083. Performance considerations2094. Best practice recommendations2105. Security concerns (if applicable)"""211)212]213214@mcp.prompt215def data_analysis_prompt(216data_description: str,217analysis_type: str,218context: str = "",219output_format: str = "detailed report"220) -> list[dict]:221"""222Generate a structured prompt for data analysis.223224Parameters:225- data_description: Description of the data to analyze226- analysis_type: Type of analysis to perform227- context: Additional context about the data or goals228- output_format: Desired format for the analysis output229230Returns:231List of message objects for data analysis conversation232"""233context_text = f"\n\nContext: {context}" if context else ""234235return [236Message(237role="system",238content=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}"""239),240Message(241role="user",242content=f"""Please perform a {analysis_type} analysis on the following data:243244Data Description:245{data_description}246247Please provide:2481. Key insights and findings2492. Statistical summary (if applicable)2503. Trends and patterns identified2514. Recommendations based on the analysis2525. Any limitations or considerations253254Format the output as: {output_format}"""255)256]257258@mcp.prompt259def creative_writing(260genre: str,261theme: str,262length: str = "short story",263style: str = "narrative",264characters: list[str] = None265) -> list[dict]:266"""267Generate a creative writing prompt with detailed instructions.268269Parameters:270- genre: Writing genre (sci-fi, mystery, romance, etc.)271- theme: Central theme or topic272- length: Desired length (short story, novel chapter, etc.)273- style: Writing style (narrative, dialogue-heavy, etc.)274- characters: Optional list of character descriptions275276Returns:277List of message objects for creative writing278"""279char_text = ""280if characters:281char_text = f"\n\nCharacters to include:\n" + "\n".join([f"- {char}" for char in characters])282283return [284Message(285role="system",286content=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}"""287),288Message(289role="user",290content=f"""Write a {length} in the {genre} genre with a {style} style.291292Theme: {theme}293294Requirements:2951. Develop the theme throughout the story2962. Use vivid descriptions and engaging dialogue2973. Create compelling characters and conflicts2984. Maintain consistency in tone and style2995. Provide a satisfying conclusion300301Begin writing:"""302)303]304```305306### Contextual and Dynamic Prompts307308```python309from fastmcp import FastMCP, Context310from fastmcp.prompts import Message311312mcp = FastMCP("Dynamic Prompt Server")313314@mcp.prompt315async def research_prompt(316topic: str,317depth: str = "comprehensive",318sources_required: bool = True,319ctx: Context = None320) -> list[dict]:321"""322Generate a research prompt with dynamic context awareness.323324Parameters:325- topic: Research topic326- depth: Research depth (basic, comprehensive, expert)327- sources_required: Whether to require source citations328- ctx: Execution context for additional capabilities329330Returns:331List of message objects for research task332"""333if ctx:334await ctx.info(f"Generating research prompt for topic: {topic}")335336depth_instructions = {337"basic": "Provide a general overview with key points",338"comprehensive": "Provide detailed analysis with examples and explanations",339"expert": "Provide in-depth analysis with technical details and expert insights"340}341342sources_text = ""343if sources_required:344sources_text = "\n\nIMPORTANT: Include citations and references for all claims and information."345346return [347Message(348role="system",349content=f"""You are a research expert. Provide {depth} research on the requested topic. {depth_instructions[depth]}{sources_text}"""350),351Message(352role="user",353content=f"""Research the following topic: {topic}354355Please provide:3561. Executive summary3572. Key findings and insights3583. Supporting evidence and examples3594. Current trends and developments3605. Implications and recommendations3616. Areas for further research362363Research depth: {depth}"""364)365]366367@mcp.prompt368async def meeting_prep(369meeting_type: str,370participants: list[str],371agenda_items: list[str],372duration: int = 60,373ctx: Context = None374) -> str:375"""376Generate meeting preparation prompt.377378Parameters:379- meeting_type: Type of meeting (standup, planning, review, etc.)380- participants: List of participant names/roles381- agenda_items: List of agenda items to cover382- duration: Meeting duration in minutes383- ctx: Execution context384385Returns:386Meeting preparation prompt387"""388if ctx:389await ctx.info(f"Preparing {meeting_type} meeting for {len(participants)} participants")390391participants_text = "\n".join([f"- {p}" for p in participants])392agenda_text = "\n".join([f"{i+1}. {item}" for i, item in enumerate(agenda_items)])393394return f"""Prepare for a {meeting_type} meeting with the following details:395396Duration: {duration} minutes397Participants:398{participants_text}399400Agenda:401{agenda_text}402403Please help me prepare by providing:4041. Key talking points for each agenda item4052. Potential questions that might arise4063. Time allocation suggestions4074. Action items template4085. Follow-up tasks to consider409410Meeting preparation notes:"""411412@mcp.prompt413def learning_plan(414subject: str,415current_level: str,416target_level: str,417timeframe: str = "3 months",418learning_style: str = "mixed"419) -> list[dict]:420"""421Generate a personalized learning plan prompt.422423Parameters:424- subject: Subject to learn425- current_level: Current skill level (beginner, intermediate, advanced)426- target_level: Target skill level427- timeframe: Available time for learning428- learning_style: Preferred learning style (visual, hands-on, mixed)429430Returns:431List of message objects for learning plan generation432"""433return [434Message(435role="system",436content=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."""437),438Message(439role="user",440content=f"""Create a learning plan for the following:441442Subject: {subject}443Current Level: {current_level}444Target Level: {target_level}445Timeframe: {timeframe}446Learning Style: {learning_style}447448Please provide:4491. Learning objectives and milestones4502. Recommended resources (books, courses, videos, etc.)4513. Practice exercises and projects4524. Weekly schedule and time allocation4535. Assessment methods to track progress4546. Tips for staying motivated4557. Common challenges and how to overcome them456457Learning Plan:"""458)459]460```461462### Multi-Language and Specialized Prompts463464```python465from fastmcp import FastMCP466from fastmcp.prompts import Message467468mcp = FastMCP("Specialized Prompt Server")469470@mcp.prompt471def multilingual_prompt(472task: str,473languages: list[str],474content: str,475output_language: str = "English"476) -> str:477"""478Generate multilingual processing prompt.479480Parameters:481- task: Task to perform (translate, analyze, compare)482- languages: List of languages involved483- content: Content to process484- output_language: Language for the output485486Returns:487Multilingual processing prompt488"""489languages_text = ", ".join(languages)490491return f"""Perform the following task: {task}492493Languages involved: {languages_text}494Output language: {output_language}495496Content to process:497{content}498499Instructions:500- Process the content according to the specified task501- Consider cultural and linguistic nuances502- Provide output in {output_language}503- Explain any cultural or linguistic considerations504505Result:"""506507@mcp.prompt508def technical_documentation(509component: str,510audience: str = "developers",511format: str = "API documentation",512include_examples: bool = True513) -> list[dict]:514"""515Generate technical documentation writing prompt.516517Parameters:518- component: Component or system to document519- audience: Target audience (developers, users, administrators)520- format: Documentation format (API docs, user guide, tutorial)521- include_examples: Whether to include code examples522523Returns:524List of message objects for technical documentation525"""526examples_text = ""527if include_examples:528examples_text = "\n- Include practical code examples and usage scenarios"529530return [531Message(532role="system",533content=f"""You are a technical writer specializing in {format}. Write clear, comprehensive documentation for {audience}. Use appropriate technical language and structure.{examples_text}"""534),535Message(536role="user",537content=f"""Create {format} for the following component: {component}538539Target audience: {audience}540541Please include:5421. Overview and purpose5432. Installation/setup instructions (if applicable)5443. Configuration options5454. API reference or feature descriptions5465. Usage examples and best practices5476. Troubleshooting common issues5487. Related resources or references549550Documentation:"""551)552]553554@mcp.prompt555def business_analysis(556business_scenario: str,557analysis_framework: str = "SWOT",558stakeholders: list[str] = None,559constraints: list[str] = None560) -> list[dict]:561"""562Generate business analysis prompt using specified framework.563564Parameters:565- business_scenario: Business situation to analyze566- analysis_framework: Framework to use (SWOT, Porter's Five Forces, etc.)567- stakeholders: List of stakeholder groups568- constraints: List of constraints or limitations569570Returns:571List of message objects for business analysis572"""573stakeholder_text = ""574if stakeholders:575stakeholder_text = f"\n\nStakeholders: {', '.join(stakeholders)}"576577constraints_text = ""578if constraints:579constraints_text = f"\n\nConstraints: {', '.join(constraints)}"580581return [582Message(583role="system",584content=f"""You are a business analyst expert. Conduct thorough analysis using the {analysis_framework} framework. Provide actionable insights and recommendations.{stakeholder_text}{constraints_text}"""585),586Message(587role="user",588content=f"""Analyze the following business scenario using {analysis_framework} analysis:589590Scenario:591{business_scenario}592593Please provide:5941. {analysis_framework} analysis breakdown5952. Key insights and findings5963. Strategic recommendations5974. Risk assessment5985. Implementation considerations5996. Success metrics and KPIs600601Analysis:"""602)603]604```605606## Prompt Return Types607608Prompts can return different formats:609610```python611# Simple string prompt612@mcp.prompt613def simple_prompt(topic: str) -> str:614return f"Write about {topic}"615616# List of message dictionaries617@mcp.prompt618def structured_prompt(query: str) -> list[dict]:619return [620{"role": "system", "content": "You are a helpful assistant."},621{"role": "user", "content": query}622]623624# Using Message helper625@mcp.prompt626def helper_prompt(task: str) -> list[dict]:627return [628Message("system", "You are an expert consultant."),629Message("user", f"Help me with: {task}")630]631```