0
# Prompts System
1
2
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.
3
4
## Capabilities
5
6
### Prompt Classes
7
8
Base classes for creating and managing prompts with parameter support and message formatting.
9
10
```python { .api }
11
class Prompt:
12
def __init__(
13
self,
14
name: str,
15
description: str,
16
func: Callable,
17
schema: dict | None = None
18
):
19
"""
20
Base prompt class.
21
22
Parameters:
23
- name: Prompt name for client reference
24
- description: Prompt description for LLM understanding
25
- func: Python function that generates prompt content
26
- schema: Optional custom JSON schema for parameters
27
"""
28
```
29
30
### Prompt Manager
31
32
Manages prompt registration, retrieval, and execution within a FastMCP server.
33
34
```python { .api }
35
class PromptManager:
36
def add_prompt(self, prompt: Prompt) -> None:
37
"""
38
Add a prompt to the manager.
39
40
Parameters:
41
- prompt: Prompt instance to add
42
"""
43
44
def get_prompt(self, name: str) -> Prompt | None:
45
"""
46
Get a prompt by name.
47
48
Parameters:
49
- name: Name of prompt to retrieve
50
51
Returns:
52
Prompt instance or None if not found
53
"""
54
55
def list_prompts(self) -> list[Prompt]:
56
"""
57
List all registered prompts.
58
59
Returns:
60
List of all prompt instances
61
"""
62
```
63
64
### Message Helper
65
66
Helper function for creating structured message objects for LLM interactions.
67
68
```python { .api }
69
def Message(
70
role: Literal["user", "assistant", "system"],
71
content: str | dict,
72
name: str | None = None
73
) -> dict:
74
"""
75
Create a structured message for LLM interactions.
76
77
Parameters:
78
- role: Message role (user, assistant, system)
79
- content: Message content as string or structured data
80
- name: Optional name for the message sender
81
82
Returns:
83
Formatted message dictionary
84
"""
85
```
86
87
### Prompt Message Type
88
89
Type definition for prompt messages with role and content structure.
90
91
```python { .api }
92
class PromptMessage:
93
"""Type for structured prompt messages with role-based content."""
94
role: Literal["user", "assistant", "system"]
95
content: str | dict
96
name: str | None = None
97
```
98
99
## Usage Examples
100
101
### Basic Prompt Templates
102
103
```python
104
from fastmcp import FastMCP
105
106
mcp = FastMCP("Prompt Server")
107
108
@mcp.prompt
109
def summarize_text(text: str, max_length: int = 100) -> str:
110
"""
111
Generate a prompt for text summarization.
112
113
Parameters:
114
- text: Text to summarize
115
- max_length: Maximum length of summary in words
116
117
Returns:
118
Summarization prompt
119
"""
120
return f"""Please provide a concise summary of the following text in no more than {max_length} words:
121
122
Text to summarize:
123
{text}
124
125
Summary:"""
126
127
@mcp.prompt
128
def analyze_sentiment(text: str) -> str:
129
"""
130
Generate a prompt for sentiment analysis.
131
132
Parameters:
133
- text: Text to analyze for sentiment
134
135
Returns:
136
Sentiment analysis prompt
137
"""
138
return f"""Analyze the sentiment of the following text and classify it as positive, negative, or neutral. Provide a brief explanation for your classification.
139
140
Text: "{text}"
141
142
Sentiment analysis:"""
143
144
@mcp.prompt
145
def translate_text(text: str, target_language: str, source_language: str = "auto") -> str:
146
"""
147
Generate a prompt for text translation.
148
149
Parameters:
150
- text: Text to translate
151
- target_language: Target language for translation
152
- source_language: Source language (defaults to auto-detect)
153
154
Returns:
155
Translation prompt
156
"""
157
source_info = f" from {source_language}" if source_language != "auto" else ""
158
159
return f"""Translate the following text{source_info} to {target_language}:
160
161
Original text: "{text}"
162
163
Translation:"""
164
```
165
166
### Structured Message Prompts
167
168
```python
169
from fastmcp import FastMCP
170
from fastmcp.prompts import Message
171
172
mcp = FastMCP("Advanced Prompt Server")
173
174
@mcp.prompt
175
def code_review(code: str, language: str, focus_areas: list[str] = None) -> list[dict]:
176
"""
177
Generate a structured prompt for code review.
178
179
Parameters:
180
- code: Code to review
181
- language: Programming language
182
- focus_areas: Optional list of areas to focus on
183
184
Returns:
185
List of message objects for code review conversation
186
"""
187
focus_text = ""
188
if focus_areas:
189
focus_text = f"\n\nPlease pay special attention to: {', '.join(focus_areas)}"
190
191
return [
192
Message(
193
role="system",
194
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}"""
195
),
196
Message(
197
role="user",
198
content=f"""Please review the following {language} code:
199
200
```{language}
201
{code}
202
```
203
204
Provide your review covering:
205
1. Code quality and readability
206
2. Potential bugs or issues
207
3. Performance considerations
208
4. Best practice recommendations
209
5. Security concerns (if applicable)"""
210
)
211
]
212
213
@mcp.prompt
214
def data_analysis_prompt(
215
data_description: str,
216
analysis_type: str,
217
context: str = "",
218
output_format: str = "detailed report"
219
) -> list[dict]:
220
"""
221
Generate a structured prompt for data analysis.
222
223
Parameters:
224
- data_description: Description of the data to analyze
225
- analysis_type: Type of analysis to perform
226
- context: Additional context about the data or goals
227
- output_format: Desired format for the analysis output
228
229
Returns:
230
List of message objects for data analysis conversation
231
"""
232
context_text = f"\n\nContext: {context}" if context else ""
233
234
return [
235
Message(
236
role="system",
237
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}"""
238
),
239
Message(
240
role="user",
241
content=f"""Please perform a {analysis_type} analysis on the following data:
242
243
Data Description:
244
{data_description}
245
246
Please provide:
247
1. Key insights and findings
248
2. Statistical summary (if applicable)
249
3. Trends and patterns identified
250
4. Recommendations based on the analysis
251
5. Any limitations or considerations
252
253
Format the output as: {output_format}"""
254
)
255
]
256
257
@mcp.prompt
258
def creative_writing(
259
genre: str,
260
theme: str,
261
length: str = "short story",
262
style: str = "narrative",
263
characters: list[str] = None
264
) -> list[dict]:
265
"""
266
Generate a creative writing prompt with detailed instructions.
267
268
Parameters:
269
- genre: Writing genre (sci-fi, mystery, romance, etc.)
270
- theme: Central theme or topic
271
- length: Desired length (short story, novel chapter, etc.)
272
- style: Writing style (narrative, dialogue-heavy, etc.)
273
- characters: Optional list of character descriptions
274
275
Returns:
276
List of message objects for creative writing
277
"""
278
char_text = ""
279
if characters:
280
char_text = f"\n\nCharacters to include:\n" + "\n".join([f"- {char}" for char in characters])
281
282
return [
283
Message(
284
role="system",
285
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}"""
286
),
287
Message(
288
role="user",
289
content=f"""Write a {length} in the {genre} genre with a {style} style.
290
291
Theme: {theme}
292
293
Requirements:
294
1. Develop the theme throughout the story
295
2. Use vivid descriptions and engaging dialogue
296
3. Create compelling characters and conflicts
297
4. Maintain consistency in tone and style
298
5. Provide a satisfying conclusion
299
300
Begin writing:"""
301
)
302
]
303
```
304
305
### Contextual and Dynamic Prompts
306
307
```python
308
from fastmcp import FastMCP, Context
309
from fastmcp.prompts import Message
310
311
mcp = FastMCP("Dynamic Prompt Server")
312
313
@mcp.prompt
314
async def research_prompt(
315
topic: str,
316
depth: str = "comprehensive",
317
sources_required: bool = True,
318
ctx: Context = None
319
) -> list[dict]:
320
"""
321
Generate a research prompt with dynamic context awareness.
322
323
Parameters:
324
- topic: Research topic
325
- depth: Research depth (basic, comprehensive, expert)
326
- sources_required: Whether to require source citations
327
- ctx: Execution context for additional capabilities
328
329
Returns:
330
List of message objects for research task
331
"""
332
if ctx:
333
await ctx.info(f"Generating research prompt for topic: {topic}")
334
335
depth_instructions = {
336
"basic": "Provide a general overview with key points",
337
"comprehensive": "Provide detailed analysis with examples and explanations",
338
"expert": "Provide in-depth analysis with technical details and expert insights"
339
}
340
341
sources_text = ""
342
if sources_required:
343
sources_text = "\n\nIMPORTANT: Include citations and references for all claims and information."
344
345
return [
346
Message(
347
role="system",
348
content=f"""You are a research expert. Provide {depth} research on the requested topic. {depth_instructions[depth]}{sources_text}"""
349
),
350
Message(
351
role="user",
352
content=f"""Research the following topic: {topic}
353
354
Please provide:
355
1. Executive summary
356
2. Key findings and insights
357
3. Supporting evidence and examples
358
4. Current trends and developments
359
5. Implications and recommendations
360
6. Areas for further research
361
362
Research depth: {depth}"""
363
)
364
]
365
366
@mcp.prompt
367
async def meeting_prep(
368
meeting_type: str,
369
participants: list[str],
370
agenda_items: list[str],
371
duration: int = 60,
372
ctx: Context = None
373
) -> str:
374
"""
375
Generate meeting preparation prompt.
376
377
Parameters:
378
- meeting_type: Type of meeting (standup, planning, review, etc.)
379
- participants: List of participant names/roles
380
- agenda_items: List of agenda items to cover
381
- duration: Meeting duration in minutes
382
- ctx: Execution context
383
384
Returns:
385
Meeting preparation prompt
386
"""
387
if ctx:
388
await ctx.info(f"Preparing {meeting_type} meeting for {len(participants)} participants")
389
390
participants_text = "\n".join([f"- {p}" for p in participants])
391
agenda_text = "\n".join([f"{i+1}. {item}" for i, item in enumerate(agenda_items)])
392
393
return f"""Prepare for a {meeting_type} meeting with the following details:
394
395
Duration: {duration} minutes
396
Participants:
397
{participants_text}
398
399
Agenda:
400
{agenda_text}
401
402
Please help me prepare by providing:
403
1. Key talking points for each agenda item
404
2. Potential questions that might arise
405
3. Time allocation suggestions
406
4. Action items template
407
5. Follow-up tasks to consider
408
409
Meeting preparation notes:"""
410
411
@mcp.prompt
412
def learning_plan(
413
subject: str,
414
current_level: str,
415
target_level: str,
416
timeframe: str = "3 months",
417
learning_style: str = "mixed"
418
) -> list[dict]:
419
"""
420
Generate a personalized learning plan prompt.
421
422
Parameters:
423
- subject: Subject to learn
424
- current_level: Current skill level (beginner, intermediate, advanced)
425
- target_level: Target skill level
426
- timeframe: Available time for learning
427
- learning_style: Preferred learning style (visual, hands-on, mixed)
428
429
Returns:
430
List of message objects for learning plan generation
431
"""
432
return [
433
Message(
434
role="system",
435
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."""
436
),
437
Message(
438
role="user",
439
content=f"""Create a learning plan for the following:
440
441
Subject: {subject}
442
Current Level: {current_level}
443
Target Level: {target_level}
444
Timeframe: {timeframe}
445
Learning Style: {learning_style}
446
447
Please provide:
448
1. Learning objectives and milestones
449
2. Recommended resources (books, courses, videos, etc.)
450
3. Practice exercises and projects
451
4. Weekly schedule and time allocation
452
5. Assessment methods to track progress
453
6. Tips for staying motivated
454
7. Common challenges and how to overcome them
455
456
Learning Plan:"""
457
)
458
]
459
```
460
461
### Multi-Language and Specialized Prompts
462
463
```python
464
from fastmcp import FastMCP
465
from fastmcp.prompts import Message
466
467
mcp = FastMCP("Specialized Prompt Server")
468
469
@mcp.prompt
470
def multilingual_prompt(
471
task: str,
472
languages: list[str],
473
content: str,
474
output_language: str = "English"
475
) -> str:
476
"""
477
Generate multilingual processing prompt.
478
479
Parameters:
480
- task: Task to perform (translate, analyze, compare)
481
- languages: List of languages involved
482
- content: Content to process
483
- output_language: Language for the output
484
485
Returns:
486
Multilingual processing prompt
487
"""
488
languages_text = ", ".join(languages)
489
490
return f"""Perform the following task: {task}
491
492
Languages involved: {languages_text}
493
Output language: {output_language}
494
495
Content to process:
496
{content}
497
498
Instructions:
499
- Process the content according to the specified task
500
- Consider cultural and linguistic nuances
501
- Provide output in {output_language}
502
- Explain any cultural or linguistic considerations
503
504
Result:"""
505
506
@mcp.prompt
507
def technical_documentation(
508
component: str,
509
audience: str = "developers",
510
format: str = "API documentation",
511
include_examples: bool = True
512
) -> list[dict]:
513
"""
514
Generate technical documentation writing prompt.
515
516
Parameters:
517
- component: Component or system to document
518
- audience: Target audience (developers, users, administrators)
519
- format: Documentation format (API docs, user guide, tutorial)
520
- include_examples: Whether to include code examples
521
522
Returns:
523
List of message objects for technical documentation
524
"""
525
examples_text = ""
526
if include_examples:
527
examples_text = "\n- Include practical code examples and usage scenarios"
528
529
return [
530
Message(
531
role="system",
532
content=f"""You are a technical writer specializing in {format}. Write clear, comprehensive documentation for {audience}. Use appropriate technical language and structure.{examples_text}"""
533
),
534
Message(
535
role="user",
536
content=f"""Create {format} for the following component: {component}
537
538
Target audience: {audience}
539
540
Please include:
541
1. Overview and purpose
542
2. Installation/setup instructions (if applicable)
543
3. Configuration options
544
4. API reference or feature descriptions
545
5. Usage examples and best practices
546
6. Troubleshooting common issues
547
7. Related resources or references
548
549
Documentation:"""
550
)
551
]
552
553
@mcp.prompt
554
def business_analysis(
555
business_scenario: str,
556
analysis_framework: str = "SWOT",
557
stakeholders: list[str] = None,
558
constraints: list[str] = None
559
) -> list[dict]:
560
"""
561
Generate business analysis prompt using specified framework.
562
563
Parameters:
564
- business_scenario: Business situation to analyze
565
- analysis_framework: Framework to use (SWOT, Porter's Five Forces, etc.)
566
- stakeholders: List of stakeholder groups
567
- constraints: List of constraints or limitations
568
569
Returns:
570
List of message objects for business analysis
571
"""
572
stakeholder_text = ""
573
if stakeholders:
574
stakeholder_text = f"\n\nStakeholders: {', '.join(stakeholders)}"
575
576
constraints_text = ""
577
if constraints:
578
constraints_text = f"\n\nConstraints: {', '.join(constraints)}"
579
580
return [
581
Message(
582
role="system",
583
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}"""
584
),
585
Message(
586
role="user",
587
content=f"""Analyze the following business scenario using {analysis_framework} analysis:
588
589
Scenario:
590
{business_scenario}
591
592
Please provide:
593
1. {analysis_framework} analysis breakdown
594
2. Key insights and findings
595
3. Strategic recommendations
596
4. Risk assessment
597
5. Implementation considerations
598
6. Success metrics and KPIs
599
600
Analysis:"""
601
)
602
]
603
```
604
605
## Prompt Return Types
606
607
Prompts can return different formats:
608
609
```python
610
# Simple string prompt
611
@mcp.prompt
612
def simple_prompt(topic: str) -> str:
613
return f"Write about {topic}"
614
615
# List of message dictionaries
616
@mcp.prompt
617
def structured_prompt(query: str) -> list[dict]:
618
return [
619
{"role": "system", "content": "You are a helpful assistant."},
620
{"role": "user", "content": query}
621
]
622
623
# Using Message helper
624
@mcp.prompt
625
def helper_prompt(task: str) -> list[dict]:
626
return [
627
Message("system", "You are an expert consultant."),
628
Message("user", f"Help me with: {task}")
629
]
630
```