Skip to main content
Glama
tkmawarire

io.github.tkmawarire/sql-sentinel

by tkmawarire

SQL Sentinel MCP Server

NuGet Docker License: MIT

SQL Serverの監視、診断、データベース操作のための本番環境対応MCP(Model Context Protocol)サーバー。.NET 9とMicrosoft.Data.SqlClientを使用して構築されており、ODBCドライバーを必要としないネイティブなSQL Server接続を実現します。

機能

  • セッション管理 — Extended Eventsセッションの作成、開始、停止、削除、一覧表示

  • スマートフィルタリング — アプリケーション、データベース、ユーザー、期間、ホスト、テキストパターンによるフィルタリング

  • クエリフィンガープリント — リテラル値のみが異なる類似クエリを正規化してグループ化

  • シーケンス分析 — タイミングギャップと累積時間を含む実行順序のトレース

  • デッドロック検出 — 被害者/プロセス詳細を含むXMLデッドロックレポートのキャプチャと分析

  • ブロッキング分析 — 待機リソースとSQLテキストを含むブロックされたプロセスイベントの監視

  • 待機統計sys.dm_os_wait_stats を直接照会し、タイプ(CPU、I/O、Lock、Memoryなど)ごとに分類

  • ヘルスチェック — 遅いクエリ、デッドロック、ブロッキング、待機統計、インサイトを含む包括的なサーバー診断

  • リアルタイムストリーミング — 指定した期間、キャプチャしたイベントをストリーミング

  • 本番環境に安全 — ノイズを自動的に除外(sp_reset_connectionSETステートメント、トレースクエリ)

  • データベース操作 — テーブルの一覧表示、スキーマの説明、データの照会、挿入、更新、テーブルの削除

  • AI最適化 — オプションのMarkdownフォーマットによる構造化JSON出力

Related MCP server: mysql-mcp-server

要件

  • Extended Eventsが有効なSQL Server 2012+(デフォルト)

  • 必要な権限:

    GRANT ALTER ANY EVENT SESSION TO [your_login];
    GRANT VIEW SERVER STATE TO [your_login];
  • ブロックされたプロセスの検出には:

    EXEC sp_configure 'show advanced options', 1;
    RECONFIGURE;
    EXEC sp_configure 'blocked process threshold', 5;
    RECONFIGURE;

インストール

オプション1: Docker(推奨)

.NET SDKは不要です。Dockerがインストールされている任意のシステムで動作します。

docker pull ghcr.io/tkmawarire/sql-sentinel-mcp:latest

Claude Desktop (claude_desktop_config.json)

{
  "mcpServers": {
    "sql-sentinel": {
      "command": "docker",
      "args": ["run", "-i", "--rm", "--network", "host",
               "-e", "SQL_SENTINEL_CONNECTION_STRING=Server=localhost;Database=master;User Id=sa;Password=YourPassword;TrustServerCertificate=true",
               "ghcr.io/tkmawarire/sql-sentinel-mcp:latest"]
    }
  }
}

Claude Code

claude mcp add sql-sentinel \
  -e SQL_SENTINEL_CONNECTION_STRING="Server=localhost;Database=master;User Id=sa;Password=YourPassword;TrustServerCertificate=true" \
  -- docker run -i --rm --network host \
  -e SQL_SENTINEL_CONNECTION_STRING \
  ghcr.io/tkmawarire/sql-sentinel-mcp:latest

ネットワークアクセス: stdioトランスポートには -i フラグが必要です。ホストマシン上のSQL Serverにコンテナが到達できるように --network host を使用してください。リモートSQL Serverの場合は、--network host を省略し、接続文字列でアクセス可能なホスト名を使用してください。

接続文字列: -eSQL_SENTINEL_CONNECTION_STRING を設定します。すべてのツールはこの環境変数から接続文字列を読み取ります。

オプション2: .NETグローバルツール(NuGet)

.NET 9 SDK以降が必要です。

dotnet tool install -g Neofenyx.SqlSentinel.Mcp
{
  "mcpServers": {
    "sql-sentinel": {
      "command": "sql-sentinel-mcp",
      "env": {
        "SQL_SENTINEL_CONNECTION_STRING": "Server=localhost;Database=master;User Id=sa;Password=YourPassword;TrustServerCertificate=true"
      }
    }
  }
}

