### Local Development Setup for MCPQL Source: https://github.com/hendrickcastro/mcpql/blob/main/README.md Steps to set up MCPQL for local development, including cloning the repository, installing dependencies, building the project, and configuring database connection via a .env file. ```bash git clone https://github.com/hendrickcastro/MCPQL.git cd MCPQL npm install npm run build ``` ```dotenv # Basic SQL Server connection DB_AUTHENTICATION_TYPE=sql DB_SERVER=localhost DB_NAME=MyDatabase DB_USER=sa DB_PASSWORD=YourPassword123! DB_PORT=1433 DB_ENCRYPT=false DB_TRUST_SERVER_CERTIFICATE=true ``` ```json { "mcpServers": { "mcpql": { "command": "node", "args": ["path/to/MCPQL/dist/server.js"] } } } ``` -------------------------------- ### SQL Server Express Setup Source: https://github.com/hendrickcastro/mcpql/blob/main/README.md Steps to set up SQL Server Express for use with MCPQL. ```APIDOC ## SQL Server Express Setup ### Description Instructions for configuring SQL Server Express to work with MCPQL. ### Method Configuration Steps ### Endpoint N/A (Configuration) ### Parameters #### Setup Steps 1. Enable TCP/IP protocol in SQL Server Configuration Manager. 2. Configure a static port (e.g., 1433) or use dynamic ports with the SQL Server Browser service. 3. Allow SQL Server traffic through the Windows Firewall. 4. Set `DB_INSTANCE_NAME=SQLEXPRESS` in your MCPQL configuration for default installations. ### Response N/A (Configuration) ### Response Example N/A (Configuration) ``` -------------------------------- ### Azure SQL Database Setup Source: https://github.com/hendrickcastro/mcpql/blob/main/README.md Configuration guidelines for connecting MCPQL to Azure SQL Database. ```APIDOC ## Azure SQL Database Setup ### Description Guidelines for successfully connecting MCPQL to Azure SQL Database, including firewall rules and encryption settings. ### Method Configuration Steps ### Endpoint N/A (Configuration) ### Parameters #### Setup Steps 1. Configure server firewall rules in Azure to allow your client IP address. 2. Use the correct server name format: `your-server-name.database.windows.net`. 3. Always set `DB_ENCRYPT=true` and `DB_TRUST_SERVER_CERTIFICATE=false`. 4. For Service Principal authentication, register an application in Azure AD and assign necessary permissions. ### Response N/A (Configuration) ### Response Example N/A (Configuration) ``` -------------------------------- ### Configure Environment-Specific Operations Source: https://github.com/hendrickcastro/mcpql/blob/main/README.md Provides examples for configuring MCPQL for development (with modifications enabled) versus production (with modifications disabled) environments. ```json { "mcpServers": { "mcpql": { "command": "npx", "args": ["-y", "hendrickcastro/mcpql"], "env": { "DB_SERVER": "localhost", "DB_NAME": "MyDatabase", "DB_USER": "sa", "DB_PASSWORD": "YourPassword123!", "DB_ALLOW_MODIFICATIONS": "true", "DB_ALLOW_STORED_PROCEDURES": "true" } } } } ``` ```json { "mcpServers": { "mcpql": { "command": "npx", "args": ["-y", "hendrickcastro/mcpql"], "env": { "DB_SERVER": "prod-server", "DB_NAME": "ProductionDB", "DB_USER": "readonly_user", "DB_PASSWORD": "secure_password", "DB_ALLOW_MODIFICATIONS": "false", "DB_ALLOW_STORED_PROCEDURES": "false" } } } } ``` -------------------------------- ### SQL Server Express Connection (Named Instance) - JSON Source: https://github.com/hendrickcastro/mcpql/blob/main/README.md Configuration for connecting to a SQL Server Express named instance. This example includes the DB_INSTANCE_NAME variable for specifying the instance. ```json { "mcpServers": { "mcpql": { "command": "npx", "args": ["-y", "hendrickcastro/mcpql"], "env": { "DB_AUTHENTICATION_TYPE": "sql", "DB_SERVER": "localhost", "DB_INSTANCE_NAME": "SQLEXPRESS", "DB_NAME": "MyDatabase", "DB_USER": "sa", "DB_PASSWORD": "YourPassword123!", "DB_ENCRYPT": "false", "DB_TRUST_SERVER_CERTIFICATE": "true" } } } } ``` -------------------------------- ### Table Analysis SQL Queries Source: https://github.com/hendrickcastro/mcpql/blob/main/doc/MCPQL-Tools-Guide.md Example SQL queries used by the table analysis tool to retrieve column metadata, including computed column definitions from system catalog views. ```sql SELECT c.*, cc.definition as computed_definition FROM INFORMATION_SCHEMA.COLUMNS c LEFT JOIN sys.computed_columns cc ON ... WHERE TABLE_SCHEMA = @schema AND TABLE_NAME = @table ``` -------------------------------- ### Advanced Usage of mcp_sp_structure (TypeScript) Source: https://github.com/hendrickcastro/mcpql/blob/main/doc/MCPQL-Tools-Guide.md Example of advanced usage for the mcp_sp_structure function in TypeScript, demonstrating how to call the function and analyze its output for output parameters, cursor parameters, dynamic SQL usage, and table dependencies. ```typescript const result = await mcp_sp_structure({ sp_name: "[api].[usp_ComplexProcedure]" }); if (result.success) { // Analyze parameter complexity const outputParams = result.data.parameters.filter(p => p.is_output); const cursorParams = result.data.parameters.filter(p => p.is_cursor_ref); // Check for dynamic SQL usage const hasDynamicSQL = result.data.definition.includes('EXEC(') || result.data.definition.includes('sp_executesql'); // Analyze dependencies for impact analysis const tableDeps = result.data.dependencies.filter(d => d.referenced_type === 'TABLE'); } ``` -------------------------------- ### Advanced Usage of mcp_preview_data (TypeScript) Source: https://github.com/hendrickcastro/mcpql/blob/main/doc/MCPQL-Tools-Guide.md Example of advanced usage for the mcp_preview_data function in TypeScript, demonstrating complex filtering with various data types (Date, Number, String, Boolean) and handling potential truncation of large result sets. ```typescript // Complex filtering with multiple data types const result = await mcp_preview_data({ table_name: "[sales].[Orders]", filters: { "OrderDate": "2023-01-01", // Date filtering "TotalAmount": 1000, // Numeric filtering "Status": "Completed", // String filtering "IsActive": true // Boolean filtering }, limit: 500 }); // Handle large result sets if (result.success && result.data.has_more_data) { console.log("Result set truncated - consider adding more filters"); } ``` -------------------------------- ### Get Sample Values from SQL Tables with mcp_get_sample_values Source: https://github.com/hendrickcastro/mcpql/blob/main/doc/MCPQL-Tools-Guide.md This function retrieves sample values from a specified column in a SQL table using stratified and frequency-based sampling. It handles large text and binary columns, ensuring statistical significance and data type-aware formatting. ```sql -- Frequency-based sampling WITH ValueFrequency AS ( SELECT [@column] as value, COUNT(*) as frequency, COUNT(*) * 100.0 / SUM(COUNT(*)) OVER() as percentage FROM [@schema].[@table] WHERE [@column] IS NOT NULL GROUP BY [@column] ), RankedValues AS ( SELECT *, ROW_NUMBER() OVER (ORDER BY frequency DESC) as rank FROM ValueFrequency ) SELECT TOP (@limit) value, frequency, percentage FROM RankedValues ORDER BY frequency DESC ``` ```typescript interface SampleValuesInput { table_name: string; column_name: string; limit?: number; // Default: 10, max: 100 include_frequency?: boolean; // Default: true min_frequency?: number; // Default: 1 } interface SampleValuesOutput { column_info: { name: string; data_type: string; max_length: number; is_nullable: boolean; }; sample_values: Array<{ value: any; frequency: number; percentage: number; formatted_value: string; }>; statistics: { total_rows: number; distinct_values: number; null_count: number; sample_coverage: number; // Percentage of total data represented }; has_more_values: boolean; } const result = await mcp_get_sample_values({ table_name: "[analytics].[UserEvents]", column_name: "EventType", limit: 25, include_frequency: true, min_frequency: 10 }); if (result.success) { const samples = result.data; // Data distribution analysis const topValues = samples.sample_values.slice(0, 5); const coverageByTop5 = topValues.reduce((sum, v) => sum + v.percentage, 0); console.log(`Top 5 values cover ${coverageByTop5.toFixed(1)}% of data`); // Outlier detection const outliers = samples.sample_values.filter(v => v.percentage < 0.1); console.log(`Found ${outliers.length} rare values (< 0.1% frequency)`); // Data quality assessment if (samples.statistics.sample_coverage < 80) { console.warn("Sample may not be representative - consider increasing limit"); } } ``` -------------------------------- ### Get Column Sample Values with mcp_get_sample_values Source: https://context7.com/hendrickcastro/mcpql/llms.txt Fetches sample values from a specific database column along with their frequency counts. This is useful for analyzing data distribution and identifying common entries. ```typescript const result = await mcp_get_sample_values({ table_name: "dbo.Orders", column_name: "Status", limit: 10 }); const countrySamples = await mcp_get_sample_values({ table_name: "dbo.Customers", column_name: "Country", limit: 20 }); ``` -------------------------------- ### Get Column Statistics Source: https://context7.com/hendrickcastro/mcpql/llms.txt Retrieves comprehensive statistics for a specified column in a SQL Server table. ```APIDOC ## mcp_get_column_stats ### Description Returns comprehensive statistics for a specific column in a table including total rows, null count, distinct values, min/max values, and sample values ordered by frequency. ### Method POST ### Endpoint /api/mcp_get_column_stats ### Parameters #### Request Body - **table_name** (string) - Required - The name of the table containing the column (e.g., "dbo.Products"). - **column_name** (string) - Required - The name of the column for which to retrieve statistics (e.g., "Price"). ### Request Example ```json { "table_name": "dbo.Products", "column_name": "Price" } ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the operation was successful. - **data** (object) - Contains the column statistics. - **column_name** (string) - The name of the column. - **total_rows** (integer) - The total number of rows in the column. - **null_count** (integer) - The number of null values in the column. - **distinct_count** (integer) - The number of distinct values in the column. - **min_value** (any) - The minimum value in the column. - **max_value** (any) - The maximum value in the column. - **sample_values** (array) - An array of sample values from the column, ordered by frequency. #### Response Example ```json { "success": true, "data": { "column_name": "Price", "total_rows": 5000, "null_count": 12, "distinct_count": 847, "min_value": 0.99, "max_value": 2499.99, "sample_values": [ 29.99, 49.99, 99.99, 149.99, 199.99, 299.99, 399.99, 499.99, 599.99, 799.99 ] } } ``` ``` -------------------------------- ### Configure MCPQL with Connection String Source: https://github.com/hendrickcastro/mcpql/blob/main/README.md Demonstrates how to configure the MCPQL server using a single database connection string within the MCP configuration file. ```json { "mcpServers": { "mcpql": { "command": "npx", "args": ["-y", "hendrickcastro/mcpql"], "env": { "DB_CONNECTION_STRING": "Server=localhost;Database=MyDatabase;User Id=sa;Password=YourPassword123!;Encrypt=false;TrustServerCertificate=true;" } } } } ``` -------------------------------- ### Running Tests Source: https://github.com/hendrickcastro/mcpql/blob/main/README.md How to execute the MCPQL test suite. ```APIDOC ## Running Tests ### Description Execute the comprehensive test suite for MCPQL to ensure all tools function correctly. ### Method Command Line ### Endpoint N/A (Testing) ### Command ```bash npm test ``` ### Response N/A (Testing) ### Response Example N/A (Testing) ``` -------------------------------- ### Run Project Test Suite Source: https://github.com/hendrickcastro/mcpql/blob/main/README.md Command to execute the comprehensive test suite for verifying MCPQL functionality. ```bash npm test ``` -------------------------------- ### Using Connection String Source: https://github.com/hendrickcastro/mcpql/blob/main/README.md Configure MCPQL using a connection string in the environment variables. ```APIDOC ## Using Connection String ### Description Configure MCPQL by providing a database connection string via environment variables. ### Method Environment Variable Configuration ### Endpoint N/A (Configuration) ### Request Body ```json { "mcpServers": { "mcpql": { "command": "npx", "args": ["-y", "hendrickcastro/mcpql"], "env": { "DB_CONNECTION_STRING": "Server=localhost;Database=MyDatabase;User Id=sa;Password=YourPassword123!;Encrypt=false;TrustServerCertificate=true;" } } } } ``` ### Response N/A (Configuration) ### Response Example N/A (Configuration) ``` -------------------------------- ### MCPQL Server Configuration Source: https://context7.com/hendrickcastro/mcpql/llms.txt Configuration details for setting up the MCPQL server in an MCP client using environment variables. ```APIDOC ## MCPQL Server Configuration Configure MCPQL in your MCP client by adding the server configuration with environment variables for database connection. ### Request Body Example ```json { "mcpServers": { "mcpql": { "command": "npx", "args": ["-y", "hendrickcastro/mcpql"], "env": { "DB_AUTHENTICATION_TYPE": "sql", "DB_SERVER": "localhost", "DB_NAME": "MyDatabase", "DB_USER": "sa", "DB_PASSWORD": "YourPassword123!", "DB_PORT": "1433", "DB_ENCRYPT": "false", "DB_TRUST_SERVER_CERTIFICATE": "true", "DB_ALLOW_MODIFICATIONS": "false", "DB_ALLOW_STORED_PROCEDURES": "false" } } } } ``` ``` -------------------------------- ### Configure MCPQL Environment Variables Source: https://context7.com/hendrickcastro/mcpql/llms.txt This configuration file defines the necessary environment variables for connecting to a SQL Server instance. It includes settings for authentication types, connection pooling, and security restrictions such as modification permissions. ```bash DB_AUTHENTICATION_TYPE=sql DB_SERVER=localhost DB_NAME=MyDatabase DB_PORT=1433 DB_INSTANCE_NAME=SQLEXPRESS DB_USER=sa DB_PASSWORD=YourPassword123! DB_DOMAIN=MYDOMAIN DB_AZURE_CLIENT_ID=your-client-id DB_AZURE_CLIENT_SECRET=your-client-secret DB_AZURE_TENANT_ID=your-tenant-id DB_TIMEOUT=30000 DB_REQUEST_TIMEOUT=30000 DB_ENCRYPT=false DB_TRUST_SERVER_CERTIFICATE=true DB_ENABLE_ARITH_ABORT=true DB_USE_UTC=true DB_POOL_MAX=10 DB_POOL_MIN=0 DB_POOL_IDLE_TIMEOUT=30000 DB_ALLOW_MODIFICATIONS=false DB_ALLOW_STORED_PROCEDURES=false DB_CONNECTION_STRING="Server=localhost;Database=MyDatabase;User Id=sa;Password=YourPassword123!;Encrypt=false;TrustServerCertificate=true;" ``` -------------------------------- ### Analyze Database Tables and Preview Data Source: https://github.com/hendrickcastro/mcpql/blob/main/README.md Demonstrates how to retrieve table structures, perform quick data overviews, and preview filtered data from a specific table. ```typescript const analysis = await mcp_table_analysis({ table_name: "dbo.Users" }); const overview = await mcp_quick_data_analysis({ table_name: "dbo.Users", sample_size: 500 }); const data = await mcp_preview_data({ table_name: "dbo.Users", filters: { "Status": "Active", "Department": "IT" }, limit: 25 }); ``` -------------------------------- ### Troubleshooting Connection Issues Source: https://github.com/hendrickcastro/mcpql/blob/main/README.md Common connection problems and their solutions for MCPQL. ```APIDOC ## Troubleshooting Connection Issues ### Description Provides solutions for common connection errors encountered with MCPQL, including login failures, server not found, certificate errors, and timeouts. ### Method Troubleshooting Guide ### Endpoint N/A (Troubleshooting) ### Parameters #### Common Issues and Solutions - **"Login failed"**: Verify `DB_USER` and `DB_PASSWORD`. For Windows authentication, set `DB_AUTHENTICATION_TYPE=windows`. - **"Server was not found"**: Ensure `DB_SERVER` and port are correct. For SQL Server Express, specify `DB_INSTANCE_NAME`. - **"Certificate" errors**: For local development, set `DB_TRUST_SERVER_CERTIFICATE=true`. - **Timeout errors**: Increase `DB_TIMEOUT` or check network connectivity. ### Response N/A (Troubleshooting) ### Response Example N/A (Troubleshooting) ``` -------------------------------- ### Get Column Statistics (TypeScript) Source: https://github.com/hendrickcastro/mcpql/blob/main/doc/MCPQL-Tools-Guide.md Calculates statistical information for a given table column. It handles various data types, NULL values, and uses approximate algorithms for distinct counts on large datasets. Input is a table and column name, output includes min/max values, averages, distinct counts, and null percentages. ```sql SELECT MIN([@column]) as min_value, MAX([@column]) as max_value, AVG(CAST([@column] AS FLOAT)) as avg_value, STDEV(CAST([@column] AS FLOAT)) as std_deviation, COUNT(*) as total_count, COUNT([@column]) as non_null_count, APPROX_COUNT_DISTINCT([@column]) as approx_distinct_count FROM [@schema].[@table] ``` ```sql SELECT MIN(LEN([@column])) as min_length, MAX(LEN([@column])) as max_length, AVG(CAST(LEN([@column] AS FLOAT)) as avg_length, COUNT(DISTINCT [@column]) as distinct_count FROM [@schema].[@table] WHERE [@column] IS NOT NULL ``` ```typescript interface ColumnStatsInput { table_name: string; column_name: string; } ``` ```typescript interface ColumnStatsOutput { column_name: string; data_type: string; total_rows: number; null_count: number; null_percentage: number; distinct_count: number; // Numeric columns min_value?: number; max_value?: number; avg_value?: number; std_deviation?: number; // String columns min_length?: number; max_length?: number; avg_length?: number; // Date columns min_date?: string; max_date?: string; date_range_days?: number; // Most common values most_common_values: Array<{ value: any, count: number, percentage: number }>; } ``` ```typescript const result = await mcp_get_column_stats({ table_name: "[analytics].[UserBehaviorКак]", column_name: "SessionDuration" }); if (result.success) { const stats = result.data; // Detect data quality issues if (stats.null_percentage > 50) { console.warn("High null percentage detected"); } // Statistical analysis if (stats.std_deviation && stats.avg_value) { const coefficientOfVariation = stats.std_deviation / stats.avg_value; console.log(`Coefficient of variation: ${coefficientOfVariation}`); } // Outlier detection for numeric columns if (stats.min_value !== undefined && stats.max_value !== undefined) { const range = stats.max_value - stats.min_value; console.log(`Value range: ${range}`); } } ``` -------------------------------- ### Configure MCPQL Security via System Variables Source: https://github.com/hendrickcastro/mcpql/blob/main/SECURITY.md This snippet demonstrates how to configure MCPQL security settings using system environment variables. It provides commands for both Windows and Linux/Mac systems to enable database modifications and stored procedure execution. ```bash # Windows set DB_ALLOW_MODIFICATIONS=true set DB_ALLOW_STORED_PROCEDURES=true ``` ```bash # Linux/Mac export DB_ALLOW_MODIFICATIONS=true export DB_ALLOW_STORED_PROCEDURES=true ``` -------------------------------- ### Generate Dynamic SQL for Data Preview (SQL) Source: https://github.com/hendrickcastro/mcpql/blob/main/doc/MCPQL-Tools-Guide.md A template for dynamically generated SQL queries used in data preview operations. It includes placeholders for table name, schema, limit, and filter conditions, utilizing TOP for limiting results and ORDER BY for deterministic ordering. ```sql -- Generated query structure SELECT TOP (@limit) * FROM [@schema].[@table] WHERE (@filter_conditions) ORDER BY (SELECT NULL) -- Deterministic ordering ``` -------------------------------- ### Enabling Operations for Production Source: https://github.com/hendrickcastro/mcpql/blob/main/README.md Configure MCPQL for production environments with recommended security settings (modifications and stored procedures disabled). ```APIDOC ## Enabling Operations for Production ### Description Recommended configuration for production environments, keeping `DB_ALLOW_MODIFICATIONS` and `DB_ALLOW_STORED_PROCEDURES` set to `false` for maximum security. ### Method Environment Variable Configuration ### Endpoint N/A (Configuration) ### Request Body ```json { "mcpServers": { "mcpql": { "command": "npx", "args": ["-y", "hendrickcastro/mcpql"], "env": { "DB_SERVER": "prod-server", "DB_NAME": "ProductionDB", "DB_USER": "readonly_user", "DB_PASSWORD": "secure_password", "DB_ALLOW_MODIFICATIONS": "false", "DB_ALLOW_STORED_PROCEDURES": "false" } } } } ``` ### Response N/A (Configuration) ### Response Example N/A (Configuration) ``` -------------------------------- ### Configure MCP Client with npx Source: https://github.com/hendrickcastro/mcpql/blob/main/README.md Configuration for MCP clients like Claude Desktop and Cursor IDE to connect to the MCPQL server using npx. It specifies the command to run and environment variables for database connection. ```json { "mcpServers": { "mcpql": { "command": "npx", "args": ["-y", "hendrickcastro/mcpql"], "env": { "DB_AUTHENTICATION_TYPE": "sql", "DB_SERVER": "your_server", "DB_NAME": "your_database", "DB_USER": "your_username", "DB_PASSWORD": "your_password", "DB_PORT": "1433", "DB_ENCRYPT": "false", "DB_TRUST_SERVER_CERTIFICATE": "true" } } } } ``` -------------------------------- ### Configure MCPQL Server for MCP Clients Source: https://context7.com/hendrickcastro/mcpql/llms.txt This JSON configuration defines the MCPQL server settings for integration with MCP-compatible clients. It includes environment variables for database connection details, authentication, and security restrictions. ```json { "mcpServers": { "mcpql": { "command": "npx", "args": ["-y", "hendrickcastro/mcpql"], "env": { "DB_AUTHENTICATION_TYPE": "sql", "DB_SERVER": "localhost", "DB_NAME": "MyDatabase", "DB_USER": "sa", "DB_PASSWORD": "YourPassword123!", "DB_PORT": "1433", "DB_ENCRYPT": "false", "DB_TRUST_SERVER_CERTIFICATE": "true", "DB_ALLOW_MODIFICATIONS": "false", "DB_ALLOW_STORED_PROCEDURES": "false" } } } } ``` -------------------------------- ### Enabling Operations for Development Source: https://github.com/hendrickcastro/mcpql/blob/main/README.md Configure MCPQL for development environments by enabling modifications and stored procedure execution. ```APIDOC ## Enabling Operations for Development ### Description Configure MCPQL for a development environment by setting `DB_ALLOW_MODIFICATIONS` and `DB_ALLOW_STORED_PROCEDURES` to `true`. ### Method Environment Variable Configuration ### Endpoint N/A (Configuration) ### Request Body ```json { "mcpServers": { "mcpql": { "command": "npx", "args": ["-y", "hendrickcastro/mcpql"], "env": { "DB_SERVER": "localhost", "DB_NAME": "MyDatabase", "DB_USER": "sa", "DB_PASSWORD": "YourPassword123!", "DB_ALLOW_MODIFICATIONS": "true", "DB_ALLOW_STORED_PROCEDURES": "true" } } } } ``` ### Response N/A (Configuration) ### Response Example N/A (Configuration) ``` -------------------------------- ### POST /mcp_get_dependencies Source: https://github.com/hendrickcastro/mcpql/blob/main/doc/MCPQL-Tools-Guide.md Analyzes hard and soft dependencies for a given SQL database object, including support for indirect dependencies and cycle detection. ```APIDOC ## POST /mcp_get_dependencies ### Description Analyzes both hard and soft dependencies for a specified database object. It traverses the dependency graph to identify direct and indirect relationships while detecting circular dependencies. ### Method POST ### Endpoint /mcp_get_dependencies ### Parameters #### Request Body - **object_name** (string) - Required - The name of the database object to analyze. - **include_indirect** (boolean) - Optional - Whether to include indirect dependencies. Default: false. - **max_depth** (number) - Optional - Maximum recursion depth for dependency traversal. Default: 3. ### Request Example { "object_name": "[sales].[vw_CustomerOrders]", "include_indirect": true, "max_depth": 5 } ### Response #### Success Response (200) - **object_info** (object) - Metadata about the target object. - **direct_dependencies** (array) - List of direct dependencies. - **indirect_dependencies** (array) - List of indirect dependencies (if requested). - **reverse_dependencies** (array) - List of objects that depend on this object. - **circular_dependencies** (array) - List of detected circular dependency paths. #### Response Example { "object_info": { "name": "vw_CustomerOrders", "schema": "sales", "type": "VIEW", "exists": true }, "direct_dependencies": [], "reverse_dependencies": [], "circular_dependencies": [] } ``` -------------------------------- ### Windows Authentication Connection - JSON Source: https://github.com/hendrickcastro/mcpql/blob/main/README.md Configuration for connecting to SQL Server using Windows Authentication. This requires specifying the domain, username, and password. ```json { "mcpServers": { "mcpql": { "command": "npx", "args": ["-y", "hendrickcastro/mcpql"], "env": { "DB_AUTHENTICATION_TYPE": "windows", "DB_SERVER": "MYSERVER", "DB_NAME": "MyDatabase", "DB_DOMAIN": "MYDOMAIN", "DB_USER": "myuser", "DB_PASSWORD": "mypassword", "DB_ENCRYPT": "false", "DB_TRUST_SERVER_CERTIFICATE": "true" } } } } ``` -------------------------------- ### Systematic Sampling Algorithm (SQL) Source: https://github.com/hendrickcastro/mcpql/blob/main/doc/MCPQL-Tools-Guide.md A SQL-based systematic sampling algorithm used for large tables when the number of rows exceeds a predefined sample size. It assigns row numbers and selects rows based on a modulo operation to achieve a uniform distribution of samples. This is a core component of the quick data analysis functionality. ```sql -- For tables > sample_size, use systematic sampling WITH SampledData AS ( SELECT *, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) as rn, @total_rows as total_count FROM [@schema].[@table] ) SELECT * FROM SampledData WHERE rn % (@total_rows / @sample_size) = 1 ``` -------------------------------- ### MCPQL Architecture Source: https://github.com/hendrickcastro/mcpql/blob/main/README.md Overview of the MCPQL project structure and key features. ```APIDOC ## MCPQL Architecture ### Description An overview of the MCPQL project structure, highlighting its modular design and key features. ### Method Architectural Overview ### Endpoint N/A (Architecture) ### Project Structure ``` MCPQL/ ├── src/ │ ├── __tests__/ # Comprehensive test suite │ ├── tools/ # Modular tool implementations │ │ ├── tableAnalysis.ts # Table analysis tools │ │ ├── storedProcedureAnalysis.ts # SP analysis tools │ │ ├── dataOperations.ts # Data operation tools │ │ ├── objectSearch.ts # Search and discovery tools │ │ ├── types.ts # Type definitions │ │ └── index.ts # Tool exports │ ├── db.ts # Database connection management │ ├── server.ts # MCP server setup and handlers │ ├── tools.ts # Tool definitions and schemas │ └── mcp-server.ts # Tool re-exports ├── dist/ # Compiled JavaScript output └── package.json # Dependencies and scripts ``` ### Key Features - **Connection Pooling**: Efficient database connection management. - **Robust Error Handling**: Comprehensive error handling and validation. - **Rich Metadata**: Detailed results with comprehensive database information. - **Flexible Configuration**: Environment-based configuration. - **Optimized Queries**: Efficient SQL queries for all operations. ### Response N/A (Architecture) ### Response Example N/A (Architecture) ``` -------------------------------- ### Preview Table Data Source: https://context7.com/hendrickcastro/mcpql/llms.txt Fetches a sample of records from a SQL Server table. Supports optional filtering using key-value pairs and allows limiting the number of returned rows. ```typescript const result = await mcp_preview_data({ table_name: "dbo.Orders", filters: { "Status": "Completed", "CustomerId": 1234 }, limit: 50 }); const allOrders = await mcp_preview_data({ table_name: "sales.OrderItems", limit: 100 }); ``` -------------------------------- ### SQL Server Local Connection (SQL Auth) - JSON Source: https://github.com/hendrickcastro/mcpql/blob/main/README.md Configuration for connecting to a local SQL Server instance using SQL Authentication. It specifies the server details, database name, and user credentials. ```json { "mcpServers": { "mcpql": { "command": "npx", "args": ["-y", "hendrickcastro/mcpql"], "env": { "DB_AUTHENTICATION_TYPE": "sql", "DB_SERVER": "localhost", "DB_NAME": "MyDatabase", "DB_USER": "sa", "DB_PASSWORD": "YourPassword123!", "DB_PORT": "1433", "DB_ENCRYPT": "false", "DB_TRUST_SERVER_CERTIFICATE": "true" } } } } ``` -------------------------------- ### TypeScript Comprehensive Search Execution Source: https://github.com/hendrickcastro/mcpql/blob/main/doc/MCPQL-Tools-Guide.md Demonstrates how to execute the `mcp_search_comprehensive` function with advanced options, including regex mode and specific object types. It shows how to process the results, sort them by relevance, and filter them by object type. ```typescript // Complex search with regex patterns const result = await mcp_search_comprehensive({ pattern: "Customer.*Order", object_types: ["TABLE", "VIEW", "PROCEDURE"], search_in_names: true, search_in_definitions: true, regex_mode: true }); if (result.success) { // Sort by relevance const sortedMatches = [...result.data.name_matches, ...result.data.definition_matches] .sort((a, b) => b.relevance_score - a.relevance_score); // Analyze search patterns const tableMatches = sortedMatches.filter(m => m.object_type === 'TABLE'); const procMatches = sortedMatches.filter(m => m.object_type === 'PROCEDURE'); console.log(`Found ${tableMatches.length} tables and ${procMatches.length} procedures`); } ``` -------------------------------- ### Search Database Objects Source: https://github.com/hendrickcastro/mcpql/blob/main/README.md Shows how to search for database objects by name or definition using configurable patterns and object type filters. ```typescript const objects = await mcp_search_comprehensive({ pattern: "User", search_in_names: true, search_in_definitions: false }); const procedures = await mcp_search_comprehensive({ pattern: "FROM Users", object_types: ["PROCEDURE"], search_in_definitions: true }); ``` -------------------------------- ### Quick Data Analysis with mcp_quick_data_analysis (TypeScript) Source: https://github.com/hendrickcastro/mcpql/blob/main/doc/MCPQL-Tools-Guide.md Performs rapid statistical analysis on a specified table, including row counts, sampling, data type detection, and quality assessments. It can optionally include histograms and provides recommendations for indexing and data quality improvements. The output includes table information, column-level statistics, a data quality score, and actionable recommendations. ```typescript const result = await mcp_quick_data_analysis({ table_name: "[warehouse].[FactSales]", sample_size: 5000, include_histograms: true }); if (result.success) { const analysis = result.data; // Data quality assessment console.log(`Overall data quality score: ${analysis.data_quality_score}/100`); // Column-specific analysis Object.entries(analysis.column_analysis).forEach(([col, stats]) => { if (stats.quality_issues.length > 0) { console.log(`${col}: ${stats.quality_issues.join(', ')}`); } // Cardinality analysis for indexing recommendations if (stats.cardinality_ratio > 0.95) { console.log(`${col}: High cardinality - consider for unique index`); } else if (stats.cardinality_ratio < 0.1) { console.log(`${col}: Low cardinality - consider for filtered index`); } }); // Performance recommendations analysis.recommendations.forEach(rec => console.log(`Recommendation: ${rec}`)); } ``` -------------------------------- ### Check Security Status via MCP Tool Source: https://github.com/hendrickcastro/mcpql/blob/main/README.md Shows how to programmatically retrieve the current security configuration status using the mcp_get_security_status tool. ```typescript const status = await mcp_get_security_status({}); ``` -------------------------------- ### mcp_get_dependencies Source: https://context7.com/hendrickcastro/mcpql/llms.txt Retrieves dependencies for a database object including objects it references and objects that reference it. Works with tables, views, stored procedures, and functions. ```APIDOC ## mcp_get_dependencies ### Description Retrieves dependencies for a database object including objects it references and objects that reference it. Works with tables, views, stored procedures, and functions. ### Method POST (Assumed, based on function call pattern) ### Endpoint /api/mcp/get/dependencies (Assumed) ### Parameters #### Request Body - **object_name** (string) - Required - The fully qualified name of the database object (e.g., "dbo.usp_ProcessOrder", "sales.Orders"). ### Request Example ```json { "object_name": "dbo.usp_ProcessOrder" } ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the operation was successful. - **data** (array) - A list of dependency objects. - **referenced_schema_name** (string) - The schema name of the referenced object. - **referenced_entity_name** (string) - The name of the referenced object. - **referenced_database_name** (string or null) - The database name of the referenced object, if applicable. - **referenced_server_name** (string or null) - The server name of the referenced object, if applicable. #### Response Example ```json { "success": true, "data": [ { "referenced_schema_name": "dbo", "referenced_entity_name": "Orders", "referenced_database_name": null, "referenced_server_name": null }, { "referenced_schema_name": "dbo", "referenced_entity_name": "OrderItems", "referenced_database_name": null, "referenced_server_name": null }, { "referenced_schema_name": "dbo", "referenced_entity_name": "Products", "referenced_database_name": null, "referenced_server_name": null }, { "referenced_schema_name": "inventory", "referenced_entity_name": "usp_UpdateStock", "referenced_database_name": null, "referenced_server_name": null } ] } ``` ``` -------------------------------- ### Execute Raw SQL Query with MCPQL Source: https://context7.com/hendrickcastro/mcpql/llms.txt Executes a raw SQL query and returns the results. By default, only SELECT queries are allowed. Modification operations require DB_ALLOW_MODIFICATIONS=true. Supports complex queries including CTEs. ```typescript // Execute SELECT query const result = await mcp_execute_query({ query: ` SELECT c.CustomerId, c.CustomerName, COUNT(o.OrderId) as OrderCount, SUM(o.TotalAmount) as TotalSpent FROM [dbo].[Customers] c LEFT JOIN [dbo].[Orders] o ON c.CustomerId = o.CustomerId WHERE o.OrderDate >= '2023-01-01' GROUP BY c.CustomerId, c.CustomerName HAVING SUM(o.TotalAmount) > 1000 ORDER BY TotalSpent DESC ` }); ``` ```typescript // Complex CTE query const analysisResult = await mcp_execute_query({ query: ` WITH MonthlySales AS ( SELECT YEAR(OrderDate) as Year, MONTH(OrderDate) as Month, SUM(TotalAmount) as Revenue FROM [sales].[Orders] GROUP BY YEAR(OrderDate), MONTH(OrderDate) ) SELECT * FROM MonthlySales ORDER BY Year DESC, Month DESC ` }); ``` -------------------------------- ### Quick Data Analysis of Table with MCPQL Source: https://context7.com/hendrickcastro/mcpql/llms.txt Performs statistical analysis on a specified table, including row count, column count, column metadata, and a data preview up to a specified limit. Useful for understanding table structure and content. ```typescript // Quick analysis of a table const result = await mcp_quick_data_analysis({ table_name: "sales.OrderItems", limit: 50 }); ``` -------------------------------- ### Preview Table Data Source: https://context7.com/hendrickcastro/mcpql/llms.txt Retrieves a preview of data from a SQL Server table, with options for filtering and row limits. ```APIDOC ## mcp_preview_data ### Description Retrieves a preview of data from a SQL Server table with optional column-value filtering. Supports configurable row limits and multiple filter conditions combined with AND logic. ### Method POST ### Endpoint /api/mcp_preview_data ### Parameters #### Request Body - **table_name** (string) - Required - The name of the table to preview (e.g., "dbo.Orders"). - **filters** (object) - Optional - An object where keys are column names and values are the desired filter values. Multiple filters are combined with AND logic. - **column_name** (any) - The value to filter by for the specified column. - **limit** (integer) - Optional - The maximum number of rows to return. Defaults to 100 if not specified. ### Request Example ```json { "table_name": "dbo.Orders", "filters": { "Status": "Completed", "CustomerId": 1234 }, "limit": 50 } ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the operation was successful. - **data** (array) - An array of objects, where each object represents a row from the table matching the filters. - **field** (any) - Represents a column in the table. #### Response Example ```json { "success": true, "data": [ { "OrderId": 5001, "CustomerId": 1234, "OrderDate": "2023-06-15T14:30:00.000Z", "Status": "Completed", "TotalAmount": 299.99 }, { "OrderId": 5045, "CustomerId": 1234, "OrderDate": "2023-07-22T09:15:00.000Z", "Status": "Completed", "TotalAmount": 149.50 } ] } ``` ``` -------------------------------- ### Advanced Table Analysis Usage Source: https://github.com/hendrickcastro/mcpql/blob/main/doc/MCPQL-Tools-Guide.md Demonstrates how to invoke the table analysis tool and process the returned data, specifically filtering for computed columns and analyzing index types. ```typescript const result = await mcp_table_analysis({ table_name: "[dbo].[ComplexTable]" }); if (result.success) { const computedCols = result.data.columns.filter(c => c.is_computed); const clusterIndex = result.data.indexes.find(i => i.index_type === 'CLUSTERED'); const checkConstraints = result.data.constraints.filter(c => c.constraint_type === 'CHECK_CONSTRAINT' ); } ``` -------------------------------- ### Analyze SQL Stored Procedure Structure and Metadata (SQL) Source: https://github.com/hendrickcastro/mcpql/blob/main/doc/MCPQL-Tools-Guide.md SQL queries to retrieve metadata, parameters, dependencies, and source code for stored procedures from system catalog views like sys.procedures, sys.parameters, sys.sql_dependencies, and sys.sql_modules. ```sql -- Procedure metadata SELECT p.*, m.definition FROM sys.procedures p JOIN sys.sql_modules m ON p.object_id = m.object_id WHERE p.name = @proc_name AND SCHEMA_NAME(p.schema_id) = @schema ``` ```sql -- Parameters with detailed type information SELECT p.*, t.name as type_name, t.max_length, t.precision, t.scale FROM sys.parameters p JOIN sys.types t ON p.user_type_id = t.user_type_id WHERE p.object_id = @object_id ``` ```sql -- Dependencies analysis SELECT d.*, o.name as referenced_name, s.name as referenced_schema FROM sys.sql_dependencies d JOIN sys.objects o ON d.referenced_major_id = o.object_id JOIN sys.schemas s ON o.schema_id = s.schema_id WHERE d.object_id = @object_id ``` -------------------------------- ### Configure MCPQL Connection Pool Source: https://github.com/hendrickcastro/mcpql/blob/main/doc/MCPQL-Tools-Guide.md Defines the configuration object for the database connection pool, including timeout and retry settings. This ensures efficient resource management and stability under load. ```typescript const poolConfig = { max: 10, min: 2, idleTimeoutMillis: 30000, acquireTimeoutMillis: 60000, createTimeoutMillis: 30000, destroyTimeoutMillis: 5000, reapIntervalMillis: 1000, createRetryIntervalMillis: 200 }; ``` -------------------------------- ### POST /mcp_search_comprehensive Source: https://github.com/hendrickcastro/mcpql/blob/main/README.md Searches for database objects based on name patterns or definitions. ```APIDOC ## POST /mcp_search_comprehensive ### Description Performs a search across database objects by name or definition with configurable filters. ### Method POST ### Endpoint mcp_search_comprehensive ### Parameters #### Request Body - **pattern** (string) - Required - The search string. - **search_in_names** (boolean) - Optional - Whether to search in object names. - **search_in_definitions** (boolean) - Optional - Whether to search in object definitions. - **object_types** (array) - Optional - List of object types to filter by (e.g., ["PROCEDURE"]). ### Request Example { "pattern": "User", "search_in_names": true } ### Response #### Success Response (200) - **results** (array) - List of matching database objects. ``` -------------------------------- ### POST /mcp_execute_query Source: https://github.com/hendrickcastro/mcpql/blob/main/doc/MCPQL-Tools-Guide.md Executes a direct SQL query against the database with built-in security protections and timeout management. ```APIDOC ## POST /mcp_execute_query ### Description Executes a raw SQL query with connection pooling and security validation. It supports schema-qualified object names and includes protection against SQL injection. ### Method POST ### Endpoint /mcp_execute_query ### Parameters #### Request Body - **query** (string) - Required - The SQL query to execute. Must use bracketed names: [schema].[table]. - **timeout_ms** (number) - Optional - Query timeout in milliseconds (default: 30000). - **max_rows** (number) - Optional - Maximum number of rows to return (default: 10000). ### Request Example { "query": "SELECT * FROM [sales].[Orders]", "timeout_ms": 30000, "max_rows": 100 } ### Response #### Success Response (200) - **rows** (array) - Array of result rows. - **column_names** (array) - List of column names. - **rows_affected** (number) - Number of rows affected by the query. - **execution_time_ms** (number) - Time taken for execution. #### Response Example { "rows": [{"id": 1, "amount": 100}], "column_names": ["id", "amount"], "rows_affected": 1, "execution_time_ms": 45 } ``` -------------------------------- ### POST /mcp_quick_data_analysis Source: https://github.com/hendrickcastro/mcpql/blob/main/doc/MCPQL-Tools-Guide.md Performs an automated analytical assessment of a database table, providing data quality scores and indexing recommendations. ```APIDOC ## POST /mcp_quick_data_analysis ### Description Analyzes a specified table using systematic sampling to provide statistics, data quality metrics, and performance optimization suggestions. ### Method POST ### Endpoint /mcp_quick_data_analysis ### Parameters #### Request Body - **table_name** (string) - Required - The fully qualified table name (e.g., [schema].[table]). - **sample_size** (number) - Optional - Number of rows to sample (default: 1000, max: 10000). - **include_histograms** (boolean) - Optional - Whether to include data histograms (default: false). ### Request Example { "table_name": "[warehouse].[FactSales]", "sample_size": 5000, "include_histograms": true } ### Response #### Success Response (200) - **table_info** (object) - Metadata about the sampling process. - **column_analysis** (object) - Detailed statistics per column. - **data_quality_score** (number) - Overall quality score from 0-100. - **recommendations** (array) - List of optimization suggestions. #### Response Example { "table_info": {"total_rows": 50000, "sample_size": 5000}, "data_quality_score": 85, "recommendations": ["Consider adding index to column X"] } ``` -------------------------------- ### Table Analysis Input and Output Schemas Source: https://github.com/hendrickcastro/mcpql/blob/main/doc/MCPQL-Tools-Guide.md TypeScript interfaces defining the input requirements and the comprehensive output structure for the table analysis tool. ```typescript interface TableAnalysisInput { table_name: string; } interface TableAnalysisOutput { columns: ColumnInfo[]; primary_keys: PrimaryKeyInfo[]; foreign_keys: ForeignKeyInfo[]; indexes: IndexInfo[]; constraints: ConstraintInfo[]; table_info: TableMetadata; } ```