SqlGuardLlm.Extensions 0.5.0-alpha.7

This is a prerelease version of SqlGuardLlm.Extensions.
dotnet add package SqlGuardLlm.Extensions --version 0.5.0-alpha.7
                    
NuGet\Install-Package SqlGuardLlm.Extensions -Version 0.5.0-alpha.7
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="SqlGuardLlm.Extensions" Version="0.5.0-alpha.7" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="SqlGuardLlm.Extensions" Version="0.5.0-alpha.7" />
                    
Directory.Packages.props
<PackageReference Include="SqlGuardLlm.Extensions" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add SqlGuardLlm.Extensions --version 0.5.0-alpha.7
                    
#r "nuget: SqlGuardLlm.Extensions, 0.5.0-alpha.7"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package SqlGuardLlm.Extensions@0.5.0-alpha.7
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=SqlGuardLlm.Extensions&version=0.5.0-alpha.7&prerelease
                    
Install as a Cake Addin
#tool nuget:?package=SqlGuardLlm.Extensions&version=0.5.0-alpha.7&prerelease
                    
Install as a Cake Tool

SqlGuardLlm for .NET

Official .NET client for sqlguardllm, the SQL firewall for LLM apps. It talks to sqlguardllm serve (the same engine, over HTTP) so .NET behaves exactly like Python. No runtime dependencies beyond HttpClient and System.Text.Json. Targets net8.0 and net10.0.

SqlGuardClient needs a running sqlguardllm serve; SqlGuard.CreateLocalAsync runs the engine shipped in the package, with no Python and no server (see below).

dotnet add package SqlGuardLlm

Usage

using SqlGuardLlm;

using var guard = new SqlGuardClient("http://localhost:8080", token: Environment.GetEnvironmentVariable("SQLGUARD_TOKEN"));

// Context comes from YOUR app (the signed-in user), never from the model.
var context = new Dictionary<string, object?> { ["tenant_id"] = currentUser.TenantId };

CheckResult r = await guard.CheckAsync(sqlFromModel, context);
if (r.Ok) Run(r.Sql!);                 // rewritten, safe SQL
else foreach (var v in r.Violations) Console.WriteLine($"{v.Code}: {v.Message}");

string safe = await guard.EnforceAsync(sqlFromModel, context);   // throws GuardViolationException

With dependency injection, pass a factory-managed client: new SqlGuardClient(httpClient, new SqlGuardOptions { BaseUrl = new("http://sqlguard:8080"), Token = token, Timeout = TimeSpan.FromSeconds(5) }).

Dapper / ADO.NET

var safeSql = await guard.EnforceAsync(modelSql, new Dictionary<string, object?> { ["tenant_id"] = tenantId });

await using var conn = new NpgsqlConnection(readOnlyConnectionString);   // also use a read-only DB role
var rows = await conn.QueryAsync(safeSql);                               // Dapper
// or plain ADO.NET: using var cmd = conn.CreateCommand(); cmd.CommandText = safeSql; ...

Integrations

Separate packages, so the core keeps no dependencies. See docs/RECIPES.md and examples/dotnet.

  • SqlGuardLlm.Extensions: services.AddSqlGuard(configuration.GetSection("SqlGuard")) (or AddSqlGuard(o => ...), or AddSqlGuard(localGuard)), AddSqlGuardContext(sp => ...), ADO.NET (GuardAsync, CreateGuardedCommandAsync, ExecuteGuardedReaderAsync) and Dapper (QueryGuardedAsync) helpers, and GuardedSqlFunction, a Microsoft.Extensions.AI AIFunction.
  • SqlGuardLlm.EntityFrameworkCore: optionsBuilder.UseSqlGuard(guard), a DbCommandInterceptor that enforces raw SQL (FromSql*, SqlQuery*, ExecuteSql*).
  • SqlGuardLlm.SemanticKernel: SqlGuardFunctionFilter, an IFunctionInvocationFilter.

Embedded engine (no server)

The package carries the engine for linux-x64, linux-arm64, osx-x64, osx-arm64 and win-x64 under runtimes/{rid}/native/sqlguardllm-engine/:

await using var guard = await SqlGuard.CreateLocalAsync(new SqlGuardLocalOptions
{
    PolicyJson = """{"dialect": "postgres", "tables": ["invoices"]}""",
});
string safe = await guard.EnforceAsync(sqlFromModel, new Dictionary<string, object?> { ["tenant_id"] = tenantId });

