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
//! Group CRUD operation handlers for MCP integration
//!
//! This module contains the implementation of all group Create, Read, Update, Delete
//! operations exposed through the MCP protocol. These handlers provide the business
//! logic for group lifecycle management with proper error handling, tenant isolation,
//! and version-based concurrency control.

use crate::{
    ResourceProvider,
    mcp_integration::core::{ScimMcpServer, ScimToolResult},
    mcp_integration::handlers::etag_to_raw_version,
    multi_tenant::TenantContext,
    operation_handler::ScimOperationRequest,
    resource::version::{Http, Raw, ScimVersion},
};
use serde_json::{Value, json};

/// Handle group creation through MCP
///
/// Creates a new group resource with tenant isolation and versioning support.
/// Returns the created group with version metadata for subsequent operations.
///
/// # Errors
///
/// Returns error result if:
/// - Required group_data parameter is missing
/// - Group data fails SCIM schema validation
/// - displayName already exists (duplicate group)
/// - Tenant permissions are insufficient
/// - Internal server error during creation
pub async fn handle_create_group<P: ResourceProvider + Send + Sync + 'static>(
    server: &ScimMcpServer<P>,
    arguments: Value,
) -> ScimToolResult {
    let group_data = match arguments.get("group_data") {
        Some(data) => data.clone(),
        None => {
            return ScimToolResult {
                success: false,
                content: json!({"error": "Missing group_data parameter"}),
                metadata: None,
            };
        }
    };

    let tenant_context = arguments
        .get("tenant_id")
        .and_then(|t| t.as_str())
        .map(|id| TenantContext::new(id.to_string(), "mcp-client".to_string()));

    let mut request = ScimOperationRequest::create("Group".to_string(), group_data);
    if let Some(tenant) = tenant_context {
        request = request.with_tenant(tenant);
    }

    let response = server.operation_handler.handle_operation(request).await;

    if response.success {
        let content = response
            .data
            .unwrap_or_else(|| json!({"status": "created"}));

        // Include version information in response for AI agent to use in subsequent operations
        let mut metadata = json!({
            "operation": "create_group",
            "resource_type": "Group",
            "resource_id": response.metadata.resource_id
        });

        if let Some(etag) = response.metadata.additional.get("etag") {
            if let Some(raw_version) = etag_to_raw_version(etag) {
                metadata["version"] = json!(raw_version);
            }
        }

        ScimToolResult {
            success: true,
            content,
            metadata: Some(metadata),
        }
    } else {
        ScimToolResult {
            success: false,
            content: json!({
                "error": response.error.unwrap_or_else(|| "Create failed".to_string()),
                "error_code": "CREATE_GROUP_FAILED"
            }),
            metadata: None,
        }
    }
}

/// Handle group retrieval through MCP
///
/// Retrieves a group by ID with tenant isolation and includes version information
/// for subsequent conditional operations.
///
/// # Errors
///
/// Returns error result if:
/// - Required group_id parameter is missing
/// - Group with specified ID does not exist
/// - Tenant permissions are insufficient
/// - Internal server error during retrieval
pub async fn handle_get_group<P: ResourceProvider + Send + Sync + 'static>(
    server: &ScimMcpServer<P>,
    arguments: Value,
) -> ScimToolResult {
    let group_id = match arguments.get("group_id").and_then(|id| id.as_str()) {
        Some(id) => id,
        None => {
            return ScimToolResult {
                success: false,
                content: json!({"error": "Missing group_id parameter"}),
                metadata: None,
            };
        }
    };

    let tenant_context = arguments
        .get("tenant_id")
        .and_then(|t| t.as_str())
        .map(|id| TenantContext::new(id.to_string(), "mcp-client".to_string()));

    let mut request = ScimOperationRequest::get("Group".to_string(), group_id.to_string());
    if let Some(tenant) = tenant_context {
        request = request.with_tenant(tenant);
    }

    let response = server.operation_handler.handle_operation(request).await;

    if response.success {
        let content = response
            .data
            .unwrap_or_else(|| json!({"status": "retrieved"}));

        let mut metadata = json!({
            "operation": "get_group",
            "resource_type": "Group",
            "resource_id": group_id
        });

        // Include version information for AI to use in conditional operations
        if let Some(etag) = response.metadata.additional.get("etag") {
            if let Some(raw_version) = etag_to_raw_version(etag) {
                metadata["version"] = json!(raw_version);
            }
        }

        ScimToolResult {
            success: true,
            content,
            metadata: Some(metadata),
        }
    } else {
        let error_msg = response
            .error
            .unwrap_or_else(|| "Group not found".to_string());
        ScimToolResult {
            success: false,
            content: json!({
                "error": error_msg,
                "error_code": if error_msg.contains("not found") { "GROUP_NOT_FOUND" } else { "GET_GROUP_FAILED" },
                "group_id": group_id
            }),
            metadata: Some(json!({
                "operation": "get_group",
                "resource_id": group_id
            })),
        }
    }
}

