Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ Sections used: Added, Changed, Deprecated (an API that still works but will be r
### Added

- Experimental optional per-session row budgets for MCP result delivery (#220).
- Optional English and Spanish remediation hints for selected guard violations, also returned by MCP `explain_query` (#217).
- Optional English and Spanish remediation hints for selected guard violations, also available in MCP, HTTP, stdio, and the Node.js and .NET clients (#217).
- **Shadow mode** (#222, [shadow](docs/SHADOW.md), experimental), off by default: `sqlguardllm.shadow.ShadowGuard(active, candidate=...)` returns the active guard's decision untouched and records what a candidate policy would have decided (`would_allow`, `would_rewrite`, `would_deny`, `error`, with violation codes). The report keeps only counters, codes and SQL shape fingerprints: no SQL, literals, context or names. Also `sqlguardllm shadow --policy A --candidate B queries.sql` and `examples/shadow_demo.py`. No stable API changed and nothing was added to `sqlguardllm.__all__`.

## [1.0.0] - 2026-12-01
Expand Down
5 changes: 4 additions & 1 deletion clients/dotnet/src/SqlGuardLlm/SqlGuardLlm.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,10 @@ namespace SqlGuardLlm;
public sealed record Violation(
[property: JsonPropertyName("code")] string Code,
[property: JsonPropertyName("message")] string Message,
[property: JsonPropertyName("detail")] string Detail = "");
[property: JsonPropertyName("detail")] string Detail = "")
{
[JsonPropertyName("fix")] public string? Fix { get; init; }
}

/// <summary>Result of a check. <see cref="Ok"/> true means <see cref="Sql"/> is safe to run.</summary>
public sealed record CheckResult
Expand Down
2 changes: 2 additions & 0 deletions clients/dotnet/tests/SqlGuardLlm.Tests/ConformanceCorpus.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ public static async Task AssertGroupAsync(ISqlGuard guard, JsonElement group)
var codes = r.Violations.Select(v => v.Code).Distinct().OrderBy(x => x, StringComparer.Ordinal).ToArray();
var expCodes = exp.GetProperty("codes").EnumerateArray().Select(x => x.GetString()!).ToArray();
Assert.True(expCodes.SequenceEqual(codes), $"{id}: codes {string.Join(',', codes)}");
foreach (var violation in r.Violations.Where(v => v.Code == "empty_statement"))
Assert.Equal("Provide a single read-only SELECT statement.", violation.Fix);
}
}
}
3 changes: 3 additions & 0 deletions clients/node/src/generated.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,8 @@ export type Policy = {
bind: string;
}>;
}>;
/** Experimental. Only read by sqlguardllm mcp --auth oidc: context path (user.tenant_id) to claim of the verified access token. The key role names the claim that selects the role of a policy set. A missing claim leaves the value out (missing_context). */
context_from_claims?: Record<string, string>;
};

/** Values for the {context.path} placeholders of the row filters. */
Expand All @@ -80,6 +82,7 @@ export type WireViolation = {
code: string;
message: string;
detail: string;
fix?: string;
};