オプション3: ソースからビルド

git clone https://github.com/tkmawarire/sql-sentinel.git
cd sql-sentinel
dotnet build

直接実行:

dotnet run --project SqlServer.Profiler.Mcp/

または、自己完結型の単一バイナリを発行:

# Windows
dotnet publish SqlServer.Profiler.Mcp/ -c Release -r win-x64 --self-contained

# Linux
dotnet publish SqlServer.Profiler.Mcp/ -c Release -r linux-x64 --self-contained

# macOS (Apple Silicon)
dotnet publish SqlServer.Profiler.Mcp/ -c Release -r osx-arm64 --self-contained

# macOS (Intel)
dotnet publish SqlServer.Profiler.Mcp/ -c Release -r osx-x64 --self-contained

出力は bin/Release/net9.0/{runtime}/publish/ に配置されます。

接続文字列

すべてのツールは SQL_SENTINEL_CONNECTION_STRING 環境変数から接続文字列を読み取ります。サーバーを起動する前に一度設定してください:

export SQL_SENTINEL_CONNECTION_STRING="Server=localhost;Database=master;User Id=sa;Password=YourPassword;TrustServerCertificate=false;Encrypt=true"

SQL認証:

Server=localhost;Database=master;User Id=sa;Password=YourPassword;TrustServerCertificate=false;Encrypt=true

Windows認証:

Server=localhost;Database=master;Integrated Security=true;TrustServerCertificate=false;Encrypt=true

注: TrustServerCertificate=true は、自己署名証明書を使用する開発環境でのみ使用してください。 本番環境では、常に TrustServerCertificate=false を有効なSSL証明書と共に使用してください。

Azure SQL:

Server=yourserver.database.windows.net;Database=yourdb;User Id=user;Password=password;Encrypt=true

MCPツールリファレンス

セッションライフサイクル

Tool

Description

sqlsentinel_create_session

フィルター付きExtended Eventsセッションを作成(開始はしない)

sqlsentinel_start_session

既存のセッションでイベントのキャプチャを開始

sqlsentinel_stop_session

キャプチャを停止。イベントは保持される

sqlsentinel_drop_session

セッションを削除し、すべてのイベントを破棄

sqlsentinel_list_sessions

MCPで作成されたすべてのセッションを状態とバッファ使用量とともに一覧表示

sqlsentinel_quick_capture

セッションの作成と開始を1つのステップで行う

イベント取得

Tool

Description

sqlsentinel_get_events

フィルタリング、並べ替え、重複排除を備えたキャプチャ済みイベントの取得

sqlsentinel_get_stats

フィンガープリント、データベース、アプリ、またはログインでグループ化された集計統計

sqlsentinel_analyze_sequence

タイミングとギャップを含むクエリ実行シーケンスの分析

sqlsentinel_get_connection_info

データベース、アプリケーション、ログイン、セッション、ブロッキング情報の一覧表示

sqlsentinel_stream_events

指定した期間(1〜300秒)のリアルタイムイベントキャプチャ

診断

Tool

Description

sqlsentinel_get_deadlocks

被害者、プロセス、ロック、SQLテキストを含むデッドロックイベントの取得

sqlsentinel_get_blocking

待機リソースとSQLテキストを含むブロックされたプロセスイベントの取得

sqlsentinel_get_wait_stats

タイプごとに分類された sys.dm_os_wait_stats の照会(セッションは不要)

sqlsentinel_health_check

包括的なレポート: 遅いクエリ、デッドロック、ブロッキング、待機統計、インサイト

権限

Tool

Description

sqlsentinel_check_permissions

現在のログイン権限とブロックされたプロセスのしきい値設定を確認

sqlsentinel_grant_permissions

ログインに必要な権限を付与(sysadminが必要)

データベース操作

Tool

Description

sqlsentinel_list_tables

データベース内のすべてのユーザーテーブルを一覧表示(スキーマ修飾)

sqlsentinel_describe_table

詳細なテーブルスキーマ: 列、インデックス、制約、外部キー

sqlsentinel_create_table

CREATE TABLEステートメントで新しいテーブルを作成

sqlsentinel_insert_data

INSERTステートメントでデータを挿入

sqlsentinel_read_data

SELECTクエリを実行して結果を返す

