pmcp-server-toolkit 0.1.0

Runtime library for config-driven MCP servers — auth, secrets, static resources/prompts, [[tools]] synthesizer, code-mode wiring
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
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
//! reqwest-backed [`HttpConnector`] implementation (OAPI-01).
//!
//! Lifts the pmcp-run reference `HttpClient::execute_with_options` body into a
//! toolkit-owned [`HttpClient`] that implements [`HttpConnector`]. The concrete
//! shape mirrors `crate::sql::sqlite::SqliteConnector` (a concrete connector impl
//! + constructor). Construction is LAZY — `new` parses the base URL but contacts
//! no backend (CF-2). URL building uses the shared [`crate::http::join_url`]
//! helper so an API-Gateway stage prefix (`/v1`) survives (Pitfall 2 — explicit
//! path concatenation, never the RFC-3986 url-crate path merge). Error messages
//! never echo the URL or a credential (Pitfall 5).

use super::auth::HttpAuthProvider;
use super::{join_url, HttpConnector, HttpConnectorError, Operation};
use async_trait::async_trait;
use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;

/// HTTP client configuration (OWNED here in `http`, mirroring [`super::AuthConfig`]
/// ownership so Plan 02 re-exports it rather than redefining).
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct HttpConfig {
    /// Request timeout in seconds.
    #[serde(default = "default_timeout")]
    pub timeout_seconds: u64,
    /// Number of retry attempts on 5xx / connect / timeout.
    #[serde(default = "default_retries")]
    pub retries: u32,
    /// Base backoff in milliseconds (exponential per attempt).
    #[serde(default = "default_retry_backoff")]
    pub retry_backoff_ms: u64,
    /// `User-Agent` header for all requests.
    #[serde(default = "default_user_agent")]
    pub user_agent: String,
    /// Extra headers applied to every request.
    #[serde(default)]
    pub default_headers: HashMap<String, String>,
}

fn default_timeout() -> u64 {
    30
}
fn default_retries() -> u32 {
    3
}
fn default_retry_backoff() -> u64 {
    1000
}
fn default_user_agent() -> String {
    format!("pmcp-server-toolkit/{}", env!("CARGO_PKG_VERSION"))
}

impl Default for HttpConfig {
    fn default() -> Self {
        Self {
            timeout_seconds: default_timeout(),
            retries: default_retries(),
            retry_backoff_ms: default_retry_backoff(),
            user_agent: default_user_agent(),
            default_headers: HashMap::new(),
        }
    }
}

/// reqwest-backed [`HttpConnector`].
pub struct HttpClient {
    client: reqwest::Client,
    base_url: url::Url,
    auth: Arc<dyn HttpAuthProvider>,
    http_config: HttpConfig,
}

impl HttpClient {
    /// Construct a client. LAZY: parses `base_url` but contacts no backend (CF-2).
    ///
    /// # Errors
    ///
    /// Returns [`HttpConnectorError::Backend`] when `base_url` is unparseable or
    /// the reqwest client cannot be built. The error message does NOT echo the URL.
    pub fn new(
        client: reqwest::Client,
        base_url: String,
        auth: Arc<dyn HttpAuthProvider>,
    ) -> Result<Self, HttpConnectorError> {
        Self::with_config(client, base_url, auth, HttpConfig::default())
    }

    /// Construct a client with an explicit [`HttpConfig`]. LAZY (CF-2).
    ///
    /// # Errors
    ///
    /// As [`HttpClient::new`].
    pub fn with_config(
        client: reqwest::Client,
        base_url: String,
        auth: Arc<dyn HttpAuthProvider>,
        http_config: HttpConfig,
    ) -> Result<Self, HttpConnectorError> {
        let base_url = url::Url::parse(&base_url)
            .map_err(|_| HttpConnectorError::Backend("invalid base URL".to_string()))?;
        Ok(Self {
            client,
            base_url,
            auth,
            http_config,
        })
    }

