Resources are a core primitive in the Model Context Protocol (MCP) that allow servers to expose data and content that can be read by clients and used as context for LLM interactions.
Resources are designed to be application-controlled, meaning that the client application can decide how and when they should be used. Different MCP clients may handle resources differently. For example:
Claude Desktop currently requires users to explicitly select resources before they can be used
Other clients might automatically select resources based on heuristics
Some implementations may even allow the AI model itself to determine which resources to use
Server authors should be prepared to handle any of these interaction patterns when implementing resource support. In order to expose data to models automatically, server authors should use a model-controlled primitive such as Tools.
Overview
Resources represent any kind of data that an MCP server wants to make available to clients. This can include:
File contents
Database records
API responses
Live system data
Screenshots and images
Log files
And more
Each resource is identified by a unique URI and can contain either text or binary data.
Resource URIs
Resources are identified using URIs that follow this format:
[protocol]://[host]/[path]
For example:
file:///home/user/documents/report.pdf
postgres://database/customers/schema
screen://localhost/display1
The protocol and path structure is defined by the MCP server implementation. Servers can define their own custom URI schemes.
Resource types
Resources can contain two types of content:
Text resources
Text resources contain UTF-8 encoded text data. These are suitable for:
Source code
Configuration files
Log files
JSON/XML data
Plain text
Binary resources
Binary resources contain raw binary data encoded in base64. These are suitable for:
Images
PDFs
Audio files
Video files
Other non-text formats
Resource discovery
Clients can discover available resources through two main methods:
Direct resources
Servers expose a list of concrete resources via the resources/list endpoint. Each resource includes:
Servers may return multiple resources in response to one resources/read request. This could be used, for example, to return a list of files inside a directory when the directory is read.
Resource updates
MCP supports real-time updates for resources through two mechanisms:
List changes
Servers can notify clients when their list of available resources changes via the notifications/resources/list_changed notification.
Content changes
Clients can subscribe to updates for specific resources:
Client sends resources/subscribe with resource URI
Server sends notifications/resources/updated when the resource changes
Client can fetch latest content with resources/read
Client can unsubscribe with resources/unsubscribe
Example implementation
Here’s a simple example of implementing resource support in an MCP server:
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 are designed to be user-controlled, meaning they are exposed from servers to clients with the intention of the user being able to explicitly select them for use.
description: "Analyze Python code for potential improvements",
messages: [
{
role: "user",
content: {
type: "text",
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`"
Provide detailed descriptions for prompts and arguments
Validate all required arguments
Handle missing arguments gracefully
Consider versioning for prompt templates
Cache dynamic content when appropriate
Implement error handling
Document expected argument formats
Consider prompt composability
Test prompts with various inputs
UI integration
Prompts can be surfaced in client UIs as:
Slash commands
Quick actions
Context menu items
Command palette entries
Guided workflows
Interactive forms
Updates and changes
Servers can notify clients about prompt changes:
Server capability: prompts.listChanged
Notification: notifications/prompts/list_changed
Client re-fetches prompt list
Security considerations
When implementing prompts:
Validate all arguments
Sanitize user input
Consider rate limiting
Implement access controls
Audit prompt usage
Handle sensitive data appropriately
Validate generated content
Implement timeouts
Consider prompt injection risks
Document security requirements
## Tools
Tools
Enable LLMs to perform actions through your server
Tools are a powerful primitive in the Model Context Protocol (MCP) that enable servers to expose executable functionality to clients. Through tools, LLMs can interact with external systems, perform computations, and take actions in the real world.
Tools are designed to be model-controlled, meaning that tools are exposed from servers to clients with the intention of the AI model being able to automatically invoke them (with a human in the loop to grant approval).
Overview
Tools in MCP allow servers to expose executable functions that can be invoked by clients and used by LLMs to perform actions. Key aspects of tools include:
Discovery: Clients can list available tools through the tools/list endpoint
Invocation: Tools are called using the tools/call endpoint, where servers perform the requested operation and return results
Flexibility: Tools can range from simple calculations to complex API interactions
Like resources, tools are identified by unique names and can include descriptions to guide their usage. However, unlike resources, tools represent dynamic operations that can modify state or interact with external systems.
Tool definition structure
Each tool is defined with the following structure:
Use detailed JSON Schema definitions for parameters
Include examples in tool descriptions to demonstrate how the model should use them
Implement proper error handling and validation
Use progress reporting for long operations
Keep tool operations focused and atomic
Document expected return value structures
Implement proper timeouts
Consider rate limiting for resource-intensive operations
Log tool usage for debugging and monitoring
Security considerations
When exposing tools:
Input validation
Validate all parameters against the schema
Sanitize file paths and system commands
Validate URLs and external identifiers
Check parameter sizes and ranges
Prevent command injection
Access control
Implement authentication where needed
Use appropriate authorization checks
Audit tool usage
Rate limit requests
Monitor for abuse
Error handling
Don’t expose internal errors to clients
Log security-relevant errors
Handle timeouts appropriately
Clean up resources after errors
Validate return values
Tool discovery and updates
MCP supports dynamic tool discovery:
Clients can list available tools at any time
Servers can notify clients when tools change using notifications/tools/list_changed
Tools can be added or removed during runtime
Tool definitions can be updated (though this should be done carefully)
Error handling
Tool errors should be reported within the result object, not as MCP protocol-level errors. This allows the LLM to see and potentially handle the error. When a tool encounters an error:
Set isError to true in the result
Include error details in the content array
Here’s an example of proper error handling for tools:
Sampling is a powerful MCP feature that allows servers to request LLM completions through the client, enabling sophisticated agentic behaviors while maintaining security and privacy.
This feature of MCP is not yet supported in the Claude Desktop client.
How sampling works
The sampling flow follows these steps:
Server sends a sampling/createMessage request to the client
Client reviews the request and can modify it
Client samples from an LLM
Client reviews the completion
Client returns the result to the server
This human-in-the-loop design ensures users maintain control over what the LLM sees and generates.
Message format
Sampling requests use a standardized message format:
Sampling is designed with human oversight in mind:
For prompts
Clients should show users the proposed prompt
Users should be able to modify or reject prompts
System prompts can be filtered or modified
Context inclusion is controlled by the client
For completions
Clients should show users the completion
Users should be able to modify or reject completions
Clients can filter or modify completions
Users control which model is used
Security considerations
When implementing sampling:
Validate all message content
Sanitize sensitive information
Implement appropriate rate limits
Monitor sampling usage
Encrypt data in transit
Handle user data privacy
Audit sampling requests
Control cost exposure
Implement timeouts
Handle model errors gracefully
Common patterns
Agentic workflows
Sampling enables agentic patterns like:
Reading and analyzing resources
Making decisions based on context
Generating structured data
Handling multi-step tasks
Providing interactive assistance
Context management
Best practices for context:
Request minimal necessary context
Structure context clearly
Handle context size limits
Update context as needed
Clean up stale context
Error handling
Robust error handling should:
Catch sampling failures
Handle timeout errors
Manage rate limits
Validate responses
Provide fallback behaviors
Log errors appropriately
Limitations
Be aware of these limitations:
Sampling depends on client capabilities
Users control sampling behavior
Context size has limits
Rate limits may apply
Costs should be considered
Model availability varies
Response times vary
Not all content types supported
## Roots
Roots
Understanding roots in MCP
Roots are a concept in MCP that define the boundaries where servers can operate. They provide a way for clients to inform servers about relevant resources and their locations.
What are Roots?
A root is a URI that a client suggests a server should focus on. When a client connects to a server, it declares which roots the server should work with. While primarily used for filesystem paths, roots can be any valid URI including HTTP URLs.
For example, roots could be:
file:///home/user/projects/myapp
https://api.example.com/v1
Why Use Roots?
Roots serve several important purposes:
Guidance: They inform servers about relevant resources and locations
Clarity: Roots make it clear which resources are part of your workspace
Organization: Multiple roots let you work with different resources simultaneously
How Roots Work
When a client supports roots, it:
Declares the roots capability during connection
Provides a list of suggested roots to the server
Notifies the server when roots change (if supported)
While roots are informational and not strictly enforcing, servers should:
Respect the provided roots
Use root URIs to locate and access resources
Prioritize operations within root boundaries
Common Use Cases
Roots are commonly used to define:
Project directories
Repository locations
API endpoints
Configuration locations
Resource boundaries
Best Practices
When working with roots:
Only suggest necessary resources
Use clear, descriptive names for roots
Monitor root accessibility
Handle root changes gracefully
Example
Here’s how a typical MCP client might expose roots:
This configuration suggests the server focus on both a local repository and an API endpoint while keeping them logically separated.
## Transports
Transports
Learn about MCP’s communication mechanisms
Transports in the Model Context Protocol (MCP) provide the foundation for communication between clients and servers. A transport handles the underlying mechanics of how messages are sent and received.
Message Format
MCP uses JSON-RPC 2.0 as its wire format. The transport layer is responsible for converting MCP protocol messages into JSON-RPC format for transmission and converting received JSON-RPC messages back into MCP protocol messages.
MCP includes two standard transport implementations:
Standard Input/Output (stdio)
The stdio transport enables communication through standard input and output streams. This is particularly useful for local integrations and command-line tools.