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
56 changes: 56 additions & 0 deletions .github/workflows/python-cli.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
name: Python CLI

on:
workflow_dispatch:
pull_request:
paths:
- 'python/**'
- 'scripts/check_wire_contract.py'
- 'crates/engine/src/gateway/**'
- 'crates/cli/src/gateway_cmd.rs'
- '.github/workflows/python-cli.yaml'
push:
branches: [main]
paths:
- 'python/**'
- 'scripts/check_wire_contract.py'
- 'crates/engine/src/gateway/**'
- 'crates/cli/src/gateway_cmd.rs'
- '.github/workflows/python-cli.yaml'

concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.ref }}
cancel-in-progress: true

jobs:
python-cli:
name: lint, type-check, test, wire-contract
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6

- uses: astral-sh/setup-uv@v6
with:
enable-cache: true

- name: Create venv with the package and tooling
# ty resolves imports against the active venv, so the package and its
# deps (httpx, typer) must be installed there, alongside ruff/ty/pytest.
run: |
uv venv
uv pip install ./python 'ruff==0.16.5' 'ty==0.0.77' pytest httpx

- name: Ruff format check
run: uv run ruff format --check python/ scripts/check_wire_contract.py

- name: Ruff lint
run: uv run ruff check python/ scripts/check_wire_contract.py

- name: Type check (ty)
run: uv run ty check python/sealg scripts/check_wire_contract.py

- name: Tests
run: uv run pytest python/tests -q

- name: Wire contract (Python <-> Rust clients agree)
run: python3 scripts/check_wire_contract.py
14 changes: 14 additions & 0 deletions prek.toml
Original file line number Diff line number Diff line change
Expand Up @@ -48,3 +48,17 @@ name = "fail if any source folder exceeds the file-count error threshold"
language = "system"
entry = "scripts/check_folder_sizes.sh"
files = "\\.(tsx|ts|rs)$"

# ── sealg wire contract: Python client (python/) ↔ Rust client (crates/) ──
[[repos]]
repo = "local"

[[repos.hooks]]
id = "wire-contract"
name = "sealg wire contract: Python <-> Rust clients agree"
language = "system"
entry = "python3 scripts/check_wire_contract.py"
pass_filenames = false
# Run when the Python contract, the Rust gateway source, or the check script
# changes. Both clients live in this repo, so the check always runs both legs.
files = "^(python/sealg/(contract|client|cli)\\.py|crates/engine/src/gateway/(config|client)\\.rs|crates/cli/src/gateway_cmd\\.rs|scripts/check_wire_contract\\.py)$"
24 changes: 24 additions & 0 deletions python/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# SealGate gateway coordinates. Export these in your shell (or your runtime sets
# them). All config is read from the environment only.

# Gateway origin (no /mcp suffix). Defaults to http://localhost:3000 when unset.
SEALGATE_URL=https://mcp.sealgate.ai

# SealGate API key from https://dashboard.sealgate.ai. Optional: leave unset when
# an upstream proxy injects Authorization. When set, it is embedded in the
# /mcp/{key}/ path.
# SEALGATE_API_KEY=ew_live_...

# Zero-knowledge secret key, only needed for tools that decrypt stored secrets.
# Generate it at https://dashboard.sealgate.ai/dashboard/settings.
# SEALGATE_SECRET_KEY=...

# Stable conversation id for audit/trifecta continuity. Falls back to
# CENTAUR_THREAD_KEY, which some agent runtimes set automatically.
# SEALGATE_CONVERSATION_ID=...

# CA bundle for a MITM egress proxy (first of these that is set wins), so sealg
# trusts the proxy's CA.
# SSL_CERT_FILE=/etc/ssl/proxy-ca.pem
# REQUESTS_CA_BUNDLE=/etc/ssl/proxy-ca.pem
# NODE_EXTRA_CA_CERTS=/etc/ssl/proxy-ca.pem
41 changes: 41 additions & 0 deletions python/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# sealg (Python)