Local mode has the same API and result types as remote mode: both implement ISqlGuard (CheckAsync, EnforceAsync, ExplainAsync), so code can take an ISqlGuard and run either. SqlGuardLocal is thread-safe: concurrent calls share one engine process and each answer is matched to its call by request id. Every call takes a CancellationToken (cancelling one call does not disturb the others) and has a per-call timeout (SqlGuardLocalOptions.Timeout, default 5 s). DisposeAsync stops the engine and fails pending calls.

If the engine crashes or a call times out, the engine is killed and every pending call fails with SqlGuardException (engine_closed, or timeout for the call that timed out). Calls made during the restart backoff fail at once with engine_restarting; the first call after it starts a new engine, verified again against engine.sha256. The backoff starts at RestartBackoff (100 ms), doubles on every consecutive failure up to MaxRestartBackoff (5 s) and resets after a call is served. Nothing is ever reported ok while the engine is down.

The library uses source-generated System.Text.Json and no reflection; it is annotated for trimming and Native AOT. context values may be strings, numbers, booleans, null, JsonElement, dictionaries and lists; any other type throws ArgumentException.

Before it starts, the client recomputes the SHA-256 of every engine file against engine.sha256 and refuses to run on any mismatch (SqlGuardException, code engine_integrity); it also refuses an engine whose version or protocol does not match the package. On an unsupported runtime (another OS or CPU, Alpine/musl) it throws engine_unsupported, whose message points to remote mode: use SqlGuardClient against sqlguardllm serve. The hashes ship in the same package as the binaries, so they catch corruption and tampering after install; the supply chain (checksums and attestations of the release) is verified by scripts/fetch-engine.py when the package is built. Unix permissions are not kept by NuGet, so the client sets the executable bit on first start: a read-only file system needs it set at image build time.

Publishing

It works with dotnet run, dotnet publish -r <rid>, self-contained and single-file publishes, Native AOT and Linux container images (glibc based, such as mcr.microsoft.com/dotnet/runtime-deps; Alpine/musl is not supported). The package ships build/SqlGuardLlm.targets, which keeps the engine folder intact in a RID-specific publish (the SDK would otherwise flatten native assets): it ends up as sqlguardllm-engine/ next to your executable, which is where the client looks. Copy the whole publish folder, not just the executable. CI proves each of these with the packed package (clients/dotnet/smoke, .github/workflows/dotnet-client.yml).

API

Member Returns
CheckAsync(sql, context?, ct) CheckResult { Ok, Sql, Tables, AppliedFilters, Violations }
EnforceAsync(sql, context?, ct) the safe SQL, or throws GuardViolationException (has Violations)
ExplainAsync(sql, context?, ct) ExplainResult { Ok, Sql, Tables, Violations, Raw } (Raw is the full JsonElement)
HealthAsync(ct) HealthResult { Status, Version }

Fails closed

If the server is unreachable, times out (default 5 s), returns an HTTP error or answers something unexpected, the client throws SqlGuardException (with a Code) and never returns an ok result. Do not catch it and run the SQL anyway: a guard that lets queries through when it is down is not a guard. A rejected query is not an error: CheckAsync returns Ok = false with the violations.

Exception messages never include the token or the context. Cancelling through your own CancellationToken raises OperationCanceledException, not SqlGuardException.

Security notes

  • The context (tenant, user id...) must come from your app's authenticated session, never from the model or the user's prompt.
  • Use TLS and a bearer token when the server is not on localhost or a private network.
  • Run queries with a read-only database role as a second layer.

Apache-2.0.

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (2)

Showing the top 2 NuGet packages that depend on SqlGuardLlm.Extensions:

Package Downloads
SqlGuardLlm.EntityFrameworkCore

EF Core DbCommandInterceptor that sends raw SQL (FromSql, SqlQuery, ExecuteSql) through sqlguardllm before it reaches the database.

SqlGuardLlm.SemanticKernel

Semantic Kernel function invocation filter that checks the SQL a model sends to a function with sqlguardllm before the function runs.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
0.5.0-alpha.7 0 11/27/2026
0.5.0-alpha.6 0 11/27/2026