diff --git a/.github/workflows/integrations.yml b/.github/workflows/integrations.yml new file mode 100644 index 0000000..f4e4687 --- /dev/null +++ b/.github/workflows/integrations.yml @@ -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 diff --git a/docs/python-integrations.md b/docs/python-integrations.md new file mode 100644 index 0000000..b5ed99a --- /dev/null +++ b/docs/python-integrations.md @@ -0,0 +1,114 @@ +# Python framework tools + +LeanGuard supplies a `guarded_tool(host)` factory in each optional +`leanguard.integrations.` 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-` 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. diff --git a/pyproject.toml b/pyproject.toml index 9f1f68f..ebc0536 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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"] diff --git a/python/leanguard/integrations/__init__.py b/python/leanguard/integrations/__init__.py new file mode 100644 index 0000000..2d02da9 --- /dev/null +++ b/python/leanguard/integrations/__init__.py @@ -0,0 +1 @@ +"""Optional agent-framework tools. SDKs are imported only by their factories.""" diff --git a/python/leanguard/integrations/adk.py b/python/leanguard/integrations/adk.py new file mode 100644 index 0000000..9069964 --- /dev/null +++ b/python/leanguard/integrations/adk.py @@ -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)) diff --git a/python/leanguard/integrations/agno.py b/python/leanguard/integrations/agno.py new file mode 100644 index 0000000..e33c79b --- /dev/null +++ b/python/leanguard/integrations/agno.py @@ -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)) diff --git a/python/leanguard/integrations/call.py b/python/leanguard/integrations/call.py new file mode 100644 index 0000000..887b14f --- /dev/null +++ b/python/leanguard/integrations/call.py @@ -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() + raise asyncio.CancelledError + return task.result() + + return guarded_call diff --git a/python/leanguard/integrations/camel.py b/python/leanguard/integrations/camel.py new file mode 100644 index 0000000..6c1b767 --- /dev/null +++ b/python/leanguard/integrations/camel.py @@ -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)) diff --git a/python/leanguard/integrations/claude.py b/python/leanguard/integrations/claude.py new file mode 100644 index 0000000..673d072 --- /dev/null +++ b/python/leanguard/integrations/claude.py @@ -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 diff --git a/python/leanguard/integrations/crewai.py b/python/leanguard/integrations/crewai.py new file mode 100644 index 0000000..28fae20 --- /dev/null +++ b/python/leanguard/integrations/crewai.py @@ -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 diff --git a/python/leanguard/integrations/deepagents.py b/python/leanguard/integrations/deepagents.py new file mode 100644 index 0000000..a59db2b --- /dev/null +++ b/python/leanguard/integrations/deepagents.py @@ -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"] diff --git a/python/leanguard/integrations/dspy.py b/python/leanguard/integrations/dspy.py new file mode 100644 index 0000000..0210249 --- /dev/null +++ b/python/leanguard/integrations/dspy.py @@ -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)) diff --git a/python/leanguard/integrations/haystack.py b/python/leanguard/integrations/haystack.py new file mode 100644 index 0000000..a6a8e26 --- /dev/null +++ b/python/leanguard/integrations/haystack.py @@ -0,0 +1,12 @@ +"""Haystack Agent tools (including Haystack 3's invocation API).""" + +from .call import bind_async_guarded_call, bind_guarded_call + + +def guarded_tool(host): + """Create a Tool with both host-owned invocation modes.""" + from haystack.tools import tool + + result = tool(bind_guarded_call(host)) + result.async_function = bind_async_guarded_call(host) + return result diff --git a/python/leanguard/integrations/langchain.py b/python/leanguard/integrations/langchain.py new file mode 100644 index 0000000..dff88a5 --- /dev/null +++ b/python/leanguard/integrations/langchain.py @@ -0,0 +1,12 @@ +"""Guarded tools for LangChain agents and LangGraph ToolNode.""" + +from .call import bind_async_guarded_call, bind_guarded_call + + +def guarded_tool(host): + """Create a StructuredTool supporting both invoke and ainvoke.""" + from langchain_core.tools import StructuredTool + + return StructuredTool.from_function( + func=bind_guarded_call(host), coroutine=bind_async_guarded_call(host) + ) diff --git a/python/leanguard/integrations/llamaindex.py b/python/leanguard/integrations/llamaindex.py new file mode 100644 index 0000000..32e2b8e --- /dev/null +++ b/python/leanguard/integrations/llamaindex.py @@ -0,0 +1,12 @@ +"""LlamaIndex function tools with synchronous and asynchronous entry points.""" + +from .call import bind_async_guarded_call, bind_guarded_call + + +def guarded_tool(host): + """Create a FunctionTool; keep raw backend functions out of the agent.""" + from llama_index.core.tools import FunctionTool + + return FunctionTool.from_defaults( + fn=bind_guarded_call(host), async_fn=bind_async_guarded_call(host) + ) diff --git a/python/leanguard/integrations/microsoft.py b/python/leanguard/integrations/microsoft.py new file mode 100644 index 0000000..3e33174 --- /dev/null +++ b/python/leanguard/integrations/microsoft.py @@ -0,0 +1,10 @@ +"""Microsoft Agent Framework function tools.""" + +from .call import bind_async_guarded_call + + +def guarded_tool(host): + """Create a Python function tool with host-owned execution.""" + from agent_framework import tool + + return tool(bind_async_guarded_call(host)) diff --git a/python/leanguard/integrations/openai.py b/python/leanguard/integrations/openai.py new file mode 100644 index 0000000..7b67228 --- /dev/null +++ b/python/leanguard/integrations/openai.py @@ -0,0 +1,14 @@ +"""OpenAI function tools; provider-hosted tools are outside this boundary.""" + +from .call import bind_async_guarded_call + + +def guarded_tool(host): + """Create a FunctionTool whose execution is owned by LeanGuard.""" + from agents import function_tool + + # Backend argument objects are intentionally open; their policy schemas are + # enforced by the compiled pack, not OpenAI's restricted strict-schema form. + return function_tool( + bind_async_guarded_call(host), strict_mode=False, failure_error_function=None + ) diff --git a/python/leanguard/integrations/pydantic.py b/python/leanguard/integrations/pydantic.py new file mode 100644 index 0000000..8c393fe --- /dev/null +++ b/python/leanguard/integrations/pydantic.py @@ -0,0 +1,10 @@ +"""PydanticAI function tools backed by LeanGuard.""" + +from .call import bind_async_guarded_call + + +def guarded_tool(host): + """Create a Tool with no framework retries or implicit approval authority.""" + from pydantic_ai import Tool + + return Tool(bind_async_guarded_call(host), takes_ctx=False, max_retries=0) diff --git a/python/leanguard/integrations/smolagents.py b/python/leanguard/integrations/smolagents.py new file mode 100644 index 0000000..70c6083 --- /dev/null +++ b/python/leanguard/integrations/smolagents.py @@ -0,0 +1,10 @@ +"""smolagents tools; unrestricted CodeAgent execution is not covered.""" + +from .call import bind_guarded_call + + +def guarded_tool(host): + """Create a Tool suitable for a constrained ToolCallingAgent.""" + from smolagents import tool + + return tool(bind_guarded_call(host)) diff --git a/python/leanguard/integrations/strands.py b/python/leanguard/integrations/strands.py new file mode 100644 index 0000000..f4f4c0a --- /dev/null +++ b/python/leanguard/integrations/strands.py @@ -0,0 +1,10 @@ +"""Strands tool registration backed by LeanGuard-owned execution.""" + +from .call import bind_async_guarded_call + + +def guarded_tool(host): + """Register the returned tool with Strands instead of the raw backend tools.""" + from strands import tool + + return tool(bind_async_guarded_call(host)) diff --git a/python/leanguard/mcp_server.py b/python/leanguard/mcp_server.py index fa914d5..24d9af0 100644 --- a/python/leanguard/mcp_server.py +++ b/python/leanguard/mcp_server.py @@ -6,9 +6,12 @@ from mcp.server.mcpserver import MCPServer +from .integrations.call import FAILURE_MESSAGE, GuardedCallError, bind_guarded_call + def build_server(host, approval=None): server = MCPServer("LeanGuard") + execute = bind_guarded_call(host) @server.tool(structured_output=True) def policy_manifest() -> dict[str, Any]: @@ -29,21 +32,13 @@ def guarded_call( `proposal_id` points to an approval the user already gave. Passing one does not grant approval. """ - if approval is not None and proposal_id is None and host.adapter.mutating(action): - proposal = host.prepare(action, arguments) - host.confirm(proposal.id, approval(proposal)) - proposal_id = proposal.id - result = host.execute(action, arguments, proposal_id=proposal_id) - if not result["allow"]: - return { - "allow": False, - "request_id": result["request_id"], - "message": "Tool call denied by policy.", - } - return { - key: value - for key, value in result.items() - if key not in {"reasons", "errors", "evidence"} - } + try: + if approval is not None and proposal_id is None and host.adapter.mutating(action): + proposal = host.prepare(action, arguments) + host.confirm(proposal.id, approval(proposal)) + proposal_id = proposal.id + except Exception: # noqa: BLE001 -- SDK error messages must not expose trusted diagnostics. + raise GuardedCallError(FAILURE_MESSAGE) from None + return execute(action, arguments, proposal_id) return server diff --git a/scripts/test_integration.py b/scripts/test_integration.py new file mode 100644 index 0000000..fe53e76 --- /dev/null +++ b/scripts/test_integration.py @@ -0,0 +1,67 @@ +"""Install one optional SDK environment and run its mandatory native conformance test.""" + +import argparse +import json +import os +import subprocess +import sys +import tomllib +from pathlib import Path + + +def main(): + root = Path(__file__).resolve().parents[1] + with (root / "pyproject.toml").open("rb") as source: + extras = tomllib.load(source)["project"]["optional-dependencies"] + integrations = { + key.removeprefix("agent-"): value + for key, value in extras.items() + if key.startswith("agent-") + } + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("framework", nargs="?", choices=sorted(integrations)) + parser.add_argument("--list", action="store_true") + parser.add_argument("--install", action="store_true") + args = parser.parse_args() + if args.list: + print(json.dumps(sorted(integrations))) + return + if not args.framework: + parser.error("framework is required without --list") + if args.install: + subprocess.run( + [ + sys.executable, + "-m", + "pip", + "install", + *extras["test"], + *integrations[args.framework], + ], + check=True, + ) + env = { + **os.environ, + "PYTHONPATH": str(root / "python"), + "LEANGUARD_REQUIRE_SDK": args.framework, + "HAYSTACK_TELEMETRY_ENABLED": "false", + "CREWAI_TELEMETRY_ENABLED": "false", + } + subprocess.run( + [ + sys.executable, + "-m", + "pytest", + "-q", + "tests/integrations/test_python_sdks.py", + "-k", + f"{args.framework}-", + ], + cwd=root, + env=env, + check=True, + ) + + +if __name__ == "__main__": + main() diff --git a/tests/integrations/test_python_sdks.py b/tests/integrations/test_python_sdks.py new file mode 100644 index 0000000..ca738a8 --- /dev/null +++ b/tests/integrations/test_python_sdks.py @@ -0,0 +1,219 @@ +"""Invoke real SDK tools; each integration runs in an isolated dependency job.""" + +import importlib +import json +import os + +import pytest +from leanguard import GuardHost +from leanguard.demo import MemoryTools + + +async def invoke(framework, host, arguments): + module = importlib.import_module(f"leanguard.integrations.{framework}") + tool = module.guarded_tool(host) + if framework == "strands": + events = [ + event + async for event in tool.stream( + {"toolUseId": "call-1", "name": "guarded_call", "input": arguments}, {} + ) + ] + return json.loads(events[-1]["tool_result"]["content"][0]["text"]) + if framework == "langchain": + from langchain_core.messages import AIMessage + from langgraph.graph import END, START, MessagesState, StateGraph + from langgraph.prebuilt import ToolNode + + graph = StateGraph(MessagesState) + graph.add_node("tools", ToolNode([tool])) + graph.add_edge(START, "tools") + graph.add_edge("tools", END) + result = await graph.compile().ainvoke( + { + "messages": [ + AIMessage( + content="", + tool_calls=[ + { + "name": tool.name, + "args": arguments, + "id": "call-1", + "type": "tool_call", + } + ], + ) + ] + } + ) + return json.loads(result["messages"][-1].content) + if framework == "deepagents": + from deepagents import create_deep_agent + from langchain_core.language_models.fake_chat_models import FakeMessagesListChatModel + from langchain_core.messages import AIMessage, ToolMessage + + class ToolModel(FakeMessagesListChatModel): + def bind_tools(self, tools, **kwargs): + return self + + model = ToolModel( + responses=[ + AIMessage( + content="", + tool_calls=[ + {"name": tool.name, "args": arguments, "id": "call-1", "type": "tool_call"} + ], + ), + AIMessage(content="Done"), + ] + ) + agent = create_deep_agent(model=model, tools=[tool]) + result = await agent.ainvoke({"messages": [{"role": "user", "content": "Run the tool"}]}) + response = next(m for m in result["messages"] if isinstance(m, ToolMessage)) + return json.loads(response.content) + if framework == "openai": + from agents.tool_context import ToolContext + + encoded = json.dumps(arguments) + context = ToolContext( + context=None, tool_name=tool.name, tool_call_id="call-1", tool_arguments=encoded + ) + return await tool.on_invoke_tool(context, encoded) + if framework == "adk": + return await tool.run_async(args=arguments, tool_context=None) + if framework == "microsoft": + return await tool.invoke(arguments=arguments, skip_parsing=True) + if framework == "crewai": + return tool.run(**arguments) + if framework == "llamaindex": + return (await tool.acall(**arguments)).raw_output + if framework == "pydantic": + from pydantic_ai import RunContext + from pydantic_ai.models.test import TestModel + from pydantic_ai.toolsets import FunctionToolset + from pydantic_ai.usage import RunUsage + + context = RunContext(deps=None, model=TestModel(), usage=RunUsage()) + toolset = FunctionToolset([tool]) + registered = await toolset.get_tools(context) + return await toolset.call_tool( + "guarded_call", arguments, context, registered["guarded_call"] + ) + if framework == "agno": + from agno.tools.function import FunctionCall + + return (await FunctionCall(function=tool, arguments=arguments).aexecute()).result + if framework == "haystack": + return await tool.invoke_async(**arguments) + if framework == "smolagents": + return tool(**arguments) + if framework == "dspy": + return await tool.acall(**arguments) + if framework == "camel": + return await tool.async_call(**arguments) + if framework == "claude": + import anyio + from claude_agent_sdk import create_sdk_mcp_server + from mcp.client.session import ClientSession + from mcp.shared.memory import create_client_server_memory_streams + + server = create_sdk_mcp_server("leanguard", tools=[tool])["instance"] + async with ( + create_client_server_memory_streams() as (client_streams, server_streams), + anyio.create_task_group() as group, + ): + group.start_soon(server.run, *server_streams, server.create_initialization_options()) + async with ClientSession(*client_streams) as client: + await client.initialize() + response = await client.call_tool("guarded_call", arguments) + result = json.loads(response.content[0].text) + group.cancel_scope.cancel() + return result + raise AssertionError(f"missing invocation fixture for {framework}") + + +@pytest.mark.parametrize( + "framework,dependency", + [ + ("strands", "strands"), + ("langchain", "langgraph"), + ("deepagents", "deepagents"), + ("openai", "agents"), + ("adk", "google.adk"), + ("microsoft", "agent_framework"), + ("crewai", "crewai"), + ("llamaindex", "llama_index.core"), + ("pydantic", "pydantic_ai"), + ("agno", "agno"), + ("haystack", "haystack"), + ("smolagents", "smolagents"), + ("dspy", "dspy"), + ("camel", "camel"), + ("claude", "claude_agent_sdk"), + ], +) +async def test_native_tool(framework, dependency, tmp_path): + if os.environ.get("LEANGUARD_REQUIRE_SDK") == framework: + importlib.import_module(dependency) + else: + pytest.importorskip(dependency) + adapter = MemoryTools() + with GuardHost( + "example", tmp_path / "events.sqlite", adapter, principal="alice", session="sdk" + ) as host: + + async def call(action, arguments, proposal_id=None): + payload = {"action": action, "arguments": arguments} + if proposal_id: + payload["proposal_id"] = proposal_id + return await invoke(framework, host, payload) + + denied = await call("write", {"value": "bad"}) + assert not denied["allow"] + assert set(denied) == {"allow", "request_id", "message"} + assert adapter.calls == [] + assert (await call("read", {}))["outcome"] == "success" + proposal = host.prepare("write", {"value": "good"}) + host.confirm(proposal.id, True) + assert not (await call("write", {"value": "changed"}, proposal.id))["allow"] + assert (await call("write", {"value": "good"}, proposal.id))["outcome"] == "success" + assert not (await call("write", {"value": "good"}, proposal.id))["allow"] + assert adapter.value == "good" + assert len(adapter.calls) == 2 + + def fail(action, arguments): + raise RuntimeError("private backend diagnostic") + + adapter.execute = fail + unknown = await call("read", {}) + assert unknown["outcome"] == "unknown" + assert "error" not in unknown + + +@pytest.mark.parametrize( + "framework,dependency", + [ + ("langchain", "langgraph"), + ("llamaindex", "llama_index.core"), + ("haystack", "haystack"), + ], +) +def test_sync_tool(framework, dependency, tmp_path): + if os.environ.get("LEANGUARD_REQUIRE_SDK") == framework: + importlib.import_module(dependency) + else: + pytest.importorskip(dependency) + adapter = MemoryTools() + with GuardHost( + "example", tmp_path / "sync.sqlite", adapter, principal="alice", session="sync" + ) as host: + tool = importlib.import_module(f"leanguard.integrations.{framework}").guarded_tool(host) + payload = {"action": "write", "arguments": {"value": "bad"}} + if framework == "langchain": + result = tool.invoke(payload) + elif framework == "llamaindex": + result = tool.call(**payload).raw_output + else: + result = tool.invoke(**payload) + assert not result["allow"] + assert not adapter.calls diff --git a/tests/test_integration_call.py b/tests/test_integration_call.py new file mode 100644 index 0000000..a30dcaa --- /dev/null +++ b/tests/test_integration_call.py @@ -0,0 +1,103 @@ +import asyncio +import threading + +import pytest +from leanguard import GuardHost +from leanguard.demo import MemoryTools +from leanguard.integrations.call import GuardedCallError, bind_async_guarded_call, bind_guarded_call + + +@pytest.fixture +def host(tmp_path): + with GuardHost( + "example", tmp_path / "events.sqlite", MemoryTools(), principal="alice", session="one" + ) as host: + yield host + + +def test_model_boundary_and_bound_approval(host): + call = bind_guarded_call(host) + denied = call("write", {"value": "new"}) + assert not denied["allow"] + assert set(denied) == {"allow", "request_id", "message"} + assert not host.adapter.calls + assert call("read", {})["outcome"] == "success" + proposal = host.prepare("write", {"value": "new"}) + host.confirm(proposal.id, True) + assert not call("write", {"value": "different"}, proposal.id)["allow"] + assert call("write", {"value": "new"}, proposal.id)["outcome"] == "success" + assert not call("write", {"value": "new"}, proposal.id)["allow"] + assert host.adapter.value == "new" + + +@pytest.mark.parametrize("args", [(1, {}), ("read", []), ("read", {}, True)]) +def test_invalid_tool_arguments_do_not_dispatch(host, args): + with pytest.raises(TypeError): + bind_guarded_call(host)(*args) + assert not host.adapter.calls + + +async def test_async_cancellation_drains_the_host_transaction(host): + entered, finish = threading.Event(), threading.Event() + execute = host.adapter.execute + + def blocked(action, arguments): + entered.set() + assert finish.wait(5) + return execute(action, arguments) + + host.adapter.execute = blocked + task = asyncio.create_task(bind_async_guarded_call(host)("read", {})) + try: + assert await asyncio.to_thread(entered.wait, 5) + task.cancel() + await asyncio.sleep(0) + task.cancel() + await asyncio.sleep(0) + assert not task.done() + finally: + finish.set() + with pytest.raises(asyncio.CancelledError): + await task + assert host.events()[-1]["kind"] == "success" + assert len(host.adapter.calls) == 1 + + +async def test_unknown_outcome_is_preserved_without_leaking_exception(host): + def fail(action, arguments): + raise RuntimeError("private backend detail") + + host.adapter.execute = fail + result = await bind_async_guarded_call(host)("read", {}) + assert result["outcome"] == "unknown" + assert "error" not in result + assert "private" not in str(result) + assert host.events()[-1]["kind"] == "unknown" + + +def test_snapshot_failure_is_safe_for_sdk_error_messages(host): + def fail(*args): + raise RuntimeError("private snapshot credential") + + host.adapter.snapshot = fail + with pytest.raises(GuardedCallError, match="outcome may be unknown") as caught: + bind_guarded_call(host)("read", {}) + assert "private" not in str(caught.value) + assert str(caught.value.__context__) == "private snapshot credential" + assert host.adapter.calls == [] + + +def test_outcome_storage_failure_never_becomes_a_denial(host): + record = host._record + + def fail_outcome(command): + if command["op"] == "observe": + raise RuntimeError("private storage diagnostic") + return record(command) + + host._record = fail_outcome + with pytest.raises(GuardedCallError, match="do not retry") as caught: + bind_guarded_call(host)("read", {}) + assert "private" not in str(caught.value) + assert len(host.adapter.calls) == 1 + assert host.events()[-1]["kind"] == "dispatch" diff --git a/tests/test_mcp.py b/tests/test_mcp.py index f558922..5a47822 100644 --- a/tests/test_mcp.py +++ b/tests/test_mcp.py @@ -5,6 +5,7 @@ pytest.importorskip("mcp") from leanguard import GuardHost from leanguard.demo import MemoryTools +from leanguard.host import ReadOnlyToolError from leanguard.mcp_server import build_server from mcp import Client from mcp.client.stdio import StdioServerParameters @@ -60,3 +61,18 @@ async def test_mcp_stdio_transport(tmp_path): assert not result.structured_content["allow"] result = await client.call_tool("guarded_call", {"action": "read", "arguments": {}}) assert result.structured_content["result"]["value"] == "initial" + + +async def test_mcp_uses_the_same_private_diagnostic_boundary(tmp_path): + adapter = MemoryTools() + + def fail(*args): + raise ReadOnlyToolError("private backend credential") + + adapter.execute = fail + with GuardHost("example", tmp_path / "journal", adapter, principal="p", session="s") as host: + async with Client(build_server(host)) as client: + result = await client.call_tool("guarded_call", {"action": "read", "arguments": {}}) + assert result.structured_content["outcome"] == "failure" + assert "private" not in str(result.structured_content) + assert "error" not in result.structured_content