hyperlane-plugin-mcp 23.3.2

A Model Context Protocol (MCP) Streamable HTTP server plugin for the Hyperlane framework with tool, resource, and prompt registries, session lifecycle management, DNS-rebinding Origin validation, and an opt-in ServerHook.
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
use super::*;

/// Borrows the last value of a lowercased HTTP request header without heap allocation.
///
/// # Arguments
///
/// - `&'a Request` - Incoming HTTP request.
/// - `&str` - Lowercased header key name.
///
/// # Returns
///
/// - `Option<&'a str>` - Borrowed last header value, if present.
#[inline(always)]
pub(crate) fn request_header_back<'a>(req: &'a Request, lower_key: &str) -> Option<&'a str> {
    req.get_headers()
        .get(lower_key)
        .and_then(|values: &VecDeque<String>| values.back())
        .map(String::as_str)
}

/// Decodes a minted MCP session identifier (`"mcp-sess-"` + 32 lowercase hex digits) into its 128-bit key.
///
/// # Arguments
///
/// - `&str` - Candidate session identifier from the `Mcp-Session-Id` header.
///
/// # Returns
///
/// - `Option<u128>` - Decoded 128-bit session key, or `None` if malformed.
#[inline(always)]
pub(crate) fn parse_mcp_session_key(session_id: &str) -> Option<u128> {
    let bytes: &[u8] = session_id.as_bytes();
    if bytes.len() != MCP_SESSION_ID_LEN || !bytes.starts_with(MCP_SESSION_PREFIX.as_bytes()) {
        return None;
    }
    let hex: &[u8] = &bytes[MCP_SESSION_PREFIX.len()..];
    let (chunks, _): (&[[u8; 4]], &[u8]) = hex.as_chunks::<4>();
    let mut hi: u64 = 0;
    let mut lo: u64 = 0;
    let mut err: u8 = 0;
    for chunk in &chunks[..4] {
        let a: u8 = MCP_HEX_DECODE_LUT[chunk[0] as usize];
        let b: u8 = MCP_HEX_DECODE_LUT[chunk[1] as usize];
        let c: u8 = MCP_HEX_DECODE_LUT[chunk[2] as usize];
        let d: u8 = MCP_HEX_DECODE_LUT[chunk[3] as usize];
        err |= (a | b) | (c | d);
        hi = (hi << 16)
            | (u64::from(a & 0x0F) << 12)
            | (u64::from(b & 0x0F) << 8)
            | (u64::from(c & 0x0F) << 4)
            | u64::from(d & 0x0F);
    }
    for chunk in &chunks[4..8] {
        let a: u8 = MCP_HEX_DECODE_LUT[chunk[0] as usize];
        let b: u8 = MCP_HEX_DECODE_LUT[chunk[1] as usize];
        let c: u8 = MCP_HEX_DECODE_LUT[chunk[2] as usize];
        let d: u8 = MCP_HEX_DECODE_LUT[chunk[3] as usize];
        err |= (a | b) | (c | d);
        lo = (lo << 16)
            | (u64::from(a & 0x0F) << 12)
            | (u64::from(b & 0x0F) << 8)
            | (u64::from(c & 0x0F) << 4)
            | u64::from(d & 0x0F);
    }
    if (err & 0xF0) != 0 {
        return None;
    }
    Some((u128::from(hi) << 64) | u128::from(lo))
}

/// Computes the shard index for a decoded 128-bit MCP session key in O(1) time.
///
/// # Arguments
///
/// - `u128` - Decoded 128-bit session key.
///
/// # Returns
///
/// - `usize` - Shard index in `0..MCP_SESSION_SHARD_COUNT`.
#[inline(always)]
pub(crate) fn mcp_session_shard_index(session_key: u128) -> usize {
    (((session_key as u64) ^ ((session_key >> 64) as u64)) as usize) & (MCP_SESSION_SHARD_COUNT - 1)
}

/// Applies one SplitMix64 avalanche step to `x`.
///
/// # Arguments
///
/// - `u64` - Input state value.
///
/// # Returns
///
/// - `u64` - Mixed 64-bit output.
#[inline(always)]
pub(crate) fn mix_splitmix64(mut x: u64) -> u64 {
    x = (x ^ (x >> 30)).wrapping_mul(SPLITMIX_MUL1);
    x = (x ^ (x >> 27)).wrapping_mul(SPLITMIX_MUL2);
    x ^ (x >> 31)
}

