From cc011de5f73beaca129d4baaf85409748d8b2e3e Mon Sep 17 00:00:00 2001 From: Juan Manuel Castillo Pinto <33883620+jmmana@users.noreply.github.com> Date: Wed, 2 Dec 2026 03:04:16 -0500 Subject: [PATCH] feat: carry remediation hints through the client protocol --- CHANGELOG.md | 2 +- clients/dotnet/src/SqlGuardLlm/SqlGuardLlm.cs | 5 ++++- .../tests/SqlGuardLlm.Tests/ConformanceCorpus.cs | 2 ++ clients/node/src/generated.ts | 3 +++ clients/node/src/index.ts | 6 ++++-- clients/node/test/conformance.test.ts | 10 ++++++++++ docs/DESIGN.md | 3 ++- schema/protocol/protocol.schema.json | 3 ++- src/sqlguardllm/cli.py | 7 ++----- src/sqlguardllm/explain.py | 7 ++----- src/sqlguardllm/mcp_server.py | 12 ++---------- src/sqlguardllm/result.py | 8 ++++++++ src/sqlguardllm/server.py | 7 ++----- tests/test_explain.py | 1 + tests/test_server.py | 5 ++++- 15 files changed, 49 insertions(+), 32 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5484269..c14d417 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/clients/dotnet/src/SqlGuardLlm/SqlGuardLlm.cs b/clients/dotnet/src/SqlGuardLlm/SqlGuardLlm.cs index 4a7d10a..9602666 100644 --- a/clients/dotnet/src/SqlGuardLlm/SqlGuardLlm.cs +++ b/clients/dotnet/src/SqlGuardLlm/SqlGuardLlm.cs @@ -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; } +} /// Result of a check. true means is safe to run. public sealed record CheckResult diff --git a/clients/dotnet/tests/SqlGuardLlm.Tests/ConformanceCorpus.cs b/clients/dotnet/tests/SqlGuardLlm.Tests/ConformanceCorpus.cs index 20fc1a5..10b3530 100644 --- a/clients/dotnet/tests/SqlGuardLlm.Tests/ConformanceCorpus.cs +++ b/clients/dotnet/tests/SqlGuardLlm.Tests/ConformanceCorpus.cs @@ -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); } } } diff --git a/clients/node/src/generated.ts b/clients/node/src/generated.ts index e1325e7..397c2de 100644 --- a/clients/node/src/generated.ts +++ b/clients/node/src/generated.ts @@ -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; }; /** Values for the {context.path} placeholders of the row filters. */ @@ -80,6 +82,7 @@ export type WireViolation = { code: string; message: string; detail: string; + fix?: string; }; export type WireCheckResult = { diff --git a/clients/node/src/index.ts b/clients/node/src/index.ts index 53d6dc1..52d718d 100644 --- a/clients/node/src/index.ts +++ b/clients/node/src/index.ts @@ -6,7 +6,7 @@ export type * from "./generated"; export type Fetch =(input: string, init?: RequestInit) => Promise; -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; @@ -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; }); } diff --git a/clients/node/test/conformance.test.ts b/clients/node/test/conformance.test.ts index 62d3e65..a3df6a5 100644 --- a/clients/node/test/conformance.test.ts +++ b/clients/node/test/conformance.test.ts @@ -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(); @@ -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"); diff --git a/docs/DESIGN.md b/docs/DESIGN.md index dc4ab1f..af3a1aa 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -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. diff --git a/schema/protocol/protocol.schema.json b/schema/protocol/protocol.schema.json index 2b208df..89bc786 100644 --- a/schema/protocol/protocol.schema.json +++ b/schema/protocol/protocol.schema.json @@ -22,7 +22,8 @@ "properties": { "code": {"type": "string", "minLength": 1}, "message": {"type": "string"}, - "detail": {"type": "string"} + "detail": {"type": "string"}, + "fix": {"type": "string"} } }, "CheckResult": { diff --git a/src/sqlguardllm/cli.py b/src/sqlguardllm/cli.py index ae4ac9f..c5be7f3 100644 --- a/src/sqlguardllm/cli.py +++ b/src/sqlguardllm/cli.py @@ -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 @@ -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, diff --git a/src/sqlguardllm/explain.py b/src/sqlguardllm/explain.py index 5abf1bd..16f6000 100644 --- a/src/sqlguardllm/explain.py +++ b/src/sqlguardllm/explain.py @@ -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 @@ -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, } diff --git a/src/sqlguardllm/mcp_server.py b/src/sqlguardllm/mcp_server.py index f95bd38..c67b42a 100644 --- a/src/sqlguardllm/mcp_server.py +++ b/src/sqlguardllm/mcp_server.py @@ -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 @@ -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 diff --git a/src/sqlguardllm/result.py b/src/sqlguardllm/result.py index ca11d3c..ceaba9a 100644 --- a/src/sqlguardllm/result.py +++ b/src/sqlguardllm/result.py @@ -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`. diff --git a/src/sqlguardllm/server.py b/src/sqlguardllm/server.py index 55aa32f..6408d4e 100644 --- a/src/sqlguardllm/server.py +++ b/src/sqlguardllm/server.py @@ -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" @@ -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], } diff --git a/tests/test_explain.py b/tests/test_explain.py index b0ac397..c281467 100644 --- a/tests/test_explain.py +++ b/tests/test_explain.py @@ -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.", } ] diff --git a/tests/test_server.py b/tests/test_server.py index 409b8ea..84a8ac5 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -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: