Skip to main content

sqlserver_mcp_catalog/services/
api_client.rs

1// SQL Server 2025 - master/msdb/model combined catalog MCP server.
2//
3// Real transport: a pooled TDS connection to SQL Server (via `tiberius`),
4// replacing mcpify's originally-generated `reqwest`-based HTTP client.
5// These OpenAPI operations are synthetic (see
6// docs/sqlserver-eda-openapi-pipeline/README.md's "OpenAPI mapping
7// convention") -- there is no real HTTP endpoint on the other end, so
8// `endpoint.path`/`endpoint.method` don't describe an HTTP request; they
9// encode `/<schema>/<name>` (set by `tools/generate_openapi.py`, one path per
10// deduplicated operation -- see that script's `build_operations()`) and are
11// always `POST`. `endpoint.description` carries the object's
12// `sys.objects.type_desc` (`VIEW` / `SQL_STORED_PROCEDURE` /
13// `SQL_INLINE_TABLE_VALUED_FUNCTION` / `EXTENDED_STORED_PROCEDURE` / ...),
14// which determines the actual T-SQL shape: a bare `SELECT` for views,
15// `SELECT ... FROM name(args)` for table-valued functions and `SELECT
16// name(args)` for scalar functions (positional args -- no named-parameter
17// call syntax exists for a function call), or `EXEC name @p = v, ...` for
18// stored procedures (named, so param order and optional/defaulted params
19// don't matter).
20
21use serde_json::{Map, Value};
22use tiberius::ToSql;
23
24use crate::auth::auth_manager::AuthManager;
25use crate::core::config_schema::Config;
26use crate::data::store::EndpointRecord;
27use crate::services::sql_pool;
28use crate::services::sql_type::{column_data_to_json, json_to_param};
29use crate::validation::validator::resolved_schemas_for;
30
31/// The synthetic request-body property documenting an operation's execution
32/// context (see `docs/sqlserver-eda-openapi-pipeline/tools/generate_openapi.py`'s
33/// `EXECUTION_DATABASE_PARAM`) -- not a real SQL Server parameter of the
34/// underlying object, so it's pulled out of `body` and used to qualify the
35/// call rather than being bound as a `@P<n>` argument. Every generated
36/// operation carries this property (see `ordered_params`'s exclusion of it),
37/// so this name is reserved across the whole generated store.
38const EXECUTION_DATABASE_PARAM: &str = "execution_database";
39
40/// Parses `endpoint.path`'s `/<schema>/<name>` shape (set by
41/// `docs/sqlserver-eda-openapi-pipeline/tools/generate_openapi.py`) into its
42/// two parts. Unlike the old per-database-prefixed path convention, which
43/// database to actually run against is no longer baked into the path at
44/// generation time (a deduplicated operation may exist identically in more
45/// than one of master/msdb/model) -- see `resolve_execution_database`.
46fn parse_path(path: &str) -> anyhow::Result<(&str, &str)> {
47    let mut parts = path.trim_start_matches('/').splitn(2, '/');
48    match (parts.next(), parts.next()) {
49        (Some(schema), Some(name)) if !schema.is_empty() && !name.is_empty() => {
50            Ok((validate_ident(schema)?, validate_ident(name)?))
51        }
52        _ => anyhow::bail!("endpoint path '{path}' is not in the expected /<schema>/<name> shape"),
53    }
54}
55
56/// Rejects any identifier containing a character outside `[A-Za-z0-9_]` --
57/// every identifier passed through here (`db`/`schema`/`name`, stored
58/// procedure parameter names) comes from this project's own generated spec
59/// (looked up from the local SQLite store by `operation_id`, never built
60/// from a caller-supplied string), and every name in the curated object
61/// set this pipeline targets is already plain alphanumeric/underscore --
62/// see docs/sqlserver-eda-openapi-pipeline/sql/eda/allowlist.yaml. This is
63/// defense-in-depth on top of `quote_ident`'s bracket-escaping, not a
64/// response to any known injection path: T-SQL has no way to bind an
65/// object/parameter *name* as a query parameter (only values), so an
66/// identifier that ever did contain attacker-influenced text would bypass
67/// the parameterized-value protection `services::sql_type::json_to_param`
68/// provides for every argument *value*. Failing loudly here on an
69/// unexpected character is preferable to silently trusting it.
70fn validate_ident(ident: &str) -> anyhow::Result<&str> {
71    if !ident.is_empty()
72        && ident
73            .bytes()
74            .all(|b| b.is_ascii_alphanumeric() || b == b'_')
75    {
76        Ok(ident)
77    } else {
78        anyhow::bail!("identifier '{ident}' contains characters outside [A-Za-z0-9_]")
79    }
80}
81
82/// Brackets a SQL Server identifier, doubling any embedded `]` -- a second,
83/// independent layer under `validate_ident`'s charset allow-list, kept
84/// rather than dropped now that the allow-list exists, since a future
85/// change loosening the allow-list (e.g. to admit `$`/`#`-prefixed names)
86/// should not silently lose this escaping.
87fn quote_ident(ident: &str) -> String {
88    format!("[{}]", ident.replace(']', "]]"))
89}
90
91/// Resolves an operation's execution-context database: the caller-supplied
92/// `execution_database` body property (see `EXECUTION_DATABASE_PARAM`) if
93/// present, else the server's configured `Config::default_database` if one
94/// was set up (optional, see `cli::setup_wizard`), else `None` -- meaning
95/// `build_statement` two-part-qualifies the call and lets the connection's
96/// own current database context resolve it (equivalent to `DB_NAME()`/
97/// `DB_ID()`). This three-tier fallback applies uniformly to every
98/// operation now, not just ones documented in a particular database --
99/// see `build_statement`'s doc comment.
100fn resolve_execution_database(
101    body: &Map<String, Value>,
102    config: &Config,
103) -> anyhow::Result<Option<String>> {
104    if let Some(value) = body.get(EXECUTION_DATABASE_PARAM) {
105        let requested = value
106            .as_str()
107            .ok_or_else(|| anyhow::anyhow!("'{EXECUTION_DATABASE_PARAM}' must be a string"))?;
108        return Ok(Some(validate_ident(requested)?.to_string()));
109    }
110    config
111        .default_database
112        .as_deref()
113        .map(validate_ident)
114        .transpose()
115        .map(|opt| opt.map(str::to_string))
116}
117
118struct Param {
119    name: String,
120    ordinal: u64,
121    x_sql_type: String,
122}
123
124/// Every operation's generated input schema wraps its real parameters one
125/// level down, under a single top-level `body` property (mcpify's
126/// request-body convention -- see `ApiClient::execute`'s own `body`
127/// extraction from the caller's `args`, which this mirrors), almost always
128/// as a `$ref` into the schema's own `$defs` rather than an inline object.
129/// Resolves that wrapper (and its `$ref`, if present) to the real
130/// parameter-name map. Returns `None` for a schema with no `body` property
131/// at all (a parameterless operation), which `ordered_params` below treats
132/// as zero parameters.
133fn request_properties(input_schema: &Value) -> Option<&Map<String, Value>> {
134    let body_schema = input_schema.get("properties")?.get("body")?;
135    let resolved = match body_schema.get("$ref").and_then(Value::as_str) {
136        Some(reference) => reference
137            .strip_prefix("#/$defs/")
138            .and_then(|name| input_schema.get("$defs")?.get(name))?,
139        None => body_schema,
140    };
141    resolved.get("properties").and_then(Value::as_object)
142}
143
144/// Reads `properties`/`x-sql-ordinal`/`x-sql-type` off a resolved input
145/// schema (see `tools/generate_openapi.py`'s `build_request_schema`),
146/// sorted by declared ordinal -- required for a table-valued function's
147/// positional call syntax, and used for stored procedures' named syntax
148/// mainly for a deterministic/readable generated statement.
149fn ordered_params(input_schema: &Value) -> Vec<Param> {
150    let mut params: Vec<Param> = request_properties(input_schema)
151        .into_iter()
152        .flatten()
153        .filter(|(name, _)| name.as_str() != EXECUTION_DATABASE_PARAM)
154        .map(|(name, schema)| Param {
155            name: name.clone(),
156            ordinal: schema
157                .get("x-sql-ordinal")
158                .and_then(Value::as_u64)
159                .unwrap_or(0),
160            x_sql_type: schema
161                .get("x-sql-type")
162                .and_then(Value::as_str)
163                .unwrap_or("nvarchar(max)")
164                .to_string(),
165        })
166        .collect();
167    params.sort_by_key(|p| p.ordinal);
168    params
169}
170
171/// Builds the T-SQL text (with `@P1`/`@P2`/... placeholders) and the
172/// matching positionally-ordered bound parameters for one operation call.
173///
174/// `execution_database` is the resolved value of the synthetic
175/// `execution_database` request property (see `resolve_execution_database`)
176/// -- every operation now behaves the way only `sandbox`-tagged operations
177/// used to: three-part-qualified (`db.schema.name`) when a database is
178/// known, two-part-qualified (`schema.name`, resolved against the
179/// connection's own current database context) when it isn't. There is no
180/// per-operation baked-in database anymore -- a deduplicated operation may
181/// exist identically in more than one of master/msdb/model (see
182/// `docs/sqlserver-eda-openapi-pipeline/README.md`'s "OpenAPI mapping
183/// convention"), so which one to actually hit is always resolved per call.
184fn build_statement(
185    schema: &str,
186    name: &str,
187    kind: Option<&str>,
188    params: &[Param],
189    body: &Map<String, Value>,
190    execution_database: Option<&str>,
191) -> anyhow::Result<(String, Vec<Box<dyn ToSql>>)> {
192    let qualified = match execution_database {
193        Some(db) => format!(
194            "{}.{}.{}",
195            quote_ident(db),
196            quote_ident(schema),
197            quote_ident(name)
198        ),
199        None => format!("{}.{}", quote_ident(schema), quote_ident(name)),
200    };
201
202    let mut bound: Vec<Box<dyn ToSql>> = Vec::with_capacity(params.len());
203    for param in params {
204        let value = body.get(&param.name).cloned().unwrap_or(Value::Null);
205        bound.push(json_to_param(&value, &param.x_sql_type)?);
206    }
207
208    let sql = match kind {
209        Some("VIEW") => format!("SELECT * FROM {qualified}"),
210        Some(k) if k.ends_with("_FUNCTION") || k.contains("TABLE_VALUED_FUNCTION") => {
211            let placeholders = (1..=bound.len())
212                .map(|i| format!("@P{i}"))
213                .collect::<Vec<_>>()
214                .join(", ");
215            format!("SELECT * FROM {qualified}({placeholders})")
216        }
217        // Stored procedures (SQL_STORED_PROCEDURE/EXTENDED_STORED_PROCEDURE)
218        // and the `kind.is_none()` fallback (an older store built before
219        // `description` carried this classification) both take the EXEC
220        // path -- named parameter syntax, so a proc with only optional
221        // parameters and no arguments supplied still works (`bound` empty
222        // produces a bare `EXEC name`).
223        _ => {
224            if bound.is_empty() {
225                format!("EXEC {qualified}")
226            } else {
227                let mut assignments = Vec::with_capacity(params.len());
228                for (i, p) in params.iter().enumerate() {
229                    // Named EXEC-argument syntax requires the `@` sigil
230                    // directly on the parameter name (`EXEC proc @param =
231                    // value`, not `EXEC proc [param] = value` or
232                    // `EXEC proc param = value`) -- bracket-quoting is for
233                    // object identifiers, not parameter references, and
234                    // using it here produced a syntax error on every
235                    // parameterized stored-procedure call. `validate_ident`
236                    // still runs first for the same defense-in-depth reason
237                    // as the object-identifier path above.
238                    assignments.push(format!("@{} = @P{}", validate_ident(&p.name)?, i + 1));
239                }
240                format!("EXEC {qualified} {}", assignments.join(", "))
241            }
242        }
243    };
244
245    Ok((sql, bound))
246}
247
248/// Maps a `tiberius` error to this project's synthetic 400/403/500 split
249/// (see `docs/sqlserver-eda-openapi-pipeline/README.md`'s "OpenAPI mapping
250/// convention" -- SQL Server severity 11-16 statement errors are `400`,
251/// severity-14 permission errors are `403`, severity 17-25 engine/fatal
252/// errors are `500`), rather than surfacing the raw driver error
253/// undifferentiated. Returned as a JSON value matching
254/// `components.schemas.SqlServerError` shape rather than a bare string, so
255/// callers get the same structured error either way they might have gotten
256/// it from a real synchronous SQL Server error.
257fn classify_tiberius_error(err: tiberius::error::Error) -> anyhow::Error {
258    use tiberius::error::Error as TError;
259    match &err {
260        TError::Server(token) => {
261            let (number, state, class, message, procedure, line) = (
262                token.code(),
263                token.state(),
264                token.class(),
265                token.message(),
266                token.procedure(),
267                token.line(),
268            );
269            let category = if class >= 17 {
270                "fatal/resource error (500-equivalent)"
271            } else if class == 14 {
272                "permission denied (403-equivalent)"
273            } else {
274                "statement/user error (400-equivalent)"
275            };
276            anyhow::anyhow!(
277                "SQL Server error {number} (severity {class}, state {state}) in '{procedure}' line {line}: {message} [{category}]"
278            )
279        }
280        other => anyhow::anyhow!("SQL Server connection/protocol error (500-equivalent): {other}"),
281    }
282}
283
284pub struct ApiClient {
285    config: Config,
286}
287
288impl ApiClient {
289    pub fn new(config: Config) -> Self {
290        Self { config }
291    }
292
293    /// Executes `endpoint` against the configured SQL Server instance.
294    /// `auth_manager` resolves to a `tiberius::AuthMethod` (see
295    /// `auth::auth_manager::AuthManager::resolve_tds_auth`) from the
296    /// server's own configured credentials -- there is no per-request
297    /// credential override; SQL Server auth is always this server's own
298    /// configured identity, not something a caller supplies per call.
299    pub async fn execute(
300        &self,
301        endpoint: &EndpointRecord,
302        args: &Value,
303        auth_manager: &mut AuthManager,
304    ) -> anyhow::Result<Value> {
305        let (schema, name) = parse_path(&endpoint.path)?;
306
307        let (input_schema, _output_schema) =
308            resolved_schemas_for(&self.config.api_version, &endpoint.operation_id).ok_or_else(
309                || {
310                    anyhow::anyhow!(
311                        "no resolved schema found for operation '{}' under api_version '{}'",
312                        endpoint.operation_id,
313                        self.config.api_version
314                    )
315                },
316            )?;
317        let params = ordered_params(input_schema);
318
319        let empty = Map::new();
320        let args_map = args.as_object().unwrap_or(&empty);
321        let body = args_map
322            .get("body")
323            .and_then(Value::as_object)
324            .cloned()
325            .unwrap_or_default();
326        let execution_database = resolve_execution_database(&body, &self.config)?;
327
328        let (sql, bound) = build_statement(
329            schema,
330            name,
331            endpoint.description.as_deref(),
332            &params,
333            &body,
334            execution_database.as_deref(),
335        )?;
336
337        let auth_method = auth_manager.resolve_tds_auth().await?;
338
339        let (host, port) = self.config.host_and_port();
340        let mut tiberius_config = tiberius::Config::new();
341        tiberius_config.host(host);
342        tiberius_config.port(port);
343        tiberius_config.authentication(auth_method);
344        if self.config.trust_server_cert {
345            // Curated system-catalog objects, not user data -- trusting the
346            // server cert matches this project's primary use case (a local
347            // Docker/dev instance with a self-signed cert; see
348            // docs/sqlserver-eda-openapi-pipeline/docker-compose.yml)
349            // rather than requiring every operator to supply a CA bundle
350            // before the first query works. Set `trust_server_cert: false`
351            // for a production instance with a real CA-signed cert.
352            tiberius_config.trust_cert();
353        }
354
355        let pool_key = format!("{host}:{port}");
356        let pool =
357            sql_pool::cached_pool(&pool_key, tiberius_config, self.config.pool_max_size).await?;
358        let mut conn = pool.get().await.map_err(|err| {
359            anyhow::anyhow!("failed to obtain a pooled SQL Server connection: {err}")
360        })?;
361
362        let bound_refs: Vec<&dyn ToSql> = bound.iter().map(|param| param.as_ref()).collect();
363        let stream = conn
364            .query(&sql, &bound_refs)
365            .await
366            .map_err(classify_tiberius_error)?;
367        let rows = stream
368            .into_first_result()
369            .await
370            .map_err(classify_tiberius_error)?;
371
372        let json_rows: Vec<Value> = rows
373            .iter()
374            .map(|row| {
375                let mut obj = Map::new();
376                for (column, data) in row.cells() {
377                    obj.insert(column.name().to_string(), column_data_to_json(data));
378                }
379                Value::Object(obj)
380            })
381            .collect();
382        Ok(Value::Array(json_rows))
383    }
384}
385
386#[cfg(test)]
387mod tests {
388    use super::*;
389
390    #[test]
391    fn parse_path_splits_schema_name() {
392        assert_eq!(
393            parse_path("/INFORMATION_SCHEMA/COLUMNS").unwrap(),
394            ("INFORMATION_SCHEMA", "COLUMNS")
395        );
396    }
397
398    #[test]
399    fn parse_path_rejects_a_path_with_too_few_segments() {
400        assert!(parse_path("/COLUMNS").is_err());
401    }
402
403    #[test]
404    fn quote_ident_doubles_embedded_closing_brackets() {
405        assert_eq!(quote_ident("weird]name"), "[weird]]name]");
406    }
407
408    #[test]
409    fn validate_ident_accepts_alphanumeric_and_underscore() {
410        assert!(validate_ident("sp_who2").is_ok());
411        assert!(validate_ident("INFORMATION_SCHEMA").is_ok());
412    }
413
414    #[test]
415    fn validate_ident_rejects_anything_else() {
416        assert!(validate_ident("").is_err());
417        assert!(validate_ident("robert'; drop table endpoints;--").is_err());
418        assert!(validate_ident("weird]name").is_err());
419        assert!(validate_ident("has space").is_err());
420    }
421
422    #[test]
423    fn parse_path_rejects_a_path_with_an_unsafe_segment() {
424        assert!(parse_path("/sys/sp_who; DROP TABLE endpoints--").is_err());
425    }
426
427    #[test]
428    fn build_statement_selects_from_a_view_with_no_parameters() {
429        let (sql, bound) = build_statement(
430            "INFORMATION_SCHEMA",
431            "COLUMNS",
432            Some("VIEW"),
433            &[],
434            &Map::new(),
435            None,
436        )
437        .unwrap();
438        assert_eq!(sql, "SELECT * FROM [INFORMATION_SCHEMA].[COLUMNS]");
439        assert!(bound.is_empty());
440    }
441
442    #[test]
443    fn build_statement_execs_a_proc_with_named_parameters() {
444        let params = vec![
445            Param {
446                name: "objname".to_string(),
447                ordinal: 1,
448                x_sql_type: "nvarchar(1035)".to_string(),
449            },
450            Param {
451                name: "newname".to_string(),
452                ordinal: 2,
453                x_sql_type: "sysname".to_string(),
454            },
455        ];
456        let mut body = Map::new();
457        body.insert("objname".to_string(), Value::String("t1".to_string()));
458        body.insert("newname".to_string(), Value::String("t2".to_string()));
459        let (sql, bound) = build_statement(
460            "sys",
461            "sp_rename",
462            Some("SQL_STORED_PROCEDURE"),
463            &params,
464            &body,
465            Some("master"),
466        )
467        .unwrap();
468        assert_eq!(
469            sql,
470            "EXEC [master].[sys].[sp_rename] @objname = @P1, @newname = @P2"
471        );
472        assert_eq!(bound.len(), 2);
473    }
474
475    /// Regression test for incident 26-07-05700-04: every parameterized
476    /// stored-procedure `call` (e.g. `sp_columns`, `sp_executesql`) failed
477    /// with SQL Server error 102 "Incorrect syntax near '='", no matter
478    /// what argument keys the caller supplied, because the generated
479    /// assignment list bracket-quoted the parameter name (`[table_name] =
480    /// @P1`) instead of prefixing it with `@` (`@table_name = @P1`) --
481    /// bracket-quoting is valid for object identifiers, not for named
482    /// EXEC arguments. This asserts the `@`-prefixed form specifically, so
483    /// a future edit can't silently reintroduce bracket-quoting here even
484    /// if it still happens to produce syntactically-plausible-looking SQL.
485    #[test]
486    fn build_statement_uses_at_prefixed_names_not_bracket_quoting_for_named_exec_arguments() {
487        let params = vec![Param {
488            name: "table_name".to_string(),
489            ordinal: 1,
490            x_sql_type: "nvarchar(384)".to_string(),
491        }];
492        let mut body = Map::new();
493        body.insert(
494            "table_name".to_string(),
495            Value::String("databases".to_string()),
496        );
497        let (sql, _bound) = build_statement(
498            "sys",
499            "sp_columns",
500            Some("SQL_STORED_PROCEDURE"),
501            &params,
502            &body,
503            None,
504        )
505        .unwrap();
506        assert_eq!(sql, "EXEC [sys].[sp_columns] @table_name = @P1");
507        assert!(!sql.contains("[table_name]"));
508    }
509
510    #[test]
511    fn build_statement_selects_from_a_function_with_positional_placeholders() {
512        let params = vec![Param {
513            name: "session_id".to_string(),
514            ordinal: 1,
515            x_sql_type: "smallint".to_string(),
516        }];
517        let mut body = Map::new();
518        body.insert("session_id".to_string(), Value::from(52));
519        let (sql, bound) = build_statement(
520            "sys",
521            "dm_exec_sql_text",
522            Some("SQL_INLINE_TABLE_VALUED_FUNCTION"),
523            &params,
524            &body,
525            Some("master"),
526        )
527        .unwrap();
528        assert_eq!(sql, "SELECT * FROM [master].[sys].[dm_exec_sql_text](@P1)");
529        assert_eq!(bound.len(), 1);
530    }
531
532    #[test]
533    fn build_statement_omits_the_database_qualifier_by_default() {
534        let (sql, bound) =
535            build_statement("dbo", "widgets", Some("VIEW"), &[], &Map::new(), None).unwrap();
536        assert_eq!(sql, "SELECT * FROM [dbo].[widgets]");
537        assert!(bound.is_empty());
538    }
539
540    #[test]
541    fn build_statement_three_part_qualifies_with_a_requested_execution_database() {
542        let (sql, bound) = build_statement(
543            "dbo",
544            "widgets",
545            Some("VIEW"),
546            &[],
547            &Map::new(),
548            Some("reporting"),
549        )
550        .unwrap();
551        assert_eq!(sql, "SELECT * FROM [reporting].[dbo].[widgets]");
552        assert!(bound.is_empty());
553    }
554
555    #[test]
556    fn build_statement_execs_a_parameterless_proc() {
557        let (sql, bound) = build_statement(
558            "sys",
559            "sp_who",
560            Some("SQL_STORED_PROCEDURE"),
561            &[],
562            &Map::new(),
563            None,
564        )
565        .unwrap();
566        assert_eq!(sql, "EXEC [sys].[sp_who]");
567        assert!(bound.is_empty());
568    }
569
570    #[test]
571    fn ordered_params_excludes_the_synthetic_execution_database_property() {
572        let schema = serde_json::json!({
573            "properties": {
574                "body": { "$ref": "#/$defs/sys_sp_who_Request" }
575            },
576            "$defs": {
577                "sys_sp_who_Request": {
578                    "properties": {
579                        "loginame": { "x-sql-ordinal": 1, "x-sql-type": "sysname" },
580                        "execution_database": { "type": "string" }
581                    }
582                }
583            }
584        });
585
586        let params = ordered_params(&schema);
587        assert_eq!(params.len(), 1);
588        assert_eq!(params[0].name, "loginame");
589    }
590
591    #[test]
592    fn resolve_execution_database_prefers_the_body_property_over_the_configured_default() {
593        let mut body = Map::new();
594        body.insert(
595            EXECUTION_DATABASE_PARAM.to_string(),
596            Value::String("reporting".to_string()),
597        );
598        let mut config = test_config();
599        config.default_database = Some("fallback".to_string());
600        assert_eq!(
601            resolve_execution_database(&body, &config)
602                .unwrap()
603                .as_deref(),
604            Some("reporting")
605        );
606    }
607
608    #[test]
609    fn resolve_execution_database_falls_back_to_the_configured_default() {
610        let mut config = test_config();
611        config.default_database = Some("fallback".to_string());
612        assert_eq!(
613            resolve_execution_database(&Map::new(), &config)
614                .unwrap()
615                .as_deref(),
616            Some("fallback")
617        );
618    }
619
620    #[test]
621    fn resolve_execution_database_is_none_when_nothing_is_configured_or_supplied() {
622        assert_eq!(
623            resolve_execution_database(&Map::new(), &test_config()).unwrap(),
624            None
625        );
626    }
627
628    fn test_config() -> Config {
629        Config {
630            url: "localhost".to_string(),
631            auth_method: crate::core::config_schema::AuthMethod::SqlServer,
632            sql_port: 1433,
633            pool_max_size: 10,
634            trust_server_cert: true,
635            api_version: "2025".to_string(),
636            log_level: "info".to_string(),
637            rate_limit: 100,
638            timeout_ms: 30_000,
639            cache_size: 500,
640            retry_attempts: 3,
641            transport: crate::core::config_schema::Transport::Stdio,
642            host: "127.0.0.1".to_string(),
643            port: 3000,
644            cors_allow: None,
645            default_database: None,
646        }
647    }
648
649    #[test]
650    fn ordered_params_follow_the_schema_ordinals() {
651        // Matches the real shape every generated schema actually has (see
652        // `generated_schemas.json`): parameters live under `$defs`, `$ref`'d
653        // from the top-level `body` property, not as flat top-level
654        // properties.
655        let schema = serde_json::json!({
656            "properties": {
657                "body": { "$ref": "#/$defs/sys_example_Request" }
658            },
659            "$defs": {
660                "sys_example_Request": {
661                    "properties": {
662                        "second": { "x-sql-ordinal": 2, "x-sql-type": "int" },
663                        "first": { "x-sql-ordinal": 1, "x-sql-type": "nvarchar(20)" }
664                    }
665                }
666            }
667        });
668
669        let params = ordered_params(&schema);
670        assert_eq!(params.len(), 2);
671        assert_eq!(params[0].name, "first");
672        assert_eq!(params[0].x_sql_type, "nvarchar(20)");
673        assert_eq!(params[1].name, "second");
674    }
675
676    /// Regression test for incident 26-07-05700-04's underlying second bug:
677    /// `ordered_params` used to read the schema's literal top-level
678    /// `properties` map, which for every real generated schema is just
679    /// `{"body": {"$ref": ...}}` -- so every parameterized operation
680    /// collapsed to a single fake `body` parameter (observed live as
681    /// `EXEC ... @body = @P1` instead of the real named arguments) rather
682    /// than the operation's actual parameters.
683    #[test]
684    fn ordered_params_resolves_the_body_ref_wrapper() {
685        let schema = serde_json::json!({
686            "properties": {
687                "body": { "$ref": "#/$defs/sys_sp_columns_Request" }
688            },
689            "$defs": {
690                "sys_sp_columns_Request": {
691                    "properties": {
692                        "table_name": { "x-sql-ordinal": 1, "x-sql-type": "nvarchar(384)" },
693                        "table_owner": { "x-sql-ordinal": 2, "x-sql-type": "nvarchar(384)" }
694                    }
695                }
696            }
697        });
698
699        let params = ordered_params(&schema);
700        assert_eq!(params.len(), 2);
701        assert_eq!(params[0].name, "table_name");
702        assert_eq!(params[1].name, "table_owner");
703        assert!(params.iter().all(|p| p.name != "body"));
704    }
705
706    #[test]
707    fn ordered_params_resolves_an_inline_body_without_a_ref() {
708        let schema = serde_json::json!({
709            "properties": {
710                "body": {
711                    "properties": {
712                        "only": { "x-sql-ordinal": 1, "x-sql-type": "int" }
713                    }
714                }
715            }
716        });
717
718        let params = ordered_params(&schema);
719        assert_eq!(params.len(), 1);
720        assert_eq!(params[0].name, "only");
721    }
722
723    #[test]
724    fn ordered_params_is_empty_for_a_schema_with_no_body_property() {
725        let schema = serde_json::json!({ "properties": {} });
726        assert!(ordered_params(&schema).is_empty());
727    }
728
729    #[test]
730    fn build_statement_rejects_an_unsafe_parameter_name() {
731        let params = vec![Param {
732            name: "unsafe name".to_string(),
733            ordinal: 1,
734            x_sql_type: "int".to_string(),
735        }];
736
737        assert!(
738            build_statement(
739                "sys",
740                "sp_example",
741                Some("SQL_STORED_PROCEDURE"),
742                &params,
743                &Map::new(),
744                None,
745            )
746            .is_err()
747        );
748    }
749
750    #[test]
751    fn protocol_errors_are_classified_as_server_failures() {
752        let error =
753            classify_tiberius_error(tiberius::error::Error::Protocol("invalid packet".into()));
754        assert_eq!(
755            error.to_string(),
756            "SQL Server connection/protocol error (500-equivalent): Protocol error: invalid packet"
757        );
758    }
759}