Skip to main content

AgentShield Python SDK

Security and governance for AI agents.

Installation

pip install agentshield

Quick Start

from agentshield import AgentShield

# Initialize with your API key
shield = AgentShield(api_key="as_live_your_key_here")

# Option 1: Decorator (recommended)
@shield.protect(scope="email.send")
def send_email(to: str, subject: str, body: str):
    # Your email sending logic here
    # This will only execute if AgentShield approves the action
    pass

# Option 2: Manual verification
result = shield.verify(scope="files.read")
if result["allowed"]:
    read_files()
else:
    print(f"Blocked: {result['reason']}")

Async Support

import asyncio
from agentshield import AgentShield

shield = AgentShield(api_key="as_live_xxx")

# Async decorator
@shield.protect(scope="api.call")
async def make_api_call():
    # Your async logic here
    pass

# Async context manager
async def main():
    async with shield.action(scope="database.write") as ctx:
        await write_to_database()
        ctx.report_success({"rows_affected": 10})

asyncio.run(main())

Handling Approvals

Some actions require human approval. You can handle this in two ways:

Option 1: Auto-wait for approval

shield = AgentShield(
    api_key="as_live_xxx",
    auto_wait_approval=True,  # Wait up to 5 minutes for approval
    approval_timeout=300
)

@shield.protect(scope="payment.process")
def process_payment(amount: float):
    # This will block until a human approves or rejects
    # the action in the AgentShield dashboard
    pass

Option 2: Handle approval manually

from agentshield import AgentShield, ApprovalRequiredError

shield = AgentShield(api_key="as_live_xxx")

try:
    result = shield.verify(scope="email.send")
    if result["allowed"]:
        send_email()
    elif result.get("pending_approval"):
        approval_id = result["approval_id"]
        print(f"Waiting for approval: {approval_id}")
        # Check dashboard or wait...
        approved = await shield.wait_for_approval(approval_id, timeout=60)
        if approved:
            send_email()
except ApprovalRequiredError as e:
    print(f"Need approval: {e.approval_id}")

Error Handling

from agentshield import (
    AgentShield,
    NotAuthorizedError,
    RateLimitError,
    ApprovalRequiredError
)

shield = AgentShield(api_key="as_live_xxx")

try:
    @shield.protect(scope="code.execute")
    def run_code():
        exec(user_code)
    
    run_code()

except NotAuthorizedError as e:
    print(f"Not authorized: {e.scope} - {e.reason}")

except RateLimitError as e:
    print(f"Rate limited on {e.scope}")
    if e.retry_after:
        print(f"Retry after {e.retry_after} seconds")

except ApprovalRequiredError as e:
    print(f"Needs approval: {e.approval_id}")

Configuration

shield = AgentShield(
    api_key="as_live_xxx",
    base_url="https://api.agentshield.io",  # Custom API URL
    timeout=30.0,  # Request timeout in seconds
    auto_wait_approval=False,  # Auto-wait for approvals
    approval_timeout=300  # Max time to wait for approval
)

Threat Intelligence

AgentShield includes built-in threat detection and reporting.

Detect Threats in Content

# Analyze user input for prompt injection, social engineering, etc.
result = shield.detect_threats(user_input)

if result["detected"]:
    print(f"⚠️ Threat detected: {result['threat_type']}")
    print(f"Confidence: {result['confidence']}")
    print(f"Patterns: {result['patterns_matched']}")

Check Blacklist

# Check if an agent is known to be malicious
result = shield.check_blacklist("agent_xyz")

if result["is_blacklisted"]:
    print(f"🚫 Agent is blacklisted!")
    print(f"Threat count: {result['threat_count']}")
    for threat in result["threats"]:
        print(f"  - {threat['type']}: {threat['evidence']}")

Report Threats

# Report a malicious agent to the community blacklist
shield.report_threat(
    agent_id="malicious_agent_123",
    threat_type="prompt_injection",  # or: credential_theft, impersonation, spam, etc.
    severity="high",  # low, medium, high, critical
    evidence="Attempted to override system prompt with 'ignore all instructions'",
    source_ip="192.168.1.1",  # optional
    context={"conversation_id": "abc123"}  # optional
)

Threat Types

Type Description
prompt_injection Attempts to override system instructions
credential_theft Trying to extract API keys/passwords
impersonation Pretending to be another agent/user
spam Excessive or unwanted communications
data_exfiltration Unauthorized data extraction
social_engineering Manipulation tactics
coordinated_attack Multi-agent attack patterns
other Other malicious behavior

Async Methods

All methods have async versions:

# Sync
result = shield.verify(scope="email.send")
result = shield.check_blacklist("agent_id")
result = shield.detect_threats("content")
shield.report_threat(agent_id="...", threat_type="...")

# Async
result = await shield.verify_async(scope="email.send")
result = await shield.check_blacklist_async("agent_id")
result = await shield.detect_threats_async("content")
await shield.report_threat_async(agent_id="...", threat_type="...")

License

MIT

Metadata

Release files for nextriad-agentshield 0.2.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for nextriad-agentshield 0.2.0
File Size Uploaded
nextriad_agentshield-0.2.0.tar.gz 16.1 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for nextriad-agentshield 0.2.0
File Interpreter ABI Platform
nextriad_agentshield-0.2.0-py3-none-any.whl Python 3 none any Details

Total release size: 30.3 kB

Release files / nextriad_agentshield-0.2.0.tar.gz

Download URL nextriad_agentshield-0.2.0.tar.gz
Size 16.1 kB
Tags Source
SHA-256 checksum
How to use checksums
53792cff41ae4aa539cd96ecfa751b5157cc13a9f037e1a273b63f5c720f2f59
BLAKE2b-256 checksum
How to use checksums
d21a613a23c93ebe379eb295b8301c062fc8c898eed33ea72a667f6036ba3e5b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.9.6

Release files / nextriad_agentshield-0.2.0-py3-none-any.whl

Download URL nextriad_agentshield-0.2.0-py3-none-any.whl
Size 14.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
87ade0f83800605a91fa98eecb2a110cd7dd72b5bf64e84b99fe06982f04129e
BLAKE2b-256 checksum
How to use checksums
8c07433d4aca8c156fd89653cf7c54c12faf69931f3c273d009cc7effa5a74a1
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.9.6

Release history Release notifications | RSS feed

This release

0.2.0 This release

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page