Hs SQL Agent MCP Server

by tse-wei-chen• 10•• Scanned•Claim this listing•Request removal
Database Managementaccuracyadmin panelai safetyai safety designanti hallucination

.NET SQL Agent MCP server featuring raw SQL input, strict AST validation, and an embedded Admin UI. Eliminates LLM hallucinations and security risks across 6 major databases.

Hs SQL Agent is an open-source mcp server by tse-wei-chen, written mainly in C#, with 10 GitHub stars and the Apache-2.0 license. Its code was last updated Nov 1, 2026.

hs-sql-agent

Turn trusted SQL into governed MCP tools for AI agents.

<img width="1000" height="500" alt="coverImage" src="https://github.com/user-attachments/assets/e317cee2-7bf3-4b11-94b9-4fdeedb29689" />

License: Apache 2.0 Docker NuGet CodeQL Advanced Tests

hs-sql-agent is an open-source SQL-to-MCP tool factory and governed SQL execution boundary. Define parameterized SQL in the Admin UI, publish it as a typed MCP tool, and let AI agents supply only the arguments — without writing a new C# method or redeploying your MCP server for every database operation.

Every published tool still runs through the same fail-closed SQL compiler, per-key database/table policy, runtime limits, audit trail, and Safe DML approval controls. Raw SQL tools remain available for cases where an agent genuinely needs flexible ad-hoc querying.

It supports PostgreSQL, MySQL, SQL Server, Oracle, SQLite, and Firebird and can run as the complete first-party server with its Admin UI or be embedded into an existing ASP.NET Core application.

Upgrading from v2.x? See the documentation website for breaking approval-store contracts, Redis key changes, Pending approvals and safe deployment requirements.

Secret protection breaking change: configure three independent protection keys and re-enter existing DB passwords. Read the documentation website before deploying.

Publish SQL as an MCP tool

Instead of teaching the model to regenerate the same query every time, define the SQL shape once:

SELECT id, total, status
FROM orders
WHERE customer_id = {{ customerId }}
  AND status = {{ status }}

Declare customerId and status in Runtime → Custom Tools, test the draft, then publish it. hs-sql-agent exposes the published definition to MCP clients as a named tool with a generated JSON input schema.

The agent sees a contract conceptually like:

get_customer_orders(
  customerId: number,
  status: string
)

The SQL template stays engineer-defined. Placeholders are value parameters only; identifiers and arbitrary SQL fragments cannot be injected through them.

Published custom tools can be Query or DML tools. Query tools use the same typed compiler and access-policy path as built-in SQL execution. DML tools use the same preview → approval → revalidation → commit protocol, including atomic multi-statement transactions.

Why hs-sql-agent?

  • SQL-to-MCP Custom Tools — Turn engineer-reviewed SQL templates into discoverable MCP tools with typed parameters, descriptions, draft/test/publish lifecycle, revisions, rollback, and database binding.
  • Fail-closed SQL compiler — Unsupported or unproven syntax is rejected instead of being silently rewritten with different semantics.
  • Closed F# compiler core — SQL enters a closed discriminated-union AST and advances through unforgeable parsed → bound → canonical → validated → executable compiler stages.
  • Six database providers — PostgreSQL, MySQL, SQL Server, Oracle, SQLite, and Firebird with provider-aware validation and lowering.
  • Safe DML — Read-only impact preview, one-time approval challenge, commit-time row-set revalidation, and explicit human approval through MCP Elicitation or an approval provider.
  • Governed access — Per-key database binding, table whitelisting, rate limits, execution limits, roles, policies, and audit records.
  • Flexible hosting — Run the packaged server and Admin UI, use the standard ASP.NET Core host, or compose advanced integrations from modular capabilities.
  • Production observability — Prometheus metrics, OpenTelemetry/OTLP, audit retention, and webhook/SIEM delivery.

SQL support is intentionally bounded by proven semantics. See the SQL Support Reference for the current contract.

Security deployment boundaries (3.1)

Query-only MCP permissions are not equivalent to database-level read-only access. Deploy each database target using a dedicated, least-privileged DB principal with SELECT access only to the intended relations, and deny untrusted native UDF/routine EXECUTE, external I/O, elevated definer/impersonation roles and cross-database access. The typed F# compiler and Host connection-local read-only fences provide additional protections but cannot sandbox arbitrary native code, external callbacks or separate connections. SQLite embedding hosts must not register write-capable callbacks on Query handles. See the six-provider Query security deployment contract for required DB identities, explicit unsupported routine effects, and physical security test boundaries.

Distributed SQL admission: MaxConcurrentSql bounds admitted operations, not all physical database sessions or driver pools. Redis-backed SqlConcurrency requires FailureMode=FailClosed; FailOpen is refused at registration and never grants an unfenced SQL lease even via legacy direct construction. The current Redis TTL sorted-set lease is supported against a single authoritative standalone Redis primary. Redis Sentinel, Cluster, multi-endpoint failover, split-brain fencing and a global physical pool ceiling are not supported as strong consistency guarantees; the standard host rejects explicitly configured Sentinel/multi-endpoint SQL coordination. The real two-primary Testcontainers counterexample is recorded in the physical evidence matrix.