sqlsentinel_update_data

UPDATEステートメントでデータを更新

sqlsentinel_drop_table

DROP TABLEステートメントでテーブルを削除

使用例

クイックデバッグセッション

Agent: sqlsentinel_quick_capture(
    sessionName: "debug_api",
    applications: "MyWebApp",
    minDurationMs: 100
)

// User triggers the slow operation

Agent: sqlsentinel_get_events(
    sessionName: "debug_api",
    sortBy: "DurationDesc",
    limit: 20
)

Agent: sqlsentinel_drop_session(sessionName: "debug_api")

N+1クエリを見つける

Agent: sqlsentinel_quick_capture(
    sessionName: "n_plus_one_check",
    databases: "OrdersDB"
)

// User loads a page

Agent: sqlsentinel_get_stats(
    sessionName: "n_plus_one_check",
    groupBy: "QueryFingerprint"
)

// Look for queries with high execution counts

特定の操作をトレース

Agent: sqlsentinel_analyze_sequence(
    sessionName: "my_session",
    correlationId: "order-12345",
    responseFormat: "Markdown"
)

デッドロック検出

Agent: sqlsentinel_quick_capture(
    sessionName: "deadlock_monitor",
    eventTypes: "Deadlock"
)

// Wait for deadlocks to occur

Agent: sqlsentinel_get_deadlocks(
    sessionName: "deadlock_monitor",
    responseFormat: "Markdown"
)

ブロッキング分析

Agent: sqlsentinel_quick_capture(
    sessionName: "blocking_check",
    eventTypes: "BlockedProcess"
)

// Requires: sp_configure 'blocked process threshold', 5

Agent: sqlsentinel_get_blocking(
    sessionName: "blocking_check",
    responseFormat: "Markdown"
)

サーバーヘルスチェック

Agent: sqlsentinel_health_check(
    sessionName: "my_session",
    slowQueryThresholdMs: 1000,
    responseFormat: "Markdown"
)

データベース操作

Agent: sqlsentinel_list_tables()

Agent: sqlsentinel_describe_table(
    name: "dbo.Products"
)

Agent: sqlsentinel_read_data(
    sql: "SELECT TOP 10 * FROM dbo.Products ORDER BY CreatedDate DESC"
)

待機統計(セッション不要)

Agent: sqlsentinel_get_wait_stats(
    topN: 20,
    responseFormat: "Markdown"
)

クエリフィンガープリント

類似したクエリをグループ化するためにクエリが正規化されます:

-- These become one fingerprint:
SELECT * FROM Users WHERE id = 123
SELECT * FROM Users WHERE id = 456

-- Fingerprint: abc123:SELECT * FROM Users WHERE id = ?
-- Execution count: 2

ノイズフィルタリング

デフォルトで除外されるパターン(excludeNoise=true の場合):

  • sp_reset_connection — コネクションプールのリセット

  • SET TRANSACTION ISOLATION LEVEL — セッション設定

  • SET NOCOUNT, SET ANSI_* — クライアント設定

  • sp_trace_*, fn_trace_* — トレースシステムクエリ

サポートされているイベントタイプ

SqlBatchCompleted, RpcCompleted, SqlStatementCompleted, SpStatementCompleted, Attention, ErrorReported, Deadlock, BlockedProcess, LoginEvent, SchemaChange, Recompile, AutoStats

プロジェクト構造

