ai icon indicating copy to clipboard operation
ai copied to clipboard

[Feature] Governance hooks for AI SDK — policy enforcement before tool execution

Open imran-siddique opened this issue 7 months ago • 17 comments

Summary

Proposing governance hooks/middleware for the Vercel AI SDK's tool execution pipeline, powered by the Agent Governance Toolkit (AGT).

Motivation

The AI SDK's tool abstraction is the natural enforcement point for governance. Before any tool executes, enterprises need policy checks, identity verification, and audit logging — without modifying tool implementations.

Proposed Integration

  1. Pre-execution policy hooks — AGT's policy engine evaluates rules before tool.execute() runs. Policies are defined as code (e.g., block file-system writes, enforce rate limits, restrict PII access). Evaluation takes <5ms.
  2. Agent identity verification — Ed25519 keypairs verify which agent/user initiated a tool call. Supports zero-trust multi-agent architectures.
  3. Tamper-evident audit trails — every tool invocation, policy decision, and result is logged in a Merkle chain. Exportable for compliance.

Integration points

  • experimental_toToolResultContent or a new onBeforeToolCall / onAfterToolCall hook
  • Middleware wrapper around tool() definitions
  • TypeScript SDK available for native integration

Technical details

  • TypeScript SDK with full type safety
  • <5ms policy evaluation overhead
  • MIT licensed, 9,500+ tests
  • Works with any AI SDK provider (OpenAI, Anthropic, etc.)

Repo: https://github.com/microsoft/agent-governance-toolkit

imran-siddique avatar Apr 20 '26 20:04 imran-siddique

Update: Contributor Reputation Action now available

While building governance tooling for the Agent Governance Toolkit, we uncovered a pattern of coordinated inauthentic contributions targeting AI agent frameworks. Accounts use a credibility-laundering pipeline: getting small PRs merged in one repo, then citing those merges as credentials in spray issues across dozens of other repos.

We built and shipped open-source tooling to detect these patterns, now available as a reusable GitHub Action any repo can adopt:

# .github/workflows/contributor-check.yml
on:
  pull_request_target:
    types: [opened]
  issues:
    types: [opened]

jobs:
  check:
    runs-on: ubuntu-latest
    steps:
      - uses: microsoft/agent-governance-toolkit/.github/actions/contributor-check@main
        with:
          github-token: ${{ secrets.GITHUB_TOKEN }}
          target-repo: microsoft/agent-governance-toolkit

What it does:

  • Checks contributor account shape (age, repo count, follower ratio)
  • Detects credential-spray patterns (merged PRs cited across other repos)
  • Labels and comments on MEDIUM/HIGH risk contributions for maintainer review
  • Zero external dependencies (Python stdlib only)

The tools are MIT-licensed at microsoft/agent-governance-toolkit/scripts/ and shipped in AGT v3.3.0.

Sharing as a heads-up since AI agent repos are prime targets for this kind of campaign. Happy to help with integration if useful.

imran-siddique avatar Apr 27 '26 03:04 imran-siddique

The AI SDK's tool abstraction is indeed the right enforcement point — governance at the tool layer catches the most impactful agent actions.

From implementing tool-level governance for multi-agent systems:

Pre-execution hook is the critical position: The governance check must happen before tool execution, not after. An executed tool call that violates policy is damage done — especially for tools that modify external state (send email, create PR, deploy). The middleware should sit between the model's tool call decision and the actual execute() function.

The authorization context: Every tool execution should be evaluated against: (agent_identity, user_identity, tool_name, tool_args, session_context, remaining_budget, delegation_depth). This enables enterprise-grade policies:

  • "Database write tools only allowed at delegation depth 0"
  • "External API calls require remaining budget > estimated cost"
  • "PII-handling tools need explicit user consent within the last 5 minutes"

Cost-aware governance: Different tools have different cost profiles. An LLM tool call costs dollars; a file read costs nothing. The governance layer should estimate cost before execution and check against the remaining session/agent budget. We use pessimistic allocation — reserve the estimated cost before execution, refund the difference after.

Capability intersection for delegated tool calls: When Agent A delegates work to Agent B via the AI SDK, B's available tools should be min(A's tools, B's tools). This prevents privilege escalation through delegation — a critical security property.