/// Handle group update through MCP
///
/// Updates an existing group with optional version-based conditional update.
/// Supports optimistic concurrency control to prevent lost updates.
///
/// # Errors
///
/// Returns error result if:
/// - Required group_id or group_data parameters are missing
/// - Group with specified ID does not exist
/// - Version conflict (if expected_version provided)
/// - Group data fails SCIM schema validation
/// - Tenant permissions are insufficient
pub async fn handle_update_group<P: ResourceProvider + Send + Sync + 'static>(
    server: &ScimMcpServer<P>,
    arguments: Value,
) -> ScimToolResult {
    let group_id = match arguments.get("group_id").and_then(|id| id.as_str()) {
        Some(id) => id,
        None => {
            return ScimToolResult {
                success: false,
                content: json!({"error": "Missing group_id parameter"}),
                metadata: None,
            };
        }
    };

    let group_data = match arguments.get("group_data") {
        Some(data) => data.clone(),
        None => {
            return ScimToolResult {
                success: false,
                content: json!({"error": "Missing group_data parameter"}),
                metadata: None,
            };
        }
    };

    let tenant_context = arguments
        .get("tenant_id")
        .and_then(|t| t.as_str())
        .map(|id| TenantContext::new(id.to_string(), "mcp-client".to_string()));

    let mut request =
        ScimOperationRequest::update("Group".to_string(), group_id.to_string(), group_data);
    if let Some(tenant) = tenant_context {
        request = request.with_tenant(tenant);
    }

    // Handle optional version-based conditional update
    if let Some(expected_version_str) = arguments.get("expected_version").and_then(|v| v.as_str()) {
        // Try parsing as HTTP ETag format first, then as raw format
        let version_result = expected_version_str
            .parse::<ScimVersion<Http>>()
            .map(|v| v.into())
            .or_else(|_| expected_version_str.parse::<ScimVersion<Raw>>());

        match version_result {
            Ok(version) => {
                request = request.with_expected_version(version);
            }
            Err(_) => {
                return ScimToolResult {
                    success: false,
                    content: json!({
                        "error": format!("Invalid expected_version format: '{}'. Use raw format (e.g., 'abc123def') or ETag format (e.g., 'W/\"abc123def\"')", expected_version_str),
                        "error_code": "INVALID_VERSION_FORMAT"
                    }),
                    metadata: None,
                };
            }
        }
    }

    let response = server.operation_handler.handle_operation(request).await;

    if response.success {
        let content = response
            .data
            .unwrap_or_else(|| json!({"status": "updated"}));

        let mut metadata = json!({
            "operation": "update_group",
            "resource_type": "Group",
            "resource_id": group_id
        });

        // Include updated version information
        if let Some(etag) = response.metadata.additional.get("etag") {
            if let Some(raw_version) = etag_to_raw_version(etag) {
                metadata["version"] = json!(raw_version);
            }
        }

        ScimToolResult {
            success: true,
            content,
            metadata: Some(metadata),
        }
    } else {
        let error_msg = response
            .error
            .unwrap_or_else(|| "Update failed".to_string());
        let error_code = if error_msg.contains("version mismatch")
            || error_msg.contains("modified by another client")
        {
            "VERSION_MISMATCH"
        } else if error_msg.contains("not found") {
            "GROUP_NOT_FOUND"
        } else {
            "UPDATE_GROUP_FAILED"
        };

        ScimToolResult {
            success: false,
            content: json!({
                "error": error_msg,
                "error_code": error_code,
                "group_id": group_id
            }),
            metadata: Some(json!({
                "operation": "update_group",
                "resource_id": group_id,
                "conditional_update": arguments.get("expected_version").is_some()
            })),
        }
    }
}