    /// Build a client from an [`HttpConfig`], constructing the reqwest client with
    /// the configured timeout, user-agent, and default headers. LAZY (CF-2).
    ///
    /// # Errors
    ///
    /// As [`HttpClient::new`].
    pub fn from_config(
        base_url: String,
        auth: Arc<dyn HttpAuthProvider>,
        http_config: HttpConfig,
    ) -> Result<Self, HttpConnectorError> {
        let mut headers = HeaderMap::new();
        if let Ok(ua) = HeaderValue::from_str(&http_config.user_agent) {
            headers.insert(reqwest::header::USER_AGENT, ua);
        }
        for (key, value) in &http_config.default_headers {
            if let (Ok(name), Ok(val)) = (
                HeaderName::try_from(key.as_str()),
                HeaderValue::try_from(value.as_str()),
            ) {
                headers.insert(name, val);
            }
        }
        let client = reqwest::Client::builder()
            .timeout(Duration::from_secs(http_config.timeout_seconds))
            .default_headers(headers)
            .build()
            .map_err(|_| HttpConnectorError::Backend("failed to build HTTP client".to_string()))?;
        Self::with_config(client, base_url, auth, http_config)
    }

    /// Substitute path parameters into the operation path template.
    ///
    /// # Errors
    ///
    /// Returns [`HttpConnectorError::Backend`] (via [`render_scalar`]) when a path
    /// parameter value is a non-scalar (`Object`/`Array`) — such a value would
    /// otherwise be JSON-stringified into the URL (WR-03).
    fn substitute_path(
        operation: &Operation,
        args: &serde_json::Map<String, serde_json::Value>,
    ) -> Result<String, HttpConnectorError> {
        let mut path = operation.path.clone();
        for param in operation.path_parameters() {
            let placeholder = format!("{{{}}}", param.name);
            if let Some(value) = args.get(&param.name) {
                let value_str = render_scalar(&param.name, value)?;
                path = path.replace(&placeholder, &value_str);
            }
        }
        Ok(path)
    }

    /// Render one query value: a scalar passes through; an array-of-scalars is
    /// comma-joined (OpenAPI `form`/`explode:false` style); an object or an array
    /// with any non-scalar member is rejected (each member is checked through
    /// [`render_scalar`]).
    ///
    /// # Errors
    ///
    /// Returns [`HttpConnectorError::Backend`] naming `param_name` when `value`
    /// (or any array member) is a non-scalar.
    fn render_query_value(
        param_name: &str,
        value: &serde_json::Value,
    ) -> Result<String, HttpConnectorError> {
        if let serde_json::Value::Array(arr) = value {
            // Comma-separate array members (OpenAPI `form`/`simple` style). A
            // nested non-scalar member is rejected by render_scalar.
            let mut csv = String::new();
            for (i, member) in arr.iter().enumerate() {
                if i > 0 {
                    csv.push(',');
                }
                csv.push_str(&render_scalar(param_name, member)?);
            }
            Ok(csv)
        } else {
            render_scalar(param_name, value)
        }
    }

    /// Build the query map from query-located params present in `args`.
    ///
    /// # Errors
    ///
    /// Returns [`HttpConnectorError::Backend`] naming the offending parameter when
    /// a query value is an object, or an array containing a non-scalar member
    /// (WR-03). A scalar or an array-of-scalars behaves exactly as before.
    fn build_query(
        operation: &Operation,
        args: &serde_json::Map<String, serde_json::Value>,
    ) -> Result<HashMap<String, String>, HttpConnectorError> {
        let mut query = HashMap::new();
        for param in operation.query_parameters() {
            if let Some(value) = args.get(&param.name) {
                query.insert(
                    param.name.clone(),
                    Self::render_query_value(&param.name, value)?,
                );
            }
        }
        Ok(query)
    }

    /// Build the header map from header-located params present in `args`.
    fn build_headers(
        operation: &Operation,
        args: &serde_json::Map<String, serde_json::Value>,
    ) -> Result<HeaderMap, HttpConnectorError> {
        let mut headers = HeaderMap::new();
        for param in operation.header_parameters() {
            if let Some(value) = args.get(&param.name) {
                let name = HeaderName::try_from(param.name.as_str()).map_err(|_| {
                    HttpConnectorError::InvalidHeader("invalid header name".to_string())
                })?;
                // Reject a non-scalar header value (naming the param) before it
                // can be JSON-stringified into the header (WR-03).
                let rendered = render_scalar(&param.name, value)?;
                let val = HeaderValue::try_from(rendered).map_err(|_| {
                    HttpConnectorError::InvalidHeader("invalid header value".to_string())
                })?;
                headers.insert(name, val);
            }
        }
        Ok(headers)
    }

