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/// Recovers an operation's known home database when it's unambiguous, i.e.
92/// the object was found in exactly one of `master`/`msdb`/`model` at
93/// extraction time. `x-sql-databases` (the OpenAPI extension
94/// `tools/generate_openapi.py` records this on) isn't preserved into the
95/// runtime store (`data::store::EndpointRecord` has no such column, and
96/// every pre-built `mcp_store*.db` would need regenerating to add one), but
97/// the same fact is already embedded, as free text, in the synthetic
98/// `execution_database` property's generated description -- see that
99/// script's `build_request_schema`, which always writes "This object was
100/// found, identically, in: db1, db2, ...." Parsing it back out here avoids
101/// a store-schema/regeneration change for what is otherwise a pure
102/// read-time fix.
103fn single_known_database(input_schema: &Value) -> Option<String> {
104    let description = request_properties(input_schema)?
105        .get(EXECUTION_DATABASE_PARAM)?
106        .get("description")?
107        .as_str()?;
108    let after_marker = description.split("found, identically, in: ").nth(1)?;
109    let database_list = after_marker.split(". ").next()?;
110    let mut databases = database_list.split(", ").map(str::trim);
111    let only = databases.next().filter(|s| !s.is_empty())?;
112    match databases.next() {
113        None => Some(only.to_string()),
114        Some(_) => None,
115    }
116}
117
118/// Resolves an operation's execution-context database, in priority order:
119/// 1. the caller-supplied `execution_database` body property (see
120///    `EXECUTION_DATABASE_PARAM`), an explicit per-call override;
121/// 2. the operation's own known home database, when `single_known_database`
122///    can recover an unambiguous one -- a stored fact about where the
123///    object actually lives takes precedence over a generic configured
124///    default, since qualifying to any *other* database for a
125///    single-database object (e.g. an `msdb`-only SQL Agent procedure)
126///    can't ever succeed regardless of what the caller intended;
127/// 3. the server's configured `Config::default_database`, if one was set
128///    up (optional, see `cli::setup_wizard`), as a convenience default for
129///    genuinely ambiguous (multi-database) operations;
130/// 4. `None`, meaning `build_statement` two-part-qualifies the call and
131///    lets the connection's own current database context resolve it
132///    (equivalent to `DB_NAME()`/`DB_ID()`).
133fn resolve_execution_database(
134    body: &Map<String, Value>,
135    input_schema: &Value,
136    config: &Config,
137) -> anyhow::Result<Option<String>> {
138    if let Some(value) = body.get(EXECUTION_DATABASE_PARAM) {
139        let requested = value
140            .as_str()
141            .ok_or_else(|| anyhow::anyhow!("'{EXECUTION_DATABASE_PARAM}' must be a string"))?;
142        return Ok(Some(validate_ident(requested)?.to_string()));
143    }
144    if let Some(database) = single_known_database(input_schema) {
145        return Ok(Some(validate_ident(&database)?.to_string()));
146    }
147    config
148        .default_database
149        .as_deref()
150        .map(validate_ident)
151        .transpose()
152        .map(|opt| opt.map(str::to_string))
153}
154
155struct Param {
156    name: String,
157    ordinal: u64,
158    x_sql_type: String,
159}
160
161/// Every operation's generated input schema wraps its real parameters one
162/// level down, under a single top-level `body` property (mcpify's
163/// request-body convention -- see `ApiClient::execute`'s own `body`
164/// extraction from the caller's `args`, which this mirrors), almost always
165/// as a `$ref` into the schema's own `$defs` rather than an inline object.
166/// Resolves that wrapper (and its `$ref`, if present) to the real
167/// parameter-name map. Returns `None` for a schema with no `body` property
168/// at all (a parameterless operation), which `ordered_params` below treats
169/// as zero parameters.
170fn request_properties(input_schema: &Value) -> Option<&Map<String, Value>> {
171    let body_schema = input_schema.get("properties")?.get("body")?;
172    let resolved = match body_schema.get("$ref").and_then(Value::as_str) {
173        Some(reference) => reference
174            .strip_prefix("#/$defs/")
175            .and_then(|name| input_schema.get("$defs")?.get(name))?,
176        None => body_schema,
177    };
178    resolved.get("properties").and_then(Value::as_object)
179}
180
181/// Reads `properties`/`x-sql-ordinal`/`x-sql-type` off a resolved input
182/// schema (see `tools/generate_openapi.py`'s `build_request_schema`),
183/// sorted by declared ordinal -- required for a table-valued function's
184/// positional call syntax, and used for stored procedures' named syntax
185/// mainly for a deterministic/readable generated statement.
186fn ordered_params(input_schema: &Value) -> Vec<Param> {
187    let mut params: Vec<Param> = request_properties(input_schema)
188        .into_iter()
189        .flatten()
190        .filter(|(name, _)| name.as_str() != EXECUTION_DATABASE_PARAM)
191        .map(|(name, schema)| Param {
192            name: name.clone(),
193            ordinal: schema
194                .get("x-sql-ordinal")
195                .and_then(Value::as_u64)
196                .unwrap_or(0),
197            x_sql_type: schema
198                .get("x-sql-type")
199                .and_then(Value::as_str)
200                .unwrap_or("nvarchar(max)")
201                .to_string(),
202        })
203        .collect();
204    params.sort_by_key(|p| p.ordinal);
205    params
206}
207
208/// Builds the T-SQL text (with `@P1`/`@P2`/... placeholders) and the
209/// matching positionally-ordered bound parameters for one operation call.
210///
211/// `execution_database` is the resolved value of the synthetic
212/// `execution_database` request property (see `resolve_execution_database`)
213/// -- every operation now behaves the way only `sandbox`-tagged operations
214/// used to: three-part-qualified (`db.schema.name`) when a database is
215/// known, two-part-qualified (`schema.name`, resolved against the
216/// connection's own current database context) when it isn't. There is no
217/// per-operation baked-in database anymore -- a deduplicated operation may
218/// exist identically in more than one of master/msdb/model (see
219/// `docs/sqlserver-eda-openapi-pipeline/README.md`'s "OpenAPI mapping
220/// convention"), so which one to actually hit is always resolved per call.
221/// Whether `kind` (an operation's catalog `sys.objects.type_desc`) can
222/// perform a write, mirroring `build_statement`'s own classification.
223/// `VIEW` and any `*_FUNCTION` kind cannot: a view is only ever queried
224/// with a bare `SELECT`, and T-SQL functions are language-level prohibited
225/// from having side effects (SQL Server rejects a `CREATE FUNCTION` body
226/// containing `INSERT`/`UPDATE`/`DELETE` outside a table variable), so
227/// both are genuinely engine-guaranteed read-only, not just app-level
228/// convention. Everything else -- `SQL_STORED_PROCEDURE`,
229/// `EXTENDED_STORED_PROCEDURE`, or a missing/unrecognized classification
230/// (an older store built before `description` carried this classification)
231/// -- has no such guarantee and is treated as write-capable, failing
232/// closed rather than assuming an unknown kind is safe.
233fn is_writable_kind(kind: Option<&str>) -> bool {
234    // The shipped `mcp_store*.db` (built from the generated OpenAPI spec's
235    // `description`, itself `sys.objects.type_desc`) stores this as
236    // space-separated words -- "SQL TABLE VALUED FUNCTION", not
237    // `sys.objects.type_desc`'s own underscore form
238    // "SQL_TABLE_VALUED_FUNCTION" -- so matching on `_FUNCTION`/
239    // `TABLE_VALUED_FUNCTION` literally never matched any function kind in
240    // production, silently blocking every function call under
241    // `read_only` (the default) despite the engine guaranteeing functions
242    // can't have side effects. Normalizing underscores to spaces before
243    // matching handles both the space form actually shipped today and the
244    // underscore form these doc comments (and `sys.objects.type_desc`
245    // itself) describe, so this keeps working regardless of which
246    // convention a future store build uses.
247    let normalized = kind.map(|k| k.replace('_', " "));
248    match normalized.as_deref() {
249        Some("VIEW") => false,
250        Some(k) if k.ends_with(" FUNCTION") || k.contains("TABLE VALUED FUNCTION") => false,
251        _ => true,
252    }
253}
254
255fn build_statement(
256    schema: &str,
257    name: &str,
258    kind: Option<&str>,
259    params: &[Param],
260    body: &Map<String, Value>,
261    execution_database: Option<&str>,
262) -> anyhow::Result<(String, Vec<Box<dyn ToSql>>)> {
263    let qualified = match execution_database {
264        Some(db) => format!(
265            "{}.{}.{}",
266            quote_ident(db),
267            quote_ident(schema),
268            quote_ident(name)
269        ),
270        None => format!("{}.{}", quote_ident(schema), quote_ident(name)),
271    };
272
273    let mut bound: Vec<Box<dyn ToSql>> = Vec::with_capacity(params.len());
274    for param in params {
275        let value = body.get(&param.name).cloned().unwrap_or(Value::Null);
276        bound.push(json_to_param(&value, &param.x_sql_type)?);
277    }
278
279    // See `is_writable_kind`'s doc comment: the shipped `mcp_store*.db`
280    // stores this classification space-separated ("SQL TABLE VALUED
281    // FUNCTION"), not with `sys.objects.type_desc`'s own underscores, so
282    // matching must normalize the same way here.
283    let normalized_kind = kind.map(|k| k.replace('_', " "));
284    let sql = match normalized_kind.as_deref() {
285        Some("VIEW") => format!("SELECT * FROM {qualified}"),
286        // Table-valued functions are a row source: `SELECT * FROM
287        // name(args)`. Checked before the scalar-function arm below since
288        // every table-valued kind also ends with " FUNCTION".
289        Some(k) if k.contains("TABLE VALUED FUNCTION") => {
290            let placeholders = (1..=bound.len())
291                .map(|i| format!("@P{i}"))
292                .collect::<Vec<_>>()
293                .join(", ");
294            format!("SELECT * FROM {qualified}({placeholders})")
295        }
296        // A scalar function returns a single value, not a row source --
297        // `SELECT * FROM name(args)` is a syntax error for one (only a
298        // table-valued function can appear after `FROM`); the correct call
299        // is a bare `SELECT name(args)`.
300        Some(k) if k.ends_with(" FUNCTION") => {
301            let placeholders = (1..=bound.len())
302                .map(|i| format!("@P{i}"))
303                .collect::<Vec<_>>()
304                .join(", ");
305            format!("SELECT {qualified}({placeholders})")
306        }
307        // Stored procedures (SQL_STORED_PROCEDURE/EXTENDED_STORED_PROCEDURE)
308        // and the `kind.is_none()` fallback (an older store built before
309        // `description` carried this classification) both take the EXEC
310        // path -- named parameter syntax, so a proc with only optional
311        // parameters and no arguments supplied still works (`bound` empty
312        // produces a bare `EXEC name`).
313        _ => {
314            if bound.is_empty() {
315                format!("EXEC {qualified}")
316            } else {
317                let mut assignments = Vec::with_capacity(params.len());
318                for (i, p) in params.iter().enumerate() {
319                    // Named EXEC-argument syntax requires the `@` sigil
320                    // directly on the parameter name (`EXEC proc @param =
321                    // value`, not `EXEC proc [param] = value` or
322                    // `EXEC proc param = value`) -- bracket-quoting is for
323                    // object identifiers, not parameter references, and
324                    // using it here produced a syntax error on every
325                    // parameterized stored-procedure call. `validate_ident`
326                    // still runs first for the same defense-in-depth reason
327                    // as the object-identifier path above.
328                    assignments.push(format!("@{} = @P{}", validate_ident(&p.name)?, i + 1));
329                }
330                format!("EXEC {qualified} {}", assignments.join(", "))
331            }
332        }
333    };
334
335    Ok((sql, bound))
336}
337
338/// The severity-to-status-category mapping documented on every generated
339/// operation's 400/403/500 responses (see `docs/sqlserver-eda-openapi-pipeline
340/// /README.md`'s "OpenAPI mapping convention") -- pulled out of
341/// `classify_tiberius_error` as its own pure function so this classification
342/// logic is unit-testable directly. `tiberius::tds::codec::TokenError`'s
343/// fields are all `pub(crate)` with no public constructor, so a
344/// `tiberius::error::Error::Server(_)` can never be built from outside the
345/// crate for a test to exercise the branch that reads `class` off it --
346/// this function is what actually stays testable.
347fn severity_category(class: u8) -> &'static str {
348    if class >= 17 {
349        "fatal/resource error (500-equivalent)"
350    } else if class == 14 {
351        "permission denied (403-equivalent)"
352    } else {
353        "statement/user error (400-equivalent)"
354    }
355}
356
357/// Maps a `tiberius` error to this project's synthetic 400/403/500 split
358/// (see `docs/sqlserver-eda-openapi-pipeline/README.md`'s "OpenAPI mapping
359/// convention" -- SQL Server severity 11-16 statement errors are `400`,
360/// severity-14 permission errors are `403`, severity 17-25 engine/fatal
361/// errors are `500`), rather than surfacing the raw driver error
362/// undifferentiated. Returned as a JSON value matching
363/// `components.schemas.SqlServerError` shape rather than a bare string, so
364/// callers get the same structured error either way they might have gotten
365/// it from a real synchronous SQL Server error.
366fn classify_tiberius_error(err: tiberius::error::Error) -> anyhow::Error {
367    use tiberius::error::Error as TError;
368    match &err {
369        TError::Server(token) => {
370            let (number, state, class, message, procedure, line) = (
371                token.code(),
372                token.state(),
373                token.class(),
374                token.message(),
375                token.procedure(),
376                token.line(),
377            );
378            let category = severity_category(class);
379            anyhow::anyhow!(
380                "SQL Server error {number} (severity {class}, state {state}) in '{procedure}' line {line}: {message} [{category}]"
381            )
382        }
383        other => anyhow::anyhow!("SQL Server connection/protocol error (500-equivalent): {other}"),
384    }
385}
386
387pub struct ApiClient {
388    config: Config,
389}
390
391impl ApiClient {
392    pub fn new(config: Config) -> Self {
393        Self { config }
394    }
395
396    /// Executes `endpoint` against the configured SQL Server instance.
397    /// `auth_manager` resolves to a `tiberius::AuthMethod` (see
398    /// `auth::auth_manager::AuthManager::resolve_tds_auth`) from the
399    /// server's own configured credentials -- there is no per-request
400    /// credential override; SQL Server auth is always this server's own
401    /// configured identity, not something a caller supplies per call.
402    pub async fn execute(
403        &self,
404        endpoint: &EndpointRecord,
405        args: &Value,
406        auth_manager: &mut AuthManager,
407    ) -> anyhow::Result<Value> {
408        if self.config.read_only && is_writable_kind(endpoint.description.as_deref()) {
409            anyhow::bail!(
410                "operation '{}' is a {} and cannot run while read_only is enabled; set read_only to false to allow it",
411                endpoint.operation_id,
412                endpoint
413                    .description
414                    .as_deref()
415                    .unwrap_or("object of unrecognized type"),
416            );
417        }
418
419        let (schema, name) = parse_path(&endpoint.path)?;
420
421        let (input_schema, _output_schema) =
422            resolved_schemas_for(&self.config.api_version, &endpoint.operation_id).ok_or_else(
423                || {
424                    anyhow::anyhow!(
425                        "no resolved schema found for operation '{}' under api_version '{}'",
426                        endpoint.operation_id,
427                        self.config.api_version
428                    )
429                },
430            )?;
431        let params = ordered_params(input_schema);
432
433        let empty = Map::new();
434        let args_map = args.as_object().unwrap_or(&empty);
435        let body = args_map
436            .get("body")
437            .and_then(Value::as_object)
438            .cloned()
439            .unwrap_or_default();
440        let execution_database = resolve_execution_database(&body, input_schema, &self.config)?;
441
442        let (sql, bound) = build_statement(
443            schema,
444            name,
445            endpoint.description.as_deref(),
446            &params,
447            &body,
448            execution_database.as_deref(),
449        )?;
450
451        let auth_method = auth_manager.resolve_tds_auth().await?;
452
453        let (host, port) = self.config.host_and_port();
454        let mut tiberius_config = tiberius::Config::new();
455        tiberius_config.host(host);
456        tiberius_config.port(port);
457        tiberius_config.authentication(auth_method);
458        if self.config.trust_server_cert {
459            // Curated system-catalog objects, not user data -- trusting the
460            // server cert matches this project's primary use case (a local
461            // Docker/dev instance with a self-signed cert; see
462            // docs/sqlserver-eda-openapi-pipeline/docker-compose.yml)
463            // rather than requiring every operator to supply a CA bundle
464            // before the first query works. Set `trust_server_cert: false`
465            // for a production instance with a real CA-signed cert.
466            tiberius_config.trust_cert();
467        }
468
469        let pool_key = format!("{host}:{port}");
470        let pool =
471            sql_pool::cached_pool(&pool_key, tiberius_config, self.config.pool_max_size).await?;
472        let mut conn = pool.get().await.map_err(|err| {
473            anyhow::anyhow!("failed to obtain a pooled SQL Server connection: {err}")
474        })?;
475
476        let bound_refs: Vec<&dyn ToSql> = bound.iter().map(|param| param.as_ref()).collect();
477        let stream = conn
478            .query(&sql, &bound_refs)
479            .await
480            .map_err(classify_tiberius_error)?;
481        let rows = stream
482            .into_first_result()
483            .await
484            .map_err(classify_tiberius_error)?;
485
486        let json_rows: Vec<Value> = rows
487            .iter()
488            .map(|row| {
489                let mut obj = Map::new();
490                for (column, data) in row.cells() {
491                    obj.insert(column.name().to_string(), column_data_to_json(data));
492                }
493                Value::Object(obj)
494            })
495            .collect();
496        Ok(Value::Array(json_rows))
497    }
498}
499
500#[cfg(test)]
501mod tests {
502    use super::*;
503
504    #[test]
505    fn is_writable_kind_treats_views_and_functions_as_read_only() {
506        assert!(!is_writable_kind(Some("VIEW")));
507        assert!(!is_writable_kind(Some("SQL_SCALAR_FUNCTION")));
508        assert!(!is_writable_kind(Some("SQL_INLINE_TABLE_VALUED_FUNCTION")));
509        assert!(!is_writable_kind(Some("SQL_TABLE_VALUED_FUNCTION")));
510        assert!(!is_writable_kind(Some("CLR_TABLE_VALUED_FUNCTION")));
511    }
512
513    /// Regression test: the shipped `mcp_store*.db` actually stores this
514    /// classification space-separated ("SQL TABLE VALUED FUNCTION"), not
515    /// with `sys.objects.type_desc`'s own underscores -- confirmed by
516    /// querying the real embedded store's `endpoints.description` column,
517    /// which returns exactly these four function-kind strings (plus `VIEW`
518    /// and two stored-procedure kinds). Before this fix, every function
519    /// call was wrongly blocked under `read_only` (the default) because
520    /// `is_writable_kind` only ever matched the underscore form.
521    #[test]
522    fn is_writable_kind_treats_the_shipped_stores_space_separated_kinds_as_read_only() {
523        assert!(!is_writable_kind(Some("VIEW")));
524        assert!(!is_writable_kind(Some("SQL SCALAR FUNCTION")));
525        assert!(!is_writable_kind(Some("CLR SCALAR FUNCTION")));
526        assert!(!is_writable_kind(Some("SQL INLINE TABLE VALUED FUNCTION")));
527        assert!(!is_writable_kind(Some("SQL TABLE VALUED FUNCTION")));
528    }
529
530    #[test]
531    fn is_writable_kind_treats_procedures_and_unknown_kinds_as_writable() {
532        assert!(is_writable_kind(Some("SQL_STORED_PROCEDURE")));
533        assert!(is_writable_kind(Some("EXTENDED_STORED_PROCEDURE")));
534        assert!(is_writable_kind(Some("CLR_STORED_PROCEDURE")));
535        assert!(is_writable_kind(Some("SQL STORED PROCEDURE")));
536        assert!(is_writable_kind(Some("CLR STORED PROCEDURE")));
537        assert!(
538            is_writable_kind(None),
539            "an unrecognized kind must fail closed"
540        );
541    }
542
543    #[test]
544    fn parse_path_splits_schema_name() {
545        assert_eq!(
546            parse_path("/INFORMATION_SCHEMA/COLUMNS").unwrap(),
547            ("INFORMATION_SCHEMA", "COLUMNS")
548        );
549    }
550
551    #[test]
552    fn parse_path_rejects_a_path_with_too_few_segments() {
553        assert!(parse_path("/COLUMNS").is_err());
554    }
555
556    #[test]
557    fn quote_ident_doubles_embedded_closing_brackets() {
558        assert_eq!(quote_ident("weird]name"), "[weird]]name]");
559    }
560
561    #[test]
562    fn validate_ident_accepts_alphanumeric_and_underscore() {
563        assert!(validate_ident("sp_who2").is_ok());
564        assert!(validate_ident("INFORMATION_SCHEMA").is_ok());
565    }
566
567    #[test]
568    fn validate_ident_rejects_anything_else() {
569        assert!(validate_ident("").is_err());
570        assert!(validate_ident("robert'; drop table endpoints;--").is_err());
571        assert!(validate_ident("weird]name").is_err());
572        assert!(validate_ident("has space").is_err());
573    }
574
575    #[test]
576    fn parse_path_rejects_a_path_with_an_unsafe_segment() {
577        assert!(parse_path("/sys/sp_who; DROP TABLE endpoints--").is_err());
578    }
579
580    #[test]
581    fn build_statement_selects_from_a_view_with_no_parameters() {
582        let (sql, bound) = build_statement(
583            "INFORMATION_SCHEMA",
584            "COLUMNS",
585            Some("VIEW"),
586            &[],
587            &Map::new(),
588            None,
589        )
590        .unwrap();
591        assert_eq!(sql, "SELECT * FROM [INFORMATION_SCHEMA].[COLUMNS]");
592        assert!(bound.is_empty());
593    }
594
595    #[test]
596    fn build_statement_execs_a_proc_with_named_parameters() {
597        let params = vec![
598            Param {
599                name: "objname".to_string(),
600                ordinal: 1,
601                x_sql_type: "nvarchar(1035)".to_string(),
602            },
603            Param {
604                name: "newname".to_string(),
605                ordinal: 2,
606                x_sql_type: "sysname".to_string(),
607            },
608        ];
609        let mut body = Map::new();
610        body.insert("objname".to_string(), Value::String("t1".to_string()));
611        body.insert("newname".to_string(), Value::String("t2".to_string()));
612        let (sql, bound) = build_statement(
613            "sys",
614            "sp_rename",
615            Some("SQL_STORED_PROCEDURE"),
616            &params,
617            &body,
618            Some("master"),
619        )
620        .unwrap();
621        assert_eq!(
622            sql,
623            "EXEC [master].[sys].[sp_rename] @objname = @P1, @newname = @P2"
624        );
625        assert_eq!(bound.len(), 2);
626    }
627
628    /// Regression test for incident 26-07-05700-04: every parameterized
629    /// stored-procedure `call` (e.g. `sp_columns`, `sp_executesql`) failed
630    /// with SQL Server error 102 "Incorrect syntax near '='", no matter
631    /// what argument keys the caller supplied, because the generated
632    /// assignment list bracket-quoted the parameter name (`[table_name] =
633    /// @P1`) instead of prefixing it with `@` (`@table_name = @P1`) --
634    /// bracket-quoting is valid for object identifiers, not for named
635    /// EXEC arguments. This asserts the `@`-prefixed form specifically, so
636    /// a future edit can't silently reintroduce bracket-quoting here even
637    /// if it still happens to produce syntactically-plausible-looking SQL.
638    #[test]
639    fn build_statement_uses_at_prefixed_names_not_bracket_quoting_for_named_exec_arguments() {
640        let params = vec![Param {
641            name: "table_name".to_string(),
642            ordinal: 1,
643            x_sql_type: "nvarchar(384)".to_string(),
644        }];
645        let mut body = Map::new();
646        body.insert(
647            "table_name".to_string(),
648            Value::String("databases".to_string()),
649        );
650        let (sql, _bound) = build_statement(
651            "sys",
652            "sp_columns",
653            Some("SQL_STORED_PROCEDURE"),
654            &params,
655            &body,
656            None,
657        )
658        .unwrap();
659        assert_eq!(sql, "EXEC [sys].[sp_columns] @table_name = @P1");
660        assert!(!sql.contains("[table_name]"));
661    }
662
663    #[test]
664    fn build_statement_selects_from_a_function_with_positional_placeholders() {
665        let params = vec![Param {
666            name: "session_id".to_string(),
667            ordinal: 1,
668            x_sql_type: "smallint".to_string(),
669        }];
670        let mut body = Map::new();
671        body.insert("session_id".to_string(), Value::from(52));
672        let (sql, bound) = build_statement(
673            "sys",
674            "dm_exec_sql_text",
675            Some("SQL_INLINE_TABLE_VALUED_FUNCTION"),
676            &params,
677            &body,
678            Some("master"),
679        )
680        .unwrap();
681        assert_eq!(sql, "SELECT * FROM [master].[sys].[dm_exec_sql_text](@P1)");
682        assert_eq!(bound.len(), 1);
683    }
684
685    /// Regression test: the shipped store's actual space-separated kind
686    /// string ("SQL TABLE VALUED FUNCTION", confirmed by querying the real
687    /// embedded `mcp_store.db`) must resolve to the same `SELECT * FROM
688    /// name(args)` shape as the underscore form the test above uses --
689    /// before this fix, this kind fell through to the `EXEC` (stored
690    /// procedure) branch, which SQL Server rejects for a function object.
691    #[test]
692    fn build_statement_selects_from_a_function_with_the_shipped_stores_space_separated_kind() {
693        let params = vec![Param {
694            name: "session_id".to_string(),
695            ordinal: 1,
696            x_sql_type: "smallint".to_string(),
697        }];
698        let mut body = Map::new();
699        body.insert("session_id".to_string(), Value::from(52));
700        let (sql, bound) = build_statement(
701            "sys",
702            "dm_exec_sql_text",
703            Some("SQL TABLE VALUED FUNCTION"),
704            &params,
705            &body,
706            None,
707        )
708        .unwrap();
709        assert_eq!(sql, "SELECT * FROM [sys].[dm_exec_sql_text](@P1)");
710        assert_eq!(bound.len(), 1);
711    }
712
713    /// Regression test: a scalar function isn't a row source -- `SELECT *
714    /// FROM name(args)` is a SQL Server syntax error for one, only valid
715    /// for a table-valued function. Before this fix, every scalar-function
716    /// kind (underscore or the shipped store's space form) either matched
717    /// the table-valued branch (wrong syntax) or, before the
718    /// `is_writable_kind` fix, never got this far at all because it was
719    /// wrongly blocked under `read_only`.
720    #[test]
721    fn build_statement_calls_a_scalar_function_without_a_from_clause() {
722        let params = vec![Param {
723            name: "id".to_string(),
724            ordinal: 1,
725            x_sql_type: "int".to_string(),
726        }];
727        let mut body = Map::new();
728        body.insert("id".to_string(), Value::from(1));
729        for kind in ["SQL_SCALAR_FUNCTION", "SQL SCALAR FUNCTION"] {
730            let (sql, bound) = build_statement(
731                "dbo",
732                "widget_price",
733                Some(kind),
734                &params,
735                &body,
736                None,
737            )
738            .unwrap();
739            assert_eq!(sql, "SELECT [dbo].[widget_price](@P1)");
740            assert_eq!(bound.len(), 1);
741        }
742    }
743
744    #[test]
745    fn build_statement_omits_the_database_qualifier_by_default() {
746        let (sql, bound) =
747            build_statement("dbo", "widgets", Some("VIEW"), &[], &Map::new(), None).unwrap();
748        assert_eq!(sql, "SELECT * FROM [dbo].[widgets]");
749        assert!(bound.is_empty());
750    }
751
752    #[test]
753    fn build_statement_three_part_qualifies_with_a_requested_execution_database() {
754        let (sql, bound) = build_statement(
755            "dbo",
756            "widgets",
757            Some("VIEW"),
758            &[],
759            &Map::new(),
760            Some("reporting"),
761        )
762        .unwrap();
763        assert_eq!(sql, "SELECT * FROM [reporting].[dbo].[widgets]");
764        assert!(bound.is_empty());
765    }
766
767    #[test]
768    fn build_statement_execs_a_parameterless_proc() {
769        let (sql, bound) = build_statement(
770            "sys",
771            "sp_who",
772            Some("SQL_STORED_PROCEDURE"),
773            &[],
774            &Map::new(),
775            None,
776        )
777        .unwrap();
778        assert_eq!(sql, "EXEC [sys].[sp_who]");
779        assert!(bound.is_empty());
780    }
781
782    #[test]
783    fn single_known_database_recovers_the_lone_database_from_the_generated_description() {
784        let schema = serde_json::json!({
785            "properties": {
786                "body": {
787                    "properties": {
788                        "execution_database": {
789                            "description": "This object was found, identically, in: msdb. \
790                                             If omitted, the server's configured default \
791                                             database is used.",
792                        }
793                    }
794                }
795            }
796        });
797        assert_eq!(single_known_database(&schema).as_deref(), Some("msdb"));
798    }
799
800    #[test]
801    fn single_known_database_is_none_for_a_multi_database_operation() {
802        let schema = serde_json::json!({
803            "properties": {
804                "body": {
805                    "properties": {
806                        "execution_database": {
807                            "description": "This object was found, identically, in: master, \
808                                             model, msdb. If omitted, ...",
809                        }
810                    }
811                }
812            }
813        });
814        assert_eq!(single_known_database(&schema), None);
815    }
816
817    #[test]
818    fn single_known_database_is_none_when_the_schema_has_no_execution_database_property() {
819        let schema = serde_json::json!({ "properties": { "body": { "properties": {} } } });
820        assert_eq!(single_known_database(&schema), None);
821    }
822
823    #[test]
824    fn ordered_params_excludes_the_synthetic_execution_database_property() {
825        let schema = serde_json::json!({
826            "properties": {
827                "body": { "$ref": "#/$defs/sys_sp_who_Request" }
828            },
829            "$defs": {
830                "sys_sp_who_Request": {
831                    "properties": {
832                        "loginame": { "x-sql-ordinal": 1, "x-sql-type": "sysname" },
833                        "execution_database": { "type": "string" }
834                    }
835                }
836            }
837        });
838
839        let params = ordered_params(&schema);
840        assert_eq!(params.len(), 1);
841        assert_eq!(params[0].name, "loginame");
842    }
843
844    /// An `input_schema` shaped like `tools/generate_openapi.py`'s
845    /// generated `execution_database` property, with a description
846    /// documenting the given `found_in` database list -- mirrors
847    /// `build_request_schema`'s "This object was found, identically, in:
848    /// ..." text exactly, since `single_known_database` parses that text.
849    fn schema_found_in(found_in: &[&str]) -> Value {
850        serde_json::json!({
851            "properties": {
852                "body": {
853                    "properties": {
854                        "execution_database": {
855                            "type": "string",
856                            "description": format!(
857                                "Optional execution context: the database to run this \
858                                 operation against. This object was found, identically, in: \
859                                 {}. If omitted, the server's configured default database is \
860                                 used if one was set up (optional, see setup); otherwise the \
861                                 connection's own current database context applies.",
862                                found_in.join(", "),
863                            ),
864                        }
865                    }
866                }
867            }
868        })
869    }
870
871    fn no_execution_database_schema() -> Value {
872        serde_json::json!({ "properties": { "body": { "properties": {} } } })
873    }
874
875    #[test]
876    fn resolve_execution_database_prefers_the_body_property_over_everything_else() {
877        let mut body = Map::new();
878        body.insert(
879            EXECUTION_DATABASE_PARAM.to_string(),
880            Value::String("reporting".to_string()),
881        );
882        let mut config = test_config();
883        config.default_database = Some("fallback".to_string());
884        assert_eq!(
885            resolve_execution_database(&body, &schema_found_in(&["msdb"]), &config)
886                .unwrap()
887                .as_deref(),
888            Some("reporting")
889        );
890    }
891
892    /// Regression test: a caller reported that operations only found in
893    /// `msdb` (e.g. SQL Agent stored procedures) were executing against
894    /// whatever database the connection's context/configured default
895    /// happened to be instead of `msdb`, since nothing consulted the
896    /// object's known home database when `execution_database` was omitted.
897    #[test]
898    fn resolve_execution_database_prefers_the_operations_single_known_database_over_the_configured_default()
899     {
900        let mut config = test_config();
901        config.default_database = Some("master".to_string());
902        assert_eq!(
903            resolve_execution_database(&Map::new(), &schema_found_in(&["msdb"]), &config)
904                .unwrap()
905                .as_deref(),
906            Some("msdb")
907        );
908    }
909
910    #[test]
911    fn resolve_execution_database_does_not_guess_when_the_operation_is_multi_database() {
912        let mut config = test_config();
913        config.default_database = Some("fallback".to_string());
914        assert_eq!(
915            resolve_execution_database(
916                &Map::new(),
917                &schema_found_in(&["master", "model", "msdb"]),
918                &config,
919            )
920            .unwrap()
921            .as_deref(),
922            Some("fallback"),
923        );
924    }
925
926    #[test]
927    fn resolve_execution_database_falls_back_to_the_configured_default() {
928        let mut config = test_config();
929        config.default_database = Some("fallback".to_string());
930        assert_eq!(
931            resolve_execution_database(&Map::new(), &no_execution_database_schema(), &config)
932                .unwrap()
933                .as_deref(),
934            Some("fallback")
935        );
936    }
937
938    #[test]
939    fn resolve_execution_database_is_none_when_nothing_is_configured_or_supplied() {
940        assert_eq!(
941            resolve_execution_database(&Map::new(), &no_execution_database_schema(), &test_config())
942                .unwrap(),
943            None
944        );
945    }
946
947    #[test]
948    fn resolve_execution_database_rejects_a_non_string_body_value() {
949        let mut body = Map::new();
950        body.insert(EXECUTION_DATABASE_PARAM.to_string(), Value::from(42));
951        assert!(
952            resolve_execution_database(&body, &no_execution_database_schema(), &test_config())
953                .is_err()
954        );
955    }
956
957    #[test]
958    fn resolve_execution_database_rejects_an_unsafe_body_value() {
959        let mut body = Map::new();
960        body.insert(
961            EXECUTION_DATABASE_PARAM.to_string(),
962            Value::String("robert'; drop table endpoints;--".to_string()),
963        );
964        assert!(
965            resolve_execution_database(&body, &no_execution_database_schema(), &test_config())
966                .is_err()
967        );
968    }
969
970    #[test]
971    fn resolve_execution_database_rejects_an_unsafe_configured_default() {
972        let mut config = test_config();
973        config.default_database = Some("has space".to_string());
974        assert!(
975            resolve_execution_database(&Map::new(), &no_execution_database_schema(), &config)
976                .is_err()
977        );
978    }
979
980    fn test_config() -> Config {
981        Config {
982            url: "localhost".to_string(),
983            auth_method: crate::core::config_schema::AuthMethod::SqlServer,
984            sql_port: 1433,
985            pool_max_size: 10,
986            trust_server_cert: true,
987            api_version: "2025".to_string(),
988            log_level: "info".to_string(),
989            rate_limit: 100,
990            timeout_ms: 30_000,
991            cache_size: 500,
992            retry_attempts: 3,
993            transport: crate::core::config_schema::Transport::Stdio,
994            host: "127.0.0.1".to_string(),
995            port: 3000,
996            cors_allow: None,
997            default_database: None,
998            read_only: true,
999        }
1000    }
1001
1002    #[test]
1003    fn ordered_params_follow_the_schema_ordinals() {
1004        // Matches the real shape every generated schema actually has (see
1005        // `generated_schemas.json`): parameters live under `$defs`, `$ref`'d
1006        // from the top-level `body` property, not as flat top-level
1007        // properties.
1008        let schema = serde_json::json!({
1009            "properties": {
1010                "body": { "$ref": "#/$defs/sys_example_Request" }
1011            },
1012            "$defs": {
1013                "sys_example_Request": {
1014                    "properties": {
1015                        "second": { "x-sql-ordinal": 2, "x-sql-type": "int" },
1016                        "first": { "x-sql-ordinal": 1, "x-sql-type": "nvarchar(20)" }
1017                    }
1018                }
1019            }
1020        });
1021
1022        let params = ordered_params(&schema);
1023        assert_eq!(params.len(), 2);
1024        assert_eq!(params[0].name, "first");
1025        assert_eq!(params[0].x_sql_type, "nvarchar(20)");
1026        assert_eq!(params[1].name, "second");
1027    }
1028
1029    /// Regression test for incident 26-07-05700-04's underlying second bug:
1030    /// `ordered_params` used to read the schema's literal top-level
1031    /// `properties` map, which for every real generated schema is just
1032    /// `{"body": {"$ref": ...}}` -- so every parameterized operation
1033    /// collapsed to a single fake `body` parameter (observed live as
1034    /// `EXEC ... @body = @P1` instead of the real named arguments) rather
1035    /// than the operation's actual parameters.
1036    #[test]
1037    fn ordered_params_resolves_the_body_ref_wrapper() {
1038        let schema = serde_json::json!({
1039            "properties": {
1040                "body": { "$ref": "#/$defs/sys_sp_columns_Request" }
1041            },
1042            "$defs": {
1043                "sys_sp_columns_Request": {
1044                    "properties": {
1045                        "table_name": { "x-sql-ordinal": 1, "x-sql-type": "nvarchar(384)" },
1046                        "table_owner": { "x-sql-ordinal": 2, "x-sql-type": "nvarchar(384)" }
1047                    }
1048                }
1049            }
1050        });
1051
1052        let params = ordered_params(&schema);
1053        assert_eq!(params.len(), 2);
1054        assert_eq!(params[0].name, "table_name");
1055        assert_eq!(params[1].name, "table_owner");
1056        assert!(params.iter().all(|p| p.name != "body"));
1057    }
1058
1059    #[test]
1060    fn ordered_params_resolves_an_inline_body_without_a_ref() {
1061        let schema = serde_json::json!({
1062            "properties": {
1063                "body": {
1064                    "properties": {
1065                        "only": { "x-sql-ordinal": 1, "x-sql-type": "int" }
1066                    }
1067                }
1068            }
1069        });
1070
1071        let params = ordered_params(&schema);
1072        assert_eq!(params.len(), 1);
1073        assert_eq!(params[0].name, "only");
1074    }
1075
1076    #[test]
1077    fn ordered_params_is_empty_for_a_schema_with_no_body_property() {
1078        let schema = serde_json::json!({ "properties": {} });
1079        assert!(ordered_params(&schema).is_empty());
1080    }
1081
1082    #[test]
1083    fn build_statement_rejects_an_unsafe_parameter_name() {
1084        let params = vec![Param {
1085            name: "unsafe name".to_string(),
1086            ordinal: 1,
1087            x_sql_type: "int".to_string(),
1088        }];
1089
1090        assert!(
1091            build_statement(
1092                "sys",
1093                "sp_example",
1094                Some("SQL_STORED_PROCEDURE"),
1095                &params,
1096                &Map::new(),
1097                None,
1098            )
1099            .is_err()
1100        );
1101    }
1102
1103    #[test]
1104    fn severity_category_maps_11_through_16_to_400_equivalent() {
1105        for class in [11, 12, 13, 14 - 1, 15, 16] {
1106            assert_eq!(
1107                severity_category(class),
1108                "statement/user error (400-equivalent)"
1109            );
1110        }
1111    }
1112
1113    #[test]
1114    fn severity_category_maps_14_to_403_equivalent() {
1115        assert_eq!(severity_category(14), "permission denied (403-equivalent)");
1116    }
1117
1118    #[test]
1119    fn severity_category_maps_17_through_25_to_500_equivalent() {
1120        for class in [17, 18, 20, 25] {
1121            assert_eq!(
1122                severity_category(class),
1123                "fatal/resource error (500-equivalent)"
1124            );
1125        }
1126    }
1127
1128    #[test]
1129    fn severity_category_boundary_at_16_vs_17() {
1130        assert_eq!(
1131            severity_category(16),
1132            "statement/user error (400-equivalent)"
1133        );
1134        assert_eq!(
1135            severity_category(17),
1136            "fatal/resource error (500-equivalent)"
1137        );
1138    }
1139
1140    #[test]
1141    fn protocol_errors_are_classified_as_server_failures() {
1142        let error =
1143            classify_tiberius_error(tiberius::error::Error::Protocol("invalid packet".into()));
1144        assert_eq!(
1145            error.to_string(),
1146            "SQL Server connection/protocol error (500-equivalent): Protocol error: invalid packet"
1147        );
1148    }
1149}