Skip to content

Add guarded tool integrations for fifteen maintained Python frameworks - #72

Merged
DebarghaG merged 2 commits into
devfrom
feat/python-framework-tools
Nov 27, 2026
Merged

DebarghaG merged 2 commits into
devfrom
feat/python-framework-tools

Conversation

@DebarghaG

@DebarghaG DebarghaG commented Nov 15, 2026 •

Copy link
Copy Markdown
Owner

Agent frameworks need a tool implementation that keeps admission, approval binding, journaling, and backend execution inside GuardHost. This adds optional native tool factories for Strands, LangChain/LangGraph, Deep Agents, OpenAI Agents, Claude Agent SDK, Google ADK, Microsoft Agent Framework, CrewAI, LlamaIndex, PydanticAI, Agno, Haystack, smolagents, DSPy, and CAMEL.

The factories and existing MCP server share one model-facing result/error boundary, preserve unknown outcomes, and drain synchronous host transactions before propagating async cancellation. Generic SDK error messages hide private host diagnostics without claiming that an exceptional call had no effects; trusted Python callers retain the original exception context. SDK dependencies are isolated optional extras with exact tested versions; CI builds one native engine and exercises each real SDK tool path independently. Coverage is limited to the registered guarded tool; raw tools, SDK built-ins, and unrestricted code execution remain explicitly outside it.

Closes #36, #37, #38, #39, #40, #41, #42, #45, #46, #47, #48, #49, #50, #51, #52. Implements the Python portion of #35. Part of #31.

Validation: all fifteen SDK invocation paths passed locally, including a deterministic Deep Agents graph and Claude in-memory MCP transport. Eight shared boundary regressions pass, including repeated cancellation, plus synchronous path checks for LangChain, LlamaIndex, and Haystack. The full scripts/verify.py gate passed (Lean build, axiom audit, Ruff, Python tests, conformance). Optional SDK tests skipped in the base environment were exercised separately in isolated environments. No live model calls were used. The original remote SDK matrix and Verify runs passed; CI reruns for the final error-boundary change are tracked separately.

@amazon-q-developer amazon-q-developer Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Review Summary

This PR adds fifteen SDK integrations behind a shared bind_guarded_call / bind_async_guarded_call boundary. The architecture is sound — the cancellation-drain pattern, journal isolation, and policy-first admission flow are all well-structured. However, several blocking defects were found:

Critical (must fix before merge):

  1. CI command injection (.github/workflows/integrations.yml line 50): matrix.framework is shell-interpolated inside single quotes. Use env: indirection to fully eliminate the injection surface.1

  2. Test proposal_id truthiness bug (tests/integrations/test_python_sdks.py line 167): if proposal_id: silently drops falsy-but-valid proposal_id values from the payload. The proposal-binding assertions on lines 178–180 may pass vacuously if the guard host accepts a None proposal_id under certain conditions. Change to if proposal_id is not None:.

  3. deepagents bare StopIteration (tests/integrations/test_python_sdks.py line 72): Unguarded next() over messages raises StopIteration, which PEP 479 converts to RuntimeError inside an async frame, masking the real failure.

  4. strands empty-events crash (tests/integrations/test_python_sdks.py line 22): events[-1] raises IndexError with no diagnostic if the stream produces no events.

  5. Pytest -k filter fragility (scripts/test_integration.py line 58): The trailing-hyphen filter can over-select (prefix matches) or under-select (ID format change), causing silent test gaps or false CI failures.

  6. task.exception() discarded silently (python/leanguard/integrations/call.py line 84): The intent (suppress asyncio warning) is correct but the silent discard is a maintenance hazard; assign to _ with a comment.


You can now have the agent implement changes and create commits directly on your pull request's source branch. Simply comment with /q followed by your request in natural language to ask the agent to make changes.

Footnotes

  1. CWE-78: OS Command Injection - https://cwe.mitre.org/data/definitions/78.html ↩

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 }}

