mcp-resources-guide
Implement MCP resources that provide data and files to AI assistants - URIs, caching, and streaming
What this skill does
You are an expert in implementing MCP resources using the rmcp crate, with deep knowledge of resource patterns, URI design, and data fetching strategies.
## Your Expertise
You guide developers on:
- Resource design and URI patterns
- Resource listing and discovery
- Content fetching and caching
- MIME type handling
- Streaming large resources
- Resource subscriptions and updates
- Testing resource implementations
## What are MCP Resources?
**Resources** are data sources that MCP servers expose to AI assistants. They provide context through files, database records, API responses, or any retrievable data.
### Resource Characteristics
- **URI-addressable**: Each resource has a unique URI
- **Typed**: Resources have MIME types
- **Listable**: Servers can list available resources
- **Fetchable**: Clients can retrieve resource content
- **Cacheable**: Support for caching strategies
### Resource vs Tools
- **Tools**: Actions that modify state or perform computations
- **Resources**: Data that provides context (read-only typically)
## Resource URI Patterns
### URI Design Principles
Good URI design is crucial for resource organization:
```rust
// Pattern 1: Hierarchical paths
"file:///project/src/main.rs"
"db://users/123"
"api://weather/san-francisco/current"
// Pattern 2: Query-style
"data://records?type=user&id=123"
"search://results?q=rust+mcp&limit=10"
// Pattern 3: Template-based
"user://{user_id}"
"document://{collection}/{document_id}"
"metric://{service}/{metric_name}/{timerange}"
```
### URI Components
```
scheme://authority/path?query#fragment
│ │ │ │ │
│ │ │ │ └─ Optional fragment
│ │ │ └─ Optional query parameters
│ │ └─ Resource path
│ └─ Optional authority (host, port)
└─ Resource type identifier
```
## Implementing Resources
### Basic Resource Implementation
```rust
use rmcp::prelude::*;
use serde::{Deserialize, Serialize};
#[derive(Clone)]
struct FileSystemResource {
root_path: PathBuf,
}
impl FileSystemResource {
fn new(root_path: impl Into<PathBuf>) -> Self {
Self {
root_path: root_path.into(),
}
}
// List resources
async fn list_resources(&self) -> Result<Vec<ResourceInfo>, Error> {
let mut resources = Vec::new();
let entries = tokio::fs::read_dir(&self.root_path).await?;
let mut entries = entries;
while let Some(entry) = entries.next_entry().await? {
let path = entry.path();
let relative_path = path.strip_prefix(&self.root_path)?;
let uri = format!("file:///{}", relative_path.display());
resources.push(ResourceInfo {
uri,
name: entry.file_name().to_string_lossy().to_string(),
description: Some(format!("File: {}", relative_path.display())),
mime_type: Some(self.detect_mime_type(&path)),
});
}
Ok(resources)
}
// Fetch resource content
async fn fetch_resource(&self, uri: &str) -> Result<ResourceContent, Error> {
// Parse URI to extract path
let path = self.parse_uri(uri)?;
let full_path = self.root_path.join(&path);
// Read file content
let content = tokio::fs::read_to_string(&full_path).await?;
let mime_type = self.detect_mime_type(&full_path);
Ok(ResourceContent {
uri: uri.to_string(),
mime_type,
text: Some(content),
blob: None,
})
}
fn detect_mime_type(&self, path: &Path) -> String {
match path.extension().and_then(|s| s.to_str()) {
Some("rs") => "text/x-rust".to_string(),
Some("toml") => "application/toml".to_string(),
Some("json") => "application/json".to_string(),
Some("md") => "text/markdown".to_string(),
Some("txt") => "text/plain".to_string(),
_ => "application/octet-stream".to_string(),
}
}
fn parse_uri(&self, uri: &str) -> Result<PathBuf, Error> {
// Remove "file:///" prefix
let path = uri.strip_prefix("file:///")
.ok_or_else(|| Error::InvalidUri(uri.to_string()))?;
Ok(PathBuf::from(path))
}
}
```
### Resource with Templates
```rust
#[derive(Clone)]
struct UserResource {
db: Arc<Database>,
}
impl UserResource {
// Template: "user://{user_id}"
async fn list_resources(&self) -> Result<Vec<ResourceInfo>, Error> {
let users = self.db.list_users().await?;
let resources = users.into_iter().map(|user| ResourceInfo {
uri: format!("user://{}", user.id),
name: user.name.clone(),
description: Some(format!("User profile for {}", user.name)),
mime_type: Some("application/json".to_string()),
}).collect();
Ok(resources)
}
async fn fetch_resource(&self, uri: &str) -> Result<ResourceContent, Error> {
// Parse "user://123" -> user_id = "123"
let user_id = uri.strip_prefix("user://")
.ok_or_else(|| Error::InvalidUri(uri.to_string()))?;
let user = self.db.get_user(user_id).await?;
let json = serde_json::to_string_pretty(&user)?;
Ok(ResourceContent {
uri: uri.to_string(),
mime_type: "application/json".to_string(),
text: Some(json),
blob: None,
})
}
}
```
## Resource Patterns
### Pattern 1: Static Files
```rust
#[derive(Clone)]
struct DocumentationResource {
docs_dir: PathBuf,
}
impl DocumentationResource {
async fn list_resources(&self) -> Result<Vec<ResourceInfo>, Error> {
let mut resources = Vec::new();
for entry in walkdir::WalkDir::new(&self.docs_dir)
.follow_links(true)
.into_iter()
.filter_map(|e| e.ok())
.filter(|e| e.path().extension().map_or(false, |ext| ext == "md"))
{
let path = entry.path();
let relative = path.strip_prefix(&self.docs_dir)?;
resources.push(ResourceInfo {
uri: format!("docs://{}", relative.display()),
name: path.file_name()
.unwrap()
.to_string_lossy()
.to_string(),
description: Some(format!("Documentation: {}", relative.display())),
mime_type: Some("text/markdown".to_string()),
});
}
Ok(resources)
}
}
```
### Pattern 2: Database Records
```rust
#[derive(Clone)]
struct DatabaseResource {
pool: PgPool,
}
impl DatabaseResource {
// Resource URI: "db://table_name/record_id"
async fn fetch_resource(&self, uri: &str) -> Result<ResourceContent, Error> {
let parts: Vec<&str> = uri.strip_prefix("db://")
.ok_or_else(|| Error::InvalidUri(uri.to_string()))?
.split('/')
.collect();
if parts.len() != 2 {
return Err(Error::InvalidUri(uri.to_string()));
}
let table = parts[0];
let id = parts[1];
// Query database
let query = format!("SELECT * FROM {} WHERE id = $1", table);
let row = sqlx::query(&query)
.bind(id)
.fetch_one(&self.pool)
.await?;
// Convert row to JSON
let json = row_to_json(&row)?;
Ok(ResourceContent {
uri: uri.to_string(),
mime_type: "application/json".to_string(),
text: Some(json),
blob: None,
})
}
}
```
### Pattern 3: API Integration
```rust
use reqwest::Client;
#[derive(Clone)]
struct ApiResource {
client: Client,
base_url: String,
api_key: String,
}
impl ApiResource {
// Resource URI: "api://endpoint/path"
async fn fetch_resource(&self, uri: &str) -> Result<ResourceContent, Error> {
let path = uri.strip_prefix("api://")
.ok_or_else(|Related in AI Agents
skill-development
IncludedComprehensive meta-skill for creating, managing, validating, auditing, and distributing Claude Code skills and slash commands (unified in v2.1.3+). Provides skill templates, creation workflows, validation patterns, audit checklists, naming conventions, YAML frontmatter guidance, progressive disclosure examples, and best practices lookup. Use when creating new skills, validating existing skills, auditing skill quality, understanding skill architecture, needing skill templates, learning about YAML frontmatter requirements, progressive disclosure patterns, tool restrictions (allowed-tools), skill composition, skill naming conventions, troubleshooting skill activation issues, creating custom slash commands, configuring command frontmatter, using command arguments ($ARGUMENTS, $1, $2), bash execution in commands, file references in commands, command namespacing, plugin commands, MCP slash commands, Skill tool configuration, or deciding between skills vs slash commands. Delegates to docs-management skill for official documentation.
reprompter
IncludedTransform messy prompts into well-structured, effective prompts — single or multi-agent. Use when: "reprompt", "reprompt this", "clean up this prompt", "structure my prompt", rough text needing XML tags and best practices, "reprompter teams", "repromptception", "run with quality", "smart run", "smart agents", multi-agent tasks, audits, parallel work, anything going to agent teams. Don't use when: simple Q&A, pure chat, immediate execution-only tasks. See "Don't Use When" section for details. Outputs: Structured XML/Markdown prompt, quality score (before/after), optional team brief + per-agent sub-prompts, agent team output files. Success criteria: Single mode quality score ≥ 7/10; Repromptception per-agent prompt quality score 8+/10; all required sections present, actionable and specific.
adaptive-compaction
IncludedAdaptive add-on policy and recovery layer that decides WHEN to compact, prune, snapshot, or fork -- replacing fixed-percent auto-compaction across Claude Code, Codex, and MCP-capable hosts. Trigger on auto-compact timing or damage: "when should I compact", "is it safe to compact now or start a fresh session", "auto-compact fires too early/mid-task", "switching to an unrelated task but the window still has space", "context rot", "answers get worse the longer the session runs", "the agent forgot the plan or my decisions after it summarized", "add a layer on top that manages context without changing the agent", raising autoCompactWindow to give the policy room, or installing/tuning a cross-tool compaction policy or PreCompact hook -- even when "compaction" is never said but the problem is context-window pressure or post-summarization memory loss. Do NOT use to summarize a conversation, build RAG, write a summarization prompt (decides WHEN not HOW), or answer max-context-length trivia.
agent-skill-creator
IncludedCreate cross-platform agent skills from workflow descriptions. Activates when users ask to create an agent, automate a repetitive workflow, create a custom skill, or need advanced agent creation. Triggers on phrases like create agent for, automate workflow, create skill for, every day I have to, daily I need to, turn process into agent, need to automate, create a cross-platform skill, validate this skill, export this skill, migrate this skill. Supports single skills, multi-agent suites, transcript processing, template-based creation, interactive configuration, cross-platform export, and spec validation.
llm-wiki
IncludedUse when building or maintaining a persistent personal knowledge base (second brain) in Obsidian where an LLM incrementally ingests sources, updates entity/concept pages, maintains cross-references, and keeps a synthesis current. Triggers include "second brain", "Obsidian wiki", "personal knowledge management", "ingest this paper/article/book", "build a research wiki", "compound knowledge", "Memex", or whenever the user wants knowledge to accumulate across sessions instead of being re-derived by RAG on every query.
skill-master
IncludedAgent Skills authoring, evaluation, and optimization. Create, edit, validate, benchmark, and improve skills following the agentskills.io specification. Use when designing SKILL.md files, structuring skill folders (references, scripts, assets), ingesting external documentation into skills, running trigger evals, benchmarking skill quality, optimizing descriptions, or performing blind A/B comparisons. Keywords: agentskills.io, SKILL.md, skill authoring, eval, benchmark, trigger optimization.