hen 0.16.0

Run protocol-aware API request collections from the command line or through MCP.
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
use std::{
    io::{Read, Write},
    net::{TcpListener, TcpStream},
    process::{Command, Stdio},
    sync::mpsc,
    thread,
    time::Duration,
};

use serde_json::Value;
use tokio_tungstenite::tungstenite::{accept, Message as WsFrame};

use crate::support::TestWorkspace;

pub(crate) fn spawn_http_server(status: u16, reason: &str, content_type: &str, body: &str) -> String {
    let listener = TcpListener::bind("127.0.0.1:0").expect("listener should bind");
    let address = listener.local_addr().expect("address should be available");
    let reason = reason.to_string();
    let content_type = content_type.to_string();
    let body = body.to_string();

    thread::spawn(move || {
        let (mut stream, _) = listener.accept().expect("connection should be accepted");
        let mut buffer = [0_u8; 1024];
        let _ = stream.read(&mut buffer);
        let response = format!(
            "HTTP/1.1 {status} {reason}\r\nContent-Type: {content_type}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
            body.len()
        );
        stream
            .write_all(response.as_bytes())
            .expect("response should be written");
    });

    format!("http://{}", address)
}

pub(crate) fn spawn_header_echo_server(header_name: &str) -> String {
    let listener = TcpListener::bind("127.0.0.1:0").expect("listener should bind");
    let address = listener.local_addr().expect("address should be available");
    let header_name = header_name.to_string();

    thread::spawn(move || {
        let (mut stream, _) = listener.accept().expect("connection should be accepted");
        let request = read_http_request(&mut stream);
        let header_value = request
            .lines()
            .find_map(|line| {
                let (name, value) = line.split_once(':')?;
                if name.trim().eq_ignore_ascii_case(&header_name) {
                    Some(value.trim().to_string())
                } else {
                    None
                }
            })
            .expect("expected request header to be present");
        let body = serde_json::json!({ "value": header_value }).to_string();

        write_http_response(
            &mut stream,
            200,
            "OK",
            Some("application/json"),
            &body,
        );
    });

    format!("http://{}", address)
}

pub(crate) fn spawn_mcp_http_server() -> String {
    let listener = TcpListener::bind("127.0.0.1:0").expect("listener should bind");
    let address = listener.local_addr().expect("address should be available");

    thread::spawn(move || {
        let (mut initialize_stream, _) = listener.accept().expect("initialize should connect");
        let initialize_request = read_http_request(&mut initialize_stream);
        let initialize_request_lower = initialize_request.to_ascii_lowercase();
        assert!(initialize_request_lower.contains("authorization: bearer test-token"));
        assert!(initialize_request.contains("\"method\":\"initialize\""));
        assert!(initialize_request.contains("\"protocolVersion\":\"2025-11-25\""));
        assert!(initialize_request.contains("\"name\":\"hen\""));
        assert!(initialize_request.contains(env!("CARGO_PKG_VERSION")));

        write_http_response(
            &mut initialize_stream,
            200,
            "OK",
            Some("application/json"),
            r#"{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":"2025-11-25","capabilities":{},"serverInfo":{"name":"fixture-mcp","version":"1.0.0"}}}"#,
        );

        let (mut initialized_stream, _) = listener.accept().expect("initialized notification should connect");
        let initialized_request = read_http_request(&mut initialized_stream);
        let initialized_request_lower = initialized_request.to_ascii_lowercase();
        assert!(initialized_request_lower.contains("authorization: bearer test-token"));
        assert!(initialized_request.contains("\"method\":\"notifications/initialized\""));

        write_http_response(&mut initialized_stream, 202, "Accepted", None, "");

        let (mut list_tools_stream, _) = listener.accept().expect("tools/list should connect");
        let list_tools_request = read_http_request(&mut list_tools_stream);
        let list_tools_request_lower = list_tools_request.to_ascii_lowercase();
        assert!(list_tools_request_lower.contains("authorization: bearer test-token"));
        assert!(list_tools_request.contains("\"method\":\"tools/list\""));

        write_http_response(
            &mut list_tools_stream,
            200,
            "OK",
            Some("application/json"),
            r#"{"jsonrpc":"2.0","id":2,"result":{"tools":[{"name":"search"}]}}"#,
        );

        let (mut list_resources_stream, _) = listener.accept().expect("resources/list should connect");
        let list_resources_request = read_http_request(&mut list_resources_stream);
        let list_resources_request_lower = list_resources_request.to_ascii_lowercase();
        assert!(list_resources_request_lower.contains("authorization: bearer test-token"));
        assert!(list_resources_request.contains("\"method\":\"resources/list\""));

        write_http_response(
            &mut list_resources_stream,
            200,
            "OK",
            Some("application/json"),
            r#"{"jsonrpc":"2.0","id":3,"result":{"resources":[{"uri":"file:///fixture.txt","name":"Fixture Resource"}]}}"#,
        );

        let (mut tool_call_stream, _) = listener.accept().expect("tools/call should connect");
        let tool_call_request = read_http_request(&mut tool_call_stream);
        let tool_call_request_lower = tool_call_request.to_ascii_lowercase();
        assert!(tool_call_request_lower.contains("authorization: bearer test-token"));
        assert!(tool_call_request.contains("\"method\":\"tools/call\""));
        assert!(tool_call_request.contains("\"name\":\"search\""));
        assert!(tool_call_request.contains("\"query\":\"hedgehog\""));

        write_http_response(
            &mut tool_call_stream,
            200,
            "OK",
            Some("application/json"),
            r#"{"jsonrpc":"2.0","id":4,"result":{"content":[{"type":"text","text":"search result"}]}}"#,
        );
    });

    format!("http://{}", address)
}

