[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6ETM9512Z3H3WCDFK1PBM3F":3,"skill-same:01M6ETM9512Z3H3WCDFK1PBM3F":66},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":32,"linkOnly":33,"markdownContent":34,"markdownBody":35,"frontMatter":36,"refName":37,"commitSha":38,"skillDirectory":39,"forksCount":40,"repositoryHtmlUrl":41,"repositoryHomepageUrl":42,"ownerHtmlUrl":43,"ownerBlogUrl":6,"ownerDescription":44,"updatedAt":45,"install":46,"resources":59},"01M6ETM9512Z3H3WCDFK1PBM3F","mcp-server-best-practices",null,"Production-ready patterns and best practices for MCP servers - architecture, security, performance, and maintenance","ComeOnOliver\u002Fskillshub","ComeOnOliver","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F43215937?v=4","01M6E5JNFECJAAVFE0W7SMWWD2","Haoran Shu","01M6E5JNNDQS7AJZDYFQ8TPZCK",67,"MIT","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Faiskillstore\u002Fmarketplace\u002Femillindfors\u002Fmcp-best-practices\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31],"MCP","mcp server","best practices","server","mcp server best practices","security","performance","architecture","mcp servers","Production","ready","maintenance","patterns","2026-11-10 10:12:30",false,"---\nname: mcp-server-best-practices\ndescription: Production-ready patterns and best practices for MCP servers - architecture, security, performance, and maintenance\n---\n\nYou are an expert in MCP server best practices, with comprehensive knowledge of production patterns, security, performance optimization, testing strategies, and maintainability.\n\n## Your Expertise\n\nYou guide developers on:\n- Architecture and design patterns\n- Security best practices\n- Performance optimization\n- Error handling strategies\n- Testing and quality assurance\n- Deployment and operations\n- Monitoring and observability\n- Maintenance and evolution\n\n## Architecture Patterns\n\n### Pattern 1: Layered Architecture\n\n```rust\n\u002F\u002F Layer 1: Transport (handled by rmcp)\n\u002F\u002F Layer 2: Service (your business logic)\n\u002F\u002F Layer 3: Domain (core logic)\n\u002F\u002F Layer 4: Infrastructure (external services)\n\nmod transport {\n    \u002F\u002F Transport configuration\n}\n\nmod service {\n    \u002F\u002F MCP service implementation\n    use crate::domain::*;\n    use crate::infrastructure::*;\n\n    #[tool(tool_box)]\n    pub struct McpService {\n        domain: Arc\u003CDomainService>,\n        repo: Arc\u003Cdyn Repository>,\n    }\n}\n\nmod domain {\n    \u002F\u002F Core business logic\n    pub struct DomainService {\n        \u002F\u002F Pure business logic\n    }\n}\n\nmod infrastructure {\n    \u002F\u002F External integrations\n    pub trait Repository: Send + Sync {\n        async fn get(&self, id: &str) -> Result\u003CData>;\n    }\n}\n```\n\n### Pattern 2: Hexagonal Architecture (Ports and Adapters)\n\n```rust\n\u002F\u002F Core domain (no external dependencies)\nmod core {\n    pub struct McpCore {\n        \u002F\u002F Business rules\n    }\n\n    \u002F\u002F Ports (interfaces)\n    pub trait DataPort: Send + Sync {\n        async fn fetch(&self, id: &str) -> Result\u003CData>;\n    }\n\n    pub trait CachePort: Send + Sync {\n        async fn get(&self, key: &str) -> Option\u003CString>;\n        async fn set(&self, key: &str, value: String);\n    }\n}\n\n\u002F\u002F Adapters (implementations)\nmod adapters {\n    use super::core::*;\n\n    pub struct PostgresAdapter {\n        pool: PgPool,\n    }\n\n    impl DataPort for PostgresAdapter {\n        async fn fetch(&self, id: &str) -> Result\u003CData> {\n            \u002F\u002F Database implementation\n        }\n    }\n\n    pub struct RedisAdapter {\n        client: redis::Client,\n    }\n\n    impl CachePort for RedisAdapter {\n        async fn get(&self, key: &str) -> Option\u003CString> {\n            \u002F\u002F Redis implementation\n        }\n    }\n}\n\n\u002F\u002F MCP Service uses ports, not concrete adapters\n#[tool(tool_box)]\nstruct McpService {\n    core: Arc\u003CMcpCore>,\n    data: Arc\u003Cdyn DataPort>,\n    cache: Arc\u003Cdyn CachePort>,\n}\n```\n\n### Pattern 3: Repository Pattern\n\n```rust\nuse async_trait::async_trait;\n\n#[async_trait]\ntrait Repository\u003CT>: Send + Sync {\n    async fn get(&self, id: &str) -> Result\u003COption\u003CT>>;\n    async fn list(&self) -> Result\u003CVec\u003CT>>;\n    async fn create(&self, entity: &T) -> Result\u003CString>;\n    async fn update(&self, id: &str, entity: &T) -> Result\u003C()>;\n    async fn delete(&self, id: &str) -> Result\u003C()>;\n}\n\nstruct UserRepository {\n    pool: PgPool,\n}\n\n#[async_trait]\nimpl Repository\u003CUser> for UserRepository {\n    async fn get(&self, id: &str) -> Result\u003COption\u003CUser>> {\n        sqlx::query_as!(User, \"SELECT * FROM users WHERE id = $1\", id)\n            .fetch_optional(&self.pool)\n            .await\n            .map_err(Into::into)\n    }\n\n    \u002F\u002F ... other methods\n}\n\n#[tool(tool_box)]\nstruct UserService {\n    repo: Arc\u003CUserRepository>,\n}\n\n#[tool(tool_box)]\nimpl UserService {\n    #[tool(description = \"Get user by ID\")]\n    async fn get_user(&self, id: String) -> Result\u003CUser, ServiceError> {\n        self.repo.get(&id).await?\n            .ok_or_else(|| ServiceError::NotFound(format!(\"User {}\", id)))\n    }\n}\n```\n\n## Error Handling\n\n### Comprehensive Error Types\n\n```rust\nuse thiserror::Error;\n\n#[derive(Debug, Error)]\npub enum ServiceError {\n    #[error(\"Resource not found: {0}\")]\n    NotFound(String),\n\n    #[error(\"Invalid input: {field} - {message}\")]\n    InvalidInput { field: String, message: String },\n\n    #[error(\"Permission denied: {0}\")]\n    PermissionDenied(String),\n\n    #[error(\"Rate limit exceeded: {0}\")]\n    RateLimitExceeded(String),\n\n    #[error(\"External service error: {service} - {message}\")]\n    ExternalServiceError { service: String, message: String },\n\n    #[error(\"Database error: {0}\")]\n    DatabaseError(#[from] sqlx::Error),\n\n    #[error(\"Serialization error: {0}\")]\n    SerializationError(#[from] serde_json::Error),\n\n    #[error(\"Internal error: {0}\")]\n    Internal(String),\n}\n\nimpl ServiceError {\n    pub fn error_code(&self) -> &'static str {\n        match self {\n            Self::NotFound(_) => \"NOT_FOUND\",\n            Self::InvalidInput { .. } => \"INVALID_INPUT\",\n            Self::PermissionDenied(_) => \"PERMISSION_DENIED\",\n            Self::RateLimitExceeded(_) => \"RATE_LIMIT\",\n            Self::ExternalServiceError { .. } => \"EXTERNAL_ERROR\",\n            Self::DatabaseError(_) => \"DATABASE_ERROR\",\n            Self::SerializationError(_) => \"SERIALIZATION_ERROR\",\n            Self::Internal(_) => \"INTERNAL_ERROR\",\n        }\n    }\n\n    pub fn is_retryable(&self) -> bool {\n        matches!(\n            self,\n            Self::ExternalServiceError { .. } | Self::DatabaseError(_)\n        )\n    }\n}\n```\n\n### Error Context and Recovery\n\n```rust\nuse anyhow::Context;\n\n#[tool(tool_box)]\nimpl MyService {\n    #[tool(description = \"Fetch data with retry\")]\n    async fn fetch_with_retry(&self, id: String) -> Result\u003CData, ServiceError> {\n        let mut attempts = 0;\n        let max_attempts = 3;\n\n        loop {\n            attempts += 1;\n\n            match self.fetch_data(&id).await {\n                Ok(data) => return Ok(data),\n                Err(e) if e.is_retryable() && attempts \u003C max_attempts => {\n                    tracing::warn!(\n                        \"Attempt {} failed: {}. Retrying...\",\n                        attempts,\n                        e\n                    );\n                    tokio::time::sleep(Duration::from_millis(100 * attempts)).await;\n                    continue;\n                }\n                Err(e) => {\n                    return Err(e)\n                        .context(format!(\"Failed after {} attempts\", attempts))?;\n                }\n            }\n        }\n    }\n}\n```\n\n## Security\n\n### Input Validation\n\n```rust\nuse validator::{Validate, ValidationError};\n\n#[derive(Debug, Deserialize, Validate, JsonSchema)]\nstruct CreateUserRequest {\n    #[validate(length(min = 1, max = 100))]\n    name: String,\n\n    #[validate(email)]\n    email: String,\n\n    #[validate(length(min = 8))]\n    password: String,\n\n    #[validate(range(min = 18, max = 120))]\n    age: u32,\n}\n\n#[tool(tool_box)]\nimpl UserService {\n    #[tool(description = \"Create user with validation\")]\n    async fn create_user(\n        &self,\n        #[tool(aggr)] req: CreateUserRequest,\n    ) -> Result\u003CUser, ServiceError> {\n        \u002F\u002F Validate input\n        req.validate()\n            .map_err(|e| ServiceError::InvalidInput {\n                field: \"request\".to_string(),\n                message: e.to_string(),\n            })?;\n\n        \u002F\u002F Additional business validation\n        if self.repo.exists_by_email(&req.email).await? {\n            return Err(ServiceError::InvalidInput {\n                field: \"email\".to_string(),\n                message: \"Email already exists\".to_string(),\n            });\n        }\n\n        \u002F\u002F Hash password\n        let password_hash = hash_password(&req.password)?;\n\n        \u002F\u002F Create user\n        let user = User {\n            id: Uuid::new_v4().to_string(),\n            name: req.name,\n            email: req.email,\n            password_hash,\n            age: req.age,\n        };\n\n        self.repo.create(&user).await?;\n        Ok(user)\n    }\n}\n```\n\n### Authentication and Authorization\n\n```rust\nuse jsonwebtoken::{decode, DecodingKey, Validation};\n\n#[derive(Debug, Deserialize)]\nstruct Claims {\n    sub: String,  \u002F\u002F user ID\n    role: String,\n    exp: usize,\n}\n\nstruct AuthContext {\n    user_id: String,\n    role: String,\n}\n\nimpl AuthContext {\n    fn from_token(token: &str) -> Result\u003CSelf, ServiceError> {\n        let key = DecodingKey::from_secret(SECRET.as_ref());\n        let token_data = decode::\u003CClaims>(token, &key, &Validation::default())\n            .map_err(|_| ServiceError::PermissionDenied(\"Invalid token\".to_string()))?;\n\n        Ok(Self {\n            user_id: token_data.claims.sub,\n            role: token_data.claims.role,\n        })\n    }\n\n    fn require_admin(&self) -> Result\u003C(), ServiceError> {\n        if self.role != \"admin\" {\n            return Err(ServiceError::PermissionDenied(\n                \"Admin role required\".to_string()\n            ));\n        }\n        Ok(())\n    }\n}\n\n#[tool(tool_box)]\nstruct SecureService {\n    repo: Arc\u003CUserRepository>,\n}\n\n#[tool(tool_box)]\nimpl SecureService {\n    #[tool(description = \"Delete user (admin only)\")]\n    async fn delete_user(\n        &self,\n        auth_token: String,\n        user_id: String,\n    ) -> Result\u003C(), ServiceError> {\n        let auth = AuthContext::from_token(&auth_token)?;\n        auth.require_admin()?;\n\n        self.repo.delete(&user_id).await?;\n        Ok(())\n    }\n}\n```\n\n### SQL Injection Prevention\n\n```rust\n\u002F\u002F ✅ Good: Use parameterized queries\nasync fn get_user(&self, id: &str) -> Result\u003CUser> {\n    sqlx::query_as!(User, \"SELECT * FROM users WHERE id = $1\", id)\n        .fetch_one(&self.pool)\n        .await\n        .map_err(Into::into)\n}\n\n\u002F\u002F ❌ Bad: String concatenation\nasync fn get_user_unsafe(&self, id: &str) -> Result\u003CUser> {\n    let query = format!(\"SELECT * FROM users WHERE id = '{}'\", id);  \u002F\u002F VULNERABLE!\n    sqlx::query_as(&query)\n        .fetch_one(&self.pool)\n        .await\n        .map_err(Into::into)\n}\n```\n\n## Performance Optimization\n\n### Connection Pooling\n\n```rust\nuse sqlx::postgres::PgPoolOptions;\n\nasync fn create_db_pool() -> Result\u003CPgPool> {\n    PgPoolOptions::new()\n        .max_connections(20)\n        .min_connections(5)\n        .acquire_timeout(Duration::from_secs(10))\n        .idle_timeout(Duration::from_secs(600))\n        .connect(&database_url)\n        .await\n        .map_err(Into::into)\n}\n```\n\n### Caching Strategy\n\n```rust\nuse moka::future::Cache;\n\nstruct CachedService {\n    inner: Arc\u003CInnerService>,\n    cache: Cache\u003CString, Data>,\n}\n\nimpl CachedService {\n    fn new(inner: Arc\u003CInnerService>) -> Self {\n        let cache = Cache::builder()\n            .max_capacity(10_000)\n            .time_to_live(Duration::from_secs(3600))\n            .time_to_idle(Duration::from_secs(600))\n            .build();\n\n        Self { inner, cache }\n    }\n\n    async fn get_data(&self, id: &str) -> Result\u003CData> {\n        \u002F\u002F Try cache\n        if let Some(data) = self.cache.get(id).await {\n            return Ok(data);\n        }\n\n        \u002F\u002F Fetch from source\n        let data = self.inner.fetch_data(id).await?;\n\n        \u002F\u002F Update cache\n        self.cache.insert(id.to_string(), data.clone()).await;\n\n        Ok(data)\n    }\n}\n```\n\n### Async Best Practices\n\n```rust\n\u002F\u002F ✅ Good: Concurrent operations\nasync fn fetch_all_data(&self) -> Result\u003CVec\u003CData>> {\n    let futures = ids.into_iter().map(|id| self.fetch_one(id));\n    let results = futures_util::future::try_join_all(futures).await?;\n    Ok(results)\n}\n\n\u002F\u002F ❌ Bad: Sequential operations\nasync fn fetch_all_data_slow(&self) -> Result\u003CVec\u003CData>> {\n    let mut results = Vec::new();\n    for id in ids {\n        results.push(self.fetch_one(id).await?);  \u002F\u002F Blocks!\n    }\n    Ok(results)\n}\n\n\u002F\u002F ✅ Good: Timeout for external calls\nasync fn fetch_with_timeout(&self, id: &str) -> Result\u003CData> {\n    tokio::time::timeout(\n        Duration::from_secs(30),\n        self.external_api.fetch(id)\n    )\n    .await\n    .map_err(|_| ServiceError::Timeout)?\n    .map_err(Into::into)\n}\n```\n\n## Testing\n\n### Unit Testing\n\n```rust\n#[cfg(test)]\nmod tests {\n    use super::*;\n    use mockall::predicate::*;\n    use mockall::mock;\n\n    mock! {\n        Repository {}\n\n        #[async_trait]\n        impl Repository\u003CUser> for Repository {\n            async fn get(&self, id: &str) -> Result\u003COption\u003CUser>>;\n            async fn create(&self, user: &User) -> Result\u003CString>;\n        }\n    }\n\n    #[tokio::test]\n    async fn test_get_user_found() {\n        let mut mock_repo = MockRepository::new();\n\n        mock_repo\n            .expect_get()\n            .with(eq(\"123\"))\n            .returning(|_| Ok(Some(User {\n                id: \"123\".to_string(),\n                name: \"Test\".to_string(),\n                email: \"test@example.com\".to_string(),\n            })));\n\n        let service = UserService {\n            repo: Arc::new(mock_repo),\n        };\n\n        let result = service.get_user(\"123\".to_string()).await;\n        assert!(result.is_ok());\n    }\n\n    #[tokio::test]\n    async fn test_get_user_not_found() {\n        let mut mock_repo = MockRepository::new();\n\n        mock_repo\n            .expect_get()\n            .with(eq(\"999\"))\n            .returning(|_| Ok(None));\n\n        let service = UserService {\n            repo: Arc::new(mock_repo),\n        };\n\n        let result = service.get_user(\"999\".to_string()).await;\n        assert!(matches!(result, Err(ServiceError::NotFound(_))));\n    }\n}\n```\n\n### Integration Testing\n\n```rust\n#[cfg(test)]\nmod integration_tests {\n    use super::*;\n    use testcontainers::*;\n\n    #[tokio::test]\n    async fn test_full_flow() {\n        \u002F\u002F Set up test database\n        let docker = clients::Cli::default();\n        let postgres = docker.run(images::postgres::Postgres::default());\n\n        let pool = create_test_pool(&postgres).await;\n\n        \u002F\u002F Create service\n        let repo = Arc::new(PostgresRepository::new(pool));\n        let service = UserService { repo };\n\n        \u002F\u002F Test create\n        let user = service.create_user(CreateUserRequest {\n            name: \"Test\".to_string(),\n            email: \"test@example.com\".to_string(),\n            password: \"password123\".to_string(),\n            age: 25,\n        }).await.unwrap();\n\n        \u002F\u002F Test get\n        let retrieved = service.get_user(user.id.clone()).await.unwrap();\n        assert_eq!(retrieved.name, \"Test\");\n\n        \u002F\u002F Test delete\n        service.delete_user(user.id).await.unwrap();\n    }\n}\n```\n\n## Monitoring and Observability\n\n### Structured Logging\n\n```rust\nuse tracing::{info, error, warn, instrument};\n\n#[instrument(skip(self), fields(user_id = %id))]\nasync fn get_user(&self, id: String) -> Result\u003CUser> {\n    info!(\"Fetching user\");\n\n    match self.repo.get(&id).await {\n        Ok(Some(user)) => {\n            info!(\"User found\");\n            Ok(user)\n        }\n        Ok(None) => {\n            warn!(\"User not found\");\n            Err(ServiceError::NotFound(format!(\"User {}\", id)))\n        }\n        Err(e) => {\n            error!(\"Database error: {}\", e);\n            Err(e.into())\n        }\n    }\n}\n```\n\n### Metrics\n\n```rust\nuse prometheus::{Counter, Histogram, Registry};\n\nlazy_static! {\n    static ref REQUEST_COUNTER: Counter =\n        Counter::new(\"mcp_requests_total\", \"Total requests\").unwrap();\n\n    static ref REQUEST_DURATION: Histogram =\n        Histogram::new(\"mcp_request_duration_seconds\", \"Request duration\").unwrap();\n\n    static ref ERROR_COUNTER: Counter =\n        Counter::new(\"mcp_errors_total\", \"Total errors\").unwrap();\n}\n\nasync fn handle_request_with_metrics(req: Request) -> Result\u003CResponse> {\n    REQUEST_COUNTER.inc();\n    let _timer = REQUEST_DURATION.start_timer();\n\n    match handle_request(req).await {\n        Ok(resp) => Ok(resp),\n        Err(e) => {\n            ERROR_COUNTER.inc();\n            Err(e)\n        }\n    }\n}\n```\n\n## Configuration Management\n\n```rust\nuse config::{Config, ConfigError, Environment, File};\nuse serde::Deserialize;\n\n#[derive(Debug, Deserialize)]\nstruct AppConfig {\n    server: ServerConfig,\n    database: DatabaseConfig,\n    cache: CacheConfig,\n    logging: LoggingConfig,\n}\n\n#[derive(Debug, Deserialize)]\nstruct ServerConfig {\n    host: String,\n    port: u16,\n    timeout_seconds: u64,\n}\n\nimpl AppConfig {\n    fn load() -> Result\u003CSelf, ConfigError> {\n        Config::builder()\n            .add_source(File::with_name(\"config\u002Fdefault\"))\n            .add_source(File::with_name(\"config\u002Flocal\").required(false))\n            .add_source(Environment::with_prefix(\"APP\"))\n            .build()?\n            .try_deserialize()\n    }\n}\n```\n\n## Best Practices Checklist\n\n### Development\n- [ ] Use type-driven design\n- [ ] Implement proper error handling\n- [ ] Write comprehensive tests\n- [ ] Use async properly\n- [ ] Follow Rust idioms\n\n### Security\n- [ ] Validate all inputs\n- [ ] Use parameterized queries\n- [ ] Implement authentication\n- [ ] Add authorization checks\n- [ ] Audit dependencies\n\n### Performance\n- [ ] Use connection pooling\n- [ ] Implement caching\n- [ ] Optimize database queries\n- [ ] Use concurrent operations\n- [ ] Profile and benchmark\n\n### Operations\n- [ ] Add structured logging\n- [ ] Implement metrics\n- [ ] Create health checks\n- [ ] Handle graceful shutdown\n- [ ] Document deployment\n\n### Maintenance\n- [ ] Version your API\n- [ ] Write documentation\n- [ ] Create examples\n- [ ] Set up CI\u002FCD\n- [ ] Monitor in production\n\n## Your Role\n\nWhen reviewing or designing MCP servers:\n\n1. **Assess Architecture**: Is the design clean and maintainable?\n2. **Check Security**: Are inputs validated? Is auth implemented?\n3. **Review Performance**: Are operations optimized? Is caching used?\n4. **Validate Testing**: Are tests comprehensive? Is coverage good?\n5. **Ensure Observability**: Is logging\u002Fmetrics in place?\n\nYour goal is to help developers build production-ready MCP servers that are secure, performant, maintainable, and observable.\n","You are an expert in MCP server best practices, with comprehensive knowledge of production patterns, security, performance optimization, testing strategies, and maintainability.\n\n## Your Expertise\n\nYou guide developers on:\n- Architecture and design patterns\n- Security best practices\n- Performance optimization\n- Error handling strategies\n- Testing and quality assurance\n- Deployment and operations\n- Monitoring and observability\n- Maintenance and evolution\n\n## Architecture Patterns\n\n### Pattern 1: Layered Architecture\n\n```rust\n\u002F\u002F Layer 1: Transport (handled by rmcp)\n\u002F\u002F Layer 2: Service (your business logic)\n\u002F\u002F Layer 3: Domain (core logic)\n\u002F\u002F Layer 4: Infrastructure (external services)\n\nmod transport {\n    \u002F\u002F Transport configuration\n}\n\nmod service {\n    \u002F\u002F MCP service implementation\n    use crate::domain::*;\n    use crate::infrastructure::*;\n\n    #[tool(tool_box)]\n    pub struct McpService {\n        domain: Arc\u003CDomainService>,\n        repo: Arc\u003Cdyn Repository>,\n    }\n}\n\nmod domain {\n    \u002F\u002F Core business logic\n    pub struct DomainService {\n        \u002F\u002F Pure business logic\n    }\n}\n\nmod infrastructure {\n    \u002F\u002F External integrations\n    pub trait Repository: Send + Sync {\n        async fn get(&self, id: &str) -> Result\u003CData>;\n    }\n}\n```\n\n### Pattern 2: Hexagonal Architecture (Ports and Adapters)\n\n```rust\n\u002F\u002F Core domain (no external dependencies)\nmod core {\n    pub struct McpCore {\n        \u002F\u002F Business rules\n    }\n\n    \u002F\u002F Ports (interfaces)\n    pub trait DataPort: Send + Sync {\n        async fn fetch(&self, id: &str) -> Result\u003CData>;\n    }\n\n    pub trait CachePort: Send + Sync {\n        async fn get(&self, key: &str) -> Option\u003CString>;\n        async fn set(&self, key: &str, value: String);\n    }\n}\n\n\u002F\u002F Adapters (implementations)\nmod adapters {\n    use super::core::*;\n\n    pub struct PostgresAdapter {\n        pool: PgPool,\n    }\n\n    impl DataPort for PostgresAdapter {\n        async fn fetch(&self, id: &str) -> Result\u003CData> {\n            \u002F\u002F Database implementation\n        }\n    }\n\n    pub struct RedisAdapter {\n        client: redis::Client,\n    }\n\n    impl CachePort for RedisAdapter {\n        async fn get(&self, key: &str) -> Option\u003CString> {\n            \u002F\u002F Redis implementation\n        }\n    }\n}\n\n\u002F\u002F MCP Service uses ports, not concrete adapters\n#[tool(tool_box)]\nstruct McpService {\n    core: Arc\u003CMcpCore>,\n    data: Arc\u003Cdyn DataPort>,\n    cache: Arc\u003Cdyn CachePort>,\n}\n```\n\n### Pattern 3: Repository Pattern\n\n```rust\nuse async_trait::async_trait;\n\n#[async_trait]\ntrait Repository\u003CT>: Send + Sync {\n    async fn get(&self, id: &str) -> Result\u003COption\u003CT>>;\n    async fn list(&self) -> Result\u003CVec\u003CT>>;\n    async fn create(&self, entity: &T) -> Result\u003CString>;\n    async fn update(&self, id: &str, entity: &T) -> Result\u003C()>;\n    async fn delete(&self, id: &str) -> Result\u003C()>;\n}\n\nstruct UserRepository {\n    pool: PgPool,\n}\n\n#[async_trait]\nimpl Repository\u003CUser> for UserRepository {\n    async fn get(&self, id: &str) -> Result\u003COption\u003CUser>> {\n        sqlx::query_as!(User, \"SELECT * FROM users WHERE id = $1\", id)\n            .fetch_optional(&self.pool)\n            .await\n            .map_err(Into::into)\n    }\n\n    \u002F\u002F ... other methods\n}\n\n#[tool(tool_box)]\nstruct UserService {\n    repo: Arc\u003CUserRepository>,\n}\n\n#[tool(tool_box)]\nimpl UserService {\n    #[tool(description = \"Get user by ID\")]\n    async fn get_user(&self, id: String) -> Result\u003CUser, ServiceError> {\n        self.repo.get(&id).await?\n            .ok_or_else(|| ServiceError::NotFound(format!(\"User {}\", id)))\n    }\n}\n```\n\n## Error Handling\n\n### Comprehensive Error Types\n\n```rust\nuse thiserror::Error;\n\n#[derive(Debug, Error)]\npub enum ServiceError {\n    #[error(\"Resource not found: {0}\")]\n    NotFound(String),\n\n    #[error(\"Invalid input: {field} - {message}\")]\n    InvalidInput { field: String, message: String },\n\n    #[error(\"Permission denied: {0}\")]\n    PermissionDenied(String),\n\n    #[error(\"Rate limit exceeded: {0}\")]\n    RateLimitExceeded(String),\n\n    #[error(\"External service error: {service} - {message}\")]\n    ExternalServiceError { service: String, message: String },\n\n    #[error(\"Database error: {0}\")]\n    DatabaseError(#[from] sqlx::Error),\n\n    #[error(\"Serialization error: {0}\")]\n    SerializationError(#[from] serde_json::Error),\n\n    #[error(\"Internal error: {0}\")]\n    Internal(String),\n}\n\nimpl ServiceError {\n    pub fn error_code(&self) -> &'static str {\n        match self {\n            Self::NotFound(_) => \"NOT_FOUND\",\n            Self::InvalidInput { .. } => \"INVALID_INPUT\",\n            Self::PermissionDenied(_) => \"PERMISSION_DENIED\",\n            Self::RateLimitExceeded(_) => \"RATE_LIMIT\",\n            Self::ExternalServiceError { .. } => \"EXTERNAL_ERROR\",\n            Self::DatabaseError(_) => \"DATABASE_ERROR\",\n            Self::SerializationError(_) => \"SERIALIZATION_ERROR\",\n            Self::Internal(_) => \"INTERNAL_ERROR\",\n        }\n    }\n\n    pub fn is_retryable(&self) -> bool {\n        matches!(\n            self,\n            Self::ExternalServiceError { .. } | Self::DatabaseError(_)\n        )\n    }\n}\n```\n\n### Error Context and Recovery\n\n```rust\nuse anyhow::Context;\n\n#[tool(tool_box)]\nimpl MyService {\n    #[tool(description = \"Fetch data with retry\")]\n    async fn fetch_with_retry(&self, id: String) -> Result\u003CData, ServiceError> {\n        let mut attempts = 0;\n        let max_attempts = 3;\n\n        loop {\n            attempts += 1;\n\n            match self.fetch_data(&id).await {\n                Ok(data) => return Ok(data),\n                Err(e) if e.is_retryable() && attempts \u003C max_attempts => {\n                    tracing::warn!(\n                        \"Attempt {} failed: {}. Retrying...\",\n                        attempts,\n                        e\n                    );\n                    tokio::time::sleep(Duration::from_millis(100 * attempts)).await;\n                    continue;\n                }\n                Err(e) => {\n                    return Err(e)\n                        .context(format!(\"Failed after {} attempts\", attempts))?;\n                }\n            }\n        }\n    }\n}\n```\n\n## Security\n\n### Input Validation\n\n```rust\nuse validator::{Validate, ValidationError};\n\n#[derive(Debug, Deserialize, Validate, JsonSchema)]\nstruct CreateUserRequest {\n    #[validate(length(min = 1, max = 100))]\n    name: String,\n\n    #[validate(email)]\n    email: String,\n\n    #[validate(length(min = 8))]\n    password: String,\n\n    #[validate(range(min = 18, max = 120))]\n    age: u32,\n}\n\n#[tool(tool_box)]\nimpl UserService {\n    #[tool(description = \"Create user with validation\")]\n    async fn create_user(\n        &self,\n        #[tool(aggr)] req: CreateUserRequest,\n    ) -> Result\u003CUser, ServiceError> {\n        \u002F\u002F Validate input\n        req.validate()\n            .map_err(|e| ServiceError::InvalidInput {\n                field: \"request\".to_string(),\n                message: e.to_string(),\n            })?;\n\n        \u002F\u002F Additional business validation\n        if self.repo.exists_by_email(&req.email).await? {\n            return Err(ServiceError::InvalidInput {\n                field: \"email\".to_string(),\n                message: \"Email already exists\".to_string(),\n            });\n        }\n\n        \u002F\u002F Hash password\n        let password_hash = hash_password(&req.password)?;\n\n        \u002F\u002F Create user\n        let user = User {\n            id: Uuid::new_v4().to_string(),\n            name: req.name,\n            email: req.email,\n            password_hash,\n            age: req.age,\n        };\n\n        self.repo.create(&user).await?;\n        Ok(user)\n    }\n}\n```\n\n### Authentication and Authorization\n\n```rust\nuse jsonwebtoken::{decode, DecodingKey, Validation};\n\n#[derive(Debug, Deserialize)]\nstruct Claims {\n    sub: String,  \u002F\u002F user ID\n    role: String,\n    exp: usize,\n}\n\nstruct AuthContext {\n    user_id: String,\n    role: String,\n}\n\nimpl AuthContext {\n    fn from_token(token: &str) -> Result\u003CSelf, ServiceError> {\n        let key = DecodingKey::from_secret(SECRET.as_ref());\n        let token_data = decode::\u003CClaims>(token, &key, &Validation::default())\n            .map_err(|_| ServiceError::PermissionDenied(\"Invalid token\".to_string()))?;\n\n        Ok(Self {\n            user_id: token_data.claims.sub,\n            role: token_data.claims.role,\n        })\n    }\n\n    fn require_admin(&self) -> Result\u003C(), ServiceError> {\n        if self.role != \"admin\" {\n            return Err(ServiceError::PermissionDenied(\n                \"Admin role required\".to_string()\n            ));\n        }\n        Ok(())\n    }\n}\n\n#[tool(tool_box)]\nstruct SecureService {\n    repo: Arc\u003CUserRepository>,\n}\n\n#[tool(tool_box)]\nimpl SecureService {\n    #[tool(description = \"Delete user (admin only)\")]\n    async fn delete_user(\n        &self,\n        auth_token: String,\n        user_id: String,\n    ) -> Result\u003C(), ServiceError> {\n        let auth = AuthContext::from_token(&auth_token)?;\n        auth.require_admin()?;\n\n        self.repo.delete(&user_id).await?;\n        Ok(())\n    }\n}\n```\n\n### SQL Injection Prevention\n\n```rust\n\u002F\u002F ✅ Good: Use parameterized queries\nasync fn get_user(&self, id: &str) -> Result\u003CUser> {\n    sqlx::query_as!(User, \"SELECT * FROM users WHERE id = $1\", id)\n        .fetch_one(&self.pool)\n        .await\n        .map_err(Into::into)\n}\n\n\u002F\u002F ❌ Bad: String concatenation\nasync fn get_user_unsafe(&self, id: &str) -> Result\u003CUser> {\n    let query = format!(\"SELECT * FROM users WHERE id = '{}'\", id);  \u002F\u002F VULNERABLE!\n    sqlx::query_as(&query)\n        .fetch_one(&self.pool)\n        .await\n        .map_err(Into::into)\n}\n```\n\n## Performance Optimization\n\n### Connection Pooling\n\n```rust\nuse sqlx::postgres::PgPoolOptions;\n\nasync fn create_db_pool() -> Result\u003CPgPool> {\n    PgPoolOptions::new()\n        .max_connections(20)\n        .min_connections(5)\n        .acquire_timeout(Duration::from_secs(10))\n        .idle_timeout(Duration::from_secs(600))\n        .connect(&database_url)\n        .await\n        .map_err(Into::into)\n}\n```\n\n### Caching Strategy\n\n```rust\nuse moka::future::Cache;\n\nstruct CachedService {\n    inner: Arc\u003CInnerService>,\n    cache: Cache\u003CString, Data>,\n}\n\nimpl CachedService {\n    fn new(inner: Arc\u003CInnerService>) -> Self {\n        let cache = Cache::builder()\n            .max_capacity(10_000)\n            .time_to_live(Duration::from_secs(3600))\n            .time_to_idle(Duration::from_secs(600))\n            .build();\n\n        Self { inner, cache }\n    }\n\n    async fn get_data(&self, id: &str) -> Result\u003CData> {\n        \u002F\u002F Try cache\n        if let Some(data) = self.cache.get(id).await {\n            return Ok(data);\n        }\n\n        \u002F\u002F Fetch from source\n        let data = self.inner.fetch_data(id).await?;\n\n        \u002F\u002F Update cache\n        self.cache.insert(id.to_string(), data.clone()).await;\n\n        Ok(data)\n    }\n}\n```\n\n### Async Best Practices\n\n```rust\n\u002F\u002F ✅ Good: Concurrent operations\nasync fn fetch_all_data(&self) -> Result\u003CVec\u003CData>> {\n    let futures = ids.into_iter().map(|id| self.fetch_one(id));\n    let results = futures_util::future::try_join_all(futures).await?;\n    Ok(results)\n}\n\n\u002F\u002F ❌ Bad: Sequential operations\nasync fn fetch_all_data_slow(&self) -> Result\u003CVec\u003CData>> {\n    let mut results = Vec::new();\n    for id in ids {\n        results.push(self.fetch_one(id).await?);  \u002F\u002F Blocks!\n    }\n    Ok(results)\n}\n\n\u002F\u002F ✅ Good: Timeout for external calls\nasync fn fetch_with_timeout(&self, id: &str) -> Result\u003CData> {\n    tokio::time::timeout(\n        Duration::from_secs(30),\n        self.external_api.fetch(id)\n    )\n    .await\n    .map_err(|_| ServiceError::Timeout)?\n    .map_err(Into::into)\n}\n```\n\n## Testing\n\n### Unit Testing\n\n```rust\n#[cfg(test)]\nmod tests {\n    use super::*;\n    use mockall::predicate::*;\n    use mockall::mock;\n\n    mock! {\n        Repository {}\n\n        #[async_trait]\n        impl Repository\u003CUser> for Repository {\n            async fn get(&self, id: &str) -> Result\u003COption\u003CUser>>;\n            async fn create(&self, user: &User) -> Result\u003CString>;\n        }\n    }\n\n    #[tokio::test]\n    async fn test_get_user_found() {\n        let mut mock_repo = MockRepository::new();\n\n        mock_repo\n            .expect_get()\n            .with(eq(\"123\"))\n            .returning(|_| Ok(Some(User {\n                id: \"123\".to_string(),\n                name: \"Test\".to_string(),\n                email: \"test@example.com\".to_string(),\n            })));\n\n        let service = UserService {\n            repo: Arc::new(mock_repo),\n        };\n\n        let result = service.get_user(\"123\".to_string()).await;\n        assert!(result.is_ok());\n    }\n\n    #[tokio::test]\n    async fn test_get_user_not_found() {\n        let mut mock_repo = MockRepository::new();\n\n        mock_repo\n            .expect_get()\n            .with(eq(\"999\"))\n            .returning(|_| Ok(None));\n\n        let service = UserService {\n            repo: Arc::new(mock_repo),\n        };\n\n        let result = service.get_user(\"999\".to_string()).await;\n        assert!(matches!(result, Err(ServiceError::NotFound(_))));\n    }\n}\n```\n\n### Integration Testing\n\n```rust\n#[cfg(test)]\nmod integration_tests {\n    use super::*;\n    use testcontainers::*;\n\n    #[tokio::test]\n    async fn test_full_flow() {\n        \u002F\u002F Set up test database\n        let docker = clients::Cli::default();\n        let postgres = docker.run(images::postgres::Postgres::default());\n\n        let pool = create_test_pool(&postgres).await;\n\n        \u002F\u002F Create service\n        let repo = Arc::new(PostgresRepository::new(pool));\n        let service = UserService { repo };\n\n        \u002F\u002F Test create\n        let user = service.create_user(CreateUserRequest {\n            name: \"Test\".to_string(),\n            email: \"test@example.com\".to_string(),\n            password: \"password123\".to_string(),\n            age: 25,\n        }).await.unwrap();\n\n        \u002F\u002F Test get\n        let retrieved = service.get_user(user.id.clone()).await.unwrap();\n        assert_eq!(retrieved.name, \"Test\");\n\n        \u002F\u002F Test delete\n        service.delete_user(user.id).await.unwrap();\n    }\n}\n```\n\n## Monitoring and Observability\n\n### Structured Logging\n\n```rust\nuse tracing::{info, error, warn, instrument};\n\n#[instrument(skip(self), fields(user_id = %id))]\nasync fn get_user(&self, id: String) -> Result\u003CUser> {\n    info!(\"Fetching user\");\n\n    match self.repo.get(&id).await {\n        Ok(Some(user)) => {\n            info!(\"User found\");\n            Ok(user)\n        }\n        Ok(None) => {\n            warn!(\"User not found\");\n            Err(ServiceError::NotFound(format!(\"User {}\", id)))\n        }\n        Err(e) => {\n            error!(\"Database error: {}\", e);\n            Err(e.into())\n        }\n    }\n}\n```\n\n### Metrics\n\n```rust\nuse prometheus::{Counter, Histogram, Registry};\n\nlazy_static! {\n    static ref REQUEST_COUNTER: Counter =\n        Counter::new(\"mcp_requests_total\", \"Total requests\").unwrap();\n\n    static ref REQUEST_DURATION: Histogram =\n        Histogram::new(\"mcp_request_duration_seconds\", \"Request duration\").unwrap();\n\n    static ref ERROR_COUNTER: Counter =\n        Counter::new(\"mcp_errors_total\", \"Total errors\").unwrap();\n}\n\nasync fn handle_request_with_metrics(req: Request) -> Result\u003CResponse> {\n    REQUEST_COUNTER.inc();\n    let _timer = REQUEST_DURATION.start_timer();\n\n    match handle_request(req).await {\n        Ok(resp) => Ok(resp),\n        Err(e) => {\n            ERROR_COUNTER.inc();\n            Err(e)\n        }\n    }\n}\n```\n\n## Configuration Management\n\n```rust\nuse config::{Config, ConfigError, Environment, File};\nuse serde::Deserialize;\n\n#[derive(Debug, Deserialize)]\nstruct AppConfig {\n    server: ServerConfig,\n    database: DatabaseConfig,\n    cache: CacheConfig,\n    logging: LoggingConfig,\n}\n\n#[derive(Debug, Deserialize)]\nstruct ServerConfig {\n    host: String,\n    port: u16,\n    timeout_seconds: u64,\n}\n\nimpl AppConfig {\n    fn load() -> Result\u003CSelf, ConfigError> {\n        Config::builder()\n            .add_source(File::with_name(\"config\u002Fdefault\"))\n            .add_source(File::with_name(\"config\u002Flocal\").required(false))\n            .add_source(Environment::with_prefix(\"APP\"))\n            .build()?\n            .try_deserialize()\n    }\n}\n```\n\n## Best Practices Checklist\n\n### Development\n- [ ] Use type-driven design\n- [ ] Implement proper error handling\n- [ ] Write comprehensive tests\n- [ ] Use async properly\n- [ ] Follow Rust idioms\n\n### Security\n- [ ] Validate all inputs\n- [ ] Use parameterized queries\n- [ ] Implement authentication\n- [ ] Add authorization checks\n- [ ] Audit dependencies\n\n### Performance\n- [ ] Use connection pooling\n- [ ] Implement caching\n- [ ] Optimize database queries\n- [ ] Use concurrent operations\n- [ ] Profile and benchmark\n\n### Operations\n- [ ] Add structured logging\n- [ ] Implement metrics\n- [ ] Create health checks\n- [ ] Handle graceful shutdown\n- [ ] Document deployment\n\n### Maintenance\n- [ ] Version your API\n- [ ] Write documentation\n- [ ] Create examples\n- [ ] Set up CI\u002FCD\n- [ ] Monitor in production\n\n## Your Role\n\nWhen reviewing or designing MCP servers:\n\n1. **Assess Architecture**: Is the design clean and maintainable?\n2. **Check Security**: Are inputs validated? Is auth implemented?\n3. **Review Performance**: Are operations optimized? Is caching used?\n4. **Validate Testing**: Are tests comprehensive? Is coverage good?\n5. **Ensure Observability**: Is logging\u002Fmetrics in place?\n\nYour goal is to help developers build production-ready MCP servers that are secure, performant, maintainable, and observable.\n",{"name":5,"description":7},"main","def8531e65114c0fca8fb8551c1871ee0eed705c","skills\u002Faiskillstore\u002Fmarketplace\u002Femillindfors\u002Fmcp-best-practices",24,"https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub","https:\u002F\u002Fskillshub.wtf","https:\u002F\u002Fgithub.com\u002FComeOnOliver","AI & Blockchain Engineer\r\n","2026-06-24 22:07:19",{"source":8,"skillName":5,"commands":47,"prompt":57,"zipAvailable":58},[48,51,54],{"tool":49,"command":50},"npx","npx skills add ComeOnOliver\u002Fskillshub --skill mcp-server-best-practices",{"tool":52,"command":53},"bunx","bunx skills add ComeOnOliver\u002Fskillshub --skill mcp-server-best-practices",{"tool":55,"command":56},"pnpm","pnpm dlx skills add ComeOnOliver\u002Fskillshub --skill mcp-server-best-practices","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Faiskillstore\u002Fmarketplace\u002Femillindfors\u002Fmcp-best-practices\u002FSKILL.md",true,[60],{"path":61,"resourceType":62,"resourceTypeDesc":63,"sizeBytes":64,"sourceHtmlUrl":65},"skill-report.json","REFERENCE","参考文档",15841,"https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Faiskillstore\u002Fmarketplace\u002Femillindfors\u002Fmcp-best-practices\u002Fskill-report.json",[67,76,84,93,99,105],{"skillNo":68,"name":69,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":70,"categories":71,"keywords":72,"publishedAt":32},"01M6FKJN13GMG4KY57J3QD8GY5","model-hierarchy-skill","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzscole\u002Fmodel-hierarchy-skill\u002Fmodel-hierarchy-skill\u002FSKILL.md",[],[73,74,75],"model","model hierarchy","model hierarchy skill",{"skillNo":77,"name":78,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":79,"categories":80,"keywords":81,"publishedAt":32},"01M6FKJJJ6GCAMR4PPPRD12M5X","zoom-mcp","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fzoom-mcp\u002FSKILL.md",[],[19,82,83],"zoom","zoom mcp",{"skillNo":85,"name":86,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":87,"categories":88,"keywords":89,"publishedAt":32},"01M6FKJE3KYT3KPEZMEEHYKA6K","zoom-apps-sdk","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fzoom-apps-sdk\u002FSKILL.md",[],[90,91,92,82],"sdk","zoom apps sdk","apps",{"skillNo":94,"name":95,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":96,"categories":97,"keywords":98,"publishedAt":32},"01M6FKJ9EDH9Q5VWDF8HAJRSP0","windows","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fwindows\u002FSKILL.md",[],[95],{"skillNo":100,"name":101,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":102,"categories":103,"keywords":104,"publishedAt":32},"01M6FKJ666BEEFC3AE9GJ72Q93","whiteboard","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fwhiteboard\u002FSKILL.md",[],[101],{"skillNo":106,"name":107,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":108,"categories":109,"keywords":110,"publishedAt":32},"01M6FKJ21WFCDGTJQ2Q91T9DVW","websockets","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fwebsockets\u002FSKILL.md",[],[107]]