Skip to main content

sqlserver_mcp_catalog/tools/
call_tool.rs

1// SQL Server 2025 - master/msdb/sandbox combined catalog MCP server.
2
3use crate::auth::auth_manager::AuthManager;
4use crate::core::config_schema::Config;
5use crate::data::store::EndpointRecord;
6use crate::services::api_client::ApiClient;
7use crate::validation::validator::{validate_input, validate_output};
8
9/// Validates arguments against the input schema, resolves the configured
10/// SQL Server credentials, executes the live TDS call, and checks the
11/// response against the output schema before returning it.
12///
13/// An output-schema mismatch is only logged, not raised: `resultset.sql`'s
14/// best-effort column introspection (see
15/// docs/sqlserver-eda-openapi-pipeline/README.md's "Known limitations")
16/// can be wrong about a conditional-result-set object's actual shape, and
17/// rejecting an otherwise-successful call over a documentation gap would
18/// deny the caller real data it already has in hand. Input validation
19/// still hard-fails: those arguments are under the caller's control, not
20/// the database's.
21///
22/// Takes an already-looked-up `EndpointRecord` rather than a `Connection`
23/// and an `operation_id` to look up itself: `rusqlite::Connection` isn't
24/// `Sync`, so a `&Connection` held across this function's `.await` points
25/// (the TDS call) would make the caller's future non-`Send` — a hard
26/// requirement for `#[tool]` methods. Callers look the endpoint up (a
27/// synchronous, `Connection`-scoped step) before calling this function,
28/// not inside it.
29pub async fn call_operation(
30    endpoint: &EndpointRecord,
31    config: &Config,
32    auth_manager: &mut AuthManager,
33    operation_id: &str,
34    args: serde_json::Value,
35) -> anyhow::Result<serde_json::Value> {
36    validate_input(&config.api_version, operation_id, &args)?;
37
38    let client = ApiClient::new(config.clone());
39    let response = client.execute(endpoint, &args, auth_manager).await?;
40
41    if let Err(err) = validate_output(&config.api_version, operation_id, &response) {
42        tracing::warn!(
43            operation_id,
44            error = %err,
45            "response did not match the documented schema; returning it as-is"
46        );
47    }
48    Ok(response)
49}
50
51#[cfg(test)]
52mod tests {
53    use super::*;
54
55    fn test_config() -> Config {
56        Config {
57            url: "localhost".to_string(),
58            auth_method: crate::core::config_schema::AuthMethod::SqlServer,
59            sql_port: 1433,
60            pool_max_size: 10,
61            trust_server_cert: true,
62            api_version: "2025".to_string(),
63            log_level: "info".to_string(),
64            rate_limit: 100,
65            timeout_ms: 30_000,
66            cache_size: 500,
67            retry_attempts: 3,
68            transport: crate::core::config_schema::Transport::Stdio,
69            host: "127.0.0.1".to_string(),
70            port: 3000,
71            cors_allow: None,
72            default_database: None,
73        }
74    }
75
76    fn dummy_endpoint(operation_id: &str) -> EndpointRecord {
77        // Never read before `validate_input` returns its `Err` below, so
78        // these placeholder values are never exercised.
79        EndpointRecord {
80            operation_id: operation_id.to_string(),
81            path: "/dbo/sp_MailItemResultSets".to_string(),
82            method: "POST".to_string(),
83            summary: None,
84            description: None,
85            input_schema: serde_json::Value::Null,
86            output_schema: serde_json::Value::Null,
87            auth_scheme_ref: None,
88        }
89    }
90
91    /// `dbo_sp_MailItemResultSets` (a real 2025-catalog operation) requires
92    /// `mailitem_id`/`profile_id`/`conversation_handle`/
93    /// `service_contract_name`/`message_type_name` -- an empty body fails
94    /// schema validation, which `call_operation` checks *before* building
95    /// an `ApiClient` or attempting any TDS connection, so this is
96    /// reachable without live SQL Server infra.
97    #[tokio::test]
98    async fn call_operation_rejects_invalid_input_before_touching_the_network() {
99        let operation_id = "dbo_sp_MailItemResultSets";
100        let endpoint = dummy_endpoint(operation_id);
101        let config = test_config();
102        let mut auth_manager = AuthManager::new(config.auth_method);
103
104        let result = call_operation(
105            &endpoint,
106            &config,
107            &mut auth_manager,
108            operation_id,
109            serde_json::json!({"body": {}}),
110        )
111        .await;
112
113        assert!(result.is_err());
114        assert!(result.unwrap_err().to_string().contains("invalid input"));
115    }
116}