sqlserver-mcp 0.4.1

SQL Server 2025/2022/2019/2017 - master/msdb/sandbox combined catalog MCP server, generated by mcpify.
Documentation
// SQL Server 2025 - master/msdb/sandbox combined catalog MCP server — generated by mcpify. Do not hand-edit.

use std::sync::Arc;

use rmcp::handler::server::router::prompt::PromptRouter;
use rmcp::handler::server::router::tool::ToolRouter;
use rmcp::handler::server::wrapper::Parameters;
use rmcp::model::{
    CallToolResult, ContentBlock, Implementation, ProtocolVersion, ServerCapabilities, ServerInfo,
};
use rmcp::service::RequestContext;
use rmcp::transport::stdio;
use rmcp::{
    ErrorData as McpError, RoleServer, ServerHandler, ServiceExt, prompt_handler, schemars, tool,
    tool_handler, tool_router,
};
use serde::Deserialize;
use tokio::sync::Mutex;

use crate::auth::auth_manager::AuthManager;
use crate::core::config_schema::Config;
use crate::core::errors::McpifyError;
use crate::data::store::{cached_store_connection, get_endpoint};
use crate::tools::call_tool::call_operation;
use crate::tools::get_tool::get_operation;
use crate::tools::search_tool::search_operations;

fn default_search_limit() -> usize {
    5
}

#[derive(Debug, Deserialize, schemars::JsonSchema)]
pub struct SearchArgs {
    /// Natural-language description of the operation you need
    pub query: String,
    /// Maximum number of results
    #[serde(default = "default_search_limit")]
    pub limit: usize,
}

#[derive(Debug, Deserialize, schemars::JsonSchema)]
pub struct GetArgs {
    /// operationId returned by search
    pub operation_id: String,
}

/// A missing `arguments` field defaults to `{}`, not `null` — every
/// operation's generated input JSON Schema unconditionally declares
/// `"type": "object"`, even for zero-param operations, so `null` always
/// fails validation while `{}` always passes.
fn default_call_arguments() -> serde_json::Value {
    serde_json::json!({})
}

#[derive(Debug, Deserialize, schemars::JsonSchema)]
pub struct CallArgs {
    /// operationId returned by search
    pub operation_id: String,
    /// Operation parameters and/or request body. Defaults to `{}` when omitted.
    #[serde(default = "default_call_arguments")]
    pub arguments: serde_json::Value,
}

/// Shared state every `search`/`get`/`call` tool method needs. `Clone`
/// because rmcp constructs one instance per session (see
/// `http::server::start_http_server`'s service factory) — every field is
/// either cheap to clone (`String`, `Config`) or already `Arc`-wrapped.
#[derive(Clone)]
pub struct McpifyServer {
    api_version: String,
    config: Config,
    auth_manager: Arc<Mutex<AuthManager>>,
    tool_router: ToolRouter<McpifyServer>,
    prompt_router: PromptRouter<McpifyServer>,
}

#[tool_router]
impl McpifyServer {
    /// Takes an already-`Arc<Mutex<_>>`-wrapped `AuthManager` rather than
    /// an owned one: `http::server::start_http_server`'s service factory
    /// constructs a fresh `McpifyServer` per session, and `AuthManager`
    /// itself isn't `Clone` (its `Box<dyn AuthStrategy>` field isn't
    /// object-safe to clone) — every session shares the one configured
    /// auth manager instead, which also matches this deployment's actual
    /// semantics (a single configured auth method, not one per session).
    pub fn new(api_version: String, config: Config, auth_manager: Arc<Mutex<AuthManager>>) -> Self {
        Self {
            api_version,
            config,
            auth_manager,
            tool_router: Self::tool_router(),
            prompt_router: Self::prompt_router(),
        }
    }

    #[tool(
        description = "Semantic search for SQL Server 2025 - master/msdb/sandbox combined catalog operations using a natural-language query."
    )]
    async fn search(
        &self,
        Parameters(args): Parameters<SearchArgs>,
    ) -> Result<CallToolResult, McpError> {
        let api_version = self.api_version.clone();
        self.run_tool("search", async move {
            let conn = cached_store_connection(&api_version)?.lock().unwrap();
            search_operations(&conn, &args.query, args.limit)
        })
        .await
    }

    #[tool(
        description = "Return the schema, path, method, and documentation for a specific SQL Server 2025 - master/msdb/sandbox combined catalog operationId."
    )]
    async fn get(&self, Parameters(args): Parameters<GetArgs>) -> Result<CallToolResult, McpError> {
        let api_version = self.api_version.clone();
        self.run_tool("get", async move {
            let conn = cached_store_connection(&api_version)?.lock().unwrap();
            get_operation(&conn, &args.operation_id)
        })
        .await
    }

    #[tool(
        description = "Validate arguments, invoke a live SQL Server 2025 - master/msdb/sandbox combined catalog API operation, and validate the response."
    )]
    async fn call(
        &self,
        Parameters(args): Parameters<CallArgs>,
        _context: RequestContext<RoleServer>,
    ) -> Result<CallToolResult, McpError> {
        let api_version = self.api_version.clone();
        let config = self.config.clone();
        let auth_manager = self.auth_manager.clone();

        self.run_tool("call", async move {
            // Looked up and the connection (guard) dropped *before* any
            // `.await` below — `rusqlite::Connection` isn't `Sync`, so a
            // `&Connection`/`MutexGuard<Connection>` held across an await
            // point would make this future non-`Send`.
            let endpoint = {
                let conn = cached_store_connection(&api_version)?.lock().unwrap();
                get_endpoint(&conn, &args.operation_id)?.ok_or_else(|| {
                    McpifyError::NotFound(format!("unknown operationId '{}'", args.operation_id))
                })?
            };

            let mut auth_manager = auth_manager.lock().await;
            call_operation(
                &endpoint,
                &config,
                &mut auth_manager,
                &args.operation_id,
                args.arguments,
            )
            .await
        })
        .await
    }
}

