SCIM Server Guide
Welcome to the comprehensive guide for the SCIM Server library! This guide will help you understand and use the Rust components for building enterprise-ready identity provisioning systems.
The Problem
Your application needs to support enterprise customers, but they require SCIM provisioning—the ability to automatically create, update, and delete user accounts from their identity systems (Okta, Azure Entra, Google Workspace, etc.).
Research shows that authentication requirements become critical blockers in 75-80% of enterprise deals, with companies losing an average of 3-5 enterprise deals annually due to insufficient identity capabilities. Building SCIM compliance seems straightforward at first: it's just REST APIs with JSON. But enterprise identity management has many hidden complexities that create months of unexpected work:
- Provider Fragmentation: Identity providers interpret SCIM differently—email handling, user deactivation, and custom attributes work differently across Okta, Azure, and Google
- Protocol Compliance: SCIM 2.0 has strict requirements with 10 common implementation pitfalls that cause enterprise integration failures
- Hidden Development Costs: Industry data shows 3-6 months and $3.5M+ in development costs for homegrown SSO/SCIM solutions over 3 years
- Ongoing Maintenance: Security incidents, provider-specific bugs, and manual customer onboarding create continuous overhead
- Schema Complexity: Extensible schemas with custom attributes while maintaining interoperability across different enterprise environments
Many developers underestimate this complexity and spend months debugging provider-specific edge cases, dealing with "more deviation than standard" implementations, and handling enterprise customers who discover integration issues in production.
What is SCIM Server?
SCIM Server is a Rust library that provides all the essential components for building SCIM 2.0-compliant systems. Instead of implementing SCIM from scratch, you get proven building blocks that handle the complex parts while letting you focus on your application logic.
The library uses the SCIM 2.0 protocol as a framework to standardize identity data validation and processing. You compose the components you need—from simple single-tenant systems to complex multi-tenant platforms with custom schemas and AI integration.
What You Get
Ready-to-Use Components
StandardResourceProvider: Complete SCIM resource operations for typical use casesInMemoryStorage: Development and testing storage backend- Schema Registry: Pre-loaded with RFC 7643 User and Group schemas
- ETag Versioning: Automatic concurrency control for production deployments
Extension Points
ResourceProvidertrait: Implement for custom business logic and data modelsStorageProvidertrait: Connect to any database or storage system- Custom Value Objects: Type-safe handling of domain-specific attributes
- Multi-Tenant Context: Built-in tenant isolation and context management
Enterprise Features
- Protocol Compliance: All the RFC 7643/7644 complexity handled correctly
- Schema Extensions: Add custom attributes while maintaining SCIM compatibility
- AI Integration: Model Context Protocol support for AI agent interactions
- Production Ready: Structured logging, error handling, and performance optimizations
Time & Cost Savings
Instead of facing the typical 3-6 month development timeline and $3.5M+ costs that industry data shows for homegrown solutions, focus on your application:
| Building From Scratch | Using SCIM Server |
|---|---|
| ❌ 3-6 months learning SCIM protocol complexities | ✅ Start building immediately with working components |
| ❌ $3.5M+ development and maintenance costs over 3 years | ✅ Fraction of the cost with proven components |
| ❌ Debugging provider-specific implementation differences | ✅ Handle Okta, Azure, Google variations automatically |
| ❌ Building multi-tenant isolation from scratch | ✅ Multi-tenant context and isolation built-in |
| ❌ Lost enterprise deals due to auth requirements | ✅ Enterprise-ready identity provisioning components |
Result: Avoid the 75-80% of enterprise deals that stall on authentication by having production-ready SCIM components instead of months of custom development.
Who Should Use This?
This library is designed for Rust developers who need to:
- Add enterprise customer support to SaaS applications requiring SCIM provisioning
- Build identity management tools that integrate with multiple identity providers
- Create AI agents that need to manage user accounts and permissions
- Develop custom identity solutions with specific business requirements
- Integrate existing systems with enterprise identity infrastructure
How to Use This Guide
The guide is organized into progressive sections:
- Getting Started: Quick setup and basic usage
- Core Concepts: Understanding the fundamental ideas
- Tutorials: Step-by-step guides for common scenarios
- How-To Guides: Solutions for specific problems
- Advanced Topics: Deep dives into complex scenarios
- Reference: Technical specifications and details
Learning Path
New to SCIM? Start with the Architecture Overview to understand the standard.
Ready to code? Jump to Your First SCIM Server for hands-on experience.
Building production systems? Read through Installation and the examples in the GitHub repository.
What You'll Learn
By the end of this guide, you'll understand how to:
- Compose SCIM Server components for your specific requirements
- Implement the ResourceProvider trait for your application's data model
- Create custom schema extensions and value objects
- Build multi-tenant systems using the provided context components
- Integrate SCIM components with web frameworks and AI tools
- Deploy production systems using the concurrency and observability components
Getting Help
- Examples: Check the examples directory for working code
- API Documentation: See docs.rs for detailed API reference
- Issues: Report bugs or ask questions on GitHub Issues
Let's get started! 🚀
References
Enterprise authentication challenges and statistics sourced from: Gupta, "Enterprise Authentication: The Hidden SaaS Growth Blocker", 2024; WorkOS "Build vs Buy" analysis, 2024; WorkOS ROI comparison, 2024.
SCIM implementation pitfalls from: Traxion "10 Most Common Pitfalls for SCIM 2.0 Compliant API Implementations" based on testing 40-50 SCIM implementations.
Provider-specific differences documented in: WorkOS "SCIM Challenges", 2024.
Installation
This guide will get you up and running with the SCIM server library in under 5 minutes.
Prerequisites
- Rust 1.75 or later - Install Rust
To verify your installation:
rustc --version
cargo --version
Adding the Dependency
Add to your Cargo.toml:
[dependencies]
scim-server = "=0.3.11"
tokio = { version = "1.0", features = ["full"] }
serde_json = "1.0"
Note: The library is under active development. Pin to exact versions for stability. Breaking changes are signaled by minor version increments until v1.0.
Verification
Create a simple test to verify the installation works:
use scim_server::{ ScimServer, providers::StandardResourceProvider, storage::InMemoryStorage, RequestContext }; use serde_json::json; #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { let storage = InMemoryStorage::new(); let provider = StandardResourceProvider::new(storage); let server = ScimServer::new(provider)?; let context = RequestContext::new("test".to_string()); let user_data = json!({ "schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"], "userName": "john.doe", "active": true }); let user = server.create_resource("User", user_data, &context).await?; let retrieved = server.get_resource("User", user.get_id().unwrap(), &context).await?; assert_eq!(retrieved.get_attribute("active").unwrap(), &json!(true)); Ok(()) }
Run with:
cargo run
If this runs without errors, your installation is working correctly!
Next Steps
Once installation is complete, proceed to:
- Your First SCIM Server - Build a complete working implementation
- Configuration Guide - Learn about storage backends and advanced setup
- API Reference - Explore all available operations
For production deployments, see the Production Setup Guide for information about system requirements, databases, and scaling considerations.
Your First SCIM Server
Learn to build a working SCIM server in 10 minutes using this library.
Quick Start
1. Create a New Project
cargo new my-scim-server
cd my-scim-server
2. Add Dependencies
[dependencies]
scim-server = "0.3.11"
tokio = { version = "1.0", features = ["full"] }
serde_json = "1.0"
3. Basic Server (15 lines)
use scim_server::{ providers::StandardResourceProvider, storage::InMemoryStorage, RequestContext, }; use serde_json::json; #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { // Create storage and provider - the foundation of your SCIM server let storage = InMemoryStorage::new(); // Simple storage for development let provider = StandardResourceProvider::new(storage); // Main SCIM interface // Create a single-tenant request context - tracks this operation for logging let context = RequestContext::new("demo".to_string()); let user_data = json!({ "userName": "john.doe", "emails": [{"value": "john@example.com", "primary": true}], "active": true }); let user = provider.create_resource("User", user_data, &context).await?; println!("Created user: {}", user.get_username().unwrap()); Ok(()) }
4. Run It
cargo run
# Output: Created user: john.doe
Core Operations
Setup
For the following examples, we'll use this provider and context setup:
#![allow(unused)] fn main() { use scim_server::{ providers::StandardResourceProvider, storage::InMemoryStorage, RequestContext, }; use serde_json::json; // Create storage and provider - the foundation of your SCIM server let storage = InMemoryStorage::new(); // Simple storage for development let provider = StandardResourceProvider::new(storage); // Main SCIM interface // Single-tenant RequestContext tracks each operation for logging let context = RequestContext::new("demo".to_string()); }
All the following examples will use these provider and context variables.
Creating Resources
#![allow(unused)] fn main() { // Use JSON to define user attributes following SCIM 2.0 schema let user_data = json!({ "userName": "alice.smith", "name": { "givenName": "Alice", "familyName": "Smith" }, "emails": [{"value": "alice@company.com", "primary": true}], "active": true }); // Create the user - provider handles validation and storage let user = provider.create_resource("User", user_data, &context).await?; let user_id = user.get_id().unwrap(); // Get the auto-generated unique ID }
Reading Resources
#![allow(unused)] fn main() { // Get user by ID - returns Option<Resource> (None if not found) let retrieved_user = provider.get_resource("User", &user_id, &context).await?; if let Some(user) = retrieved_user { println!("Found: {}", user.get_username().unwrap()); } // Search by specific attribute value - useful for username lookups let found_user = provider .find_resource_by_attribute("User", "userName", &json!("alice.smith"), &context) .await?; }
Updating Resources
#![allow(unused)] fn main() { // Updates require the full resource data, including the ID let update_data = json!({ "id": user_id, "userName": "alice.smith", "name": { "givenName": "Alice", "familyName": "Johnson" // Changed surname }, "emails": [{"value": "alice@company.com", "primary": true}], "active": false // Deactivated }); // Update replaces the entire resource with new data let updated_user = provider .update_resource("User", &user_id, update_data, &context) .await?; }
Listing and Searching
#![allow(unused)] fn main() { // List all users - None means no pagination/filtering let all_users = provider.list_resources("User", None, &context).await?; println!("Total users: {}", all_users.len()); // Efficiently check existence without retrieving full data let exists = provider.resource_exists("User", &user_id, &context).await?; println!("User exists: {}", exists); }
Validation and Error Handling
#![allow(unused)] fn main() { // The provider automatically validates data against SCIM schemas let invalid_user = json!({ "userName": "", // Empty username - violates SCIM requirements "emails": [{"value": "not-an-email"}], // Invalid email format }); // Always handle validation errors gracefully match provider.create_resource("User", invalid_user, &context).await { Ok(user) => println!("User created: {}", user.get_id().unwrap()), Err(e) => println!("Validation failed: {}", e), // Detailed error message } }
Deleting Resources
#![allow(unused)] fn main() { // Delete a resource by ID provider.delete_resource("User", &user_id, &context).await?; // Verify deletion let exists = provider.resource_exists("User", &user_id, &context).await?; println!("User still exists: {}", exists); // Should be false }
Working with Groups
#![allow(unused)] fn main() { // Groups can contain users as members - useful for access control // Create a group (assuming you have a user_id from previous examples) let group_data = json!({ "displayName": "Engineering Team", // Required: human-readable name "members": [ // Optional: list of member references { "value": user_id, // Reference to the user's ID "$ref": format!("https://example.com/v2/Users/{}", user_id), // Full URI "type": "User" // Type of the referenced resource } ] }); // Using the context and user_id from previous examples // Create group just like users - same provider interface let group = provider.create_resource("Group", group_data, &context).await?; println!("Created group: {}", group.get_attribute("displayName").unwrap()); }
Multi-Tenant Support
For multi-tenant scenarios, you create explicit tenant contexts instead of using the default single-tenant setup:
#![allow(unused)] fn main() { // Import TenantContext for multi-tenant operations use scim_server::resource::TenantContext; // Create the same provider as before let storage = InMemoryStorage::new(); let provider = StandardResourceProvider::new(storage); // Multi-tenant contexts - each gets isolated data space let tenant_a = TenantContext::new("company-a".to_string(), "client-123".to_string()); let tenant_a_context = RequestContext::with_tenant("req-a".to_string(), tenant_a); let tenant_b = TenantContext::new("company-b".to_string(), "client-456".to_string()); let tenant_b_context = RequestContext::with_tenant("req-b".to_string(), tenant_b); // Same provider, different tenants - data is completely isolated provider.create_resource("User", user_data.clone(), &tenant_a_context).await?; provider.create_resource("User", user_data, &tenant_b_context).await?; // Each tenant sees only their own data let tenant_a_users = provider.list_resources("User", None, &tenant_a_context).await?; let tenant_b_users = provider.list_resources("User", None, &tenant_b_context).await?; println!("Company A users: {}", tenant_a_users.len()); println!("Company B users: {}", tenant_b_users.len()); }
Provider Statistics
#![allow(unused)] fn main() { // Useful for monitoring and debugging your SCIM server let stats = provider.get_stats().await; println!("Total tenants: {}", stats.tenant_count); // Number of active tenants println!("Total resources: {}", stats.total_resources); // Users + Groups + etc. println!("Resource types: {:?}", stats.resource_types); // ["User", "Group", ...] }
Next Steps
- HTTP Server Integration - Add REST endpoints with Axum or Actix
- Multi-tenant Setup - Advanced tenant isolation and management
- Advanced Features - Groups, custom schemas, bulk operations
- Storage Backends - PostgreSQL, SQLite, and custom storage
Complete Examples
See the examples directory for full working implementations:
- basic_usage.rs - Complete CRUD operations
- group_example.rs - Group management with members
- multi_tenant_example.rs - Tenant isolation patterns
Running Examples
# Run any example to see it in action
cargo run --example basic_usage
cargo run --example group_example
Key Concepts
StandardResourceProvider- Main interface for SCIM operationsInMemoryStorage- Simple storage backend for developmentRequestContext- Request tracking and tenant isolation- Resource Types - "User", "Group", or custom types
- JSON Data - All resource data uses
serde_json::Value
You now have a working SCIM server! The examples above demonstrate all core functionality needed for most SCIM implementations.
Setting Up Your MCP Server
This guide shows you how to set up a working Model Context Protocol (MCP) server that exposes your SCIM operations as discoverable tools for AI agents.
What is MCP Integration?
The MCP integration allows AI agents to interact with your SCIM server through a standardized protocol. AI agents can discover available tools (like "create user" or "search users") and execute them with proper validation and error handling.
Key Benefits:
- AI-Friendly Interface - Structured tool discovery and execution
- Multi-Tenant Support - Isolated operations for different clients
- Schema Introspection - AI agents can understand your data model
- Error Handling - Graceful error responses with detailed information
Quick Start
1. Enable the MCP Feature
Add the MCP feature to your Cargo.toml:
[dependencies]
scim-server = { version = "0.3.11", features = ["mcp"] }
tokio = { version = "1.0", features = ["full"] }
serde_json = "1.0"
env_logger = "0.10" # For logging (recommended)
2. Basic MCP Server (30 lines)
Create a minimal MCP server that exposes SCIM operations:
use scim_server::{ mcp_integration::ScimMcpServer, multi_tenant::ScimOperation, providers::StandardResourceProvider, resource_handlers::create_user_resource_handler, scim_server::ScimServer, storage::InMemoryStorage, }; #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> { // Initialize logging for debugging env_logger::init(); // Create SCIM server with in-memory storage let storage = InMemoryStorage::new(); let provider = StandardResourceProvider::new(storage); let mut scim_server = ScimServer::new(provider)?; // Register User resource type with full operations let user_schema = scim_server .get_schema_by_id("urn:ietf:params:scim:schemas:core:2.0:User")? .clone(); let user_handler = create_user_resource_handler(user_schema); scim_server.register_resource_type( "User", user_handler, vec![ ScimOperation::Create, ScimOperation::Read, ScimOperation::Update, ScimOperation::Delete, ScimOperation::List, ScimOperation::Search, ], )?; // Create and start MCP server let mcp_server = ScimMcpServer::new(scim_server); println!("🚀 MCP Server starting - listening on stdio"); // This runs until EOF (Ctrl+D) or process termination mcp_server.run_stdio().await?; Ok(()) }
3. Run Your MCP Server
cargo run --features mcp
The server starts and listens on standard input/output for MCP protocol messages.
Testing Your Server
You can test the server by sending JSON-RPC messages directly:
1. Initialize Connection
echo '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{}}}' | your_server
2. Discover Available Tools
echo '{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}' | your_server
3. Create a User
echo '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"scim_create_user","arguments":{"user_data":{"schemas":["urn:ietf:params:scim:schemas:core:2.0:User"],"userName":"alice@example.com","active":true}}}}' | your_server
Production-Ready Setup
For production use, you'll want a more comprehensive setup:
use scim_server::{ mcp_integration::{McpServerInfo, ScimMcpServer}, multi_tenant::ScimOperation, providers::StandardResourceProvider, resource_handlers::{create_user_resource_handler, create_group_resource_handler}, scim_server::ScimServer, storage::InMemoryStorage, // Replace with your database storage }; #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> { // Production logging configuration env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")) .init(); // Create SCIM server (use your production storage here) let storage = InMemoryStorage::new(); // Replace with PostgresStorage, etc. let provider = StandardResourceProvider::new(storage); let mut scim_server = ScimServer::new(provider)?; // Register User resource type let user_schema = scim_server .get_schema_by_id("urn:ietf:params:scim:schemas:core:2.0:User")? .clone(); let user_handler = create_user_resource_handler(user_schema); scim_server.register_resource_type( "User", user_handler, vec![ ScimOperation::Create, ScimOperation::Read, ScimOperation::Update, ScimOperation::Delete, ScimOperation::List, ScimOperation::Search, ], )?; // Register Group resource type (if needed) if let Some(group_schema) = scim_server .get_schema_by_id("urn:ietf:params:scim:schemas:core:2.0:Group") { let group_handler = create_group_resource_handler(group_schema.clone()); scim_server.register_resource_type( "Group", group_handler, vec![ ScimOperation::Create, ScimOperation::Read, ScimOperation::Update, ScimOperation::Delete, ScimOperation::List, ScimOperation::Search, ], )?; } // Create MCP server with custom information let server_info = McpServerInfo { name: "Production SCIM Server".to_string(), version: env!("CARGO_PKG_VERSION").to_string(), description: "Enterprise SCIM server with MCP integration".to_string(), supported_resource_types: vec!["User".to_string(), "Group".to_string()], }; let mcp_server = ScimMcpServer::with_info(scim_server, server_info); // Log available tools let tools = mcp_server.get_tools(); log::info!("🔧 Available MCP tools: {}", tools.len()); for tool in &tools { if let Some(name) = tool.get("name").and_then(|n| n.as_str()) { log::info!(" • {}", name); } } log::info!("🚀 MCP Server ready - listening on stdio"); // Start the server mcp_server.run_stdio().await?; log::info!("✅ MCP Server shutdown complete"); Ok(()) }
Available MCP Tools
Your MCP server exposes these tools to AI agents:
User Management
scim_create_user- Create a new userscim_get_user- Retrieve user by IDscim_update_user- Update existing userscim_delete_user- Delete user by IDscim_list_users- List all users with paginationscim_search_users- Search users by attributescim_user_exists- Check if user exists
System Information
scim_get_schemas- Get all SCIM schemasscim_server_info- Get server capabilities and info
Multi-Tenant Support
The MCP server supports multi-tenant operations out of the box:
{
"jsonrpc": "2.0",
"id": 4,
"method": "tools/call",
"params": {
"name": "scim_create_user",
"arguments": {
"user_data": {
"schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],
"userName": "bob@tenant-a.com",
"active": true
},
"tenant_id": "tenant-a"
}
}
}
Each tenant's data is completely isolated from others.
Integration with AI Agents
Your MCP server can be used with any MCP-compatible AI agent or framework. The AI agent will:
- Initialize - Establish connection and capabilities
- Discover Tools - Get list of available SCIM operations
- Get Schemas - Understand your data model structure
- Execute Operations - Create, read, update, delete resources
- Handle Errors - Process validation and operation errors gracefully
Error Handling
The MCP server provides structured error responses for AI agents:
{
"jsonrpc": "2.0",
"id": 5,
"error": {
"code": -32000,
"message": "Tool execution failed: Validation error: userName is required"
}
}
Logging and Monitoring
Enable comprehensive logging for production deployments:
#![allow(unused)] fn main() { // In your main function env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")) .format_timestamp_secs() .init(); log::info!("MCP Server starting"); log::debug!("Available tools: {:?}", mcp_server.get_tools().len()); }
Running Examples
The crate includes complete working examples:
# Basic MCP server
cargo run --example mcp_stdio_server --features mcp
# Comprehensive example with demos
cargo run --example mcp_server_example --features mcp
Next Steps
- Storage Backends - Replace InMemoryStorage with PostgreSQL or other databases
- Multi-Tenant Configuration - Advanced tenant management
- Custom Resource Types - Beyond User and Group
- Production Deployment - Scaling and monitoring MCP servers
Complete Working Example
See examples/mcp_stdio_server.rs for a complete, production-ready MCP server implementation with:
- Comprehensive error handling
- Multi-tenant support
- Full logging configuration
- Tool discovery and execution
- Schema introspection
- Graceful shutdown handling
The MCP integration makes your SCIM server AI-ready with minimal configuration!
Architecture
The SCIM Server follows a clean trait-based architecture with clear separation of concerns designed for maximum composability and extensibility.
Component Architecture
The library is built around composable traits that you implement for your specific needs:
┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
│ Client Layer │ │ SCIM Server │ │ Resource Layer │
│ │ │ │ │ │
│ • MCP AI │───▶│ • Operations │───▶│ ResourceProvider│
│ • Web Framework│ │ • Multi-tenant │ │ trait │
│ • Custom │ │ • Type Safety │ │ │
└─────────────────┘ └──────────────────┘ └─────────────────┘
│ │
▼ ▼
┌──────────────────┐ ┌─────────────────┐
│ Schema System │ │ Storage Layer │
│ │ │ │
│ • SchemaRegistry │ │ StorageProvider │
│ • Validation │ │ trait │
│ • Value Objects │ │ • In-Memory │
│ • Extensions │ │ • Database │
└──────────────────┘ │ • Custom │
└─────────────────┘
Layer Responsibilities
Client Layer: Your integration points - compose these components into web endpoints, AI tools, or custom applications.
SCIM Server: Orchestration component that coordinates resource operations using your provider implementations.
Resource Layer: ResourceProvider trait - implement this interface for your data model, or use the provided StandardResourceProvider for common scenarios.
Schema System: Schema registry and validation components - extend with custom schemas and value objects.
Storage Layer: StorageProvider trait - use the provided InMemoryStorage for development, or connect to any database or custom backend.
Core Traits
ResourceProvider
Your main integration point for SCIM resource operations:
#![allow(unused)] fn main() { pub trait ResourceProvider { type Error: std::error::Error + Send + Sync + 'static; async fn create_resource( &self, resource_type: &str, data: Value, context: &RequestContext, ) -> Result<Resource, Self::Error>; async fn get_resource( &self, resource_type: &str, id: &str, context: &RequestContext, ) -> Result<Option<Resource>, Self::Error>; // ... other CRUD operations } }
Implementation Options:
- Use
StandardResourceProvider<S>with anyStorageProviderfor typical use cases - Implement directly for custom business logic and data models
- Wrap existing services or databases
StorageProvider
Pure data persistence abstraction:
#![allow(unused)] fn main() { pub trait StorageProvider: Send + Sync { type Error: std::error::Error + Send + Sync + 'static; async fn put(&self, key: StorageKey, data: Value) -> Result<Value, Self::Error>; async fn get(&self, key: StorageKey) -> Result<Option<Value>, Self::Error>; async fn delete(&self, key: StorageKey) -> Result<bool, Self::Error>; async fn list(&self, prefix: StoragePrefix) -> Result<Vec<Value>, Self::Error>; } }
Implementation Options:
- Use
InMemoryStoragefor development and testing - Implement for your database (PostgreSQL, MongoDB, etc.)
- Connect to cloud storage or external APIs
Value Objects
Type-safe SCIM attribute handling:
#![allow(unused)] fn main() { pub trait ValueObject: Debug + Send + Sync { fn attribute_type(&self) -> AttributeType; fn to_json(&self) -> ValidationResult<Value>; fn validate_against_schema(&self, definition: &AttributeDefinition) -> ValidationResult<()>; // ... } pub trait SchemaConstructible: ValueObject + Sized { fn from_schema_and_value( definition: &AttributeDefinition, value: &Value, ) -> ValidationResult<Self>; // ... } }
Extension Points:
- Create custom value objects for domain-specific attributes
- Implement validation logic for business rules
- Support for complex multi-valued attributes
Multi-Tenant Architecture
The library provides several components for multi-tenant systems:
TenantResolver
Maps authentication credentials to tenant context:
#![allow(unused)] fn main() { pub trait TenantResolver: Send + Sync { type Error: std::error::Error + Send + Sync + 'static; async fn resolve_tenant(&self, credential: &str) -> Result<TenantContext, Self::Error>; } }
RequestContext
Carries tenant and request information through all operations:
#![allow(unused)] fn main() { pub struct RequestContext { pub request_id: String, tenant_context: Option<TenantContext>, } }
Tenant Isolation
- All
ResourceProvideroperations includeRequestContext - Storage keys automatically include tenant ID
- Schema validation respects tenant-specific extensions
Schema System Architecture
SchemaRegistry
Central registry for SCIM schemas:
- Loads and validates RFC 7643 core schemas
- Supports custom schema extensions
- Provides validation services for all operations
Dynamic Value Objects
- Runtime creation from schema definitions
- Type-safe attribute handling
- Extensible factory pattern for custom types
Extension Model
- Custom resource types beyond User/Group
- Organization-specific attributes
- Maintains SCIM compliance and interoperability
Concurrency Control
ETag-Based Versioning
Built into the core architecture:
- Automatic version generation from resource content
- Conditional operations (If-Match, If-None-Match)
- Conflict detection and resolution
- Production-ready optimistic locking
Version-Aware Operations
All resource operations support conditional execution:
#![allow(unused)] fn main() { // Conditional update with version check let result = provider.conditional_update( "User", &user_id, updated_data, &expected_version, &context ).await?; match result { ConditionalResult::Success(resource) => // Update succeeded ConditionalResult::PreconditionFailed => // Version conflict } }
Integration Patterns
Web Framework Integration
Components work with any HTTP framework:
- Extract SCIM request details
- Create
RequestContextwith tenant info - Call appropriate
ScimServeroperations - Format responses per SCIM specification
AI Agent Integration
Model Context Protocol (MCP) components:
- Expose SCIM operations as discoverable tools
- Structured schemas for AI understanding
- Error handling designed for AI decision making
- Multi-tenant aware tool descriptions
Custom Client Integration
Direct component usage:
- Implement
ResourceProviderfor your data model - Choose appropriate
StorageProvider - Configure schema extensions as needed
- Build custom API layer or integration logic
Performance Considerations
Async-First Design
- All I/O operations are async
- Non-blocking concurrent operations
- Efficient resource utilization
Minimal Allocations
- Zero-copy JSON processing where possible
- Efficient value object system
- Smart caching in schema registry
Scalability Features
- Pluggable storage for horizontal scaling
- Multi-tenant isolation for SaaS platforms
- Connection pooling support through storage traits
Understanding SCIM Schemas
SCIM (System for Cross-domain Identity Management) uses a sophisticated schema system to define how identity data is structured, validated, and extended across HTTP REST operations. This chapter explores the schema-centric aspects of SCIM and how they're implemented in the SCIM Server library.
SCIM Protocol Background
SCIM is defined by two key Internet Engineering Task Force (IETF) Request for Comments (RFC) specifications:
- RFC 7643: System for Cross-domain Identity Management (SCIM): Core Schema - Defines the core schema and extension model for representing users and groups, published September 2015
- RFC 7644: System for Cross-domain Identity Management (SCIM): Protocol - Specifies the REST API protocol for provisioning and managing identity data, published September 2015
These RFCs establish SCIM 2.0 as the industry standard for identity provisioning, providing a specification for automated user lifecycle management between identity providers (like Okta, Azure AD) and service providers (applications). The schema system defined in RFC 7643 forms the foundation for all SCIM operations, ensuring consistent data representation while allowing for extensibility to meet specific organizational requirements.
What Are SCIM Schemas?
SCIM schemas define the structure and constraints for identity resources like Users and Groups across HTTP REST operations. They serve multiple purposes:
- Data Structure Definition: Define what attributes a resource can have
- Validation Rules: Specify required fields, data types, and constraints
- HTTP Operation Context: Guide validation and processing for GET, POST, PUT, PATCH, DELETE
- Extensibility Framework: Allow custom attributes while maintaining interoperability
- API Contract: Provide a machine-readable description of resource formats
- Meta Components: Define service provider capabilities and resource types
Schema Structure Progression
SCIM uses a layered approach to schema definition, progressing from meta-schemas to concrete resource schemas.
1. Schema for Schemas (Meta-Schema)
At the foundation is the meta-schema that defines how schemas themselves are structured. This is defined in RFC 7643 Section 7 and includes attributes like:
{
"id": "urn:ietf:params:scim:schemas:core:2.0:Schema",
"name": "Schema",
"description": "Specifies the schema that describes a SCIM schema",
"attributes": [
{
"name": "id",
"type": "string",
"multiValued": false,
"description": "The unique URI of the schema",
"required": true,
"mutability": "readOnly"
}
// ... more meta-attributes
]
}
This meta-schema ensures consistency across all SCIM schema definitions and enables programmatic schema discovery and validation.
2. Core Resource Schemas
SCIM defines two core resource schemas that all compliant implementations must support:
User Schema (urn:ietf:params:scim:schemas:core:2.0:User)
The User schema defines standard attributes for representing people in identity systems:
{
"schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],
"id": "urn:ietf:params:scim:schemas:core:2.0:User",
"name": "User",
"description": "User Account",
"attributes": [
{
"name": "userName",
"type": "string",
"multiValued": false,
"description": "Unique identifier for the User",
"required": true,
"mutability": "readWrite",
"returned": "default",
"uniqueness": "server"
},
{
"name": "name",
"type": "complex",
"multiValued": false,
"description": "The components of the user's real name",
"required": false,
"subAttributes": [
{
"name": "formatted",
"type": "string",
"multiValued": false,
"description": "The full name",
"required": false
},
{
"name": "familyName",
"type": "string",
"multiValued": false,
"description": "The family name",
"required": false
}
// ... more name components
]
}
// ... more user attributes
]
}
Key User Attributes:
userName: Unique identifier (required)name: Complex type with formatted, family, and given namesemails: Multi-valued array of email addressesactive: Boolean indicating account statusgroups: Multi-valued references to group memberships
Group Schema (urn:ietf:params:scim:schemas:core:2.0:Group)
The Group schema defines attributes for representing collections of users:
{
"schemas": ["urn:ietf:params:scim:schemas:core:2.0:Group"],
"id": "urn:ietf:params:scim:schemas:core:2.0:Group",
"name": "Group",
"description": "Group",
"attributes": [
{
"name": "displayName",
"type": "string",
"multiValued": false,
"description": "A human-readable name for the Group",
"required": true,
"mutability": "readWrite"
},
{
"name": "members",
"type": "complex",
"multiValued": true,
"description": "A list of members of the Group",
"required": false,
"subAttributes": [
{
"name": "value",
"type": "string",
"multiValued": false,
"description": "Identifier of the member",
"mutability": "immutable"
},
{
"name": "$ref",
"type": "reference",
"referenceTypes": ["User", "Group"],
"multiValued": false,
"description": "The URI of the member resource"
}
]
}
]
}
Key Group Attributes:
displayName: Human-readable group name (required)members: Multi-valued complex attribute containing user/group references
3. Schema Specialization and Extensions
SCIM's extensibility model allows organizations to add custom attributes while maintaining core compatibility.
Enterprise User Extension
RFC 7643 defines a standard extension for enterprise environments:
{
"schemas": [
"urn:ietf:params:scim:schemas:core:2.0:User",
"urn:ietf:params:scim:schemas:extension:enterprise:2.0:User"
],
"userName": "john.doe",
"emails": [{"value": "john@example.com", "primary": true}],
"urn:ietf:params:scim:schemas:extension:enterprise:2.0:User": {
"employeeNumber": "12345",
"department": "Engineering",
"manager": {
"value": "26118915-6090-4610-87e4-49d8ca9f808d",
"$ref": "../Users/26118915-6090-4610-87e4-49d8ca9f808d",
"displayName": "Jane Smith"
},
"organization": "Acme Corp"
}
}
Custom Schema Extensions
Organizations can define completely custom schemas using proper URN namespacing:
{
"schemas": [
"urn:ietf:params:scim:schemas:core:2.0:User",
"urn:example:params:scim:schemas:extension:acme:2.0:User"
],
"userName": "alice.engineer",
"urn:example:params:scim:schemas:extension:acme:2.0:User": {
"securityClearance": "SECRET",
"projectAssignments": [
{
"projectId": "PROJ-001",
"role": "Lead Developer",
"startDate": "2024-01-15"
}
],
"skills": ["rust", "scim", "identity-management"]
}
}
Schema Processing in SCIM Operations
SCIM schemas drive all protocol operations, providing structure and validation rules that ensure consistent data handling across different identity providers and service providers.
HTTP REST Operations and Schema Processing
SCIM schemas are deeply integrated with HTTP REST operations. Each SCIM command has specific schema processing requirements:
Schema-Aware HTTP Operations
GET Operations - Schema-Driven Response Formation
// GET /Users/{id} - Schema determines response structure
let user = provider.get_resource("User", &user_id, &context).await?;
// Schema controls:
// - Which attributes are returned by default
// - Attribute mutability affects response inclusion
// - Extension schemas determine namespace organization
// - "returned" attribute property: "always", "never", "default", "request"
{
"schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],
"id": "2819c223-7f76-453a-919d-413861904646",
"userName": "bjensen@example.com", // returned: "default"
"meta": { // Always included per spec
"resourceType": "User",
"created": "2010-01-23T04:56:22Z",
"lastModified": "2011-05-13T04:42:34Z",
"version": "W/\"3694e05e9dff591\"",
"location": "https://example.com/v2/Users/2819c223..."
}
}
POST Operations - Schema Validation on Creation
// POST /Users - Complete resource creation with schema validation
let create_request = json!({
"schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],
"userName": "newuser@example.com", // Required per schema
"emails": [{"value": "newuser@example.com", "primary": true}]
});
// Schema validation includes:
// - Required attribute presence check
// - Data type validation
// - Uniqueness constraint enforcement
// - Mutability rules ("readOnly" attributes rejected)
// - Extension schema validation
let user = provider.create_resource("User", create_request, &context).await?;
PUT Operations - Complete Resource Replacement
// PUT /Users/{id} - Schema ensures complete resource validity
let replacement_data = json!({
"schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],
"userName": "bjensen@example.com", // Must include all required fields
"emails": [{"value": "bjensen@newdomain.com", "primary": true}],
"active": true
});
// Schema processing for PUT:
// - Validates complete resource structure
// - Ensures all required attributes present
// - Respects "immutable" and "readOnly" constraints
// - Processes all registered extension schemas
PATCH Operations - Partial Updates with Schema Context
use scim_server::patch::{PatchOperation, PatchOp};
// PATCH /Users/{id} - Schema-aware partial modifications
let patch_ops = vec![
PatchOperation {
op: PatchOp::Replace,
path: Some("emails[primary eq true].value".to_string()),
value: Some(json!("newemail@example.com")),
},
PatchOperation {
op: PatchOp::Add,
path: Some("urn:ietf:params:scim:schemas:extension:enterprise:2.0:User:department".to_string()),
value: Some(json!("Engineering")),
}
];
// Schema validation for PATCH:
// - Path expression validation against schema structure
// - Target attribute mutability checking
// - Extension schema awareness for namespaced paths
// - Multi-valued attribute handling per schema rules
DELETE Operations - Schema-Informed Cleanup
// DELETE /Users/{id} - Schema guides deletion processing
// Schema-informed deletion:
// - Validates deletion permissions based on mutability constraints
// - Processes extension schema cleanup requirements
// - Determines soft delete vs hard delete approach
SCIM Meta Components and Schema Integration
SCIM defines several meta-schemas that describe the service provider's capabilities and resource structures:
Service Provider Configuration Schema
The ServiceProviderConfig resource describes server capabilities:
{
"schemas": ["urn:ietf:params:scim:schemas:core:2.0:ServiceProviderConfig"],
"documentationUri": "https://example.com/help/scim.html",
"patch": {
"supported": true
},
"bulk": {
"supported": true,
"maxOperations": 1000,
"maxPayloadSize": 1048576
},
"filter": {
"supported": true,
"maxResults": 200
},
"changePassword": {
"supported": false
},
"sort": {
"supported": true
},
"etag": {
"supported": true
},
"authenticationSchemes": [
{
"type": "oauthbearertoken",
"name": "OAuth Bearer Token",
"description": "Authentication scheme using the OAuth Bearer Token",
"specUri": "http://www.rfc-editor.org/info/rfc6750",
"documentationUri": "https://example.com/help/oauth.html"
}
]
}
Resource Type Meta-Schema
Resource types describe available SCIM resources and their schemas:
// GET /ResourceTypes/User returns:
{
"schemas": ["urn:ietf:params:scim:schemas:core:2.0:ResourceType"],
"id": "User",
"name": "User",
"endpoint": "/Users",
"description": "User Account",
"schema": "urn:ietf:params:scim:schemas:core:2.0:User",
"schemaExtensions": [
{
"schema": "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User",
"required": false
},
{
"schema": "urn:example:params:scim:schemas:extension:acme:2.0:User",
"required": true
}
],
"meta": {
"location": "https://example.com/v2/ResourceTypes/User",
"resourceType": "ResourceType"
}
}
Schema Meta-Attributes
Every SCIM resource includes meta-attributes that support HTTP operations:
{
"schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],
"id": "2819c223-7f76-453a-919d-413861904646",
"userName": "bjensen@example.com",
"meta": {
"resourceType": "User", // Schema-derived type
"created": "2010-01-23T04:56:22Z", // Creation timestamp
"lastModified": "2011-05-13T04:42:34Z", // Modification tracking
"location": "https://example.com/v2/Users/2819c223-7f76-453a-919d-413861904646",
"version": "W/\"3694e05e9dff591\"" // ETag for concurrency control
}
}
// Meta attributes enable:
// - HTTP caching with ETags
// - Conditional operations (If-Match, If-None-Match)
// - Audit trail capabilities
// - Resource location for HATEOAS compliance
Schema Processing in SCIM Server Implementation
The SCIM Server library integrates schema processing throughout the HTTP request lifecycle:
Request Processing Pipeline
use scim_server::{ScimServer, RequestContext};
let server = ScimServer::new(provider)?;
// 1. HTTP Request → Schema Identification
let schemas = extract_schemas_from_request(&request_body)?;
// 2. Schema Validation → Resource Processing
let validation_context = ValidationContext {
schemas: &schemas,
operation: HttpOperation::Post,
resource_type: "User",
};
// 3. Operation Execution with Schema Constraints
let result = match request.method() {
"GET" => server.get_with_schema_filtering(&resource_type, &id, &query_params, &context).await?,
"POST" => server.create_with_schema_validation(&resource_type, &request_body, &context).await?,
"PUT" => server.replace_with_schema_validation(&resource_type, &id, &request_body, &context).await?,
"PATCH" => server.patch_with_schema_awareness(&resource_type, &id, &patch_ops, &context).await?,
"DELETE" => server.delete_with_schema_cleanup(&resource_type, &id, &context).await?,
};
Schema-Driven Query Processing
SCIM query parameters interact directly with schema definitions:
GET /Users?attributes=userName,emails&filter=active eq true
Schema processing for queries:
- Validates attribute names against schema definitions
- Handles extension schema attributes in projections
- Enforces "returned" attribute constraints
- Processes complex attribute path expressions
- Validates filter expressions against attribute types
Auto Schema Discovery
SCIM Server provides automatic schema discovery capabilities that integrate with the SCIM protocol's introspection endpoints:
Schema Endpoint Implementation
SCIM servers provide schema introspection endpoints:
GET /Schemasreturns all registered schemasGET /Schemas/{schema_id}returns specific schema details- Enables automatic schema discovery for clients and tools
Resource Type Discovery
SCIM servers support resource type introspection as defined in RFC 7644:
GET /ResourceTypes returns supported resource types, including:
- Resource endpoint paths
- Associated schema URNs
- Available schema extensions
- Extension requirement status
Dynamic Data Validation
The schema system enables sophisticated validation that goes beyond simple type checking:
Multi-Level Validation
SCIM validation occurs at multiple levels:
- HTTP Method Validation: Operation-specific constraints
- Syntax Validation: JSON structure and basic type checking
- Schema Validation: Compliance with schema definitions
- Business Rule Validation: Custom validation logic
The validation process ensures that data conforms to schema requirements before processing, returning appropriate HTTP status codes for different error types.
Operation-Specific Validation
Each HTTP operation has specific validation requirements based on schema attribute properties:
- POST (Create): All required attributes must be present
- PUT (Replace): Complete resource validation, immutable attributes cannot change
- PATCH (Update): Path validation, readOnly attributes cannot be targeted
- GET (Read): Response filtering based on "returned" attribute property
HTTP Status Code Mapping
Schema validation errors map to specific HTTP status codes:
- 400 Bad Request: Invalid values, missing required attributes, mutability violations
- 409 Conflict: Uniqueness constraint violations
- 412 Precondition Failed: ETag version mismatches
Working with Standard Data Definitions
SCIM defines standard data formats and constraints that the library enforces:
Attribute Types and Constraints
| Type | Description | Validation Rules |
|---|---|---|
string | Text data | Length limits, case sensitivity, uniqueness |
boolean | True/false values | Must be valid JSON boolean |
decimal | Numeric data | Precision and scale constraints |
integer | Whole numbers | Range validation |
dateTime | ISO 8601 timestamps | Format and timezone validation |
binary | Base64-encoded data | Encoding validation |
reference | Resource references | Referential integrity checks |
complex | Nested objects | Sub-attribute validation |
Multi-Valued Attributes
SCIM supports multi-valued attributes with sophisticated handling:
{
"emails": [
{
"value": "primary@example.com",
"type": "work",
"primary": true
},
{
"value": "secondary@example.com",
"type": "personal",
"primary": false
}
]
}
Multi-Value Rules:
- At most one
primaryvalue allowed - Type values from canonical list (if specified)
- Duplicate detection and handling
- Order preservation for client expectations
Reference Attributes
References to other SCIM resources are handled with full integrity checking:
{
"groups": [
{
"value": "e9e30dba-f08f-4109-8486-d5c6a331660a",
"$ref": "https://example.com/scim/v2/Groups/e9e30dba-f08f-4109-8486-d5c6a331660a",
"display": "Administrators"
}
]
}
// The library validates:
// - Reference type matches schema constraints
// - Tenant isolation for multi-tenant systems
HTTP Content Negotiation and Schema Processing
SCIM servers use HTTP headers to negotiate schema processing:
Content-Type and Schema Validation
SCIM requests must include proper Content-Type headers and schema declarations:
POST /Users HTTP/1.1
Content-Type: application/scim+json
{
"schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],
"userName": "newuser@example.com"
}
Servers validate:
- Content-Type header matches SCIM specification (
application/scim+json) - schemas array matches Content-Type expectations
- Resource structure conforms to declared schemas
ETag and Schema Versioning
The SCIM protocol uses ETags (entity tags) for optimistic concurrency control, preventing lost updates when multiple clients modify the same resource. Each SCIM resource includes a meta.version field containing an ETag value that changes whenever the resource is modified. Clients use HTTP conditional headers (If-Match, If-None-Match) with these ETags to ensure they're operating on the expected version of a resource.
For implementation details and practical usage patterns, see the ETag Concurrency Control chapter and Schema Mechanisms in SCIM Server.
Schema Extensibility Patterns
The SCIM Server supports several patterns for extending schemas while maintaining interoperability:
Additive Extensions
Add new attributes without modifying core schemas:
// Core user data remains unchanged
{
"schemas": [
"urn:ietf:params:scim:schemas:core:2.0:User",
"urn:example:params:scim:schemas:extension:acme:2.0:User"
],
"userName": "alice.engineer",
"emails": [{"value": "alice@acme.com", "primary": true}],
// Extension data in separate namespace
"urn:example:params:scim:schemas:extension:acme:2.0:User": {
"department": "R&D",
"clearanceLevel": "SECRET",
"projects": ["moonshot", "widget-2.0"]
}
}
Schema Composition
Combine multiple extensions for complex scenarios:
{
"schemas": [
"urn:ietf:params:scim:schemas:core:2.0:User",
"urn:ietf:params:scim:schemas:extension:enterprise:2.0:User",
"urn:example:params:scim:schemas:extension:security:2.0:User",
"urn:example:params:scim:schemas:extension:hr:2.0:User"
],
"userName": "bob.manager",
// Each extension provides its own attributes
"urn:ietf:params:scim:schemas:extension:enterprise:2.0:User": {
"employeeNumber": "E12345"
},
"urn:example:params:scim:schemas:extension:security:2.0:User": {
"lastSecurityReview": "2024-01-15T10:30:00Z"
},
"urn:example:params:scim:schemas:extension:hr:2.0:User": {
"performanceRating": "exceeds-expectations"
}
}
Best Practices for Schema Design
When designing custom schemas for use with SCIM Server:
1. Follow Naming Conventions
- Use proper URN namespacing:
urn:example:params:scim:schemas:extension:company:version:Type - Choose descriptive attribute names that clearly indicate purpose
- Use camelCase for attribute names to match SCIM conventions
2. Design for Interoperability
- Minimize custom types - prefer standard SCIM types when possible
- Document extensions clearly for integration partners
- Provide sensible defaults and make attributes optional when appropriate
3. Consider Performance Implications
- Avoid deeply nested complex attributes that are expensive to validate
- Use appropriate uniqueness constraints to leverage database indexes
- Consider query patterns when designing multi-valued attributes
4. Plan for Evolution
- Design extensible schemas that can accommodate future requirements
- Use semantic versioning for schema URNs
- Maintain backwards compatibility when modifying existing schemas
Integration with AI Systems
The SCIM Server's schema system is designed to work seamlessly with AI agents through the Model Context Protocol (MCP):
Schema-Aware AI Tools
SCIM schemas enable AI integration by providing structured descriptions of available operations and data formats. AI systems can discover schema capabilities and generate compliant requests automatically.
Schema information that benefits AI systems includes:
- Required and optional attributes for each resource type
- Validation rules and data format constraints
- Available HTTP operations and their requirements
- Extension schemas and custom attribute definitions
For implementation details, see Schema Mechanisms in SCIM Server and the AI Integration Guide.
Conclusion
Conclusion
SCIM schemas provide a powerful foundation for identity data management that balances standardization with extensibility across HTTP REST operations. Understanding these protocol concepts enables you to:
- Design compliant SCIM resources that work with enterprise identity providers
- Implement proper validation across all HTTP operations
- Create extensible systems using schema extension mechanisms
- Build interoperable solutions that follow RFC specifications
- Support diverse client requirements through schema discovery
Key takeaways include:
- Schema Structure: Schemas define both data structure and operational behavior
- HTTP Integration: Each REST operation has specific schema processing requirements
- Extensibility: Extension schemas enable customization while maintaining compatibility
- Validation: Multi-layered validation ensures data integrity and compliance
- Discovery: Schema endpoints enable dynamic client capabilities
For practical implementation of these concepts using the SCIM Server library, see Schema Mechanisms in SCIM Server.
The next chapter will explore hands-on implementation patterns and real-world usage scenarios.
Schema Mechanisms in SCIM Server
This chapter explores how the SCIM Server library implements the schema concepts defined in the SCIM protocol. While Understanding SCIM Schemas covers the protocol specifications, this chapter focuses on the conceptual mechanisms that make schema processing practical and type-safe in Rust applications.
The SCIM Server library transforms the abstract schema definitions from RFC 7643 into concrete, composable components that provide compile-time safety, runtime validation, and seamless integration with Rust's type system.
Schema Registry
The Schema Registry serves as the central schema management system within SCIM Server. It acts as a knowledge base that holds all schema definitions and provides validation services throughout the request lifecycle.
Core Concept: Rather than parsing schemas repeatedly or maintaining scattered validation logic, the Schema Registry centralizes all schema knowledge in a single, queryable component. It comes pre-loaded with RFC 7643 core schemas (User, Group, Enterprise User extension) and supports dynamic registration of custom schemas at runtime.
The registry operates as a validation oracle—when any component needs to understand attribute constraints, validate data structures, or determine response formatting, it queries the registry. This creates a single source of truth for schema behavior across the entire system.
Integration Points: The registry integrates with every major operation—resource creation validates against registered schemas, query processing checks attribute names, and response formatting respects schema-defined visibility rules.
For detailed usage examples and API reference, see the Schema Registry Guide.
Value Objects
Value Objects provide compile-time type safety for SCIM attributes by wrapping primitive values in domain-specific types. This mechanism prevents common errors like assigning invalid email addresses or constructing malformed names.
Core Concept: Instead of working with raw JSON values that can contain any data, Value Objects create typed wrappers that enforce validation at construction time. An Email value object can only be created with a valid email string, and a UserName can only contain characters that meet SCIM requirements.
This approach leverages Rust's ownership system to make invalid states unrepresentable. Once you have a DisplayName value object, you know it contains valid display name data—no runtime checks needed. The type system becomes your validation mechanism.
Schema Integration: Value objects understand their corresponding schema definitions. They know their attribute type, validation rules, and serialization requirements. When converting to JSON for API responses, they automatically apply schema-defined formatting and constraints.
Extensibility: The value object system supports both pre-built types for common SCIM attributes and custom value objects for organization-specific extensions. The factory pattern allows dynamic creation while maintaining type safety.
For implementation details and custom value object creation, see the Value Objects Guide.
Dynamic Schema Construction
Dynamic Schema Construction addresses the challenge of working with schemas that are not known at compile time—such as tenant-specific extensions or runtime-configured resource types.
Core Concept: While value objects provide compile-time safety for known schemas, dynamic construction enables runtime flexibility for unknown or variable schemas. The system can examine a schema definition at runtime and create appropriate value objects and validation logic on demand.
This mechanism uses a factory pattern where schema definitions drive object creation. Given a schema's attribute definition and a JSON value, the system can construct the appropriate typed representation without prior knowledge of the specific schema structure.
Schema-Driven Behavior: The construction process respects all schema constraints—required attributes, data types, multi-valued rules, and custom validation logic. The resulting objects behave identically to compile-time created value objects, maintaining consistency across static and dynamic scenarios.
Use Cases: This enables multi-tenant systems where each tenant may have custom schemas, AI integration where schemas are discovered at runtime, and administrative tools that work with arbitrary SCIM resource types.
For advanced usage patterns and performance considerations, see the Dynamic Construction Guide.
Validation Pipeline
The Validation Pipeline orchestrates multi-layered validation that progresses from basic syntax checking to complex business rule enforcement. This mechanism ensures that only valid, schema-compliant data enters your system.
Core Concept: Rather than ad-hoc validation scattered throughout the codebase, the pipeline provides a structured, configurable validation process. Each layer builds on the previous one—syntax validation ensures basic JSON correctness, schema validation checks SCIM compliance, and business validation enforces organizational rules.
The pipeline integrates with HTTP operations, applying operation-specific validation rules. A POST request validates required attributes, while a PATCH request validates path expressions and mutability constraints.
Validation Context: The pipeline operates within a context that includes the target schema, HTTP operation type, tenant information, and existing resource state. This context enables sophisticated validation logic that considers the complete request environment.
Error Handling: Validation failures produce structured errors with appropriate HTTP status codes and detailed messages. The pipeline can collect multiple errors in a single pass, providing comprehensive feedback rather than stopping at the first issue.
For error handling strategies and custom validation rules, see the Validation Guide.
Auto Schema Discovery
Auto Schema Discovery provides SCIM-compliant endpoints that expose available schemas and resource types to clients and tools. This mechanism enables runtime introspection of server capabilities.
Core Concept: The discovery system automatically generates schema and resource type information from the registered schemas in the Schema Registry. Clients can query /Schemas and /ResourceTypes endpoints to understand what resources are available and how they're structured.
This creates a self-documenting API where tools and AI agents can discover capabilities dynamically rather than requiring pre-configured knowledge of the server's schema support.
Standards Compliance: The discovery endpoints conform to RFC 7644 specifications, ensuring compatibility with standard SCIM clients and identity providers. The generated responses include all required metadata for proper client integration.
For endpoint configuration and custom resource type registration, see the REST API Guide.
AI Integration
AI Integration makes SCIM operations accessible to artificial intelligence agents through structured, schema-aware tool descriptions. This mechanism transforms SCIM Server capabilities into AI-consumable formats.
Core Concept: The integration generates Model Context Protocol (MCP) tool descriptions that include schema constraints, validation rules, and example usage patterns. AI agents receive structured information about what operations are available and how to use them correctly.
Schema awareness ensures that AI tools understand not just the API surface but the data validation requirements, making them more likely to generate valid requests and handle errors appropriately.
Dynamic Capabilities: The AI integration reflects the current server configuration, including custom schemas and tenant-specific extensions. As schemas are added or modified, the AI tools automatically update to reflect new capabilities.
For AI agent configuration and custom tool creation, see the AI Integration Guide.
Component Relationships
These mechanisms work together to create a cohesive schema processing system:
- Schema Registry provides the authoritative schema definitions
- Value Objects implement type-safe attribute handling based on registry schemas
- Dynamic Construction creates value objects from registry definitions at runtime
- Validation Pipeline uses registry schemas to enforce compliance
- Auto Discovery exposes registry contents through SCIM endpoints
- AI Integration translates registry capabilities into agent-readable formats
This architecture ensures that schema knowledge flows consistently throughout the system, from initial registration through final API responses.
Extensibility and Customization
Each mechanism supports extension while maintaining SCIM compliance:
- Custom Schemas integrate seamlessly with the registry system
- Domain-Specific Value Objects extend the type safety model
- Business Validation Rules plug into the validation pipeline
- Tenant-Specific Behavior works across all mechanisms
- Custom AI Tools can be generated from schema definitions
The key principle is additive customization—you extend capabilities without modifying core behavior, ensuring that standard SCIM operations continue to work while supporting organization-specific requirements.
Production Considerations
These mechanisms are designed for production deployment:
- Performance: Schema processing is optimized for minimal runtime overhead
- Memory Efficiency: Schema definitions are shared across requests and tenants
- Thread Safety: All mechanisms support concurrent access without locking
- Error Recovery: Validation failures don't impact server stability
- Observability: Schema processing integrates with structured logging
For deployment and monitoring guidance, see the Production Deployment Guide.
Next Steps
Understanding these schema mechanisms prepares you for implementing SCIM Server in your applications:
- Getting Started: Begin with the First SCIM Server tutorial
- Implementation: Explore How-To Guides for specific scenarios
- Advanced Usage: Review Advanced Topics for complex deployments
- API Reference: Consult API Documentation for detailed interfaces
These conceptual mechanisms become practical tools through hands-on implementation and real-world usage patterns.