Metadata-Version: 2.4
Name: skarn-guard
Version: 0.37.0
Summary: Runs the Skarn guard inside Python agent runtimes and gateways
License-Expression: MIT
License-File: LICENSE
Requires-Python: >=3.11
Provides-Extra: adk
Requires-Dist: google-adk==2.14.0; extra == 'adk'
Provides-Extra: langchain
Requires-Dist: langchain==1.4.10; extra == 'langchain'
Provides-Extra: litellm
Requires-Dist: litellm==1.109.1; extra == 'litellm'
Provides-Extra: mcp
Requires-Dist: mcp==2.3.0; extra == 'mcp'
Provides-Extra: openai-agents
Requires-Dist: openai-agents==0.24.0; extra == 'openai-agents'
Provides-Extra: strands
Requires-Dist: strands-agents==1.65.0; extra == 'strands'
Description-Content-Type: text/markdown

# skarn-guard

`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.

## Install

```shell
brew install skarn-security/tap/skarn
pip install "skarn-guard[langchain]"
```

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.

## Configuration

```python
from skarn_guard import SkarnGuard

guard = SkarnGuard(mode="enforce")
```

| Argument | Default | Meaning |
|---|---|---|
| `binary` | `$SKARN_BIN`, then `skarn` on `PATH` | The `skarn` binary. If neither exists, the constructor raises `BinaryNotFound` with the install command. |
| `mode` | `"audit"` | `--guard-mode` for the binary: `audit` or `enforce`. |
| `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. |
| `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. |
| `timeout` | `5.0` | Seconds the binary gets per call. |
| `log` | `$SKARN_GUARD_LOG`, else `~/.cache/skarn/guard-sdk-audit.jsonl` | The guard log the binary appends to. `False` passes `--log none`. |
| `runtime` | the adapter's name | The `runtime` label in the envelope and the log. |
| `identity` | `None` | An identity label for the log. The guard does not authenticate it. |

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`.

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.

| Tool name | Kind |
|---|---|
| `bash`, `shell`, `run_command`, `terminal` | `shell` |
| `write_file`, `create_file` | `write` |
| `edit_file`, `apply_patch` | `edit` |
| `read_file` | `read` |
| `fetch`, `http_get`, `web_fetch` | `fetch` |

## The envelope

The adapters build this object for you. A runtime with no adapter can build it with `skarn_guard.GuardEvent` and call `guard.check(event)`.

```python
from skarn_guard import GuardEvent, SkarnGuard

event = GuardEvent.pre_tool("run_command", "shell", {"command": "ls -la"}, runtime="my-runtime")
verdict = SkarnGuard().check(event)
print(verdict.verdict, verdict.enforce, verdict.rule)
```

`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.

## The blocking rule

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.

In the examples below, `model` is your own model object and `run_command` is one of your own tools.

## `skarn_guard.langchain`

Middleware for a LangChain agent built with `create_agent`.

```python
from langchain.agents import create_agent

from skarn_guard import SkarnGuard
from skarn_guard.langchain import SkarnGuardMiddleware

agent = create_agent(
    model,
    tools=[run_command],
    middleware=[SkarnGuardMiddleware(SkarnGuard(mode="enforce"))],
)
```

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.

## `skarn_guard.openai_agents`

Tool guardrails for the OpenAI Agents SDK.

```python
from agents import function_tool

from skarn_guard import SkarnGuard
from skarn_guard.openai_agents import skarn_tool_input_guardrail, skarn_tool_output_guardrail

guard = SkarnGuard(mode="enforce")


@function_tool(
    tool_input_guardrails=[skarn_tool_input_guardrail(guard)],
    tool_output_guardrails=[skarn_tool_output_guardrail(guard)],
)
def lookup(q: str) -> str:
    """Look up an order."""
    return q
```

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.

## `skarn_guard.strands`

A plugin for a Strands Agents agent.

```python
from strands import Agent

from skarn_guard import SkarnGuard
from skarn_guard.strands import SkarnGuardPlugin

agent = Agent(model=model, tools=[run_command], plugins=[SkarnGuardPlugin(SkarnGuard(mode="enforce"))])
result = agent("rotate the logs")
while result.stop_reason == "interrupt":
    result = agent(
        [{"interruptResponse": {"interruptId": interrupt.id, "response": "reject"}} for interrupt in result.interrupts]
    )
```

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.

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.

## `skarn_guard.adk`

A `before_tool_callback` for a Google Agent Development Kit (ADK) agent.

```python
from google.adk.agents import LlmAgent

from skarn_guard import SkarnGuard
from skarn_guard.adk import before_tool_callback

agent = LlmAgent(
    name="ops",
    model="gemini-2.5-flash",
    tools=[run_command],
    before_tool_callback=before_tool_callback(SkarnGuard(mode="enforce")),
)
```

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.

## `skarn_guard.mcp`

Server middleware for the MCP Python SDK.

```python
from mcp.server.mcpserver import MCPServer

from skarn_guard import SkarnGuard
from skarn_guard.mcp import skarn_middleware

server = MCPServer("orders", middleware=[skarn_middleware(SkarnGuard(mode="enforce"), "orders")])


@server.tool()
def lookup(q: str) -> str:
    return q
```

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.

## `skarn_guard.agentcore`

A REQUEST interceptor for an Amazon Bedrock AgentCore Gateway with MCP targets.

```python
from skarn_guard import SkarnGuard
from skarn_guard.agentcore import make_handler

handler = make_handler(SkarnGuard(mode="enforce"), server="orders")
```

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.

## `skarn_guard.litellm`

A guardrail for the LiteLLM proxy.

```python
from skarn_guard.litellm import SkarnGuardrail
```

```yaml
guardrails:
  - guardrail_name: skarn
    litellm_params:
      guardrail: skarn_guard.litellm.SkarnGuardrail
      mode: [pre_call, post_call]
      default_on: true
      skarn_mode: enforce
      streaming_buffer_until_moderated: true
```

`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.

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.

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.

## Runtimes with their own hook

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.

## Without a license

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.

## What it never does

- It reads no license, no rules file and no session store, and it runs no detector of its own.
- It opens no socket. The binary reads stdin and writes stdout.
- It never changes a tool input, a request or a tool result, and it composes no text from them.
- 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.

## Support matrix

| Runtime | Package and version | Deny | Ask | Tested on |
|---|---|---|---|---|
| LangChain | `langchain` 1.4.10 | `ToolMessage` with `status="error"` | `on_ask`, else blocked | 2026-11-15, Python 3.11 and 3.13 |
| OpenAI Agents SDK | `openai-agents` 0.24.0 | `reject_content` | blocked | 2026-11-15, Python 3.11 and 3.13 |
| 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 |
| Google ADK | `google-adk` 2.14.0 | `{"error": ...}` | blocked | 2026-11-15, Python 3.11 and 3.13 |
| MCP Python SDK | `mcp` 2.3.0 | `CallToolResult(is_error=True)` | blocked | 2026-11-15, Python 3.11 and 3.13 |
| AgentCore Gateway | REQUEST interceptor, version 1.0 | `transformedGatewayResponse` | blocked | 2026-11-15, Python 3.11 and 3.13 |
| LiteLLM | `litellm` 1.109.1 | `GuardrailRaisedException` (HTTP 400) | blocked | 2026-11-15, Python 3.11 and 3.13 |

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.

## License

MIT, see `LICENSE`.
