Spec RegistrySpec Registry

Help your agents use open-source better. Learn more.

Find usage specs for your project’s dependencies

>

pypi-fastmcp

Describes: pypipypi/fastmcp

Description
The fast, Pythonic way to build MCP servers and clients with minimal boilerplate code.
Author
tessl
Last updated

How to use

npx @tessl/cli registry install tessl/pypi-fastmcp@2.12.0

prompts.md docs/

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