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
50 changes: 50 additions & 0 deletions .github/workflows/integrations.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
name: Framework integrations
on: [push, pull_request, workflow_dispatch]
permissions:
contents: read
jobs:
native:
runs-on: ubuntu-latest
timeout-minutes: 30
outputs:
frameworks: ${{ steps.matrix.outputs.frameworks }}
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: '3.12'
- id: matrix
run: echo "frameworks=$(python scripts/test_integration.py --list)" >> "$GITHUB_OUTPUT"
- name: Install pinned Lean toolchain
run: |
curl -sSf https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh | sh -s -- -y --default-toolchain none
echo "$HOME/.elan/bin" >> "$GITHUB_PATH"
- run: lake update
- run: lake exe cache get
- run: lake build leanguard
- uses: actions/upload-artifact@v4
with:
name: integration-engine
path: .lake/build/bin/leanguard
retention-days: 2
sdk:
needs: native
runs-on: ubuntu-latest
timeout-minutes: 15
strategy:
fail-fast: false
matrix:
framework: ${{ fromJSON(needs.native.outputs.frameworks) }}
env:
LEANGUARD_BINARY: ${{ github.workspace }}/.native/leanguard
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: '3.12'
- uses: actions/download-artifact@v4
with:
name: integration-engine
path: .native
- run: chmod +x .native/leanguard
- run: python scripts/test_integration.py '${{ matrix.framework }}' --install

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛑 Security Vulnerability: The matrix.framework value is interpolated directly into a shell command via single-quote wrapping ('${{ matrix.framework }}'). While single quotes prevent most shell injection, the framework value is sourced from the JSON output of scripts/test_integration.py --list, which itself reads from pyproject.toml. If a malicious commit introduces an extra key containing a single-quote in pyproject.toml (e.g., agent-foo'), the single-quote boundary is broken and arbitrary shell commands can be injected. Use the environment variable indirection pattern instead to fully eliminate injection risk.

Suggested change
- run: python scripts/test_integration.py '${{ matrix.framework }}' --install
- run: python scripts/test_integration.py "$FRAMEWORK" --install
env:
FRAMEWORK: ${{ matrix.framework }}

114 changes: 114 additions & 0 deletions docs/python-integrations.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
# Python framework tools

LeanGuard supplies a `guarded_tool(host)` factory in each optional
`leanguard.integrations.<framework>` module. Each factory registers one
`guarded_call` tool with `action`, `arguments`, and optional `proposal_id` inputs.
It delegates the full operation to the host's existing backend adapter; it does
not wrap arbitrary framework tools or infer backend facts from their output.

```sh
pip install 'leanguard[agent-strands]'
```

```python
from pathlib import Path
from leanguard import GuardHost
from leanguard.demo import MemoryTools
from leanguard.integrations.strands import guarded_tool
from strands import Agent

with GuardHost("example", Path("private/events.sqlite"), MemoryTools(),
principal="alice", session="conversation-1") as host:
agent = Agent(tools=[guarded_tool(host)])
# Configure your model/provider before invoking the agent.
# Keep the host open until the agent and all tool work have finished.
```

Replace `MemoryTools` with an authoritative backend adapter in production. Its
lock must coordinate every writer. Never register the underlying raw tools or
give the agent another credential/path to the same backend.

| Module / extra suffix | SDK registration type | Invocation coverage |
| --- | --- | --- |
| `strands` | decorated Strands tool | async tool stream |
| `langchain` | `StructuredTool` | sync/async tool; LangGraph `ToolNode` |
| `deepagents` | same LangChain tool | Deep Agents graph with deterministic model |
| `openai` | `FunctionTool` | function invocation; hosted tools excluded |
| `adk` | `FunctionTool` | async invocation |
| `microsoft` | `FunctionTool` | Python invocation; .NET not included |
| `crewai` | CrewAI tool | synchronous invocation, cache disabled |
| `llamaindex` | `FunctionTool` | call/acall |
| `pydantic` | `Tool` | toolset execution, no framework retry allowance |
| `agno` | `Function` | async `FunctionCall` |
| `haystack` | `Tool` | invoke/invoke_async on Haystack 3 |
| `smolagents` | `Tool` | synchronous tool invocation |
| `dspy` | `Tool` | async tool invocation |
| `camel` | `FunctionTool` | async tool invocation |
| `claude` | SDK MCP tool | in-process MCP request/response |

Install `agent-<suffix>` and import the corresponding module. All SDK imports
are lazy, so the core package remains dependency-free. Exact tested versions
live in `pyproject.toml`; they deliberately describe a narrow support set.
Use isolated environments when frameworks have incompatible dependencies.
In particular, CAMEL's current stable release needs MCP 1.x and cannot share an
environment with LeanGuard's MCP 2.x server extra; its native tool integration
does not need that server. Do not force conflicting dependency versions.

Claude Agent SDK uses `create_sdk_mcp_server("leanguard", tools=[guarded_tool(host)])`
and `ClaudeAgentOptions(mcp_servers={"leanguard": server},
allowed_tools=["mcp__leanguard__guarded_call"])`. Its built-in tools and permission
modes remain separate controls; the approval authority is still the host UI.

## Authority and outcomes

Only trusted application code owns the host. Approval uses `host.prepare`, an
authenticated human review of the exact proposal details, and `host.confirm`.
The model may pass an existing proposal ID; that reference does not grant approval.
Framework approval flags, context objects, and tool output do not create trusted
identity or confirmations. A changed or consumed proposal remains denied.

The model sees denial/status/request correlation and successful backend results.
Detailed rules, evidence, and exception text stay in the trusted journal. An
allowed call can have an `unknown` outcome: it might have taken effect. These
factories never retry it. Configure surrounding SDK retry/caching middleware so
it cannot bypass the host or turn an uncertain result into a successful one.

Host exceptions become a generic `GuardedCallError` because SDKs may place their
text in model-visible tool messages. It does not claim denial or absence of
effects; trusted Python callers can inspect its original exception context.
The MCP server uses this same result/error boundary, including removal of the
private `error` field from recorded failure/unknown results. Do not depend on
that diagnostic field in model-facing code.

Async factories run the complete synchronous host transaction on one worker
thread. Cancellation waits for that work to settle before propagating. It does
not interrupt the backend, undo effects, or provide a timeout guarantee. Give
backend operations bounded timeouts and keep the host alive until completion.
Async-only backend adapters are not supported by the synchronous host contract.

These tools cover the operations reached through this single registration.
SDK built-ins, dynamic tools added by other code, shell/browser access, unrestricted
code execution, and subagents are not automatically covered. Deep Agents'
filesystem/shell tools and smolagents' CodeAgent particularly require separate
restrictions. Multi-agent authority must use an explicitly bound
`MultiAgentHost` agent, not model-selected identities.

## Reproducing and extending validation

Build the native engine and create a fresh Python 3.12 environment, then run:

```sh
python scripts/test_integration.py strands --install
```

The isolated CI matrix uses the same command and the native engine from the same
commit. Missing required SDKs fail the job instead of silently skipping tests.
Tests drive actual SDK tool entry points with deterministic requests and inspect
backend effects. They cover denials, successful approved calls, changed and reused
approvals, and unknown outcomes. Shared host tests cover journal and snapshot
contracts; the async boundary additionally tests repeated cancellation.

Upgrade one SDK pin at a time, review its public invocation/schema changes, and
run its conformance job plus the repository gate. Expand mode/version claims only
with corresponding tests. No live model calls or provider credentials are needed
for these checks.
16 changes: 16 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,22 @@ classifiers = ["Operating System :: POSIX :: Linux", "Programming Language :: Py
Repository = "https://github.com/DebarghaG/LeanGuard"

[project.optional-dependencies]
agent-claude = ["claude-agent-sdk==0.2.182"]
# Exact SDK versions validated by the isolated integration matrix.
agent-strands = ["strands-agents==1.65.0"]
agent-langchain = ["langchain==1.5.0", "langchain-core==1.8.1", "langgraph==1.2.22"]
agent-deepagents = ["deepagents==0.7.38", "langchain==1.5.0", "langchain-core==1.8.1", "langgraph==1.2.22"]
agent-openai = ["openai-agents==0.24.0"]
agent-adk = ["google-adk==2.14.1"]
agent-microsoft = ["agent-framework-core==1.26.0"]
agent-crewai = ["crewai==1.15.41"]
agent-llamaindex = ["llama-index-core==0.14.26"]
agent-pydantic = ["pydantic-ai-slim==2.68.0"]
agent-agno = ["agno==3.2.0"]
agent-haystack = ["haystack-ai==3.5.0"]
agent-smolagents = ["smolagents==1.26.0"]
agent-dspy = ["dspy==3.5.0"]
agent-camel = ["camel-ai==0.2.90", "mcp==1.30.0"]
test = ["pytest>=8", "pytest-asyncio>=0.24", "ruff>=0.12"]
release = ["build>=1.2", "twine>=6", "auditwheel>=6; sys_platform == 'linux'", "patchelf>=0.17; sys_platform == 'linux'"]
mcp = ["mcp==2.2.0"]
Expand Down
1 change: 1 addition & 0 deletions python/leanguard/integrations/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"""Optional agent-framework tools. SDKs are imported only by their factories."""
10 changes: 10 additions & 0 deletions python/leanguard/integrations/adk.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
"""Google ADK tools backed by the trusted host."""

from .call import bind_async_guarded_call


def guarded_tool(host):
"""Create an ADK FunctionTool; approvals stay in trusted host code."""
from google.adk.tools import FunctionTool

return FunctionTool(bind_async_guarded_call(host))
10 changes: 10 additions & 0 deletions python/leanguard/integrations/agno.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
"""Agno function tools backed by LeanGuard."""

from .call import bind_async_guarded_call


def guarded_tool(host):
"""Create an asynchronous Function; do not enable SDK result caching."""
from agno.tools.function import Function

return Function.from_callable(bind_async_guarded_call(host))
102 changes: 102 additions & 0 deletions python/leanguard/integrations/call.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
"""The model-facing entry point shared by framework tools."""

import asyncio
from collections.abc import Callable
from typing import Any


class GuardedCallError(RuntimeError):
"""Model-safe failure; it does not establish whether a dispatch occurred."""


FAILURE_MESSAGE = (
"Guarded call failed; its outcome may be unknown. Ask the operator; do not retry automatically."
)


def bind_guarded_call(host) -> Callable:
"""Bind a tool to a trusted host (or a bound MultiAgentHost agent).

Keep the host alive until every invocation has completed. Only the returned
callable belongs in the agent's tool registry; the host remains trusted.
"""

def guarded_call(
action: str, arguments: dict[str, Any], proposal_id: str | None = None
) -> dict[str, Any]:
"""Execute a backend tool subject to the compiled policy.

Args:
action: Backend action name.
arguments: Exact arguments for the backend action.
proposal_id: Reference to a prior human approval, if available.

Returns:
Admission status, request ID, and recorded outcome. Unknown outcomes
require reconciliation; do not retry them automatically.
"""
if not isinstance(action, str) or not isinstance(arguments, dict):
raise TypeError("action must be a string and arguments must be an object")
if proposal_id is not None and not isinstance(proposal_id, str):
raise TypeError("proposal_id must be a string or null")
try:
result = host.execute(action, arguments, proposal_id=proposal_id)
except Exception: # noqa: BLE001 -- SDK error messages must not expose trusted diagnostics.
# SDKs commonly turn exception strings into tool messages. The
# original context remains available to trusted Python callers.
raise GuardedCallError(FAILURE_MESSAGE) from None
if not result["allow"]:
return {
"allow": False,
"request_id": result["request_id"],
"message": "Tool call denied by policy.",
}
# Detailed diagnostics and exception text belong in the trusted journal.
return {
key: value
for key, value in result.items()
if key not in {"reasons", "errors", "evidence", "error"}
}

return guarded_call


def bind_async_guarded_call(host) -> Callable:
"""Bind asynchronous SDK entry points to the complete synchronous transaction."""
execute = bind_guarded_call(host)

async def guarded_call(
action: str, arguments: dict[str, Any], proposal_id: str | None = None
) -> dict[str, Any]:
"""Execute a backend tool subject to the compiled policy.

Args:
action: Backend action name.
arguments: Exact arguments for the backend action.
proposal_id: Reference to a prior human approval, if available.

Returns:
Admission status, request ID, and recorded outcome. Unknown outcomes
require reconciliation; do not retry them automatically.
"""
task = asyncio.create_task(asyncio.to_thread(execute, action, arguments, proposal_id))
cancelled = False
while not task.done():
try:
await asyncio.shield(task)
except asyncio.CancelledError:
# Cancellation cannot stop a synchronous backend. Drain its
# journal transaction before releasing the owning host.
cancelled = True
except Exception:
if not cancelled:
raise
break
if cancelled:
# Retrieve any exception so the completed worker is never orphaned.
if not task.cancelled():
task.exception()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛑 Crash Risk: In bind_async_guarded_call, when the task completes normally (no cancellation), task.result() on line 86 re-raises any exception the task raised. However, the loop on lines 70–80 already breaks out when an exception is caught during the cancelled=True state. For the non-cancelled path, if asyncio.shield(task) raises a non-CancelledError exception (i.e., the backend task itself raised), the loop exits via the raise on line 79, but task.result() is never called — so the exception is raised directly. This is correct. The problem is line 84: task.exception() is called but its return value is discarded. The comment says "so the completed worker is never orphaned", but the actual purpose is to suppress the "exception was never retrieved" asyncio warning. The discarded return value is intentional but non-obvious; a reviewer or future maintainer may flag it as dead code and remove it. This should at minimum have an explicit discard _ = task.exception() or use task.exception() # retrieve to suppress asyncio warning to make it clear.

Suggested change
task.exception()
_ = task.exception() # retrieve to suppress asyncio "exception never retrieved" warning

raise asyncio.CancelledError
return task.result()

return guarded_call
10 changes: 10 additions & 0 deletions python/leanguard/integrations/camel.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
"""CAMEL FunctionTool registration backed by LeanGuard."""

from .call import bind_async_guarded_call


def guarded_tool(host):
"""Create an asynchronous tool; unrestricted code tools remain excluded."""
from camel.toolkits import FunctionTool

return FunctionTool(bind_async_guarded_call(host))
31 changes: 31 additions & 0 deletions python/leanguard/integrations/claude.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
"""In-process MCP tools for Claude Agent SDK."""

from ..engine import canonical
from .call import bind_async_guarded_call


def guarded_tool(host):
"""Create an SDK MCP tool; expose only this tool in allowed_tools."""
from claude_agent_sdk import tool

execute = bind_async_guarded_call(host)

@tool(
"guarded_call",
"Execute a backend action through LeanGuard. Approval is supplied by trusted human UI.",
{
"type": "object",
"properties": {
"action": {"type": "string"},
"arguments": {"type": "object"},
"proposal_id": {"type": ["string", "null"]},
},
"required": ["action", "arguments"],
"additionalProperties": False,
},
)
async def guarded_call(arguments):
result = await execute(**arguments)
return {"content": [{"type": "text", "text": canonical(result)}]}

return guarded_call
12 changes: 12 additions & 0 deletions python/leanguard/integrations/crewai.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
"""CrewAI tools backed by LeanGuard."""

from .call import bind_guarded_call


def guarded_tool(host):
"""Create a synchronous CrewAI tool without result caching."""
from crewai.tools import tool

result = tool(bind_guarded_call(host))
result.cache_function = lambda arguments, result: False
return result
9 changes: 9 additions & 0 deletions python/leanguard/integrations/deepagents.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
"""Reuse LangChain's guarded tool in Deep Agents.

Coverage is limited to this registered tool. Built-in shell, filesystem, browser,
and subagent tools require their own deployment restrictions.
"""

from .langchain import guarded_tool

__all__ = ["guarded_tool"]
10 changes: 10 additions & 0 deletions python/leanguard/integrations/dspy.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
"""DSPy ReAct tools backed by LeanGuard."""

from .call import bind_async_guarded_call


def guarded_tool(host):
"""Create an asynchronous DSPy Tool; optimization cannot change policy."""
from dspy import Tool

return Tool(bind_async_guarded_call(host))
Loading
Loading