export type WireCheckResult = {
Expand Down
6 changes: 4 additions & 2 deletions clients/node/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ export type * from "./generated";

export type Fetch =(input: string, init?: RequestInit) => Promise<Response>;

export interface Violation { code: string; message: string; detail: string }
export interface Violation { code: string; message: string; detail: string; fix?: string }
export interface CheckResult {
ok: boolean;
sql: string | null;
Expand Down Expand Up @@ -64,7 +64,9 @@ function parseViolations(v: unknown): Violation[] {
if (!Array.isArray(v)) throw bad("violations");
return v.map((x) => {
if (!isObj(x) || typeof x.code !== "string" || typeof x.message !== "string") throw bad("violation");
return { code: x.code, message: x.message, detail: typeof x.detail === "string" ? x.detail : "" };
const violation: Violation = { code: x.code, message: x.message, detail: typeof x.detail === "string" ? x.detail : "" };
if (typeof x.fix === "string") violation.fix = x.fix;
return violation;
});
}

Expand Down
10 changes: 10 additions & 0 deletions clients/node/test/conformance.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,11 @@ describe.skipIf(!engine)("conformance (local mode)", () => {
const codes = [...new Set(r.violations.map((v) => v.code))].sort();
expect({ ok: r.ok, sql: r.sql, codes }, c.id).toEqual(c.expected);
expect(r.ok, c.id).toBe(c.expect === "allow");
for (const violation of r.violations) {
if (violation.code === "empty_statement") {
expect(violation.fix, c.id).toBe("Provide a single read-only SELECT statement.");
}
}
}
} finally {
await client.close();
Expand All @@ -78,6 +83,11 @@ describe.skipIf(!available)("conformance", () => {
const codes = [...new Set(r.violations.map((v) => v.code))].sort();
expect({ ok: r.ok, sql: r.sql, codes }, c.id).toEqual(c.expected);
expect(r.ok, c.id).toBe(c.expect === "allow");
for (const violation of r.violations) {
if (violation.code === "empty_statement") {
expect(violation.fix, c.id).toBe("Provide a single read-only SELECT statement.");
}
}
}
} finally {
proc.removeAllListeners("exit");
Expand Down
3 changes: 2 additions & 1 deletion docs/DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -306,7 +306,8 @@ The 2 ms target holds on the laptop. **On GitHub's shared runner, about 2.3 time
### Remediation hints

Selected Python violations expose an optional `fix` field. MCP `explain_query`
includes it when available. The hint is a localized constant keyed by violation
includes it when available, as do HTTP, stdio and CLI JSON. Node.js and .NET
clients expose the optional field. The hint is a localized constant keyed by violation
code. It never interpolates SQL fragments, identifiers, policy contents or caller
context, and leaves the guard decision and the existing rejection message intact.

Expand Down
3 changes: 2 additions & 1 deletion schema/protocol/protocol.schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@
"properties": {
"code": {"type": "string", "minLength": 1},
"message": {"type": "string"},
"detail": {"type": "string"}
"detail": {"type": "string"},
"fix": {"type": "string"}
}
},
"CheckResult": {
Expand Down
7 changes: 2 additions & 5 deletions src/sqlguardllm/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@
from sqlguardllm.messages import LANGUAGES
from sqlguardllm.policy import Policy
from sqlguardllm.policy_set import PolicySet
from sqlguardllm.result import CheckResult, PolicyError
from sqlguardllm.result import CheckResult, PolicyError, violation_to_dict
from sqlguardllm.schema import policy_schema, policy_set_schema, policy_tests_schema

EXIT_OK = 0
Expand Down Expand Up @@ -459,10 +459,7 @@ def _as_json(result: CheckResult) -> str:
"sql": result.sql,
"tables": sorted(result.tables),
"applied_filters": list(result.applied_filters),
"violations": [
{"code": v.code.value, "message": v.message, "detail": v.detail}
for v in result.violations
],
"violations": [violation_to_dict(v) for v in result.violations],
},
ensure_ascii=False,
indent=2,
Expand Down
7 changes: 2 additions & 5 deletions src/sqlguardllm/explain.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
from sqlguardllm._compiled import Compiled
from sqlguardllm._names import find, norm, table_name
from sqlguardllm.messages import LANGUAGES, violation
from sqlguardllm.result import Violation, ViolationCode
from sqlguardllm.result import Violation, ViolationCode, violation_to_dict
from sqlguardllm.rules.columns import _visible_sources, scope_columns
from sqlguardllm.rules.sources import PhysicalRef

Expand Down Expand Up @@ -164,10 +164,7 @@ def to_dict(self) -> dict[str, Any]:
"aggregate_only": dict(sorted(self.aggregate_only.items())),
"row_filters": dict(sorted(self.row_filters.items())),
"limit": self.limit,
"violations": [
{"code": v.code.value, "message": v.message, "detail": v.detail}
for v in self.violations
],
"violations": [violation_to_dict(v) for v in self.violations],
"text": self.text,
}

Expand Down
12 changes: 2 additions & 10 deletions src/sqlguardllm/mcp_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@
from sqlguardllm.messages import violation
from sqlguardllm.policy import Policy
from sqlguardllm.policy_set import PolicySet
from sqlguardllm.result import PolicyError, Violation, ViolationCode
from sqlguardllm.result import PolicyError, Violation, ViolationCode, violation_to_dict
from sqlguardllm.result_delivery import DeliveryDenied, ResultPolicy
from sqlguardllm.rules.taint import reads_untrusted, touches_sensitive, view_taint
from sqlguardllm.session_limits import RowBudgets
Expand Down Expand Up @@ -719,15 +719,7 @@ def explain_query(self, sql: _SqlArg, ctx: Context = None) -> dict[str, Any]: #
for table in sorted(explanation.row_filters)
},
"limit": explanation.limit,
"violations": [
{
"code": item.code.value,
"message": item.message,
"detail": item.detail,
**({"fix": item.fix} if item.fix is not None else {}),
}
for item in violations
],
"violations": [violation_to_dict(item) for item in violations],
}

@property
Expand Down
8 changes: 8 additions & 0 deletions src/sqlguardllm/result.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,14 @@ class Violation:
fix: str | None = field(default=None, repr=False, compare=False, kw_only=True)


def violation_to_dict(item: Violation) -> dict[str, str]:
"""Serialize optional guidance without changing older response fields."""
data = {"code": item.code.value, "message": item.message, "detail": item.detail}
if item.fix is not None:
data["fix"] = item.fix
return data


@dataclass(frozen=True)
class CheckResult:
"""Outcome of :meth:`sqlguardllm.Guard.check`.
Expand Down
7 changes: 2 additions & 5 deletions src/sqlguardllm/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

from sqlguardllm import __version__
from sqlguardllm.guard import Guard
from sqlguardllm.result import CheckResult
from sqlguardllm.result import CheckResult, violation_to_dict

MAX_BODY = 1024 * 1024
_JSON = "application/json; charset=utf-8"
Expand All @@ -27,10 +27,7 @@ def result_to_dict(result: CheckResult) -> dict[str, Any]:
"sql": result.sql,
"tables": sorted(result.tables),
"applied_filters": list(result.applied_filters),
"violations": [
{"code": v.code.value, "message": v.message, "detail": v.detail}
for v in result.violations
],
"violations": [violation_to_dict(v) for v in result.violations],
}


Expand Down
1 change: 1 addition & 0 deletions tests/test_explain.py
Original file line number Diff line number Diff line change
Expand Up @@ -329,6 +329,7 @@ def test_to_dict_is_json_ready() -> None:
"code": "hidden_column",
"message": "customers.email is a hidden column",
"detail": "customers.email",
"fix": "Use only columns the application has authorized for this task.",
}
]

Expand Down
5 changes: 4 additions & 1 deletion tests/test_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,10 @@ def test_check_allowed_and_rejected(server: GuardServer) -> None:
assert status == 200
assert bad["ok"] is False
assert bad["sql"] is None
assert bad["violations"][0].keys() == {"code", "message", "detail"}
assert bad["violations"][0].keys() == {"code", "message", "detail", "fix"}
assert bad["violations"][0]["fix"] == (
"Use a read-only SELECT if the request only needs to retrieve data."
)


def test_explain(server: GuardServer) -> None:
Expand Down
Loading