Skip to main content
Glama

PolicyGuard

Security & Governance MCP Server for AI Agents

Python 3.10+ MCP License: MIT

PolicyGuard is an MCP (Model Context Protocol) server that provides policy-based access control, incident tracking, and compliance monitoring for AI agents.

Note: This project demonstrates working integration with kagent (AI agent platform) and can be extended with kgateway (API gateway) for additional network-level security.


Table of Contents


Related MCP server: hejdar-mcp

Overview

As AI agents become more autonomous, organizations need controls to govern their behavior. PolicyGuard is my first MCP server project - built to explore how security and governance can be implemented at the MCP layer.

The Problem

AI agents can call any tool they have access to. Without governance:

  • Agents might perform destructive operations

  • No audit trail of agent actions

  • No way to enforce security policies

  • No visibility into compliance

The Solution

PolicyGuard adds a security layer that agents call before taking action:

User Request → AI Agent → PolicyGuard (validate_action) → Allowed/Denied

Features

Feature

Description

Policy Enforcement

Validate actions against security rules

Trust Levels

low, medium, high, admin hierarchy

Pattern Matching

Wildcard patterns like delete_*, *_production

Auto-Registration

Unknown agents get minimal trust

Incident Tracking

Automatic violation logging

Audit Trail

Complete action history

Compliance Dashboard

Security metrics at a glance


Architecture

┌─────────────────────────────────────────────────────────────────┐
│                         AI Agent / LLM                          │
│                                                                 │
│  "Before any action, call validate_action to check permission" │
└─────────────────────────────────────────────────────────────────┘
                              │
                              │ MCP Protocol
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│                     PolicyGuard MCP Server                      │
│                                                                 │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐             │
│  │  validate   │  │   create    │  │   report    │             │
│  │   action    │  │   policy    │  │  incident   │             │
│  └─────────────┘  └─────────────┘  └─────────────┘             │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐             │
│  │  register   │  │  get_audit  │  │    get      │             │
│  │   agent     │  │    log      │  │ compliance  │             │
│  └─────────────┘  └─────────────┘  └─────────────┘             │
└─────────────────────────────────────────────────────────────────┘
                              │
                              ▼
                    ┌───────────────────┐
                    │   JSON Storage    │
                    │   (policies,      │
                    │    agents,        │
                    │    audit_log,     │
                    │    incidents)     │
                    └───────────────────┘

MCP Tools

PolicyGuard exposes 6 tools via MCP:

1. validate_action ⭐ Primary Tool

Check if an action is allowed before executing it.

{
  "action_type": "tool_call",
  "target": "delete_records",
  "agent_id": "my-agent"
}

Response:

{
  "action_id": "act_a1b2c3d4e5f6",
  "allowed": false,
  "reason": "Delete operations require admin trust level"
}

2. register_agent

Register an agent with a trust level.

{
  "agent_id": "data-processor",
  "name": "Data Agent",
  "trust_level": "medium"
}

3. create_policy

Create security rules.

{
  "policy_id": "block-deletes",
  "name": "Block Deletes",
  "rules": "[{\"condition\": {\"tool_pattern\": \"delete_*\"}, \"action\": \"deny\"}]"
}

4. get_audit_log

Query action history.

5. get_compliance_status

Get security dashboard metrics.

6. report_incident

Manually report security incidents.


Quick Start

Prerequisites

  • Python 3.10+

  • pip

Local Installation

# Clone
git clone https://github.com/PrateekKumar1709/policyguard.git
cd policyguard

# Setup
python3 -m venv .venv
source .venv/bin/activate
pip install -e .

# Run
python src/main.py

Test the Tools

import json
from src.tools.validate_action import validate_action
from src.tools.register_agent import register_agent

# Register an agent
result = json.loads(register_agent.fn(
    agent_id="test-agent",
    name="Test Agent",
    trust_level="medium"
))
print(f"Registered: {result['agent_id']}")

