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.10 or higher is required
Check your Python version:
python --version
# or
python3 --version
Platform-Specific Setup
-
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 .
-
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 .
-
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 .
-
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
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
$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"
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.
Attachments (screenshots, videos, logs)
Keywords can attach files to the run. They are shown with the step (or the whole
flow) in the Keycase run results - e.g. a screenshot of the failing step.
Keycase is technology agnostic: attach() takes anything your tool produces -
a file path, bytes, or a binary file-like object - from a browser, mobile or
desktop driver, an HTTP client, a CLI tool or a logger.
from keycase_agent import keyword, attach
@keyword("Check Dashboard")
def check_dashboard() -> dict:
...
attach("dashboard.png") # a file on disk
attach(image_bytes, name="after-login.png") # raw bytes
attach(response_body, name="response.json") # JSON / text logs
attach("session.webm", scope="flow") # the whole flow
return {}
| Argument |
Default |
Description |
source |
- |
File path, bytes, or binary file-like object |
name |
file name |
Display name |
kind |
from type |
SCREENSHOT, VIDEO, TRACE, LOG or OTHER |
mime_type |
from name / content |
Content type |
scope |
"step" |
"step" or "flow" |
wait |
False |
Block until uploaded and return the attachment id |
timeout |
none |
With wait=True, the maximum seconds to wait |
Allowed types: PNG, JPEG, WebP, GIF (10 MB) · WebM, MP4 (100 MB) ·
ZIP, e.g. traces (100 MB) · plain text, JSON (10 MB). Per run: 500 files, 1 GB.
Notes:
-
Background uploads: the file is read and validated immediately (you may
delete it right after), then uploaded in the background so the keyword is not
slowed down. Use attach(..., wait=True) to block and get the attachment id.
-
Best effort: attach() never raises. If a file is invalid or the upload
fails, the reason is logged and the step continues.
-
The run waits for pending uploads before it sends its results (the server only
accepts attachments while the run is in progress). After
ExecutionManager(attachment_drain_timeout=300) seconds the results are sent
anyway and the remaining uploads are dropped, with a warning.
-
Requires a Keycase server with attachment support. Older servers are detected
and attachments are switched off for the run after one log message.
-
Local mode (ExecutionManager(mode="local")): nothing is uploaded; files
are saved under keycase-results/<run_id>/flow-<id>/step-<n>/ (or flow/)
and listed per flow in the results. Choose the folder with
ExecutionManager(mode="local", attachments_dir="my-folder"), or pass
attachments_dir=None to ignore attachments.
results = manager.execute_local(plan)
for flow in results["result"]["flowResults"]:
for a in flow.get("attachments", []):
print(a["stepOrder"], a["kind"], a["path"])
Capture evidence when a step fails
@OnStepFailure runs when a keyword raises, while the failed step is still the
current step, so anything you attach() there lands on that step. Capture
whatever your tooling offers; the hook is the same for every technology:
from keycase_agent import OnStepFailure, attach
@OnStepFailure
def capture_evidence(failure):
# failure: flow_id, flow_name, step_order, keyword_name, instance_name, error, message
attach(my_driver.screenshot(), name=f"{failure.keyword_name}.png")
attach("\n".join(recent_log_lines).encode(), name="failure.log")
The hook may also take no argument. It only runs for errors raised by a keyword
(not for plan problems such as a missing keyword), and an error inside the hook
is logged without changing the step's result.
Step results
Every flow result includes the outcome and duration of each step, measured by
the agent, so Keycase can show how long each step took:
"stepResults": [
{"stepOrder": 0, "status": "PASSED", "durationMs": 405.2},
{"stepOrder": 1, "status": "FAILED", "durationMs": 30012.0},
{"stepOrder": 2, "status": "NOT_RUN", "durationMs": null}
]
No code is needed in your keywords. Older Keycase servers that do not accept
stepResults are handled automatically: the result is sent again without it.
Step values
Each step also reports the values the keyword actually received (inputs) and
returned (outputs) - after environment variables, connections from earlier
steps and value resolvers - so the run results show e.g.
{{$randomEmail}} → emma.bakker.k3f9a2@example.com.
Value resolvers turn configured values into real ones before a keyword runs.
The keyword receives the resolved values, and those are what is reported:
from keycase_agent import ValueResolver
@ValueResolver
def generated_values(inputs, step): # step: flow, step order, keyword, instance
return {name: my_generator.resolve(value) for name, value in inputs.items()}
An error raised by a resolver fails the step with its message.
report_value() reports a value produced inside a keyword that is not a
declared output:
from keycase_agent import keyword, report_value
@keyword("Place Order")
def place_order() -> dict:
...
report_value("orderNumber", page.locator("#order-no").inner_text())
return {}
Sensitive values are never sent, only their name. A value counts as
sensitive when the parameter is marked sensitive in Keycase (keyword parameter
or environment variable), declared with sensitive=True
(@input_param("pin", sensitive=True)), named like a secret (password,
token, apiKey, authorization, ...), or reported with
report_value(..., sensitive=True). Values are limited to 2,000 characters;
objects that are not JSON are reported as text.
Architecture