    /// Collect the request body: args that are NOT path/query/header params.
    fn build_body(
        operation: &Operation,
        args: &serde_json::Map<String, serde_json::Value>,
    ) -> Option<serde_json::Value> {
        if !operation.has_request_body {
            return None;
        }
        if let Some(body) = args.get("body") {
            return Some(body.clone());
        }
        let declared: std::collections::HashSet<&str> = operation
            .parameters
            .iter()
            .map(|p| p.name.as_str())
            .collect();
        let body: serde_json::Map<String, serde_json::Value> = args
            .iter()
            .filter(|(k, _)| !declared.contains(k.as_str()))
            .map(|(k, v)| (k.clone(), v.clone()))
            .collect();
        if body.is_empty() {
            None
        } else {
            Some(serde_json::Value::Object(body))
        }
    }

    fn convert_method(method: &str) -> Result<reqwest::Method, HttpConnectorError> {
        match method.to_uppercase().as_str() {
            "GET" => Ok(reqwest::Method::GET),
            "POST" => Ok(reqwest::Method::POST),
            "PUT" => Ok(reqwest::Method::PUT),
            "PATCH" => Ok(reqwest::Method::PATCH),
            "DELETE" => Ok(reqwest::Method::DELETE),
            "HEAD" => Ok(reqwest::Method::HEAD),
            "OPTIONS" => Ok(reqwest::Method::OPTIONS),
            _ => Err(HttpConnectorError::Backend(
                "unknown HTTP method".to_string(),
            )),
        }
    }

    /// Send the request, retrying on 5xx / connect / timeout with exponential backoff.
    async fn send_with_retries(
        &self,
        request: reqwest::RequestBuilder,
    ) -> Result<reqwest::Response, HttpConnectorError> {
        let max_retries = self.http_config.retries;
        let mut last_status: Option<u16> = None;
        for attempt in 0..=max_retries {
            if attempt > 0 {
                let delay = self.http_config.retry_backoff_ms * (1u64 << (attempt - 1));
                tokio::time::sleep(Duration::from_millis(delay)).await;
            }
            let Some(attempt_request) = request.try_clone() else {
                return Err(HttpConnectorError::Request(
                    "request body is not retryable".to_string(),
                ));
            };
            match attempt_request.send().await {
                Ok(response) => {
                    let status = response.status();
                    if status.is_server_error() && attempt < max_retries {
                        last_status = Some(status.as_u16());
                        continue;
                    }
                    return Ok(response);
                },
                Err(e) => {
                    let retryable = e.is_connect() || e.is_timeout();
                    if retryable && attempt < max_retries {
                        continue;
                    }
                    // Redacted: never forward the reqwest error Display (echoes URL).
                    return Err(HttpConnectorError::Request(
                        "transport error contacting backend".to_string(),
                    ));
                },
            }
        }
        Err(HttpConnectorError::Status {
            status: last_status.unwrap_or(0),
        })
    }
}

/// Render a JSON scalar for use in a path / query / header position, REJECTING
/// non-scalar values (WR-03 / GAP 4).
///
/// # The decided rule (uniform)
///
/// The `http::schema::Parameter` model carries NO OpenAPI `style` / `explode` /
/// `type` hint, so there is no per-parameter serialization directive to honor;
/// the rule must therefore be uniform across every path / query / header
/// position:
///
/// - A scalar (`String`, `Number`, `Bool`, `Null`) renders to a bare string
///   (`Null` → `"null"`, matching the `code_mode::HttpCodeExecutor::scalar_str`
///   counterpart so the two HTTP surfaces stay consistent).
/// - A query parameter that is an **array of scalars** is comma-joined by the
///   caller ([`build_query`]); each member is rendered through this function so a
///   nested non-scalar member is rejected.
/// - An `Object`, an array containing any non-scalar member, or ANY non-scalar
///   in path / header position is **rejected** with a typed error that names the
///   parameter — it is NEVER JSON-stringified into the URL/header (which would
///   leak literal `{`/`[`/`"` that then percent-encode into a silently-wrong
///   request).
///
/// # Errors
///
/// Returns [`HttpConnectorError::Backend`] naming `param_name` when `value` is a
/// non-scalar (`Object` or `Array`). Per the module's redaction discipline
/// (Pitfall 5) the message names the PARAMETER ONLY — never the value.
fn render_scalar(
    param_name: &str,
    value: &serde_json::Value,
) -> Result<String, HttpConnectorError> {
    match value {
        serde_json::Value::String(s) => Ok(s.clone()),
        serde_json::Value::Number(n) => Ok(n.to_string()),
        serde_json::Value::Bool(b) => Ok(b.to_string()),
        serde_json::Value::Null => Ok("null".to_string()),
        // Object OR Array: non-scalar in a path/query/header position is rejected
        // rather than silently JSON-stringified. Name the param ONLY (Pitfall 5).
        serde_json::Value::Object(_) | serde_json::Value::Array(_) => {
            Err(HttpConnectorError::Backend(format!(
                "param '{param_name}' must be a scalar (non-scalar values are \
                 not supported in path/query/header position)"
            )))
        },
    }
}

