#
tokens: 6723/50000 7/7 files
lines: off (toggle) GitHub
raw markdown copy
# Directory Structure

```
├── .github
│   └── copilot-instructions.md
├── .gitignore
├── appsettings.json
├── Helpers
│   └── SchemaHelper.cs
├── LICENSE
├── MsSqlMCP.csproj
├── MsSqlMCP.sln
├── Program.cs
├── README.md
└── SchemaTool.cs
```

# Files

--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------

```
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore

# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates

# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs

# Mono auto generated files
mono_crash.*

# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Ww][Ii][Nn]32/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
[Ll]ogs/

# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/

# Visual Studio 2017 auto generated files
Generated\ Files/

# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*

# NUnit
*.VisualState.xml
TestResult.xml
nunit-*.xml

# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c

# Benchmark Results
BenchmarkDotNet.Artifacts/

# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/

# ASP.NET Scaffolding
ScaffoldingReadMe.txt

# StyleCop
StyleCopReport.xml

# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
# but not Directory.Build.rsp, as it configures directory-level build defaults
!Directory.Build.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.tlog
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc

# Chutzpah Test files
_Chutzpah*

# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb

# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap

# Visual Studio Trace Files
*.e2e

# TFS 2012 Local Workspace
$tf/

# Guidance Automation Toolkit
*.gpState

# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user

# TeamCity is a build add-in
_TeamCity*

# DotCover is a Code Coverage Tool
*.dotCover

# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json

# Coverlet is a free, cross platform Code Coverage Tool
coverage*.json
coverage*.xml
coverage*.info

# Visual Studio code coverage results
*.coverage
*.coveragexml

# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*

# MightyMoose
*.mm.*
AutoTest.Net/

# Web workbench (sass)
.sass-cache/

# Installshield output folder
[Ee]xpress/

# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html

# Click-Once directory
publish/

# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj

# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/

# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets

# Microsoft Azure Build Output
csx/
*.build.csdef

# Microsoft Azure Emulator
ecf/
rcf/

# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload

# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/

# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs

# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk

# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/

# RIA/Silverlight projects
Generated_Code/

# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak

# SQL Server files
*.mdf
*.ldf
*.ndf

# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl

# Microsoft Fakes
FakesAssemblies/

# GhostDoc plugin setting file
*.GhostDoc.xml

# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/

# Visual Studio 6 build log
*.plg

# Visual Studio 6 workspace options file
*.opt

# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw

# Visual Studio 6 auto-generated project file (contains which files were open etc.)
*.vbp

# Visual Studio 6 workspace and project file (working project files containing files to include in project)
*.dsw
*.dsp

# Visual Studio 6 technical files
*.ncb
*.aps

# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions

# Paket dependency manager
.paket/paket.exe
paket-files/

# FAKE - F# Make
.fake/

# CodeRush personal settings
.cr/personal

# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc

# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config

# Tabs Studio
*.tss

# Telerik's JustMock configuration file
*.jmconfig

# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs

# OpenCover UI analysis results
OpenCover/

# Azure Stream Analytics local run output
ASALocalRun/

# MSBuild Binary and Structured Log
*.binlog

# NVidia Nsight GPU debugger configuration file
*.nvuser

# MFractors (Xamarin productivity tool) working folder
.mfractor/

# Local History for Visual Studio
.localhistory/

# Visual Studio History (VSHistory) files
.vshistory/

# BeatPulse healthcheck temp database
healthchecksdb

# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/

# Ionide (cross platform F# VS Code tools) working folder
.ionide/

# Fody - auto-generated XML schema
FodyWeavers.xsd

# VS Code files for those working on multiple tools
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
*.code-workspace

# Local History for Visual Studio Code
.history/

# Windows Installer files from build outputs
*.cab
*.msi
*.msix
*.msm
*.msp

# JetBrains Rider
*.sln.iml

```

--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------

```markdown
# MsSqlMCP
MCP to query SQL Server database schema, such as tables, columns, and relationships

## Prerequisites:
- .NET 9
- SQL

## Configuration
To configure Copilot in Visual Studio Code, add the MCP server configuration to the `settings.json` file:

```json
"mcp": {
    "inputs": [],
    "servers": {
        "MsSqlMCP": {
            "type": "stdio",
            "command": "dotnet",
            "args": [
                "run",
                "--project",
                "c:\\{path of repository}\\MsSqlMCP\\MsSqlMCP.csproj"
            ]
        }
    }
}