# Validate an action
result = json.loads(validate_action.fn(
    action_type="tool_call",
    target="read_data",
    agent_id="test-agent"
))
print(f"Allowed: {result['allowed']}")

HTTP Mode

python src/main.py --transport http --port 8000

Kubernetes Deployment

PolicyGuard includes a Helm chart for Kubernetes deployment.

Using Kind

# Create cluster
kind create cluster --name policyguard

# Build and load image
docker build -t policyguard:latest .
kind load docker-image policyguard:latest --name policyguard

# Deploy
kubectl create namespace policyguard
helm install policyguard ./helm/policyguard -n policyguard

# Verify
kubectl get pods -n policyguard

Port Forward

kubectl port-forward -n policyguard svc/policyguard 8000:8000

Testing

Unit Tests

pytest tests/ -v

Test Results

tests/test_tools.py::TestValidateAction::test_allow_read_for_low_trust PASSED
tests/test_tools.py::TestValidateAction::test_deny_delete_for_low_trust PASSED
tests/test_tools.py::TestValidateAction::test_allow_delete_for_admin PASSED
tests/test_tools.py::TestValidateAction::test_deny_suspended_agent PASSED
tests/test_tools.py::TestRegisterAgent::test_register_new_agent PASSED
tests/test_tools.py::TestCreatePolicy::test_create_valid_policy PASSED
... (16 tests total)
============================== 16 passed ==============================

E2E Test Output

[1/6] register_agent      ✅ SUCCESS
[2/6] create_policy       ✅ SUCCESS  
[3/6] validate_action     ✅ ALLOWED (read_data)
[4/6] validate_action     ✅ DENIED (delete_records)
[5/6] report_incident     ✅ SUCCESS
[6/6] get_compliance_status ✅ SUCCESS

ALL 6 MCP TOOLS WORKING!

kagent Integration

PolicyGuard integrates with kagent for Kubernetes-native AI agent management.

Screenshots

Agent List - PolicyGuard agent registered and ready:

Agent List

Agent Tools - 6 PolicyGuard MCP tools available:

Agent Tools

Compliance Dashboard - Asking for compliance status:

Compliance Chat

Policy Validation - Action denied based on policy:

Validation Chat

Quick Setup

# 1. Install kagent CRDs
helm install kagent-crds ./kagent-reference/helm/kagent-crds -n kagent --create-namespace

# 2. Install kagent with Ollama (free local LLM)
helm upgrade --install kagent ./kagent-reference/helm/kagent -n kagent \
  --set providers.default=ollama \
  --set providers.ollama.model=qwen2.5:1.5b \
  --set tag=0.7.13

# 3. Deploy PolicyGuard
helm install policyguard ./helm/policyguard -n policyguard --create-namespace

# 4. Create RemoteMCPServer
kubectl apply -f - <<EOF
apiVersion: kagent.dev/v1alpha2
kind: RemoteMCPServer
metadata:
  name: policyguard
  namespace: kagent
spec:
  protocol: STREAMABLE_HTTP
  url: http://policyguard.policyguard:8000/mcp
  timeout: 30s
EOF

# 5. Create PolicyGuard Agent
kubectl apply -f - <<EOF
apiVersion: kagent.dev/v1alpha2
kind: Agent
metadata:
  name: policyguard-agent
  namespace: kagent
spec:
  description: "Security agent using PolicyGuard"
  type: Declarative
  declarative:
    modelConfig: "default-model-config"
    systemMessage: |
      You are a PolicyGuard Security Agent. Use the PolicyGuard tools to:
      - validate_action: Check if actions are allowed
      - register_agent: Register new agents
      - create_policy: Define security rules
      - get_compliance_status: View compliance dashboard
    tools:
    - type: McpServer
      mcpServer:
        name: policyguard
        kind: RemoteMCPServer
        apiGroup: kagent.dev
        toolNames:
        - validate_action
        - register_agent
        - create_policy
        - get_audit_log
        - get_compliance_status
        - report_incident
