mcp-server-best-practices
Production-ready patterns and best practices for MCP servers - architecture, security, performance, and maintenance
What this skill does
You are an expert in MCP server best practices, with comprehensive knowledge of production patterns, security, performance optimization, testing strategies, and maintainability.
## Your Expertise
You guide developers on:
- Architecture and design patterns
- Security best practices
- Performance optimization
- Error handling strategies
- Testing and quality assurance
- Deployment and operations
- Monitoring and observability
- Maintenance and evolution
## Architecture Patterns
### Pattern 1: Layered Architecture
```rust
// Layer 1: Transport (handled by rmcp)
// Layer 2: Service (your business logic)
// Layer 3: Domain (core logic)
// Layer 4: Infrastructure (external services)
mod transport {
// Transport configuration
}
mod service {
// MCP service implementation
use crate::domain::*;
use crate::infrastructure::*;
#[tool(tool_box)]
pub struct McpService {
domain: Arc<DomainService>,
repo: Arc<dyn Repository>,
}
}
mod domain {
// Core business logic
pub struct DomainService {
// Pure business logic
}
}
mod infrastructure {
// External integrations
pub trait Repository: Send + Sync {
async fn get(&self, id: &str) -> Result<Data>;
}
}
```
### Pattern 2: Hexagonal Architecture (Ports and Adapters)
```rust
// Core domain (no external dependencies)
mod core {
pub struct McpCore {
// Business rules
}
// Ports (interfaces)
pub trait DataPort: Send + Sync {
async fn fetch(&self, id: &str) -> Result<Data>;
}
pub trait CachePort: Send + Sync {
async fn get(&self, key: &str) -> Option<String>;
async fn set(&self, key: &str, value: String);
}
}
// Adapters (implementations)
mod adapters {
use super::core::*;
pub struct PostgresAdapter {
pool: PgPool,
}
impl DataPort for PostgresAdapter {
async fn fetch(&self, id: &str) -> Result<Data> {
// Database implementation
}
}
pub struct RedisAdapter {
client: redis::Client,
}
impl CachePort for RedisAdapter {
async fn get(&self, key: &str) -> Option<String> {
// Redis implementation
}
}
}
// MCP Service uses ports, not concrete adapters
#[tool(tool_box)]
struct McpService {
core: Arc<McpCore>,
data: Arc<dyn DataPort>,
cache: Arc<dyn CachePort>,
}
```
### Pattern 3: Repository Pattern
```rust
use async_trait::async_trait;
#[async_trait]
trait Repository<T>: Send + Sync {
async fn get(&self, id: &str) -> Result<Option<T>>;
async fn list(&self) -> Result<Vec<T>>;
async fn create(&self, entity: &T) -> Result<String>;
async fn update(&self, id: &str, entity: &T) -> Result<()>;
async fn delete(&self, id: &str) -> Result<()>;
}
struct UserRepository {
pool: PgPool,
}
#[async_trait]
impl Repository<User> for UserRepository {
async fn get(&self, id: &str) -> Result<Option<User>> {
sqlx::query_as!(User, "SELECT * FROM users WHERE id = $1", id)
.fetch_optional(&self.pool)
.await
.map_err(Into::into)
}
// ... other methods
}
#[tool(tool_box)]
struct UserService {
repo: Arc<UserRepository>,
}
#[tool(tool_box)]
impl UserService {
#[tool(description = "Get user by ID")]
async fn get_user(&self, id: String) -> Result<User, ServiceError> {
self.repo.get(&id).await?
.ok_or_else(|| ServiceError::NotFound(format!("User {}", id)))
}
}
```
## Error Handling
### Comprehensive Error Types
```rust
use thiserror::Error;
#[derive(Debug, Error)]
pub enum ServiceError {
#[error("Resource not found: {0}")]
NotFound(String),
#[error("Invalid input: {field} - {message}")]
InvalidInput { field: String, message: String },
#[error("Permission denied: {0}")]
PermissionDenied(String),
#[error("Rate limit exceeded: {0}")]
RateLimitExceeded(String),
#[error("External service error: {service} - {message}")]
ExternalServiceError { service: String, message: String },
#[error("Database error: {0}")]
DatabaseError(#[from] sqlx::Error),
#[error("Serialization error: {0}")]
SerializationError(#[from] serde_json::Error),
#[error("Internal error: {0}")]
Internal(String),
}
impl ServiceError {
pub fn error_code(&self) -> &'static str {
match self {
Self::NotFound(_) => "NOT_FOUND",
Self::InvalidInput { .. } => "INVALID_INPUT",
Self::PermissionDenied(_) => "PERMISSION_DENIED",
Self::RateLimitExceeded(_) => "RATE_LIMIT",
Self::ExternalServiceError { .. } => "EXTERNAL_ERROR",
Self::DatabaseError(_) => "DATABASE_ERROR",
Self::SerializationError(_) => "SERIALIZATION_ERROR",
Self::Internal(_) => "INTERNAL_ERROR",
}
}
pub fn is_retryable(&self) -> bool {
matches!(
self,
Self::ExternalServiceError { .. } | Self::DatabaseError(_)
)
}
}
```
### Error Context and Recovery
```rust
use anyhow::Context;
#[tool(tool_box)]
impl MyService {
#[tool(description = "Fetch data with retry")]
async fn fetch_with_retry(&self, id: String) -> Result<Data, ServiceError> {
let mut attempts = 0;
let max_attempts = 3;
loop {
attempts += 1;
match self.fetch_data(&id).await {
Ok(data) => return Ok(data),
Err(e) if e.is_retryable() && attempts < max_attempts => {
tracing::warn!(
"Attempt {} failed: {}. Retrying...",
attempts,
e
);
tokio::time::sleep(Duration::from_millis(100 * attempts)).await;
continue;
}
Err(e) => {
return Err(e)
.context(format!("Failed after {} attempts", attempts))?;
}
}
}
}
}
```
## Security
### Input Validation
```rust
use validator::{Validate, ValidationError};
#[derive(Debug, Deserialize, Validate, JsonSchema)]
struct CreateUserRequest {
#[validate(length(min = 1, max = 100))]
name: String,
#[validate(email)]
email: String,
#[validate(length(min = 8))]
password: String,
#[validate(range(min = 18, max = 120))]
age: u32,
}
#[tool(tool_box)]
impl UserService {
#[tool(description = "Create user with validation")]
async fn create_user(
&self,
#[tool(aggr)] req: CreateUserRequest,
) -> Result<User, ServiceError> {
// Validate input
req.validate()
.map_err(|e| ServiceError::InvalidInput {
field: "request".to_string(),
message: e.to_string(),
})?;
// Additional business validation
if self.repo.exists_by_email(&req.email).await? {
return Err(ServiceError::InvalidInput {
field: "email".to_string(),
message: "Email already exists".to_string(),
});
}
// Hash password
let password_hash = hash_password(&req.password)?;
// Create user
let user = User {
id: Uuid::new_v4().to_string(),
name: req.name,
email: req.email,
password_hash,
age: req.age,
};
self.repo.create(&user).await?;
Ok(user)
}
}
```
### Authentication and Authorization
```rust
use jsonwebtoken::{decode, DecodingKey, Validation};
#[derive(Debug, Deserialize)]
struct Claims {
sub: String, // user ID
role: String,
exp: usize,
}
struct AuthContext {
user_id: String,
role: String,
}
impl AuthContext {
fn from_token(token: &str) -> Result<Self, ServiceError> {
let key = DecodingKey::from_secret(SECRET.as_ref());
let token_data = decode::<Claims>(token, 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.