pub(crate) fn spawn_mcp_protocol_error_server() -> String {
    let listener = TcpListener::bind("127.0.0.1:0").expect("listener should bind");
    let address = listener.local_addr().expect("address should be available");

    thread::spawn(move || {
        let (mut initialize_stream, _) = listener.accept().expect("initialize should connect");
        let initialize_request = read_http_request(&mut initialize_stream);
        let initialize_request_lower = initialize_request.to_ascii_lowercase();
        assert!(initialize_request_lower.contains("authorization: bearer test-token"));
        assert!(initialize_request.contains("\"method\":\"initialize\""));

        write_http_response(
            &mut initialize_stream,
            200,
            "OK",
            Some("application/json"),
            r#"{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":"2025-11-25","capabilities":{},"serverInfo":{"name":"fixture-mcp","version":"1.0.0"}}}"#,
        );

        let (mut initialized_stream, _) = listener.accept().expect("initialized notification should connect");
        let initialized_request = read_http_request(&mut initialized_stream);
        let initialized_request_lower = initialized_request.to_ascii_lowercase();
        assert!(initialized_request_lower.contains("authorization: bearer test-token"));
        assert!(initialized_request.contains("\"method\":\"notifications/initialized\""));

        write_http_response(&mut initialized_stream, 202, "Accepted", None, "");

        let (mut tool_call_stream, _) = listener.accept().expect("tools/call should connect");
        let tool_call_request = read_http_request(&mut tool_call_stream);
        let tool_call_request_lower = tool_call_request.to_ascii_lowercase();
        assert!(tool_call_request_lower.contains("authorization: bearer test-token"));
        assert!(tool_call_request.contains("\"method\":\"tools/call\""));
        assert!(tool_call_request.contains("\"name\":\"missing-tool\""));

        write_http_response(
            &mut tool_call_stream,
            200,
            "OK",
            Some("application/json"),
            r#"{"jsonrpc":"2.0","id":2,"error":{"code":-32601,"message":"Tool not found"}}"#,
        );
    });

    format!("http://{}", address)
}

pub(crate) fn spawn_mcp_sse_http_server() -> String {
    let listener = TcpListener::bind("127.0.0.1:0").expect("listener should bind");
    let address = listener.local_addr().expect("address should be available");

    thread::spawn(move || {
        let (mut initialize_stream, _) = listener.accept().expect("initialize should connect");
        let initialize_request = read_http_request(&mut initialize_stream);
        assert!(initialize_request.contains("\"method\":\"initialize\""));

        write_http_response(
            &mut initialize_stream,
            200,
            "OK",
            Some("text/event-stream"),
            concat!(
                "event: message\r\n",
                "data:\r\n\r\n",
                "event: message\r\n",
                "data: {\"jsonrpc\":\"2.0\",\"id\":1,\"result\":{\"protocolVersion\":\"2025-06-18\",\"capabilities\":{\"tools\":{\"listChanged\":true}},\"serverInfo\":{\"name\":\"fixture-mcp\",\"version\":\"1.0.0\"}}}\r\n\r\n"
            ),
        );

        let (mut initialized_stream, _) = listener.accept().expect("initialized notification should connect");
        let initialized_request = read_http_request(&mut initialized_stream);
        assert!(initialized_request.contains("\"method\":\"notifications/initialized\""));

        write_http_response(&mut initialized_stream, 202, "Accepted", None, "");
    });

    format!("http://{}", address)
}

pub(crate) fn spawn_sse_http_server() -> String {
    let listener = TcpListener::bind("127.0.0.1:0").expect("listener should bind");
    let address = listener.local_addr().expect("address should be available");

    thread::spawn(move || {
        let (mut stream, _) = listener.accept().expect("stream should connect");
        let request = read_http_request(&mut stream);
        let request_lower = request.to_ascii_lowercase();
        assert!(request.starts_with("GET / HTTP/1.1") || request.starts_with("GET / "));
        assert!(request_lower.contains("accept: text/event-stream"));

        write_http_response(
            &mut stream,
            200,
            "OK",
            Some("text/event-stream"),
            concat!(
                "event: price\r\n",
                "id: evt-1\r\n",
                "data: {\"symbol\":\"AAPL\",\"price\":182.4}\r\n\r\n"
            ),
        );
    });

    format!("http://{}", address)
}

