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로 빌드되어 네이티브 SQL Server 연결을 지원합니다 — ODBC 드라이버가 필요 없습니다.

기능

  • 세션 관리 — Extended Events 세션 생성, 시작, 중지, 삭제 및 목록 조회

  • 스마트 필터링 — 애플리케이션, 데이터베이스, 사용자, 기간, 호스트 및 텍스트 패턴으로 필터링

  • 쿼리 핑거프린팅 — 리터럴 값만 다른 유사한 쿼리를 정규화하고 그룹화

  • 시퀀스 분석 — 타이밍 간격 및 누적 기간으로 실행 순서 추적

  • 교착 상태 감지 — victim/프로세스 세부 정보가 포함된 XML 교착 상태 보고서 캡처 및 분석

  • 차단 분석 — 대기 리소스 및 SQL 텍스트와 함께 차단된 프로세스 이벤트 모니터링

  • 대기 통계sys.dm_os_wait_stats 직접 쿼리, 유형별 분류(CPU, I/O, Lock, Memory 등)

  • 상태 점검 — 느린 쿼리, 교착 상태, 차단, 대기 통계 및 인사이트를 포함한 종합 서버 진단

  • 실시간 스트리밍 — 지정된 시간 동안 캡처된 이벤트 스트리밍

  • 프로덕션 안전 — 노이즈 자동 제외(sp_reset_connection, SET 문, 추적 쿼리)

  • 데이터베이스 작업 — 테이블 목록, 스키마 설명, 데이터 쿼리, 삽입, 업데이트 및 테이블 삭제

  • AI 최적화 — 선택적 Markdown 서식이 포함된 구조화된 JSON 출력

Related MCP server: mysql-mcp-server

요구 사항

  • SQL Server 2012+ 및 Extended Events 활성화(기본값)

  • 필요한 권한:

    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를 생략하고 연결 문자열에서 접근 가능한 호스트 이름을 사용하세요.

연결 문자열: -e를 통해 SQL_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는 자체 서명 인증서가 있는 개발 환경에서만 사용하세요. 프로덕션에서는 항상 유효한 SSL 인증서와 함께 TrustServerCertificate=false를 사용하세요.

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

한 단계로 세션 생성 및 시작

이벤트 검색

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

victim, 프로세스, 잠금 및 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 프로젝트는 수동 테스트를 위한 Swagger UI와 함께 모든 MCP 도구에 대한 REST 래퍼를 제공합니다.

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로 출력됩니다.

  • 도구 자동 검색WithToolsFromAssembly()를 통해 어셈블리에서 MCP 도구 검색

  • XE 세션 접두사 — 생성된 모든 세션은 mcp_sentinel_ 접두사로 시작

  • 두 가지 이벤트 형식 — 유형화된 필드가 있는 표준 이벤트(쿼리, 로그인, 다시 컴파일)와 Extended Events XML에서 파싱되는 XML 페이로드 이벤트(교착 상태, 차단)

새 MCP 도구 추가

  1. Tools/ 아래 적절한 파일에 public static 메서드를 생성합니다(또는 새 파일 생성).

  2. [McpServerTool(Name = "sqlsentinel_your_tool")][Description("...")]로 데코레이션합니다.

  3. [Description("...")] 속성으로 매개변수를 추가합니다 — 도구의 입력 스키마가 됩니다.

  4. 메서드 매개변수를 통해 서비스를 주입합니다(예: IProfilerService, IWaitStatsService).

  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);
}

문제 해결

세션 생성 시 "권한 거부됨"

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

"로그인 실패"

  • 연결 문자열 자격 증명을 확인하세요.

  • Windows 인증의 경우 프로세스가 올바른 사용자로 실행되는지 확인하세요.

  • Azure SQL의 경우 방화벽에서 IP를 허용하는지 확인하세요.

캡처된 이벤트 없음

  1. 세션이 실행 중인지 확인(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