impl McpifyServer {
    /// Wraps a tool's core logic with consistent MCP response formatting
    /// and error handling, so `search`/`get`/`call` each only implement
    /// their own business logic, not the MCP content-envelope
    /// boilerplate — mirrors `targets::typescript`'s `tool-executor.ts`.
    async fn run_tool<F>(&self, tool_name: &str, fut: F) -> Result<CallToolResult, McpError>
    where
        F: std::future::Future<Output = anyhow::Result<serde_json::Value>>,
    {
        match fut.await {
            Ok(value) => {
                let text =
                    serde_json::to_string_pretty(&value).unwrap_or_else(|_| value.to_string());
                Ok(CallToolResult::success(vec![ContentBlock::text(text)]))
            }
            Err(err) => {
                tracing::error!(tool = tool_name, error = %err, "tool execution failed");
                Ok(CallToolResult::error(vec![ContentBlock::text(
                    err.to_string(),
                )]))
            }
        }
    }
}

// `router = self.tool_router.clone()`: without it, `#[tool_handler]`
// defaults to calling `Self::tool_router()` fresh on every `list_tools`/
// `call_tool` request, rebuilding the router instead of reusing the one
// `new()` already built into this instance's `tool_router` field.
#[tool_handler(router = self.tool_router.clone())]
#[prompt_handler(router = self.prompt_router.clone())]
impl ServerHandler for McpifyServer {
    fn get_info(&self) -> ServerInfo {
        ServerInfo::new(
            ServerCapabilities::builder()
                .enable_tools()
                .enable_prompts()
                .build(),
        )
        .with_server_info(Implementation::from_build_env())
        .with_protocol_version(ProtocolVersion::V_2024_11_05)
        .with_instructions(
            "Exposes exactly 3 tools -- search, get, call -- backed by an embedded \
             semantic database, so you never need the full API surface in context. \
             Also exposes MCP prompts -- start with the `sqlserver_workflow` prompt \
             for guided, multi-step help with common SQL Server operational tasks."
                .to_string(),
        )
    }
}

/// Runs `server` over the stdio transport until the client disconnects —
/// the Terminal Client / Harness Server "stdio" mode's connection point
/// (Story R5 wires this into `main.rs`'s subcommand dispatch).
pub async fn connect_stdio<S>(server: S) -> anyhow::Result<()>
where
    S: rmcp::ServerHandler,
{
    let running = server.serve(stdio()).await?;
    tracing::info!("MCP server connected over stdio");
    running.waiting().await?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::config_schema::AuthMethod;

    fn server() -> McpifyServer {
        let config: Config = serde_json::from_value(serde_json::json!({
            "url": "localhost",
            "auth_method": "sql_server"
        }))
        .unwrap();
        McpifyServer::new(
            "2025".to_string(),
            config,
            Arc::new(Mutex::new(AuthManager::new(AuthMethod::SqlServer))),
        )
    }

    #[tokio::test]
    async fn successful_tool_execution_returns_pretty_json_text() {
        let result = server()
            .run_tool("test", async { Ok(serde_json::json!({ "answer": 42 })) })
            .await
            .unwrap();

        assert_eq!(result.is_error, Some(false));
        assert_eq!(result.content.len(), 1);
        assert_eq!(
            result.content[0].as_text().unwrap().text,
            "{\n  \"answer\": 42\n}"
        );
    }

    #[tokio::test]
    async fn failed_tool_execution_returns_a_caller_visible_error() {
        let result = server()
            .run_tool("test", async {
                Err::<serde_json::Value, _>(anyhow::anyhow!("operation failed"))
            })
            .await
            .unwrap();

        assert_eq!(result.is_error, Some(true));
        assert_eq!(
            result.content[0].as_text().unwrap().text,
            "operation failed"
        );
    }

    #[test]
    fn server_info_advertises_only_the_curated_tool_surface() {
        let info = server().get_info();
        assert!(info.capabilities.tools.is_some());
        assert!(info.capabilities.prompts.is_some());
        assert!(info.instructions.unwrap().contains("exactly 3 tools"));
    }
}