/// Generates a process-unique 64-bit seed from wall-clock nanoseconds, PID, and stack ASLR entropy.
///
/// # Returns
///
/// - `u64` - Non-trivial per-registry entropy seed.
pub(crate) fn mcp_random_seed() -> u64 {
    let nanos: u128 = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|dur: Duration| dur.as_nanos())
        .unwrap_or(0);
    let pid: u64 = process::id() as u64;
    let stack_probe: u64 = (&nanos as *const u128) as usize as u64;
    let mixed: u64 =
        (nanos as u64) ^ ((nanos >> 64) as u64).rotate_left(17) ^ pid.rotate_left(33) ^ stack_probe;
    mix_splitmix64(mixed.wrapping_add(SPLITMIX_GAMMA))
}

/// Mints an unpredictable 128-bit session key and formatted string identifier via stack hex encoding.
///
/// # Arguments
///
/// - `u64` - Registry entropy seed.
/// - `u64` - Monotonic sequence number.
/// - `u64` - Monotonic nanosecond entropy sample.
///
/// # Returns
///
/// - `(u128, String)` - Compact 128-bit session key paired with its formatted header string.
#[inline]
pub(crate) fn mint_mcp_session_id(seed: u64, seq: u64, nanos: u64) -> (u128, String) {
    let hi: u64 =
        mix_splitmix64(seed.wrapping_add(seq.wrapping_mul(SPLITMIX_GAMMA)) ^ nanos.rotate_left(13));
    let lo: u64 = mix_splitmix64(hi.wrapping_add(SPLITMIX_GAMMA) ^ seq.rotate_left(29));
    let key: u128 = (u128::from(hi) << 64) | u128::from(lo);
    let prefix: &[u8] = MCP_SESSION_PREFIX.as_bytes();
    let mut stack: [u8; MCP_SESSION_ID_LEN] = [0u8; MCP_SESSION_ID_LEN];
    stack[..prefix.len()].copy_from_slice(prefix);
    let mut pos: usize = prefix.len();
    for byte in hi.to_be_bytes() {
        stack[pos] = MCP_HEX_DIGITS[(byte >> 4) as usize];
        stack[pos + 1] = MCP_HEX_DIGITS[(byte & 0x0F) as usize];
        pos += 2;
    }
    for byte in lo.to_be_bytes() {
        stack[pos] = MCP_HEX_DIGITS[(byte >> 4) as usize];
        stack[pos + 1] = MCP_HEX_DIGITS[(byte & 0x0F) as usize];
        pos += 2;
    }
    let id: String = from_utf8(&stack).unwrap_or_default().to_owned();
    (key, id)
}

/// Appends an unsigned 64-bit integer in ASCII decimal directly into `out`.
///
/// # Arguments
///
/// - `u64` - Non-negative integer to format.
/// - `&mut Vec<u8>` - Destination byte buffer.
#[inline]
pub(crate) fn push_u64_json(mut val: u64, out: &mut Vec<u8>) {
    let mut digits: [u8; 20] = [0u8; 20];
    let mut pos: usize = 20;
    while val >= 100 {
        let pair: usize = ((val % 100) as usize) * 2;
        val /= 100;
        pos -= 2;
        digits[pos] = MCP_DEC_DIGITS_LUT[pair];
        digits[pos + 1] = MCP_DEC_DIGITS_LUT[pair + 1];
    }
    if val < 10 {
        pos -= 1;
        digits[pos] = ASCII_ZERO + (val as u8);
    } else {
        let pair: usize = (val as usize) * 2;
        pos -= 2;
        digits[pos] = MCP_DEC_DIGITS_LUT[pair];
        digits[pos + 1] = MCP_DEC_DIGITS_LUT[pair + 1];
    }
    out.extend_from_slice(&digits[pos..]);
}

/// Appends a signed 64-bit integer in ASCII decimal directly into `out`.
///
/// # Arguments
///
/// - `i64` - Signed integer to format.
/// - `&mut Vec<u8>` - Destination byte buffer.
#[inline]
pub(crate) fn push_i64_json(val: i64, out: &mut Vec<u8>) {
    if val < 0 {
        out.push(ASCII_MINUS);
    }
    push_u64_json(val.unsigned_abs(), out);
}