```

--------------------------------------------------------------------------------
/appsettings.json:
--------------------------------------------------------------------------------

```json
{
  "ConnectionStrings": {
    "DefaultConnection": "Data Source=your_database_server;Initial Catalog=your_database;Encrypt=False;Trusted_Connection=True;MultipleActiveResultSets=true"
  }

}

```

--------------------------------------------------------------------------------
/Program.cs:
--------------------------------------------------------------------------------

```csharp
namespace MsSqlMCP 
{
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Hosting;
    using Microsoft.Extensions.Logging;
    
    public static class Program
    {
        public static (string connectionString, bool warning) GetConnectionString()
        {
            
            IConfigurationRoot configuration = new ConfigurationBuilder()
                .SetBasePath(AppContext.BaseDirectory)
                .AddJsonFile("appsettings.json", optional: false)
                .AddEnvironmentVariables()
                .Build();
            
            string? connectionString = configuration.GetConnectionString("DefaultConnection");
            if (string.IsNullOrEmpty(connectionString))
            {
                throw new InvalidOperationException("Connection string 'DefaultConnection' not found in appsettings.json");
            }
            
            return (connectionString, false);
        }
        public static async Task Main(string[] args)
        {
            var builder = Host.CreateApplicationBuilder(args);
            builder.Logging.AddConsole(consoleLogOptions =>
            {
                // Configure all logs to go to stderr
                consoleLogOptions.LogToStandardErrorThreshold = LogLevel.Trace;
            });

            // Get connection string from appsettings.json to anticipate error
            GetConnectionString();

            builder.Services
                .AddMcpServer()
                .WithStdioServerTransport()
                .WithToolsFromAssembly();

            
            var app = builder.Build();
            
            await app.RunAsync();
        }
        
    }
}
        
```

--------------------------------------------------------------------------------
/.github/copilot-instructions.md:
--------------------------------------------------------------------------------

```markdown
# MsSqlMCP - AI Coding Agent Instructions

## Project Overview
MsSqlMCP is a Model Context Protocol (MCP) server that provides SQL Server database schema exploration tools for AI agents. It exposes database metadata through MCP tools that can be called by AI assistants.

## Architecture & Key Components

### Core Pattern: MCP Tool Registration
- Tools are defined as static methods in `SchemaTool.cs` decorated with `[McpServerTool]`
- Each tool method is automatically registered via `WithToolsFromAssembly()` in `Program.cs`
- Tools follow async pattern: `public async static Task<string> ToolName(params)`

### Database Connection Strategy
- Connection string loaded from `appsettings.json` via `Program.GetConnectionString()`
- Always use `using var connection = new SqlConnection(connectionString)` pattern
- Database switching handled via `USE {SanitizeDatabaseName(databaseName)}` commands
- **Critical**: All database names must be sanitized using `SanitizeDatabaseName()` to prevent SQL injection

### Helper Layer Pattern
- `SchemaHelper.cs` contains all SQL queries and data access logic
- Tools in `SchemaTool.cs` handle MCP concerns (connection, database switching, formatting)
- Separation: SchemaTool = MCP interface, SchemaHelper = data access

## Development Workflows

### Adding New MCP Tools
1. Add method to `SchemaTool.cs` with `[McpServerTool, Description("...")]`
2. Implement data access method in `SchemaHelper.cs`
3. Follow connection pattern: open connection, switch database if needed, call helper
4. Return formatted string (not JSON) - MCP handles serialization

### Running & Testing
```bash
dotnet run --project MsSqlMCP.csproj
```
- Configure in VS Code `settings.json` under `"mcp"` section
- Test via Copilot chat which calls the MCP tools

### Configuration
- Database connection in `appsettings.json` under `ConnectionStrings.DefaultConnection`
- Supports Windows Authentication (`Trusted_Connection=True`) and SQL auth
- `appsettings.json` copied to output directory via `.csproj` configuration

## Code Conventions

### SQL Injection Prevention
- **Always** use `SanitizeDatabaseName()` for dynamic database names
- Use parameterized queries (`@parameter`) for user input in SchemaHelper
- Example: `command.Parameters.AddWithValue("@tableName", tableName)`

