Integrations Reference
Integrations Reference¶
Huitzo provides built-in integrations for common services. All integrations are accessed through the Context object and are automatically configured based on platform settings.
Architecture & registry: This page is the SDK-side reference. For the unified registry model, REST contract, ORM schema, migration strategy, security boundaries, and OAuth lifecycle see Integrations Subsystem v2.
Overview¶
Huitzo Context surfaces fall into two groups:
Platform integrations (always-available)¶
| Integration | Access | Description |
|---|---|---|
| LLM | ctx.llm |
AI/LLM completions (OpenAI, Anthropic) |
ctx.email |
Send emails (SendGrid, SMTP) | |
| Speech Synthesis | ctx.tts |
Platform text-to-speech (see TTS Reference) |
| HTTP | ctx.http |
External API requests |
| Telegram | ctx.telegram |
Send Telegram messages |
| Files | ctx.files |
Read/write files |
| Database | ctx.db |
Postgres / MySQL connectors |
Deployment-scoped extensions (epic #583)¶
Extensions are advertised by the deployment via /api/v1/capabilities,
fetched as a signed bundle on huitzo login (ADR-001), and surfaced under
the unified ctx.integrations.* namespace. Pack manifests pin acceptable
versions via PEP 440 specifiers.
| Access | Backed by | Notes |
|---|---|---|
ctx.integrations.salesforce |
huitzo-ext-salesforce extension wheel |
Same loader, different vendor. |
ctx.integrations.crm |
Vendor-neutral CRM facade (#497 redirected) | Dispatches to whichever vendor extension is configured for the pack. |
ctx.integrations.<other> |
Any extension advertised by the deployment | Lazy-loaded on first attribute access. |
There is no ctx.crm namespace. Per ADR-002, the public generic CRM
surface (#497) is folded under ctx.integrations.crm; deployment-advertised extensions are surfaced by
their own name. Both share one loader,
one error taxonomy (ExtensionNotAvailable, ExtensionVersionMismatch,
ExtensionSignatureInvalid, CapabilityFetchError), and one trust model.
For the full pack-author guide — declaring extensions in
huitzo.yaml, lazy resolution via ctx.integrations.<name>, the
four user-facing error types,
and best practices — see Extensions Reference.
See also:
- Extensions Reference
docs/architecture/adrs/001-extension-bundle-format.mddocs/architecture/adrs/002-ctx-integrations-collapse.mddocs/architecture/security/extension-signing.mddocs/architecture/deployment-capabilities.mddocs/architecture/component-model.md#deployment-scoped-extensions-epic-583
LLM Integration¶
The LLM integration provides model-agnostic access to AI language models for text generation, analysis, and structured output.
Packs declare a
profile, never a model. A pack call site passes a capabilityprofile(e.g."default"or a named profile from the manifest). The backend ModelRouter resolves that profile to a concrete(provider, model)route from the deployment's LLM registry, managed at/admin/llm: the profile's mapping, else the registry default model, else a local Ollama model when local AI is enabled. A cloud model is eligible only when its provider is enabled and has an API key (ADR-006 D3, amended 2026-09-29). Customers swap models deployment-wide without touching a pack. See ADR-006 andmanifest.md#serviceslmfor the requirements shape.Credentials are resolved by the platform, not the pack. For a cloud route, the tenant's bring-your-own key takes precedence over the platform key: if the tenant has an
llm_byokintegration for the routed provider, that key is used on the wire; otherwise the platform key is used. A pack never reads or passes the key — it just callsctx.llm. Seedocs/reference/secrets.md#bring-your-own-key-byok.
Declaring LLM needs (manifest)¶
Packs declare needs (a capability floor), not model names, under
services.llm:
# huitzo.yaml — pseudocode
services:
llm:
required: true
requirements:
min_context: 16000
capabilities: ["structured_output"] # enum: structured_output | tool_use
profiles: # optional named profiles
accurate:
min_context: 200000
capabilities: ["structured_output"]
The implicit "default" profile uses requirements; named profiles add
per-profile overrides. At install time the deployment checks that some
configured model satisfies each required requirement.
Basic Completion¶
# pseudocode — basic LLM completion
response = await ctx.llm.complete(
prompt="your prompt text",
profile="default", # capability profile, never a model name
)
# response is a string containing the LLM output
With System Message¶
# pseudocode — completion with system message
response = await ctx.llm.complete(
prompt=user_query,
system="role/persona instructions for the LLM",
profile="default",
)
Structured Output (typed schema=)¶
Define a Pydantic model for the expected output, then pass it as schema. The
call returns a validated instance of that model — the standardized
deterministic → LLM handoff. The router requests structured output from the
provider, then validates the response into the typed instance (a validation
miss raises LLMError):
# pseudocode — typed structured output
person = await ctx.llm.complete(
prompt="your extraction/analysis prompt",
schema=PersonModel, # returns a validated PersonModel instance
profile="default",
)
# person.name, person.age — no manual json.loads / shape-checking
Without schema, complete/chat return str. response_format="json"
remains for the untyped-JSON-string case.
Multi-turn Chat¶
# pseudocode — multi-turn conversation
reply = await ctx.llm.chat(
[
{"role": "system", "content": "persona / instructions"},
{"role": "user", "content": "first turn"},
{"role": "assistant", "content": "model reply"},
{"role": "user", "content": "follow-up"},
],
profile="default",
schema=ReplyModel, # optional — same typed handoff as complete()
)
The real multi-turn message array is sent to the provider (system + alternating user/assistant turns); it is not collapsed into a single prompt.
Streaming Responses¶
# pseudocode — streaming completion
async for chunk in ctx.llm.stream(prompt="...", profile="default"):
# process each chunk as it arrives
...
LLM Options¶
| Parameter | Type | Description |
|---|---|---|
prompt |
str |
The user prompt |
profile |
str |
Capability profile to route on (never a model name; defaults to "default") |
system |
str |
Optional system/role message |
temperature |
float |
Creativity (0.0–2.0) |
max_tokens |
int |
Maximum response length |
top_p |
float |
Nucleus sampling threshold |
stop |
list[str] |
Stop sequences |
response_format |
str |
"json" for an untyped JSON string |
schema |
BaseModel |
Pydantic model; returns a validated instance |
# pseudocode — using LLM options
response = await ctx.llm.complete(
prompt="...",
profile="default",
temperature=0.7,
max_tokens=1000,
...
)
Token usage and v1 billing¶
This SDK reference does not define a token-billing contract. SaaS v1 does not charge customer memberships by LLM tokens, compute, or TTS credits; the credit economy is dark. Any usage exposed by an integration is operational or quota-related, not a promise of usage-priced billing.
Error Handling¶
from huitzo_sdk.errors import LLMError
try:
response = await ctx.llm.complete(prompt="...", profile="default")
except LLMError as e:
ctx.log.error(f"LLM failed: {e.provider} - {e.message}")
# e.provider: the resolved provider (or "model_router" for a routing error)
# e.model: the resolved model that failed (if any)
# e.status_code: HTTP status if applicable
A routing failure (e.g. a profile resolves to a cloud model on a deployment with
cloud disabled, or no configured model satisfies a requirement) raises LLMError
with a clear message describing which constraint was unmet.
Email Integration¶
Send transactional email through the platform email provider (SendGrid).
Configuration¶
Both variables carry the HUITZO_ env prefix — Settings.model_config["env_prefix"]
is "HUITZO_", so an unprefixed SENDGRID_API_KEY never binds and email silently
never sends (see Configuration → Services).
| Variable | Required | Description |
|---|---|---|
HUITZO_SENDGRID_API_KEY |
❌ | SendGrid API key. Unset → email is disabled and ctx.email.send raises EmailError. |
HUITZO_EMAIL_FROM |
⚠️ | From: address on every message the deployment sends. Ships with a built-in default so an unset value can never break boot, but you must set it whenever HUITZO_SENDGRID_API_KEY is set — see Sender authentication below. |
Legend: ✅ required · ⚠️ has a default, but a deployment that sends email must override it · ❌ optional.
SMTP is not configured through env vars. It is a per-integration provider
(smtp) registered through the integrations registry; there are no SMTP_*
platform settings.
Sender authentication¶
SendGrid will happily accept a message with any From: domain. Receiving mail
servers will not. Whether that message lands in the inbox is decided by DNS
records on the sender domain, not by anything in Huitzo:
| Record | On | Effect when missing |
|---|---|---|
SPF (TXT) |
the HUITZO_EMAIL_FROM domain |
SendGrid's sending IPs are unauthorized → softfail/fail → spam folder or rejection |
DKIM (CNAME ×2) |
the HUITZO_EMAIL_FROM domain |
Message is unsigned → no aligned DKIM identity for DMARC |
DMARC (TXT) |
_dmarc.<domain> |
No policy signal; receivers apply their own heuristics |
Operator requirements:
- Set
HUITZO_EMAIL_FROMto an address at a domain you control. - Publish SendGrid's SPF
include:and both DKIMCNAMErecords for that domain before enabling sending, and complete SendGrid domain authentication. - A sender domain whose SPF record authorizes a different provider (e.g. only a mailbox host) is worse than no SPF record at all — the receiver sees an explicit non-authorization rather than "no opinion".
The backend does not verify DNS (no network calls at boot, and DNS state can
change under a running process). Instead it logs a startup warning — never
an exception — when HUITZO_SENDGRID_API_KEY is set and HUITZO_EMAIL_FROM is
in any of four shapes that are certainly wrong:
| Detected state | Example | Why it is wrong |
|---|---|---|
| empty | HUITZO_EMAIL_FROM= (a compose ${VAR:-} passthrough) |
Falls back to the built-in default |
| the built-in default | [email protected] |
Huitzo's own domain; your deployment cannot authenticate it |
| a shipped placeholder domain | [email protected] |
The fill-me-in value from Huitzo's own templates — nobody owns it |
| malformed | noreply@localhost |
SendGrid rejects the message outright |
The comparison is case-insensitive. A silent result is not a claim that your DNS is correct — it only means the configuration shape is not obviously broken.
The same signal is reported as a degraded email row on
/health/integrations. Sending is never blocked: degrading delivery is bad, but
silently dropping password-reset mail is worse.
Self-hosted operators: both variables must reach the containers, not just the
.env file. The canonical docker-compose.yml has no env_file: directive and
forwards settings through explicit environment: maps, so each variable is
listed there for both the app and worker services — the worker sends mail
too (retried notifications).
Basic Email¶
@command("notify", namespace="alerts")
async def notify(args: Args, ctx: Context) -> dict:
await ctx.email.send(
to="[email protected]",
subject="Alert: Action Required",
body="Your report is ready for review."
)
return {"sent": True}
HTML Email¶
await ctx.email.send(
to="[email protected]",
subject="Weekly Report",
html="""
<h1>Weekly Report</h1>
<p>Here are your metrics:</p>
<ul>
<li>Revenue: $10,000</li>
<li>Users: 150</li>
</ul>
""",
)
With Attachments¶
# PDF attachment
pdf_bytes = generate_pdf_report(data)
await ctx.email.send(
to="[email protected]",
subject="Your Report",
body="Please find your report attached.",
attachments=[
{
"filename": "report.pdf",
"content": pdf_bytes,
"content_type": "application/pdf"
}
]
)
Multiple Recipients¶
await ctx.email.send(
to=["[email protected]", "[email protected]"],
cc=["[email protected]"],
bcc=["[email protected]"],
subject="Team Update",
body="..."
)
Email Templates¶
# pseudocode — sending a template-based email
await ctx.email.send_template(
to="[email protected]",
template_id="<your-template-id>", # provider-specific template ID
template_data={ # variables to fill in the template
"name": "...",
"report_url": "..."
}
)
HTTP Integration¶
Make HTTP requests to external APIs with automatic timeout and retry handling.
GET Request¶
@command("fetch-data", namespace="api")
async def fetch_data(args: Args, ctx: Context) -> dict:
response = await ctx.http.get(
"https://api.example.com/data",
headers={"Authorization": f"Bearer {args.api_key}"}
)
return response # Parsed JSON
POST Request¶
response = await ctx.http.post(
"https://api.example.com/submit",
json={"name": "value", "count": 42}
)
Request Options¶
response = await ctx.http.get(
"https://api.example.com/data",
headers={"X-Custom-Header": "value"},
params={"page": 1, "limit": 100},
timeout=60, # seconds
)
response = await ctx.http.post(
"https://api.example.com/upload",
data={"field": "value"}, # Form data
files={"document": file_bytes},
)
response = await ctx.http.put(
"https://api.example.com/resource/123",
json={"updated": True}
)
response = await ctx.http.delete(
"https://api.example.com/resource/123"
)
Domain Restrictions¶
Packs can restrict HTTP access to specific domains in the manifest:
# huitzo.yaml
services:
http:
required: true
allowed_domains:
- "api.example.com"
- "*.trusted-domain.org"
Relative Paths and base_url¶
When a tenant configures an HTTP integration with a base_url, packs may pass
relative paths to ctx.http.get / post / put / delete and the path is
joined onto the integration's base URL. The base URL's host is implicitly
allowed in addition to any allowed_domains declared in the manifest, so
operators don't need to repeat the host in two places.
Tenants configure base_url (and allowed_domains) when creating the HTTP
integration in the dashboard. See Integrations Subsystem v2
for the full configuration contract.
# pseudocode — assumes the tenant's HTTP integration has
# base_url = https://api.weather.example.com
response = await ctx.http.get(
"/v1/forecast",
params={"latitude": 37.77, "longitude": -122.42, "current": "temperature_2m"},
)
Absolute URLs always pass through unchanged, so a pack can target additional
hosts (subject to allowed_domains) even when a base_url is set. Wildcard
entries in allowed_domains (e.g. *.trusted-domain.org) continue to apply
independently of base_url — both mechanisms are additive permits, neither
replaces the other.
Without a base_url, a relative path raises HTTPSecurityError with the
message URL has no valid hostname. so misconfigured packs surface a clear
diagnostic.
If the configured base_url itself includes a path component (e.g.
https://api.example.com/v2), the relative path is always appended onto
that prefix — the SDK normalizes leading slashes so /v1/forecast and
v1/forecast both yield https://api.example.com/v2/v1/forecast.
The cloud-metadata blocklist (169.254.169.254, metadata.google.internal,
100.100.100.200) and HTTPS enforcement still take precedence — base_url
cannot unblock SSRF targets or downgrade to plain HTTP. See the security
threat model in Architecture: Security for the
implications of tenants configuring arbitrary HTTPS hosts.
Redirects¶
On the Huitzo platform, ctx.http follows a redirect only when its target
passes the same checks as the URL the pack asked for: the allowlist (or
base_url host), HTTPS, the metadata blocklist, and the private-address check
on every address the host resolves to. The platform runs those checks on each
request it sends, so a redirect that fails them raises HTTPSecurityError
before it is sent, and the error's domain names the redirect's host (#1744).
On every hop the platform resolves the host once, refuses it if any address it
resolves to is private, and connects to one of those vetted addresses, never
to the name, so the address that was checked is the address used (#1963). TLS
still runs against the host name: SNI, certificate verification and the
Host header are unchanged. A host that does not resolve is refused with
HTTPSecurityError rather than handed on to a second lookup.
ctx.http does not use the platform's environment proxies (HTTPS_PROXY,
HTTP_PROXY, ALL_PROXY, NO_PROXY): a proxy would resolve the name again,
out of reach of the check, so every request and every redirect hop connects
directly to its vetted address.
A request follows at most HUITZO_HTTP_MAX_REDIRECTS redirects (5 by default);
a longer chain raises HTTPError and is not retried. The manifest's
services.http.max_redirects is not applied yet (#1872).
What the checks do not cover:
- Egress through a proxy. There is no egress-proxy setting for
ctx.httpyet. One would have to open its tunnel (CONNECT) to the vetted address, not to the name. Until then, a deployment whose egress must pass a proxy needs direct outbound HTTPS from the workers forctx.http. - What a passing redirect carries. A redirect that keeps the method (any
307 or 308, or a 301 answering anything but a POST) sends the request body
again, and headers other than
AuthorizationandCookie, such asX-API-Key, go to the next host. Under"*"that host can be any public one. - Local development. The CLI's local sandbox (
huitzo pack dev,huitzo pack execorhuitzo sandbox startwith--local-keys) follows redirects without these checks (#1873).
Upgrade note. Redirects used to be followed unchecked. If an API you call
redirects to another host, such as a CDN or a regional endpoint, add that host
to allowed_domains.
Error messages¶
An HTTPError message names the request as scheme://host[:port]/path and the
failure (status, attempts, or the exception class). The query string, basic-auth
userinfo and fragment never appear in the message, in the error's url, or in
the platform's retry log, so an API key passed as ?api_key=... stays out of
logs when a call fails. See
Security: Error message hygiene.
Error Handling¶
from huitzo_sdk.errors import HTTPError, HTTPSecurityError
try:
response = await ctx.http.get("https://api.example.com/data")
except HTTPSecurityError as e:
ctx.log.error(f"Domain not allowed: {e.domain}")
# e.domain: The blocked domain
# e.allowed_domains: List of allowed domains
except HTTPError as e:
ctx.log.error(f"HTTP request failed: {e.status_code}")
# e.url: Request URL
# e.method: HTTP method
# e.status_code: Response status
# e.response_body: Response body (truncated)
Retry Logic¶
Both ctx.http and ctx.llm share one retry-with-backoff policy for
transient failures — a timeout, a connection error, or a retryable status
code (502/503/504, plus 429 and 500 for LLM calls) triggers an exponential
backoff (1s, 2s, 4s, ...) up to a configured attempt ceiling before the
call surfaces as a typed error (HTTPError / LLMError) to the pack.
# pseudocode — conceptual retry shape, not the literal implementation
for attempt in range(max_retries):
try:
response = await make_request()
if response.status_code in retryable_status_codes:
await sleep(backoff_for(attempt))
continue
return response
except (TimeoutError, ConnectionError):
await sleep(backoff_for(attempt))
# every attempt exhausted -> a typed error surfaces to the pack
A caller running under its own explicit wall-clock budget (e.g. the async
SPECIFY job — see Architecture: Studio Artifact Model)
may additionally bound the retry loop by a deadline: once a retry would start
with too little of that budget left to plausibly complete, the loop stops
rather than spawning an attempt only the caller's own outer timeout could
ever cut short. This applies only to a caller that opts into an explicit
budget; ordinary ctx.http/ctx.llm calls retry exactly as described above.
Telegram Integration¶
Send messages and documents via Telegram bot.
Configuration¶
| Variable | Required | Description |
|---|---|---|
TELEGRAM_BOT_TOKEN |
✅ | Bot token from @BotFather |
Send Message¶
@command("alert", namespace="notifications")
async def alert(args: Args, ctx: Context) -> dict:
await ctx.telegram.send(
chat_id=args.chat_id, # User or group chat ID
message="Alert: System status changed to WARNING"
)
return {"sent": True}
Formatted Message¶
await ctx.telegram.send(
chat_id="123456789",
message="*Bold* and _italic_ text\n\n`code block`",
parse_mode="Markdown" # or "HTML"
)
Send Document¶
pdf_bytes = generate_report()
await ctx.telegram.send_document(
chat_id="123456789",
document=pdf_bytes,
filename="report.pdf",
caption="Your weekly report"
)
Send Photo¶
await ctx.telegram.send_photo(
chat_id="123456789",
photo=image_bytes,
caption="Chart: Revenue over time"
)
Log Integration¶
Emit structured log lines from pack commands. Lines flow into the platform's JSON log stream alongside platform logs, automatically tagged with the pack's tenant, user, namespace, and correlation IDs.
Usage¶
# pseudocode
ctx.log.info("processing claim", claim_id=args.claim_id, dimensions=len(args.dimensions))
ctx.log.warning("rate limit retry", attempt=2, wait_ms=500)
ctx.log.error("upstream timeout", service="claims-api", elapsed_ms=4500)
message is a single string. Structured fields go in keyword arguments — the
SDK does NOT support printf-style positional formatting.
Sensitive-Field Scrubbing¶
The platform redacts log values whose key names look sensitive. The single
source of truth for the pattern is _SENSITIVE_FIELD_RE in
tools/sdk/src/huitzo_sdk/errors.py (currently
(password|passwd|secret|token|api[_-]?key|credential|auth), case-insensitive,
matched as a substring — so it catches api_key, apikey, AND x-api-key).
Two layers apply the same regex:
- SDK (
huitzo_sdk.integrations.log._scrub_kwargs): replaces the value of any top-level kwarg whose key name matches the regex with<redacted>before the kwargs reach the backend. - Backend (
HuitzoLogBackend._scrub_value): imports the same compiled regex and walks one level into dict and list values, redacting subkeys whose names match. Protects the common footgun where the outer kwarg key is benign but the dict carries sensitive sub-values, e.g.headers={"x-api-key": "..."}orpayload={"password": "..."}.
Both passes are name-based only. Free-form sensitive values inside the
message string, or sensitive payloads more than one level deep, are NOT
redacted. Pack authors are responsible for what they log.
Sentry Routing¶
Pack-emitted ctx.log.error(...) lines are surfaced to Sentry as breadcrumbs,
not as standalone events, so a chatty pack can't flood the platform's Sentry
quota. Real pack failures (uncaught exceptions raised inside the command
function) still create Sentry events through the command-execution wrapper.
Files Integration¶
Read and write files from user uploads and pack storage.
Backend Abstraction¶
The ctx.files API is backend-agnostic—your pack code works identically whether the platform uses local filesystem, S3, Azure Blob, or GCS. The storage backend is configured at the platform level, not in pack code.
# This code works with ANY storage backend
@command("process-data", namespace="analytics")
async def process_data(args: Args, ctx: Context) -> dict:
df = await ctx.files.read_excel(args.file_path) # Works everywhere
result = analyze(df)
await ctx.files.write("output/report.csv", result.to_csv()) # Works everywhere
return {"status": "complete"}
Pack developers don't need to know or care which backend is configured. See File Storage Backends for platform configuration details.
Permissions¶
ctx.files is available when the pack's policy.allowed_actions holds any of files:read, files:write or files:delete. Each operation then needs its own token:
| Operations | Token |
|---|---|
read, read_excel, read_csv, read_json, info, list, exists, get_url(method="GET") |
files:read |
write, copy, get_url(method="PUT") |
files:write |
delete |
files:delete |
move, rename |
files:write and files:delete |
These are pack permission tokens, not the files:read API-key scope that the download endpoint checks.
On the platform, an operation without its token raises PackPermissionError (HTTP 403), relayed to the pack's isolated child. A pack holding none of the three tokens has no ctx.files; accessing it raises IntegrationError. Add the token to the pack's permissions: and policy.allowed_actions, then republish the pack.
Local development. The CLI's local sandbox (huitzo pack dev, huitzo pack exec or huitzo sandbox start with --local-keys) wires ctx.files without these checks, so a missing token shows up only on the platform.
Read Excel¶
@command("analyze-excel", namespace="data")
async def analyze_excel(args: Args, ctx: Context) -> dict:
# Returns pandas DataFrame
df = await ctx.files.read_excel(args.file_path)
# Specific sheet
df = await ctx.files.read_excel(args.file_path, sheet="Sales")
return {"rows": len(df), "columns": list(df.columns)}
Read CSV¶
df = await ctx.files.read_csv(args.file_path)
df = await ctx.files.read_csv(args.file_path, delimiter=";", encoding="utf-8")
Read JSON¶
data = await ctx.files.read_json(args.file_path)
Write Files¶
# Write CSV
await ctx.files.write("output/report.csv", df.to_csv(index=False))
# Write JSON
await ctx.files.write("output/data.json", json.dumps(data, indent=2))
# Write binary
await ctx.files.write("output/report.pdf", pdf_bytes, binary=True)
File Information¶
info = await ctx.files.info(args.file_path)
# Returns: {"size": 1024, "created": datetime, "modified": datetime, "type": "xlsx"}
List Files¶
files = await ctx.files.list("uploads/")
# Returns: [{"name": "data.xlsx", "size": 1024, "modified": datetime}, ...]
File Existence¶
if await ctx.files.exists("uploads/data.xlsx"):
df = await ctx.files.read_excel("uploads/data.xlsx")
Get Download URL¶
Generate a URL for direct file download (useful for returning file links to users). The result depends on the configured storage backend:
| Backend | get_url() result |
|---|---|
| Local | /api/v1/files/{path} — the authenticated download endpoint; path segments percent-encoded (a filename's #, ?, %, or spaces survive the round trip); no expiry semantics, auth is required on every request |
| S3 / Azure / GCS | Time-limited presigned URL (expires seconds) |
# pseudocode — get_url result per backend
url = await ctx.files.get_url("output/report.pdf", expires=3600) # 1 hour
# local backend -> "/api/v1/files/output/report.pdf" (expires does not apply)
# object storage -> time-limited presigned URL for direct download
return {"download_url": url}
The local backend previously returned
/files/t/...URLs that no route served. Those dead URLs are gone —LocalFileSystem.get_urlnow returns/api/v1/files/{path}paths, which resolve against the authenticated endpoint on any deployment.
For how dashboards consume the authenticated endpoint (fetch with credentials, then a blob URL), see Downloading files over HTTP.
File Limits¶
Platform-wide defaults (configurable by administrators):
| Limit | Default | Environment Variable |
|---|---|---|
| Max file size | 100 MB | HUITZO_FILE_MAX_SIZE_MB |
| Max files per user | 1000 | HUITZO_FILE_MAX_PER_USER |
| Tenant storage quota | 10 GB | HUITZO_FILE_QUOTA_GB |
Packs can declare stricter limits in the manifest:
# huitzo.yaml
services:
files:
max_size_mb: 50 # Stricter than platform default
allowed_types:
- .csv
- .xlsx
- .json
Tenant Isolation¶
Files are automatically isolated by tenant. Pack code uses relative paths:
# Pack writes to "output/report.pdf"
await ctx.files.write("output/report.pdf", data)
# Platform stores at: tenant/{tenant_id}/output/report.pdf
# Other tenants cannot access this file
Integration Permissions¶
Permissions are declared once, at pack level, not per command (ADR-003 D4). A per-command permissions: list is rejected by the manifest model. Every permission must also appear in policy.allowed_actions (ADR-005):
# huitzo.yaml
services:
llm:
required: true
files:
required: true
policy:
autonomy: "act_with_approval"
allowed_actions:
- "llm:complete"
- "llm:stream"
- "files:read"
- "files:write"
data_scope:
scope: "tenant"
audit:
level: "standard"
permissions:
- "llm:complete" # LLM completion
- "llm:stream" # LLM streaming
- "files:read" # Read files
- "files:write" # Write files
See the Permission Registry for every token and the service it requires, and Files permissions for the per-operation ctx.files table.
Best Practices¶
1. Declare needs via profiles, never model names¶
# ✅ Good: the default profile covers simple tasks
summary = await ctx.llm.complete(prompt=simple_prompt, profile="default")
# ✅ Good: a named profile (declared in the manifest) for harder tasks
analysis = await ctx.llm.complete(prompt=complex_prompt, profile="accurate")
# ❌ Bad: never name a model in pack code — the deployment owns model choice
2. Handle Integration Errors¶
# ✅ Good: Graceful degradation
try:
await ctx.email.send(to=user_email, subject="Report", body=content)
except EmailError:
ctx.log.warning("Email failed, saving to storage instead")
await ctx.storage.save("pending-email", {"to": user_email, "content": content})
3. Respect Rate Limits¶
# ✅ Good: Batch operations where possible
# Instead of 100 individual LLM calls, batch into fewer calls with more content
4. Secure API Keys¶
# pseudocode
# ❌ Bad: hardcoded API key
response = await ctx.http.get(url, headers={"Authorization": "Bearer sk-xxx"})
# ✅ Good: read the caller's own credential from Tier 3 user secrets
api_key = await ctx.secrets.require("EXTERNAL_API_KEY")
response = await ctx.http.get(url, headers={"Authorization": f"Bearer {api_key}"})
The SDK gives packs no way to read a platform (Tier 1) secret. There is no
ctx.env— it is not implemented, and no accessor is planned that would hand platform credentials to pack code. If a pack needs a credential of its own, it belongs in Tier 3 (ctx.secrets). This is an API-surface contract, not a sandbox: pack code runs in an env-scrubbed child process, confined from the platform's credentials only where the sandbox helper is installed — see Secrets Management.
User Secrets for External Services¶
When your pack integrates with external services where each user has their own API key (e.g., Plaid, QuickBooks, or a third-party Stripe account), use the ctx.secrets API. This is an external integration credential example, not Huitzo marketplace billing or Stripe Connect support. ctx.secrets is the only credential accessor a pack has.
When to Use User Secrets¶
| Scenario | Tier | How the pack gets it |
|---|---|---|
| Platform-wide LLM key | Platform (Tier 1) | Never directly — call ctx.llm.complete(...); the platform supplies the key |
| Platform email service | Platform (Tier 1) | Never directly — call ctx.email.send(...) |
| User's own CRM API key | User (Tier 3) | await ctx.secrets.require("CRM_API_KEY") |
| User's financial data provider | User (Tier 3) | await ctx.secrets.require("PLAID_API_KEY") |
Declaring User Secrets¶
Declaring a secret is not documentation — it is the authorization input that lets your pack read that name at all. Both user_required and user_optional grant the same read authority; a name in neither list is refused before any lookup and is indistinguishable from an unconfigured secret. See Declared-secret authorization.
Declare required user secrets in your pack manifest:
# huitzo.yaml
secrets:
user_required:
- name: "PLAID_CLIENT_ID"
description: "Your Plaid client ID"
help_url: "https://dashboard.plaid.com/developers/keys"
- name: "PLAID_SECRET"
description: "Your Plaid secret key"
help_url: "https://dashboard.plaid.com/developers/keys"
user_optional:
- name: "PREMIUM_DATA_KEY"
description: "Optional: Premium data provider API key"
Accessing User Secrets¶
The secrets API has three methods:
| Method | Behavior | Use When |
|---|---|---|
await ctx.secrets.require(name) |
Returns value or raises SecretsError |
Secret is mandatory for the command |
await ctx.secrets.get(name) |
Returns value or None |
Secret is optional |
await ctx.secrets.exists(name) |
Returns bool |
Checking before conditional logic |
# pseudocode — accessing user secrets in a command
# Required secret → raises SecretsError if the user hasn't configured it
api_key = await ctx.secrets.require("SECRET_NAME")
# Optional secret → returns None if not set
optional_key = await ctx.secrets.get("OPTIONAL_SECRET_NAME")
# Use the credentials with your external service
result = await external_service.call(api_key=api_key, ...)
# Conditionally use optional features
if optional_key:
result = await enrich_result(result, optional_key)
Error Handling for User Secrets¶
Provide helpful guidance when secrets are missing or invalid:
# pseudocode — secrets error handling pattern
try:
api_key = await ctx.secrets.require("SECRET_NAME")
except SecretsError:
# Return user-friendly guidance. Nothing prompts the user for you — there is
# no install-time secrets surface and no deep-link on the error, so this
# string is the ONLY guidance they get. See
# docs/reference/secrets.md#configuring-a-secret for the real path.
return {"error": "...", "help": "Add your key on the Integrations page"}
try:
data = await external_api.call(api_key, ...)
except AuthenticationError:
# Wrap as ExternalAPIError with actionable message
raise ExternalAPIError(service="...", message="Key invalid. Update it on the Integrations page.")
Best Practices for User Secrets¶
- Minimize required secrets - Only require what's essential
```yaml # ✅ Good: Single required secret secrets: user_required: - name: "API_KEY" description: "Your service API key"
# ❌ Avoid: Too many required secrets secrets: user_required: - name: "API_KEY" - name: "API_SECRET" - name: "API_REGION" - name: "API_VERSION" ```
- Provide clear descriptions and help URLs
yaml
secrets:
user_required:
- name: "STRIPE_SECRET_KEY"
description: "Your Stripe secret key (starts with sk_)"
help_url: "https://dashboard.stripe.com/apikeys"
- Use optional secrets for premium features
python
if await ctx.secrets.exists("PREMIUM_API_KEY"):
return await premium_analysis(data)
else:
return await standard_analysis(data)
- Validate credentials early
```python @command("setup", namespace="integration") async def setup(args: Args, ctx: Context) -> dict: """Validate user credentials before first use.""" api_key = await ctx.secrets.require("SERVICE_API_KEY")
# Verify the key works
valid = await service.validate_key(api_key)
if not valid:
raise ExternalAPIError(
service="service-name",
message="API key validation failed. Please check your key."
)
return {"status": "configured", "valid": True}
```
Related: See Secrets Management for the complete three-tier secrets model.
Database Integration¶
The database integration lets a pack run parameterised queries against
user-registered Postgres or MySQL connectors. Connectors are stored in the
unified Integration registry and resolved at command-execution time when the
pack manifest declares services.db.
Architecture: Full lifecycle (create → verify → use → revoke → audit), security boundaries, and the registry contract live in Integrations Subsystem v2.
Declaring DB integrations in the manifest¶
# huitzo.yaml — pseudocode
services:
db: # required to receive ctx.db at runtime
integrations: # optional name allowlist (omit to allow any)
- "primary"
- "warehouse"
The allowlist is pack-wide and applies on every path that wires ctx.db: REST,
MCP and scheduled runs (manifest cron and per-user schedules) alike. Field
reference: Database Service Configuration.
Querying¶
# pseudocode — read rows
rows = await ctx.db.query(
"primary", # integration name
"SELECT id, email FROM users WHERE id = $1",
user_id,
timeout=10,
)
# rows is a list[dict[str, Any]] with one entry per row.
Mutating¶
# pseudocode — INSERT / UPDATE / DELETE
n = await ctx.db.execute(
"primary",
"UPDATE users SET active = $1 WHERE id = $2",
True, user_id,
)
# n is the integer row count reported by the engine.
Transactions¶
# pseudocode — multi-statement transaction (commits on clean exit, rolls back on raise)
async with ctx.db.transaction("primary") as txn:
await txn.execute("INSERT INTO orders (id, total) VALUES ($1, $2)", order_id, 99)
await txn.execute("UPDATE inventory SET qty = qty - 1 WHERE sku = $1", sku)
Placeholder syntax¶
| Engine | Placeholder | Example |
|---|---|---|
Postgres (type=postgres) |
$1, $2, ... |
WHERE id = $1 |
MySQL (type=mysql) |
%s |
WHERE id = %s |
Limits and security¶
| Concern | Default | How to change |
|---|---|---|
| Query timeout | 30 s | Pass timeout=… (max 300 s) |
| Result row cap | 10 000 (default) | Set row_limit on the integration config; max 1 000 000 |
DDL (CREATE/DROP/ALTER/...) |
rejected | Set allow_ddl: true on the integration |
| TLS for Postgres | sslmode=require |
verify-ca / verify-full; disable is rejected (see the TLS note below) |
| Internal hosts (loopback / RFC1918) | rejected if any resolved address is internal | self-hosted/edge only — set HUITZO_ALLOW_INTERNAL_HOSTS=true; hard-blocked on Cloud regardless of this setting (#1262) |
TLS note. If the deployment has a Postgres root certificate
(PGSSLROOTCERT or ~/.postgresql/root.crt), every mode verifies the
server's chain against it, require included, and verify-full also checks
the host name. Without one, require encrypts without verifying, and
verify-ca/verify-full verify against the system trust store and both check
the host name. A deployment revocation list (PGSSLCRL), client certificate
(PGSSLCERT/PGSSLKEY) and TLS version bounds (PGSSLMINPROTOCOLVERSION,
TLS 1.2 by default, and PGSSLMAXPROTOCOLVERSION) apply to every integration.
These deployment settings are read once per process. A per-integration CA is
not supported yet.
The platform connects to the addresses the internal-host check vetted, in resolver order, never to the name a second time, so a DNS answer that changes after the check is not followed (#1744). TLS SNI and certificate verification still use the host name.
Error handling¶
from huitzo_sdk.errors import DatabaseError
try:
rows = await ctx.db.query("primary", "SELECT 1")
except DatabaseError as e:
ctx.log.error(f"DB query failed on {e.integration!r}: {e.message}")
DatabaseError is raised for: integration not in the manifest allowlist,
DDL violations, timeouts, row-limit overruns, SSRF/TLS gate failures, and
all driver-level errors (asyncpg / aiomysql).
MCP Integration¶
Not available on hosted execution yet:
ctx.mcpis not wired on any hosted execution path, so a command that calls it fails withIntegrationError. Tracked in #1943.
The MCP (Model Context Protocol) integration enables your pack to call tools from external MCP servers. This provides a standardized way to integrate with services like GitHub, PostgreSQL, Slack, and many others.
Overview¶
| Aspect | Details |
|---|---|
| Access | ctx.mcp |
| Configuration | mcp_servers section in huitzo.yaml |
| Transport | STDIO (subprocess) or HTTP+SSE (remote) |
| Discovery | Tools discovered automatically via tools/list |
Quick Example¶
from huitzo_sdk import command, Context
@command("github-issue", namespace="devtools")
async def github_issue(args: Args, ctx: Context) -> dict:
"""Create a GitHub issue using MCP."""
result = await ctx.mcp.call(
server="github",
tool="create_issue",
arguments={
"owner": args.owner,
"repo": args.repo,
"title": args.title,
"body": args.body
}
)
return {"issue_number": result["number"], "url": result["html_url"]}
Configuration¶
# huitzo.yaml
mcp_servers:
- name: github
type: stdio
command: ["uvx", "mcp-server-github"]
env:
GITHUB_TOKEN: "${secrets.GITHUB_TOKEN}"
secrets:
user_required:
- name: "GITHUB_TOKEN"
description: "Your GitHub personal access token"
help_url: "https://github.com/settings/tokens"
Error Handling¶
from huitzo_sdk.errors import MCPError, MCPConnectionError, MCPToolError
try:
result = await ctx.mcp.call("github", "create_issue", {...})
except MCPConnectionError:
ctx.log.error("GitHub MCP server unavailable")
return {"error": "GitHub integration temporarily unavailable"}
except MCPToolError as e:
ctx.log.error(f"GitHub tool failed: {e.message}")
raise
Available MCP Servers¶
Popular MCP servers include:
| Server | Package | Description |
|---|---|---|
| GitHub | mcp-server-github |
GitHub API (issues, PRs, repos) |
| PostgreSQL | mcp-server-postgres |
Database queries |
| Filesystem | mcp-server-filesystem |
File operations |
| Slack | mcp-server-slack |
Slack messaging |
| Brave Search | mcp-server-brave-search |
Web search |
See the MCP Server Directory for more options.
Full Reference: See MCP Reference for complete API documentation.
Related Documentation¶
- Context Reference – Full Context API
- MCP Reference – MCP API documentation
- Commands Reference – Command patterns
- Error Handling – Integration errors
- File Storage Backends – Platform file storage configuration
- Secrets Management – Three-tier secrets model
- Configuration – Environment variables