Kirak is an open-source backend runtime. Declare your data model, auth, and access rules in JSON; Kirak serves the whole backend — REST & GraphQL APIs, authentication, row-level security, payments, storage, notifications, AI agents, and MCP servers — live from that declaration. Self-host it anywhere. No account, no key, no phone-home.
Python 3.11 or newer.
pip install kirak
Creates main.py, kirak.json, a sample model in models/, hooks/, an AGENTS.md for coding agents, and JSON Schemas your editor picks up. The project's pyproject.toml pulls in the database driver.
kirak new my-backend --database postgres # or mysql, or sqlite cd my-backend pip install -e . cp .env.example .env # secrets only: DB password + JWT keys
One file per model: its fields and access rules in models/note.json. Run kirak validate to check it.
{ "schema": { "title": {"type":"string","required":true}, "body": {"type":"text"}, "owner_id": {"type":"integer","required":true} }, "access": { "fetch": [{"role":"user","condition":"owner_id = {user_id}"}], "create": [{"role":"user","condition":"owner_id = {user_id}"}] } }
Applies the schema to your database, then starts serving on :8000.
kirak db init uvicorn main:app --reload
Full CRUD on /note, access-filtered to the authenticated user by owner_id.
curl -X POST localhost:8000/note/create \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d '{"data":{"title":"first","body":"hello"}}'
Run kirak deploy in the project folder and the API is live on Kirak's hosting, with a public URL — no account required. The instance is temporary until you claim it, which keeps it running on the free tier. How Kirak Deploy works →
kirak deploy Deployed: https://<random-name>.kirak.dev Claim URL: https://...
Blue layers are served automatically from your declaration; amber is the one layer where you write real Python you own. Coding-agent tooling is set apart at the end.
Every model file in models/ becomes a documented endpoint set — list, search, count, create, update, upsert, soft delete and restore, hard delete — with filtering, pagination, sorting, per-model rate limits, and before/after hooks on every operation. The same operations are served over a shared GraphQL endpoint, under the same access rules. Change a field and the API changes with it.
Per-role access rules declared as an access block in each model file, enforced at the query level on every list, read, and join — for every role. Field rules go further: hide a column from some roles, or make it read-only. Declarative, not a bolt-on policy language you maintain separately.
"access": { "fetch": [ {"role":"admin"}, {"role":"user", "condition":"renter_id = {user_id}"} ], "create": [{"role":"user"}], "update": [{"role":"user", "condition":"renter_id = {user_id}"}], "destroy": [{"role":"admin"}], "fields": { "internal_notes": { "read": ["admin"], "write": ["admin"] } } }
The one place you write real code. Business logic that isn't plain CRUD runs as before/after hooks on every operation, or as fully custom endpoints beyond the generated set. Sync hooks are blocking: they work like a pipeline — each takes the request, modifies it, and feeds it to the next hook or the operation, and raising an error stops the request with a clean 4xx.
Async hooks are non-blocking: a failure or timeout is logged and skipped, so they suit side effects like notifications that must never fail the request. Real Python/FastAPI — scaffolded for you, committed to your own repo, surviving every later declaration change. It runs inside the runtime's access rules, so you extend the backend without opening a hole in it.
# registered inside on_kirak_ready(kirak) # sync hooks are a blocking pipeline: each takes the request, modifies it, # and feeds it to the next hook or the operation -- raise to stop it @kirak.on("booking").hook("before_create") def check_dates(payload): data = payload["data"] if data["ends_at"] <= data["starts_at"]: raise ValidationError("ends_at must be after starts_at") # 400 return payload @kirak.on("booking").hook("before_create") def apply_deposit(payload): # runs next, on check_dates' output payload["data"]["deposit_cents"] = payload["data"]["total_cents"] * 20 // 100 return payload # async hooks are non-blocking: a failure or timeout is logged # and skipped -- it never fails the request @kirak.on("booking").hook("after_create") async def notify_owner(result): await kirak.notifications.send_im({"to": OWNER_CHANNEL, "text": "New booking"}) return result
MFA, passwordless SMS one-time codes, API keys, and email verification are built directly into Kirak Auth — Kirak's own build on JWT sessions with refresh-token rotation, not bolted on from a third-party library. Social / OAuth login is powered separately by Social Core, covering 200+ provider backends.
# kirak.auth — in any hook or custom endpoint result = await kirak.auth.login({"email": email, "password": password}) result = await kirak.auth.get_current_user({"request": request}) # in a hook, from kirak.auth.utils.jwt token = create_access_token(subject=str(user_id), extra_claims={"role": "user"})
Checkout, one-off charges, subscriptions (cancel, change, pause, resume), refunds, saved cards and off-session charges, disputes, and Stripe Connect marketplace payouts — with webhook verification and reconciliation wired up, served by the runtime, not a hook you maintain. Run several gateways side by side as named providers; amounts are handled in each currency's minor unit. Provisioning logic lives in an after_webhook hook when you need it.
# kirak.payments — in any hook or custom endpoint # verify_payment / refund_payment / get_billing_portal are Python-only, no built-in route result = await kirak.payments.initiate_payment({ "provider": "paypal", # any configured gateway; omit for the default "user_id": "42", "amount": 2999, "currency": "USD", "type": "one_time", "name": "Pro Plan" }) portal = await kirak.payments.get_billing_portal({"user_id": "42", "return_url": "..."})
File and image upload with automatic image compression and thumbnail generation. Declare an upload field and the runtime handles multipart parsing, validation, and the storage backend — local disk or any of nine object stores, several at once as named providers.
kirak.json — no code change# kirak.storage — in any hook or custom endpoint result = await kirak.storage.upload_image( file=file_bytes, path="images/avatars/user_42.jpg", filename="photo.jpg", thumbnails=[{"name":"sm","width":100,"height":100}], ) url = await kirak.storage.get_url(path="images/avatars/user_42.jpg", expires=3600)
Email, SMS, push, instant messages to Slack, Discord, or Telegram, signed outgoing webhooks, and an in-app notification inbox, each with its own send method — delivery, templates, and per-user preference checks are runtime concerns; you call kirak.notifications from a hook or route.
kirak.json# kirak.notifications — in any hook or custom endpoint await kirak.notifications.send_email({"to": user_email, "template_name": "booking_confirmed", "template_params": data}) await kirak.notifications.send_sms({"to": phone, "message": "Your code is 4821"}) await kirak.notifications.send_notification({"user_id": user_id, "title": "Booking confirmed"}) await kirak.notifications.send_im({"to": "C0123456789", "text": "New booking"})
Let your users connect their own third-party accounts, through OAuth2 or API keys. Kirak encrypts the tokens with AES-GCM, refreshes them automatically, hands your code a ready client for API calls, and stores and retries incoming webhooks. Pick from ready-made profiles or define your own without touching Kirak.
# kirak.integrations — in any hook or custom endpoint repos = await kirak.integrations.get("github", "/user/repos", user_id=42) # react to a webhook from a connected service @kirak.integrations.on_webhook("github", "push") async def on_push(...): ...
Background job queue and cron scheduler with zero extra infrastructure by default — DB-backed out of the box. Register a job with a decorator, or create schedules at runtime over HTTP; the runtime handles timing, retries with backoff, timeouts, crash recovery, and history. Route queues to several backends at once, or run in serverless tick mode.
# registered inside on_kirak_ready(kirak) @kirak.scheduler.cron("0 * * * *") # register a recurring job async def expire_holds(payload: dict) -> None: ... # kirak.scheduler — enqueue from any hook await kirak.scheduler.enqueue(task="send_report", payload={"org_id": org_id}) await kirak.scheduler.enqueue(task="send_reminder", payload={}, run_at=int(time.time()) + 3600)
Native Redis query caching: switch it on for every model in kirak.json, or per model in its own file. The runtime keys each entry by what the caller is allowed to see, invalidates on write, and serves reads from cache — no cache code in your project.
// default for every model "cache": { "enabled": true, "default_ttl_seconds": 60 }
// per-model override, next to "schema" and "access" "cache": { "enabled": true, "ttl_seconds": 300 }
Global limits and per-model overrides, with Redis or database-backed counters and standard rate-limit headers. Declared, not coded.
Retry-After header// default for every route "rate_limit": { "enabled": true, "default_max_requests": 100, "default_window_seconds": 60 }
// per-model override, next to "schema" and "access" "rate_limit": { "create": { "max_requests": 5, "window_seconds": 60 } }
Declare agents in agents/*.json: a model, instructions, and the tools they may use — CRUD on your models, a module's operations, or whole MCP servers. For anything custom, register a Python function with @kirak.agent("name").tool, the same way you write a hook. Every tool call runs as the caller, under your access rules, and each agent sets who may run it and a per-caller rate limit. Mark a tool requires_confirmation and the run pauses for a human to approve it.
Multi-turn conversations with automatic compaction, cost caps, goal-driven runs checked by a reviewer model, streaming, structured output, and a full run history are built in — with model, tokens, cost, and tool calls recorded by monitoring.
Built on pydantic-ai — so any model pydantic-ai supports works, not a fixed provider list: OpenAI, Anthropic, Gemini, OpenRouter, and more.
{ "name": "support", "model": "anthropic:claude-haiku-4-5-20251001", "instructions": "Help customers with their orders.", "access": "User", "rate_limit_per_minute": 30, "tools": { "orders.fetch": {}, "vector.search": {}, "payments.refund_payment": { "requires_confirmation": true } } }
# a custom tool, registered like a hook @kirak.agent("support").tool async def delivery_eta(ctx, order_id: str) -> dict: """Estimated delivery date for an order.""" ... # kirak.ai — in any hook or custom endpoint (BYOK) result = await kirak.ai.prompt({"prompt": document, "output_schema": Invoice}) result = await kirak.ai.run_agent({"agent": "support", "prompt": question, "max_budget_usd": 0.05})
Declare an MCP server per audience — an admin server for an internal agent, a support server for a customer-facing one, one for a UI builder — each a JSON file in mcp/ with its own toolkit: the operations it offers as tools, who may connect, and a rate limit. Add Python tools to a server with @kirak.mcp("support").tool. Any MCP client can connect; every tool call runs as the caller, under your access rules. Nothing is exposed until you declare it.
/mcp/<name>/ · bearer token or API key · calls per server and tool recorded by monitoring{ "name": "support", "description": "Order lookups for the support team", "access": "User", "rate_limit_per_minute": 60, "tools": { "orders.fetch": {}, "orders.search": {}, "orders.update": { "timeout": 10 } } }
# registered inside on_kirak_ready(kirak) @kirak.mcp("support").tool async def order_summary(order_id: int, include_items: bool = False) -> dict: """One order with its customer and items, in one call.""" result = await kirak.graphql({"query": ORDER_SUMMARY, "variables": {"id": order_id}}) return result["data"] # the client asks the user to confirm before it runs @kirak.mcp("support").tool(requires_confirmation=True, destructive=True) async def close_account(user_id: int) -> dict: """Close a customer's account.""" ...
Vector stores and embeddings for retrieval-augmented generation: create indexes, upsert text or vectors, and search with metadata filters. Agents use it as a tool, so the agent decides when to retrieve — there's no fixed pipeline to maintain. No public HTTP endpoints by design — call it from your own routes, hooks, and agents under your access rules.
kirak.jsonawait kirak.vector.upsert({ "index": "docs", "vectors": [{"id": "faq-1", "text": "Refunds take 5 days."}], }) result = await kirak.vector.search({ "index": "docs", "text": "How long do refunds take?", "top_k": 5, })
A Kirak project is mostly JSON, so a coding agent needs facts it can't guess and a way to know its edit is valid. kirak new writes an AGENTS.md and JSON Schemas for every file; kirak validate checks each edit before the app starts; kirak catalog --json and friends report modules, providers, settings, and secrets for the installed version; kirak dev mcp serves all of it to the agent over MCP; GET /docs describes the running API in Markdown; and the Agent Kit plugins teach the agent how to use it all.
kirak validate # models, kirak.json, agents, MCP servers kirak catalog --json # every module, provider, and setting kirak providers payments --json # settings + secrets for each gateway kirak env # the secrets this project needs kirak dev mcp # all of the above, over MCP
Application performance data, structured logs, error tracking, per-request tracing, audit records, AI run costs, and MCP tool calls — opt-in module, the instrumentation lives in the runtime itself, so you can see into a Kirak backend without bolting on a third-party APM.
PostgreSQL, MySQL, or SQLite, switched with one line — "database": {"type": "postgres"} in kirak.json — not tied to a single vendor.
Security controls built to help the APIs you serve pass a SOC 2 review.
Lazy-loaded, so nothing ships unless you enable it. Self-host it on your own database, anywhere you run Python.
Official client SDKs for calling a Kirak backend from your app — sign-in and sessions handled for you, so your UI code only talks about your data.
The core client for any JavaScript runtime — the browser, Node.js, and React Native.
React bindings for the Kirak client, for using your backend from React components.
The Dart and Flutter client — sign-in sessions persisted and restored across app starts.
kirak dev mcp is a local MCP server for the agent writing your backend. Your coding tool starts it in the project folder; it opens no port, needs no credentials, and every tool is read-only. Instead of guessing at Kirak, the agent asks.
The agent can read the project — Kirak version, enabled modules, models, agents, migrations — and look up every module, provider, setting, and secret the installed Kirak supports. It fetches the JSON Schema for any file it's about to write, and validates a draft before saving it, so a bad edit never reaches the running app. Migration status and a dry-run preview tell it what a schema change will do to the database.
kirak command's --jsonkirak_project_info # version, modules, models, agents kirak_catalog # modules, providers, settings, secrets kirak_schema # JSON Schema for any Kirak file kirak_validate # check a draft before it's written kirak_env # the secrets this project needs kirak_migration_status # applied and pending migrations kirak_migration_preview # what the next migration would do
Live tools show the agent what your running app has been doing: recent errors with tracebacks and the request that failed, recent requests filtered by status or route, a full trace of any one request through its hooks, database, and provider calls, and recent AI agent runs with their tokens, cost, and tool calls. They read the files the app writes, so they still answer after it has crashed. And the agent can read the app's own /docs before building a front end against it.
kirak.logkirak_recent_errors # tracebacks + the failing request kirak_recent_requests # filter by 5xx, 404, route, slowest kirak_request_trace # hooks, db, provider calls, timings kirak_recent_agent_runs # model, tokens, cost, tool calls kirak_api_docs # the running app's GET /docs // .mcp.json (Claude Code) — same command in any tool { "mcpServers": { "kirak": { "command": "uv", "args": ["run", "kirak", "dev", "mcp"] } } }
The Dev MCP gives an agent the facts. The Agent Kit gives it the judgment: a plugin for each major coding tool with skills, guardrails, and hooks written by the people who build Kirak. It never holds its own copy of a Kirak fact — it tells the agent to ask the project's kirak, so the answers always match your installed version.
How to design models and access rules, choose between configuration, hooks, routes, and modules, pick providers, write AI agents, run migrations, debug, and build a front end against GET /docs.
Kirak first: data only through Kirak's model layer, never raw SQL; a provider before any integration code; settings in kirak.json and only secrets in .env; every model secured with an access block.
Where the tool supports them: validate after every edit of a Kirak file, remind about migrations, guard destructive commands — plus commands to scaffold a model, check project status, and review changes.
Then /plugin install kirak@kirak. Install steps for every tool are in the repository.
OSI-approved. No license-level restriction on commercial use, forking, or offering Kirak as a competing hosted service.
Copy, modify, distribute, and run Kirak for any purpose — including building a commercial product or a hosted service on top of it.
Contributors grant a patent license for their contributions; anyone who sues over patent infringement loses their license to use the software.
The license grants no right to the Kirak name or marks. A fork can rename and rebrand freely, but can't call itself "Kirak" or imply endorsement.
A fork must preserve copyright and attribution notices in the source and mark modified files as changed — it has no obligation to keep the Kirak name or credit Kirak in marketing. That's the deliberate trade-off of Apache 2.0 over a source-available license.
Questions, ideas, and design discussion — indexable and searchable, the durable record.
Open Discussions →Read CONTRIBUTING.md first — it covers the PR process and the policy on AI-generated contributions.