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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
//! Tests for MCP integration functionality
//!
//! This module contains comprehensive tests for the MCP protocol implementation,
//! including stdio communication, tool discovery, and tool execution.

#[cfg(feature = "mcp")]
mod mcp_tests {
    use super::super::core::{McpServerInfo, ScimMcpServer};
    use crate::{
        multi_tenant::ScimOperation,
        providers::StandardResourceProvider,
        resource_handlers::{create_group_resource_handler, create_user_resource_handler},
        scim_server::{ScimServerBuilder, TenantStrategy},
        storage::InMemoryStorage,
    };
    use serde_json::{Value, json};

    /// Test helper to create a test MCP server
    async fn create_test_mcp_server() -> ScimMcpServer<StandardResourceProvider<InMemoryStorage>> {
        let storage = InMemoryStorage::new();
        let provider = StandardResourceProvider::new(storage);
        let mut scim_server = ScimServerBuilder::new(provider)
            .with_base_url("mcp://scim".to_string())
            .with_tenant_strategy(TenantStrategy::SingleTenant)
            .build()
            .expect("Failed to build SCIM server");

        // Register User resource type
        let user_schema = scim_server
            .get_schema_by_id("urn:ietf:params:scim:schemas:core:2.0:User")
            .expect("Failed to get user schema")
            .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::Search,
                ],
            )
            .expect("Failed to register User resource type");

        // Register Group resource type
        let group_schema = scim_server
            .get_schema_by_id("urn:ietf:params:scim:schemas:core:2.0:Group")
            .expect("Failed to get group schema")
            .clone();
        let group_handler = create_group_resource_handler(group_schema);

        scim_server
            .register_resource_type(
                "Group",
                group_handler,
                vec![
                    ScimOperation::Create,
                    ScimOperation::Read,
                    ScimOperation::Update,
                    ScimOperation::Delete,
                    ScimOperation::Search,
                ],
            )
            .expect("Failed to register Group resource type");

        ScimMcpServer::new(scim_server)
    }

    #[tokio::test]
    async fn test_tool_discovery() {
        let mcp_server = create_test_mcp_server().await;
        let tools = mcp_server.get_tools();

        assert_eq!(tools.len(), 16, "Should have 16 tools available");

        // Verify expected tool names are present
        let tool_names: Vec<&str> = tools
            .iter()
            .map(|tool| tool.get("name").and_then(|n| n.as_str()).unwrap_or(""))
            .collect();

        let expected_tools = vec![
            // User operations
            "scim_create_user",
            "scim_get_user",
            "scim_update_user",
            "scim_delete_user",
            "scim_list_users",
            "scim_search_users",
            "scim_user_exists",
            // Group operations
            "scim_create_group",
            "scim_get_group",
            "scim_update_group",
            "scim_delete_group",
            "scim_list_groups",
            "scim_search_groups",
            "scim_group_exists",
            // System operations
            "scim_get_schemas",
            "scim_server_info",
        ];

        for expected_tool in expected_tools {
            assert!(
                tool_names.contains(&expected_tool),
                "Tool '{}' should be available",
                expected_tool
            );
        }
    }

    #[tokio::test]
    async fn test_tool_execution_create_user() {
        let mcp_server = create_test_mcp_server().await;

        let arguments = json!({
            "user_data": {
                "schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],
                "userName": "test.user@example.com",
                "active": true,
                "name": {
                    "givenName": "Test",
                    "familyName": "User"
                }
            }
        });

        let result = mcp_server.execute_tool("scim_create_user", arguments).await;

        // Debug the result if it fails
        if !result.success {
            println!("Tool execution failed!");
            println!(
                "Content: {}",
                serde_json::to_string_pretty(&result.content).unwrap()
            );
            println!("Metadata: {:?}", result.metadata);
        }

        assert!(
            result.success,
            "Tool execution should succeed. Content: {}",
            result.content
        );
        assert!(result.content.get("id").is_some(), "Should return user ID");
        if let Some(user_name) = result.content.get("userName") {
            assert_eq!(user_name.as_str().unwrap(), "test.user@example.com");
        }
    }

    #[tokio::test]
    async fn test_tool_execution_unknown_tool() {
        let mcp_server = create_test_mcp_server().await;

        let result = mcp_server.execute_tool("unknown_tool", json!({})).await;

        assert!(!result.success, "Unknown tool should fail");
        assert!(
            result.content.get("error").is_some(),
            "Should return error message"
        );
        assert_eq!(
            result.content.get("tool_name").unwrap().as_str().unwrap(),
            "unknown_tool"
        );
    }

    /// Test MCP JSON-RPC message parsing
    #[test]
    fn test_mcp_request_parsing() {
        let initialize_request = r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"test-client","version":"1.0.0"}}}"#;

        let parsed: Value =
            serde_json::from_str(initialize_request).expect("Should parse initialize request");

        assert_eq!(parsed["jsonrpc"], "2.0");
        assert_eq!(parsed["method"], "initialize");
        assert_eq!(parsed["id"], 1);
    }

    /// Test MCP response formatting
    #[test]
    fn test_mcp_response_formatting() {
        let response = json!({
            "jsonrpc": "2.0",
            "id": 1,
            "result": {
                "protocolVersion": "2024-11-05",
                "capabilities": {
                    "tools": {}
                },
                "serverInfo": {
                    "name": "SCIM Server",
                    "version": "2.0"
                }
            }
        });

        let serialized = serde_json::to_string(&response).expect("Should serialize response");

        assert!(serialized.contains("jsonrpc"));
        assert!(serialized.contains("protocolVersion"));
        assert!(serialized.contains("SCIM Server"));
    }

    /// Test stdio communication flow
    #[tokio::test]
    async fn test_stdio_communication_flow() {
        let mcp_server = create_test_mcp_server().await;

        // Test messages that would come from stdin
        let test_messages = vec![
            // Initialize request
            json!({
                "jsonrpc": "2.0",
                "id": 1,
                "method": "initialize",
                "params": {
                    "protocolVersion": "2024-11-05",
                    "capabilities": {},
                    "clientInfo": {
                        "name": "test-client",
                        "version": "1.0.0"
                    }
                }
            }),
            // List tools request
            json!({
                "jsonrpc": "2.0",
                "id": 2,
                "method": "tools/list",
                "params": {}
            }),
            // Call tool request
            json!({
                "jsonrpc": "2.0",
                "id": 3,
                "method": "tools/call",
                "params": {
                    "name": "scim_server_info",
                    "arguments": {}
                }
            }),
        ];

        // Simulate processing each message
        for (_i, message) in test_messages.iter().enumerate() {
            let method = message["method"].as_str().unwrap();
            let id = message["id"].clone();

            match method {
                "initialize" => {
                    // Should return initialize response
                    let response = create_initialize_response(id);
                    assert!(response["result"]["serverInfo"]["name"].is_string());
                }
                "tools/list" => {
                    // Should return tools list
                    let tools = mcp_server.get_tools();
                    assert_eq!(tools.len(), 16);
                }
                "tools/call" => {
                    // Should execute tool
                    let tool_name = message["params"]["name"].as_str().unwrap();
                    let arguments = message["params"]["arguments"].clone();
                    let result = mcp_server.execute_tool(tool_name, arguments).await;
                    assert!(result.success);
                }
                _ => panic!("Unexpected method: {}", method),
            }
        }
    }

    /// Test error handling in MCP protocol
    #[tokio::test]
    async fn test_mcp_error_handling() {
        let mcp_server = create_test_mcp_server().await;

        // Test invalid JSON parsing
        let _invalid_json = "invalid json";
        let error_response = create_parse_error_response();
        assert_eq!(error_response["error"]["code"], -32700);
        assert_eq!(error_response["error"]["message"], "Parse error");

        // Test method not found
        let unknown_method_response = create_method_not_found_response(json!(1));
        assert_eq!(unknown_method_response["error"]["code"], -32601);
        assert_eq!(
            unknown_method_response["error"]["message"],
            "Method not found"
        );

        // Test tool execution failure
        let result = mcp_server
            .execute_tool("scim_create_user", json!({"invalid": "data"}))
            .await;
        assert!(!result.success);
    }

    // Helper functions for creating MCP responses
    fn create_initialize_response(id: Value) -> Value {
        json!({
            "jsonrpc": "2.0",
            "id": id,
            "result": {
                "protocolVersion": "2024-11-05",
                "capabilities": {
                    "tools": {}
                },
                "serverInfo": {
                    "name": "SCIM Server",
                    "version": "2.0"
                }
            }
        })
    }

    fn create_parse_error_response() -> Value {
        json!({
            "jsonrpc": "2.0",
            "id": null,
            "error": {
                "code": -32700,
                "message": "Parse error"
            }
        })
    }

    fn create_method_not_found_response(id: Value) -> Value {
        json!({
            "jsonrpc": "2.0",
            "id": id,
            "error": {
                "code": -32601,
                "message": "Method not found"
            }
        })
    }

    /// Test concurrent tool execution
    #[tokio::test]
    async fn test_concurrent_tool_execution() {
        let mcp_server = std::sync::Arc::new(create_test_mcp_server().await);

        let mut handles = vec![];

        // Execute multiple tools concurrently
        for i in 0..5 {
            let server = mcp_server.clone();
            let handle = tokio::spawn(async move {
                let result = server.execute_tool("scim_server_info", json!({})).await;
                (i, result.success)
            });
            handles.push(handle);
        }

        // Wait for all executions to complete
        for handle in handles {
            let (id, success) = handle.await.expect("Task should complete");
            assert!(success, "Concurrent execution {} should succeed", id);
        }
    }

    /// Test server info functionality
    #[test]
    fn test_server_info() {
        let server_info = McpServerInfo::default();

        assert_eq!(server_info.name, "SCIM Server");
        assert_eq!(server_info.version, "2.0");
        assert!(
            server_info
                .supported_resource_types
                .contains(&"User".to_string())
        );
        assert!(
            server_info
                .supported_resource_types
                .contains(&"Group".to_string())
        );
    }

    /// Test custom server info
    #[test]
    fn test_custom_server_info() {
        let custom_info = McpServerInfo {
            name: "Custom SCIM Server".to_string(),
            version: "1.5.0".to_string(),
            description: "Custom description".to_string(),
            supported_resource_types: vec!["User".to_string()],
        };

        assert_eq!(custom_info.name, "Custom SCIM Server");
        assert_eq!(custom_info.version, "1.5.0");
        assert_eq!(custom_info.description, "Custom description");
        assert_eq!(custom_info.supported_resource_types.len(), 1);
    }

    /// Integration test that simulates a complete MCP client-server interaction
    #[tokio::test]
    async fn test_complete_mcp_stdio_integration() {
        let mcp_server = create_test_mcp_server().await;

        // Test complete MCP workflow: initialize -> list tools -> call tool

        // 1. Initialize
        let initialize_response = mcp_server.handle_mcp_request(
            r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"test-client","version":"1.0.0"}}}"#
        ).await;

        assert!(initialize_response.is_some());
        let init_resp = initialize_response.unwrap();
        assert!(init_resp.result.is_some());
        assert!(init_resp.error.is_none());

        let init_result = init_resp.result.unwrap();
        assert_eq!(init_result["protocolVersion"], "2024-11-05");
        assert!(init_result["capabilities"]["tools"].is_object());
        assert_eq!(init_result["serverInfo"]["name"], "SCIM Server");

        // 2. List tools
        let tools_response = mcp_server
            .handle_mcp_request(r#"{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}"#)
            .await;

        assert!(tools_response.is_some());
        let tools_resp = tools_response.unwrap();
        assert!(tools_resp.result.is_some());
        assert!(tools_resp.error.is_none());

        let tools_result = tools_resp.result.unwrap();
        let tools_array = tools_result["tools"].as_array().unwrap();
        assert_eq!(tools_array.len(), 16);

        // Verify expected tools are present
        let tool_names: Vec<String> = tools_array
            .iter()
            .filter_map(|tool| tool.get("name"))
            .filter_map(|name| name.as_str())
            .map(|s| s.to_string())
            .collect();

        assert!(tool_names.contains(&"scim_create_user".to_string()));
        assert!(tool_names.contains(&"scim_get_user".to_string()));
        assert!(tool_names.contains(&"scim_server_info".to_string()));

        // 3. Call a tool - create user
        let create_user_response = mcp_server.handle_mcp_request(
            r#"{"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":"integration.test@example.com","active":true,"name":{"givenName":"Integration","familyName":"Test"}}}}}"#
        ).await;

        assert!(create_user_response.is_some());
        let create_resp = create_user_response.unwrap();
        assert!(create_resp.result.is_some());
        assert!(create_resp.error.is_none());

        let create_result = create_resp.result.unwrap();
        assert!(create_result["content"].is_array());
        let content_array = create_result["content"].as_array().unwrap();
        assert!(!content_array.is_empty());

        let content_text = content_array[0]["text"].as_str().unwrap();
        let user_data: Value = serde_json::from_str(content_text).unwrap();
        assert!(user_data.get("id").is_some());
        assert_eq!(user_data["userName"], "integration.test@example.com");

        // 4. Call server info tool
        let server_info_response = mcp_server.handle_mcp_request(
            r#"{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"scim_server_info","arguments":{}}}"#
        ).await;

        assert!(server_info_response.is_some());
        let info_resp = server_info_response.unwrap();
        assert!(info_resp.result.is_some());
        assert!(info_resp.error.is_none());

        // 5. Test error handling with invalid tool
        let error_response = mcp_server.handle_mcp_request(
            r#"{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"nonexistent_tool","arguments":{}}}"#
        ).await;

        assert!(error_response.is_some());
        let err_resp = error_response.unwrap();
        assert!(err_resp.error.is_some());
        assert!(err_resp.result.is_none());

        let error_obj = err_resp.error.unwrap();
        assert_eq!(error_obj["code"], -32000);

        // 6. Test ping
        let ping_response = mcp_server
            .handle_mcp_request(r#"{"jsonrpc":"2.0","id":6,"method":"ping","params":{}}"#)
            .await;

        assert!(ping_response.is_some());
        let ping_resp = ping_response.unwrap();
        assert!(ping_resp.result.is_some());
        assert!(ping_resp.error.is_none());

        // 7. Test invalid JSON
        let invalid_response = mcp_server.handle_mcp_request("invalid json").await;
        assert!(invalid_response.is_some());
        let invalid_resp = invalid_response.unwrap();
        assert!(invalid_resp.error.is_some());
        assert_eq!(invalid_resp.error.unwrap()["code"], -32700);

        println!("✅ Complete MCP stdio integration test passed!");
    }

    /// Test that demonstrates user lifecycle through MCP tools
    #[tokio::test]
    async fn test_user_lifecycle_via_mcp() {
        let mcp_server = create_test_mcp_server().await;

        // 1. Create user
        let create_result = mcp_server
            .execute_tool(
                "scim_create_user",
                json!({
                    "user_data": {
                        "schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],
                        "userName": "lifecycle.test@example.com",
                        "active": true,
                        "name": {
                            "givenName": "Lifecycle",
                            "familyName": "Test"
                        }
                    }
                }),
            )
            .await;

        assert!(create_result.success, "User creation should succeed");
        let user_id = create_result.content.get("id").unwrap().as_str().unwrap();
        println!("✅ Created user with ID: {}", user_id);

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

        assert!(get_result.success, "User retrieval should succeed");
        assert_eq!(get_result.content["userName"], "lifecycle.test@example.com");
        println!("✅ Retrieved user successfully");

        // 3. Update user
        let update_result = mcp_server
            .execute_tool(
                "scim_update_user",
                json!({
                    "user_id": user_id,
                    "user_data": {
                        "schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],
                        "userName": "lifecycle.updated@example.com",
                        "active": false,
                        "name": {
                            "givenName": "Updated",
                            "familyName": "User"
                        }
                    }
                }),
            )
            .await;

        assert!(update_result.success, "User update should succeed");
        assert_eq!(
            update_result.content["userName"],
            "lifecycle.updated@example.com"
        );
        println!("✅ Updated user successfully");

        // 4. Verify update by getting user again
        let verify_result = mcp_server
            .execute_tool(
                "scim_get_user",
                json!({
                    "user_id": user_id
                }),
            )
            .await;

        assert!(verify_result.success, "User verification should succeed");
        assert_eq!(
            verify_result.content["userName"],
            "lifecycle.updated@example.com"
        );
        assert_eq!(verify_result.content["active"], false);
        println!("✅ Verified user update");

        // 5. Delete user
        let delete_result = mcp_server
            .execute_tool(
                "scim_delete_user",
                json!({
                    "user_id": user_id
                }),
            )
            .await;

        assert!(delete_result.success, "User deletion should succeed");
        println!("✅ Deleted user successfully");

        // 6. Verify user is gone
        let verify_gone_result = mcp_server
            .execute_tool(
                "scim_get_user",
                json!({
                    "user_id": user_id
                }),
            )
            .await;

        assert!(
            !verify_gone_result.success,
            "Getting deleted user should fail"
        );
        println!("✅ Confirmed user deletion");

        println!("✅ Complete user lifecycle test passed!");
    }

    /// Test raw version handling in MCP operations
    #[tokio::test]
    async fn test_mcp_etag_version_handling() {
        let mcp_server = create_test_mcp_server().await;

        // 1. Create user and get version
        let create_result = mcp_server
            .execute_tool(
                "scim_create_user",
                json!({
                    "user_data": {
                        "schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],
                        "userName": "version.test@example.com",
                        "active": true
                    }
                }),
            )
            .await;

        assert!(create_result.success, "User creation should succeed");
        let user_id = create_result.content.get("id").unwrap().as_str().unwrap();
        let initial_version = create_result.metadata.as_ref().unwrap()["version"]
            .as_str()
            .unwrap()
            .to_string();

        // Version should only be available in metadata, not embedded in content
        assert!(
            create_result.content.get("_version").is_none(),
            "Content should not contain _version field"
        );

        println!("✅ Created user with version: {}", initial_version);

        // 2. Test conditional update with ETag version (should succeed)
        let conditional_update_result = mcp_server
            .execute_tool(
                "scim_update_user",
                json!({
                    "user_id": user_id,
                    "user_data": {
                        "schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],
                        "userName": "version.updated@example.com",
                        "active": false
                    },
                    "expected_version": initial_version  // ETag version format
                }),
            )
            .await;

        assert!(
            conditional_update_result.success,
            "Conditional update with ETag version should succeed"
        );
        let new_version = conditional_update_result.metadata.as_ref().unwrap()["version"]
            .as_str()
            .unwrap()
            .to_string();

        assert_ne!(
            initial_version, new_version,
            "Version should change after update"
        );
        println!(
            "✅ Conditional update succeeded with ETag version. New version: {}",
            new_version
        );

        // 3. Test conditional update with stale version (should fail)
        let stale_update_result = mcp_server
            .execute_tool(
                "scim_update_user",
                json!({
                    "user_id": user_id,
                    "user_data": {
                        "schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],
                        "userName": "should.not.work@example.com",
                        "active": true
                    },
                    "expected_version": initial_version  // Stale version
                }),
            )
            .await;

        assert!(
            !stale_update_result.success,
            "Conditional update with stale version should fail"
        );
        assert_eq!(
            stale_update_result.content["error_code"],
            "VERSION_MISMATCH"
        );
        println!("✅ Conditional update correctly failed with stale version");

        // 4. Test conditional delete with ETag version (should succeed)
        let conditional_delete_result = mcp_server
            .execute_tool(
                "scim_delete_user",
                json!({
                    "user_id": user_id,
                    "expected_version": new_version  // Use updated ETag version
                }),
            )
            .await;

        assert!(
            conditional_delete_result.success,
            "Conditional delete with ETag version should succeed"
        );
        println!("✅ Conditional delete succeeded with ETag version");

        // 5. Test invalid version format
        let invalid_version_result = mcp_server
            .execute_tool(
                "scim_update_user",
                json!({
                    "user_id": "dummy",
                    "user_data": {
                        "schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],
                        "userName": "test"
                    },
                    "expected_version": ""  // Empty version should fail
                }),
            )
            .await;

        assert!(!invalid_version_result.success, "Empty version should fail");
        assert_eq!(
            invalid_version_result.content["error_code"],
            "INVALID_VERSION_FORMAT"
        );
        println!("✅ Empty version correctly rejected");

        println!("✅ Complete raw version handling test passed!");
    }

    /// Test that MCP interface returns SCIM 2.0 compliant $ref fields in group members and user groups
    #[tokio::test]
    async fn test_mcp_ref_field_compliance() {
        println!("🧪 Testing MCP $ref field compliance...");

        let server = create_test_mcp_server().await;

        // Step 1: Create a user via MCP
        let user_create_request = json!({
            "user_data": {
                "schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],
                "userName": "ref.test@example.com",
                "name": {
                    "givenName": "RefField",
                    "familyName": "Test"
                },
                "emails": [{
                    "value": "ref.test@example.com",
                    "type": "work",
                    "primary": true
                }]
            }
        });

        let user_result = server
            .execute_tool("scim_create_user", user_create_request)
            .await;

        assert!(user_result.success, "User creation should succeed");
        let user_data = &user_result.content;
        let user_id = user_data["id"].as_str().expect("User should have ID");
        println!("✅ Created user: {}", user_id);

        // Step 2: Create a group with the user as a member
        let group_create_request = json!({
            "group_data": {
                "schemas": ["urn:ietf:params:scim:schemas:core:2.0:Group"],
                "displayName": "Ref Test Group",
                "externalId": "ref-test-group",
                "members": [{
                    "value": user_id,
                    "$ref": format!("https://example.com/v2/Users/{}", user_id),
                    "type": "User",
                    "display": "RefField Test"
                }]
            }
        });

        let group_result = server
            .execute_tool("scim_create_group", group_create_request)
            .await;

        if !group_result.success {
            println!("❌ Group creation failed: {:?}", group_result.content);
        }
        assert!(group_result.success, "Group creation should succeed");
        let group_data = &group_result.content;
        let group_id = group_data["id"].as_str().expect("Group should have ID");
        println!("✅ Created group: {}", group_id);

        // Step 3: Verify Group.members array has proper $ref fields
        let group_members = group_data["members"]
            .as_array()
            .expect("Group should have members array");

        assert_eq!(
            group_members.len(),
            1,
            "Group should have exactly one member"
        );
        let member = &group_members[0];

        // CRITICAL ASSERTIONS: These will currently fail and need to be fixed
        assert_eq!(member["value"], user_id, "Member value should be user ID");
        assert_eq!(member["type"], "User", "Member type should be User");
        assert_eq!(
            member["display"], "RefField Test",
            "Member display should be set"
        );

        // This is the key test that should pass but currently fails
        assert!(
            member["$ref"].is_string(),
            "Group member must have $ref field - currently missing!"
        );
        assert_eq!(
            member["$ref"].as_str().unwrap(),
            format!("mcp://scim/v2/Users/{}", user_id),
            "$ref should contain proper URI to user resource"
        );
        println!("✅ Group member has proper $ref field");

        // Step 4: Client updates user to include group reference (maintaining referential integrity)
        let user_update_request = json!({
            "user_id": user_id,
            "user_data": {
                "schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],
                "userName": "ref.test@example.com",
                "name": {
                    "givenName": "RefField",
                    "familyName": "Test"
                },
                "emails": [{
                    "value": "ref.test@example.com",
                    "type": "work",
                    "primary": true
                }],
                "groups": [{
                    "value": group_id,
                    "type": "direct",
                    "display": "Ref Test Group"
                }]
            }
        });

        let updated_user = server
            .execute_tool("scim_update_user", user_update_request)
            .await;

        if !updated_user.success {
            println!("❌ User update failed: {:?}", updated_user.content);
        }
        assert!(updated_user.success, "User update should succeed");
        let updated_user_data = &updated_user.content;

        // Step 5: Verify User.groups array has proper $ref fields
        assert!(
            updated_user_data["groups"].is_array(),
            "User must have groups array after client update"
        );

        let user_groups = updated_user_data["groups"]
            .as_array()
            .expect("User should have groups array");

        assert_eq!(
            user_groups.len(),
            1,
            "User should be member of exactly one group"
        );
        let group_ref = &user_groups[0];

        assert_eq!(
            group_ref["value"], group_id,
            "Group reference value should be group ID"
        );
        assert_eq!(
            group_ref["type"], "direct",
            "Group reference type should be direct"
        );
        assert_eq!(
            group_ref["display"], "Ref Test Group",
            "Group reference display should be group name"
        );

        // This is the key test for bidirectional $ref compliance
        assert!(
            group_ref["$ref"].is_string(),
            "User group reference must have $ref field - currently missing!"
        );
        assert_eq!(
            group_ref["$ref"].as_str().unwrap(),
            format!("mcp://scim/v2/Groups/{}", group_id),
            "User group $ref should contain proper URI to group resource"
        );
        println!("✅ User group reference has proper $ref field");

        println!("✅ Complete MCP $ref field compliance test passed!");

        // Note: Update operations to test $ref preservation are omitted to avoid
        // version mismatch complexity in this core functionality test. The key
        // $ref generation and bidirectional reference functionality is verified.
    }
}