delegated 0.1.0

Fail-closed trust evaluation for agentic AI systems — delegation tokens, policy enforcement, and audit for agent-to-agent and human-to-agent workflows.
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
use crate::adapters::guard::{AdapterGuardConfig, enter_adapter_guard};
use crate::audit::AuditSink;
use crate::engine::evaluate_and_audit_with_state;
use crate::models::{HostContext, RequestEnvelope};
use crate::revocation::{RuntimeTrustConfig, TrustStateStore, trust_state_from_runtime_config};
use crate::wire::{SHARED_CLAIMS_KIND, SharedTrustClaims};
use chrono::{DateTime, Utc};
use serde::Serialize;
use serde_json::{Map, Value, json};

#[derive(Debug, Clone, PartialEq, Eq, Serialize, serde::Deserialize)]
pub struct McpJsonRpcResponse {
    pub jsonrpc: String,
    pub id: Option<Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub result: Option<Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<Value>,
}

pub fn handle_mcp_jsonrpc_request(
    raw_body: &str,
    now: DateTime<Utc>,
    sink: &dyn AuditSink,
) -> McpJsonRpcResponse {
    handle_mcp_jsonrpc_request_with_runtime_config(
        raw_body,
        now,
        sink,
        &RuntimeTrustConfig::default(),
    )
}

pub fn handle_mcp_jsonrpc_request_with_runtime_config(
    raw_body: &str,
    now: DateTime<Utc>,
    sink: &dyn AuditSink,
    runtime_config: &RuntimeTrustConfig,
) -> McpJsonRpcResponse {
    let trust_state = trust_state_from_runtime_config(runtime_config);
    handle_mcp_jsonrpc_request_with_state(
        raw_body,
        now,
        sink,
        trust_state.as_ref(),
        &HostContext::default(),
    )
}

pub fn handle_mcp_jsonrpc_request_with_state(
    raw_body: &str,
    now: DateTime<Utc>,
    sink: &dyn AuditSink,
    trust_state: &dyn TrustStateStore,
    host_context: &HostContext,
) -> McpJsonRpcResponse {
    handle_mcp_jsonrpc_request_with_state_and_guard_config(
        raw_body,
        now,
        sink,
        trust_state,
        &AdapterGuardConfig::default(),
        host_context,
    )
}

pub fn handle_mcp_jsonrpc_request_with_state_and_guard_config(
    raw_body: &str,
    now: DateTime<Utc>,
    sink: &dyn AuditSink,
    trust_state: &dyn TrustStateStore,
    guard_config: &AdapterGuardConfig,
    host_context: &HostContext,
) -> McpJsonRpcResponse {
    let raw_request: Value = match serde_json::from_str(raw_body) {
        Ok(value) => value,
        Err(error) => {
            return jsonrpc_error(
                None,
                -32700,
                format!("parse error: {error}"),
                Some(json!({"stage":"mcp_adapter"})),
            );
        }
    };

    let object = match raw_request.as_object() {
        Some(object) => object,
        None => {
            return jsonrpc_error(
                None,
                -32600,
                "invalid request: body must be a JSON object".to_string(),
                Some(json!({"stage":"mcp_adapter"})),
            );
        }
    };

    let id = object.get("id").cloned();
    let version = object.get("jsonrpc").and_then(Value::as_str).unwrap_or("");
    if version != "2.0" {
        return jsonrpc_error(
            id,
            -32600,
            "invalid request: jsonrpc must equal 2.0".to_string(),
            Some(json!({"stage":"mcp_adapter"})),
        );
    }

    let params = match object.get("params").and_then(Value::as_object) {
        Some(params) => params,
        None => {
            return jsonrpc_error(
                id,
                -32602,
                "invalid params: params must be an object".to_string(),
                Some(json!({"stage":"mcp_adapter"})),
            );
        }
    };
    let claims = match parse_shared_claims(params) {
        Ok(claims) => claims,
        Err(error_response) => return error_response.with_id(id),
    };
    let _guard_lease =
        match enter_adapter_guard(&claims.agent_id, &claims.delegator_id, now, guard_config) {
            Ok(lease) => lease,
            Err(violation) => {
                return jsonrpc_error(
                    id,
                    -32029,
                    "adapter throttled request".to_string(),
                    Some(json!({"stage":"adapter_guard","reason":violation.reason})),
                );
            }
        };
    let envelope: RequestEnvelope = claims.into();
    let raw_envelope = match serde_json::to_value(envelope) {
        Ok(value) => value,
        Err(error) => {
            return jsonrpc_error(
                id,
                -32603,
                format!("failed to encode request envelope: {error}"),
                Some(json!({"stage":"mcp_adapter"})),
            );
        }
    };

    match evaluate_and_audit_with_state(&raw_envelope, now, sink, trust_state, host_context) {
        Ok(decision) if decision.allowed => McpJsonRpcResponse {
            jsonrpc: "2.0".to_string(),
            id,
            result: Some(json!({
                "allowed": true,
                "stage": decision.stage,
                "reason": decision.reason
            })),
            error: None,
        },
        Ok(decision) => jsonrpc_error(
            id,
            -32001,
            "trust policy denied request".to_string(),
            Some(json!({
                "allowed": false,
                "stage": decision.stage,
                "reason": decision.reason
            })),
        ),
        Err(error) => jsonrpc_error(
            id,
            -32603,
            format!("adapter failed to emit audit event: {error}"),
            Some(json!({"stage":"audit_sink"})),
        ),
    }
}