sql-profiler-mcp/
├── .github/
│   └── workflows/
│       ├── docker.yml                     # Build & push multi-arch Docker images
│       └── publish-mcp-registry.yml       # Publish NuGet + MCP registry
├── .mcp/
│   └── server.json                        # MCP manifest (NuGet + OCI packages)
├── SqlServer.Profiler.Mcp/                # Main MCP server (stdio transport)
│   ├── SqlServer.Profiler.Mcp.csproj
│   ├── Program.cs                         # Entry point, DI setup, MCP config
│   ├── Models/
│   │   ├── ProfilerModels.cs              # Records, enums, data models
│   │   └── DbOperationResult.cs           # Result model for CRUD operations
│   ├── Services/
│   │   ├── ProfilerService.cs             # Core Extended Events logic
│   │   ├── QueryFingerprintService.cs     # SQL normalization & fingerprinting
│   │   ├── WaitStatsService.cs            # DMV-based wait stats analysis
│   │   ├── SessionConfigStore.cs          # In-memory session config storage
│   │   └── EventStreamingService.cs       # Real-time event streaming
│   ├── Utilities/
│   │   └── SqlInputValidator.cs           # SQL input validation & escaping
│   └── Tools/
│       ├── SessionManagementTools.cs      # Session lifecycle tools (6)
│       ├── EventRetrievalTools.cs         # Event retrieval tools (5)
│       ├── DiagnosticTools.cs             # Diagnostic tools (4)
│       ├── PermissionTools.cs             # Permission tools (2)
│       └── DatabaseTools.cs               # Database CRUD tools (7)
├── SqlServer.Profiler.Mcp.Api/            # Debug REST API (Swagger on port 5100)
│   ├── SqlServer.Profiler.Mcp.Api.csproj
│   ├── Program.cs
│   ├── Controllers/
│   │   └── ProfilerController.cs
│   ├── Models/
│   │   └── RequestModels.cs
│   └── appsettings.json
├── SqlServer.Profiler.Mcp.Cli/            # Debug CLI (REPL + script mode)
│   ├── SqlServer.Profiler.Mcp.Cli.csproj
│   └── Program.cs
├── SqlServer.Profiler.Mcp.Tests/          # xUnit tests for core MCP library (228 tests)
│   └── ...
├── SqlServer.Profiler.Mcp.Api.Tests/      # xUnit tests for API project (29 tests)
│   └── ...
├── Dockerfile                             # Multi-stage build (bookworm-slim)
├── .dockerignore
├── SqlServer.Profiler.Mcp.slnx           # Solution file
├── CLAUDE.md
├── CONTRIBUTING.md
└── README.md

開発

前提条件

  • .NET 9 SDK

  • SQL Server 2012+ インスタンス(ローカル、Docker、またはリモート)

  • Docker(オプション、コンテナビルド用)

クローンとビルド

git clone https://github.com/tkmawarire/sql-sentinel.git
cd sql-sentinel
dotnet restore
dotnet build

MCPサーバーをローカルで実行

dotnet run --project SqlServer.Profiler.Mcp/

サーバーはMCPプロトコルを使用してstdio上で通信します。対話的に使用するには、MCPクライアント(Claude Desktop、Claude Codeなど)に接続してください。

デバッグAPIの使用

APIプロジェクトは、すべてのMCPツールのRESTラッパーと、手動テスト用のSwagger UIを提供します。

dotnet run --project SqlServer.Profiler.Mcp.Api/
  • Swagger UI: http://localhost:5100/

  • 環境変数 SQL_SENTINEL_CONNECTION_STRING で接続文字列を設定

デバッグCLIの使用

CLIプロジェクトは、ツールを直接テストするための対話型REPLとスクリプトモードを提供します。

# Interactive REPL mode
dotnet run --project SqlServer.Profiler.Mcp.Cli/

# List all available tools
dotnet run --project SqlServer.Profiler.Mcp.Cli/ list

# Get help for a specific tool
dotnet run --project SqlServer.Profiler.Mcp.Cli/ help sqlsentinel_quick_capture

# Execute a single tool
dotnet run --project SqlServer.Profiler.Mcp.Cli/ call sqlsentinel_list_sessions

実行前に SQL_SENTINEL_CONNECTION_STRING 環境変数を設定してください。

Dockerビルド

docker build -t sql-sentinel-mcp:test .
docker run -i --rm --network host sql-sentinel-mcp:test

アーキテクチャ

主要パターン

  • 依存性注入Microsoft.Extensions.Hosting による

  • stdioトランスポート — stdoutはMCPプロトコル用に予約されており、すべてのロギングはstderrに出力されます

  • ツールの自動検出 — MCPツールは WithToolsFromAssembly() を使用してアセンブリから検出されます

  • XEセッションプレフィックス — 作成されたすべてのセッションには mcp_sentinel_ というプレフィックスが付きます

  • 2つのイベント形状 — 型付きフィールドを持つ標準イベント(クエリ、ログイン、再コンパイル)と、Extended Events XMLから解析されるXMLペイロードイベント(デッドロック、ブロッキング)

