The prompts/get Method
Implement prompt retrieval with argument substitution.
Understanding prompts/get
The prompts/get method retrieves a specific prompt and expands it
with the user's arguments. This is where the magic happens — arguments are
substituted into the prompt template to create the final messages.
Request Format
The client specifies which prompt to get and provides arguments:
{
"jsonrpc": "2.0",
"id": 2,
"method": "prompts/get",
"params": {
"name": "code-review",
"arguments": {
"code": "def add(a, b):\n return a + b",
"language": "python",
"focus": "style"
}
}
}
Response Format
The server returns an expanded prompt with messages that can be used in a conversation:
{
"jsonrpc": "2.0",
"id": 2,
"result": {
"description": "Code review for Python code focusing on style",
"messages": [
{
"role": "user",
"content": {
"type": "text",
"text": "Please review the following Python code, focusing on style:\n\n```python\ndef add(a, b):\n return a + b\n```\n\nProvide specific feedback on code style, naming conventions, and readability."
}
}
]
}
}
Message Structure
Each message in the response has:
| Field | Type | Description |
|---|---|---|
role |
string | "user" or "assistant" |
content |
object | Content with type and text/data |
Python Implementation
Here's how to implement prompts/get with argument substitution:
"""
Prompt handlers with argument substitution
"""
PROMPTS = {
"code-review": {
"name": "code-review",
"description": "Review code for bugs and improvements",
"arguments": [
{"name": "code", "description": "Code to review", "required": True},
{"name": "language", "description": "Programming language", "required": True},
{"name": "focus", "description": "Review focus area", "required": False}
]
},
"summarize": {
"name": "summarize",
"description": "Summarize text concisely",
"arguments": [
{"name": "text", "description": "Text to summarize", "required": True},
{"name": "max_length", "description": "Max sentences", "required": False}
]
},
"explain-code": {
"name": "explain-code",
"description": "Explain code in plain English",
"arguments": [
{"name": "code", "description": "Code to explain", "required": True},
{"name": "detail_level", "description": "brief/normal/detailed", "required": False}
]
}
}
def handle_prompts_get(params):
"""Handle the prompts/get method."""
name = params.get("name", "")
arguments = params.get("arguments", {})
# Check if prompt exists
if name not in PROMPTS:
raise ValueError(f"Unknown prompt: {name}")
prompt = PROMPTS[name]
# Validate required arguments
for arg in prompt.get("arguments", []):
if arg.get("required") and arg["name"] not in arguments:
raise ValueError(f"Missing required argument: {arg['name']}")
# Generate prompt messages based on the prompt type
if name == "code-review":
return generate_code_review_prompt(arguments)
elif name == "summarize":
return generate_summarize_prompt(arguments)
elif name == "explain-code":
return generate_explain_prompt(arguments)
raise ValueError(f"No handler for prompt: {name}")
def generate_code_review_prompt(arguments):
"""Generate a code review prompt."""
code = arguments.get("code", "")
language = arguments.get("language", "")
focus = arguments.get("focus", "all aspects")
text = f"""Please review the following {language} code, focusing on {focus}:
```{language}
{code}
```
Provide specific, actionable feedback on:
- Potential bugs or errors
- Code style and readability
- Best practices and improvements"""
return {
"description": f"Code review for {language} code",
"messages": [
{
"role": "user",
"content": {
"type": "text",
"text": text
}
}
]
}
def generate_summarize_prompt(arguments):
"""Generate a summarization prompt."""
text_to_summarize = arguments.get("text", "")
max_length = arguments.get("max_length", "3")
text = f"""Please summarize the following text in {max_length} sentences or fewer:
{text_to_summarize}
Provide a clear, concise summary that captures the main points."""
return {
"description": "Text summarization",
"messages": [
{
"role": "user",
"content": {
"type": "text",
"text": text
}
}
]
}
def generate_explain_prompt(arguments):
"""Generate a code explanation prompt."""
code = arguments.get("code", "")
detail_level = arguments.get("detail_level", "normal")
detail_instructions = {
"brief": "Give a brief, one-paragraph explanation.",
"normal": "Explain each major component and how they work together.",
"detailed": "Provide a detailed line-by-line explanation."
}
instruction = detail_instructions.get(detail_level, detail_instructions["normal"])
text = f"""Please explain what the following code does:
```
{code}
```
{instruction}"""
return {
"description": f"Code explanation ({detail_level})",
"messages": [
{
"role": "user",
"content": {
"type": "text",
"text": text
}
}
]
}
Error Handling
Handle common errors gracefully:
def handle_request(method, params, request_id):
"""Route requests with error handling."""
try:
if method == "prompts/list":
result = {"prompts": list(PROMPTS.values())}
elif method == "prompts/get":
result = handle_prompts_get(params)
else:
return error_response(request_id, -32601, f"Method not found: {method}")
return {
"jsonrpc": "2.0",
"id": request_id,
"result": result
}
except ValueError as e:
# Invalid params (e.g., unknown prompt, missing argument)
return error_response(request_id, -32602, str(e))
except Exception as e:
# Internal error
return error_response(request_id, -32603, f"Internal error: {e}")
def error_response(request_id, code, message):
"""Create a JSON-RPC error response."""
return {
"jsonrpc": "2.0",
"id": request_id,
"error": {
"code": code,
"message": message
}
}
Use standard JSON-RPC error codes: -32602 for invalid params
(unknown prompt, missing arguments) and -32603 for internal errors.
Testing prompts/get
Test with curl:
# Get a prompt with arguments
curl -X POST http://localhost:8080 \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"id": 1,
"method": "prompts/get",
"params": {
"name": "code-review",
"arguments": {
"code": "print(\"hello\")",
"language": "python"
}
}
}'
# Test missing required argument (should error)
curl -X POST http://localhost:8080 \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"id": 2,
"method": "prompts/get",
"params": {
"name": "code-review",
"arguments": {
"code": "print(\"hello\")"
}
}
}'
# Expected error response:
{
"jsonrpc": "2.0",
"id": 2,
"error": {
"code": -32602,
"message": "Missing required argument: language"
}
}
Multi-Message Prompts
Prompts can return multiple messages to set up a conversation context:
def generate_debug_session_prompt(arguments):
"""Generate a debugging session with context."""
error_message = arguments.get("error", "")
code = arguments.get("code", "")
return {
"description": "Interactive debugging session",
"messages": [
{
"role": "user",
"content": {
"type": "text",
"text": f"I'm getting this error:\n\n{error_message}"
}
},
{
"role": "assistant",
"content": {
"type": "text",
"text": "I'll help you debug this. Can you share the relevant code?"
}
},
{
"role": "user",
"content": {
"type": "text",
"text": f"Here's my code:\n\n```\n{code}\n```"
}
}
]
}
Including "assistant" role messages in your prompt can establish context and guide the conversation flow. The client will use these to populate the conversation history before the AI responds.
What's Next?
Now that you can list and retrieve prompts, let's look at practical examples of useful prompts you can build for real-world use cases.