/// Appends a JSON-quoted string directly into `out`, falling back to `serde_json` only when escaping is needed.
///
/// # Arguments
///
/// - `&str` - String value to serialize.
/// - `&mut Vec<u8>` - Destination byte buffer.
#[inline]
pub(crate) fn push_json_str_fast(s: &str, out: &mut Vec<u8>) {
    let bytes: &[u8] = s.as_bytes();
    if !bytes
        .iter()
        .any(|&b: &u8| b < 0x20 || b == ASCII_QUOTE || b == ASCII_BACKSLASH)
    {
        out.push(ASCII_QUOTE);
        out.extend_from_slice(bytes);
        out.push(ASCII_QUOTE);
        return;
    }
    if to_writer(&mut *out, s).is_err() {
        out.extend_from_slice(MCP_JSON_NULL);
    }
}

/// Appends the serialized JSON representation of [`McpRpcId`] directly into `out`.
///
/// # Arguments
///
/// - `&McpRpcId<'_>` - Request correlation identifier.
/// - `&mut Vec<u8>` - Destination byte buffer.
#[inline]
pub(crate) fn push_mcp_id_json(id: &McpRpcId<'_>, out: &mut Vec<u8>) {
    match id {
        McpRpcId::Null => out.extend_from_slice(MCP_JSON_NULL),
        McpRpcId::U64(n) => push_u64_json(*n, out),
        McpRpcId::I64(n) => push_i64_json(*n, out),
        McpRpcId::Str(s) => push_json_str_fast(s.as_ref(), out),
        McpRpcId::Other(v) => {
            if to_writer(&mut *out, v).is_err() {
                out.extend_from_slice(MCP_JSON_NULL);
            }
        }
    }
}

/// Builds a standard MCP text content block `{"type": "text", "text": text}`.
///
/// # Arguments
///
/// - `String` - Plain-text content payload.
///
/// # Returns
///
/// - `Value` - Constructed text content JSON object.
#[inline]
pub(crate) fn mcp_text_content(text: String) -> Value {
    let mut map: Map<String, Value> = Map::with_capacity(2);
    map.insert(KEY_TYPE.to_owned(), Value::String(KEY_TEXT.to_owned()));
    map.insert(KEY_TEXT.to_owned(), Value::String(text));
    Value::Object(map)
}

/// Formats a JSON-RPC 2.0 error envelope directly into a single exact-sized `Vec<u8>`.
///
/// # Arguments
///
/// - `&McpRpcId<'_>` - Request correlation identifier (`McpRpcId::Null` if unavailable).
/// - `i64` - JSON-RPC error code.
/// - `&str` - Human-readable error message.
///
/// # Returns
///
/// - `Vec<u8>` - Serialized JSON-RPC error response.
#[inline]
pub(crate) fn mcp_json_error(id: &McpRpcId<'_>, code: i64, message: &str) -> Vec<u8> {
    let mut out: Vec<u8> = Vec::with_capacity(64 + message.len());
    out.extend_from_slice(MCP_WIRE_ENVELOPE_PREFIX);
    push_mcp_id_json(id, &mut out);
    out.extend_from_slice(MCP_WIRE_ERROR_CODE_SEP);
    push_i64_json(code, &mut out);
    out.extend_from_slice(MCP_WIRE_ERROR_MSG_SEP);
    push_json_str_fast(message, &mut out);
    out.extend_from_slice(MCP_WIRE_ERROR_SUFFIX);
    out
}

/// Formats a JSON-RPC 2.0 `ping` success envelope `{"jsonrpc":"2.0","id":<id>,"result":{}}` in one allocation.
///
/// # Arguments
///
/// - `&McpRpcId<'_>` - Request correlation identifier.
///
/// # Returns
///
/// - `Vec<u8>` - Serialized JSON-RPC ping response.
#[inline]
pub(crate) fn mcp_json_ping(id: &McpRpcId<'_>) -> Vec<u8> {
    let mut out: Vec<u8> = Vec::with_capacity(48);
    out.extend_from_slice(MCP_WIRE_ENVELOPE_PREFIX);
    push_mcp_id_json(id, &mut out);
    out.extend_from_slice(MCP_WIRE_PING_SUFFIX);
    out
}

