Update prompts.mdx

This commit is contained in:
Justin Spahr-Summers 2024-11-21 15:27:37 +00:00
commit de7ee4337a
No known key found for this signature in database

View file

@ -3,7 +3,7 @@ title: "Prompts"
description: "Create resuable prompt templates and workflows" description: "Create resuable prompt templates and workflows"
--- ---
MCP Prompts enable servers to define reusable prompt templates and workflows that clients can easily surface to users and LLMs. They provide a powerful way to standardize and share common LLM interactions. Prompts enable servers to define reusable prompt templates and workflows that clients can easily surface to users and LLMs. They provide a powerful way to standardize and share common LLM interactions.
## Overview ## Overview
@ -78,15 +78,13 @@ To use a prompt, clients make a `prompts/get` request:
// Response // Response
{ {
description?: string, // Optional context about the prompt description: "Analyze Python code for potential improvements",
messages: [ // Messages to send to the LLM messages: [
{ {
role: "user" | "assistant", role: "user",
content: { content: {
type: "text" | "image", type: "text",
text?: string, text: "Please analyze the following Python code for potential improvements:\n\n```python\ndef calculate_sum(numbers):\n total = 0\n for num in numbers:\n total = total + num\n return total\n\nresult = calculate_sum([1, 2, 3, 4, 5])\nprint(result)\n```"
data?: string, // base64 for images
mimeType?: string
} }
} }
] ]
@ -97,57 +95,63 @@ To use a prompt, clients make a `prompts/get` request:
Prompts can be dynamic and include: Prompts can be dynamic and include:
### Context integration ### Embedded resource context
```typescript ```json
const analyzeLogsPrompt = { {
name: "analyze-logs", "name": "analyze-project",
description: "Analyze recent system logs", "description": "Analyze project logs and code",
arguments: [ "arguments": [
{ {
name: "timeframe", "name": "timeframe",
description: "Time period to analyze", "description": "Time period to analyze logs",
required: true "required": true
},
{
"name": "fileUri",
"description": "URI of code file to review",
"required": true
} }
] ]
}; }
server.setRequestHandler(GetPromptRequestSchema, async (request) => {
if (request.params.name === "analyze-logs") {
const logs = await getSystemLogs(request.params.arguments?.timeframe);
return {
messages: [
{
role: "user",
content: {
type: "text",
text: `Analyze these system logs and identify any issues:\n\n${logs}`
}
}
]
};
}
});
``` ```
### Resource references When handling the `prompts/get` request:
```typescript ```json
const codeReviewPrompt = { {
name: "review-code", "messages": [
async getMessages(fileUri: string) {
const code = await readResource(fileUri);
return [
{ {
role: "user", "role": "user",
content: { "content": {
type: "text", "type": "text",
text: `Review this code for best practices:\n\n${code}` "text": "Analyze these system logs and the code file for any issues:"
}
},
{
"role": "user",
"content": {
"type": "resource",
"resource": {
"uri": "logs://recent?timeframe=1h",
"text": "[2024-03-14 15:32:11] ERROR: Connection timeout in network.py:127\n[2024-03-14 15:32:15] WARN: Retrying connection (attempt 2/3)\n[2024-03-14 15:32:20] ERROR: Max retries exceeded",
"mimeType": "text/plain"
} }
} }
]; },
{
"role": "user",
"content": {
"type": "resource",
"resource": {
"uri": "file:///path/to/code.py",
"text": "def connect_to_service(timeout=30):\n retries = 3\n for attempt in range(retries):\n try:\n return establish_connection(timeout)\n except TimeoutError:\n if attempt == retries - 1:\n raise\n time.sleep(5)\n\ndef establish_connection(timeout):\n # Connection implementation\n pass",
"mimeType": "text/x-python"
} }
}; }
}
]
}
``` ```
### Multi-step workflows ### Multi-step workflows
@ -187,14 +191,16 @@ const debugWorkflow = {
Here's a complete example of implementing prompts in an MCP server: Here's a complete example of implementing prompts in an MCP server:
```typescript <Tabs>
import { Server } from "@modelcontextprotocol/sdk/server"; <Tab title="TypeScript">
import { ```typescript
import { Server } from "@modelcontextprotocol/sdk/server";
import {
ListPromptsRequestSchema, ListPromptsRequestSchema,
GetPromptRequestSchema GetPromptRequestSchema
} from "@modelcontextprotocol/sdk/types"; } from "@modelcontextprotocol/sdk/types";
const PROMPTS = { const PROMPTS = {
"git-commit": { "git-commit": {
name: "git-commit", name: "git-commit",
description: "Generate a Git commit message", description: "Generate a Git commit message",
@ -222,22 +228,26 @@ const PROMPTS = {
} }
] ]
} }
}; };
const server = new Server({ const server = new Server({
name: "example-prompts-server", name: "example-prompts-server",
version: "1.0.0" version: "1.0.0"
}); }, {
capabilities: {
prompts: {}
}
});
// List available prompts // List available prompts
server.setRequestHandler(ListPromptsRequestSchema, async () => { server.setRequestHandler(ListPromptsRequestSchema, async () => {
return { return {
prompts: Object.values(PROMPTS) prompts: Object.values(PROMPTS)
}; };
}); });
// Get specific prompt // Get specific prompt
server.setRequestHandler(GetPromptRequestSchema, async (request) => { server.setRequestHandler(GetPromptRequestSchema, async (request) => {
const prompt = PROMPTS[request.params.name]; const prompt = PROMPTS[request.params.name];
if (!prompt) { if (!prompt) {
throw new Error(`Prompt not found: ${request.params.name}`); throw new Error(`Prompt not found: ${request.params.name}`);
@ -273,8 +283,15 @@ server.setRequestHandler(GetPromptRequestSchema, async (request) => {
} }
throw new Error("Prompt implementation not found"); throw new Error("Prompt implementation not found");
}); });
``` ```
</Tab>
<Tab title="Python">
```python
# Python implementation coming soon
```
</Tab>
</Tabs>
## Best practices ## Best practices
@ -324,70 +341,3 @@ When implementing prompts:
- Implement timeouts - Implement timeouts
- Consider prompt injection risks - Consider prompt injection risks
- Document security requirements - Document security requirements
## Advanced features
### Prompt chaining
```typescript
const analyzePRPrompt = {
async getMessages(prId: string) {
// Chain multiple prompts
const diffPrompt = await getPrompt("analyze-diff");
const testsPrompt = await getPrompt("review-tests");
const securityPrompt = await getPrompt("security-review");
return [
...diffPrompt.messages,
...testsPrompt.messages,
...securityPrompt.messages
];
}
};
```
### Context enrichment
```typescript
const troubleshootPrompt = {
async getMessages(error: string) {
// Enrich with system context
const systemInfo = await getSystemInfo();
const recentLogs = await getRecentLogs();
const stackTrace = await parseError(error);
return [
{
role: "user",
content: {
type: "text",
text: `Help troubleshoot this error:
Error: ${error}
System: ${systemInfo}
Logs: ${recentLogs}
Stack: ${stackTrace}`
}
}
];
}
};
```
### Interactive workflows
```typescript
const debugWorkflow = {
async getMessages(stage: string, context: any) {
switch (stage) {
case "initial":
return promptForError();
case "analysis":
return analyzeError(context.error);
case "solution":
return suggestFixes(context.analysis);
case "verification":
return verifyFix(context.solution);
}
}
};
```