Repository navigation
Add guarded tool integrations for fifteen maintained Python frameworks #72
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| 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 | ||
| 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. |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| """Optional agent-framework tools. SDKs are imported only by their factories.""" |
| 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)) |
| 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)) |
| 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() | ||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🛑 Crash Risk: In
Suggested change
|
||||||
| raise asyncio.CancelledError | ||||||
| return task.result() | ||||||
|
|
||||||
| return guarded_call | ||||||
| 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)) |
| 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 |
| 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 |
| 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"] |
| 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)) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛑 Security Vulnerability: The
matrix.frameworkvalue 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 ofscripts/test_integration.py --list, which itself reads frompyproject.toml. If a malicious commit introduces an extra key containing a single-quote inpyproject.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.