scim-server 0.4.0

A comprehensive SCIM 2.0 server library for Rust with multi-tenant support and type-safe operations
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
//! MCP Version-Based Concurrency Control Example
//!
//! This example demonstrates how AI agents can use raw version strings through the
//! Model Context Protocol (MCP) integration to perform safe concurrent operations
//! on SCIM resources. It shows how versions prevent lost updates and enable proper
//! conflict resolution in AI-driven identity management scenarios.

#[cfg(feature = "mcp")]
use scim_server::{
    ScimServer, mcp_integration::ScimMcpServer, multi_tenant::ScimOperation,
    providers::StandardResourceProvider, resource_handlers::create_user_resource_handler,
    storage::InMemoryStorage,
};
#[cfg(feature = "mcp")]
use serde_json::json;

#[cfg(feature = "mcp")]
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Initialize logging
    env_logger::init();

    println!("🤖 MCP Version-Based Concurrency Control Example");
    println!("===============================================\n");

    // 1. Setup SCIM server with MCP integration
    let storage = InMemoryStorage::new();
    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")
        .expect("User schema should be available")
        .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,
        ],
    )?;

    let mcp_server = ScimMcpServer::new(scim_server);

    println!("✅ MCP server initialized with version support\n");

    // === AVAILABLE MCP TOOLS ===
    println!("🔧 AVAILABLE MCP TOOLS WITH VERSION SUPPORT");
    println!("==========================================");

    let tools = mcp_server.get_tools();
    for tool in &tools {
        let name = tool["name"].as_str().unwrap();
        let description = tool["description"].as_str().unwrap();
        println!("{}: {}", name, description);

        // Show version parameters for update/delete tools
        if name.contains("update") || name.contains("delete") {
            if let Some(expected_version_prop) =
                tool["input_schema"]["properties"]["expected_version"].as_object()
            {
                println!(
                    "  └─ Version parameter: {}",
                    expected_version_prop["description"].as_str().unwrap()
                );
            }
        }
    }

    println!();

    // === AI AGENT USER CREATION ===
    println!("👤 AI AGENT: CREATING NEW USER");
    println!("==============================");

    let create_result = mcp_server
        .execute_tool(
            "scim_create_user",
            json!({
                "user_data": {
                    "schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],
                    "userName": "ai.assistant@company.com",
                    "name": {
                        "familyName": "Assistant",
                        "givenName": "AI",
                        "formatted": "AI Assistant"
                    },
                    "emails": [
                        {
                            "value": "ai.assistant@company.com",
                            "type": "work",
                            "primary": true
                        }
                    ],
                    "active": true
                }
            }),
        )
        .await;

    let (user_id, initial_version) = if create_result.success {
        let user_id = create_result.metadata.as_ref().unwrap()["resource_id"]
            .as_str()
            .unwrap()
            .to_string();
        let version = create_result.metadata.as_ref().unwrap()["version"]
            .as_str()
            .unwrap()
            .to_string();

        println!("✅ AI Agent successfully created user:");
        println!("   User ID: {}", user_id);
        println!("   Initial Version: {}", version);
        println!("   Response includes version for subsequent operations");

        (user_id, version)
    } else {
        panic!("Failed to create user: {:?}", create_result.content);
    };

    println!();

    // === AI AGENT RETRIEVAL WITH VERSION ===
    println!("🔍 AI AGENT: RETRIEVING USER WITH VERSION");
    println!("=========================================");

    let get_result = mcp_server
        .execute_tool(
            "scim_get_user",
            json!({
                "user_id": user_id
            }),
        )
        .await;

    if get_result.success {
        let current_version = get_result.metadata.as_ref().unwrap()["version"]
            .as_str()
            .unwrap();
        println!("✅ AI Agent retrieved user successfully:");
        println!("   Current Version: {}", current_version);
        println!("   User data includes _version field for easy access");

        // Show that version is also embedded in content for easy AI access
        if let Some(embedded_version) = get_result.content["_version"].as_str() {
            println!("   Embedded Version in content: {}", embedded_version);
        }
    }

    println!();

    // === AI AGENT CONDITIONAL UPDATE WITH VERSION ===
    println!("\n🤖 AI AGENT: CONDITIONAL UPDATE WITH VERSION");
    println!("============================================");

    let conditional_update_result = mcp_server
        .execute_tool(
            "scim_update_user",
            json!({
                "user_id": user_id,
                "user_data": {
                    "id": user_id,
                    "schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],
                    "userName": "ai.assistant@company.com",
                    "name": {
                        "familyName": "Assistant",
                        "givenName": "AI",
                        "formatted": "AI Assistant (Updated)"
                    },
                    "emails": [
                        {
                            "value": "ai.assistant@newcompany.com",
                            "type": "work",
                            "primary": true
                        }
                    ],
                    "active": true
                },
                "expected_version": initial_version  // Using raw version from creation
            }),
        )
        .await;

    let _new_version = if conditional_update_result.success {
        let new_version = conditional_update_result.metadata.as_ref().unwrap()["version"]
            .as_str()
            .unwrap()
            .to_string();
        println!("✅ AI Agent conditional update succeeded:");
        println!("   Old Version: {}", initial_version);
        println!("   New Version: {}", new_version);
        println!("   Version-safe update completed");
        new_version
    } else {
        panic!(
            "Conditional update should have succeeded: {:?}",
            conditional_update_result.content
        );
    };

    println!();

    // === AI AGENT CONCURRENT MODIFICATION SIMULATION ===
    // === AI AGENT CONFLICT DETECTION ===
    println!("\n🚨 AI AGENT: SIMULATING VERSION CONFLICT");
    println!("=========================================");

    // Simulate another AI agent trying to update with stale version
    let conflict_update_result = mcp_server
        .execute_tool(
            "scim_update_user",
            json!({
                "user_id": user_id,
                "user_data": {
                    "id": user_id,
                    "schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],
                    "userName": "ai.assistant@company.com",
                    "active": false  // Different change
                },
                "expected_version": initial_version  // Using stale version
            }),
        )
        .await;

    if !conflict_update_result.success {
        println!("✅ AI Agent properly detected version conflict:");
        println!(
            "   Error: {}",
            conflict_update_result.content["error"].as_str().unwrap()
        );
        println!(
            "   Error Code: {}",
            conflict_update_result.content["error_code"]
                .as_str()
                .unwrap()
        );

        let is_version_conflict = conflict_update_result.content["is_version_conflict"]
            .as_bool()
            .unwrap_or(false);
        println!("   Is Version Conflict: {}", is_version_conflict);

        if is_version_conflict {
            println!("   → AI Agent should refresh user data and retry");
        }
    } else {
        panic!("Update should have failed due to version conflict");
    }

    println!();

    // === AI AGENT CONFLICT RESOLUTION ===
    println!("🔄 AI AGENT: CONFLICT RESOLUTION STRATEGY");
    println!("=========================================");

    // Step 1: AI Agent detects conflict and refreshes data
    println!("Step 1: AI Agent refreshes user data after conflict");
    let refresh_result = mcp_server
        .execute_tool(
            "scim_get_user",
            json!({
                "user_id": user_id
            }),
        )
        .await;

    let current_version = if refresh_result.success {
        let current_version = refresh_result.metadata.as_ref().unwrap()["version"]
            .as_str()
            .unwrap()
            .to_string();
        println!("✅ Refreshed user data successfully");
        println!("   Current Version: {}", current_version);
        current_version
    } else {
        panic!("Failed to refresh user data");
    };

    // Step 2: AI Agent retries with current version
    println!("\nStep 2: AI Agent retries update with current version");
    let retry_update_result = mcp_server
        .execute_tool(
            "scim_update_user",
            json!({
                "user_id": user_id,
                "user_data": {
                    "id": user_id,
                    "schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],
                    "userName": "ai.assistant@company.com",
                    "name": {
                        "familyName": "Assistant",
                        "givenName": "AI",
                        "formatted": "AI Assistant (Conflict Resolved)"
                    },
                    "emails": [
                        {
                            "value": "ai.assistant@newcompany.com",
                            "type": "work",
                            "primary": true
                        }
                    ],
                    "active": false  // Applying the change that failed before
                },
                "expected_version": current_version  // Using current version
            }),
        )
        .await;

    let final_version = if retry_update_result.success {
        let final_version = retry_update_result.metadata.as_ref().unwrap()["version"]
            .as_str()
            .unwrap()
            .to_string();
        println!("✅ AI Agent retry succeeded:");
        println!("   Previous Version: {}", current_version);
        println!("   Final Version: {}", final_version);
        println!("   Conflict successfully resolved");
        final_version
    } else {
        panic!(
            "Retry update should have succeeded: {:?}",
            retry_update_result.content
        );
    };

    println!();

    // === AI AGENT CONDITIONAL DELETE ===
    println!("\n🗑️  AI AGENT: CONDITIONAL DELETE WITH VERSION");
    println!("====================================");

    // First try delete with wrong version
    println!("Attempting delete with stale version (should fail):");
    let wrong_delete_result = mcp_server
        .execute_tool(
            "scim_delete_user",
            json!({
                "user_id": user_id,
                "expected_version": initial_version  // Stale version
            }),
        )
        .await;

    if !wrong_delete_result.success {
        println!("✅ AI Agent properly rejected unsafe delete:");
        println!(
            "   Error: {}",
            wrong_delete_result.content["error"].as_str().unwrap()
        );
        let is_version_conflict = wrong_delete_result.content["is_version_conflict"]
            .as_bool()
            .unwrap_or(false);
        println!("   Is Version Conflict: {}", is_version_conflict);
    }

    // Now try delete with correct version
    println!("\nAttempting delete with current version (should succeed):");
    let correct_delete_result = mcp_server
        .execute_tool(
            "scim_delete_user",
            json!({
                "user_id": user_id,
                "expected_version": final_version
            }),
        )
        .await;

    if correct_delete_result.success {
        println!("✅ AI Agent successfully deleted user:");
        println!("   Safe deletion completed with version check");
    } else {
        panic!("Delete with correct ETag should have succeeded");
    }

    println!();

    // === AI AGENT BEST PRACTICES ===
    println!("🎯 AI AGENT BEST PRACTICES FOR VERSION USAGE");
    println!("===========================================");

    println!("1. Always capture version from operation responses:");
    println!("   • Create operations return version in metadata['version']");
    println!("   • Get operations return version in metadata['version']");
    println!("   • Content also includes _version field for convenience");

    println!("\n2. Use raw versions for all update and delete operations:");
    println!("   • Include 'expected_version' parameter with raw version value");
    println!("   • Version format: Simple string like 'abc123def456'");

    println!("\n3. Handle version conflicts gracefully:");
    println!("   • Check 'error_code' for 'VERSION_MISMATCH' in error responses");
    println!("   • Refresh resource data when conflicts occur");
    println!("   • Retry operation with current version");

    println!("\n4. Version format and usage:");
    println!("   • Use raw version strings directly");
    println!("   • Example: 'abc123def456' (no HTTP formatting needed)");
    println!("   • No parsing or modification required - use as-is");

    println!();

    // === MULTI-TENANT AI OPERATIONS ===
    println!("🏢 AI AGENT: MULTI-TENANT OPERATIONS");
    println!("====================================");

    // Create user in specific tenant
    let tenant_create_result = mcp_server
        .execute_tool(
            "scim_create_user",
            json!({
                "user_data": {
                    "schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],
                    "userName": "tenant.ai@enterprise.com",
                    "active": true
                },
                "tenant_id": "enterprise-corp"
            }),
        )
        .await;

    if tenant_create_result.success {
        let tenant_user_id = tenant_create_result.metadata.as_ref().unwrap()["resource_id"]
            .as_str()
            .unwrap();
        let tenant_version = tenant_create_result.metadata.as_ref().unwrap()["version"]
            .as_str()
            .unwrap();

        println!("✅ AI Agent created user in tenant 'enterprise-corp':");
        println!("   User ID: {}", tenant_user_id);
        println!("   Version: {}", tenant_version);

        // Update in same tenant with ETag
        let tenant_update_result = mcp_server
            .execute_tool(
                "scim_update_user",
                json!({
                    "user_id": tenant_user_id,
                    "user_data": {
                        "id": tenant_user_id,
                        "schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],
                        "userName": "tenant.ai@enterprise.com",
                        "active": false
                    },
                    "expected_version": tenant_version,
                    "tenant_id": "enterprise-corp"
                }),
            )
            .await;

        if tenant_update_result.success {
            println!("✅ AI Agent updated tenant user with version successfully");
        }
    }

    println!();

    // === CONCLUSION ===
    println!("🎉 MCP VERSION-BASED CONCURRENCY CONTROL EXAMPLE COMPLETED!");
    println!("==========================================================");
    println!("✅ Demonstrated AI agent version usage patterns");
    println!("✅ Showed version conflict detection and resolution");
    println!("✅ Illustrated safe conditional operations");
    println!("✅ Covered multi-tenant version scenarios");
    println!("✅ Provided AI agent best practices");
    println!();
    println!("🤖 AI INTEGRATION BENEFITS:");
    println!("   • Simple raw version handling in MCP tools");
    println!("   • Clear version conflict indicators");
    println!("   • Embedded versions in response content");
    println!("   • Structured error responses for AI decision making");
    println!("   • Multi-tenant aware versioning");
    println!("   • Zero-configuration optimistic locking");

    Ok(())
}

#[cfg(not(feature = "mcp"))]
fn main() {
    println!("This example requires the 'mcp' feature to be enabled.");
    println!("Run with: cargo run --example mcp_etag_example --features mcp");
}