Skip to content

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 ​

FrameworkExtraVersionsPlug in withMinimum SDK
LangChain 1.xlangchainlangchain>=1,<2GuardMiddleware(guard), last in create_agent(middleware=[...])0.5.0
LangGraphlanggraphlanggraph>=1.2.11,<2guard_tool_node(tools, guard)0.8.0
Claude Agent SDKclaudeclaude-agent-sdk>=0.1.26GuardHooks(guard).options()0.5.0
OpenAI Agentsopenai-agentsopenai-agents>=0.20,<0.24protect_function_tool(tool, guard)0.5.0
Pydantic AIpydantic-ai (the slim package)pydantic-ai-slim>=2.55,<3guard_hooks(guard) capability0.8.0
Google ADKgoogle-adkgoogle-adk>=2.11,<3GuardPlugin(guard), last in App(plugins=[...])0.8.0
Microsoft Agent Frameworkagent-framework (core only)agent-framework-core>=1.21,<1.22GuardFunctionMiddleware(guard), last in Agent(middleware=[...])0.9.0
LlamaIndexllama-index (core only)llama-index-core>=0.14.25,<0.15guard_tools(tools, guard)0.9.0
Agnoagnoagno>=3.1.2,<3.2GuardToolHook(guard) in the agent's or team's tool_hooks0.9.0
DSPydspydspy>=3.4,<4guard_tools(tools, guard)0.9.0
CrewAIcrewaicrewai>=1.15.27,<2guard_tools(tools, guard); optional guard_tool_call_hook(guard)0.9.0
Vercel AI SDK (TypeScript)npm @preworld/guardai@^7, Node.js 22.12+, ESMguardTools(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 ​

CombinationConflict
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:

python
from preworld_guard import GuardClient

guard = GuardClient("https://guard.example.com", "pwg_...", "prj_...", agent_id="support-agent")

LangChain ​

python
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 ​

python
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 inside guard_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_wrappers keep 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 ​

python
from preworld_guard import GuardHooks
options = ClaudeAgentOptions(hooks=GuardHooks(guard).options())
  • Guard uses the PreToolUse, PostToolUse and PostToolUseFailure hooks.
  • 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, or async with ClaudeSDKClient(...), in guard_run(...): the hooks only see the context present when the client connected.

OpenAI Agents ​

python
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" raises GuardDenied or GuardApprovalRequired and 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 through on_invoke_tool and need their own boundary.
  • With timeout_seconds on a tool, the decision counts toward the timeout. Leave room for it on tools that need approval.

Pydantic AI ​

python
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, so output_type must include DeferredToolRequests; approval="ticket" returns the ticket in a ToolFailed instead.
  • 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 ​

python
from preworld_guard.google_adk import GuardPlugin
app = App(name="support", root_agent=agent, plugins=[*your_plugins, GuardPlugin(guard)])
  • An agent-level before_tool_callback runs after plugins and can still change arguments. Set verify_arguments=True to 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 ​

python
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 MiddlewareFailure and stops the run.
  • Not covered: tools the model provider executes, and FunctionTool.invoke called directly.

LlamaIndex ​

python
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 CodeActAgent calls functions directly and isn't covered.

Agno ​

python
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=True are refused (GUARD_TOOL_CACHED): Agno's cache is shared across users.
  • A Guard failure raises StopAgentRun. The run status still says completed. Check tool_call_error in RunOutput.tools.
  • external_execution=True tools never reach a hook. Protect them where you run them.

DSPy ​

python
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 calling
  • ToolCall.execute() without functions= looks the name up in your globals and runs the raw function. Pass functions=tools, or use execute_tool_calls, which refuses anything not guarded (TOOL_NOT_GUARDED).
  • DSPy's thread pools (Parallel, batch, Evaluate, optimizers) don't carry guard_run. Enter it inside each worker's function. Compile optimizers against test doubles, not side-effecting tools.

CrewAI ​

python
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 unless tool_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 no started/completed. Use Crew(cache=False) with it.

Vercel AI SDK (TypeScript) ​

ts
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.

FrameworkDenyRequire approvalDegradeGuard can't decide
LangChain, LangGraphError ToolMessage with the payloadSame, with the ticketToolMessage with the fallback's resultGuardUnavailable stops the run; on_guard_error="deny" returns an error message instead
Claude Agent SDKHook returns deny with the rule's messagedeny with the ticket JSONdeny; fallback_resource names the fallbackdeny, GUARD_UNAVAILABLE
OpenAI Agents (default)Tool result is the JSON; run continuesSame, with the ticketThe fallback's resultGuardUnavailable stops the run
OpenAI Agents, on_deny="raise"GuardDenied stops the runGuardApprovalRequired stops the runThe fallback's resultSame
Pydantic AIToolFailedNative deferral (ApprovalRequired)SkipToolExecution with the fallback's resultRaises; the run stops
Google ADKTool skipped; the JSON as the function responseSame, with the ticket{"result": ..., "preworld_guard": ...}Raises; on_guard_error="deny" returns a GUARD_* payload
Microsoft Agent FrameworkFunction result is the JSONSame, with the ticketThe fallback's resultMiddlewareFailure stops the run
LlamaIndexToolOutput(is_error=True) with the JSONSame, with the ticketThe fallback's resultError ToolOutput; the run continues
AgnoTool result is the JSONSame, with the ticketThe fallback's resultStopAgentRun
DSPyThe JSON, as the observationSame, with the ticketThe fallback's resultGUARD_* JSON; the run continues
CrewAITool result is the JSONSame, with the ticketThe fallback's resultToolFailure; 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:

FieldMeaning
statusdenied, approval_required or degraded
reason_codeThe rule's reason, or APPROVAL_NOT_CONSUMABLE, FALLBACK_UNAVAILABLE, GUARD_UNAVAILABLE and so on
messageA sentence for people
policy_versionThe version that decided; absent when Guard couldn't decide
ticket_id, expires_at, approval_statusOnly for approvals
fallback_resourceOnly for degrade
json
{"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's resolve, or guard_run(...). Arguments the model wrote and IDs the framework generated are never taken as identity.
  • Run, session and trace IDs come from resolve, then guard_run, then the framework's own IDs, then new ones.
  • If resolve and guard_run give different subjects, Guard can't decide (GUARD_SUBJECT_MISMATCH). If resolve raises, the same (GUARD_IDENTITY_UNAVAILABLE).
Frameworkresolve receives
LangChain, LangGraphruntime.context
Claude Agent SDKThe hook context (usually you use guard_run instead)
OpenAI AgentsThe context passed to Runner.run(...)
Pydantic AIctx.deps
Google ADKtool_context.state, or the session's user_id with subject_from_user_id=True
Microsoft Agent FrameworkFunctionInvocationContext; by default function_invocation_kwargs
LlamaIndex, DSPy, CrewAINo resolve: use guard_run(...) around the run
AgnoRunContext (use dependencies, not session_state), or user_id with subject_from_user_id=True

Approvals ​

  1. An approval rule makes the adapter file a ticket. The tool doesn't run. Retrying the same action returns the same ticket.
  2. Without a trusted subject the call is denied (APPROVAL_SUBJECT_REQUIRED).
  3. 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.
  4. Pydantic AI defaults to its own deferral: mark the call approved with DeferredToolResults and continue. The Guard ticket still decides. Approving only in your app doesn't count.

Where the ticket is:

FrameworkTicket
LangChain, LangGraphThe error ToolMessage's content and artifact
Claude Agent SDKThe deny reason
OpenAI Agents, Agno, CrewAIThe tool result (GuardApprovalRequired.ticket_id with OpenAI Agents' raise)
Pydantic AIDeferredToolRequests.metadata, or the ToolFailed
Google ADK, Microsoft Agent FrameworkThe function response or result
LlamaIndexThe ToolOutput
DSPyThe observation

See Approvals and degrade.