EOF

Verified Working

# Check status
$ kubectl get agents,remotemcpservers -n kagent
NAME                TYPE          READY   ACCEPTED
policyguard-agent   Declarative   True    True

NAME          PROTOCOL          URL                                       ACCEPTED
policyguard   STREAMABLE_HTTP   http://policyguard.policyguard:8000/mcp   True

# Invoke agent via CLI
$ kagent invoke -t "Get compliance status" --agent policyguard-agent

Response:
- Security Posture: Healthy
- Total Policies: 1, Enabled: 1  
- Total Incidents: 0
- Agents Registered: 0

# Test validation
$ kagent invoke -t "Can test-agent delete the database?" --agent policyguard-agent

Response:
The action delete_database was not allowed for test-agent.
Reason: Delete operations require admin trust level.

Access kagent UI

kubectl port-forward -n kagent svc/kagent-ui 8080:8080
# Open http://localhost:8080

Security Model

Trust Levels

Level

Score

Use Case

low

1

Unknown agents, read-only

medium

2

Verified agents

high

3

Trusted agents

admin

4

Full access

Policy Rules

{
  "condition": {
    "tool_pattern": "delete_*",
    "trust_level_below": "admin"
  },
  "action": "deny",
  "message": "Delete requires admin"
}

Evaluation Order

  1. Agent suspended? → DENY

  2. Tool in denied list? → DENY

  3. Tool not in allowed list? → DENY

  4. Policy match? → Apply rule

  5. Default → ALLOW


Project Structure

policyguard/
├── helm/
│   └── policyguard/          # Helm chart
│       ├── Chart.yaml
│       ├── values.yaml
│       └── templates/
├── src/
│   ├── main.py               # Entry point
│   ├── core/
│   │   ├── server.py         # MCP server
│   │   └── utils.py          # Utilities
│   └── tools/
│       ├── validate_action.py
│       ├── register_agent.py
│       ├── create_policy.py
│       ├── get_audit_log.py
│       ├── get_compliance_status.py
│       └── report_incident.py
├── tests/
│   └── test_tools.py         # 16 unit tests
├── Dockerfile
├── pyproject.toml
└── README.md

Technologies Used

  • FastMCP - Python MCP server SDK

  • Pydantic - Data validation

  • Helm - Kubernetes packaging

  • pytest - Testing


Future Improvements

  • Database backend (PostgreSQL)

  • Web dashboard UI

  • Prometheus metrics

  • RBAC integration

  • Policy versioning


License

MIT License


Hackathon

MCP_HACK//26 - "MCP & AI Agents Starter Track"

This is my first MCP server project! I built PolicyGuard to learn:

  • How MCP servers work

  • How to expose tools to AI agents

  • How to deploy MCP servers on Kubernetes

  • How security/governance can be implemented at the MCP layer

What I Built

  • ✅ 6 MCP tools for security governance

  • ✅ Policy engine with pattern matching

  • ✅ Trust level system

  • ✅ Audit logging and incident tracking

  • ✅ Helm chart for Kubernetes

  • ✅ 16 unit tests

  • ✅ kagent integration examples

Available Tools

6 tools
create_policyA

Create or update a security policy for agent governance.

Policies define rules that control what agents can do. Each policy contains conditions and actions (allow/deny/require_approval).

Args: policy_id: Unique identifier for the policy (e.g., "prod-db-access") name: Human-readable name (e.g., "Production Database Access Control") description: Description of what this policy controls rules: JSON array of rule objects. Each rule has: - condition: Object with matching criteria - tool_pattern: Glob pattern for tool names (e.g., "database_*") - action_type: Type of action (e.g., "tool_call") - trust_level_at_least: Minimum trust level required - trust_level_below: Trigger if trust below this level - action: "allow", "deny", or "require_approval" - message: Message to show when rule matches priority: Higher priority policies are evaluated first (default: 100) enabled: Whether the policy is active (default: true)