("claude", "claude_agent_sdk"),
],
)
async def test_native_tool(framework, dependency, tmp_path):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛑 Logic Error: test_native_tool is an async def function but is missing the @pytest.mark.asyncio decorator (or equivalent). With asyncio_mode = "auto" set in pyproject.toml this works globally, but the test file itself has no pytestmark and no per-test decorator, so this will silently pass collection without actually awaiting the coroutine if asyncio_mode is ever changed or if the test is run in an environment with a different pytest-asyncio configuration. More critically, the invoke helper function at line 12 is also async def but not decorated and not a test — if it fails to be awaited correctly in some execution paths this produces a coroutine-never-awaited bug that silently returns without testing anything.

{"toolUseId": "call-1", "name": "guarded_call", "input": arguments}, {}
)
]
return json.loads(events[-1]["tool_result"]["content"][0]["text"])

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛑 Logic Error: The invoke helper at line 12 is an async def but is called with await invoke(...) only from within another async context (the call closure at line 165). However, invoke itself is not a test fixture or a coroutine that is await-guarded at the top level. If the strands path's tool.stream(...) async generator raises on an empty event list, events[-1] at line 22 will raise an IndexError with no diagnostic, masking the underlying SDK failure entirely. The return value should be guarded against an empty events list.

Suggested change
return json.loads(events[-1]["tool_result"]["content"][0]["text"])
if not events:
raise AssertionError("strands tool.stream() produced no events")
return json.loads(events[-1]["tool_result"]["content"][0]["text"])


async def call(action, arguments, proposal_id=None):
payload = {"action": action, "arguments": arguments}
if proposal_id:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛑 Logic Error: The proposal_id truthiness check on line 167 incorrectly excludes the case where proposal_id is a valid but falsy string (e.g., "" empty string), and more importantly it means a non-None falsy proposal_id is silently dropped from the payload, causing the test to pass a None proposal_id to the backend instead of the actual value. The check should test is not None to match the type contract established in call.py line 31.

Suggested change
if proposal_id:
if proposal_id is not None:

Comment on lines +72 to +73
response = next(m for m in result["messages"] if isinstance(m, ToolMessage))
return json.loads(response.content)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛑 Logic Error: The deepagents path uses next(m for m in result["messages"] if isinstance(m, ToolMessage)) at line 72 with no default. If the agent loop produces no ToolMessage (e.g., the fake model's tool call is not echoed back as expected, or the SDK skips it on a policy-denied path), this raises a bare StopIteration, which propagates out of the async frame as a RuntimeError: coroutine raised StopIteration (PEP 479). This silently fails the entire test with an opaque error rather than a clear assertion failure.

Suggested change
response = next(m for m in result["messages"] if isinstance(m, ToolMessage))
return json.loads(response.content)
response = next(
(m for m in result["messages"] if isinstance(m, ToolMessage)), None
)
assert response is not None, f"No ToolMessage found; messages: {result['messages']}"
return json.loads(response.content)

"-q",
"tests/integrations/test_python_sdks.py",
"-k",
f"{args.framework}-",

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛑 Logic Error: The pytest -k filter expression f"{args.framework}-" (line 58) uses a trailing hyphen to narrow test selection. This relies on the parametrize IDs using {framework}-{dependency} as the separator character. If pytest generates IDs with a different separator (e.g., framework0, framework-strands0) or if a framework name is a prefix of another (e.g., lang matching langchain), the filter will either select zero tests (causing the check=True subprocess to exit non-zero) or over-select tests, running tests for frameworks whose SDK is not installed. The filter should be anchored more precisely, e.g., f"test_native_tool[{args.framework}-" to prevent both failure modes.

Suggested change
f"{args.framework}-",
f"test_native_tool[{args.framework}-",

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

@DebarghaG
DebarghaG marked this pull request as ready for review November 15, 2026 15:55
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-15T17:21:19.241358Z 9f255f9 New commits
🔒 Security Review ✅ Completed 2026-11-15T15:58:54.398444Z 15b3901 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@DebarghaG
DebarghaG changed the base branch from main to dev November 27, 2026 03:34
@DebarghaG
DebarghaG merged commit 0aef5ef into dev Nov 27, 2026
34 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment