Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Prefer a profiles file (~/.config/zedcloud/config.toml); see docs/getting-started.md.
# These variables are the fallback when no profile is selected.

# Select a profile from the profiles file instead of the variables below.
# ZEDCLOUD_PROFILE=acme-prod

ZEDCLOUD_BASE_URL=https://zedcontrol.zededa.net

# Either a session/API token…
ZEDCLOUD_TOKEN=
# …or username/password (the SDK logs in and re-logs in on expiry).
# ZEDCLOUD_USERNAME=
# ZEDCLOUD_PASSWORD=
# ZEDCLOUD_ENTERPRISE=

# Optional: X-API-KEY for the Kubernetes service (defaults to the session token).
# ZEDCLOUD_API_KEY=

# Optional tuning.
# ZEDCLOUD_TIMEOUT=30
# ZEDCLOUD_MAX_RETRIES=3
# ZEDCLOUD_VERIFY=true # false, or a CA bundle path

# MCP server, env-only mode: allow writes for the single "env" tenant.
# ZEDCLOUD_MCP_ALLOW_WRITES=false
38 changes: 38 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
name: CI

on:
push:
branches: [main]
pull_request:

jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ["3.10", "3.12", "3.13"]

steps:
- uses: actions/checkout@v4

- name: Install uv
uses: astral-sh/setup-uv@v5
with:
python-version: ${{ matrix.python-version }}

- name: Sync workspace
run: uv sync --all-packages --group dev

- name: Verify OpenAPI codegen is current
run: uv run python scripts/generate.py --check

- name: Ruff
run: |
uv run ruff check packages scripts
uv run ruff format --check packages scripts

- name: Unit tests
run: uv run pytest -q -m "not needs_cloud"

- name: MCP tool list
run: uv run zedcloud-mcp --list-tools
33 changes: 33 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# Byte-compiled / cache
__pycache__/
*.py[cod]
*$py.class
*.egg-info/
.eggs/
dist/
build/
.pytest_cache/
.ruff_cache/
.mypy_cache/
.coverage
htmlcov/

# Virtualenvs / uv
.venv/
uv.lock.bak

# Secrets & local env
.env
.env.*
!.env.example
*.pem
*.key

# Editors / OS
.DS_Store
.idea/
.vscode/

# Generated scratch
/tmp/
*.oa3.json
1 change: 1 addition & 0 deletions .python-version
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
3.12
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2026 vignesh-zededa

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT ANY WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
33 changes: 33 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
.PHONY: generate check-generated install test lint format mcp-list sync specs

UV ?= uv

sync:
$(UV) sync --all-packages --group dev

generate:
$(UV) run python scripts/generate.py

check-generated:
$(UV) run python scripts/generate.py --check

# Refresh openapi/ from the live controller, then regenerate.
specs:
$(UV) run python scripts/fetch_specs.py
$(UV) run python scripts/generate.py

install: sync generate

test:
$(UV) run pytest -q -m "not needs_cloud"

lint:
$(UV) run ruff check packages scripts
$(UV) run ruff format --check packages scripts

format:
$(UV) run ruff format packages scripts
$(UV) run ruff check --fix packages scripts

mcp-list:
$(UV) run zedcloud-mcp --list-tools
133 changes: 132 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,133 @@
# zedcloud-sdk
Python SDK, automation framework, and MCP server for ZEDEDA Zedcloud APIs