Returns: JSON string with creation result: - success: Whether creation succeeded - policy_id: The policy's ID - message: Status message

Example: create_policy( policy_id="prevent-deletions", name="Prevent Dangerous Deletions", description="Block delete operations for non-admin agents", rules='[{"condition": {"tool_pattern": "delete_*", "trust_level_below": "admin"}, "action": "deny", "message": "Delete operations require admin access"}]' )

Inputs: policy_id (required), name (required), description (required), rules (required), +2 more. Returns: result

get_audit_logA

Retrieve audit log entries for compliance and investigation.

The audit log records all action validations, policy violations, and administrative actions performed through Guardian Agent.

Args: agent_id: Filter by specific agent ID (optional) action_type: Filter by action type like "tool_call", "resource_access" (optional) time_range: Time range to query - "1h", "24h", "7d", "30d" (default: "24h") status: Filter by status - "allowed", "denied", or "" for all (optional) limit: Maximum number of entries to return (default: 100)

Returns: JSON string with: - entries: Array of audit log entries - count: Number of entries returned - total: Total entries matching filter (before limit) - time_range: The time range used - filters_applied: Summary of filters used

Example: # Get all denied actions in the last hour get_audit_log(time_range="1h", status="denied")

# Get all actions by a specific agent
get_audit_log(agent_id="prod-agent-01", time_range="7d")

Inputs: agent_id, action_type, time_range, status, +1 more. Returns: result

get_compliance_statusA

Get compliance status and security health metrics.

Generates a compliance report showing policy violations, security incidents, and overall governance health for the specified time period.

Args: time_range: Time range - "1h", "24h", "7d", "30d" (default: "24h") include_incidents: Include active incidents in report (default: true) include_policy_summary: Include policy overview (default: true)

Returns: JSON string with compliance report: - status: Overall status ("healthy", "warning", "critical") - metrics: Key security metrics - incidents: Active security incidents (if requested) - policies: Policy summary (if requested) - recommendations: Suggested actions to improve security

Example: # Get daily compliance status get_compliance_status(time_range="24h")

# Get weekly report with all details
get_compliance_status(time_range="7d", include_incidents=True)

Inputs: time_range, include_incidents, include_policy_summary. Returns: result

register_agentA

Register a new agent with Guardian for security policy evaluation.

Registered agents get proper trust levels and can have custom tool permissions. Unregistered agents are treated as 'low' trust.

Args: agent_id: Unique identifier for the agent (e.g., "prod-assistant-01") name: Human-readable name (e.g., "Production Assistant") description: Description of the agent's purpose trust_level: Trust level - "low", "medium", "high", or "admin" allowed_tools: JSON array of allowed tool patterns (e.g., '["read_*", "query_*"]') denied_tools: JSON array of denied tool patterns (e.g., '["delete_*", "drop_*"]') metadata: JSON object with additional agent metadata

Returns: JSON string with registration result: - success: Whether registration succeeded - agent_id: The agent's ID - message: Status message - warnings: Any warnings about the registration

Example: register_agent( agent_id="data-analyst-01", name="Data Analyst Bot", description="Runs analytical queries on warehouse", trust_level="medium", allowed_tools='["query_*", "read_*"]', denied_tools='["delete_*", "drop_*", "truncate_*"]' )

Inputs: agent_id (required), name (required), description, trust_level, +3 more. Returns: result

report_incidentA

Report a security incident for investigation and tracking.

Use this tool to log security incidents such as policy violations, suspicious agent behavior, or potential security threats.