Audit trail: Every governance decision (allow, deny, escalate) should be logged with the full context. The @ai-sdk/otel integration point (#14727) is the natural place to emit governance events as OpenTelemetry spans.

Architecture on per-agent tool governance: https://blog.kinthai.ai/openclaw-multi-tenancy-why-vm-per-user-doesnt-scale Multi-agent delegation and trust: https://blog.kinthai.ai/221-agents-multi-agent-coordination-lessons

kinthaiofficial avatar Apr 28 '26 17:04 kinthaiofficial

Strong proposal. The AI SDK's tool abstraction is indeed the right enforcement point. From implementing governance hooks for 31 agents, some patterns that complement AGT:

The guardrail interface pattern

Pre-execution hooks need a clean interface that doesn't require modifying tool implementations. We use a pattern inspired by Semantic Kernel's IGuardrailProvider:

interface GovernanceHook {
  evaluate(call: ToolCall, context: AgentContext): Promise<PolicyDecision>;
}

type PolicyDecision = 
  | { action: 'allow' }
  | { action: 'deny'; reason: string }
  | { action: 'escalate'; to: 'human' | 'supervisor' }
  | { action: 'modify'; transformedInput: unknown };

// Registration
const agent = createAgent({
  tools: [webSearch, codeExec, fileWrite],
  governance: [
    budgetGuard,          // check cost budget before execution
    capabilityGuard,      // verify agent has permission for this tool
    delegationChainGuard, // check delegation chain for cycles/escalation
    rateLimitGuard,       // prevent burst tool usage
  ]
});

The modify action is important — sometimes governance shouldn't block the call but should redact sensitive fields from the input before the tool sees them.

Capability intersection for multi-agent AI SDK workflows

When one agent delegates to another (common in multi-step AI SDK flows), the child agent's effective capabilities must be ≤ parent's:

function delegate(parent: AgentContext, child: AgentContext) {
  child.effectiveTools = parent.tools.filter(t => 
    child.declaredTools.includes(t.name)
  );
  // Intersection — tools only shrink down the delegation chain
}

Ed25519 signed audit receipts

Every tool execution should produce a signed receipt for the audit trail:

const receipt = {
  agentId: context.agent.did,
  toolName: call.toolName,
  inputHash: sha256(JSON.stringify(call.input)),
  timestamp: Date.now(),
  delegationChain: context.delegationChain,
  signature: sign(context.agent.privateKey, canonicalize(receipt))
};

This creates a tamper-evident chain. If something goes wrong, you can trace the exact execution path.

Budget enforcement as governance

Budget checks should be governance hooks, not tool-level concerns. The budget guard checks the agent's remaining budget before every tool execution and transitions to half-open mode (only cheap operations) when approaching limits.

Related deep-dives:

Running this at agents.kinthai.ai on OpenClaw.

kinthaiofficial avatar Apr 28 '26 18:04 kinthaiofficial

@arian-gogani you named the hardest part precisely: tamper-evident audit trails for multi-agent.

We built exactly that layer. Mycelium Trails (https://argentum-api.rgiskard.xyz) generates a signed, externally-anchored TrailRecord for every agent action — post-execution, non-blocking, independently verifiable without accessing the operator's infrastructure.

Working example with Vercel AI SDK hooks pattern (RunHooks.on_tool_end / BaseCallbackHandler equivalent): https://github.com/giskard09/argentum-core

The spec for action_ref derivation and the guarantee model (what a TrailRecord proves / does not prove) is in the repo. For Art. 12 specifically: Mycelium "supports compliance with" Art. 12 in the integrity + independent auditability component — the operator still needs to configure logging granularity and field coverage.

Happy to answer technical questions.

giskard09 avatar May 15 '26 13:05 giskard09

@giskard09 the pre-execution side of this is where nobulex fits. Mycelium Trails records what happened after execution. nobulex enforces behavioral rules before execution happens and receipts the result. the two compose: enforcement proof + external anchor.

for the Vercel AI SDK hooks pattern: nobulex integrates as a pre-tool-execution check. the agent declares its behavioral boundaries in a covenant. every tool call is evaluated against those boundaries before it runs. if it passes, the action executes and a bilateral receipt is produced (Ed25519 over JCS-canonical JSON). if it fails, the action is blocked and the violation is recorded.

over time, the receipt chain accumulates into Trust Capital -- a credit score for the agent. higher Trust Capital = more autonomy, bigger transaction limits, lower insurance premiums. the governance hook becomes an economic signal, not just a compliance gate.

microsoft merged the receipt primitive into their Agent Governance Toolkit (PRs #1302, #1333). happy to scope what an AI SDK middleware integration would look like.

repo: https://github.com/arian-gogani/nobulex

arian-gogani avatar May 16 '26 01:05 arian-gogani

The pre-execution enforcement position @kinthaiofficial identified is the right one — executed tool calls that violate policy are damage done, not a policy violation.

One gap worth naming in the hook design: the policy check and the credential retrieval need to be in the same pass. When a tool call reaches onBeforeToolCall, the agent is about to pull whatever secret the tool needs (API key, DB credentials, signing key). If the governance check runs but credential access is handled separately downstream, you have a window where the tool is authorized but the credential is already live before any final scoping check.

Wiring a credential broker into the same hook — so the policy decision and the secret vend happen atomically — closes that window. The tool either gets both the approval and the scoped credential, or it gets neither. That's the architecture we've been building at 1Claw with Shroud + Vault. Happy to compare notes on the TypeScript integration surface. docs.1claw.xyz

redbotster avatar May 16 '26 20:05 redbotster

The governance hook proposal is architecturally sound — pre-execution policy checks before is the right enforcement point for tool calls. One gap worth surfacing: tools are not the only attack surface.

The current design hooks into the tool execution pipeline. But the agent's reasoning is shaped before any tool runs — by the system prompt, by skill files, by RAG content, by conversation history. A governance hook that only checks tool calls is like a security checkpoint at the exit but no checkpoint at the entrance.

The missing layer: pre-ingestion enforcement — governance hooks that fire before content enters the agent's context window, not just before tools execute. This catches the manipulation at the source rather than at the action:

  1. System prompt integrity: verify the agent's instructions have not been tampered with between sessions
  2. Skill file validation: check loaded SKILL.md and references for encoding-level manipulation before the agent reads them
  3. RAG content filtering: scan retrieved documents for adversarial instructions before they enter the context
  4. Input boundary enforcement: catch encoding-obfuscated payloads (zero-width, confusables, RTL overrides, homoglyphs) that bypass semantic content filtering

The hook signature could mirror the proposed tool hook: . Same evaluation time (<5ms), same policy engine, different surface.

We have been building this layer specifically: deterministic input-boundary enforcement with 40+ encoding variant detection, territory/domain scoping, and zero-false-positive calibration. Repo: https://github.com/woshilaohei/vsos-guard. The policy evaluation pipeline maps directly onto AGT's hook architecture — the governance scope just needs to extend one step earlier in the agent's processing chain.

Tool governance + input governance = complete coverage. Tool governance alone = locked door, open window.

woshilaohei avatar May 31 '26 12:05 woshilaohei

On the policy-hook side of @imran-siddique's proposal: the rule supply layer below AGT's policy engine is Agent Threat Rules (https://github.com/Agent-Threat-Rule/agent-threat-rules), MIT-licensed, 462 rules across 10 attack categories. AGT syncs 287 of them weekly (PRs microsoft/agent-governance-toolkit#1277, #908, #1981) and routes them through its policy engine — exactly the path the onBeforeToolCall hook here would consume.

For the AI SDK side specifically, two things worth folding in.

The hook signature Imran proposed maps cleanly onto the existing experimental_toToolResultContent plumbing, but the JS SDK case wants a different rule format than AGT's Python policy syntax. agent-threat-rules ships as an npm package (v3.1.1) with rules as JSON, so a TypeScript middleware can ingest the same corpus AGT uses without round-tripping through the policy engine for the basic detect-and-block case. The Merkle audit trail described in the proposal still composes on top.

The detection layer is small and high-precision by default (~30 rules for the built-in subset: prompt-injection override, system-prompt extraction, indirect-injection markers, credential shapes, shell injection, AWS metadata SSRF), with the full catalog opt-in. That keeps the AI SDK side dependency-light while letting AGT users get the full policy surface they already have.

If @gr2m / @lgrammel are open to an onBeforeToolCall hook landing, I can prepare a small starter PR for the detection-middleware piece against the ai package, sized to match how the existing middleware (e.g., wrapLanguageModel) is structured. AGT integration stays as Imran proposed.

ATR is also already merged into Microsoft PyRIT (#1715, merged 2026-05-27 by Roman Lutz), Cisco AI Defense skill-scanner (#99, 314 rules), and MISP via CIRCL Luxembourg (#1207, 336 rules) — same rule corpus, three different runtimes.

eeee2345 avatar Jun 05 '26 17:06 eeee2345

The "Merkle audit trail composes on top" framing is the right layering — action_ref is the binding key that connects the two sides across runtimes.

Pre-execution: ATR evaluates the tool call intent. Post-execution: Mycelium derives action_ref = SHA-256(JCS({agent_id, action_type, scope, timestamp})) from the same intent tuple and anchors the trail on-chain. A verifier holding both can correlate detection → execution → outcome without trusting either operator's infrastructure — the onBeforeToolCall / onAfterToolCall boundary is the same preimage.

This is already in production: Pioneer (our monitoring agent) generates action_ref-anchored trails on Arbitrum mainnet each cycle; SafeAgent has been anchoring production trails since this week. Spec + conformance fixtures: giskard09/argentum-core

giskard09 avatar Jun 05 '26 18:06 giskard09

The governance hook (pre-execution policy check) and the tamper-evident audit trail are two separate layers and they work best kept separate.

The action_ref is the binding key between them. Before executing a tool call, derive:

const actionRef = sha256(jcs({ agentId, actionType, scope, timestampMs }))

Pass it to the policy check. If allowed, execute, then generate the receipt using the same actionRef. The receipt chain then proves what the policy allowed, when, and what actually ran — verifiable by any auditor with only the agent's public key, no platform trust required.

// Pre-execution
const actionRef = deriveActionRef({ agentId, actionType, scope, timestampMs })
const policy = await policyEngine.check(actionRef, context)
if (!policy.allowed) throw new PolicyViolation(policy)

// Post-execution
const receipt = await sign({ actionRef, resultHash: hash(result), policyRef: policy.ref })
await chain.append(receipt) // hash-chained, Ed25519 signed

The open question is where action_ref derivation is specified so policy engines and receipt layers from different vendors agree on the same canonical hash. That spec alignment is what makes the two-layer architecture composable.

pip install nobulex / npm install @nobulex/core — ships the receipt side (Ed25519, JCS/RFC 8785, hash chain) with LangChain and CrewAI integrations. Pairs with whatever policy engine sits above it.

arian-gogani avatar Jun 05 '26 23:06 arian-gogani

governance hooks need to produce verifiable records, not just runtime decisions.

if the hook blocks a tool call, the evidence should survive outside the SDK process. if it allows, the authorization should be independently checkable. that means the hook output is a signed receipt, not a boolean.

the receipt shape: content-addressed action identity (SHA-256 over RFC 8785 canonical form of the tool call parameters), Ed25519 signature against a pinned authorized key, hash-chained for ordering. a downstream auditor verifies by recomputing hashes and checking signatures. no callback to the SDK or the policy provider.

nobulex implements this as a framework-agnostic primitive with integrations for LangChain, CrewAI, Google ADK, and PydanticAI. a Vercel AI SDK middleware adapter would follow the same pattern.

pip install nobulex / npm install @nobulex/core https://github.com/arian-gogani/nobulex

arian-gogani avatar Jun 27 '26 21:06 arian-gogani

@arian-gogani agree, and the receipt-not-a-boolean framing is the part most hook designs miss. One thing worth pinning down alongside the signature: what's inside the receipt.

A signed receipt proves who authorized the call and when. It doesn't, on its own, prove the decision was the right one — an auditor still has to trust whoever produced the verdict. That gap closes if the verdict itself is reproducible. If the policy check is deterministic (fixed ruleset, no model call in the decision path), then the receipt can carry the ruleset version alongside the verdict, and a downstream verifier can re-run that exact version against the same canonical action bytes and get the same answer offline. The receipt goes from "signed assertion" to "re-derivable," which is the stronger property.

So the payload I'd want under your action_ref is roughly { action_ref, ruleset_version, verdict, timestamp }, then Ed25519 over the JCS form of that. The detector produces the verdict; your receipt layer makes it tamper-evident and ordered. They compose cleanly and stay independent — the receipt format shouldn't care which engine produced the verdict, and the engine shouldn't need to know how it's anchored.

For the deterministic-detector half I work on Agent Threat Rules (MIT, agent-threat-rules on npm). Not pitching it as the only option — the point is just that pinning a versioned, reproducible verdict into the receipt is what makes "independently checkable" actually hold without trusting the producer. Happy to sketch what the verdict payload looks like if it's useful for the spec.

eeee2345 avatar Jun 28 '26 11:06 eeee2345

The three points you named map to the three-record trail in the guardrail conformance fixture (giskard09/argentum-core, examples/conformance/guardrail-provider-v1.fixture.json).

Policy hash at evaluation time: policy_id is embedded in authorization_ref = SHA-256(JCS({action_ref, authorized_scope, decision_ts, policy_id})). A verifier holding the decision record can confirm which policy was in force at decision time — without trusting the system that issued the receipt.

Context snapshot: original_args_digest and effective_args_digest — JCS hashes of what the guardrail received and what it dispatched. If they diverge without an authorized revision, the verifier state is QUIET_SWAP_OR_STALE, not AUTHORIZED_EXECUTION.

Derivation chain: action_ref is embedded in authorization_ref's preimage. A verifier can confirm the decision was for this specific intent instance — recomputed from the four-field intent tuple — not any instance that happened to match the same policy.

giskard09 avatar Jun 28 '26 14:06 giskard09

@imran-siddique did you take a look at https://www.npmjs.com/package/@ai-sdk/policy-opa / https://ai-sdk.dev/docs/agents/policy-tool-approvals

That should cover most of what you need. Let me know if you have other suggestions/feedback

dnukumamras avatar Jul 01 '26 04:07 dnukumamras

Identify issue type

{
  "evidence": [
    "The issue proposes new governance hooks/middleware for the AI SDK tool execution pipeline, including pre-execution policy checks, identity verification, and audit logging.",
    "It suggests integration points such as a new `onBeforeToolCall` / `onAfterToolCall` hook or middleware around `tool()` definitions.",
    "Multiple comments discuss desired hook design, receipt/audit behavior, credential brokering, and possible middleware implementations.",
    "A later comment points to existing `@ai-sdk/policy-opa` and policy tool approvals as potentially covering much of the need, but does not describe a broken behavior."
  ],
  "rationale": "The report requests new or expanded SDK capabilities for policy enforcement and governance around tool execution, without alleging an existing documented behavior is failing.",
  "type": "feature",
  "confidence": "high"
}

lgrammel avatar Jul 02 '26 08:07 lgrammel

+1 to @dnukumamras pointing at @ai-sdk/policy-opa — the PolicyClient seam it introduces looks like the right extension point for this, and it's worth noting it's engine-agnostic: anything implementing evaluate(path, input) -> { decision, reason } can slot in, not just OPA/Rego.

One concrete third-party engine for that seam, if it's useful as a reference: we maintain Agent Threat Rules (ATR, MIT) — an open detection-rule standard for agent/tool-call traffic (688 rules today, YAML, no Rego to author). It already ships as a guardrail in a few agent frameworks — e.g. the ATRGuardrail capability merged into AG2/AutoGen (ag2ai/ag2classic), plus integrations in NeMo Guardrails and LiteLLM — so the "evaluate a tool call, return allow/deny/needs-approval" shape is one we already implement elsewhere.

If PolicyClient is intended as a stable interface for third-party policy providers (not OPA-only), we'd be glad to ship a small evaluate() adapter that feeds the AI SDK's { tool, args, messages } into the ATR engine and maps findings to the decision enum — happy to sanity-check the shape against what you'd want before building anything. Repo: https://github.com/Agent-Threat-Rule/agent-threat-rules

eeee2345 avatar Jul 06 '26 09:07 eeee2345

Closing this. @ai-sdk/policy-opa plus the policy/tool-approval hooks cover the core of what I was asking for here. Thanks for the pointer.

imran-siddique avatar Jul 09 '26 14:07 imran-siddique