Framework adapters
The Python SDK has adapters for eleven agent frameworks, and the TypeScript SDK one for the Vercel AI SDK. They all share one decision path and the same rules:
- Guard only restricts. It never widens a permission. In the Claude Agent SDK, for example, your own permission rules and prompts still apply after Guard allows a call.
- When Guard can't decide, the tool doesn't run.
- Guard sits closest to the tool, so it decides on the arguments the tool will really receive, after your own middleware has changed them.
- The model gets the same payload everywhere, the same as from the MCP proxy (see what the model sees).
MCP tools go through the MCP proxy instead.
Supported frameworks
| Framework | Extra | Versions | Plug in with | Minimum SDK |
|---|---|---|---|---|
| LangChain 1.x | langchain | langchain>=1,<2 | GuardMiddleware(guard), last in create_agent(middleware=[...]) | 0.5.0 |
| LangGraph | langgraph | langgraph>=1.2.11,<2 | guard_tool_node(tools, guard) | 0.8.0 |
| Claude Agent SDK | claude | claude-agent-sdk>=0.1.26 | GuardHooks(guard).options() | 0.5.0 |
| OpenAI Agents | openai-agents | openai-agents>=0.20,<0.24 | protect_function_tool(tool, guard) | 0.5.0 |
| Pydantic AI | pydantic-ai (the slim package) | pydantic-ai-slim>=2.55,<3 | guard_hooks(guard) capability | 0.8.0 |
| Google ADK | google-adk | google-adk>=2.11,<3 | GuardPlugin(guard), last in App(plugins=[...]) | 0.8.0 |
| Microsoft Agent Framework | agent-framework (core only) | agent-framework-core>=1.21,<1.22 | GuardFunctionMiddleware(guard), last in Agent(middleware=[...]) | 0.9.0 |
| LlamaIndex | llama-index (core only) | llama-index-core>=0.14.25,<0.15 | guard_tools(tools, guard) | 0.9.0 |
| Agno | agno | agno>=3.1.2,<3.2 | GuardToolHook(guard) in the agent's or team's tool_hooks | 0.9.0 |
| DSPy | dspy | dspy>=3.4,<4 | guard_tools(tools, guard) | 0.9.0 |
| CrewAI | crewai | crewai>=1.15.27,<2 | guard_tools(tools, guard); optional guard_tool_call_hook(guard) | 0.9.0 |
| Vercel AI SDK (TypeScript) | npm @preworld/guard | ai@^7, Node.js 22.12+, ESM | guardTools(tools, guard) → { tools, toolApproval } | npm 0.1.0 |
Microsoft Agent Framework, LlamaIndex, Agno, DSPy and CrewAI arrived in SDK 0.9.0, the newest release. Some version ranges are narrow on purpose: the Agent Framework and Agno adapters rely on behaviour checked on those exact versions, and are widened only after the checks are redone.
The setup wizard won't create a connection for a framework that the SDK it installs doesn't support yet.
Extras that conflict
| Combination | Conflict |
|---|---|
preworld-guard-sdk[crewai,mcp] | mcp 1.28 against 2.0 |
preworld-guard-sdk[google-adk,gateway], [google-adk,oauth] | fastapi and starlette versions |
Run the MCP proxy or the HTTP broker in their own virtual environment or container in those cases.
Examples
guard is a GuardClient:
from preworld_guard import GuardClient
guard = GuardClient("https://guard.example.com", "pwg_...", "prj_...", agent_id="support-agent")LangChain
from preworld_guard import GuardMiddleware
agent = create_agent(model, tools, middleware=[*your_middleware, GuardMiddleware(guard)])Put GuardMiddleware last so it sees what earlier middleware changed. Denials and pending approvals come back to the model as an error ToolMessage.
LangGraph
from preworld_guard.langgraph import guard_tool_node
builder.add_node("tools", guard_tool_node(tools, guard))- No
interrupt(): interrupting inside the wrapper would replay the whole node. Approved calls resume insideguard_resume(ticket_id). - When a node replays (from a checkpoint, say), each call in it is decided and audited again. Make side-effecting tools idempotent.
- ToolNode takes one sync and one async wrapper.
compose_tool_wrappers/compose_async_tool_wrapperskeep yours outside Guard's. - With
handle_tool_errors=True, a Guard failure becomes an error message to the model instead of stopping the run. The tool still doesn't run.
Claude Agent SDK
from preworld_guard import GuardHooks
options = ClaudeAgentOptions(hooks=GuardHooks(guard).options())- Guard uses the
PreToolUse,PostToolUseandPostToolUseFailurehooks. - The hook never raises: Claude Code treats a failing hook as non-blocking, so every failure becomes a deny with
GUARD_UNAVAILABLE. A decision may take up to 45 seconds, and the hook timeout is 60. - When Guard allows, the hook returns no decision of its own and your permission flow continues.
GuardHooks(guard, on_allow="allow")restores the behaviour before 0.7.0. - Wrap the whole
query()loop, orasync with ClaudeSDKClient(...), inguard_run(...): the hooks only see the context present when the client connected.
OpenAI Agents
from agents import Agent, function_tool
from preworld_guard import GuardClient, protect_function_tool, guard_run
guard = GuardClient("https://guard.example.com", "pwg_...", "prj_...", background_events=True)
@function_tool
def update_record(value: str) -> str:
"""Update a record."""
return value
agent = Agent(name="support", tools=[protect_function_tool(update_record, guard)])- By default a denial or pending approval becomes the tool's result (JSON) and the run continues.
on_deny="raise"raisesGuardDeniedorGuardApprovalRequiredand stops it, as before 0.8.0. Tools with an output schema always raise. - Only
FunctionTools are covered. Hosted and built-in tools don't pass throughon_invoke_tooland need their own boundary. - With
timeout_secondson a tool, the decision counts toward the timeout. Leave room for it on tools that need approval.
Pydantic AI
from preworld_guard.pydantic_ai import guard_hooks
agent = Agent(model, tools=[transfer], capabilities=[*your_capabilities, guard_hooks(guard)])- The capability always places itself innermost. It decides on the arguments' JSON form. The tool still gets typed values.
- Denials are
ToolFailed(visible to the model, no retry used up). Approvals use Pydantic AI's own deferral, sooutput_typemust includeDeferredToolRequests;approval="ticket"returns the ticket in aToolFailedinstead. - Covers function tools and toolsets, MCP servers included. Not covered: output tools, external tools (
CallDeferred), provider built-in tools. - Durable execution (Temporal, DBOS, Prefect) isn't covered.
Google ADK
from preworld_guard.google_adk import GuardPlugin
app = App(name="support", root_agent=agent, plugins=[*your_plugins, GuardPlugin(guard)])- An agent-level
before_tool_callbackruns after plugins and can still change arguments. Setverify_arguments=Trueto refuse a call whose arguments changed after Guard decided. - Live and bidirectional streaming runs don't call plugin tool callbacks and are not protected. Model-side built-in tools (Gemini's google_search, for example) aren't either.
Microsoft Agent Framework
from preworld_guard.agent_framework import GuardFunctionMiddleware
agent = Agent(client=chat_client, tools=[transfer], middleware=[*your_middleware, GuardFunctionMiddleware(guard)])
await agent.run("…", function_invocation_kwargs={"subject_id": user_id})- List it last at agent level. If middleware inside it changes the arguments afterwards, the framework refuses the call.
- A Guard failure raises
MiddlewareFailureand stops the run. - Not covered: tools the model provider executes, and
FunctionTool.invokecalled directly.
LlamaIndex
from preworld_guard.llama_index import guard_tools
agent = FunctionAgent(tools=guard_tools([search, transfer], guard), llm=llm)
with guard_run(subject_id=user_id):
response = await agent.run(user_msg="…")- LlamaIndex agents turn every tool exception into an error result, so a Guard failure can't stop the run. The tool still doesn't run, and the model gets an error result.
- Code generated by
CodeActAgentcalls functions directly and isn't covered.
Agno
from preworld_guard.agno import GuardToolHook
agent = Agent(model=model, tools=[transfer], tool_hooks=[GuardToolHook(guard, subject_from_user_id=True), *your_hooks])
agent.run("…", user_id=user_id)- Guard reads and validates the arguments from the call itself, the way Agno will, so its place among the hooks doesn't matter.
- Tools with
cache_results=Trueare refused (GUARD_TOOL_CACHED): Agno's cache is shared across users. - A Guard failure raises
StopAgentRun. The run status still sayscompleted. Checktool_call_errorinRunOutput.tools. external_execution=Truetools never reach a hook. Protect them where you run them.
DSPy
from preworld_guard.dspy import execute_tool_calls, guard_tools
tools = guard_tools([search, transfer], guard)
react = dspy.ReAct("question -> answer", tools=tools)
with guard_run(subject_id=user_id):
prediction = react(question="…")
results = execute_tool_calls(other_prediction.tool_calls, tools) # native tool callingToolCall.execute()withoutfunctions=looks the name up in your globals and runs the raw function. Passfunctions=tools, or useexecute_tool_calls, which refuses anything not guarded (TOOL_NOT_GUARDED).- DSPy's thread pools (
Parallel,batch,Evaluate, optimizers) don't carryguard_run. Enter it inside each worker's function. Compile optimizers against test doubles, not side-effecting tools.
CrewAI
from preworld_guard.crewai import guard_tools
clerk = Agent(role="Clerk", goal="…", backstory="…", tools=guard_tools([search, transfer], guard))
with guard_run(subject_id=user_id):
result = Crew(agents=[clerk], tasks=[task]).kickoff()- A Guard failure returns a
ToolFailure. The run continues unlesstool_failure_policy="raise". guard_tool_call_hook(guard)is an optional process-wide backstop for tools CrewAI adds itself (code execution,mcps=,apps=, delegation). Register it last. It never resumes approvals and records nostarted/completed. UseCrew(cache=False)with it.
Vercel AI SDK (TypeScript)
import { GuardClient, guardRun } from "@preworld/guard";
import { guardTools } from "@preworld/guard/ai-sdk";
const guard = new GuardClient({ endpoint: "https://guard.example.com", token: process.env.PREWORLD_GUARD_TOKEN!,
projectId: "prj_...", agentId: "support-agent", backgroundEvents: true });
await guard.start();
const { tools, toolApproval } = guardTools({ lookup, transfer }, guard);
const result = await guardRun({ subjectId: user.id, sessionId: chat.id }, () =>
generateText({ model, tools, toolApproval, messages }));Each tool's execute is where Guard decides. toolApproval only answers the AI SDK's "approve first?" question. See TypeScript SDK.
Decisions in each framework
When Guard allows, every adapter records started before the tool runs and completed after it.
| Framework | Deny | Require approval | Degrade | Guard can't decide |
|---|---|---|---|---|
| LangChain, LangGraph | Error ToolMessage with the payload | Same, with the ticket | ToolMessage with the fallback's result | GuardUnavailable stops the run; on_guard_error="deny" returns an error message instead |
| Claude Agent SDK | Hook returns deny with the rule's message | deny with the ticket JSON | deny; fallback_resource names the fallback | deny, GUARD_UNAVAILABLE |
| OpenAI Agents (default) | Tool result is the JSON; run continues | Same, with the ticket | The fallback's result | GuardUnavailable stops the run |
OpenAI Agents, on_deny="raise" | GuardDenied stops the run | GuardApprovalRequired stops the run | The fallback's result | Same |
| Pydantic AI | ToolFailed | Native deferral (ApprovalRequired) | SkipToolExecution with the fallback's result | Raises; the run stops |
| Google ADK | Tool skipped; the JSON as the function response | Same, with the ticket | {"result": ..., "preworld_guard": ...} | Raises; on_guard_error="deny" returns a GUARD_* payload |
| Microsoft Agent Framework | Function result is the JSON | Same, with the ticket | The fallback's result | MiddlewareFailure stops the run |
| LlamaIndex | ToolOutput(is_error=True) with the JSON | Same, with the ticket | The fallback's result | Error ToolOutput; the run continues |
| Agno | Tool result is the JSON | Same, with the ticket | The fallback's result | StopAgentRun |
| DSPy | The JSON, as the observation | Same, with the ticket | The fallback's result | GUARD_* JSON; the run continues |
| CrewAI | Tool result is the JSON | Same, with the ticket | The fallback's result | ToolFailure; stops only with tool_failure_policy="raise" |
In every row, when Guard can't decide, the tool does not run.
What the model sees
On deny, require approval or degrade the model gets the same JSON fields as from the MCP proxy:
| Field | Meaning |
|---|---|
status | denied, approval_required or degraded |
reason_code | The rule's reason, or APPROVAL_NOT_CONSUMABLE, FALLBACK_UNAVAILABLE, GUARD_UNAVAILABLE and so on |
message | A sentence for people |
policy_version | The version that decided; absent when Guard couldn't decide |
ticket_id, expires_at, approval_status | Only for approvals |
fallback_resource | Only for degrade |
{"status": "approval_required", "reason_code": "…", "message": "…", "policy_version": 12,
"ticket_id": "…", "expires_at": "…", "approval_status": "pending"}It never contains the raw arguments.
Identity
- The trusted subject (and
tenant_id,destination,data_labels) comes only from your application: the adapter'sresolve, orguard_run(...). Arguments the model wrote and IDs the framework generated are never taken as identity. - Run, session and trace IDs come from
resolve, thenguard_run, then the framework's own IDs, then new ones. - If
resolveandguard_rungive different subjects, Guard can't decide (GUARD_SUBJECT_MISMATCH). Ifresolveraises, the same (GUARD_IDENTITY_UNAVAILABLE).
| Framework | resolve receives |
|---|---|
| LangChain, LangGraph | runtime.context |
| Claude Agent SDK | The hook context (usually you use guard_run instead) |
| OpenAI Agents | The context passed to Runner.run(...) |
| Pydantic AI | ctx.deps |
| Google ADK | tool_context.state, or the session's user_id with subject_from_user_id=True |
| Microsoft Agent Framework | FunctionInvocationContext; by default function_invocation_kwargs |
| LlamaIndex, DSPy, CrewAI | No resolve: use guard_run(...) around the run |
| Agno | RunContext (use dependencies, not session_state), or user_id with subject_from_user_id=True |
Approvals
- An approval rule makes the adapter file a ticket. The tool doesn't run. Retrying the same action returns the same ticket.
- Without a trusted subject the call is denied (
APPROVAL_SUBJECT_REQUIRED). - After a reviewer approves, run the agent again inside
with guard_resume(ticket_id):. When the model proposes the same call, the ticket is consumed once and the tool runs on the approved arguments. - Pydantic AI defaults to its own deferral: mark the call approved with
DeferredToolResultsand continue. The Guard ticket still decides. Approving only in your app doesn't count.
Where the ticket is:
| Framework | Ticket |
|---|---|
| LangChain, LangGraph | The error ToolMessage's content and artifact |
| Claude Agent SDK | The deny reason |
| OpenAI Agents, Agno, CrewAI | The tool result (GuardApprovalRequired.ticket_id with OpenAI Agents' raise) |
| Pydantic AI | DeferredToolRequests.metadata, or the ToolFailed |
| Google ADK, Microsoft Agent Framework | The function response or result |
| LlamaIndex | The ToolOutput |
| DSPy | The observation |