Python SDK, pytest automation framework, and MCP server for the
[ZEDEDA Zedcloud API](https://zedcontrol.zededa.net/api/v1/docs/).

| Package | What it is |
|---|---|
| [`zedcloud`](packages/zedcloud) | Typed sync + async client for all 470 operations across the 11 Zedcloud services |
| [`zedcloud-automation`](packages/zedcloud-automation) | Pytest plugin: tenant fixtures, resource cleanup, write guards |
| [`zedcloud-mcp`](packages/zedcloud-mcp) | MCP server so a chat assistant can query and (safely) change a chosen tenant |

## Quick start

```bash
uv sync --all-packages --group dev
```

```python
from zedcloud import ZedcloudClient

with ZedcloudClient(base_url="https://zedcontrol.zededa.net", token="…") as zc:
for node in zc.nodes.iter_edge_node_status(project_name="plant-7"):
print(node.name, node.run_state)

gw = zc.nodes.lookup_edge_node("gw-17") # name or ID
zc.nodes.reboot(gw.id)
zc.nodes.wait_for_edge_node(gw.id) # until RUN_STATE_ONLINE
```

Async works the same way:

```python
from zedcloud import AsyncZedcloudClient

async with AsyncZedcloudClient.from_profile("acme-prod") as zc:
async for app in zc.apps.iter_edge_application_instance_status(run_state="ERROR"):
print(app.name, app.device_name)
```

## Tenants and credentials

Each tenant is a *profile*: a controller URL plus one user's credentials
(a session/API token, or username + password). Profiles live in
`~/.config/zedcloud/config.toml` (override with `ZEDCLOUD_CONFIG`):

```toml
default = "acme-prod"

[profiles.acme-prod]
base_url = "https://zedcontrol.zededa.net"
token_env = "ACME_ZEDCLOUD_TOKEN" # or token = "…", token_command = [...], token_keyring = true
description = "Acme production"

[profiles.lab]
base_url = "https://zedcontrol.zededa.net"
username = "me@example.com"
password_command = ["security", "find-generic-password", "-s", "zedcloud-lab", "-w"]
enterprise = "lab-enterprise" # which enterprise to log into
allow_writes = true # lets the MCP server / integration tests change this tenant
```

```python
ZedcloudClient.from_profile("lab") # or ZEDCLOUD_PROFILE=lab, or the file's default
```

Secrets can come from the file, an environment variable (`*_env`), a command
such as a password-manager CLI (`*_command`), or the OS keychain
(`*_keyring`, needs `zedcloud[keyring]`). Without a profile, `ZEDCLOUD_BASE_URL`
plus `ZEDCLOUD_TOKEN` or `ZEDCLOUD_USERNAME`/`ZEDCLOUD_PASSWORD` are used.
Password sessions log in on first use and log in again when the session expires.

```bash
zedcloud profiles # list tenants
zedcloud -p lab whoami # confirm which user/enterprise a profile reaches
zedcloud ops search "app instance logs"
zedcloud -p lab call nodes.query_edge_nodes -q project_name=plant-7
```

## SDK highlights

- **Every operation, typed.** One pydantic model per API definition (989),
including typed request bodies for updates. Optional arguments are keyword-only.
- **Tolerant of API drift.** Unknown fields are kept and round-trip through
GET β†’ modify β†’ PUT; enum values added server-side are accepted
(`value.is_known` tells you); fields the spec calls required may be absent.
- **Safe retries.** Connection failures and 429s retry for any method; 5xx
retries only for reads, so a write is never applied twice.
- **Helpers.** `iter_*` for all 56 paginated lists, `lookup_*` (name or ID)
for 45 resource types, `wait_for_edge_node` / `wait_for_app_instance` /
`wait_for_job`, `client.call(operation_id, …)` for registry-driven access.
- **Useful errors.** `ConflictError`, `NotFoundError`, `PermissionDeniedError`, …
carry the Zedcloud error code, details, and the `X-Request-Id` to quote to support.

See [docs/getting-started.md](docs/getting-started.md) and
[docs/architecture.md](docs/architecture.md).

## MCP server

```bash
uv run zedcloud-mcp # stdio; reads the same profiles file
```

Claude Code / Claude Desktop configuration:

```json
{
"mcpServers": {
"zedcloud": {
"command": "uv",
"args": ["--directory", "/path/to/zedcloud-sdk", "run", "zedcloud-mcp"]
}
}
}
```

Ask things like *"which edge nodes in plant-7 are offline on acme-prod?"* or
*"on lab, rename gw-17's title to Dock 3"*. Tenants are read-only unless the
profile sets `allow_writes = true`; every change is previewed, approved by you,
executed exactly as previewed, and audit-logged. Details in
[packages/zedcloud-mcp](packages/zedcloud-mcp/README.md).

## Development

```bash
make test # unit tests (no tenant needed)
make lint
make specs # refresh openapi/ from the live controller and regenerate
make generate # regenerate after editing scripts/generate.py
uv run pytest -m smoke --zedcloud-profile acme-prod # read-only checks against a real tenant
```

Generated code lives in `packages/zedcloud/src/zedcloud/_generated/` and is
checked in; CI fails if it is out of date with `openapi/`.
79 changes: 79 additions & 0 deletions docs/architecture.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
# Architecture

```
openapi/*.swagger.json 11 Swagger 2.0 specs, refreshed by scripts/fetch_specs.py
β”‚
β–Ό
scripts/generate.py merges definitions, hoists inline bodies, names methods
β”‚
β”œβ”€β–Ί _generated/models.py 989 tolerant pydantic models (shared by all services)
β”œβ”€β–Ί _generated/services/<ns>.py sync + async class per service
└─► _generated/operations.json registry: params, models, risk per operation
β”‚
β–Ό
zedcloud (runtime)
config.py profiles, credentials, secret sources
auth.py httpx.Auth: bearer token, login + re-login, X-API-KEY for k8s
_transport.py retries, path/query/body encoding, error mapping, logging
_service.py request dispatch, pagination, name-or-ID lookup
services/ hand-written extensions (waiters, aliases) over generated classes
operations.py registry search, prepare_call validation
client.py ZedcloudClient / AsyncZedcloudClient
β”‚
β”Œβ”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β–Ό β–Ό
zedcloud-automation zedcloud-mcp
pytest plugin tenants.py Β· guard.py Β· shaping.py Β· server.py
```

## Why the generator is custom

The specs are gRPC-gateway output and have quirks that generic generators
handle poorly:

| Quirk | Handling |
|---|---|
| ~190 definitions repeated verbatim in several specs | merged into one module; a conflicting duplicate fails generation |
| update bodies declared inline (`body: *` minus path params) | hoisted into named `<Method>Body` models |
| `required` lists that responses do not honour | every field optional; the requirement is documented in the model docstring |
| enums that grow server-side | `OpenEnum`: unknown values become pseudo-members |
| numbered/copy-pasted operationIds (`…BaseOS2`, `HardwareModel_DeleteEdgeNode`) | `METHOD_OVERRIDES`; any remaining collision fails generation |
| `next.totalPages` (a response field) listed as a request parameter | dropped |
| multipart `formData` uploads, base64 `format: byte` bodies | `files=` and base64 encoding |
| the Kubernetes proxy `{path}` spans several segments | slashes kept, `.`/`..` segments rejected |

## Auth

| Scheme | Header | Services |
|---|---|---|
| BearerToken | `Authorization: Bearer <token>` | all |
| ApiKeyAuth | `X-API-KEY` (explicit key, or the session token) | Kubernetes |

`PasswordCredentials` log in with `POST /v1/login` (`usernameAtRealm`, or
`username` + `realm`; optional `enterpriseName`) on first use and once more on
a 401, then retry the request.

## Retries

| Failure | Retried for |
|---|---|
| connection refused / connect timeout | every method (the server never saw it) |
| 429 | every method, honouring `Retry-After` |
| 500/502/503/504 | GET/HEAD/OPTIONS only |
| read timeout, other transport errors | never (a write may have been applied) |

Backoff is exponential with jitter, capped at 30 s. All attempts of one call
share an `X-Request-Id`.

## MCP write safety

1. `plan_write_operation` validates arguments, checks `allow_writes`, fetches
the target object, merges partial update bodies onto it, computes a
field-level diff, and stores the exact request under a random single-use
token (10-minute expiry).
2. The assistant shows the preview; the user approves.
3. `execute_write_operation(token)` runs the stored request, not new
arguments. If the MCP client supports elicitation, the server also asks the
user directly (`--require-human-approval` makes that mandatory).
4. Planned, executed, declined, and failed events go to a JSONL audit log with
secret-looking fields redacted.
Loading
Loading