DML uncertainty: a lost native COMMIT/ROLLBACK acknowledgement is not proof of success or failure. An outcome_unknown response is non-retryable; preserve the approval request ID and reconcile durable DB state before any new approval. Do not automatically replay.

Quick Start

cp .env.example .env
# Set HMAC_KEY and JWT_KEY to unique secrets of at least 32 bytes.
# Also set DB_ENCRYPTION_KEY, DML_ENCRYPTION_KEY, and DML_FINGERPRINT_KEY
# to three independent Base64-encoded random 32-byte values.
docker compose up -d

Open the Admin UI at http://localhost:8080.

For production settings and deployment options, use the Configuration Reference and Deployment Guide.

Use with an MCP client

Set MCP_PUBLIC_ENDPOINT to the externally reachable MCP URL, including /mcp, before issuing production keys.

Then open Runtime → MCP Keys in the Admin UI and issue a key. The one-time Save and connect dialog generates ready-to-paste configuration for Claude Desktop, Cursor, Visual Studio Code, and generic Streamable HTTP clients.

New API-issued MCP keys default to the four read/query tools (get_schemas, get_tables, get_columns, execute_query_sql); DML, DDL and published Custom Tools must be explicitly selected. Existing legacy keys with empty tool grants can still have unrestricted Custom Tool access until an administrator edits them. Audit and restrict such keys during upgrades.

The plaintext secret is shown only once. See MCP Client Onboarding for client setup, compatibility, and DML Elicitation requirements.

Automate the Admin API

Integrations can issue a Management API Key in the Admin UI and use the existing /api endpoints without an interactive login:

X-API-Key: hsa_mgmt_<secret>

Management API Keys are independent from MCP access keys (/mcp) and human JWT sessions. The key's explicitly granted canonical permissions determine which management actions are allowed; it is not an SQL row-level or tenant-isolation mechanism. See the Management API Keys guide for lifecycle, security boundaries, and integration examples.

Use from .NET

For the same batteries-included composition as the official Docker host, install HsSqlAgent.Hosting:

dotnet add package HsSqlAgent.Hosting
using HsSqlAgent.Hosting;

var builder = WebApplication.CreateBuilder(args);
builder.AddHsSqlAgentStandardHost();

var app = builder.Build();
app.UseHsSqlAgentStandardHost();

await app.RunAsync();

Use HsSqlAgent.Server directly only when you need custom authentication, middleware ordering, approval providers, UI, or capability composition.

See the ASP.NET Core Integration Guide and the HsSqlAgent.Hosting package README for the full integration contract.

How SQL execution works

  1. Authenticate the MCP key and establish its database, table, tool, and execution-policy scope.
  2. For Custom Tools, resolve the published definition and render declared value parameters into the engineer-defined SQL template.
  3. Parse SQL into the closed compiler model and bind source semantics.
  4. Normalize and validate syntax, semantics, capabilities, and policy.
  5. Render only an executable typestate into provider-specific SQL and parameters.
  6. Execute within configured runtime limits.

The compiler core is provider-driver-free: parsing, validation, normalization, capability proof, lowering, and rendering are kept separate from database drivers and runtime execution.

For DML, hs-sql-agent first builds a read-only impact preview, binds approval to the validated plan and matched row set, requires explicit human approval, and revalidates inside the commit transaction before applying the mutation.

Custom SQL tools pass through the same compiler, access policy, and execution limits as built-in tools.

SQL Execution Flow

<picture> <source media="(prefers-color-scheme: dark)" srcset="miscellaneous/diagram-black.png"> <source media="(prefers-color-scheme: light)" srcset="miscellaneous/diagram-light.png"> <img alt="SQL Execution Flow" src="miscellaneous/diagram-light.png"> </picture>

DML Approval Prompt

<img width="1199" height="890" alt="dml-approval-prompt" src="https://github.com/user-attachments/assets/ebd40519-e0b3-43d6-9e83-24238f3c00d6" />

Documentation

The documentation site is the source of truth for detailed configuration, integration, SQL capability, security, and operations guidance:

Contributing

See CONTRIBUTING.md and the Architecture and Contribution Flow.

License

Apache License 2.0

Hs SQL Agent alternatives

View more →

Similar mcp servers in Database Management, ranked by GitHub stars. Compare licence, recent activity and scan status before you choose.

NameStarsLicenceLast updatedScan
Hs SQL Agent (this page)
tse-wei-chen
10Apache-2.0Nov 1, 2026Scanned, no flagged issues
Codebase Memory MCP
DeusData
48kMITNov 1, 2026Scanned, see report
Xerj
xerj-org
19kApache-2.0Nov 1, 2026Scanned, no flagged issues
MCP Toolbox
googleapis
17kApache-2.0Nov 1, 2026Scanned, no flagged issues
Nightingale
ccfos
13kApache-2.0Oct 30, 2026Scanned, no flagged issues
Dbhub
bytebase
3.8kMITOct 26, 2026Scanned, no flagged issues