新しいMCPツールの追加

  1. Tools/ 配下の適切なファイルに public static メソッドを作成します(または新しいファイルを作成)

  2. [McpServerTool(Name = "sqlsentinel_your_tool")][Description("...")] を付与します

  3. [Description("...")] 属性を持つパラメータを追加します — これらがツールの入力スキーマになります

  4. メソッドパラメータでサービスを注入します(例: IProfilerServiceIWaitStatsService

  5. 文字列(JSONまたはMarkdown)を返します — フレームワークがMCPレスポンスのラッピングを処理します

[McpServerTool(Name = "sqlsentinel_example")]
[Description("Description shown to AI agents")]
public static async Task<string> Example(
    IProfilerService profilerService,
    [Description("Optional filter")] string? filter = null)
{
    var connectionString = ConnectionStringResolver.Resolve();
    // Implementation
    return JsonSerializer.Serialize(result);
}

トラブルシューティング

セッション作成時に「Permission denied」

GRANT ALTER ANY EVENT SESSION TO [your_login];
GRANT VIEW SERVER STATE TO [your_login];

「Login failed」

  • 接続文字列の資格情報を確認してください

  • Windows認証の場合、プロセスが正しいユーザーで実行されていることを確認してください

  • Azure SQLの場合、ファイアウォールがお使いのIPを許可していることを確認してください

イベントがキャプチャされない

  1. セッションがRUNNING状態であることを確認してください(sqlsentinel_list_sessions

  2. フィルターが厳しすぎないか確認してください

  3. 対象のデータベース/アプリがクエリを生成しているか確認してください

  4. minDurationMs がすべてをフィルタリングしていないか確認してください

デッドロックイベントがない

  • セッションが eventTypes: "Deadlock" で作成されていることを確認してください

  • セッションの実行中に実際にデッドロックが発生する必要があります

ブロッキングイベントがない

  • blocked process threshold が設定されていることを確認してください: sp_configure 'blocked process threshold', 5

  • セッションが eventTypes: "BlockedProcess" で作成されていることを確認してください

  • ブロッキングが設定されたしきい値(秒)を超える必要があります

イベント読み取りのタイムアウト

多数のイベントを含む大きなリングバッファは解析に時間がかかる場合があります。以下を使用してください:

  • 時間フィルターで対象期間を絞り込む

  • 必要に応じてコード内のコマンドタイムアウトを増やす

セキュリティ上の注意

  • SQL_SENTINEL_CONNECTION_STRING 環境変数には資格情報が含まれます — 適切に保護してください

  • 本番環境でセッションを無期限に実行したままにしないでください

  • クエリテキストには機密データが含まれる場合があります

  • 必要最小限の権限を付与してください

コントリビューション

問題やプルリクエストの提出に関するガイドラインは CONTRIBUTING.md を参照してください。

ライセンス

MIT

A
license - permissive license
-
quality - not tested
C
maintenance

Maintenance

Maintainers
Response time
0dRelease cycle
5Releases (12mo)
Commit activity

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

If you are the server author, to access and configure the admin panel.

Related MCP Servers

  • F
    license
    A
    quality
    D
    maintenance
    An MCP server for Microsoft SQL Server that enables executing read-only queries, listing tables, and describing database schemas. It offers specialized support for custom ports and multiple authentication methods including SQL credentials, NTLM, and Windows Integrated Auth.
    3
  • A
    license
    -
    quality
    C
    maintenance
    A production-ready MCP server for MySQL database operations, providing secure HTTP endpoints for read-only queries, performance analysis, and server monitoring.
    45
    9
    MIT
  • A
    license
    -
    quality
    B
    maintenance
    MCP server for SQL Server database inspection and querying, with connection pooling, security features, and a web manager UI.
    4
    MIT
  • F
    license
    -
    quality
    A
    maintenance
    Provides read-only SQL Server health diagnostics (server health, blocking queries, missing indexes) via MCP, with a GUI installer that automatically configures AI clients like Claude Desktop.

View all related MCP servers

Related MCP Connectors

  • MCP server for managing Prisma Postgres.

  • The MCP server for Azure DevOps, bringing the power of Azure DevOps directly to your agents.

  • MCP server for interacting with the Supabase platform

View all MCP Connectors

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/tkmawarire/sql-sentinel'

If you have feedback or need assistance with the MCP directory API, please join our Discord server