|
| 1 | +# Copyright 2026 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +"""ADK plugin for Agent Governance Toolkit policy enforcement. |
| 16 | +
|
| 17 | +Evaluates policy-as-code rules before tool execution using the Agent |
| 18 | +Governance Toolkit (https://github.com/microsoft/agent-governance-toolkit). |
| 19 | +Denied tool calls are short-circuited with a policy violation response. |
| 20 | +
|
| 21 | +Requires: ``pip install agentmesh-platform`` |
| 22 | +""" |
| 23 | + |
| 24 | +from __future__ import annotations |
| 25 | + |
| 26 | +import logging |
| 27 | +from pathlib import Path |
| 28 | +from typing import Any, Optional |
| 29 | + |
| 30 | +from google.adk.plugins.base_plugin import BasePlugin |
| 31 | +from google.adk.tools.base_tool import BaseTool |
| 32 | +from google.adk.tools.tool_context import ToolContext |
| 33 | + |
| 34 | +logger = logging.getLogger(__name__) |
| 35 | + |
| 36 | + |
| 37 | +class _GovernanceUnavailableError(ImportError): |
| 38 | + """Raised when agentmesh-platform is not installed and fail_open=False.""" |
| 39 | + |
| 40 | + |
| 41 | +class AgentGovernancePlugin(BasePlugin): |
| 42 | + """ADK plugin that enforces governance policies before tool execution. |
| 43 | +
|
| 44 | + Uses the Agent Governance Toolkit to evaluate YAML/OPA/Cedar policies. |
| 45 | + When a tool call is denied by policy, the plugin returns a dict response |
| 46 | + that short-circuits tool execution (per the ADK plugin contract). |
| 47 | +
|
| 48 | + Args: |
| 49 | + policy_dir: Absolute or relative path to the directory containing |
| 50 | + ``*.yaml`` policy files. Resolved relative to the caller's |
| 51 | + working directory. Must be provided explicitly. |
| 52 | + agent_did: Decentralized identifier for the agent. |
| 53 | + fail_open: If ``True``, tool calls proceed when ``agentmesh-platform`` |
| 54 | + is not installed (logs a warning). If ``False`` (default), raises |
| 55 | + ``ImportError`` at construction time. |
| 56 | +
|
| 57 | + Raises: |
| 58 | + ImportError: If ``agentmesh-platform`` is not installed and |
| 59 | + ``fail_open`` is False. |
| 60 | +
|
| 61 | + Example:: |
| 62 | +
|
| 63 | + from google.adk_community.plugins import AgentGovernancePlugin |
| 64 | +
|
| 65 | + plugin = AgentGovernancePlugin( |
| 66 | + policy_dir=Path(__file__).parent / "policies", |
| 67 | + ) |
| 68 | + runner = Runner(agent=my_agent, plugins=[plugin], ...) |
| 69 | + """ |
| 70 | + |
| 71 | + def __init__( |
| 72 | + self, |
| 73 | + policy_dir: str | Path, |
| 74 | + agent_did: str = "did:mesh:adk-agent", |
| 75 | + fail_open: bool = False, |
| 76 | + ) -> None: |
| 77 | + super().__init__(name="agent_governance") |
| 78 | + self._policy_dir = Path(policy_dir).resolve() |
| 79 | + self._agent_did = agent_did |
| 80 | + self._engine = None |
| 81 | + self._audit = None |
| 82 | + self._setup(fail_open=fail_open) |
| 83 | + |
| 84 | + def _setup(self, *, fail_open: bool) -> None: |
| 85 | + """Initialize AGT policy engine and audit service.""" |
| 86 | + try: |
| 87 | + from agentmesh.governance.policy import PolicyEngine |
| 88 | + from agentmesh.services.audit import AuditService |
| 89 | + |
| 90 | + self._engine = PolicyEngine() |
| 91 | + self._audit = AuditService() |
| 92 | + |
| 93 | + if self._policy_dir.exists(): |
| 94 | + for f in sorted(self._policy_dir.glob("*.yaml")): |
| 95 | + try: |
| 96 | + self._engine.load_yaml(f.read_text()) |
| 97 | + logger.info("Loaded policy: %s", f.name) |
| 98 | + except Exception as exc: |
| 99 | + logger.warning("Skipped %s: %s", f.name, exc) |
| 100 | + else: |
| 101 | + logger.warning( |
| 102 | + "Policy directory does not exist: %s", self._policy_dir |
| 103 | + ) |
| 104 | + |
| 105 | + logger.info( |
| 106 | + "AgentGovernancePlugin initialized (agent=%s, policies=%s)", |
| 107 | + self._agent_did, |
| 108 | + self._policy_dir, |
| 109 | + ) |
| 110 | + except ImportError: |
| 111 | + if not fail_open: |
| 112 | + raise _GovernanceUnavailableError( |
| 113 | + "agentmesh-platform is required for governance enforcement. " |
| 114 | + "Install with: pip install agentmesh-platform" |
| 115 | + ) |
| 116 | + logger.warning( |
| 117 | + "agentmesh-platform not installed; governance checks disabled. " |
| 118 | + "Install with: pip install agentmesh-platform" |
| 119 | + ) |
| 120 | + |
| 121 | + async def before_tool_callback( |
| 122 | + self, |
| 123 | + *, |
| 124 | + tool: BaseTool, |
| 125 | + tool_args: dict[str, Any], |
| 126 | + tool_context: ToolContext, |
| 127 | + ) -> Optional[dict]: |
| 128 | + """Evaluate governance policy before a tool call. |
| 129 | +
|
| 130 | + Returns ``None`` to allow the tool to proceed, or a dict response |
| 131 | + to short-circuit execution when the policy denies the call. |
| 132 | + """ |
| 133 | + if self._engine is None: |
| 134 | + return None |
| 135 | + |
| 136 | + context = { |
| 137 | + "action": tool.name, |
| 138 | + "tool_args": tool_args, |
| 139 | + } |
| 140 | + |
| 141 | + result = self._engine.evaluate( |
| 142 | + agent_did=self._agent_did, |
| 143 | + context=context, |
| 144 | + ) |
| 145 | + |
| 146 | + if self._audit: |
| 147 | + self._audit.log_policy_decision( |
| 148 | + agent_did=self._agent_did, |
| 149 | + action=tool.name, |
| 150 | + decision=result.action, |
| 151 | + policy_name=result.policy_name or "", |
| 152 | + data={"tool_args": tool_args, "reason": result.reason}, |
| 153 | + ) |
| 154 | + |
| 155 | + if not result.allowed: |
| 156 | + logger.warning( |
| 157 | + "Policy denied tool '%s': %s (rule: %s)", |
| 158 | + tool.name, |
| 159 | + result.reason, |
| 160 | + result.matched_rule, |
| 161 | + ) |
| 162 | + return { |
| 163 | + "error": "policy_denied", |
| 164 | + "reason": result.reason, |
| 165 | + "matched_rule": result.matched_rule, |
| 166 | + } |
| 167 | + |
| 168 | + return None |
0 commit comments