#[async_trait]
impl HttpConnector for HttpClient {
    async fn execute(
        &self,
        operation: &Operation,
        args: &serde_json::Value,
    ) -> Result<serde_json::Value, HttpConnectorError> {
        let empty = serde_json::Map::new();
        let args_map = args.as_object().unwrap_or(&empty);

        // Build URL via the shared join_url helper (explicit concat, never the
        // url-crate RFC-3986 path merge) — preserves a stage prefix like /v1
        // (Pitfall 2 / T-90-01-05).
        let substituted = Self::substitute_path(operation, args_map)?;
        let joined = join_url(self.base_url.as_str(), &substituted);
        let mut url = url::Url::parse(&joined)
            .map_err(|_| HttpConnectorError::Backend("constructed URL is invalid".to_string()))?;

        let mut query = Self::build_query(operation, args_map)?;
        let mut headers = Self::build_headers(operation, args_map)?;

        // Single-call tools have no per-request passthrough token (Plan 04/06 carry
        // it through HttpCodeExecutor); pass None here.
        self.auth.apply(&mut headers, &mut query, None).await?;

        // Why: reqwest 0.13 gates `RequestBuilder::query` behind a `query` feature
        // (verified in reqwest-0.13.2 request.rs:`#[cfg(feature = "query")]`). The
        // toolkit deliberately does NOT enable that feature (Pitfall 4 / lean
        // build), so query params are appended to the URL via `url`'s built-in,
        // percent-encoding query-pair serializer instead.
        if !query.is_empty() {
            let mut pairs = url.query_pairs_mut();
            for (key, value) in &query {
                pairs.append_pair(key, value);
            }
            drop(pairs);
        }

        let method = Self::convert_method(&operation.method)?;
        let mut request = self.client.request(method, url);
        request = request.headers(headers);
        if let Some(body) = Self::build_body(operation, args_map) {
            request = request.json(&body);
        }

        let response = self.send_with_retries(request).await?;
        let status = response.status();
        if !status.is_success() {
            return Err(HttpConnectorError::Status {
                status: status.as_u16(),
            });
        }
        let body = response
            .text()
            .await
            .map_err(|_| HttpConnectorError::Request("failed to read response body".to_string()))?;
        if body.is_empty() {
            return Ok(serde_json::Value::Null);
        }
        serde_json::from_str(&body).map_err(|_| {
            HttpConnectorError::Backend("response body was not valid JSON".to_string())
        })
    }

