Tools, Resources, and Prompts
Prompt Templates in MCP
4 min read
MCP allows servers to expose reusable prompt templates that AI hosts can invoke. Prompts are pre-built conversation starters with configurable arguments.
Why Prompts?
Prompts are useful for:
- Standardizing common interactions
- Providing domain-specific starting points
- Encapsulating complex instructions
Defining Prompts
from mcp.types import Prompt, PromptArgument, PromptMessage, TextContent
@server.list_prompts()
async def list_prompts():
return [
Prompt(
name="code_review",
description="Review code for best practices and issues",
arguments=[
PromptArgument(
name="language",
description="Programming language",
required=True
),
PromptArgument(
name="focus",
description="What to focus on (security, performance, style)",
required=False
)
]
)
]
Generating Prompt Content
When a prompt is requested, return the actual messages:
@server.get_prompt()
async def get_prompt(name: str, arguments: dict):
if name == "code_review":
language = arguments["language"]
focus = arguments.get("focus", "general best practices")
return [
PromptMessage(
role="user",
content=TextContent(
type="text",
text=f"""Please review the following {language} code.
Focus on: {focus}
Provide specific suggestions with line numbers where applicable.
Rate the code from 1-10 and explain your rating."""
)
)
]
Multi-Turn Prompts
Prompts can include multiple messages for complex workflows:
@server.get_prompt()
async def get_prompt(name: str, arguments: dict):
if name == "debug_session":
return [
PromptMessage(
role="user",
content=TextContent(
type="text",
text="I'm going to share an error. Help me debug it step by step."
)
),
PromptMessage(
role="assistant",
content=TextContent(
type="text",
text="I'll help you debug. Please share the error message and relevant code."
)
),
PromptMessage(
role="user",
content=TextContent(
type="text",
text=f"Error: {arguments['error']}\nCode: {arguments['code']}"
)
)
]
Dynamic Prompt Arguments
Fetch argument options dynamically:
Prompt(
name="query_database",
description="Query a specific table",
arguments=[
PromptArgument(
name="table",
description="Table name",
required=True,
# Could be validated against actual schema
)
]
)
Next, let's build a complete MCP server with tools, resources, and prompts. :::