fn parse_shared_claims(
    params: &Map<String, Value>,
) -> Result<SharedTrustClaims, AdapterErrorResponse> {
    let raw_claims = params.get("_trust").ok_or_else(|| {
        AdapterErrorResponse::new(
            -32602,
            "invalid params: params._trust is required".to_string(),
            Some(json!({"stage":"mcp_adapter"})),
        )
    })?;
    let claims: SharedTrustClaims =
        serde_json::from_value(raw_claims.clone()).map_err(|error| {
            AdapterErrorResponse::new(
                -32602,
                format!("invalid params: params._trust is malformed: {error}"),
                Some(json!({"stage":"mcp_adapter"})),
            )
        })?;
    if claims.kind != SHARED_CLAIMS_KIND {
        return Err(AdapterErrorResponse::new(
            -32602,
            format!("invalid params: params._trust.kind must equal {SHARED_CLAIMS_KIND}"),
            Some(json!({"stage":"mcp_adapter"})),
        ));
    }
    Ok(claims)
}

#[derive(Debug, Clone)]
struct AdapterErrorResponse {
    code: i64,
    message: String,
    data: Option<Value>,
}

impl AdapterErrorResponse {
    fn new(code: i64, message: String, data: Option<Value>) -> Self {
        Self {
            code,
            message,
            data,
        }
    }

    fn with_id(self, id: Option<Value>) -> McpJsonRpcResponse {
        jsonrpc_error(id, self.code, self.message, self.data)
    }
}