    fn base_url(&self) -> &str {
        self.base_url.as_str()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::http::auth::NoAuth;
    use crate::http::{Parameter, ParameterLocation};

    fn get_user_op() -> Operation {
        Operation {
            method: "GET".to_string(),
            path: "/users/{id}".to_string(),
            parameters: vec![
                Parameter::new("id", ParameterLocation::Path, true),
                Parameter::new("verbose", ParameterLocation::Query, false),
            ],
            has_request_body: false,
            base_url: None,
        }
    }

    #[test]
    fn test_build_url_with_path_prefix() {
        // Regression: an API-Gateway stage prefix /v1 survives via join_url.
        let client = HttpClient::new(
            reqwest::Client::new(),
            "https://xxx.execute-api.eu-west-1.amazonaws.com/v1/".to_string(),
            Arc::new(NoAuth),
        )
        .unwrap();
        let op = get_user_op();
        let mut args = serde_json::Map::new();
        args.insert("id".to_string(), serde_json::json!("42"));
        let substituted = HttpClient::substitute_path(&op, &args).unwrap();
        let joined = join_url(client.base_url(), &substituted);
        assert_eq!(
            joined,
            "https://xxx.execute-api.eu-west-1.amazonaws.com/v1/users/42"
        );
    }

    #[test]
    fn test_substitute_path_replaces_placeholder() {
        let op = get_user_op();
        let mut args = serde_json::Map::new();
        args.insert("id".to_string(), serde_json::json!(7));
        assert_eq!(HttpClient::substitute_path(&op, &args).unwrap(), "/users/7");
    }

    #[test]
    fn test_build_query_skips_path_params() {
        let op = get_user_op();
        let mut args = serde_json::Map::new();
        args.insert("id".to_string(), serde_json::json!("42"));
        args.insert("verbose".to_string(), serde_json::json!(true));
        let query = HttpClient::build_query(&op, &args).unwrap();
        assert_eq!(query.get("verbose"), Some(&"true".to_string()));
        assert!(!query.contains_key("id"));
    }

    // -- WR-03 / GAP 4: fallible scalar renderer (reject non-scalar params) -----

    /// An array-of-scalars query param comma-joins (unchanged OpenAPI
    /// `form`/`explode:false` behavior).
    #[test]
    fn render_query_value_comma_joins_scalar_array() {
        let rendered =
            HttpClient::render_query_value("tags", &serde_json::json!(["a", 2, true])).unwrap();
        assert_eq!(rendered, "a,2,true");
    }

    /// A scalar query param renders bare (unchanged).
    #[test]
    fn render_query_value_scalar_passthrough() {
        assert_eq!(
            HttpClient::render_query_value("q", &serde_json::json!("hi")).unwrap(),
            "hi"
        );
        assert_eq!(
            HttpClient::render_query_value("n", &serde_json::json!(7)).unwrap(),
            "7"
        );
    }

    /// `render_scalar` renders Null as the bare string `"null"` (matches the
    /// code_mode `scalar_str` counterpart).
    #[test]
    fn render_scalar_null_is_bare_null() {
        assert_eq!(
            render_scalar("x", &serde_json::Value::Null).unwrap(),
            "null"
        );
    }

    /// An OBJECT path param is rejected, naming the param; the error never echoes
    /// the value and never produces a JSON-stringified `{`/`[`/`"`.
    #[test]
    fn substitute_path_rejects_object_param() {
        let op = get_user_op();
        let mut args = serde_json::Map::new();
        args.insert("id".to_string(), serde_json::json!({"nested": "x"}));
        let err = HttpClient::substitute_path(&op, &args).unwrap_err();
        assert!(matches!(err, HttpConnectorError::Backend(_)));
        let rendered = err.to_string();
        assert!(
            rendered.contains("id"),
            "error must name the param: {rendered}"
        );
        for forbidden in ['{', '[', '"'] {
            assert!(
                !rendered.contains(forbidden),
                "must not echo JSON: {rendered}"
            );
        }
        // Pitfall 5: never echo the value.
        assert!(
            !rendered.contains("nested"),
            "must not echo the value: {rendered}"
        );
    }

    /// An OBJECT query param is rejected, naming the param.
    #[test]
    fn build_query_rejects_object_param() {
        let op = get_user_op();
        let mut args = serde_json::Map::new();
        args.insert("verbose".to_string(), serde_json::json!({"k": "v"}));
        let err = HttpClient::build_query(&op, &args).unwrap_err();
        assert!(matches!(err, HttpConnectorError::Backend(_)));
        assert!(err.to_string().contains("verbose"));
    }

    /// An array CONTAINING a non-scalar member is rejected (the scalar comma-join
    /// is preserved only for scalar-only arrays).
    #[test]
    fn render_query_value_rejects_array_with_object_member() {
        let err = HttpClient::render_query_value("tags", &serde_json::json!(["ok", {"bad": 1}]))
            .unwrap_err();
        assert!(matches!(err, HttpConnectorError::Backend(_)));
        assert!(err.to_string().contains("tags"));
    }

    /// A non-scalar HEADER param is rejected, naming the param.
    #[test]
    fn build_headers_rejects_non_scalar_param() {
        let op = Operation {
            method: "GET".to_string(),
            path: "/x".to_string(),
            parameters: vec![Parameter::new("x-trace", ParameterLocation::Header, false)],
            has_request_body: false,
            base_url: None,
        };
        // An ARRAY in header position is non-scalar (arrays comma-join ONLY in
        // query position) and is rejected.
        let mut args = serde_json::Map::new();
        args.insert("x-trace".to_string(), serde_json::json!(["a", "b"]));
        let err = HttpClient::build_headers(&op, &args).unwrap_err();
        assert!(matches!(err, HttpConnectorError::Backend(_)));
        assert!(err.to_string().contains("x-trace"));
        // An OBJECT in header position is likewise rejected.
        let mut args2 = serde_json::Map::new();
        args2.insert("x-trace".to_string(), serde_json::json!({"k": "v"}));
        let err2 = HttpClient::build_headers(&op, &args2).unwrap_err();
        assert!(matches!(err2, HttpConnectorError::Backend(_)));
        assert!(err2.to_string().contains("x-trace"));
        // A scalar header value still succeeds.
        let mut args3 = serde_json::Map::new();
        args3.insert("x-trace".to_string(), serde_json::json!("abc"));
        let headers = HttpClient::build_headers(&op, &args3).unwrap();
        assert_eq!(headers.get("x-trace").unwrap(), "abc");
    }

    #[test]
    fn test_new_is_lazy_and_rejects_bad_url() {
        // Lazy: a bad URL fails synchronously without any network (CF-2).
        let err = HttpClient::new(
            reqwest::Client::new(),
            "not a url".to_string(),
            Arc::new(NoAuth),
        )
        .err()
        .expect("bad URL should error");
        assert!(matches!(err, HttpConnectorError::Backend(_)));
        let rendered = err.to_string();
        assert!(!rendered.contains("not a url"), "must not echo the bad URL");
    }

    #[tokio::test]
    async fn http_connector_get_returns_json() {
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/users/42"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"id": 42, "name": "Ada"})),
            )
            .mount(&server)
            .await;

        let client =
            HttpClient::new(reqwest::Client::new(), server.uri(), Arc::new(NoAuth)).unwrap();
        let op = get_user_op();
        let args = serde_json::json!({"id": "42"});
        let result = client.execute(&op, &args).await.unwrap();
        assert_eq!(result["id"], 42);
        assert_eq!(result["name"], "Ada");
    }