A Python client for the SealGate gateway, exposing the same `sealg` CLI as the
Rust binary in this repo. It is a thin MCP-over-HTTP client: `sealg list` /
`sealg call` forward `tools/list` / `tools/call` to your per-user gateway
endpoint, where all policy and enforcement live. It carries no policy of its own.

It exists alongside the Rust `sealg` because a `uvx`-installable Python package
drops into environments that reach for `uvx`/`pip` rather than a native binary.
The two clients are kept from drifting by `scripts/check_wire_contract.py` (a
pre-commit + CI check): every shared wire constant lives once in
`sealg/contract.py` and is checked against the Rust source in `crates/`.

## Install and run

```
uvx --from python/ sealg doctor # from a checkout
uvx --from 'git+https://github.com/Edison-Watch/cli#subdirectory=python' sealg list
```

Or `pip install ./python` into a virtualenv, then run `sealg`.

## Commands

```
sealg doctor # resolved gateway env + reachability probe
sealg list [--json] # tools your org has authorized
sealg call <tool> [--args '{}'] # invoke one tool
```

Exit codes mirror the Rust CLI: `0` ok, `1` client/transport error, `6` the
gateway returned an MCP tool error (`isError: true`).

## Configuration

All from the environment (see `.env.example`): `SEALGATE_URL`,
`SEALGATE_API_KEY` (optional - keyless when auth is injected upstream by a
proxy), `SEALGATE_SECRET_KEY`, `SEALGATE_CONVERSATION_ID` (with a
`CENTAUR_THREAD_KEY` fallback that some agent runtimes set automatically), and a
CA bundle via `SSL_CERT_FILE` / `REQUESTS_CA_BUNDLE` / `NODE_EXTRA_CA_CERTS` for
a MITM egress proxy.
20 changes: 20 additions & 0 deletions python/pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
[project]
name = "sealg"
description = "Python client for the SealGate gateway - governed access to every tool via one CLI"
version = "0.1.0"
requires-python = ">=3.11"
dependencies = [
"httpx>=0.27.0",
"typer>=0.12.0",
]

# The command this package installs: `sealg list`, `sealg call ...`, `sealg doctor`.
[project.scripts]
sealg = "sealg.cli:app"