pub(crate) fn spawn_ws_server() -> String {
    let listener = TcpListener::bind("127.0.0.1:0").expect("listener should bind");
    let address = listener.local_addr().expect("address should be available");

    thread::spawn(move || {
        let (stream, _) = listener.accept().expect("socket should connect");
        let mut socket = accept(stream).expect("handshake should succeed");

        let message = socket.read().expect("message should be readable");

        let text = match message {
            WsFrame::Text(text) => text.to_string(),
            other => panic!("expected text message, got {:?}", other),
        };

        let payload: Value = serde_json::from_str(&text).expect("payload should be valid json");
        assert_eq!(payload["type"], "hello");
        assert_eq!(payload["room"], "prices");

        socket
            .send(WsFrame::Text(
                r#"{"type":"ack","room":"prices"}"#.to_string().into(),
            ))
            .expect("ack should be sent");
    });

    format!("ws://{}", address)
}

fn read_http_request(stream: &mut TcpStream) -> String {
    let mut buffer = Vec::new();
    let mut chunk = [0_u8; 1024];
    let mut headers_end = None;
    let mut content_length = 0usize;

    loop {
        let bytes_read = stream.read(&mut chunk).expect("request should be readable");
        if bytes_read == 0 {
            break;
        }

        buffer.extend_from_slice(&chunk[..bytes_read]);

        if headers_end.is_none() {
            if let Some(end) = find_header_terminator(&buffer) {
                headers_end = Some(end);
                let headers = String::from_utf8_lossy(&buffer[..end]);
                content_length = parse_content_length(headers.as_ref());
            }
        }

        if let Some(end) = headers_end {
            if buffer.len() >= end + content_length {
                break;
            }
        }
    }

    String::from_utf8(buffer).expect("request should be utf-8")
}

fn find_header_terminator(buffer: &[u8]) -> Option<usize> {
    buffer
        .windows(4)
        .position(|window| window == b"\r\n\r\n")
        .map(|position| position + 4)
}

fn parse_content_length(headers: &str) -> usize {
    headers
        .lines()
        .find_map(|line| {
            let (name, value) = line.split_once(':')?;
            if name.eq_ignore_ascii_case("content-length") {
                value.trim().parse::<usize>().ok()
            } else {
                None
            }
        })
        .unwrap_or(0)
}

fn write_http_response(
    stream: &mut TcpStream,
    status: u16,
    reason: &str,
    content_type: Option<&str>,
    body: &str,
) {
    let content_type_header = content_type
        .map(|value| format!("Content-Type: {value}\r\n"))
        .unwrap_or_default();
    let response = format!(
        "HTTP/1.1 {status} {reason}\r\n{content_type_header}Content-Length: {}\r\nConnection: close\r\n\r\n{body}",
        body.len()
    );
    stream
        .write_all(response.as_bytes())
        .expect("response should be written");
}

#[cfg(unix)]
pub(crate) fn spawn_blocking_http_server(started_tx: mpsc::Sender<()>) -> String {
    let listener = TcpListener::bind("127.0.0.1:0").expect("listener should bind");
    let address = listener.local_addr().expect("address should be available");

    thread::spawn(move || {
        let (mut stream, _) = listener.accept().expect("connection should be accepted");
        let mut buffer = [0_u8; 1024];
        let _ = stream.read(&mut buffer);
        started_tx
            .send(())
            .expect("test should observe the blocking request");
        thread::sleep(Duration::from_secs(5));

        let body = r#"{"ok":true}"#;
        let response = format!(
            "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
            body.len()
        );
        let _ = stream.write_all(response.as_bytes());
    });

    format!("http://{}", address)
}

#[cfg(unix)]
pub(crate) fn run_until_signal(
    workspace: &TestWorkspace,
    args: &[&str],
    signal: &str,
    started_rx: mpsc::Receiver<()>,
) -> std::process::Output {
    let child = Command::new(env!("CARGO_BIN_EXE_hen"))
        .args(args)
        .current_dir(workspace.root())
        .env("NO_COLOR", "1")
        .env("TERM", "dumb")
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("hen command should execute");

    if started_rx.recv_timeout(Duration::from_secs(5)).is_err() {
        let output = child
            .wait_with_output()
            .expect("child output should be available");
        let stdout = String::from_utf8_lossy(&output.stdout);
        let stderr = String::from_utf8_lossy(&output.stderr);
        panic!(
            "second request should start before signalling\nstatus: {:?}\nstdout: {}\nstderr: {}",
            output.status.code(),
            stdout,
            stderr,
        );
    }

    thread::sleep(Duration::from_millis(200));

    let status = Command::new("kill")
        .args([signal, &child.id().to_string()])
        .status()
        .expect("signal command should execute");
    assert!(status.success(), "failed to send signal {signal}");

    child
        .wait_with_output()
        .expect("child output should be available")
}