Prompts

Learn how MCP enables reusable prompt templates and workflows

Prompts in MCP

Prompts are pre-defined templates that help standardize interactions with AI models. They provide a way to create consistent, reusable workflows that users can easily access through the client interface.

Prompts are designed to be user-controlled, meaning they are typically selected explicitly by the user rather than automatically invoked by the AI model. In many client applications, they appear as slash commands or menu items.

What Are Prompts?

MCP prompts allow you to:

  • Create reusable templates for common tasks
  • Accept dynamic arguments to customize behavior
  • Include context from resources automatically
  • Build multi-step interactions
  • Standardize AI interactions across users

How Prompts Work

Prompts follow this general workflow:

  1. Discovery: The client asks the server what prompts are available
  2. Selection: The user chooses a prompt from the interface (often as a slash command)
  3. Arguments: The user provides any required arguments for the prompt
  4. Generation: The server generates the actual message content based on the template and arguments
  5. Usage: The client sends the generated messages to the AI model

Prompt Structure

Each prompt is defined with:

  • Name: A unique identifier for the prompt (e.g., analyze-code)
  • Description: A human-readable explanation of what the prompt does
  • Arguments: Optional parameters that can be supplied when using the prompt

Here's what a prompt definition looks like:

{
  "name": "analyze-code",
  "description": "Analyze code for improvements",
  "arguments": [
    {
      "name": "language",
      "description": "Programming language of the code",
      "required": true
    },
    {
      "name": "code",
      "description": "Code to analyze",
      "required": true
    },
    {
      "name": "focus",
      "description": "Specific aspects to focus on (performance, security, readability)",
      "required": false
    }
  ]
}

Dynamic Prompts

When a user requests a prompt with specific arguments, the server generates the actual message content:

{
  "messages": [
    {
      "role": "user",
      "content": {
        "type": "text",
        "text": "Please analyze this Python code for improvements:\n\n```python\ndef calculate_sum(numbers):\n    total = 0\n    for num in numbers:\n        total = total + num\n    return total\n```\n\nFocus on: performance"
      }
    }
  ]
}

This dynamic generation makes prompts powerful - they can include resource content, format arguments appropriately, and create specialized interactions for different use cases.

Multi-Step Workflows

Prompts can also define multi-step interactions by including multiple messages with different roles. This is useful for guiding the AI through a specific workflow:

{
  "messages": [
    {
      "role": "user",
      "content": {
        "type": "text", 
        "text": "I need help debugging an error."
      }
    },
    {
      "role": "assistant",
      "content": {
        "type": "text",
        "text": "I'll help analyze this error. What have you tried so far?"
      }
    },
    {
      "role": "user",
      "content": {
        "type": "text", 
        "text": "I've tried restarting the service, but the error persists: ${error}"
      }
    }
  ]
}

This creates a more structured conversation that guides both the user and the AI through a specific interaction pattern.

Example Implementation

import { Server } from "@modelcontextprotocol/sdk/server";
 
// Create a server with prompts capability
const server = new Server({
  name: "example-server",
  version: "1.0.0"
}, {
  capabilities: {
    prompts: {}
  }
});
 
// Define available prompts
server.setRequestHandler("prompts/list", async () => {
  return {
    prompts: [
      {
        name: "explain-code",
        description: "Get an explanation of code",
        arguments: [
          {
            name: "code",
            description: "Code to explain",
            required: true
          },
          {
            name: "language",
            description: "Programming language",
            required: false
          }
        ]
      }
    ]
  };
});
 
// Handle prompt requests
server.setRequestHandler("prompts/get", async (request) => {
  const { name, arguments: args } = request.params;
  
  if (name === "explain-code") {
    const code = args.code || "";
    const language = args.language || "unknown";
    
    return {
      description: `Explain ${language} code`,
      messages: [
        {
          role: "user",
          content: {
            type: "text",
            text: `Please explain how this ${language} code works:\n\n\`\`\`${language}\n${code}\n\`\`\`\n\nFocus on explaining the logic in simple terms.`
          }
        }
      ]
    };
  }
  
  throw new Error(`Unknown prompt: ${name}`);
});

Surfacing Prompts in UI

Client applications typically expose prompts as UI elements for easy access. Common implementations include:

  • Slash Commands: Type / to access a list of available prompts
  • Quick Actions: Buttons or menu items for common prompts
  • Command Palette: Search for prompts by name or description
  • Context Menus: Right-click options for context-specific prompts

Prompt Updates

MCP supports dynamic prompt discovery and updates:

  1. Servers can notify clients when the list of available prompts changes
  2. Clients can refresh their prompt list accordingly
  3. Updates can introduce new prompts or modify existing ones

This allows for updating prompt templates without requiring application restarts.

Best Practices

When implementing prompts in your MCP server:

  1. Clear Names: Use descriptive names that indicate the prompt's purpose
  2. Helpful Descriptions: Write descriptions that explain what the prompt does
  3. Sensible Defaults: Provide default values for optional arguments when possible
  4. Error Handling: Validate arguments and return clear error messages
  5. Consistent Style: Maintain a consistent style across your prompts
  6. Group Related Prompts: Consider organizing related prompts with similar naming
  7. Progressive Complexity: Create both simple and advanced prompts for different users
  8. Document Expectations: Make it clear what kind of output users should expect

Security Considerations

When implementing prompts:

  • Validate Arguments: Check all user-provided arguments for security issues
  • Sanitize Inputs: Prevent injection attacks through arguments
  • Access Control: Ensure users can only access appropriate prompts
  • Sensitive Data: Be careful about including sensitive data in prompt templates
  • Resource Usage: Monitor prompt generation for unexpected resource consumption

Prompts are a great way to provide standardized workflows for common tasks. They help users get consistent results and follow best practices when interacting with AI models.

How is this guide?

On this page