Skip to main content

Python SDK for MeshGuard - Governance Control Plane for AI Agents

Project description

MeshGuard Python SDK

PyPI version Python 3.9+ License: MIT

Python SDK for MeshGuard — Governance Control Plane for AI Agents.

Installation

pip install meshguard

With LangChain support:

pip install meshguard[langchain]

Quick Start

from meshguard import MeshGuardClient

# Connect to MeshGuard (free tier available at meshguard.app)
client = MeshGuardClient(
    agent_token="your-agent-token",  # Get your token at meshguard.app
)

# Check if an action is allowed
decision = client.check("read:contacts")
if decision.allowed:
    print("Access granted!")
else:
    print(f"Denied: {decision.reason}")

# Enforce policy (raises PolicyDeniedError if denied)
client.enforce("read:contacts")

# Use context manager for governed code blocks
with client.govern("write:email") as decision:
    # This code only runs if allowed
    send_email(to="user@example.com", body="Hello!")

Pro tip: Need advanced features like SSO, custom policies, or dedicated support? Check out MeshGuard Pro and Enterprise.

Environment Variables

You can configure the client using environment variables:

export MESHGUARD_AGENT_TOKEN="your-agent-token"
export MESHGUARD_ADMIN_TOKEN="your-admin-token"  # For admin operations

# Optional: Override gateway URL (defaults to https://dashboard.meshguard.app)
# export MESHGUARD_GATEWAY_URL="https://meshguard.yourcompany.com"  # Enterprise self-hosted only

Then simply:

from meshguard import MeshGuardClient

client = MeshGuardClient()  # Uses env vars, connects to MeshGuard SaaS

LangChain Integration

Govern Individual Tools

from meshguard import MeshGuardClient
from meshguard.langchain import governed_tool

client = MeshGuardClient()

@governed_tool("read:contacts", client=client)
def fetch_contacts(query: str) -> str:
    """Fetch contacts matching query."""
    return contacts_db.search(query)

# The tool only runs if policy allows "read:contacts"
result = fetch_contacts("John")

Wrap Existing Tools

from langchain.tools import DuckDuckGoSearchRun
from meshguard import MeshGuardClient
from meshguard.langchain import GovernedTool

client = MeshGuardClient()
search = DuckDuckGoSearchRun()

# Wrap the tool with governance
governed_search = GovernedTool(
    tool=search,
    action="read:web_search",
    client=client,
)

result = governed_search.run("MeshGuard AI governance")

Create Governed Agent

from langchain.llms import OpenAI
from langchain.agents import load_tools
from meshguard import MeshGuardClient
from meshguard.langchain import create_governed_agent

client = MeshGuardClient()
llm = OpenAI()
tools = load_tools(["serpapi", "llm-math"], llm=llm)

agent = create_governed_agent(
    llm=llm,
    tools=tools,
    client=client,
    action_map={
        "serpapi": "read:web_search",
        "Calculator": "execute:math",
    },
)

result = agent.run("What is 25 * 4?")

Handle Denied Actions

from meshguard import MeshGuardClient, PolicyDeniedError
from meshguard.langchain import governed_tool

client = MeshGuardClient()

def handle_denial(error, *args, **kwargs):
    return f"Sorry, I can't do that: {error.reason}"

@governed_tool("write:email", client=client, on_deny=handle_denial)
def send_email(to: str, body: str) -> str:
    # Send email...
    return "Email sent!"

# If denied, returns the denial message instead of raising
result = send_email("user@example.com", "Hello!")

Admin Operations

from meshguard import MeshGuardClient

client = MeshGuardClient(admin_token="your-admin-token")

# List agents
agents = client.list_agents()
for agent in agents:
    print(f"{agent.name} ({agent.trust_tier})")

# Create agent
result = client.create_agent(
    name="my-agent",
    trust_tier="verified",
    tags=["production"],
)
print(f"Created agent: {result['id']}")
print(f"Token: {result['token']}")

# List policies
policies = client.list_policies()

# Get audit log
entries = client.get_audit_log(limit=10, decision="deny")

Proxy Requests

Route requests through MeshGuard for automatic governance:

from meshguard import MeshGuardClient

client = MeshGuardClient()

# GET request
response = client.get("/api/contacts", action="read:contacts")

# POST request
response = client.post(
    "/api/emails",
    action="write:email",
    json={"to": "user@example.com", "body": "Hello!"},
)

Error Handling

from meshguard import (
    MeshGuardClient,
    MeshGuardError,
    AuthenticationError,
    PolicyDeniedError,
    RateLimitError,
)

client = MeshGuardClient()

try:
    client.enforce("delete:database")
except PolicyDeniedError as e:
    print(f"Action denied: {e.action}")
    print(f"Policy: {e.policy}")
    print(f"Reason: {e.reason}")
except AuthenticationError:
    print("Invalid or expired token")
except RateLimitError:
    print("Rate limit exceeded")
except MeshGuardError as e:
    print(f"MeshGuard error: {e}")

API Reference

MeshGuardClient

Method Description
check(action) Check if action is allowed (returns PolicyDecision)
enforce(action) Enforce policy (raises PolicyDeniedError if denied)
govern(action) Context manager for governed code blocks
health() Check gateway health
list_agents() List all agents (admin)
create_agent(name, trust_tier, tags) Create agent (admin)
revoke_agent(agent_id) Revoke agent (admin)
list_policies() List policies (admin)
get_audit_log(limit, decision) Get audit entries (admin)

LangChain Integration

Function/Class Description
@governed_tool(action) Decorator for governed tools
GovernedTool(tool, action) Wrapper for existing tools
GovernedToolkit(tools, action_map) Govern multiple tools
create_governed_agent(llm, tools) Create governed agent

License

MIT License - see LICENSE for details.

Links

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

meshguard-0.1.2.tar.gz (135.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

meshguard-0.1.2-py3-none-any.whl (10.4 kB view details)

Uploaded Python 3

File details

Details for the file meshguard-0.1.2.tar.gz.

File metadata

  • Download URL: meshguard-0.1.2.tar.gz
  • Upload date:
  • Size: 135.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.9.25 {"installer":{"name":"uv","version":"0.9.25","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for meshguard-0.1.2.tar.gz
Algorithm Hash digest
SHA256 d3dcce4bd1d8790fcc80743f318f48221c181ddc838501f6d28ff332f03cca7d
MD5 e5ed9eb6b595c1abfcd4c0fd290f6b94
BLAKE2b-256 2b28b14650c5ead307726683a05d1cb2d5a31d677f46d6d4131a8b8207050c74

See more details on using hashes here.

File details

Details for the file meshguard-0.1.2-py3-none-any.whl.

File metadata

  • Download URL: meshguard-0.1.2-py3-none-any.whl
  • Upload date:
  • Size: 10.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.9.25 {"installer":{"name":"uv","version":"0.9.25","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for meshguard-0.1.2-py3-none-any.whl
Algorithm Hash digest
SHA256 a384a333f314e2097bf0f9ac605a8a72433c1ff72b18173e508fd9008b2ad0aa
MD5 5391391c6b25a66f78ee6d6bfcd428e9
BLAKE2b-256 8b8c37662b356d0079b02263a221af3e4d78b17a36d40e0e1370d2dafd6bd8d4

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page