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