### SQL Query Restrictions
- `ExecuteSql` only allows read-only operations (SELECT, SHOW, DESCRIBE, etc.)
- Blocked statements: DROP, INSERT, UPDATE, DELETE, TRUNCATE, ALTER, CREATE, EXEC, EXECUTE, MERGE, BULK, BACKUP, RESTORE, DBCC, GRANT, DENY, REVOKE, USE, SHUTDOWN, KILL, RECONFIGURE
- Multi-statement queries are validated to prevent restriction bypass
- This ensures the tool remains a safe schema exploration utility

### Error Handling Pattern
```csharp
try {
    // SQL operations
} catch (SqlException ex) {
    return $"SQL Error: {ex.Message}";
} catch (Exception ex) {
    return $"Error: {ex.Message}";
}
```

### Query Result Formatting
- Tables: `schema.tablename` format
- Columns: `name | datatype(length) | NULL/NOT NULL IDENTITY PRIMARY KEY`
- Relationships: `table.column -> referenced_table.referenced_column (FK: name)`

## Key Dependencies
- `ModelContextProtocol` (v0.1.0-preview.9): Core MCP framework
- `Microsoft.Data.SqlClient`: SQL Server connectivity
- `Microsoft.Extensions.Hosting`: Dependency injection and configuration

## Schema Query Patterns
- Use `INFORMATION_SCHEMA` views for portable metadata queries
- Use `sys.*` views for SQL Server-specific features (foreign keys, procedures)
- Always include schema prefix in table references
- Order results consistently for predictable output

## Security Considerations
- All data-modifying statements explicitly blocked in `ExecuteSql`: DROP, INSERT, UPDATE, DELETE, TRUNCATE, ALTER, CREATE, EXEC/EXECUTE, MERGE, BULK, BACKUP, RESTORE, DBCC, GRANT, DENY, REVOKE, USE, SHUTDOWN, KILL, RECONFIGURE
- Multi-statement queries are validated to prevent bypassing restrictions
- Database name sanitization prevents injection
- Connection string supports both Windows and SQL authentication
- Only read-only operations permitted - this is a schema exploration tool only
- No direct file system access - database operations only

```

--------------------------------------------------------------------------------
/Helpers/SchemaHelper.cs:
--------------------------------------------------------------------------------

```csharp
using Microsoft.Data.SqlClient;

namespace MsSqlMCP.Helpers
{
    public class SchemaHelper
    {
        
        
        public async Task<List<string>> GetTablesAsync(SqlConnection connection)
        {
            var tables = new List<string>();

            string sql = @"
        SELECT TABLE_SCHEMA, TABLE_NAME 
        FROM INFORMATION_SCHEMA.TABLES 
        WHERE TABLE_TYPE = 'BASE TABLE'
        ORDER BY TABLE_SCHEMA, TABLE_NAME";

            using var command = new SqlCommand(sql, connection);
            using var reader = await command.ExecuteReaderAsync();

            while (await reader.ReadAsync())
            {
                string schema = reader.GetString(0);
                string tableName = reader.GetString(1);
                tables.Add($"{schema}.{tableName}");
            }

            return tables;
        }

        public async Task<List<string>> GetColumnsAsync(SqlConnection connection, string tableName)
        {
            var columns = new List<string>();

            string schema = "dbo"; // default value
            if (tableName.Contains("."))
            {
                var parts = tableName.Split('.');
                schema = parts[0];
                tableName = parts[1];
            }

            string sql = @"
        SELECT 
            COLUMN_NAME, 
            DATA_TYPE, 
            CHARACTER_MAXIMUM_LENGTH,
            IS_NULLABLE,
            COLUMNPROPERTY(object_id(TABLE_SCHEMA + '.' + TABLE_NAME), COLUMN_NAME, 'IsIdentity') as IS_IDENTITY,
            (
                SELECT COUNT(*)
                FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu
                JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc 
                ON kcu.CONSTRAINT_NAME = tc.CONSTRAINT_NAME
                WHERE kcu.TABLE_SCHEMA = c.TABLE_SCHEMA
                AND kcu.TABLE_NAME = c.TABLE_NAME
                AND kcu.COLUMN_NAME = c.COLUMN_NAME
                AND tc.CONSTRAINT_TYPE = 'PRIMARY KEY'
            ) as IS_PRIMARY_KEY
        FROM 
            INFORMATION_SCHEMA.COLUMNS c
        WHERE 
            TABLE_SCHEMA = @schema 
            AND TABLE_NAME = @tableName
        ORDER BY 
            ORDINAL_POSITION";

            using var command = new SqlCommand(sql, connection);
            command.Parameters.AddWithValue("@schema", schema);
            command.Parameters.AddWithValue("@tableName", tableName);

            using var reader = await command.ExecuteReaderAsync();

            while (await reader.ReadAsync())
            {
                string columnName = reader.GetString(0);
                string dataType = reader.GetString(1);
                object charMaxLength = reader.GetValue(2);
                string isNullable = reader.GetString(3);
                int isIdentity = reader.GetInt32(4);
                int isPrimaryKey = reader.GetInt32(5);

                string lengthInfo = charMaxLength == DBNull.Value ? "" : $"({charMaxLength})";
                string nullableInfo = isNullable == "YES" ? "NULL" : "NOT NULL";
                string identityInfo = isIdentity == 1 ? "IDENTITY" : "";
                string pkInfo = isPrimaryKey == 1 ? "PRIMARY KEY" : "";

                columns.Add($"{columnName} | {dataType}{lengthInfo} | {nullableInfo} {identityInfo} {pkInfo}".Trim());
            }

            return columns;
        }

