skarn-guard 0.37.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,4 @@
1
+ .venv/
2
+ .pytest_cache/
3
+ .ruff_cache/
4
+ dist/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Skarn Software OÜ
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,260 @@
1
+ Metadata-Version: 2.4
2
+ Name: skarn-guard
3
+ Version: 0.37.0
4
+ Summary: Runs the Skarn guard inside Python agent runtimes and gateways
5
+ License-Expression: MIT
6
+ License-File: LICENSE
7
+ Requires-Python: >=3.11
8
+ Provides-Extra: adk
9
+ Requires-Dist: google-adk==2.14.0; extra == 'adk'
10
+ Provides-Extra: langchain
11
+ Requires-Dist: langchain==1.4.10; extra == 'langchain'
12
+ Provides-Extra: litellm
13
+ Requires-Dist: litellm==1.109.1; extra == 'litellm'
14
+ Provides-Extra: mcp
15
+ Requires-Dist: mcp==2.3.0; extra == 'mcp'
16
+ Provides-Extra: openai-agents
17
+ Requires-Dist: openai-agents==0.24.0; extra == 'openai-agents'
18
+ Provides-Extra: strands
19
+ Requires-Dist: strands-agents==1.65.0; extra == 'strands'
20
+ Description-Content-Type: text/markdown
21
+
22
+ # skarn-guard
23
+
24
+ `skarn-guard` runs the Skarn guard inside a server-side agent runtime. Before a tool runs, the adapter for your runtime sends the call to `skarn guard --agent sdk` on stdin and reads back one JSON verdict object. When the verdict says to block, the adapter stops the call and hands the runtime the binary's redacted reason. The binary does all the work: detection, redaction, the audit log and the decision whether a verdict is enforced. This package only carries the call to the binary and maps the answer onto each runtime's own return type.
25
+
26
+ ## Install
27
+
28
+ ```shell
29
+ brew install skarn-security/tap/skarn
30
+ pip install "skarn-guard[langchain]"
31
+ ```
32
+
33
+ The first command installs the `skarn` binary; other platforms are on https://getskarn.com/install/. The package is published to PyPI as `skarn-guard` from the first Skarn release that ships it. The base package has no dependencies. Each adapter is an extra that pins the runtime version it was tested against: `langchain`, `openai-agents`, `strands`, `adk`, `mcp` and `litellm`. The AgentCore handler needs no extra.
34
+
35
+ ## Configuration
36
+
37
+ ```python
38
+ from skarn_guard import SkarnGuard
39
+
40
+ guard = SkarnGuard(mode="enforce")
41
+ ```
42
+
43
+ | Argument | Default | Meaning |
44
+ |---|---|---|
45
+ | `binary` | `$SKARN_BIN`, then `skarn` on `PATH` | The `skarn` binary. If neither exists, the constructor raises `BinaryNotFound` with the install command. |
46
+ | `mode` | `"audit"` | `--guard-mode` for the binary: `audit` or `enforce`. |
47
+ | `strict` | `False` | Passes `--strict`, so an unclassifiable call answers deny. The OpenAI Agents adapter also raises the SDK's tripwire exception instead of rejecting the tool call. |
48
+ | `on_error` | `"ask"` | What a transport failure becomes: a timeout, a nonzero exit, output that is not one valid verdict object, or an event that JSON cannot encode. `"ask"` blocks when `mode` is `enforce`. `"allow"` lets the call through and logs a warning. |
49
+ | `timeout` | `5.0` | Seconds the binary gets per call. |
50
+ | `log` | `$SKARN_GUARD_LOG`, else `~/.cache/skarn/guard-sdk-audit.jsonl` | The guard log the binary appends to. `False` passes `--log none`. |
51
+ | `runtime` | the adapter's name | The `runtime` label in the envelope and the log. |
52
+ | `identity` | `None` | An identity label for the log. The guard does not authenticate it. |
53
+
54
+ The guard log is enabled by default. The binary writes a record only for a flagged call and ignores a write failure, so the log is a record of flagged calls, not of every call. Read it with `skarn guard report --agent sdk --log ~/.cache/skarn/guard-sdk-audit.jsonl`.
55
+
56
+ The LangChain, OpenAI Agents, Strands, ADK and LiteLLM adapters take a `kind_for` keyword that maps a runtime tool name to the envelope's tool kind; the MCP middleware and the AgentCore handler always send kind `mcp`. The default table is in `skarn_guard.envelope.DEFAULT_KINDS`; every other name maps to `other`, which the guard scans for content but gives no structural meaning.
57
+
58
+ | Tool name | Kind |
59
+ |---|---|
60
+ | `bash`, `shell`, `run_command`, `terminal` | `shell` |
61
+ | `write_file`, `create_file` | `write` |
62
+ | `edit_file`, `apply_patch` | `edit` |
63
+ | `read_file` | `read` |
64
+ | `fetch`, `http_get`, `web_fetch` | `fetch` |
65
+
66
+ ## The envelope
67
+
68
+ The adapters build this object for you. A runtime with no adapter can build it with `skarn_guard.GuardEvent` and call `guard.check(event)`.
69
+
70
+ ```python
71
+ from skarn_guard import GuardEvent, SkarnGuard
72
+
73
+ event = GuardEvent.pre_tool("run_command", "shell", {"command": "ls -la"}, runtime="my-runtime")
74
+ verdict = SkarnGuard().check(event)
75
+ print(verdict.verdict, verdict.enforce, verdict.rule)
76
+ ```
77
+
78
+ `event.to_json()` is `{"v": 1, "event": "pre_tool_use", "runtime": "my-runtime", "tool": {"name": "run_command", "kind": "shell", "input": {"command": "ls -la"}}}`. The full contract is in the guard manual, https://getskarn.com/manual/#cmd-guard, under server-side agent runtimes.
79
+
80
+ ## The blocking rule
81
+
82
+ An adapter blocks a call only when the verdict's `enforce` is true and its `verdict` is `ask` or `deny`; `skarn_guard.should_block` is that rule. The binary sets `enforce`, so this package never decides enforcement on its own. Every verdict is logged through the `skarn_guard` logger at INFO, and a call that is not blocked goes through. The text an adapter hands the runtime is `skarn-guard: ` followed by the binary's redacted reason, and nothing else.
83
+
84
+ In the examples below, `model` is your own model object and `run_command` is one of your own tools.
85
+
86
+ ## `skarn_guard.langchain`
87
+
88
+ Middleware for a LangChain agent built with `create_agent`.
89
+
90
+ ```python
91
+ from langchain.agents import create_agent
92
+
93
+ from skarn_guard import SkarnGuard
94
+ from skarn_guard.langchain import SkarnGuardMiddleware
95
+
96
+ agent = create_agent(
97
+ model,
98
+ tools=[run_command],
99
+ middleware=[SkarnGuardMiddleware(SkarnGuard(mode="enforce"))],
100
+ )
101
+ ```
102
+
103
+ A blocked call returns a `ToolMessage` with `status="error"` and the reason as its content, and the tool does not run. The middleware treats an enforced ask as a deny unless you pass `on_ask`, a callable that receives the verdict and the `ToolCallRequest` and returns `True` to run the tool. If your agent already runs `HumanInTheLoopMiddleware`, `on_ask` is where you route the decision to it. Both `invoke` and `ainvoke` are covered.
104
+
105
+ ## `skarn_guard.openai_agents`
106
+
107
+ Tool guardrails for the OpenAI Agents SDK.
108
+
109
+ ```python
110
+ from agents import function_tool
111
+
112
+ from skarn_guard import SkarnGuard
113
+ from skarn_guard.openai_agents import skarn_tool_input_guardrail, skarn_tool_output_guardrail
114
+
115
+ guard = SkarnGuard(mode="enforce")
116
+
117
+
118
+ @function_tool(
119
+ tool_input_guardrails=[skarn_tool_input_guardrail(guard)],
120
+ tool_output_guardrails=[skarn_tool_output_guardrail(guard)],
121
+ )
122
+ def lookup(q: str) -> str:
123
+ """Look up an order."""
124
+ return q
125
+ ```
126
+
127
+ The input guardrail runs before the tool and answers a block with `reject_content`, so the model receives the reason in place of the tool result and the tool does not run. The output guardrail runs after the tool, which has already run by the SDK's contract, and replaces an unsafe result before the model sees it. The SDK has no ask channel for tool guardrails, so an enforced ask is rejected like a deny. With `strict=True` the guardrails raise `ToolInputGuardrailTripwireTriggered` or `ToolOutputGuardrailTripwireTriggered` instead.
128
+
129
+ ## `skarn_guard.strands`
130
+
131
+ A plugin for a Strands Agents agent.
132
+
133
+ ```python
134
+ from strands import Agent
135
+
136
+ from skarn_guard import SkarnGuard
137
+ from skarn_guard.strands import SkarnGuardPlugin
138
+
139
+ agent = Agent(model=model, tools=[run_command], plugins=[SkarnGuardPlugin(SkarnGuard(mode="enforce"))])
140
+ result = agent("rotate the logs")
141
+ while result.stop_reason == "interrupt":
142
+ result = agent(
143
+ [{"interruptResponse": {"interruptId": interrupt.id, "response": "reject"}} for interrupt in result.interrupts]
144
+ )
145
+ ```
146
+
147
+ The plugin registers a Strands tool middleware (`ExecuteToolStage`). The middleware runs after every `BeforeToolCallEvent` hook, so it checks the tool that runs and the input that tool receives, under the name of that tool, even when a hook selected another tool or rewrote the input. A tool middleware that wraps the call and is registered after the plugin runs inside it and can still change the call. List the plugin last in `plugins`, and do not call `agent.add_middleware(ExecuteToolStage, ...)` on the agent after you build it.
148
+
149
+ An enforced deny answers the call with an error tool result that carries the reason, and the tool does not run. An enforced ask raises a Strands interrupt whose reason is the blocking message; the agent stops with `stop_reason == "interrupt"`. The interrupt name is `skarn-guard:` followed by a SHA-256 digest of the event the binary judged, which holds the tool name and the input, so Strands hands a response back only for that exact call. Resume the agent with a response: `True`, `"approve"`, `"approved"` or `"yes"` runs the tool, and any other response answers the call with the error result `skarn-guard: the call was not approved`. An answered call is not checked a second time. If a hook changes the tool or the input before the resume, the response does not apply: the changed call is checked as a new call and, on an enforced ask, raises a new interrupt. The plugin keeps no state of its own. An enforced ask on an input that JSON cannot encode has no digest to bind a response to, so it blocks the call without an interrupt. After a tool runs, the middleware sends its result as a `post_tool_use` event and logs the verdict; it never changes the result.
150
+
151
+ ## `skarn_guard.adk`
152
+
153
+ A `before_tool_callback` for a Google Agent Development Kit (ADK) agent.
154
+
155
+ ```python
156
+ from google.adk.agents import LlmAgent
157
+
158
+ from skarn_guard import SkarnGuard
159
+ from skarn_guard.adk import before_tool_callback
160
+
161
+ agent = LlmAgent(
162
+ name="ops",
163
+ model="gemini-2.5-flash",
164
+ tools=[run_command],
165
+ before_tool_callback=before_tool_callback(SkarnGuard(mode="enforce")),
166
+ )
167
+ ```
168
+
169
+ A blocked call returns `{"error": <reason>}` as the tool response, and the tool does not run. ADK has no ask channel here, so an enforced ask blocks like a deny.
170
+
171
+ ## `skarn_guard.mcp`
172
+
173
+ Server middleware for the MCP Python SDK.
174
+
175
+ ```python
176
+ from mcp.server.mcpserver import MCPServer
177
+
178
+ from skarn_guard import SkarnGuard
179
+ from skarn_guard.mcp import skarn_middleware
180
+
181
+ server = MCPServer("orders", middleware=[skarn_middleware(SkarnGuard(mode="enforce"), "orders")])
182
+
183
+
184
+ @server.tool()
185
+ def lookup(q: str) -> str:
186
+ return q
187
+ ```
188
+
189
+ The middleware checks `tools/call` requests only; every other method passes through unchecked. The second argument names the server, and the guard builds the tool name as `mcp__orders__<tool>` the way every host builds an MCP name. A blocked call returns a `CallToolResult` with `is_error` set and the reason as text, and the tool does not run. MCP has no ask channel, so an enforced ask blocks like a deny.
190
+
191
+ ## `skarn_guard.agentcore`
192
+
193
+ A REQUEST interceptor for an Amazon Bedrock AgentCore Gateway with MCP targets.
194
+
195
+ ```python
196
+ from skarn_guard import SkarnGuard
197
+ from skarn_guard.agentcore import make_handler
198
+
199
+ handler = make_handler(SkarnGuard(mode="enforce"), server="orders")
200
+ ```
201
+
202
+ Deploy `handler` as the Lambda of a REQUEST interceptor on your gateway, with the `skarn` binary in the function's layer and `SKARN_BIN` pointing at it. The handler always returns `interceptorOutputVersion` `"1.0"`. For an allowed `tools/call`, and for every other method, it passes the request body through unchanged in `transformedGatewayRequest`. For a blocked `tools/call` it returns `transformedGatewayResponse` with status 200 and a JSON-RPC result that carries the request's `id`, `isError: true` and the reason as text, so the target tool never runs. The handler reads the `mcp` payload of an MCP target; it does not read the `http` payload, with its base64-encoded body, that an HTTP target sends.
203
+
204
+ ## `skarn_guard.litellm`
205
+
206
+ A guardrail for the LiteLLM proxy.
207
+
208
+ ```python
209
+ from skarn_guard.litellm import SkarnGuardrail
210
+ ```
211
+
212
+ ```yaml
213
+ guardrails:
214
+ - guardrail_name: skarn
215
+ litellm_params:
216
+ guardrail: skarn_guard.litellm.SkarnGuardrail
217
+ mode: [pre_call, post_call]
218
+ default_on: true
219
+ skarn_mode: enforce
220
+ streaming_buffer_until_moderated: true
221
+ ```
222
+
223
+ `SkarnGuardrail` is a LiteLLM `CustomGuardrail`. Extra `litellm_params` reach it as keyword arguments: `skarn_mode`, `skarn_strict`, `skarn_log` and `skarn_binary`, and `streaming_buffer_until_moderated` reaches LiteLLM (see the streaming paragraph below). On the request it sends each text as a `user_prompt_submit` event, all linked image URLs together as one more `user_prompt_submit` event with one URL on each line, and each tool result in the conversation as a `post_tool_use` event. LiteLLM calls a guardrail only for a request that carries text or a tool call, so a request whose only content is images reaches the model with no scan. On the response it sends each tool call the model proposes as a `pre_tool_use` event. `SkarnGuardrail` supports the `pre_call`, `during_call` and `post_call` modes. LiteLLM refuses to start it in an MCP mode (`pre_mcp_call`, `during_mcp_call`, `post_mcp_call`), because those hooks hand a guardrail argument and result text without the tool call it belongs to; with `LITELLM_STRICT_GUARDRAIL_MODES=false` LiteLLM only logs the mismatch. Guard an MCP server with `skarn_guard.mcp` instead. A block raises `GuardrailRaisedException`, which LiteLLM answers with HTTP 400; a gateway has no ask channel, so an enforced ask blocks like a deny. Allowed inputs are returned unchanged.
224
+
225
+ Timing matters at a gateway. A tool result in a request reaches the gateway after the runtime already ran that tool, so blocking the request stops the result from reaching the model, not the tool. A tool call in a response reaches the gateway before the runtime runs it, and blocking the response rejects the whole model turn rather than one call. To stop a tool before it runs, put an in-process adapter in the runtime.
226
+
227
+ With a streaming response, LiteLLM by default forwards chunks to the client as they arrive and checks tool calls only once the stream has finished, so a response-side block comes after the client already holds the streamed tool call. `streaming_buffer_until_moderated: true` makes LiteLLM withhold every chunk until the guardrail returns its verdict on the finished stream: an allowed stream is then released whole, and a blocked one releases no chunk. The cost is that the client receives the response only after the stream has finished. A guardrail in enforce mode sets this by default, because a block that arrives after the tool call does not stop it; set `streaming_buffer_until_moderated: false` in the guardrail's `litellm_params` to get LiteLLM's forwarding back. A guardrail in audit mode blocks nothing and leaves LiteLLM's default in place. LiteLLM's own DEBUG logging can record a guardrail's inputs, as it records other request content; the package's own log lines stay redacted.
228
+
229
+ ## Runtimes with their own hook
230
+
231
+ The Claude Agent SDK loads the shell command hooks from settings files by default, so the hook `skarn setup` writes for Claude Code already guards a server-side Claude Agent SDK application; this package is not needed there. Bedrock Agents (classic) has no dedicated hook: you own the action group Lambda or the calling application, and that code calls `guard.check` before it acts on the tool call.
232
+
233
+ ## Without a license
234
+
235
+ A server with no Skarn license installed runs in audit: every verdict the binary returns carries `enforce: false`, so the adapters log the verdict and never block on a binary verdict. A transport failure is the client's own answer, not the binary's: with `mode="enforce"` and the default `on_error="ask"` it still blocks, so a runtime that is configured to enforce does not lose the guard when the binary cannot answer. To enforce, install your organisation's automation license on the server with `skarn license -`, which reads the token from stdin. Enforcement is where the policy, the baselines and the audit record decide what blocks.
236
+
237
+ ## What it never does
238
+
239
+ - It reads no license, no rules file and no session store, and it runs no detector of its own.
240
+ - It opens no socket. The binary reads stdin and writes stdout.
241
+ - It never changes a tool input, a request or a tool result, and it composes no text from them.
242
+ - It never logs the raw tool name, the arguments or the result. Its log lines carry the verdict, `enforce`, the source, the rule, the fingerprint, the severity and the redacted reason.
243
+
244
+ ## Support matrix
245
+
246
+ | Runtime | Package and version | Deny | Ask | Tested on |
247
+ |---|---|---|---|---|
248
+ | LangChain | `langchain` 1.4.10 | `ToolMessage` with `status="error"` | `on_ask`, else blocked | 2026-11-15, Python 3.11 and 3.13 |
249
+ | OpenAI Agents SDK | `openai-agents` 0.24.0 | `reject_content` | blocked | 2026-11-15, Python 3.11 and 3.13 |
250
+ | Strands Agents | `strands-agents` 1.65.0 | error tool result from the tool middleware | interrupt and resume | 2026-11-15, Python 3.11 and 3.13 |
251
+ | Google ADK | `google-adk` 2.14.0 | `{"error": ...}` | blocked | 2026-11-15, Python 3.11 and 3.13 |
252
+ | MCP Python SDK | `mcp` 2.3.0 | `CallToolResult(is_error=True)` | blocked | 2026-11-15, Python 3.11 and 3.13 |
253
+ | AgentCore Gateway | REQUEST interceptor, version 1.0 | `transformedGatewayResponse` | blocked | 2026-11-15, Python 3.11 and 3.13 |
254
+ | LiteLLM | `litellm` 1.109.1 | `GuardrailRaisedException` (HTTP 400) | blocked | 2026-11-15, Python 3.11 and 3.13 |
255
+
256
+ Every in-process row is tested through the runtime's own dispatch path with a fake model, LiteLLM through its chat-completions guardrail handler and AgentCore through the documented interceptor event, all against the real `skarn` binary: a deny, an enforced ask, an ask in audit, an allow, a transport failure while enforcing, and an enforce request with no license. CI runs the suite on Python 3.11.
257
+
258
+ ## License
259
+
260
+ MIT, see `LICENSE`.
@@ -0,0 +1,239 @@
1
+ # skarn-guard
2
+
3
+ `skarn-guard` runs the Skarn guard inside a server-side agent runtime. Before a tool runs, the adapter for your runtime sends the call to `skarn guard --agent sdk` on stdin and reads back one JSON verdict object. When the verdict says to block, the adapter stops the call and hands the runtime the binary's redacted reason. The binary does all the work: detection, redaction, the audit log and the decision whether a verdict is enforced. This package only carries the call to the binary and maps the answer onto each runtime's own return type.
4
+
5
+ ## Install
6
+
7
+ ```shell
8
+ brew install skarn-security/tap/skarn
9
+ pip install "skarn-guard[langchain]"
10
+ ```
11
+
12
+ The first command installs the `skarn` binary; other platforms are on https://getskarn.com/install/. The package is published to PyPI as `skarn-guard` from the first Skarn release that ships it. The base package has no dependencies. Each adapter is an extra that pins the runtime version it was tested against: `langchain`, `openai-agents`, `strands`, `adk`, `mcp` and `litellm`. The AgentCore handler needs no extra.
13
+
14
+ ## Configuration
15
+
16
+ ```python
17
+ from skarn_guard import SkarnGuard
18
+
19
+ guard = SkarnGuard(mode="enforce")
20
+ ```
21
+
22
+ | Argument | Default | Meaning |
23
+ |---|---|---|
24
+ | `binary` | `$SKARN_BIN`, then `skarn` on `PATH` | The `skarn` binary. If neither exists, the constructor raises `BinaryNotFound` with the install command. |
25
+ | `mode` | `"audit"` | `--guard-mode` for the binary: `audit` or `enforce`. |
26
+ | `strict` | `False` | Passes `--strict`, so an unclassifiable call answers deny. The OpenAI Agents adapter also raises the SDK's tripwire exception instead of rejecting the tool call. |
27
+ | `on_error` | `"ask"` | What a transport failure becomes: a timeout, a nonzero exit, output that is not one valid verdict object, or an event that JSON cannot encode. `"ask"` blocks when `mode` is `enforce`. `"allow"` lets the call through and logs a warning. |
28
+ | `timeout` | `5.0` | Seconds the binary gets per call. |
29
+ | `log` | `$SKARN_GUARD_LOG`, else `~/.cache/skarn/guard-sdk-audit.jsonl` | The guard log the binary appends to. `False` passes `--log none`. |
30
+ | `runtime` | the adapter's name | The `runtime` label in the envelope and the log. |
31
+ | `identity` | `None` | An identity label for the log. The guard does not authenticate it. |
32
+
33
+ The guard log is enabled by default. The binary writes a record only for a flagged call and ignores a write failure, so the log is a record of flagged calls, not of every call. Read it with `skarn guard report --agent sdk --log ~/.cache/skarn/guard-sdk-audit.jsonl`.
34
+
35
+ The LangChain, OpenAI Agents, Strands, ADK and LiteLLM adapters take a `kind_for` keyword that maps a runtime tool name to the envelope's tool kind; the MCP middleware and the AgentCore handler always send kind `mcp`. The default table is in `skarn_guard.envelope.DEFAULT_KINDS`; every other name maps to `other`, which the guard scans for content but gives no structural meaning.
36
+
37
+ | Tool name | Kind |
38
+ |---|---|
39
+ | `bash`, `shell`, `run_command`, `terminal` | `shell` |
40
+ | `write_file`, `create_file` | `write` |
41
+ | `edit_file`, `apply_patch` | `edit` |
42
+ | `read_file` | `read` |
43
+ | `fetch`, `http_get`, `web_fetch` | `fetch` |
44
+
45
+ ## The envelope
46
+
47
+ The adapters build this object for you. A runtime with no adapter can build it with `skarn_guard.GuardEvent` and call `guard.check(event)`.
48
+
49
+ ```python
50
+ from skarn_guard import GuardEvent, SkarnGuard
51
+
52
+ event = GuardEvent.pre_tool("run_command", "shell", {"command": "ls -la"}, runtime="my-runtime")
53
+ verdict = SkarnGuard().check(event)
54
+ print(verdict.verdict, verdict.enforce, verdict.rule)
55
+ ```
56
+
57
+ `event.to_json()` is `{"v": 1, "event": "pre_tool_use", "runtime": "my-runtime", "tool": {"name": "run_command", "kind": "shell", "input": {"command": "ls -la"}}}`. The full contract is in the guard manual, https://getskarn.com/manual/#cmd-guard, under server-side agent runtimes.
58
+
59
+ ## The blocking rule
60
+
61
+ An adapter blocks a call only when the verdict's `enforce` is true and its `verdict` is `ask` or `deny`; `skarn_guard.should_block` is that rule. The binary sets `enforce`, so this package never decides enforcement on its own. Every verdict is logged through the `skarn_guard` logger at INFO, and a call that is not blocked goes through. The text an adapter hands the runtime is `skarn-guard: ` followed by the binary's redacted reason, and nothing else.
62
+
63
+ In the examples below, `model` is your own model object and `run_command` is one of your own tools.
64
+
65
+ ## `skarn_guard.langchain`
66
+
67
+ Middleware for a LangChain agent built with `create_agent`.
68
+
69
+ ```python
70
+ from langchain.agents import create_agent
71
+
72
+ from skarn_guard import SkarnGuard
73
+ from skarn_guard.langchain import SkarnGuardMiddleware
74
+
75
+ agent = create_agent(
76
+ model,
77
+ tools=[run_command],
78
+ middleware=[SkarnGuardMiddleware(SkarnGuard(mode="enforce"))],
79
+ )
80
+ ```
81
+
82
+ A blocked call returns a `ToolMessage` with `status="error"` and the reason as its content, and the tool does not run. The middleware treats an enforced ask as a deny unless you pass `on_ask`, a callable that receives the verdict and the `ToolCallRequest` and returns `True` to run the tool. If your agent already runs `HumanInTheLoopMiddleware`, `on_ask` is where you route the decision to it. Both `invoke` and `ainvoke` are covered.
83
+
84
+ ## `skarn_guard.openai_agents`
85
+
86
+ Tool guardrails for the OpenAI Agents SDK.
87
+
88
+ ```python
89
+ from agents import function_tool
90
+
91
+ from skarn_guard import SkarnGuard
92
+ from skarn_guard.openai_agents import skarn_tool_input_guardrail, skarn_tool_output_guardrail
93
+
94
+ guard = SkarnGuard(mode="enforce")
95
+
96
+
97
+ @function_tool(
98
+ tool_input_guardrails=[skarn_tool_input_guardrail(guard)],
99
+ tool_output_guardrails=[skarn_tool_output_guardrail(guard)],
100
+ )
101
+ def lookup(q: str) -> str:
102
+ """Look up an order."""
103
+ return q
104
+ ```
105
+
106
+ The input guardrail runs before the tool and answers a block with `reject_content`, so the model receives the reason in place of the tool result and the tool does not run. The output guardrail runs after the tool, which has already run by the SDK's contract, and replaces an unsafe result before the model sees it. The SDK has no ask channel for tool guardrails, so an enforced ask is rejected like a deny. With `strict=True` the guardrails raise `ToolInputGuardrailTripwireTriggered` or `ToolOutputGuardrailTripwireTriggered` instead.
107
+
108
+ ## `skarn_guard.strands`
109
+
110
+ A plugin for a Strands Agents agent.
111
+
112
+ ```python
113
+ from strands import Agent
114
+
115
+ from skarn_guard import SkarnGuard
116
+ from skarn_guard.strands import SkarnGuardPlugin
117
+
118
+ agent = Agent(model=model, tools=[run_command], plugins=[SkarnGuardPlugin(SkarnGuard(mode="enforce"))])
119
+ result = agent("rotate the logs")
120
+ while result.stop_reason == "interrupt":
121
+ result = agent(
122
+ [{"interruptResponse": {"interruptId": interrupt.id, "response": "reject"}} for interrupt in result.interrupts]
123
+ )
124
+ ```
125
+
126
+ The plugin registers a Strands tool middleware (`ExecuteToolStage`). The middleware runs after every `BeforeToolCallEvent` hook, so it checks the tool that runs and the input that tool receives, under the name of that tool, even when a hook selected another tool or rewrote the input. A tool middleware that wraps the call and is registered after the plugin runs inside it and can still change the call. List the plugin last in `plugins`, and do not call `agent.add_middleware(ExecuteToolStage, ...)` on the agent after you build it.
127
+
128
+ An enforced deny answers the call with an error tool result that carries the reason, and the tool does not run. An enforced ask raises a Strands interrupt whose reason is the blocking message; the agent stops with `stop_reason == "interrupt"`. The interrupt name is `skarn-guard:` followed by a SHA-256 digest of the event the binary judged, which holds the tool name and the input, so Strands hands a response back only for that exact call. Resume the agent with a response: `True`, `"approve"`, `"approved"` or `"yes"` runs the tool, and any other response answers the call with the error result `skarn-guard: the call was not approved`. An answered call is not checked a second time. If a hook changes the tool or the input before the resume, the response does not apply: the changed call is checked as a new call and, on an enforced ask, raises a new interrupt. The plugin keeps no state of its own. An enforced ask on an input that JSON cannot encode has no digest to bind a response to, so it blocks the call without an interrupt. After a tool runs, the middleware sends its result as a `post_tool_use` event and logs the verdict; it never changes the result.
129
+
130
+ ## `skarn_guard.adk`
131
+
132
+ A `before_tool_callback` for a Google Agent Development Kit (ADK) agent.
133
+
134
+ ```python
135
+ from google.adk.agents import LlmAgent
136
+
137
+ from skarn_guard import SkarnGuard
138
+ from skarn_guard.adk import before_tool_callback
139
+
140
+ agent = LlmAgent(
141
+ name="ops",
142
+ model="gemini-2.5-flash",
143
+ tools=[run_command],
144
+ before_tool_callback=before_tool_callback(SkarnGuard(mode="enforce")),
145
+ )
146
+ ```
147
+
148
+ A blocked call returns `{"error": <reason>}` as the tool response, and the tool does not run. ADK has no ask channel here, so an enforced ask blocks like a deny.
149
+
150
+ ## `skarn_guard.mcp`
151
+
152
+ Server middleware for the MCP Python SDK.
153
+
154
+ ```python
155
+ from mcp.server.mcpserver import MCPServer
156
+
157
+ from skarn_guard import SkarnGuard
158
+ from skarn_guard.mcp import skarn_middleware
159
+
160
+ server = MCPServer("orders", middleware=[skarn_middleware(SkarnGuard(mode="enforce"), "orders")])
161
+
162
+
163
+ @server.tool()
164
+ def lookup(q: str) -> str:
165
+ return q
166
+ ```
167
+
168
+ The middleware checks `tools/call` requests only; every other method passes through unchecked. The second argument names the server, and the guard builds the tool name as `mcp__orders__<tool>` the way every host builds an MCP name. A blocked call returns a `CallToolResult` with `is_error` set and the reason as text, and the tool does not run. MCP has no ask channel, so an enforced ask blocks like a deny.
169
+
170
+ ## `skarn_guard.agentcore`
171
+
172
+ A REQUEST interceptor for an Amazon Bedrock AgentCore Gateway with MCP targets.
173
+
174
+ ```python
175
+ from skarn_guard import SkarnGuard
176
+ from skarn_guard.agentcore import make_handler
177
+
178
+ handler = make_handler(SkarnGuard(mode="enforce"), server="orders")
179
+ ```
180
+
181
+ Deploy `handler` as the Lambda of a REQUEST interceptor on your gateway, with the `skarn` binary in the function's layer and `SKARN_BIN` pointing at it. The handler always returns `interceptorOutputVersion` `"1.0"`. For an allowed `tools/call`, and for every other method, it passes the request body through unchanged in `transformedGatewayRequest`. For a blocked `tools/call` it returns `transformedGatewayResponse` with status 200 and a JSON-RPC result that carries the request's `id`, `isError: true` and the reason as text, so the target tool never runs. The handler reads the `mcp` payload of an MCP target; it does not read the `http` payload, with its base64-encoded body, that an HTTP target sends.
182
+
183
+ ## `skarn_guard.litellm`
184
+
185
+ A guardrail for the LiteLLM proxy.
186
+
187
+ ```python
188
+ from skarn_guard.litellm import SkarnGuardrail
189
+ ```
190
+
191
+ ```yaml
192
+ guardrails:
193
+ - guardrail_name: skarn
194
+ litellm_params:
195
+ guardrail: skarn_guard.litellm.SkarnGuardrail
196
+ mode: [pre_call, post_call]
197
+ default_on: true
198
+ skarn_mode: enforce
199
+ streaming_buffer_until_moderated: true
200
+ ```
201
+
202
+ `SkarnGuardrail` is a LiteLLM `CustomGuardrail`. Extra `litellm_params` reach it as keyword arguments: `skarn_mode`, `skarn_strict`, `skarn_log` and `skarn_binary`, and `streaming_buffer_until_moderated` reaches LiteLLM (see the streaming paragraph below). On the request it sends each text as a `user_prompt_submit` event, all linked image URLs together as one more `user_prompt_submit` event with one URL on each line, and each tool result in the conversation as a `post_tool_use` event. LiteLLM calls a guardrail only for a request that carries text or a tool call, so a request whose only content is images reaches the model with no scan. On the response it sends each tool call the model proposes as a `pre_tool_use` event. `SkarnGuardrail` supports the `pre_call`, `during_call` and `post_call` modes. LiteLLM refuses to start it in an MCP mode (`pre_mcp_call`, `during_mcp_call`, `post_mcp_call`), because those hooks hand a guardrail argument and result text without the tool call it belongs to; with `LITELLM_STRICT_GUARDRAIL_MODES=false` LiteLLM only logs the mismatch. Guard an MCP server with `skarn_guard.mcp` instead. A block raises `GuardrailRaisedException`, which LiteLLM answers with HTTP 400; a gateway has no ask channel, so an enforced ask blocks like a deny. Allowed inputs are returned unchanged.
203
+
204
+ Timing matters at a gateway. A tool result in a request reaches the gateway after the runtime already ran that tool, so blocking the request stops the result from reaching the model, not the tool. A tool call in a response reaches the gateway before the runtime runs it, and blocking the response rejects the whole model turn rather than one call. To stop a tool before it runs, put an in-process adapter in the runtime.
205
+
206
+ With a streaming response, LiteLLM by default forwards chunks to the client as they arrive and checks tool calls only once the stream has finished, so a response-side block comes after the client already holds the streamed tool call. `streaming_buffer_until_moderated: true` makes LiteLLM withhold every chunk until the guardrail returns its verdict on the finished stream: an allowed stream is then released whole, and a blocked one releases no chunk. The cost is that the client receives the response only after the stream has finished. A guardrail in enforce mode sets this by default, because a block that arrives after the tool call does not stop it; set `streaming_buffer_until_moderated: false` in the guardrail's `litellm_params` to get LiteLLM's forwarding back. A guardrail in audit mode blocks nothing and leaves LiteLLM's default in place. LiteLLM's own DEBUG logging can record a guardrail's inputs, as it records other request content; the package's own log lines stay redacted.
207
+
208
+ ## Runtimes with their own hook
209
+
210
+ The Claude Agent SDK loads the shell command hooks from settings files by default, so the hook `skarn setup` writes for Claude Code already guards a server-side Claude Agent SDK application; this package is not needed there. Bedrock Agents (classic) has no dedicated hook: you own the action group Lambda or the calling application, and that code calls `guard.check` before it acts on the tool call.
211
+
212
+ ## Without a license
213
+
214
+ A server with no Skarn license installed runs in audit: every verdict the binary returns carries `enforce: false`, so the adapters log the verdict and never block on a binary verdict. A transport failure is the client's own answer, not the binary's: with `mode="enforce"` and the default `on_error="ask"` it still blocks, so a runtime that is configured to enforce does not lose the guard when the binary cannot answer. To enforce, install your organisation's automation license on the server with `skarn license -`, which reads the token from stdin. Enforcement is where the policy, the baselines and the audit record decide what blocks.
215
+
216
+ ## What it never does
217
+
218
+ - It reads no license, no rules file and no session store, and it runs no detector of its own.
219
+ - It opens no socket. The binary reads stdin and writes stdout.
220
+ - It never changes a tool input, a request or a tool result, and it composes no text from them.
221
+ - It never logs the raw tool name, the arguments or the result. Its log lines carry the verdict, `enforce`, the source, the rule, the fingerprint, the severity and the redacted reason.
222
+
223
+ ## Support matrix
224
+
225
+ | Runtime | Package and version | Deny | Ask | Tested on |
226
+ |---|---|---|---|---|
227
+ | LangChain | `langchain` 1.4.10 | `ToolMessage` with `status="error"` | `on_ask`, else blocked | 2026-11-15, Python 3.11 and 3.13 |
228
+ | OpenAI Agents SDK | `openai-agents` 0.24.0 | `reject_content` | blocked | 2026-11-15, Python 3.11 and 3.13 |
229
+ | Strands Agents | `strands-agents` 1.65.0 | error tool result from the tool middleware | interrupt and resume | 2026-11-15, Python 3.11 and 3.13 |
230
+ | Google ADK | `google-adk` 2.14.0 | `{"error": ...}` | blocked | 2026-11-15, Python 3.11 and 3.13 |
231
+ | MCP Python SDK | `mcp` 2.3.0 | `CallToolResult(is_error=True)` | blocked | 2026-11-15, Python 3.11 and 3.13 |
232
+ | AgentCore Gateway | REQUEST interceptor, version 1.0 | `transformedGatewayResponse` | blocked | 2026-11-15, Python 3.11 and 3.13 |
233
+ | LiteLLM | `litellm` 1.109.1 | `GuardrailRaisedException` (HTTP 400) | blocked | 2026-11-15, Python 3.11 and 3.13 |
234
+
235
+ Every in-process row is tested through the runtime's own dispatch path with a fake model, LiteLLM through its chat-completions guardrail handler and AgentCore through the documented interceptor event, all against the real `skarn` binary: a deny, an enforced ask, an ask in audit, an allow, a transport failure while enforcing, and an enforce request with no license. CI runs the suite on Python 3.11.
236
+
237
+ ## License
238
+
239
+ MIT, see `LICENSE`.
@@ -0,0 +1,40 @@
1
+ [build-system]
2
+ requires = ["hatchling==1.27.0"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "skarn-guard"
7
+ version = "0.37.0"
8
+ description = "Runs the Skarn guard inside Python agent runtimes and gateways"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.11"
13
+ dependencies = []
14
+
15
+ [project.optional-dependencies]
16
+ langchain = ["langchain==1.4.10"]
17
+ openai-agents = ["openai-agents==0.24.0"]
18
+ strands = ["strands-agents==1.65.0"]
19
+ adk = ["google-adk==2.14.0"]
20
+ mcp = ["mcp==2.3.0"]
21
+ litellm = ["litellm==1.109.1"]
22
+
23
+ [dependency-groups]
24
+ dev = ["pytest==9.2.0", "ruff==0.17.5"]
25
+
26
+ [tool.hatch.build.targets.wheel]
27
+ packages = ["src/skarn_guard"]
28
+
29
+ [tool.ruff]
30
+ line-length = 120
31
+ target-version = "py311"
32
+
33
+ [tool.ruff.lint]
34
+ select = ["E", "F", "W", "I", "B", "UP"]
35
+
36
+ [tool.ruff.lint.isort]
37
+ known-first-party = ["skarn_guard", "conftest"]
38
+
39
+ [tool.pytest.ini_options]
40
+ testpaths = ["tests"]
@@ -0,0 +1,29 @@
1
+ from skarn_guard.client import (
2
+ INSTALL_COMMAND,
3
+ PREFIX,
4
+ BinaryNotFound,
5
+ SkarnGuard,
6
+ Verdict,
7
+ blocking_message,
8
+ evaluate,
9
+ parse_verdict,
10
+ should_block,
11
+ )
12
+ from skarn_guard.envelope import DEFAULT_KINDS, KINDS, GuardEvent, Kind, kind_for
13
+
14
+ __all__ = [
15
+ "DEFAULT_KINDS",
16
+ "INSTALL_COMMAND",
17
+ "KINDS",
18
+ "PREFIX",
19
+ "BinaryNotFound",
20
+ "GuardEvent",
21
+ "Kind",
22
+ "SkarnGuard",
23
+ "Verdict",
24
+ "blocking_message",
25
+ "evaluate",
26
+ "kind_for",
27
+ "parse_verdict",
28
+ "should_block",
29
+ ]
@@ -0,0 +1,30 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ from collections.abc import Awaitable, Callable
5
+ from typing import Any
6
+
7
+ from google.adk.tools import BaseTool, ToolContext
8
+
9
+ from skarn_guard.client import SkarnGuard, blocking_message, evaluate
10
+ from skarn_guard.envelope import GuardEvent, Kind, kind_for
11
+
12
+
13
+ def before_tool_callback(
14
+ guard: SkarnGuard, *, kind_for: Callable[[str], Kind] = kind_for
15
+ ) -> Callable[[BaseTool, dict[str, Any], ToolContext], Awaitable[dict[str, str] | None]]:
16
+ async def callback(tool: BaseTool, args: dict[str, Any], tool_context: ToolContext) -> dict[str, str] | None:
17
+ name = tool.name
18
+ event = GuardEvent.pre_tool(
19
+ name,
20
+ kind_for(name),
21
+ args,
22
+ runtime=guard.runtime_label("adk"),
23
+ identity=guard.identity,
24
+ )
25
+ verdict, blocked = await asyncio.to_thread(evaluate, guard, event)
26
+ if blocked:
27
+ return {"error": blocking_message(verdict)}
28
+ return None
29
+
30
+ return callback