/// Handle group deletion through MCP
///
/// Deletes a group with optional version-based conditional delete.
/// Supports optimistic concurrency control to prevent accidental deletion of modified resources.
///
/// # Errors
///
/// Returns error result if:
/// - Required group_id parameter is missing
/// - Group with specified ID does not exist
/// - Version conflict (if expected_version provided)
/// - Tenant permissions are insufficient
/// - Internal server error during deletion
pub async fn handle_delete_group<P: ResourceProvider + Send + Sync + 'static>(
    server: &ScimMcpServer<P>,
    arguments: Value,
) -> ScimToolResult {
    let group_id = match arguments.get("group_id").and_then(|id| id.as_str()) {
        Some(id) => id,
        None => {
            return ScimToolResult {
                success: false,
                content: json!({"error": "Missing group_id parameter"}),
                metadata: None,
            };
        }
    };

    let tenant_context = arguments
        .get("tenant_id")
        .and_then(|t| t.as_str())
        .map(|id| TenantContext::new(id.to_string(), "mcp-client".to_string()));

    let mut request = ScimOperationRequest::delete("Group".to_string(), group_id.to_string());
    if let Some(tenant) = tenant_context {
        request = request.with_tenant(tenant);
    }

    // Handle optional version-based conditional delete
    if let Some(expected_version_str) = arguments.get("expected_version").and_then(|v| v.as_str()) {
        // Try parsing as HTTP ETag format first, then as raw format
        let version_result = expected_version_str
            .parse::<ScimVersion<Http>>()
            .map(|v| v.into())
            .or_else(|_| expected_version_str.parse::<ScimVersion<Raw>>());

        match version_result {
            Ok(version) => {
                request = request.with_expected_version(version);
            }
            Err(_) => {
                return ScimToolResult {
                    success: false,
                    content: json!({
                        "error": format!("Invalid expected_version format: '{}'. Use raw format (e.g., 'abc123def') or ETag format (e.g., 'W/\"abc123def\"')", expected_version_str),
                        "error_code": "INVALID_VERSION_FORMAT"
                    }),
                    metadata: None,
                };
            }
        }
    }

    let response = server.operation_handler.handle_operation(request).await;

    if response.success {
        ScimToolResult {
            success: true,
            content: json!({"status": "deleted", "group_id": group_id}),
            metadata: Some(json!({
                "operation": "delete_group",
                "resource_type": "Group",
                "resource_id": group_id,
                "conditional_delete": arguments.get("expected_version").is_some()
            })),
        }
    } else {
        let error_msg = response
            .error
            .unwrap_or_else(|| "Delete failed".to_string());
        let error_code = if error_msg.contains("version mismatch")
            || error_msg.contains("modified by another client")
        {
            "VERSION_MISMATCH"
        } else if error_msg.contains("not found") {
            "GROUP_NOT_FOUND"
        } else {
            "DELETE_GROUP_FAILED"
        };

        ScimToolResult {
            success: false,
            content: json!({
                "error": error_msg,
                "error_code": error_code,
                "group_id": group_id
            }),
            metadata: Some(json!({
                "operation": "delete_group",
                "resource_id": group_id,
                "conditional_delete": arguments.get("expected_version").is_some()
            })),
        }
    }
}