    #[tokio::test]
    async fn http_connector_post_sends_body_and_auth() {
        use wiremock::matchers::{body_json, header, method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/items"))
            .and(header("authorization", "Bearer tok"))
            .and(body_json(serde_json::json!({"name": "widget"})))
            .respond_with(ResponseTemplate::new(201).set_body_json(serde_json::json!({"ok": true})))
            .mount(&server)
            .await;

        let auth = crate::http::auth::create_auth_provider(&crate::http::AuthConfig::Bearer {
            token: "tok".to_string(),
            required: true,
        })
        .unwrap();
        let client = HttpClient::new(reqwest::Client::new(), server.uri(), auth).unwrap();
        let op = Operation {
            method: "POST".to_string(),
            path: "/items".to_string(),
            parameters: vec![],
            has_request_body: true,
            base_url: None,
        };
        let args = serde_json::json!({"name": "widget"});
        let result = client.execute(&op, &args).await.unwrap();
        assert_eq!(result["ok"], true);
    }

    #[tokio::test]
    async fn http_connector_maps_non_2xx_to_status_without_url() {
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/users/42"))
            .respond_with(ResponseTemplate::new(404))
            .mount(&server)
            .await;

        let client =
            HttpClient::new(reqwest::Client::new(), server.uri(), Arc::new(NoAuth)).unwrap();
        let op = get_user_op();
        let args = serde_json::json!({"id": "42"});
        let err = client.execute(&op, &args).await.unwrap_err();
        assert!(matches!(err, HttpConnectorError::Status { status: 404 }));
        let rendered = err.to_string();
        assert!(rendered.contains("404"));
        assert!(
            !rendered.contains("http://"),
            "status error must not echo the URL"
        );
    }
}