feat: Scribase plugin for Hermes Agent — scribase_create_project tool

Provisions a hosted Postgres backend project on Scribase (api.scribase.com)
via its public REST API and returns the new environment's connection
string and API keys. Registers a single tool (ctx.register_tool) and reads
its API key through Hermes's secret scope (agent.secret_scope.get_secret);
no other Hermes surfaces, no third-party dependencies.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Caelum 2026-11-05 18:52:29 +03:00
commit dfce6f241d
6 changed files with 410 additions and 0 deletions

21
LICENSE Normal file
View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Scribase
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 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.

76
README.md Normal file
View File

@ -0,0 +1,76 @@
# Scribase plugin for Hermes Agent
Lets a [Hermes Agent](https://github.com/NousResearch/hermes-agent) provision
a real hosted Postgres backend on [Scribase](https://scribase.com) — a
Postgres-as-a-service with a Supabase-API-compatible REST/Auth/Storage/
Realtime/Functions surface — without the user leaving the chat.
## What it does
Registers one tool, `scribase_create_project`, that:
1. Creates (or confirms) a project inside an existing Scribase organization.
2. Creates the project's first environment (`production` by default).
3. Polls until the environment finishes provisioning (bounded: it returns a
`"status": "provisioning"` result with the operation id instead of
hanging forever if it isn't ready yet — see "Disclosure" below).
4. Returns the new environment's Postgres connection URI and its API keys
(`anon_key`, `service_role_key`, `publishable_key`, `secret_key`,
`api_url`).
That's it — no other tools, no hooks, no middleware, no CLI/slash commands.
## Setup
1. Have a Scribase account and organization (`scribase.com`).
2. Create an organization API key: console → **Organization → API tokens**,
or `POST /v1/organizations/{org}/api-keys` against the [Scribase Control
API](https://docs.scribase.com/docs/api).
3. Install the plugin and set `SCRIBASE_API_KEY` when Hermes prompts for it
(or add it to your Hermes profile's `.env`).
```bash
hermes plugins install scribase
```
### Optional: self-hosted Scribase
If you run your own Scribase cluster instead of the hosted
`api.scribase.com`, set the plugin's `api_base_url` config key to your
gateway's base URL (e.g. `https://api.your-domain.com`). This is a plain
URL, not a secret.
## Disclosure (Hermes plugin-catalog rule 13)
- **Hermes surfaces used:** `ctx.register_tool` only. No hooks, no
middleware, no CLI/slash commands, no runtime overrides of Hermes
internals.
- **Network calls:** only to the Scribase management API
(`https://api.scribase.com` by default, or the operator's own
`api_base_url` for a self-hosted cluster). No other host is contacted and
no telemetry is sent anywhere.
- **Credentials:** the plugin stores no credentials of its own. It reads
`SCRIBASE_API_KEY` exclusively through Hermes's secret scope
(`agent.secret_scope.get_secret`), never from `os.environ` directly, a
`.env` file, or any other local store.
- **Side effects:** calling the tool creates real, billable resources in
the user's Scribase organization (a project and a Postgres environment).
It does not delete, suspend, or modify anything that already exists.
- **Long-running behavior:** the tool call itself blocks for up to roughly
30 seconds while polling the new environment's provisioning operation. If
provisioning is not done by then, it returns a `"status": "provisioning"`
result with the operation id instead of blocking indefinitely, so it
cannot hang an unattended run (cron, messaging gateway).
- **No UI:** this is a pure tool-call plugin. No screens, no Desktop
surface.
- **No self-updating code:** the plugin does not fetch or replace its own
files. Updates reach users only through a new pinned commit in the
Hermes plugin catalog.
## Dependencies
None beyond the Python standard library (`urllib`, `json`, `uuid`, `time`).
## License
MIT — see [LICENSE](./LICENSE).

64
__init__.py Normal file
View File

@ -0,0 +1,64 @@
"""Scribase plugin for Hermes Agent — registration.
Registers exactly one tool, `scribase_create_project`, that provisions a
new hosted Postgres backend project on Scribase (https://api.scribase.com)
through its public REST API and returns the new environment's connection
string and API keys.
Hermes surfaces used: `ctx.register_tool` only. No hooks, no middleware, no
CLI/slash commands, no runtime overrides of Hermes internals.
Network calls: only to `api_base_url` (default `https://api.scribase.com`,
overridable for a self-hosted Scribase cluster via the plugin's
`api_base_url` config key, never a secret) — see tools.py.
Credentials: the Scribase organization API key is read through Hermes's
secret scope (`agent.secret_scope.get_secret("SCRIBASE_API_KEY")`), per the
plugin-catalog's credential rule. This plugin never reads `.env` files or
`os.environ` directly, and stores no credentials of its own.
"""
from __future__ import annotations
import json
import logging
from agent.secret_scope import get_secret
from . import schemas, tools
logger = logging.getLogger(__name__)
_DEFAULT_API_BASE = "https://api.scribase.com"
def register(ctx) -> None:
"""Wire the `scribase_create_project` tool to the Scribase REST client."""
def _handle_create_project(args: dict, **kwargs) -> str:
api_key = get_secret("SCRIBASE_API_KEY") or ""
if not api_key:
return json.dumps({
"error": (
"SCRIBASE_API_KEY is not set. Create a Scribase organization "
"API key (console: Organization -> API tokens, or "
"POST /v1/organizations/{org}/api-keys) and configure it for "
"this plugin."
),
})
api_base = str(
ctx.get_config("api_base_url", _DEFAULT_API_BASE) or _DEFAULT_API_BASE
).strip().rstrip("/")
try:
result = tools.create_project(args, api_key=api_key, api_base=api_base)
except Exception as exc: # a tool handler must never raise (dev guide, "Common mistakes")
logger.exception("scribase_create_project failed")
result = {"error": f"unexpected error: {exc}"}
return json.dumps(result)
ctx.register_tool(
name="scribase_create_project",
toolset="scribase",
schema=schemas.SCRIBASE_CREATE_PROJECT,
handler=_handle_create_project,
)

16
plugin.yaml Normal file
View File

@ -0,0 +1,16 @@
name: scribase
version: "1.0.0"
description: "Provision a hosted Postgres backend project on Scribase (api.scribase.com) and get back its connection string and API keys."
author: Scribase
requires_hermes: ">=0.20.0"
provides_tools:
- scribase_create_project
requires_env:
- name: SCRIBASE_API_KEY
description: "Scribase organization API key. Create one under Organization -> API tokens in the Scribase console, or via POST /v1/organizations/{org}/api-keys."
url: "https://docs.scribase.com/docs/api"
secret: true
config_schema:
api_base_url:
type: str
required: false

50
schemas.py Normal file
View File

@ -0,0 +1,50 @@
"""Tool schema for `scribase_create_project` — this is what the LLM reads to
decide when and how to call the tool."""
SCRIBASE_CREATE_PROJECT = {
"name": "scribase_create_project",
"description": (
"Provision a new hosted Postgres backend project on Scribase "
"(api.scribase.com) and return its connection string and API keys. "
"Creates the project, creates its first environment (production by "
"default), waits for it to finish provisioning, then reads back the "
"Postgres connection URI and the environment's anon/service-role API "
"keys. Use this when a user wants a real Postgres database plus a "
"REST/Auth/Storage/Realtime API for an app and doesn't want to set "
"up a database by hand. Requires an existing Scribase organization "
"id and an organization API key configured as SCRIBASE_API_KEY."
),
"parameters": {
"type": "object",
"properties": {
"organization_id": {
"type": "string",
"description": (
"The Scribase organization this project belongs to "
"(lowercase alphanumeric + hyphens, 2-64 chars). The "
"organization must already exist."
),
},
"project_id": {
"type": "string",
"description": (
"A new, unique project id within the organization "
"(lowercase alphanumeric + hyphens, 2-64 chars)."
),
},
"environment_id": {
"type": "string",
"description": "Name for the project's first environment. Defaults to 'production'.",
},
"region": {
"type": "string",
"description": "Region to provision in. Defaults to 'eu-frankfurt' (hosted Scribase's region).",
},
"postgres_major": {
"type": "integer",
"description": "Postgres major version. Only 17 is currently supported; defaults to 17.",
},
},
"required": ["organization_id", "project_id"],
},
}

183
tools.py Normal file
View File

@ -0,0 +1,183 @@
"""HTTP client for Scribase's public /v1 management API.
Every function here takes an already-resolved `api_key`/`api_base` and
returns a plain dict — never raises. The caller (`__init__.py`'s tool
handler) is responsible for the handler contract (always return a JSON
string, success or error alike). This module makes network calls only to
`api_base` (default `https://api.scribase.com`, overridable via the
plugin's optional `api_base_url` config key for self-hosted Scribase
clusters) and uses only the Python standard library — no third-party
dependencies.
"""
from __future__ import annotations
import json
import time
import urllib.error
import urllib.request
import uuid
from typing import Any, Dict, Optional, Tuple
_TIMEOUT = 20 # seconds per HTTP call
_POLL_ATTEMPTS = 8
_POLL_INTERVAL = 3 # seconds
_DEFAULT_REGION = "eu-frankfurt"
_DEFAULT_POSTGRES_MAJOR = 17
_DEFAULT_ENVIRONMENT_ID = "production"
_TERMINAL_STATES = ("succeeded", "failed", "cancelled")
def _request(
method: str, url: str, api_key: str,
body: Optional[Dict[str, Any]] = None,
extra_headers: Optional[Dict[str, str]] = None,
) -> Tuple[int, Any]:
"""One HTTP call against the Scribase management API.
Returns ``(status, parsed_body)``. ``status`` is 0 when the request
could not be sent at all (DNS/connection failure); callers treat that
as a terminal error, never a retryable one, to avoid hanging an
unattended run (plugin-catalog rule 12).
"""
data = json.dumps(body).encode("utf-8") if body is not None else None
headers = {"Authorization": f"Bearer {api_key}", "Accept": "application/json"}
if data is not None:
headers["Content-Type"] = "application/json"
if extra_headers:
headers.update(extra_headers)
req = urllib.request.Request(url, data=data, method=method, headers=headers)
try:
with urllib.request.urlopen(req, timeout=_TIMEOUT) as resp:
raw = resp.read().decode("utf-8", "replace")
status = resp.status
except urllib.error.HTTPError as exc:
raw = exc.read().decode("utf-8", "replace")
status = exc.code
except urllib.error.URLError as exc:
return 0, {"error": f"could not reach the Scribase API: {exc.reason}"}
if not raw:
return status, {}
try:
return status, json.loads(raw)
except json.JSONDecodeError:
return status, {"error": raw[:500]}
def _idempotency_key() -> str:
return str(uuid.uuid4())
def create_project(args: Dict[str, Any], *, api_key: str, api_base: str) -> Dict[str, Any]:
"""Create a Scribase project and its first environment, then return connection info.
Required args: ``organization_id``, ``project_id``. Optional:
``environment_id`` (default "production"), ``region`` (default
"eu-frankfurt", hosted Scribase's region), ``postgres_major`` (default
17, the only currently supported version).
"""
org = str(args.get("organization_id") or "").strip()
project = str(args.get("project_id") or "").strip()
environment = str(args.get("environment_id") or "").strip() or _DEFAULT_ENVIRONMENT_ID
region = str(args.get("region") or "").strip() or _DEFAULT_REGION
try:
postgres_major = int(args.get("postgres_major") or _DEFAULT_POSTGRES_MAJOR)
except (TypeError, ValueError):
return {"error": "postgres_major must be an integer (only 17 is currently supported)."}
if not org:
return {"error": "organization_id is required (the existing Scribase org this project belongs to)."}
if not project:
return {"error": "project_id is required."}
# 1. Create (or confirm) the project — idempotent PUT.
status, body = _request(
"PUT", f"{api_base}/v1/organizations/{org}/projects/{project}", api_key,
body={"region": region, "postgres_major": postgres_major},
extra_headers={"Idempotency-Key": _idempotency_key()},
)
if status == 0:
return body
if status not in (200, 201):
return {"error": "failed to create project", "status": status, "detail": body}
# 2. Create its first environment — async; returns an operation to poll.
status, body = _request(
"POST", f"{api_base}/v1/environments", api_key,
body={
"organization_id": org, "project_id": project, "environment_id": environment,
"kind": "production", "data_mode": "schema_only",
"region": region, "postgres_major": postgres_major, "ttl_hours": None,
},
extra_headers={"Idempotency-Key": _idempotency_key()},
)
if status == 0:
return body
if status != 202:
return {"error": "failed to create environment", "status": status, "detail": body}
operation_id = body.get("id")
# 3. Poll the operation until it leaves pending/running/waiting_retry, bounded so an
# unattended run (cron, gateway) can never hang on this tool call (rule 12).
final_state = None
last_op_body: Dict[str, Any] = {}
for _ in range(_POLL_ATTEMPTS):
time.sleep(_POLL_INTERVAL)
op_status, op_body = _request(
"GET", f"{api_base}/v1/operations/{operation_id}", api_key,
extra_headers={"X-Scribase-Organization-ID": org},
)
if op_status == 200:
last_op_body = op_body
final_state = op_body.get("state")
if final_state in _TERMINAL_STATES:
break
if final_state != "succeeded":
still_going = final_state not in ("failed", "cancelled")
return {
"status": "provisioning" if still_going else "failed",
"organization_id": org, "project_id": project, "environment_id": environment,
"operation_id": operation_id,
"message": (
f"Environment is still provisioning (state={final_state!r}). Call this tool "
f"again shortly, or poll GET /v1/operations/{operation_id} directly."
if still_going else
f"Environment provisioning failed (state={final_state!r})."
),
"operation": last_op_body,
}
# 4. Fetch the new environment's API keys and connection string.
status, keys = _request(
"GET",
f"{api_base}/v1/organizations/{org}/projects/{project}/environments/{environment}/api-keys",
api_key,
)
if status != 200:
return {
"status": "ready",
"warning": "environment created, but failed to read its API keys",
"detail": keys,
}
status, conn = _request(
"GET",
f"{api_base}/v1/organizations/{org}/projects/{project}/environments/{environment}/connection",
api_key,
)
connection_uri = conn.get("connection_uri") if status == 200 else None
return {
"status": "ready",
"organization_id": org,
"project_id": project,
"environment_id": environment,
"region": region,
"api_url": keys.get("api_url"),
"anon_key": keys.get("anon_key"),
"publishable_key": keys.get("publishable_key"),
"service_role_key": keys.get("service_role_key"),
"secret_key": keys.get("secret_key"),
"connection_uri": connection_uri,
}