        public async Task<List<string>> GetRelationshipsAsync(SqlConnection connection)
        {
            var relationships = new List<string>();

            string sql = @"
        SELECT 
            fk.name AS ForeignKey,
            OBJECT_NAME(fk.parent_object_id) AS TableName,
            COL_NAME(fkc.parent_object_id, fkc.parent_column_id) AS ColumnName,
            OBJECT_NAME(fk.referenced_object_id) AS ReferencedTableName,
            COL_NAME(fkc.referenced_object_id, fkc.referenced_column_id) AS ReferencedColumnName
        FROM 
            sys.foreign_keys AS fk
        INNER JOIN 
            sys.foreign_key_columns AS fkc 
            ON fk.OBJECT_ID = fkc.constraint_object_id
        ORDER BY
            TableName, ReferencedTableName";

            using var command = new SqlCommand(sql, connection);
            using var reader = await command.ExecuteReaderAsync();

            while (await reader.ReadAsync())
            {
                string foreignKey = reader.GetString(0);
                string tableName = reader.GetString(1);
                string columnName = reader.GetString(2);
                string referencedTableName = reader.GetString(3);
                string referencedColumnName = reader.GetString(4);

                relationships.Add($"{tableName}.{columnName} -> {referencedTableName}.{referencedColumnName} (FK: {foreignKey})");
            }

            return relationships;
        }
        
        

