Observed since 20 Oct, 23:22 UTC
No superseded metadata states collected. Unchanged observations do not create new revisions.
Python SDK for the AgentShield API - Runtime security for agentic AI applications.
Python SDK and CLI for the AgentShield API - Runtime security for agentic AI applications.
Modern AI agents often need to interact with the outside world (like calling APIs or running code) to complete tasks. However, allowing an AI agent unrestricted ability to perform these actions can be risky. It might:
AgentShield acts as a safety checkpoint for your AI agent.
It's useful whenever your agent is about to perform an action that could potentially carry risk. Specifically:
os, using eval, accessing sensitive files) based on security policies.Think of it like a security guard asking "Are you sure you should do that?" before the agent takes a potentially dangerous step.
AgentShield works proactively, meaning it performs its check before the risky action happens. Here's the flow when using the SDK:
https://api.example.com/data" or "I need to run this code: import os; os.remove('file')").shield.guarded_get(url=...) for API calls.shield.safe_execute(code_snippet=...) for code execution checks.url string for guarded_get or the code_snippet string for safe_execute) and sends it to the deployed AgentShield API's /evaluate endpoint, including its API key for authentication.guarded_get, it then proceeds to make the actual HTTP request to the target URL. For safe_execute, it simply returns, indicating the check passed (it doesn't run the code itself).AgentShieldError, immediately stopping the process. The risky API call is not made, and the code check indicates it should not be executed. The error includes details about which policy caused the block.This entire check happens between the agent's intention to act and the actual execution of that action.
The agentshield-sdk package includes both the Python SDK for your agent code and the agentshield command-line tool for managing your user account and API keys.
Install the SDK using pip:
pip install agentshield-sdk
AgentShield requires an API key to authenticate requests from your agent to the security service. You can now manage your account and generate API keys yourself using the included agentshield CLI tool.
Open your terminal and run the register command. You will be prompted for a username, email, and password (min 8 characters).
agentshield register
Once registered, log in to your account. This will save a session token locally (typically in ~/.agentshield/config.json) allowing you to manage keys.
agentshield login
Now you can generate one or more API keys for your agents. You can optionally add a description to help you remember what each key is for.
# Example with description
agentshield keys create -d "My Test Agent v1 Key"
# Example without description
agentshield keys create
---> IMPORTANT: <--- The command will output your new API key (e.g., ask_...). Copy this key immediately and store it securely (e.g., in an environment variable or secret manager). You cannot retrieve the full key again after this step. You can list your keys later (agentshield keys list) to see their ID, prefix, and description, but not the full key.
Now that you have generated an API key via the CLI, you can use it to initialize the AgentShield client in your Python agent code.
import os
import asyncio
import httpx # SDK uses httpx; import it if handling its specific exceptions
from agentshield_sdk.client import AgentShield, AgentShieldError
# --- Configuration ---
# Your unique API Key obtained via the 'agentshield keys create' command
# Best practice: Load key from environment variable or secure storage
# Example: export AGENTSHEILD_API_KEY="ask_YOUR_GENERATED_KEY_HERE"
api_key = os.environ.get("AGENTSHEILD_API_KEY")
# The URL where the AgentShield API service is deployed
# Use the official public URL unless self-hosting
service_url = "[https://agentshield-api-service-338863748406.us-central1.run.app](https://agentshield-api-service-338863748406.us-central1.run.app)"
# Optional: An identifier for the agent using the SDK
agent_id = "my_example_agent_v1"
if not api_key:
print("ERROR: Please set the AGENTSHEILD_API_KEY environment variable.")
# In a real agent, handle missing key appropriately
exit()
# --- Initialize Client ---
# You only need to do this once for your agent instance
try:
shield = AgentShield(
api_key=api_key,
service_url=service_url,
agent_id=agent_id,
timeout=15.0 # Optional: Default timeout for calls TO AgentShield (seconds)
)
except ValueError as e:
print(f"ERROR: Configuration error initializing AgentShield: {e}")
# Handle configuration errors
exit()
# --- Example: Guarded GET request ---
async def make_guarded_request():
url_to_check = "[https://httpbin.org/get](https://httpbin.org/get)" # A test URL
print(f"\nChecking if GET request to {url_to_check} is allowed...")
try:
# This method first calls AgentShield's /evaluate endpoint.
# If allowed, it then proceeds to make the actual GET request using httpx.
response = await shield.guarded_get(
url=url_to_check,
headers={"X-Custom-Header": "MyAgent"}, # Example: Headers for the *target* URL
timeout=20.0 # Optional: Timeout for the call to the *target* URL
)
# If we reach here, the request was allowed by AgentShield
print(f"Request allowed by AgentShield! Status Code from target: {response.status_code}")
# Process the actual response from the target
# data = response.json()
# print(f"Data received: {data}")
except AgentShieldError as e:
# If blocked by AgentShield policy or API communication fails
print(f"Request BLOCKED or SDK Error! Reason: {e} (Details: {e.policy_details})")
# Agent should NOT proceed with the request
except ValueError as e:
# Handle invalid input like bad URLs passed to the SDK
print(f"Input Error: {e}")
except httpx.TimeoutException:
# Handle timeout contacting the *target* URL (after allow)
print(f"Request to {url_to_check} timed out.")
except httpx.RequestError as e:
# Handle network errors contacting the *target* URL (after allow)
print(f"Network error contacting {url_to_check}: {e}")
except Exception as e:
# Handle any other unexpected errors
print(f"An unexpected error occurred: {e}")
# --- Example: Safe Execute Check ---
async def check_code_execution():
safe_code = "print('This is safe code.')\nx = 1 + 2"
dangerous_code = "import os\nos.system('echo potentially harmful')"
print(f"\nChecking if safe code is allowed...")
try:
# This calls /evaluate but DOES NOT run the code
await shield.safe_execute(code_snippet=safe_code)
print("Check ALLOWED for safe code. (Agent would execute it now)")
# Agent would proceed to execute 'safe_code' here using its own method
except AgentShieldError as e:
print(f"Check BLOCKED for safe code unexpectedly! Reason: {e} (Details: {e.policy_details})")
except Exception as e:
print(f"An unexpected error occurred: {e}")
print(f"\nChecking if dangerous code is allowed...")
try:
# This calls /evaluate but DOES NOT run the code
await shield.safe_execute(code_snippet=dangerous_code)
print("Check ALLOWED for dangerous code unexpectedly! (Agent should NOT execute this)")
except AgentShieldError as e:
print(f"Check BLOCKED for dangerous code as expected. Reason: {e} (Details: {e.policy_details})")
# Agent should NOT execute 'dangerous_code'
except Exception as e:
print(f"An unexpected error occurred: {e}")
# Run the examples
async def run_examples():
await make_guarded_request()
await check_code_execution()
if __name__ == "__main__":
# Ensure you have a valid API key set before running the test
if api_key:
asyncio.run(run_examples())
else:
print("Skipping example run: API key not configured.")
agentshield)The agentshield-sdk package includes a command-line tool, agentshield, for managing your user account and API keys required by the SDK.
The CLI interacts with the deployed AgentShield API service. By default, it uses https://agentshield-api-service-338863748406.us-central1.run.app.
Login sessions are stored locally (typically ~/.agentshield/config.json).
agentshield --help: Shows the main help message and lists all commands.agentshield --version: Shows the installed package version.agentshield register: Register a new user account. Prompts for username, email, and password.agentshield register
agentshield login: Log in to your account. Prompts for email and password. Saves a session token locally.agentshield login
agentshield logout: Log out by deleting the locally stored session token.agentshield logout
agentshield keys list: List all your existing API keys, showing their ID, prefix, status, creation date, and description.agentshield keys list
agentshield keys create [-d DESCRIPTION]: Generate a new API key.
# Create with description
agentshield keys create -d "My Production Agent Key"
# Create without description
agentshield keys create
agentshield keys delete <KEY_ID>: Permanently delete an API key using its numeric ID (obtained from keys list). You will be asked for confirmation.agentshield keys delete 123
AgentShield comes with a set of default blocking policies enabled to provide baseline protection. These checks are performed before the agent executes an API call (guarded_get) or runs code (safe_execute).
Here's a summary of what the currently active default policies detect and block, with links to relevant OWASP Top 10 for LLM Applications items:
Code Execution Risks Blocked by Default:
os module or using os.system/os.popen. (LLM05, LLM06)subprocess module. (LLM05, LLM06)shutil or specific os file deletion/modification functions. (LLM06)socket module. (LLM06, LLM03)open() common sensitive file paths (like /etc/passwd, SSH keys, cloud credentials, .env). (LLM02, LLM06); or && followed by risky commands like rm, wget, curl). (LLM01, LLM05, LLM06)eval() Usage: Blocks code using the eval() function. (LLM05, LLM06)exec() Usage: Blocks code using the exec() function. (LLM05, LLM06)pickle Usage: Blocks code importing or using pickle.load/loads to prevent unsafe deserialization. (LLM03, LLM04)API Call Risks Blocked by Default:
localhost, 127.0.0.1, or common cloud provider metadata service endpoints (GCP, AWS, Azure). (LLM06)10.x.x.x, 192.168.x.x). (LLM06)http://. (LLM02, LLM06)(Note: Any policies added, removed, or modifed will be updated in this documentation)
Instantiate the client with your API key and the service URL.
from agentshield_sdk.client import AgentShield
shield = AgentShield(
api_key: str, # Your mandatory API key from the admin
service_url: str, # Mandatory URL of the AgentShield API service
agent_id: str = "sdk_agent_default", # Optional identifier for your agent
timeout: float = 10.0 # Optional default timeout for calls TO the AgentShield API itself
)
async guarded_get(url: str, **kwargs) -> httpx.Response
Checks if a GET request to the specified url is permitted by AgentShield policies before executing it using httpx.
url (str): The target URL the agent intends to call.**kwargs: Any additional keyword arguments accepted by httpx.get (e.g., headers, params, timeout). The timeout kwarg here applies to the request to the target URL.httpx.Response object from the target URL if the request is allowed by AgentShield and the request to the target is successful.AgentShieldError: If the action is blocked by an AgentShield policy or if communication with the AgentShield API fails (check policy_details attribute for more info).ValueError: If the provided url format is invalid.httpx.TimeoutException: If the request to the target URL times out.httpx.RequestError: For other network errors contacting the target URL (after being allowed).async safe_execute(code_snippet: str)
Checks if executing a Python code_snippet (string) is permitted by AgentShield policies.
code_snippet (str): The Python code the agent intends to execute.None if the check indicates the code is allowed.AgentShieldError: If code execution is blocked by an AgentShield policy or if communication with the AgentDownload counts and popularity will appear here as the collector receives them.
| Version | Published | Direct dependencies | Open version |
|---|---|---|---|
| 0.2.1 | 5 May 2025 | 3 |
This describes our collected data; it is not a security assessment.
Observed since 20 Oct, 23:22 UTC
No superseded metadata states collected. Unchanged observations do not create new revisions.
package:fe76a42f9be67a9ad2c82e617509c2c50d30667cc016f46e5923c3d87d665bb6