fn jsonrpc_error(
    id: Option<Value>,
    code: i64,
    message: String,
    data: Option<Value>,
) -> McpJsonRpcResponse {
    McpJsonRpcResponse {
        jsonrpc: "2.0".to_string(),
        id,
        result: None,
        error: Some(json!({
            "code": code,
            "message": message,
            "data": data
        })),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::adapters::guard::AdapterGuardConfig;
    use crate::audit::JsonlFileAuditSink;
    use crate::crypto::{
        TOKEN_SIGNATURE_ALG_ED25519, sign_delegation_token, sign_identity_document,
    };
    use crate::models::{
        AgentEndpoint, AgentIdentityDocument, DelegationToken, PublicKeyRecord, RequestEnvelope,
        RuntimeContext, TrustProfile,
    };
    use crate::revocation::InMemoryTrustState;
    use base64ct::{Base64UrlUnpadded, Encoding};
    use chrono::TimeZone;
    use ed25519_dalek::SigningKey;
    use std::sync::atomic::{AtomicU64, Ordering};

    static REQUEST_COUNTER: AtomicU64 = AtomicU64::new(1);

    fn now() -> DateTime<Utc> {
        Utc.with_ymd_and_hms(2026, 6, 1, 20, 20, 0)
            .single()
            .expect("valid test timestamp")
    }

    fn unique_id() -> String {
        let counter = REQUEST_COUNTER.fetch_add(1, Ordering::Relaxed);
        let nanos = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .expect("time should be after epoch")
            .as_nanos();
        format!("{counter}_{nanos}")
    }

    fn signed_shared_claims_for_actor(nonce: &str, delegator_id: &str) -> SharedTrustClaims {
        let unique_id = unique_id();
        let key = SigningKey::from_bytes(&[12u8; 32]);
        let mut identity = AgentIdentityDocument {
            spec_version: "0.1".to_string(),
            kind: "AgentIdentityDocument".to_string(),
            agent_id: "agent:example:scheduler:v1".to_string(),
            display_name: None,
            owner_id: "org:example".to_string(),
            issuer: "https://trust.example.ai".to_string(),
            identity_type: "spiffe".to_string(),
            subject: "spiffe://example.ai/agents/scheduler".to_string(),
            public_keys: vec![PublicKeyRecord {
                kid: "key-2026-01".to_string(),
                kty: "OKP".to_string(),
                crv: Some(TOKEN_SIGNATURE_ALG_ED25519.to_string()),
                x: Some(Base64UrlUnpadded::encode_string(
                    &key.verifying_key().to_bytes(),
                )),
            }],
            supported_protocols: vec!["mcp".to_string()],
            supported_auth_methods: vec!["delegation_token".to_string()],
            capabilities: None,
            endpoints: vec![AgentEndpoint {
                protocol: "mcp".to_string(),
                url: "https://agents.example.ai/scheduler/mcp".to_string(),
            }],
            attestation: None,
            created_at: Utc
                .with_ymd_and_hms(2026, 6, 1, 20, 0, 0)
                .single()
                .expect("valid timestamp"),
            expires_at: Utc
                .with_ymd_and_hms(2026, 6, 8, 20, 0, 0)
                .single()
                .expect("valid timestamp"),
            signature: String::new(),
        };
        identity.signature = sign_identity_document(&identity, &key).expect("identity signing");

        let mut token = DelegationToken {
            spec_version: "0.1".to_string(),
            kind: "DelegationToken".to_string(),
            token_id: format!("dlg_mcp_{unique_id}"),
            issuer: "https://trust.example.ai".to_string(),
            agent_id: "agent:example:scheduler:v1".to_string(),
            delegator_id: delegator_id.to_string(),
            owner_id: "org:example".to_string(),
            audience: vec!["tool:google-calendar".to_string()],
            allowed_actions: vec!["calendar.create_event".to_string()],
            resource_constraints: None,
            max_spend: None,
            max_delegation_depth: Some(0),
            issued_at: Utc
                .with_ymd_and_hms(2026, 6, 1, 20, 10, 0)
                .single()
                .expect("valid timestamp"),
            expires_at: Utc
                .with_ymd_and_hms(2026, 6, 1, 20, 40, 0)
                .single()
                .expect("valid timestamp"),
            intent: None,
            nonce: nonce.to_string(),
            key_id: "key-2026-01".to_string(),
            signature_alg: TOKEN_SIGNATURE_ALG_ED25519.to_string(),
            signature: String::new(),
        };
        token.signature = sign_delegation_token(&token, &key).expect("token signing");
        let request = RequestEnvelope {
            spec_version: "0.1".to_string(),
            kind: "TrustRequestEnvelope".to_string(),
            request_id: Some(format!("req_mcp_{unique_id}")),
            profile: TrustProfile::Developer,
            agent_id: "agent:example:scheduler:v1".to_string(),
            delegator_id: delegator_id.to_string(),
            audience: "tool:google-calendar".to_string(),
            action: "calendar.create_event".to_string(),
            resource: None,
            runtime_context: RuntimeContext::default(),
            identity_document: Some(identity),
            token,
        };
        request.into()
    }

    fn signed_shared_claims(nonce: &str) -> SharedTrustClaims {
        signed_shared_claims_for_actor(nonce, "user:jake-abendroth")
    }

    fn unique_nonce(prefix: &str) -> String {
        format!("{prefix}-{}", unique_id())
    }

    #[test]
    fn allows_valid_mcp_request() {
        let nonce = unique_nonce("nonce-mcp");
        let body = json!({
            "jsonrpc":"2.0",
            "id":"msg-1",
            "method":"tools.call",
            "params":{
                "_trust": signed_shared_claims(&nonce),
                "_payload":{"tool":"calendar.create_event"}
            }
        })
        .to_string();
        let sink_path = std::env::temp_dir().join(format!(
            "delegated_mcp_{}.jsonl",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .expect("time should be after epoch")
                .as_nanos()
        ));
        let sink = JsonlFileAuditSink::new(sink_path.clone());
        let response = handle_mcp_jsonrpc_request(&body, now(), &sink);
        assert!(response.error.is_none());
        assert_eq!(
            response.result.as_ref().and_then(|v| v.get("allowed")),
            Some(&json!(true))
        );
        std::fs::remove_file(sink_path).expect("temporary audit file should be removable");
    }

    #[test]
    fn blocks_nonce_replay_in_mcp_stateful_path() {
        let replay_nonce = unique_nonce("nonce-mcp-replay");
        let body = json!({
            "jsonrpc":"2.0",
            "id":"msg-2",
            "method":"tools.call",
            "params":{
                "_trust": signed_shared_claims(&replay_nonce),
                "_payload":{"tool":"calendar.create_event"}
            }
        })
        .to_string();
        let sink_path = std::env::temp_dir().join(format!(
            "delegated_mcp_replay_{}.jsonl",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .expect("time should be after epoch")
                .as_nanos()
        ));
        let sink = JsonlFileAuditSink::new(sink_path.clone());
        let state = InMemoryTrustState::new();
        let first = handle_mcp_jsonrpc_request_with_state(
            &body,
            now(),
            &sink,
            &state,
            &HostContext::default(),
        );
        let second = handle_mcp_jsonrpc_request_with_state(
            &body,
            now(),
            &sink,
            &state,
            &HostContext::default(),
        );
        assert!(first.error.is_none());
        assert!(second.error.is_some());
        assert_eq!(
            second
                .error
                .as_ref()
                .and_then(|e| e.get("data"))
                .and_then(|d| d.get("reason")),
            Some(&json!("delegation token nonce replay detected"))
        );
        std::fs::remove_file(sink_path).expect("temporary audit file should be removable");
    }

    #[test]
    fn returns_jsonrpc_rate_limit_error_when_throttled() {
        let delegator = format!(
            "user:mcp-rate-limit:{}",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .expect("time should be after epoch")
                .as_nanos()
        );
        let config = AdapterGuardConfig {
            max_requests_per_minute: 1,
            max_inflight_per_tuple: 4,
        };
        let first_nonce = unique_nonce("nonce-mcp-rate-one");
        let second_nonce = unique_nonce("nonce-mcp-rate-two");
        let first_body = json!({
            "jsonrpc":"2.0",
            "id":"msg-rate-1",
            "method":"tools.call",
            "params":{
                "_trust": signed_shared_claims_for_actor(&first_nonce, &delegator),
                "_payload":{"tool":"calendar.create_event"}
            }
        })
        .to_string();
        let second_body = json!({
            "jsonrpc":"2.0",
            "id":"msg-rate-2",
            "method":"tools.call",
            "params":{
                "_trust": signed_shared_claims_for_actor(&second_nonce, &delegator),
                "_payload":{"tool":"calendar.create_event"}
            }
        })
        .to_string();
        let sink_path = std::env::temp_dir().join(format!(
            "delegated_mcp_rate_{}.jsonl",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .expect("time should be after epoch")
                .as_nanos()
        ));
        let sink = JsonlFileAuditSink::new(sink_path.clone());
        let state = InMemoryTrustState::new();
        let first = handle_mcp_jsonrpc_request_with_state_and_guard_config(
            &first_body,
            now(),
            &sink,
            &state,
            &config,
            &HostContext::default(),
        );
        let second = handle_mcp_jsonrpc_request_with_state_and_guard_config(
            &second_body,
            now(),
            &sink,
            &state,
            &config,
            &HostContext::default(),
        );
        assert!(first.error.is_none());
        assert_eq!(
            second
                .error
                .as_ref()
                .and_then(|e| e.get("code"))
                .and_then(|c| c.as_i64()),
            Some(-32029)
        );
        assert_eq!(
            second
                .error
                .as_ref()
                .and_then(|e| e.get("data"))
                .and_then(|d| d.get("reason")),
            Some(&json!("rate limit exceeded for agent/delegator tuple"))
        );
        std::fs::remove_file(sink_path).expect("temporary audit file should be removable");
    }
}