Skip to main content

protocol_7h3/
lib.rs

1pub mod http;
2pub mod keys;
3pub mod queue;
4pub mod webhook;
5
6use base64::engine::general_purpose::URL_SAFE_NO_PAD;
7use base64::Engine;
8use ed25519_dalek::pkcs8::{DecodePrivateKey, DecodePublicKey};
9use ed25519_dalek::{Signature as Ed25519Signature, Signer, SigningKey, Verifier, VerifyingKey};
10use hmac::{Hmac, KeyInit, Mac};
11use serde::{Deserialize, Serialize};
12use serde_json::Value;
13use sha2::Sha256;
14use zeroize::Zeroize;
15
16type HmacSha256 = Hmac<Sha256>;
17
18/// Ceiling on ttlMs — a huge TTL keeps an envelope replayable (and its nonce
19/// pinned in every replay store) far beyond any legitimate messaging window.
20pub const MAX_TTL_MS: i64 = 86_400_000; // 24 hours
21
22/// How far into the future a timestamp may sit before it is rejected. Without
23/// this ceiling `MAX_TTL_MS` bounds nothing: a sender can post-date
24/// `timestamp_ms` by a year and still pass a 24h `ttl_ms`, keeping the envelope
25/// valid — and replayable — long after any replay store has forgotten its nonce.
26pub const MAX_CLOCK_SKEW_MS: i64 = 30_000;
27
28#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
29pub struct ProtocolHeader {
30    pub version: String,
31    #[serde(rename = "messageId")]
32    pub message_id: String,
33    #[serde(rename = "timestampMs")]
34    pub timestamp_ms: i64,
35    #[serde(rename = "ttlMs")]
36    pub ttl_ms: i64,
37    pub sender: String,
38    #[serde(skip_serializing_if = "Option::is_none")]
39    pub recipient: Option<String>,
40    pub nonce: String,
41}
42
43#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
44pub struct ProtocolBody {
45    pub intent: String,
46    pub content: String,
47    #[serde(skip_serializing_if = "Option::is_none")]
48    pub capability: Option<String>,
49    #[serde(rename = "correlationId", skip_serializing_if = "Option::is_none")]
50    pub correlation_id: Option<String>,
51}
52
53#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
54pub struct ProtocolSignature {
55    pub alg: String,
56    #[serde(rename = "keyId")]
57    pub key_id: String,
58    pub value: String,
59}
60
61#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
62pub struct ProtocolEnvelope {
63    pub header: ProtocolHeader,
64    pub body: ProtocolBody,
65    #[serde(skip_serializing_if = "Option::is_none")]
66    pub signature: Option<ProtocolSignature>,
67}
68
69#[derive(Debug, Clone, PartialEq, Eq)]
70pub struct ProtocolDiagnostic {
71    pub level: String,
72    pub message: String,
73}
74
75#[derive(Debug, Clone, Serialize, Deserialize)]
76struct CompactSignature {
77    #[serde(skip_serializing_if = "Option::is_none")]
78    a: Option<String>,
79    k: String,
80    v: String,
81}
82
83#[derive(Debug, Clone, Serialize, Deserialize)]
84struct CompactEnvelope {
85    v: String,
86    mid: String,
87    ts: i64,
88    ttl: i64,
89    s: String,
90    n: String,
91    i: String,
92    c: String,
93    #[serde(skip_serializing_if = "Option::is_none")]
94    r: Option<String>,
95    #[serde(skip_serializing_if = "Option::is_none")]
96    cap: Option<String>,
97    #[serde(skip_serializing_if = "Option::is_none")]
98    cid: Option<String>,
99    #[serde(skip_serializing_if = "Option::is_none")]
100    sig: Option<CompactSignature>,
101}
102
103fn json_string<T: Serialize>(value: &T) -> String {
104    serde_json::to_string(value).expect("json serialization should not fail")
105}
106
107pub fn canonicalize_envelope(envelope: &ProtocolEnvelope) -> String {
108    let mut body_parts: Vec<String> = Vec::new();
109    if let Some(capability) = &envelope.body.capability {
110        body_parts.push(format!("\"capability\":{}", json_string(capability)));
111    }
112    body_parts.push(format!(
113        "\"content\":{}",
114        json_string(&envelope.body.content)
115    ));
116    if let Some(correlation_id) = &envelope.body.correlation_id {
117        body_parts.push(format!("\"correlationId\":{}", json_string(correlation_id)));
118    }
119    body_parts.push(format!("\"intent\":{}", json_string(&envelope.body.intent)));
120
121    let mut header_parts: Vec<String> = vec![
122        format!("\"messageId\":{}", json_string(&envelope.header.message_id)),
123        format!("\"nonce\":{}", json_string(&envelope.header.nonce)),
124    ];
125    if let Some(recipient) = &envelope.header.recipient {
126        header_parts.push(format!("\"recipient\":{}", json_string(recipient)));
127    }
128    header_parts.push(format!(
129        "\"sender\":{}",
130        json_string(&envelope.header.sender)
131    ));
132    header_parts.push(format!("\"timestampMs\":{}", envelope.header.timestamp_ms));
133    header_parts.push(format!("\"ttlMs\":{}", envelope.header.ttl_ms));
134    header_parts.push(format!(
135        "\"version\":{}",
136        json_string(&envelope.header.version)
137    ));
138
139    format!(
140        "{{\"body\":{{{}}},\"header\":{{{}}}}}",
141        body_parts.join(","),
142        header_parts.join(",")
143    )
144}
145
146/// Cryptographically secure random nonce (96 bits, hex-encoded).
147/// Nonces back replay protection, so they must come from the OS CSPRNG —
148/// never a timestamp or a non-cryptographic PRNG.
149pub fn random_nonce() -> String {
150    let mut buf = [0u8; 12];
151    // getrandom 0.3 renamed the free `getrandom()` fill function to `fill()`.
152    getrandom::fill(&mut buf).expect("OS RNG should be available");
153    buf.iter().map(|b| format!("{b:02x}")).collect()
154}
155
156pub fn sign_canonical_payload_hmac(canonical_payload: &str, secret: &str) -> String {
157    let mut mac = HmacSha256::new_from_slice(secret.as_bytes()).expect("HMAC key should be valid");
158    mac.update(canonical_payload.as_bytes());
159    let digest = mac.finalize().into_bytes();
160    URL_SAFE_NO_PAD.encode(digest)
161}
162
163pub fn verify_canonical_payload_hmac(
164    canonical_payload: &str,
165    signature: &str,
166    secret: &str,
167) -> bool {
168    let Ok(signature_bytes) = URL_SAFE_NO_PAD.decode(signature) else {
169        return false;
170    };
171    let mut mac = HmacSha256::new_from_slice(secret.as_bytes()).expect("HMAC key should be valid");
172    mac.update(canonical_payload.as_bytes());
173    // verify_slice performs a constant-time comparison; a plain `==` on the
174    // encoded strings would leak matching-prefix length as a timing oracle.
175    mac.verify_slice(&signature_bytes).is_ok()
176}
177
178pub fn sign_canonical_payload_ed25519(
179    canonical_payload: &str,
180    private_key_pkcs8_base64url: &str,
181) -> Result<String, String> {
182    let mut private_der = URL_SAFE_NO_PAD
183        .decode(private_key_pkcs8_base64url)
184        .map_err(|_| "Invalid ED25519 private key encoding".to_string())?;
185    // Wipe the decoded PKCS8 bytes before returning on either path — the
186    // SigningKey keeps its own copy and zeroizes it on drop.
187    let parsed = SigningKey::from_pkcs8_der(&private_der);
188    private_der.zeroize();
189    let signing_key = parsed.map_err(|_| "Invalid ED25519 private key".to_string())?;
190    let signature = signing_key.sign(canonical_payload.as_bytes());
191    Ok(URL_SAFE_NO_PAD.encode(signature.to_bytes()))
192}
193
194pub fn verify_canonical_payload_ed25519(
195    canonical_payload: &str,
196    signature_base64url: &str,
197    public_key_spki_base64url: &str,
198) -> Result<bool, String> {
199    let public_der = URL_SAFE_NO_PAD
200        .decode(public_key_spki_base64url)
201        .map_err(|_| "Invalid ED25519 public key encoding".to_string())?;
202    let verifying_key = VerifyingKey::from_public_key_der(&public_der)
203        .map_err(|_| "Invalid ED25519 public key".to_string())?;
204
205    let signature_raw = URL_SAFE_NO_PAD
206        .decode(signature_base64url)
207        .map_err(|_| "Invalid ED25519 signature encoding".to_string())?;
208    let signature = Ed25519Signature::from_slice(&signature_raw)
209        .map_err(|_| "Invalid ED25519 signature".to_string())?;
210
211    Ok(verifying_key
212        .verify(canonical_payload.as_bytes(), &signature)
213        .is_ok())
214}
215
216pub fn sign_envelope_hmac(
217    envelope: &ProtocolEnvelope,
218    secret: &str,
219    key_id: &str,
220) -> ProtocolEnvelope {
221    let mut unsigned = envelope.clone();
222    unsigned.signature = None;
223    let canonical = canonicalize_envelope(&unsigned);
224    let signature = sign_canonical_payload_hmac(&canonical, secret);
225    let mut signed = unsigned;
226    signed.signature = Some(ProtocolSignature {
227        alg: "HS256".to_string(),
228        key_id: key_id.to_string(),
229        value: signature,
230    });
231    signed
232}
233
234pub fn verify_envelope_hmac(envelope: &ProtocolEnvelope, secret: &str) -> bool {
235    let Some(signature) = &envelope.signature else {
236        return false;
237    };
238    if signature.alg != "HS256" {
239        return false;
240    }
241    let mut unsigned = envelope.clone();
242    unsigned.signature = None;
243    let canonical = canonicalize_envelope(&unsigned);
244    verify_canonical_payload_hmac(&canonical, &signature.value, secret)
245}
246
247pub fn sign_envelope_ed25519(
248    envelope: &ProtocolEnvelope,
249    private_key_pkcs8_base64url: &str,
250    key_id: &str,
251) -> Result<ProtocolEnvelope, String> {
252    let mut unsigned = envelope.clone();
253    unsigned.signature = None;
254    let canonical = canonicalize_envelope(&unsigned);
255    let signature = sign_canonical_payload_ed25519(&canonical, private_key_pkcs8_base64url)?;
256    let mut signed = unsigned;
257    signed.signature = Some(ProtocolSignature {
258        alg: "ED25519".to_string(),
259        key_id: key_id.to_string(),
260        value: signature,
261    });
262    Ok(signed)
263}
264
265pub fn verify_envelope_ed25519(
266    envelope: &ProtocolEnvelope,
267    public_key_spki_base64url: &str,
268) -> Result<bool, String> {
269    let Some(signature) = &envelope.signature else {
270        return Ok(false);
271    };
272    if signature.alg != "ED25519" {
273        return Ok(false);
274    }
275    let mut unsigned = envelope.clone();
276    unsigned.signature = None;
277    let canonical = canonicalize_envelope(&unsigned);
278    verify_canonical_payload_ed25519(&canonical, &signature.value, public_key_spki_base64url)
279}
280
281pub fn encode_envelope_compact(envelope: &ProtocolEnvelope) -> String {
282    let compact = CompactEnvelope {
283        v: envelope.header.version.clone(),
284        mid: envelope.header.message_id.clone(),
285        ts: envelope.header.timestamp_ms,
286        ttl: envelope.header.ttl_ms,
287        s: envelope.header.sender.clone(),
288        n: envelope.header.nonce.clone(),
289        i: envelope.body.intent.clone(),
290        c: envelope.body.content.clone(),
291        r: envelope.header.recipient.clone(),
292        cap: envelope.body.capability.clone(),
293        cid: envelope.body.correlation_id.clone(),
294        sig: envelope.signature.as_ref().map(|sig| CompactSignature {
295            a: Some(sig.alg.clone()),
296            k: sig.key_id.clone(),
297            v: sig.value.clone(),
298        }),
299    };
300    serde_json::to_string(&compact).expect("compact envelope serialization should not fail")
301}
302
303pub fn decode_envelope(raw: &str) -> Result<ProtocolEnvelope, String> {
304    let parsed: Value =
305        serde_json::from_str(raw).map_err(|_| "Invalid JSON payload".to_string())?;
306
307    if parsed.get("header").is_some() && parsed.get("body").is_some() {
308        return serde_json::from_value(parsed)
309            .map_err(|_| "Envelope JSON shape is not recognized".to_string());
310    }
311
312    let compact: CompactEnvelope = serde_json::from_value(parsed)
313        .map_err(|_| "Envelope JSON shape is not recognized".to_string())?;
314    if compact.v != "7h3/0.1" {
315        return Err("Envelope JSON shape is not recognized".to_string());
316    }
317
318    Ok(ProtocolEnvelope {
319        header: ProtocolHeader {
320            version: compact.v,
321            message_id: compact.mid,
322            timestamp_ms: compact.ts,
323            ttl_ms: compact.ttl,
324            sender: compact.s,
325            recipient: compact.r,
326            nonce: compact.n,
327        },
328        body: ProtocolBody {
329            intent: compact.i,
330            content: compact.c,
331            capability: compact.cap,
332            correlation_id: compact.cid,
333        },
334        signature: compact.sig.map(|sig| ProtocolSignature {
335            alg: sig.a.unwrap_or_else(|| "HS256".to_string()),
336            key_id: sig.k,
337            value: sig.v,
338        }),
339    })
340}
341
342pub fn validate_envelope(
343    envelope: &ProtocolEnvelope,
344    now_ms: Option<i64>,
345) -> Vec<ProtocolDiagnostic> {
346    let mut diagnostics: Vec<ProtocolDiagnostic> = Vec::new();
347
348    if envelope.header.version != "7h3/0.1" {
349        diagnostics.push(ProtocolDiagnostic {
350            level: "error".to_string(),
351            message: format!("Unsupported protocol version '{}'", envelope.header.version),
352        });
353    }
354    if envelope.header.message_id.trim().is_empty() {
355        diagnostics.push(ProtocolDiagnostic {
356            level: "error".to_string(),
357            message: "Missing messageId".to_string(),
358        });
359    }
360    if envelope.header.sender.trim().is_empty() {
361        diagnostics.push(ProtocolDiagnostic {
362            level: "error".to_string(),
363            message: "Missing sender identity".to_string(),
364        });
365    }
366    if envelope.header.nonce.trim().is_empty() {
367        diagnostics.push(ProtocolDiagnostic {
368            level: "error".to_string(),
369            message: "Missing nonce — replay protection requires a unique nonce per message"
370                .to_string(),
371        });
372    }
373    if envelope.header.ttl_ms <= 0 {
374        diagnostics.push(ProtocolDiagnostic {
375            level: "error".to_string(),
376            message: "ttlMs must be greater than zero".to_string(),
377        });
378    }
379    if envelope.header.ttl_ms > MAX_TTL_MS {
380        diagnostics.push(ProtocolDiagnostic {
381            level: "error".to_string(),
382            message: format!("ttlMs exceeds maximum allowed {MAX_TTL_MS} ms"),
383        });
384    }
385    if let Some(now) = now_ms {
386        if envelope.header.timestamp_ms > now + MAX_CLOCK_SKEW_MS {
387            diagnostics.push(ProtocolDiagnostic {
388                level: "error".to_string(),
389                message: format!("timestampMs is more than {MAX_CLOCK_SKEW_MS} ms in the future"),
390            });
391        }
392        if envelope.header.timestamp_ms + envelope.header.ttl_ms < now {
393            diagnostics.push(ProtocolDiagnostic {
394                level: "error".to_string(),
395                message: "Message TTL expired".to_string(),
396            });
397        }
398    }
399    if envelope.body.content.trim().is_empty() {
400        diagnostics.push(ProtocolDiagnostic {
401            level: "warning".to_string(),
402            message: "Empty content payload".to_string(),
403        });
404    }
405
406    diagnostics
407}
408
409#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
410#[serde(untagged)]
411pub enum JsonRpcId {
412    Null,
413    String(String),
414    Number(i64),
415}
416
417impl JsonRpcId {
418    fn as_string(&self) -> String {
419        match self {
420            JsonRpcId::Null => "null".to_string(),
421            JsonRpcId::String(value) => value.clone(),
422            JsonRpcId::Number(value) => value.to_string(),
423        }
424    }
425}
426
427#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
428pub struct JsonRpcRequestLike {
429    pub jsonrpc: String,
430    pub id: JsonRpcId,
431    pub method: String,
432    #[serde(skip_serializing_if = "Option::is_none")]
433    pub params: Option<Value>,
434}
435
436#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
437pub struct JsonRpcError {
438    pub code: i64,
439    pub message: String,
440    #[serde(skip_serializing_if = "Option::is_none")]
441    pub data: Option<Value>,
442}
443
444#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
445pub struct JsonRpcResponseLike {
446    pub jsonrpc: String,
447    pub id: JsonRpcId,
448    #[serde(skip_serializing_if = "Option::is_none")]
449    pub result: Option<Value>,
450    #[serde(skip_serializing_if = "Option::is_none")]
451    pub error: Option<JsonRpcError>,
452}
453
454#[derive(Debug, Clone, PartialEq, Eq)]
455pub struct JsonRpcPolicyContext {
456    pub intent: String,
457    pub recipient: Option<String>,
458    pub capability: String,
459    pub correlation_id: String,
460    pub created_at_ms: i64,
461}
462
463#[derive(Debug, Clone)]
464pub struct JsonRpcBridgeConfig {
465    pub recipient: Option<String>,
466    pub allowed_methods: Option<Vec<String>>,
467    pub capability_prefix: String,
468}
469
470impl Default for JsonRpcBridgeConfig {
471    fn default() -> Self {
472        Self {
473            recipient: None,
474            allowed_methods: None,
475            capability_prefix: "mcp.".to_string(),
476        }
477    }
478}
479
480pub fn create_envelope(
481    sender: &str,
482    recipient: Option<&str>,
483    intent: &str,
484    content: &str,
485    capability: Option<&str>,
486    correlation_id: Option<&str>,
487    now_ms: i64,
488    ttl_ms: i64,
489) -> ProtocolEnvelope {
490    ProtocolEnvelope {
491        header: ProtocolHeader {
492            version: "7h3/0.1".to_string(),
493            message_id: format!("msg-{}-{}", now_ms, sender),
494            timestamp_ms: now_ms,
495            ttl_ms,
496            sender: sender.to_string(),
497            recipient: recipient.map(|value| value.to_string()),
498            nonce: random_nonce(),
499        },
500        body: ProtocolBody {
501            intent: intent.to_string(),
502            content: content.to_string(),
503            capability: capability.map(|value| value.to_string()),
504            correlation_id: correlation_id.map(|value| value.to_string()),
505        },
506        signature: None,
507    }
508}
509
510pub fn create_signed_task_from_jsonrpc<F, G>(
511    request: &JsonRpcRequestLike,
512    sender: &str,
513    secret: &str,
514    key_id: &str,
515    now_ms: i64,
516    config: &JsonRpcBridgeConfig,
517    authorize: Option<F>,
518    rate_limit: Option<G>,
519) -> Result<ProtocolEnvelope, String>
520where
521    F: Fn(&JsonRpcRequestLike, &JsonRpcPolicyContext) -> bool,
522    G: Fn(&str, &JsonRpcRequestLike, &JsonRpcPolicyContext) -> bool,
523{
524    if request.jsonrpc != "2.0" {
525        return Err("JSON-RPC request must have jsonrpc='2.0'".to_string());
526    }
527    if request.method.trim().is_empty() {
528        return Err("JSON-RPC request must include method".to_string());
529    }
530    if let Some(allowlist) = &config.allowed_methods {
531        if !allowlist.iter().any(|method| method == &request.method) {
532            return Err(format!(
533                "JSON-RPC method '{}' is not allowed",
534                request.method
535            ));
536        }
537    }
538
539    let correlation_id = request.id.as_string();
540    let capability = format!("{}{}", config.capability_prefix, request.method);
541    let context = JsonRpcPolicyContext {
542        intent: "TASK".to_string(),
543        recipient: config.recipient.clone(),
544        capability: capability.clone(),
545        correlation_id: correlation_id.clone(),
546        created_at_ms: now_ms,
547    };
548
549    if let Some(authorize_fn) = authorize {
550        if !authorize_fn(request, &context) {
551            return Err(format!(
552                "JSON-RPC method '{}' is not authorized",
553                request.method
554            ));
555        }
556    }
557
558    let rate_key = request.method.clone();
559    if let Some(rate_limit_fn) = rate_limit {
560        if !rate_limit_fn(&rate_key, request, &context) {
561            return Err(format!(
562                "JSON-RPC method '{}' is rate-limited",
563                request.method
564            ));
565        }
566    }
567
568    let content = json_string(&serde_json::json!({
569        "method": request.method,
570        "params": request.params.clone().unwrap_or(Value::Null),
571    }));
572    let envelope = create_envelope(
573        sender,
574        config.recipient.as_deref(),
575        "TASK",
576        &content,
577        Some(&capability),
578        Some(&correlation_id),
579        now_ms,
580        60_000,
581    );
582    Ok(sign_envelope_hmac(&envelope, secret, key_id))
583}
584
585pub fn jsonrpc_response_from_envelope(
586    envelope: &ProtocolEnvelope,
587    id: JsonRpcId,
588) -> JsonRpcResponseLike {
589    if envelope.body.intent == "ERROR" {
590        return JsonRpcResponseLike {
591            jsonrpc: "2.0".to_string(),
592            id,
593            result: None,
594            error: Some(JsonRpcError {
595                code: -32000,
596                message: envelope.body.content.clone(),
597                data: Some(serde_json::json!({
598                    "capability": envelope.body.capability,
599                    "correlationId": envelope.body.correlation_id,
600                })),
601            }),
602        };
603    }
604
605    let result = serde_json::from_str::<Value>(&envelope.body.content)
606        .unwrap_or_else(|_| Value::String(envelope.body.content.clone()));
607    JsonRpcResponseLike {
608        jsonrpc: "2.0".to_string(),
609        id,
610        result: Some(result),
611        error: None,
612    }
613}
614
615#[derive(Debug, Clone)]
616pub struct AipMcpGatewayOptions {
617    pub shared_secret: String,
618    pub gateway_agent_id: String,
619    pub worker_agent_id: String,
620    pub allowed_methods: Vec<String>,
621    pub capability_prefix: String,
622}
623
624impl Default for AipMcpGatewayOptions {
625    fn default() -> Self {
626        Self {
627            shared_secret: "mcp-gateway-secret".to_string(),
628            gateway_agent_id: "agent.gateway".to_string(),
629            worker_agent_id: "agent.worker".to_string(),
630            allowed_methods: vec![
631                "tools/call".to_string(),
632                "resources/read".to_string(),
633                "prompts/get".to_string(),
634            ],
635            capability_prefix: "mcp.".to_string(),
636        }
637    }
638}
639
640#[derive(Debug, Clone)]
641pub struct AipMcpGatewayRuntime {
642    options: AipMcpGatewayOptions,
643}
644
645pub fn create_aip_mcp_gateway_runtime(options: AipMcpGatewayOptions) -> AipMcpGatewayRuntime {
646    AipMcpGatewayRuntime { options }
647}
648
649impl AipMcpGatewayRuntime {
650    fn error_response(id: Option<JsonRpcId>, code: i64, message: &str) -> String {
651        let response = JsonRpcResponseLike {
652            jsonrpc: "2.0".to_string(),
653            id: id.unwrap_or(JsonRpcId::Null),
654            result: None,
655            error: Some(JsonRpcError {
656                code,
657                message: message.to_string(),
658                data: None,
659            }),
660        };
661        json_string(&response)
662    }
663
664    pub fn handle_line(&self, line: &str, now_ms: i64) -> Option<String> {
665        let raw = line.trim();
666        if raw.is_empty() {
667            return None;
668        }
669
670        let request: JsonRpcRequestLike = match serde_json::from_str(raw) {
671            Ok(parsed) => parsed,
672            Err(_) => {
673                return Some(Self::error_response(None, -32600, "Invalid Request"));
674            }
675        };
676
677        let bridge_config = JsonRpcBridgeConfig {
678            recipient: Some(self.options.worker_agent_id.clone()),
679            allowed_methods: Some(self.options.allowed_methods.clone()),
680            capability_prefix: self.options.capability_prefix.clone(),
681        };
682
683        let outbound = match create_signed_task_from_jsonrpc(
684            &request,
685            &self.options.gateway_agent_id,
686            &self.options.shared_secret,
687            "gateway-k1",
688            now_ms,
689            &bridge_config,
690            Option::<fn(&JsonRpcRequestLike, &JsonRpcPolicyContext) -> bool>::None,
691            Option::<fn(&str, &JsonRpcRequestLike, &JsonRpcPolicyContext) -> bool>::None,
692        ) {
693            Ok(envelope) => envelope,
694            Err(message) => {
695                let code = if message.contains("not allowed") {
696                    -32601
697                } else if message.contains("not authorized") {
698                    -32001
699                } else if message.contains("rate-limited") {
700                    -32002
701                } else {
702                    -32603
703                };
704                return Some(Self::error_response(Some(request.id), code, &message));
705            }
706        };
707
708        let worker_payload = serde_json::json!({
709            "ok": true,
710            "capability": outbound.body.capability,
711            "content": outbound.body.content,
712        });
713        let worker_envelope = create_envelope(
714            &self.options.worker_agent_id,
715            Some(&self.options.gateway_agent_id),
716            "RESULT",
717            &json_string(&worker_payload),
718            outbound.body.capability.as_deref(),
719            outbound.body.correlation_id.as_deref(),
720            now_ms,
721            60_000,
722        );
723        let signed_worker =
724            sign_envelope_hmac(&worker_envelope, &self.options.shared_secret, "worker-k1");
725
726        if !verify_envelope_hmac(&signed_worker, &self.options.shared_secret) {
727            return Some(Self::error_response(
728                Some(request.id),
729                -32603,
730                "AIP verification failed",
731            ));
732        }
733
734        let response = jsonrpc_response_from_envelope(&signed_worker, request.id);
735        Some(json_string(&response))
736    }
737}