Python SDK for Keycase Agent execution and keyword integration
Project description
Keycase Python Agent
A professional Python SDK for Keycase Agent execution and keyword integration. This agent connects to the Keycase automation platform to execute keyword-based automation flows.
Features
- WebSocket Communication: Real-time connection to Keycase server
- Local Execution Mode: Run execution plans locally without server connection
- Plugin Architecture: Extensible keyword system with auto-discovery
- Robust Execution: Threaded execution with graceful shutdown
- Automatic Reconnection: Exponential backoff with circuit breaker pattern
- Token Management: Automatic token refresh before expiry
- Type Safety: Full type hints throughout codebase
- Cross-Platform: Works on Windows, macOS, and Linux
Prerequisites
Python Version
- Python 3.8 or higher is required
Check your Python version:
python --version
# or
python3 --version
Platform-Specific Setup
Windows
-
Install Python from python.org or via Windows Store
-
Verify pip is installed:
python -m pip --version
-
(Recommended) Create a virtual environment:
python -m venv venv venv\Scripts\activate
-
Install the package:
pip install -e .
macOS
-
Install Python (if not already installed):
# Using Homebrew (recommended) brew install python@3.11 # Or download from python.org
-
(Recommended) Create a virtual environment:
python3 -m venv venv source venv/bin/activate
-
Install the package:
pip install -e .
Linux (Ubuntu/Debian)
-
Install Python and pip:
sudo apt update sudo apt install python3 python3-pip python3-venv
-
(Recommended) Create a virtual environment:
python3 -m venv venv source venv/bin/activate
-
Install the package:
pip install -e .
Linux (RHEL/CentOS/Fedora)
-
Install Python and pip:
# Fedora sudo dnf install python3 python3-pip # RHEL/CentOS 8+ sudo dnf install python39 python39-pip
-
(Recommended) Create a virtual environment:
python3 -m venv venv source venv/bin/activate
-
Install the package:
pip install -e .
Installation
Quick Start
# Clone the repository
git clone https://github.com/TharassKeycase/keycase-python-sdk.git
cd keycase-python-sdk
# Create and activate virtual environment
python3 -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
# Install the package
pip install -e .
Development Installation
For development with testing and code quality tools:
pip install -e ".[dev]"
This installs additional dependencies: pytest, black, isort, mypy, flake8, and more.
Configuration
The agent uses AgentToken-based authentication. Get your AgentToken from the Keycase platform.
Required Environment Variables
| Variable | Description | Example |
|---|---|---|
HTTP_URL |
HTTP API base URL | http://localhost:3000/api |
AGENT_TOKEN |
AgentToken from platform (must start with agt_) |
agt_NW6KGfsl3Re... |
AGENT_NAME |
Unique agent name within organization | my-agent-01 |
Optional Environment Variables
| Variable | Description | Example |
|---|---|---|
AGENT_VERSION |
Agent version | 1.0.0 |
AGENT_CAPABILITIES |
Comma-separated list of capabilities | selenium,api |
AGENT_TAGS |
Comma-separated tags for categorization | production,windows |
Note: The WebSocket URL (
wsUrl) and Agent ID (agentId) are now returned dynamically from the authentication response. You no longer need to configure these manually.
Setting Environment Variables
Windows (Command Prompt)
set HTTP_URL=http://localhost:3000/api
set AGENT_TOKEN=agt_your_token_here
set AGENT_NAME=my-agent-01
set AGENT_VERSION=1.0.0
set AGENT_CAPABILITIES=selenium,api
set AGENT_TAGS=production,windows
Windows (PowerShell)
$env:HTTP_URL = "http://localhost:3000/api"
$env:AGENT_TOKEN = "agt_your_token_here"
$env:AGENT_NAME = "my-agent-01"
$env:AGENT_VERSION = "1.0.0"
$env:AGENT_CAPABILITIES = "selenium,api"
$env:AGENT_TAGS = "production,windows"
macOS / Linux
export HTTP_URL="http://localhost:3000/api"
export AGENT_TOKEN="agt_your_token_here"
export AGENT_NAME="my-agent-01"
export AGENT_VERSION="1.0.0"
export AGENT_CAPABILITIES="selenium,api"
export AGENT_TAGS="production,windows"
Or create a .env file in the project root:
HTTP_URL=http://localhost:3000/api
AGENT_TOKEN=agt_your_token_here
AGENT_NAME=my-agent-01
AGENT_VERSION=1.0.0
AGENT_CAPABILITIES=selenium,api
AGENT_TAGS=production,windows
Usage
Command Line
# Start the agent (uses environment variables)
keycase-agent
# Or run directly
python main.py
Programmatic Usage
WebSocket Mode (Server Connection)
from keycase_agent import KeycaseAgent, load_config, load_keywords
# Load keywords from directory
load_keywords()
# Load configuration from environment
config = load_config()
# Create and start agent
agent = KeycaseAgent(config)
agent.start()
Local Mode (Standalone Execution)
from keycase_agent import ExecutionManager, load_keywords
# Load keywords
load_keywords('path/to/keywords')
# Create manager in local mode
manager = ExecutionManager(mode='local')
# Execute plan (dict or JSON string)
execution_plan = {
"keywordInstances": [...],
"flows": [...]
}
results = manager.execute_local(execution_plan)
print(results)
See LOCAL_EXECUTION.md for complete local mode documentation.
Creating Custom Keywords
Keywords are Python functions decorated with @keyword. You can also annotate parameters with @param, @input_param, and @output_param for documentation and validation.
Basic Keyword
from keycase_agent import keyword
@keyword("Add Numbers")
def add_numbers(a: int, b: int) -> dict:
"""Add two numbers together."""
return {"sum": a + b}
Keyword with Parameter Annotations
from keycase_agent import keyword, input_param, output_param
@keyword("Calculate Sum")
@input_param("a", type="number", required=True, description="First number")
@input_param("b", type="number", required=True, description="Second number")
@output_param("sum", type="number", description="The sum of a and b")
@output_param("product", type="number", description="The product of a and b")
def calculate(a: float, b: float) -> dict:
"""Calculate sum and product of two numbers."""
return {
"sum": a + b,
"product": a * b,
}
Parameter Decorator Options
| Option | Type | Description | Status |
|---|---|---|---|
name |
str | Parameter name (must match function argument for inputs) | Supported |
direction |
str | "input" or "output" |
Supported |
default |
any | Default value if not provided | Supported |
description |
str | Human-readable description | Supported |
choices |
list | List of allowed values (for dropdowns) | Supported |
type |
str | Parameter type ("string", "number", etc.) |
Planned |
required |
bool | Whether the parameter is required | Planned |
Note: Options marked as "Planned" are accepted by the SDK for forward compatibility but are not yet enforced by the Keycase platform. They will be fully supported in a future release. See ROADMAP.md for details.
Parameter with Choices (Dropdown)
@keyword("Set Log Level")
@input_param("level", type="string", required=True,
description="Logging level",
choices=["DEBUG", "INFO", "WARNING", "ERROR"])
def set_log_level(level: str) -> dict:
return {"status": "ok"}
Getting Keyword Schemas
You can retrieve the schema for documentation or UI generation:
from keycase_agent import get_keyword_schema, get_all_keyword_schemas
# Get schema for a specific keyword
schema = get_keyword_schema(calculate)
print(schema)
# {
# "name": "Calculate Sum",
# "function": "calculate",
# "params": [
# {"name": "a", "direction": "input", "type": "number", "required": true, ...},
# ...
# ]
# }
# Get all registered keyword schemas
all_schemas = get_all_keyword_schemas()
Place your keyword files in a folder and load them with load_keywords('your_folder').
See the examples/ folder for sample keyword implementations.
Architecture
┌─────────────────────────────────────────────────────────┐
│ KeycaseAgent │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────────┐ │
│ │ AuthService │ │ WebSocket │ │ ExecutionManager│ │
│ │ │ │ Client │ │ │ │
│ └─────────────┘ └─────────────┘ └─────────────────┘ │
│ │ │ │ │
│ └────────────────┼──────────────────┘ │
│ │ │
│ ┌───────▼───────┐ │
│ │ Keyword │ │
│ │ Registry │ │
│ └───────────────┘ │
└─────────────────────────────────────────────────────────┘
Core Components
| Component | Description |
|---|---|
| KeycaseAgent | Main orchestrator managing connections and execution |
| ExecutionManager | Handles threaded execution of keyword flows |
| AuthService | Manages authentication and automatic token refresh |
| WebSocketClient | Handles real-time communication with reconnection |
| KeywordRegistry | Stores and retrieves registered keyword functions |
Development
Running Tests
# Run all tests
pytest
# Run with coverage report
pytest --cov=keycase_agent --cov-report=html
# Run specific test file
pytest tests/test_execution_manager.py -v
Code Quality
# Format code
black keycase_agent/
# Sort imports
isort keycase_agent/
# Type checking
mypy keycase_agent/
# Linting
flake8 keycase_agent/
# Run all checks
black keycase_agent/ && isort keycase_agent/ && mypy keycase_agent/ && flake8 keycase_agent/
Building Distribution
# Install build tools
pip install build
# Build package
python -m build
# Install built package
pip install dist/keycase_agent_sdk-0.1.0-py3-none-any.whl
Troubleshooting
Common Issues
"No module named 'keycase_agent'"
Make sure you've installed the package:
pip install -e .
If using a virtual environment, ensure it's activated.
"Connection refused" or WebSocket errors
- Verify the Keycase server is running
- Check
HTTP_URLis correct - Ensure no firewall is blocking the connection
- The WebSocket URL is returned from authentication - verify the server is returning a valid
wsUrl
"Authentication failed"
- Verify
AGENT_TOKENis correct and starts withagt_ - Check the token has not been revoked on the platform
- Ensure
AGENT_NAMEis unique within your organization - Verify the token has the correct permissions
Keywords not found
- Ensure keywords are in the
keywords/directory - Check the
@keyworddecorator is applied - Verify keyword names match the execution plan
License
This project is licensed under the MIT License - see the LICENSE file for details.
Support
- Documentation: docs.keycase.io
- Issues: GitHub Issues
- Email: support@keycase.io
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file keycase_agent_sdk-0.1.0b3.tar.gz.
File metadata
- Download URL: keycase_agent_sdk-0.1.0b3.tar.gz
- Upload date:
- Size: 48.3 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
73565e1733196d2ba2453f9e8cbae4600f29d915d437a2b61a569879d40ad2e9
|
|
| MD5 |
f81e0d3496a4abe575614443fa59cdea
|
|
| BLAKE2b-256 |
04d92384d0b3c2f32b3493046ea7902fa451a43dff5e904a9facb85ae4df24e0
|
File details
Details for the file keycase_agent_sdk-0.1.0b3-py3-none-any.whl.
File metadata
- Download URL: keycase_agent_sdk-0.1.0b3-py3-none-any.whl
- Upload date:
- Size: 43.0 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
b2b6c3b126d494f374f5b0f9dbb911ba4700006b9f1155717a07c8b1dcf81b76
|
|
| MD5 |
33e22e3142ae2ee64ec321cc7ef4e1c5
|
|
| BLAKE2b-256 |
9b21be36f70910c8d202c621e40e725f9db11844d354492bd86b78b292fc550c
|