scim-server 0.5.3

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
//! Group MCP Operations Test Example
//!
//! This example demonstrates the newly added Group operations in the SCIM MCP server.
//! It shows how AI agents can manage groups through the MCP protocol with full CRUD
//! operations and query capabilities.

#[cfg(feature = "mcp")]
use scim_server::{
    ScimServer,
    mcp_integration::{McpServerInfo, ScimMcpServer},
    multi_tenant::ScimOperation,
    providers::StandardResourceProvider,
    resource_handlers::{create_group_resource_handler, 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::Builder::from_env(env_logger::Env::default().default_filter_or("info"))
        .format_timestamp_secs()
        .init();

    println!("๐Ÿš€ Group MCP Operations Test");
    println!("============================\n");

    // 1. Create SCIM server with both User and Group support
    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,
            ScimOperation::List,
            ScimOperation::Search,
        ],
    )?;

    // Register Group resource type
    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,
            ],
        )?;
        println!("โœ… Registered Group resource type");
    }

    // 2. Create MCP server
    let server_info = McpServerInfo {
        name: "SCIM Group Test Server".to_string(),
        version: "1.0.0".to_string(),
        description: "Testing Group operations in MCP integration".to_string(),
        supported_resource_types: scim_server
            .get_supported_resource_types()
            .into_iter()
            .map(|s| s.to_string())
            .collect(),
    };

    let mcp_server = ScimMcpServer::with_info(scim_server, server_info);

    // 3. First, create some users to add to groups
    println!("๐Ÿ‘ฅ Creating test users...");

    let alice_result = mcp_server
        .execute_tool(
            "scim_create_user",
            json!({
                "user_data": {
                    "schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],
                    "userName": "alice@company.com",
                    "name": {
                        "givenName": "Alice",
                        "familyName": "Smith"
                    },
                    "active": true
                }
            }),
        )
        .await;

    let alice_id = if alice_result.success {
        alice_result.metadata.unwrap()["resource_id"].as_str().unwrap().to_string()
    } else {
        panic!("Failed to create Alice user");
    };

    let bob_result = mcp_server
        .execute_tool(
            "scim_create_user",
            json!({
                "user_data": {
                    "schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],
                    "userName": "bob@company.com",
                    "name": {
                        "givenName": "Bob",
                        "familyName": "Johnson"
                    },
                    "active": true
                }
            }),
        )
        .await;

    let bob_id = if bob_result.success {
        bob_result.metadata.unwrap()["resource_id"].as_str().unwrap().to_string()
    } else {
        panic!("Failed to create Bob user");
    };

    println!("   โœ… Created users Alice and Bob\n");

    // 4. Test Group CRUD operations
    println!("๐Ÿ“ Testing Group CRUD operations:");
    println!("=================================");

    // Create a group
    println!("1. Creating a new group...");
    let create_group_result = mcp_server
        .execute_tool(
            "scim_create_group",
            json!({
                "group_data": {
                    "schemas": ["urn:ietf:params:scim:schemas:core:2.0:Group"],
                    "displayName": "Engineering Team",
                    "members": [
                        {
                            "value": alice_id,
                            "$ref": format!("https://example.com/v2/Users/{}", alice_id),
                            "type": "User"
                        },
                        {
                            "value": bob_id,
                            "$ref": format!("https://example.com/v2/Users/{}", bob_id),
                            "type": "User"
                        }
                    ],
                    "externalId": "eng-team-001"
                }
            }),
        )
        .await;

    let group_id = if create_group_result.success {
        let group_id = create_group_result.metadata.as_ref().unwrap()["resource_id"]
            .as_str()
            .unwrap()
            .to_string();
        println!("   โœ… Group created successfully with ID: {}", group_id);
        group_id
    } else {
        println!("   โŒ Group creation failed: {:?}", create_group_result.content);
        return Ok(());
    };

    // Get the group
    println!("\n2. Retrieving the group...");
    let get_group_result = mcp_server
        .execute_tool(
            "scim_get_group",
            json!({
                "group_id": group_id
            }),
        )
        .await;

    if get_group_result.success {
        println!("   โœ… Group retrieved successfully");
        let group_data = &get_group_result.content;
        println!("   ๐Ÿ“‹ Group name: {}",
            group_data.get("displayName").and_then(|d| d.as_str()).unwrap_or("Unknown"));
        println!("   ๐Ÿ‘ฅ Members count: {}",
            group_data.get("members").and_then(|m| m.as_array()).map(|a| a.len()).unwrap_or(0));

        // Verify no _version field exists in content (standardized approach)
        if group_data.get("_version").is_some() {
            println!("   WARNING: _version field found in content - this should not exist");
        }
    } else {
        println!("   โŒ Group retrieval failed: {:?}", get_group_result.content);
    }

    // Update the group
    println!("\n3. Updating the group...");
    let update_group_result = mcp_server
        .execute_tool(
            "scim_update_group",
            json!({
                "group_id": group_id,
                "group_data": {
                    "id": group_id,
                    "schemas": ["urn:ietf:params:scim:schemas:core:2.0:Group"],
                    "displayName": "Senior Engineering Team",
                    "members": [
                        {
                            "value": alice_id,
                            "$ref": format!("https://example.com/v2/Users/{}", alice_id),
                            "type": "User"
                        }
                    ],
                    "externalId": "senior-eng-team-001"
                }
            }),
        )
        .await;

    if update_group_result.success {
        println!("   โœ… Group updated successfully");
        println!("   ๐Ÿ“ Updated name and removed Bob from members");
    } else {
        println!("   โŒ Group update failed: {:?}", update_group_result.content);
    }

    // 5. Test Group query operations
    println!("\n๐Ÿ” Testing Group query operations:");
    println!("==================================");

    // Create a second group for better testing
    let create_group2_result = mcp_server
        .execute_tool(
            "scim_create_group",
            json!({
                "group_data": {
                    "schemas": ["urn:ietf:params:scim:schemas:core:2.0:Group"],
                    "displayName": "Marketing Team",
                    "members": [
                        {
                            "value": bob_id,
                            "$ref": format!("https://example.com/v2/Users/{}", bob_id),
                            "type": "User"
                        }
                    ],
                    "externalId": "marketing-001"
                }
            }),
        )
        .await;

    let group2_id = if create_group2_result.success {
        create_group2_result.metadata.as_ref().unwrap()["resource_id"]
            .as_str()
            .unwrap()
            .to_string()
    } else {
        println!("Failed to create second group");
        return Ok(());
    };

    // List all groups
    println!("\n1. Listing all groups...");
    let list_groups_result = mcp_server.execute_tool("scim_list_groups", json!({})).await;

    if list_groups_result.success {
        let empty_vec = vec![];
        let groups = list_groups_result.content
            .get("Resources")
            .and_then(|r| r.as_array())
            .unwrap_or(&empty_vec);
        println!("   โœ… Groups list retrieved");
        println!("   ๐Ÿ“Š Total groups: {}", groups.len());
        for group in groups {
            if let Some(name) = group.get("displayName").and_then(|n| n.as_str()) {
                println!("      โ€ข {}", name);
            }
        }
    } else {
        println!("   โŒ Groups listing failed: {:?}", list_groups_result.content);
    }

    // Search for groups
    println!("\n2. Searching for groups by displayName...");
    let search_groups_result = mcp_server
        .execute_tool(
            "scim_search_groups",
            json!({
                "attribute": "displayName",
                "value": "Marketing Team"
            }),
        )
        .await;

    if search_groups_result.success {
        let empty_vec = vec![];
        let found_groups = search_groups_result.content
            .get("Resources")
            .and_then(|r| r.as_array())
            .unwrap_or(&empty_vec);
        println!("   โœ… Group search completed");
        println!("   ๐Ÿ” Found {} matching groups", found_groups.len());
    } else {
        println!("   โŒ Group search failed: {:?}", search_groups_result.content);
    }

    // Check if group exists
    println!("\n3. Checking if group exists...");
    let group_exists_result = mcp_server
        .execute_tool(
            "scim_group_exists",
            json!({
                "group_id": group_id
            }),
        )
        .await;

    if group_exists_result.success {
        let exists = group_exists_result.content
            .get("exists")
            .and_then(|e| e.as_bool())
            .unwrap_or(false);
        println!("   โœ… Group existence check: {}", if exists { "EXISTS" } else { "NOT FOUND" });
    } else {
        println!("   โŒ Group existence check failed: {:?}", group_exists_result.content);
    }

    // 6. Test multi-tenant operations
    println!("\n๐Ÿข Testing multi-tenant Group operations:");
    println!("=========================================");

    let tenant_group_result = mcp_server
        .execute_tool(
            "scim_create_group",
            json!({
                "group_data": {
                    "schemas": ["urn:ietf:params:scim:schemas:core:2.0:Group"],
                    "displayName": "Tenant A Admin Group",
                    "externalId": "tenant-a-admins"
                },
                "tenant_id": "tenant-a"
            }),
        )
        .await;

    if tenant_group_result.success {
        println!("   โœ… Tenant-specific group created");
        if let Some(metadata) = tenant_group_result.metadata {
            if let Some(tenant_id) = metadata.get("tenant_id") {
                println!("   ๐Ÿข Tenant context preserved: {}", tenant_id);
            }
        }
    } else {
        println!("   โŒ Tenant-specific group creation failed");
    }

    // 7. Test error handling
    println!("\nโš ๏ธ  Testing Group error handling:");
    println!("=================================");

    // Try to get non-existent group
    let error_test_result = mcp_server
        .execute_tool(
            "scim_get_group",
            json!({
                "group_id": "non-existent-group-id"
            }),
        )
        .await;

    if !error_test_result.success {
        println!("   โœ… Error handling working correctly for non-existent groups");
        let error_code = error_test_result.content
            .get("error_code")
            .and_then(|e| e.as_str())
            .unwrap_or("UNKNOWN");
        println!("   ๐Ÿ“ Error code: {}", error_code);
    }

    // 8. Cleanup
    println!("\n๐Ÿงน Cleaning up test data:");
    println!("=========================");

    // Delete groups
    for (name, id) in [("Engineering Group", &group_id), ("Marketing Group", &group2_id)] {
        let delete_result = mcp_server
            .execute_tool(
                "scim_delete_group",
                json!({
                    "group_id": id
                }),
            )
            .await;

        if delete_result.success {
            println!("   โœ… {} deleted", name);
        } else {
            println!("   โŒ Failed to delete {}", name);
        }
    }

    // Delete users
    for (name, id) in [("Alice", &alice_id), ("Bob", &bob_id)] {
        let delete_result = mcp_server
            .execute_tool(
                "scim_delete_user",
                json!({
                    "user_id": id
                }),
            )
            .await;

        if delete_result.success {
            println!("   โœ… User {} deleted", name);
        } else {
            println!("   โŒ Failed to delete user {}", name);
        }
    }

    // 9. Final verification
    println!("\n๐ŸŽ‰ Group MCP Operations Test Complete!");
    println!("======================================");

    let final_tools = mcp_server.get_tools();
    let group_tools: Vec<_> = final_tools
        .iter()
        .filter(|tool| tool.get("name")
            .and_then(|n| n.as_str())
            .map_or(false, |name| name.contains("group")))
        .collect();

    println!("โœ… Group operations successfully integrated into MCP server");
    println!("โœ… Total Group tools available: {}", group_tools.len());
    println!("โœ… All CRUD operations tested and working");
    println!("โœ… Query operations tested and working");
    println!("โœ… Multi-tenant support verified");
    println!("โœ… Error handling confirmed");

    println!("\n๐Ÿ“‹ Available Group Tools:");
    for tool in group_tools {
        if let Some(name) = tool.get("name").and_then(|n| n.as_str()) {
            if let Some(desc) = tool.get("description").and_then(|d| d.as_str()) {
                println!("  โ€ข {} - {}", name, desc);
            }
        }
    }

    println!("\n๐Ÿš€ Group MCP Integration Ready for Production!");

    Ok(())
}

#[cfg(not(feature = "mcp"))]
fn main() {
    eprintln!("This example requires the 'mcp' feature to be enabled.");
    eprintln!("Please run with: cargo run --example test_group_mcp --features mcp");
    std::process::exit(1);
}