        public string ExtractTableName(string query)
        {

            var words = query.Split(new[] { ' ', '\t', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < words.Length; i++)
            {
                if ((words[i].ToLower() == "tabla" || words[i].ToLower() == "table") && i + 1 < words.Length)
                {
                    return words[i + 1].Trim(',', '.', ':', ';', '?', '!');
                }
                else
                {
                    return words[i].Trim(',', '.', ':', ';', '?', '!');
                }
            }
            return string.Empty;
        }

        public async Task<List<string>> GetStoreProcedureAsync(SqlConnection connection, string spName)
        {
            var procedures = new List<string>();

            string sql = @"select name, object_definition(object_id) 
                        from sys.procedures
                        where name = @spName;";

            using var command = new SqlCommand(sql, connection);
            command.Parameters.AddWithValue("@spName", spName);
            using var reader = await command.ExecuteReaderAsync();

            while (await reader.ReadAsync())
            {
                string name = reader.GetString(0);
                string definition = reader.IsDBNull(1) ? string.Empty : reader.GetString(1);
                procedures.Add($"{name}:\n{definition}");
            }

            return procedures;
        }

    }
}

```

--------------------------------------------------------------------------------
/SchemaTool.cs:
--------------------------------------------------------------------------------

```csharp
using System.ComponentModel;
using MsSqlMCP.Helpers;
using ModelContextProtocol.Server;
using Microsoft.Data.SqlClient;
using MsSqlMCP;
using System.Text;

[McpServerToolType]
public static class SchemaTool
{
    // Helper method to sanitize database name to prevent SQL injection.
    // For SQL Server, names can be enclosed in []. This also escapes any existing ] characters.
    private static string SanitizeDatabaseName(string databaseName)
    {
        return $"[{databaseName.Replace("]", "]]")}]";
    }

    [McpServerTool, Description("Get tables name of database. Optionally, specify a database name to query a different database in the same instance.")]
    public async static Task<string> GetTables(string? databaseName = null)
    {
        var (connectionString, warning) = Program.GetConnectionString();
        using var connection = new SqlConnection(connectionString);
        await connection.OpenAsync();

        if (!string.IsNullOrWhiteSpace(databaseName))
        {
            using var useDbCommand = new SqlCommand($"USE {SanitizeDatabaseName(databaseName)};", connection);
            await useDbCommand.ExecuteNonQueryAsync();
        }

        SchemaHelper schemaHelper = new SchemaHelper();
        var tables = await schemaHelper.GetTablesAsync(connection);
        string dbInfo = string.IsNullOrWhiteSpace(databaseName) ? string.Empty : $" in database '{databaseName}'";
        return $"Tables{dbInfo}:\n\n{string.Join("\n", tables)}";
    }

    [McpServerTool, Description("Get the columns (fields) of a database table. Optionally, specify a database name to query a different database in the same instance.")]
    public async static Task<string> GetColumns(string tableName, string? databaseName = null)
    {
        var (connectionString, warning) = Program.GetConnectionString();
        using var connection = new SqlConnection(connectionString);
        await connection.OpenAsync();

        if (!string.IsNullOrWhiteSpace(databaseName))
        {
            using var useDbCommand = new SqlCommand($"USE {SanitizeDatabaseName(databaseName)};", connection);
            await useDbCommand.ExecuteNonQueryAsync();
        }

        SchemaHelper schemaHelper = new SchemaHelper();
        tableName = schemaHelper.ExtractTableName(tableName); 
        if (!string.IsNullOrEmpty(tableName))
        {
            var columns = await schemaHelper.GetColumnsAsync(connection, tableName);
            string dbInfo = string.IsNullOrWhiteSpace(databaseName) ? string.Empty : $" (database '{databaseName}')";
            return $"Columns in the table {tableName}{dbInfo}:\n\n{string.Join("\n", columns)}";
        }
        else
        {
            return "Please specify the table name to query its fields.";
        }
    }

    [McpServerTool, Description("Get the relationships between tables in the database. Optionally, specify a database name to query a different database in the same instance.")]
    public async static Task<string> GetRelationships(string? databaseName = null)
    {
        var (connectionString, warning) = Program.GetConnectionString();
        using var connection = new SqlConnection(connectionString);
        await connection.OpenAsync();

        if (!string.IsNullOrWhiteSpace(databaseName))
        {
            using var useDbCommand = new SqlCommand($"USE {SanitizeDatabaseName(databaseName)};", connection);
            await useDbCommand.ExecuteNonQueryAsync();
        }

        SchemaHelper schemaHelper = new SchemaHelper();
        var relationships = await schemaHelper.GetRelationshipsAsync(connection);
        string dbInfo = string.IsNullOrWhiteSpace(databaseName) ? string.Empty : $" in database '{databaseName}'";
        return $"Relationships between tables{dbInfo}:\n\n{string.Join("\n", relationships)}";
    }

    [McpServerTool, Description("Execute a SQL query against the database. Only allows SELECT statements and other read-only operations. Optionally, specify a database name to query a different database in the same instance.")]
    public async static Task<string> ExecuteSql(string sqlQuery, string? databaseName = null)
    {
        if (string.IsNullOrWhiteSpace(sqlQuery))
        {
            return "SQL query cannot be empty.";
        }

        // Block any statements that can modify data or structure
        string normalizedQuery = sqlQuery.Trim().ToUpperInvariant();
        string[] forbiddenStatements = { 
            "DROP ", "INSERT ", "UPDATE ", "DELETE ", "TRUNCATE ", "ALTER ", "CREATE ", 
            "EXEC ", "EXECUTE ", "MERGE ", "BULK ", "BACKUP ", "RESTORE ", "DBCC ",
            "GRANT ", "DENY ", "REVOKE ", "USE ", "SHUTDOWN ", "KILL ", "RECONFIGURE "
        };
        
        foreach (string forbidden in forbiddenStatements)
        {
            if (normalizedQuery.StartsWith(forbidden))
            {
                return $"Error: {forbidden.Trim()} statements are not allowed. Only read-only operations are permitted.";
            }
        }

        // Additional check for multi-statement queries that might contain forbidden operations
        if (normalizedQuery.Contains(";"))
        {
            string[] statements = sqlQuery.Split(';', StringSplitOptions.RemoveEmptyEntries);
            foreach (string statement in statements)
            {
                string normalizedStatement = statement.Trim().ToUpperInvariant();
                if (string.IsNullOrWhiteSpace(normalizedStatement)) continue;
                
                foreach (string forbidden in forbiddenStatements)
                {
                    if (normalizedStatement.StartsWith(forbidden))
                    {
                        return $"Error: {forbidden.Trim()} statements are not allowed in multi-statement queries. Only read-only operations are permitted.";
                    }
                }
            }
        }

        var (connectionString, warningFlag) = Program.GetConnectionString(); 
        if (warningFlag)
        {
            // Potentially log the warning or handle it as needed
        }

        StringBuilder resultBuilder = new StringBuilder();

        try
        {
            using var connection = new SqlConnection(connectionString);
            await connection.OpenAsync();

            if (!string.IsNullOrWhiteSpace(databaseName))
            {
                using var useDbCommand = new SqlCommand($"USE {SanitizeDatabaseName(databaseName)};", connection);
                await useDbCommand.ExecuteNonQueryAsync();
                resultBuilder.AppendLine($"Switched to database '{SanitizeDatabaseName(databaseName)}'."); // Show sanitized name for clarity
            }

            using var command = new SqlCommand(sqlQuery, connection);
            bool isSelectQuery = sqlQuery.Trim().ToUpperInvariant().StartsWith("SELECT");

            if (isSelectQuery)
            {
                using var reader = await command.ExecuteReaderAsync();
                if (reader.HasRows)
                {
                    for (int i = 0; i < reader.FieldCount; i++)
                    {
                        resultBuilder.Append(reader.GetName(i));
                        if (i < reader.FieldCount - 1) resultBuilder.Append("\t|\t");
                    }
                    resultBuilder.AppendLine();
                    // Ensure separator line is not drawn if resultBuilder is empty or too short
                    if (resultBuilder.Length > 2) 
                    {
                        resultBuilder.AppendLine(new string('-', resultBuilder.Length - (resultBuilder.ToString().EndsWith(Environment.NewLine) ? Environment.NewLine.Length*2 : Environment.NewLine.Length) )); 
                    } else if (resultBuilder.Length > 0 && !resultBuilder.ToString().EndsWith(Environment.NewLine)) {
                        resultBuilder.AppendLine(new string('-', resultBuilder.Length));
                    }

                    while (await reader.ReadAsync())
                    {
                        for (int i = 0; i < reader.FieldCount; i++)
                        {
                            resultBuilder.Append(reader[i]?.ToString() ?? "NULL");
                            if (i < reader.FieldCount - 1) resultBuilder.Append("\t|\t");
                        }
                        resultBuilder.AppendLine();
                    }
                }
                else
                {
                    resultBuilder.AppendLine("No rows returned from the query.");
                }
            }
            else
            {
                int affectedRows = await command.ExecuteNonQueryAsync();
                resultBuilder.AppendLine($"Command executed successfully. {affectedRows} row(s) affected.");
            }
        }
        catch (SqlException ex)
        {
            return $"SQL Error: {ex.Message}";
        }
        catch (Exception ex)
        {
            return $"Error executing SQL query: {ex.Message}";
        }

        return resultBuilder.ToString();
    }

    [McpServerTool, Description("Get the definition of a stored procedure by name. Optionally, specify a database name to query a different database in the same instance.")]
    public async static Task<string> GetStoreProcedure(string spName, string? databaseName = null)
    {
        if (string.IsNullOrWhiteSpace(spName))
        {
            return "Stored procedure name cannot be empty.";
        }

        var (connectionString, warning) = Program.GetConnectionString();
        using var connection = new SqlConnection(connectionString);
        await connection.OpenAsync();

        if (!string.IsNullOrWhiteSpace(databaseName))
        {
            using var useDbCommand = new SqlCommand($"USE {SanitizeDatabaseName(databaseName)};", connection);
            await useDbCommand.ExecuteNonQueryAsync();
        }

        SchemaHelper schemaHelper = new SchemaHelper();
        var procedures = await schemaHelper.GetStoreProcedureAsync(connection, spName);
        string dbInfo = string.IsNullOrWhiteSpace(databaseName) ? string.Empty : $" in database '{databaseName}'";
        if (procedures.Count == 0)
        {
            return $"Stored procedure '{spName}' not found{dbInfo}.";
        }
        return $"Stored procedure '{spName}'{dbInfo}:\n\n{string.Join("\n\n", procedures)}";
    }
}

```