Args: incident_type: Type of incident: - "policy_violation": Agent violated a security policy - "suspicious_activity": Unusual or potentially malicious behavior - "unauthorized_access": Attempt to access restricted resources - "rate_limit_exceeded": Agent exceeded rate limits - "data_exfiltration": Potential data leak detected - "configuration_error": Security misconfiguration detected - "other": Other security concern severity: Incident severity: - "low": Minor issue, no immediate action needed - "medium": Notable issue, should be reviewed - "high": Serious issue, needs prompt attention - "critical": Emergency, immediate action required description: Detailed description of the incident agent_id: ID of the agent involved (if applicable) evidence: JSON object with supporting evidence/data recommended_action: Suggested remediation steps

Returns: JSON string with: - incident_id: Unique incident identifier - success: Whether the incident was logged - message: Status message - agent_suspended: Whether the agent was auto-suspended

Example: report_incident( incident_type="suspicious_activity", severity="high", description="Agent attempted to access 50 databases in 1 minute", agent_id="rogue-agent-01", evidence='{"databases_accessed": 50, "time_window": "60s"}', recommended_action="Review agent permissions and suspend if needed" )

Inputs: incident_type (required), severity (required), description (required), agent_id, +2 more. Returns: result

validate_actionA

Validate whether an agent can perform a specific action.

This is the PRIMARY security gate. Agents should call this BEFORE performing any sensitive action to ensure compliance with security policies.

Args: action_type: Type of action (e.g., "tool_call", "resource_access", "data_read", "data_write") target: Target of the action (e.g., tool name, resource URI, database name) agent_id: Unique identifier of the requesting agent parameters: JSON string of action-specific parameters (optional) context: Additional context about why this action is needed (optional)

Returns: JSON string with validation result: - action_id: Unique ID for this validation (for audit correlation) - allowed: Whether the action is permitted - require_approval: If true, action needs human approval first - reason: Explanation of the decision - warnings: Any non-blocking warnings

Example: validate_action( action_type="tool_call", target="database_delete", agent_id="prod-agent-01", parameters='{"table": "users"}', context="Cleanup stale records" )

Inputs: action_type (required), target (required), agent_id (required), parameters, +1 more. Returns: result

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A4.3/5.0

    Scored across 6 tools

    Disambiguation5/5

    Each tool has a distinct and clearly defined purpose: create_policy defines policies, get_audit_log retrieves logs, get_compliance_status provides reports, register_agent manages agents, report_incident logs incidents, and validate_action checks permissions. There is no overlap or ambiguity in their functions.

    Naming Consistency5/5

    All tool names follow a consistent verb_noun pattern (e.g., create_policy, get_audit_log, register_agent). The verbs are appropriate and descriptive, and there are no deviations or mixed conventions, making the set highly predictable.

    Tool Count5/5

    With 6 tools, the server is well-scoped for agent governance and security policy management. Each tool serves a clear role in the lifecycle (e.g., policy creation, agent registration, action validation, incident reporting, auditing, and compliance), with no redundant or missing tools.

    Completeness5/5

    The tool set provides complete coverage for the security policy domain: create_policy for policy management, validate_action for enforcement, get_audit_log and get_compliance_status for monitoring, register_agent for agent setup, and report_incident for incident handling. There are no obvious gaps, enabling full agent governance workflows.

    Maintenance

    ActivityNo data
    ResponsivenessOutdated data

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      C
      maintenance
      An enforcement layer that validates AI agent actions against governance policies, including path permissions and content scanning, at runtime. It enables secure, role-based execution of file operations and commands with zero token overhead by processing policies independently from the agent's context.
      87 npm
      3
      MIT
    • A
      license
      A
      quality
      C
      maintenance
      Runtime policy enforcement for AI agents. Evaluate every agent action against your organization's policies before execution, with observe and enforce modes.
      1
      1
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      Enforces deterministic policies on AI agent tool calls, evaluating actions against compliance modules (SOC 2, HIPAA, GDPR, etc.) and returning ALLOW, BLOCK, or CONSTRAIN decisions with an audit trail.
      MIT