/// Formats a JSON-RPC 2.0 success envelope wrapping pre-serialized `result_json` bytes in one allocation.
///
/// # Arguments
///
/// - `&McpRpcId<'_>` - Request correlation identifier.
/// - `&[u8]` - Pre-serialized JSON bytes for the `"result"` value.
///
/// # Returns
///
/// - `Vec<u8>` - Serialized JSON-RPC success response.
#[inline]
pub(crate) fn mcp_json_raw_result(id: &McpRpcId<'_>, result_json: &[u8]) -> Vec<u8> {
    let mut out: Vec<u8> = Vec::with_capacity(44 + result_json.len());
    out.extend_from_slice(MCP_WIRE_ENVELOPE_PREFIX);
    push_mcp_id_json(id, &mut out);
    out.extend_from_slice(MCP_WIRE_RESULT_SEP);
    out.extend_from_slice(result_json);
    out.push(ASCII_RBRACE);
    out
}

/// Formats a JSON-RPC 2.0 `initialize` success response directly into one pre-sized `Vec<u8>`.
///
/// # Arguments
///
/// - `&McpRpcId<'_>` - Request correlation identifier.
/// - `&McpServerConfig` - Server metadata configuration.
///
/// # Returns
///
/// - `Vec<u8>` - Serialized JSON-RPC `initialize` response.
#[inline]
pub(crate) fn mcp_json_initialize(id: &McpRpcId<'_>, config: &McpServerConfig) -> Vec<u8> {
    let proto: &str = config.get_protocol_version().as_str();
    let name: &str = config.get_name().as_str();
    let version: &str = config.get_version().as_str();
    let cap: usize = MCP_WIRE_ENVELOPE_PREFIX.len()
        + MCP_WIRE_RESULT_SEP.len()
        + MCP_WIRE_INIT_PROTO.len()
        + MCP_WIRE_INIT_CAPS_NAME.len()
        + MCP_WIRE_INIT_VERSION.len()
        + MCP_WIRE_INIT_SUFFIX.len()
        + 32
        + proto.len()
        + name.len()
        + version.len();
    let mut out: Vec<u8> = Vec::with_capacity(cap);
    out.extend_from_slice(MCP_WIRE_ENVELOPE_PREFIX);
    push_mcp_id_json(id, &mut out);
    out.extend_from_slice(MCP_WIRE_RESULT_SEP);
    out.extend_from_slice(MCP_WIRE_INIT_PROTO);
    push_json_str_fast(proto, &mut out);
    out.extend_from_slice(MCP_WIRE_INIT_CAPS_NAME);
    push_json_str_fast(name, &mut out);
    out.extend_from_slice(MCP_WIRE_INIT_VERSION);
    push_json_str_fast(version, &mut out);
    out.extend_from_slice(MCP_WIRE_INIT_SUFFIX);
    out
}

/// Formats a JSON-RPC 2.0 success envelope for any serializable `result` directly into one `Vec<u8>`.
///
/// # Arguments
///
/// - `&McpRpcId<'_>` - Request correlation identifier.
/// - `T` - Typed serializable result payload.
///
/// # Returns
///
/// - `Vec<u8>` - Serialized JSON-RPC success response.
#[inline]
pub(crate) fn mcp_json_success<T>(id: &McpRpcId<'_>, result: T) -> Vec<u8>
where
    T: Serialize,
{
    let mut out: Vec<u8> = Vec::with_capacity(128);
    out.extend_from_slice(MCP_WIRE_ENVELOPE_PREFIX);
    push_mcp_id_json(id, &mut out);
    out.extend_from_slice(MCP_WIRE_RESULT_SEP);
    if to_writer(&mut out, &result).is_err() {
        out.extend_from_slice(MCP_JSON_NULL);
    }
    out.push(ASCII_RBRACE);
    out
}

/// Validates an incoming `Origin` header against `allowed_origins` to mitigate DNS rebinding.
///
/// # Arguments
///
/// - `Option<&str>` - Incoming `Origin` header value.
/// - `&[String]` - Configured allowed origins (empty allows all origins).
///
/// # Returns
///
/// - `bool` - `true` when the request origin is permitted.
#[inline]
pub(crate) fn is_origin_allowed(origin: Option<&str>, allowed_origins: &[String]) -> bool {
    if allowed_origins.is_empty() {
        return true;
    }
    let Some(value) = origin else {
        return true;
    };
    let trimmed: &str = value.trim();
    allowed_origins
        .iter()
        .any(|allowed: &String| allowed.eq_ignore_ascii_case(trimmed))
}