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.
184/// Whether `kind` (an operation's catalog `sys.objects.type_desc`) can
185/// perform a write, mirroring `build_statement`'s own classification.
186/// `VIEW` and any `*_FUNCTION` kind cannot: a view is only ever queried
187/// with a bare `SELECT`, and T-SQL functions are language-level prohibited
188/// from having side effects (SQL Server rejects a `CREATE FUNCTION` body
189/// containing `INSERT`/`UPDATE`/`DELETE` outside a table variable), so
190/// both are genuinely engine-guaranteed read-only, not just app-level
191/// convention. Everything else -- `SQL_STORED_PROCEDURE`,
192/// `EXTENDED_STORED_PROCEDURE`, or a missing/unrecognized classification
193/// (an older store built before `description` carried this classification)
194/// -- has no such guarantee and is treated as write-capable, failing
195/// closed rather than assuming an unknown kind is safe.
196fn is_writable_kind(kind: Option<&str>) -> bool {
197    match kind {
198        Some("VIEW") => false,
199        Some(k) if k.ends_with("_FUNCTION") || k.contains("TABLE_VALUED_FUNCTION") => false,
200        _ => true,
201    }
202}
203
204fn build_statement(
205    schema: &str,
206    name: &str,
207    kind: Option<&str>,
208    params: &[Param],
209    body: &Map<String, Value>,
210    execution_database: Option<&str>,
211) -> anyhow::Result<(String, Vec<Box<dyn ToSql>>)> {
212    let qualified = match execution_database {
213        Some(db) => format!(
214            "{}.{}.{}",
215            quote_ident(db),
216            quote_ident(schema),
217            quote_ident(name)
218        ),
219        None => format!("{}.{}", quote_ident(schema), quote_ident(name)),
220    };
221
222    let mut bound: Vec<Box<dyn ToSql>> = Vec::with_capacity(params.len());
223    for param in params {
224        let value = body.get(&param.name).cloned().unwrap_or(Value::Null);
225        bound.push(json_to_param(&value, &param.x_sql_type)?);
226    }
227
228    let sql = match kind {
229        Some("VIEW") => format!("SELECT * FROM {qualified}"),
230        Some(k) if k.ends_with("_FUNCTION") || k.contains("TABLE_VALUED_FUNCTION") => {
231            let placeholders = (1..=bound.len())
232                .map(|i| format!("@P{i}"))
233                .collect::<Vec<_>>()
234                .join(", ");
235            format!("SELECT * FROM {qualified}({placeholders})")
236        }
237        // Stored procedures (SQL_STORED_PROCEDURE/EXTENDED_STORED_PROCEDURE)
238        // and the `kind.is_none()` fallback (an older store built before
239        // `description` carried this classification) both take the EXEC
240        // path -- named parameter syntax, so a proc with only optional
241        // parameters and no arguments supplied still works (`bound` empty
242        // produces a bare `EXEC name`).
243        _ => {
244            if bound.is_empty() {
245                format!("EXEC {qualified}")
246            } else {
247                let mut assignments = Vec::with_capacity(params.len());
248                for (i, p) in params.iter().enumerate() {
249                    // Named EXEC-argument syntax requires the `@` sigil
250                    // directly on the parameter name (`EXEC proc @param =
251                    // value`, not `EXEC proc [param] = value` or
252                    // `EXEC proc param = value`) -- bracket-quoting is for
253                    // object identifiers, not parameter references, and
254                    // using it here produced a syntax error on every
255                    // parameterized stored-procedure call. `validate_ident`
256                    // still runs first for the same defense-in-depth reason
257                    // as the object-identifier path above.
258                    assignments.push(format!("@{} = @P{}", validate_ident(&p.name)?, i + 1));
259                }
260                format!("EXEC {qualified} {}", assignments.join(", "))
261            }
262        }
263    };
264
265    Ok((sql, bound))
266}
267
268/// The severity-to-status-category mapping documented on every generated
269/// operation's 400/403/500 responses (see `docs/sqlserver-eda-openapi-pipeline
270/// /README.md`'s "OpenAPI mapping convention") -- pulled out of
271/// `classify_tiberius_error` as its own pure function so this classification
272/// logic is unit-testable directly. `tiberius::tds::codec::TokenError`'s
273/// fields are all `pub(crate)` with no public constructor, so a
274/// `tiberius::error::Error::Server(_)` can never be built from outside the
275/// crate for a test to exercise the branch that reads `class` off it --
276/// this function is what actually stays testable.
277fn severity_category(class: u8) -> &'static str {
278    if class >= 17 {
279        "fatal/resource error (500-equivalent)"
280    } else if class == 14 {
281        "permission denied (403-equivalent)"
282    } else {
283        "statement/user error (400-equivalent)"
284    }
285}
286
287/// Maps a `tiberius` error to this project's synthetic 400/403/500 split
288/// (see `docs/sqlserver-eda-openapi-pipeline/README.md`'s "OpenAPI mapping
289/// convention" -- SQL Server severity 11-16 statement errors are `400`,
290/// severity-14 permission errors are `403`, severity 17-25 engine/fatal
291/// errors are `500`), rather than surfacing the raw driver error
292/// undifferentiated. Returned as a JSON value matching
293/// `components.schemas.SqlServerError` shape rather than a bare string, so
294/// callers get the same structured error either way they might have gotten
295/// it from a real synchronous SQL Server error.
296fn classify_tiberius_error(err: tiberius::error::Error) -> anyhow::Error {
297    use tiberius::error::Error as TError;
298    match &err {
299        TError::Server(token) => {
300            let (number, state, class, message, procedure, line) = (
301                token.code(),
302                token.state(),
303                token.class(),
304                token.message(),
305                token.procedure(),
306                token.line(),
307            );
308            let category = severity_category(class);
309            anyhow::anyhow!(
310                "SQL Server error {number} (severity {class}, state {state}) in '{procedure}' line {line}: {message} [{category}]"
311            )
312        }
313        other => anyhow::anyhow!("SQL Server connection/protocol error (500-equivalent): {other}"),
314    }
315}
316
317pub struct ApiClient {
318    config: Config,
319}
320
321impl ApiClient {
322    pub fn new(config: Config) -> Self {
323        Self { config }
324    }
325
326    /// Executes `endpoint` against the configured SQL Server instance.
327    /// `auth_manager` resolves to a `tiberius::AuthMethod` (see
328    /// `auth::auth_manager::AuthManager::resolve_tds_auth`) from the
329    /// server's own configured credentials -- there is no per-request
330    /// credential override; SQL Server auth is always this server's own
331    /// configured identity, not something a caller supplies per call.
332    pub async fn execute(
333        &self,
334        endpoint: &EndpointRecord,
335        args: &Value,
336        auth_manager: &mut AuthManager,
337    ) -> anyhow::Result<Value> {
338        if self.config.read_only && is_writable_kind(endpoint.description.as_deref()) {
339            anyhow::bail!(
340                "operation '{}' is a {} and cannot run while read_only is enabled; set read_only to false to allow it",
341                endpoint.operation_id,
342                endpoint.description.as_deref().unwrap_or("object of unrecognized type"),
343            );
344        }
345
346        let (schema, name) = parse_path(&endpoint.path)?;
347
348        let (input_schema, _output_schema) =
349            resolved_schemas_for(&self.config.api_version, &endpoint.operation_id).ok_or_else(
350                || {
351                    anyhow::anyhow!(
352                        "no resolved schema found for operation '{}' under api_version '{}'",
353                        endpoint.operation_id,
354                        self.config.api_version
355                    )
356                },
357            )?;
358        let params = ordered_params(input_schema);
359
360        let empty = Map::new();
361        let args_map = args.as_object().unwrap_or(&empty);
362        let body = args_map
363            .get("body")
364            .and_then(Value::as_object)
365            .cloned()
366            .unwrap_or_default();
367        let execution_database = resolve_execution_database(&body, &self.config)?;
368
369        let (sql, bound) = build_statement(
370            schema,
371            name,
372            endpoint.description.as_deref(),
373            &params,
374            &body,
375            execution_database.as_deref(),
376        )?;
377
378        let auth_method = auth_manager.resolve_tds_auth().await?;
379
380        let (host, port) = self.config.host_and_port();
381        let mut tiberius_config = tiberius::Config::new();
382        tiberius_config.host(host);
383        tiberius_config.port(port);
384        tiberius_config.authentication(auth_method);
385        if self.config.trust_server_cert {
386            // Curated system-catalog objects, not user data -- trusting the
387            // server cert matches this project's primary use case (a local
388            // Docker/dev instance with a self-signed cert; see
389            // docs/sqlserver-eda-openapi-pipeline/docker-compose.yml)
390            // rather than requiring every operator to supply a CA bundle
391            // before the first query works. Set `trust_server_cert: false`
392            // for a production instance with a real CA-signed cert.
393            tiberius_config.trust_cert();
394        }
395
396        let pool_key = format!("{host}:{port}");
397        let pool =
398            sql_pool::cached_pool(&pool_key, tiberius_config, self.config.pool_max_size).await?;
399        let mut conn = pool.get().await.map_err(|err| {
400            anyhow::anyhow!("failed to obtain a pooled SQL Server connection: {err}")
401        })?;
402
403        let bound_refs: Vec<&dyn ToSql> = bound.iter().map(|param| param.as_ref()).collect();
404        let stream = conn
405            .query(&sql, &bound_refs)
406            .await
407            .map_err(classify_tiberius_error)?;
408        let rows = stream
409            .into_first_result()
410            .await
411            .map_err(classify_tiberius_error)?;
412
413        let json_rows: Vec<Value> = rows
414            .iter()
415            .map(|row| {
416                let mut obj = Map::new();
417                for (column, data) in row.cells() {
418                    obj.insert(column.name().to_string(), column_data_to_json(data));
419                }
420                Value::Object(obj)
421            })
422            .collect();
423        Ok(Value::Array(json_rows))
424    }
425}
426
427#[cfg(test)]
428mod tests {
429    use super::*;
430
431    #[test]
432    fn is_writable_kind_treats_views_and_functions_as_read_only() {
433        assert!(!is_writable_kind(Some("VIEW")));
434        assert!(!is_writable_kind(Some("SQL_SCALAR_FUNCTION")));
435        assert!(!is_writable_kind(Some("SQL_INLINE_TABLE_VALUED_FUNCTION")));
436        assert!(!is_writable_kind(Some("SQL_TABLE_VALUED_FUNCTION")));
437        assert!(!is_writable_kind(Some("CLR_TABLE_VALUED_FUNCTION")));
438    }
439
440    #[test]
441    fn is_writable_kind_treats_procedures_and_unknown_kinds_as_writable() {
442        assert!(is_writable_kind(Some("SQL_STORED_PROCEDURE")));
443        assert!(is_writable_kind(Some("EXTENDED_STORED_PROCEDURE")));
444        assert!(is_writable_kind(Some("CLR_STORED_PROCEDURE")));
445        assert!(is_writable_kind(None), "an unrecognized kind must fail closed");
446    }
447
448    #[test]
449    fn parse_path_splits_schema_name() {
450        assert_eq!(
451            parse_path("/INFORMATION_SCHEMA/COLUMNS").unwrap(),
452            ("INFORMATION_SCHEMA", "COLUMNS")
453        );
454    }
455
456    #[test]
457    fn parse_path_rejects_a_path_with_too_few_segments() {
458        assert!(parse_path("/COLUMNS").is_err());
459    }
460
461    #[test]
462    fn quote_ident_doubles_embedded_closing_brackets() {
463        assert_eq!(quote_ident("weird]name"), "[weird]]name]");
464    }
465
466    #[test]
467    fn validate_ident_accepts_alphanumeric_and_underscore() {
468        assert!(validate_ident("sp_who2").is_ok());
469        assert!(validate_ident("INFORMATION_SCHEMA").is_ok());
470    }
471
472    #[test]
473    fn validate_ident_rejects_anything_else() {
474        assert!(validate_ident("").is_err());
475        assert!(validate_ident("robert'; drop table endpoints;--").is_err());
476        assert!(validate_ident("weird]name").is_err());
477        assert!(validate_ident("has space").is_err());
478    }
479
480    #[test]
481    fn parse_path_rejects_a_path_with_an_unsafe_segment() {
482        assert!(parse_path("/sys/sp_who; DROP TABLE endpoints--").is_err());
483    }
484
485    #[test]
486    fn build_statement_selects_from_a_view_with_no_parameters() {
487        let (sql, bound) = build_statement(
488            "INFORMATION_SCHEMA",
489            "COLUMNS",
490            Some("VIEW"),
491            &[],
492            &Map::new(),
493            None,
494        )
495        .unwrap();
496        assert_eq!(sql, "SELECT * FROM [INFORMATION_SCHEMA].[COLUMNS]");
497        assert!(bound.is_empty());
498    }
499
500    #[test]
501    fn build_statement_execs_a_proc_with_named_parameters() {
502        let params = vec![
503            Param {
504                name: "objname".to_string(),
505                ordinal: 1,
506                x_sql_type: "nvarchar(1035)".to_string(),
507            },
508            Param {
509                name: "newname".to_string(),
510                ordinal: 2,
511                x_sql_type: "sysname".to_string(),
512            },
513        ];
514        let mut body = Map::new();
515        body.insert("objname".to_string(), Value::String("t1".to_string()));
516        body.insert("newname".to_string(), Value::String("t2".to_string()));
517        let (sql, bound) = build_statement(
518            "sys",
519            "sp_rename",
520            Some("SQL_STORED_PROCEDURE"),
521            &params,
522            &body,
523            Some("master"),
524        )
525        .unwrap();
526        assert_eq!(
527            sql,
528            "EXEC [master].[sys].[sp_rename] @objname = @P1, @newname = @P2"
529        );
530        assert_eq!(bound.len(), 2);
531    }
532
533    /// Regression test for incident 26-07-05700-04: every parameterized
534    /// stored-procedure `call` (e.g. `sp_columns`, `sp_executesql`) failed
535    /// with SQL Server error 102 "Incorrect syntax near '='", no matter
536    /// what argument keys the caller supplied, because the generated
537    /// assignment list bracket-quoted the parameter name (`[table_name] =
538    /// @P1`) instead of prefixing it with `@` (`@table_name = @P1`) --
539    /// bracket-quoting is valid for object identifiers, not for named
540    /// EXEC arguments. This asserts the `@`-prefixed form specifically, so
541    /// a future edit can't silently reintroduce bracket-quoting here even
542    /// if it still happens to produce syntactically-plausible-looking SQL.
543    #[test]
544    fn build_statement_uses_at_prefixed_names_not_bracket_quoting_for_named_exec_arguments() {
545        let params = vec![Param {
546            name: "table_name".to_string(),
547            ordinal: 1,
548            x_sql_type: "nvarchar(384)".to_string(),
549        }];
550        let mut body = Map::new();
551        body.insert(
552            "table_name".to_string(),
553            Value::String("databases".to_string()),
554        );
555        let (sql, _bound) = build_statement(
556            "sys",
557            "sp_columns",
558            Some("SQL_STORED_PROCEDURE"),
559            &params,
560            &body,
561            None,
562        )
563        .unwrap();
564        assert_eq!(sql, "EXEC [sys].[sp_columns] @table_name = @P1");
565        assert!(!sql.contains("[table_name]"));
566    }
567
568    #[test]
569    fn build_statement_selects_from_a_function_with_positional_placeholders() {
570        let params = vec![Param {
571            name: "session_id".to_string(),
572            ordinal: 1,
573            x_sql_type: "smallint".to_string(),
574        }];
575        let mut body = Map::new();
576        body.insert("session_id".to_string(), Value::from(52));
577        let (sql, bound) = build_statement(
578            "sys",
579            "dm_exec_sql_text",
580            Some("SQL_INLINE_TABLE_VALUED_FUNCTION"),
581            &params,
582            &body,
583            Some("master"),
584        )
585        .unwrap();
586        assert_eq!(sql, "SELECT * FROM [master].[sys].[dm_exec_sql_text](@P1)");
587        assert_eq!(bound.len(), 1);
588    }
589
590    #[test]
591    fn build_statement_omits_the_database_qualifier_by_default() {
592        let (sql, bound) =
593            build_statement("dbo", "widgets", Some("VIEW"), &[], &Map::new(), None).unwrap();
594        assert_eq!(sql, "SELECT * FROM [dbo].[widgets]");
595        assert!(bound.is_empty());
596    }
597
598    #[test]
599    fn build_statement_three_part_qualifies_with_a_requested_execution_database() {
600        let (sql, bound) = build_statement(
601            "dbo",
602            "widgets",
603            Some("VIEW"),
604            &[],
605            &Map::new(),
606            Some("reporting"),
607        )
608        .unwrap();
609        assert_eq!(sql, "SELECT * FROM [reporting].[dbo].[widgets]");
610        assert!(bound.is_empty());
611    }
612
613    #[test]
614    fn build_statement_execs_a_parameterless_proc() {
615        let (sql, bound) = build_statement(
616            "sys",
617            "sp_who",
618            Some("SQL_STORED_PROCEDURE"),
619            &[],
620            &Map::new(),
621            None,
622        )
623        .unwrap();
624        assert_eq!(sql, "EXEC [sys].[sp_who]");
625        assert!(bound.is_empty());
626    }
627
628    #[test]
629    fn ordered_params_excludes_the_synthetic_execution_database_property() {
630        let schema = serde_json::json!({
631            "properties": {
632                "body": { "$ref": "#/$defs/sys_sp_who_Request" }
633            },
634            "$defs": {
635                "sys_sp_who_Request": {
636                    "properties": {
637                        "loginame": { "x-sql-ordinal": 1, "x-sql-type": "sysname" },
638                        "execution_database": { "type": "string" }
639                    }
640                }
641            }
642        });
643
644        let params = ordered_params(&schema);
645        assert_eq!(params.len(), 1);
646        assert_eq!(params[0].name, "loginame");
647    }
648
649    #[test]
650    fn resolve_execution_database_prefers_the_body_property_over_the_configured_default() {
651        let mut body = Map::new();
652        body.insert(
653            EXECUTION_DATABASE_PARAM.to_string(),
654            Value::String("reporting".to_string()),
655        );
656        let mut config = test_config();
657        config.default_database = Some("fallback".to_string());
658        assert_eq!(
659            resolve_execution_database(&body, &config)
660                .unwrap()
661                .as_deref(),
662            Some("reporting")
663        );
664    }
665
666    #[test]
667    fn resolve_execution_database_falls_back_to_the_configured_default() {
668        let mut config = test_config();
669        config.default_database = Some("fallback".to_string());
670        assert_eq!(
671            resolve_execution_database(&Map::new(), &config)
672                .unwrap()
673                .as_deref(),
674            Some("fallback")
675        );
676    }
677
678    #[test]
679    fn resolve_execution_database_is_none_when_nothing_is_configured_or_supplied() {
680        assert_eq!(
681            resolve_execution_database(&Map::new(), &test_config()).unwrap(),
682            None
683        );
684    }
685
686    #[test]
687    fn resolve_execution_database_rejects_a_non_string_body_value() {
688        let mut body = Map::new();
689        body.insert(EXECUTION_DATABASE_PARAM.to_string(), Value::from(42));
690        assert!(resolve_execution_database(&body, &test_config()).is_err());
691    }
692
693    #[test]
694    fn resolve_execution_database_rejects_an_unsafe_body_value() {
695        let mut body = Map::new();
696        body.insert(
697            EXECUTION_DATABASE_PARAM.to_string(),
698            Value::String("robert'; drop table endpoints;--".to_string()),
699        );
700        assert!(resolve_execution_database(&body, &test_config()).is_err());
701    }
702
703    #[test]
704    fn resolve_execution_database_rejects_an_unsafe_configured_default() {
705        let mut config = test_config();
706        config.default_database = Some("has space".to_string());
707        assert!(resolve_execution_database(&Map::new(), &config).is_err());
708    }
709
710    fn test_config() -> Config {
711        Config {
712            url: "localhost".to_string(),
713            auth_method: crate::core::config_schema::AuthMethod::SqlServer,
714            sql_port: 1433,
715            pool_max_size: 10,
716            trust_server_cert: true,
717            api_version: "2025".to_string(),
718            log_level: "info".to_string(),
719            rate_limit: 100,
720            timeout_ms: 30_000,
721            cache_size: 500,
722            retry_attempts: 3,
723            transport: crate::core::config_schema::Transport::Stdio,
724            host: "127.0.0.1".to_string(),
725            port: 3000,
726            cors_allow: None,
727            default_database: None,
728            read_only: true,
729        }
730    }
731
732    #[test]
733    fn ordered_params_follow_the_schema_ordinals() {
734        // Matches the real shape every generated schema actually has (see
735        // `generated_schemas.json`): parameters live under `$defs`, `$ref`'d
736        // from the top-level `body` property, not as flat top-level
737        // properties.
738        let schema = serde_json::json!({
739            "properties": {
740                "body": { "$ref": "#/$defs/sys_example_Request" }
741            },
742            "$defs": {
743                "sys_example_Request": {
744                    "properties": {
745                        "second": { "x-sql-ordinal": 2, "x-sql-type": "int" },
746                        "first": { "x-sql-ordinal": 1, "x-sql-type": "nvarchar(20)" }
747                    }
748                }
749            }
750        });
751
752        let params = ordered_params(&schema);
753        assert_eq!(params.len(), 2);
754        assert_eq!(params[0].name, "first");
755        assert_eq!(params[0].x_sql_type, "nvarchar(20)");
756        assert_eq!(params[1].name, "second");
757    }
758
759    /// Regression test for incident 26-07-05700-04's underlying second bug:
760    /// `ordered_params` used to read the schema's literal top-level
761    /// `properties` map, which for every real generated schema is just
762    /// `{"body": {"$ref": ...}}` -- so every parameterized operation
763    /// collapsed to a single fake `body` parameter (observed live as
764    /// `EXEC ... @body = @P1` instead of the real named arguments) rather
765    /// than the operation's actual parameters.
766    #[test]
767    fn ordered_params_resolves_the_body_ref_wrapper() {
768        let schema = serde_json::json!({
769            "properties": {
770                "body": { "$ref": "#/$defs/sys_sp_columns_Request" }
771            },
772            "$defs": {
773                "sys_sp_columns_Request": {
774                    "properties": {
775                        "table_name": { "x-sql-ordinal": 1, "x-sql-type": "nvarchar(384)" },
776                        "table_owner": { "x-sql-ordinal": 2, "x-sql-type": "nvarchar(384)" }
777                    }
778                }
779            }
780        });
781
782        let params = ordered_params(&schema);
783        assert_eq!(params.len(), 2);
784        assert_eq!(params[0].name, "table_name");
785        assert_eq!(params[1].name, "table_owner");
786        assert!(params.iter().all(|p| p.name != "body"));
787    }
788
789    #[test]
790    fn ordered_params_resolves_an_inline_body_without_a_ref() {
791        let schema = serde_json::json!({
792            "properties": {
793                "body": {
794                    "properties": {
795                        "only": { "x-sql-ordinal": 1, "x-sql-type": "int" }
796                    }
797                }
798            }
799        });
800
801        let params = ordered_params(&schema);
802        assert_eq!(params.len(), 1);
803        assert_eq!(params[0].name, "only");
804    }
805
806    #[test]
807    fn ordered_params_is_empty_for_a_schema_with_no_body_property() {
808        let schema = serde_json::json!({ "properties": {} });
809        assert!(ordered_params(&schema).is_empty());
810    }
811
812    #[test]
813    fn build_statement_rejects_an_unsafe_parameter_name() {
814        let params = vec![Param {
815            name: "unsafe name".to_string(),
816            ordinal: 1,
817            x_sql_type: "int".to_string(),
818        }];
819
820        assert!(
821            build_statement(
822                "sys",
823                "sp_example",
824                Some("SQL_STORED_PROCEDURE"),
825                &params,
826                &Map::new(),
827                None,
828            )
829            .is_err()
830        );
831    }
832
833    #[test]
834    fn severity_category_maps_11_through_16_to_400_equivalent() {
835        for class in [11, 12, 13, 14 - 1, 15, 16] {
836            assert_eq!(severity_category(class), "statement/user error (400-equivalent)");
837        }
838    }
839
840    #[test]
841    fn severity_category_maps_14_to_403_equivalent() {
842        assert_eq!(severity_category(14), "permission denied (403-equivalent)");
843    }
844
845    #[test]
846    fn severity_category_maps_17_through_25_to_500_equivalent() {
847        for class in [17, 18, 20, 25] {
848            assert_eq!(severity_category(class), "fatal/resource error (500-equivalent)");
849        }
850    }
851
852    #[test]
853    fn severity_category_boundary_at_16_vs_17() {
854        assert_eq!(severity_category(16), "statement/user error (400-equivalent)");
855        assert_eq!(severity_category(17), "fatal/resource error (500-equivalent)");
856    }
857
858    #[test]
859    fn protocol_errors_are_classified_as_server_failures() {
860        let error =
861            classify_tiberius_error(tiberius::error::Error::Protocol("invalid packet".into()));
862        assert_eq!(
863            error.to_string(),
864            "SQL Server connection/protocol error (500-equivalent): Protocol error: invalid packet"
865        );
866    }
867}