[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"

[tool.hatch.build.targets.wheel]
packages = ["sealg"]
1 change: 1 addition & 0 deletions python/sealg/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"""SealGate CLI (sealg) - the Python client for the SealGate gateway."""
Binary file added python/sealg/__pycache__/__init__.cpython-311.pyc
Binary file not shown.
Binary file added python/sealg/__pycache__/client.cpython-311.pyc
Binary file not shown.
Binary file not shown.
151 changes: 151 additions & 0 deletions python/sealg/cli.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
"""CLI for SealGate - a thin MCP client to the SealGate gateway.

``sealg list`` / ``sealg call`` forward ``tools/list`` / ``tools/call`` to the
per-user gateway endpoint; all policy and enforcement live in the gateway.
``sealg doctor`` reports the resolved environment and probes reachability. This
is the Python client; it mirrors the Rust ``sealg`` binary's surface and exit
codes.
"""

from __future__ import annotations

import json
import os
import platform

import typer

from .client import GatewayClient, GatewayConfig, redact_url
from .contract import ENV_CA_BUNDLE, EXIT_ERROR, EXIT_TOOL_ERROR

app = typer.Typer(
name="sealg",
help="Command-line interface for SealGate, the agentic data firewall",
no_args_is_help=True,
add_completion=False,
)


def _emit(value: object) -> None:
print(json.dumps(value, indent=2, ensure_ascii=False, default=str))


@app.command("doctor")
def doctor(
gateway_url: str = typer.Option(
None, "--gateway-url", help="Override the gateway base URL."
),
) -> None:
"""Report the resolved gateway environment and probe reachability."""
cfg = GatewayConfig.from_env(url_override=gateway_url)
report: dict[str, object] = {
"tool": "sealg",
"os": platform.system().lower(),
"arch": platform.machine(),
"gateway_url": redact_url(cfg.mcp_url(), cfg.api_key),
"auth": cfg.auth_mode(),
"secret_key_set": cfg.secret_key is not None,
"conversation_id_set": cfg.conversation_id is not None,
"ca_bundle": cfg.ca_bundle,
# Which env var actually supplied the bundle (first non-blank, matching
# GatewayConfig's precedence), or None.
"ca_bundle_source": next(
(k for k in ENV_CA_BUNDLE if os.environ.get(k, "").strip()), None
),
}
# Separate "could we reach + initialize the gateway" (reachable) from "did
# the tools/list probe succeed" (readiness), so a connect that succeeds but
# a probe that fails isn't reported as unreachable.
try:
client = GatewayClient(cfg).connect()
except Exception as exc: # noqa: BLE001 - doctor reports failures, never raises on them
report["reachable"] = False
report["error"] = str(exc)
else:
report["reachable"] = True
try:
report["tool_count"] = len(client.tools_list())
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
except Exception as exc: # noqa: BLE001
report["probe_error"] = str(exc)
finally:
client.close()

_emit(report) # doctor is a diagnostic; always structured JSON
if not report["reachable"]:
raise typer.Exit(EXIT_ERROR)


@app.command("list")
def list_tools(
json_out: bool = typer.Option(
False, "--json", help="Output as a JSON array of {name, description}."
),
gateway_url: str = typer.Option(
None, "--gateway-url", help="Override the gateway base URL."
),
) -> None:
"""List the user's tools from the live SealGate gateway."""
cfg = GatewayConfig.from_env(url_override=gateway_url)
try:
client = GatewayClient(cfg).connect()
try:
tools = client.tools_list()
finally:
client.close()
except Exception as exc:
typer.echo(f"error: {exc}", err=True)
raise typer.Exit(EXIT_ERROR) from exc

if json_out:
_emit([{"name": t.name, "description": t.description} for t in tools])
else:
for t in tools:
# The em dash keeps this list output identical to the Rust client's;
# written as a backslash-u2014 escape because the repo ai-writing
# check bans a literal U+2014 in source.
typer.echo(f"{t.name} \u2014 {t.description}")


@app.command("call")
def call_tool(
tool: str = typer.Argument(..., help="Tool name as advertised by `sealg list`."),
args: str = typer.Option(
"{}", "--args", help="JSON arguments object to pass to the tool."
),
gateway_url: str = typer.Option(
None, "--gateway-url", help="Override the gateway base URL."
),
) -> None:
"""Call a tool on the live SealGate gateway."""
try:
arguments = json.loads(args)
except json.JSONDecodeError as exc:
typer.echo(f"error: invalid --args JSON: {exc}", err=True)
raise typer.Exit(EXIT_ERROR) from exc
# MCP arguments must be an object. Reject a valid-JSON non-object locally
# (e.g. --args '5' or '"x"') with a clear error rather than forwarding an
# invalid tools/call. null is allowed; the client maps it to {}.
if arguments is not None and not isinstance(arguments, dict):
typer.echo("error: --args must be a JSON object", err=True)
raise typer.Exit(EXIT_ERROR)

cfg = GatewayConfig.from_env(url_override=gateway_url)
try:
client = GatewayClient(cfg).connect()
try:
result = client.tools_call(tool, arguments)
finally:
client.close()
except Exception as exc:
typer.echo(f"error: {exc}", err=True)
raise typer.Exit(EXIT_ERROR) from exc

_emit(result)
# Mirror the MCP tool-call response: an `isError: true` result is a failed
# call and must not exit 0.
if isinstance(result, dict) and result.get("isError") is True:
raise typer.Exit(EXIT_TOOL_ERROR)


if __name__ == "__main__":
app()
Loading
Loading