# Wkala documentation Release 0.1.0. Generated from the same canonical pages as the documentation site. # Run your first agent Install the SDK, create a session, and stream a complete execution from your backend. ## Before you begin Create a Wkala account. Verify your email. Wait for operator approval. The operator assigns your provider, models, and limits. Create a key in [your dashboard](/dashboard/keys). Start with read and run permissions. Add configure permission to register tools, skills, or profiles. Keep the service key in your backend. Never put it in a browser bundle, a public environment variable, or a copied AI prompt. Browser clients use same-origin `/app`. ## 1. Install the SDK ### Python Python 3.11 or newer is supported. Install the downloadable release artifact. ```bash python -m pip install "wkala @ https://wkala.okal.io/downloads/wkala-0.1.0-py3-none-any.whl" ``` For a bare Go service, pass `base_url="http://localhost:8080/v1"` to the client. The Compose ingress uses `http://localhost:8088/v1`; native multi-service development uses `http://localhost:18080/v1`; production uses the configured public origin. Python also accepts an origin-style override for compatibility. ### TypeScript Use Node 22.13 or newer. Install the downloadable release artifact. ```bash npm install "https://wkala.okal.io/downloads/wkala-client-0.1.0.tgz" ``` For a bare Go service, pass `baseUrl: "http://localhost:8080/v1"` to the server client. The Compose ingress uses `http://localhost:8088/v1`; native multi-service development uses `http://localhost:18080/v1`; production uses the configured public origin. ## 2. Set the key Set this variable in your backend environment: ```bash export WKALA_API_KEY="your-private-service-key" ``` ## 3. Create and observe a run This example creates a session and submits a release checklist task. It observes updates and inspects the final result. Persist the generated request ID before submission when your application must recover after a restart. ### Python Save this as `first_agent.py`: ```python import asyncio import os import uuid from wkala import AgentClient, SnapshotUpdate async def main(): async with AgentClient(api_key=os.environ["WKALA_API_KEY"]) as agents: session = await agents.sessions.create(title="First task") request_id = str(uuid.uuid4()) run = await session.send( "Draft a concise release checklist for a web application.", idempotency_key=request_id, ) print("Session:", session.id, "Run:", run.id) async with run.stream() as stream: async for update in stream: if isinstance(update, SnapshotUpdate): print("Snapshot restored") else: print(update.type, update.model_dump(mode="json", by_alias=True)) result = await run.result() print(result.status, result.stop_reason) print(result.messages) asyncio.run(main()) ``` Run it: ```bash python first_agent.py ``` ### TypeScript Save this JavaScript-compatible example as `first_agent.mjs`: ```typescript import { createServerClient } from "@wkala/client/server" const apiKey = process.env.WKALA_API_KEY if (!apiKey) { throw new Error("Set WKALA_API_KEY in your backend environment") } const agents = createServerClient({ apiKey }) const session = await agents.sessions.create({ title: "First task" }) const requestId = crypto.randomUUID() const run = await session.send( "Draft a concise release checklist for a web application.", { idempotencyKey: requestId }, ) console.log("Session:", session.id, "Run:", run.id) for await (const event of run.events()) { console.log(event.type, event.data) } const result = await run.result() console.log(result.run.status, result.run.stop_reason) console.log(result.messages) ``` Run it: ```bash node first_agent.mjs ``` `send()` returns after admission. The service continues executing while your application observes it. The result includes messages, tool calls, backend invocations, interactions, and usage. Failed or cancelled executions remain inspectable. Check the status and stop reason. If the run needs input, observation can remain open until another authorized component responds. Follow [approvals and questions](/docs/raw/interactions?locale=en). ### Python Release 0.1.0 is supplied as a downloadable wheel. The install command does not assume a registry publication. Find checksums and downloads on the [documentation home](/llms.txt?locale=en). ### TypeScript Release 0.1.0 is supplied as a downloadable npm archive. The install command does not assume a registry publication. Find checksums and downloads on the [documentation home](/llms.txt?locale=en). ## 4. Choose the next boundary - [Stream messages and tools](/docs/raw/streaming?locale=en). - [Connect backend tools](/docs/raw/backend-tools?locale=en). - [Connect a React interface](/docs/raw/react?locale=en) through your authenticated backend. - [Understand cost and limits](/docs/raw/usage-and-limits?locale=en) before admitting production work. --- # Stream messages, tools, and results Observe the entire execution as it happens, with durable state and reconnect behavior included. ## What streams An execution can produce messages, tool calls, tool results, backend invocations, progress, usage, and requests for input. A completed message does not mean the run has completed. Tool arguments arrive at the granularity supplied by the service. The API does not invent argument-token chunks. Tool records and backend invocation records have separate identities. One tool can make several backend requests. A tool built into the execution environment can have no backend invocation. Do not join their IDs or infer exactly-once business side effects. ## Observe updates ### Python The high-level Python stream hydrates a coherent snapshot, applies ordered events, ignores duplicates, and restores state when a prerequisite is missing. Replace your view when `SnapshotUpdate` arrives. ```python from wkala import SnapshotUpdate, ToolUpdated, MCPInvocationUpdated async with run.stream() as stream: async for update in stream: if isinstance(update, SnapshotUpdate): print(stream.state.runs[run.id].status) elif isinstance(update, ToolUpdated): tool = update.data.tool print(tool.title, tool.status) print(tool.arguments, tool.output, tool.content) elif isinstance(update, MCPInvocationUpdated): call = update.data.invocation print(call.server_name, call.status, call.result) ``` ### TypeScript Use the TypeScript store from `run.stream()` or React `useSession()` for a coherent snapshot, ordered updates, duplicate handling, and recovery. `run.events()` below is a lower-level iterator. It validates sequence and can raise `RecoveryRequired` on a gap. Fetch a new snapshot instead of continuing from incomplete state. ```typescript const observer = new AbortController() for await (const event of run.events({ signal: observer.signal })) { switch (event.type) { case "message.delta": console.log(event.data.message_id, event.data.part_id, event.data.delta) break case "tool.updated": console.log(event.data.tool) break case "mcp.invocation.updated": console.log(event.data.invocation.result) break case "interaction.updated": console.log(event.data.interaction) break case "run.updated": console.log(event.data.run.status, event.data.run.usage) break } } ``` Authoritative `tool.updated` and `message.updated` records replace earlier versions of the same record. Results preserve typed JSON, including arrays, scalars, and MCP `structuredContent` or `isError`. Rich message content may include text, embedded image or audio, resources, and resource links. Render unsupported content explicitly. Do not automatically fetch arbitrary resource links. ## Observation and execution are independent Closing a stream, unmounting a component, or losing a browser connection stops observation. An admitted run continues. Request cancellation explicitly when you mean to stop execution: ### Python ```python await run.cancel() ``` ### TypeScript ```typescript await run.cancel() ``` A run-scoped iterator ends after its terminal event. Observe the session or request a later snapshot to see subsequent reconciliation of an uncertain backend operation. `tool.incomplete` or an invocation with `uncertain` status requires application reconciliation. ## Proxy behavior Use the supplied [Next proxy](/docs/raw/nextjs?locale=en) and [customer backend example](/docs/raw/python-backend?locale=en) to retain authentication and ownership. The supplied example uses a Python backend. A proxy must forward response headers before consuming the body. It must disable event buffering and leave the body open for the lifetime of observation. A connection timeout may bound opening the response. It must not truncate a healthy long-running stream. An SDK stream is not a generic chatbot token response. Sessions, durable runs, tools, permissions, and usage are independent parts of the same execution state. --- # Keep your backend in control Put your authentication, ownership, and business logic between your frontend and the Wkala SDK. ## The application boundary Your users sign into your application. Your backend checks their permissions, keeps the Wkala service key, and sends only authorized work. Wkala authenticates that backend key and enforces account limits. It does not replace your application's user model. The complete runnable Python example is `apps/customer-backend`. It includes: - FastAPI routes and PostgreSQL persistence through SQLAlchemy. - HttpOnly sessions, Origin and CSRF checks, and session ownership. - Signed builtin tools. - A business operation receipt recorded in the same transaction as its side effect. No TypeScript customer backend example is supplied. The supplied Next proxy requires the Python customer backend. The Next application's `/dashboard/playground` route uses that backend and the shared React SDK. ## One client per application lifespan ### Python The server client supplies the hosted endpoint internally. For a bare Go service, pass `base_url="http://localhost:8080/v1"`. The Compose ingress uses `http://localhost:8088/v1`; native multi-service development uses `http://localhost:18080/v1`; production uses the configured public origin. Python also accepts an origin-style override for compatibility. ```python from contextlib import asynccontextmanager import os from fastapi import FastAPI from wkala import AgentClient @asynccontextmanager async def lifespan(app: FastAPI): async with AgentClient( api_key=os.environ["WKALA_API_KEY"], ) as agents: app.state.agents = agents yield app = FastAPI(lifespan=lifespan) ``` ### TypeScript Create the server client once and reuse it for the application lifespan. The client supplies the hosted endpoint internally. For a bare Go service, pass `baseUrl: "http://localhost:8080/v1"`. The Compose ingress uses `http://localhost:8088/v1`; native multi-service development uses `http://localhost:18080/v1`; production uses the configured public origin. ```typescript import { createServerClient } from "@wkala/client/server" const apiKey = process.env.WKALA_API_KEY if (!apiKey) { throw new Error("Set WKALA_API_KEY in your backend environment") } const agents = createServerClient({ apiKey }) ``` ## Inject business logic before admission This function is an integration point in your backend. Get the user identity, owned session ID, and durable business request ID from your authenticated application and database. Do not trust JSON passed through by a browser for these values. ### Python ```python from wkala import AgentClient async def start_order_review( agents: AgentClient, *, user_id: str, owned_session_id: str, persisted_request_id: str, order_id: str, approved_company_tool_id: str, ): session = agents.sessions.handle(owned_session_id) return await session.send( f"Review order {order_id} and explain the next steps.", idempotency_key=persisted_request_id, subject={"id": user_id}, context={"order_id": order_id}, mcp_server_ids=[approved_company_tool_id], ) ``` ### TypeScript ```typescript import type { AgentClient } from "@wkala/client" async function startOrderReview( agents: AgentClient, userId: string, ownedSessionId: string, persistedRequestId: string, orderId: string, approvedCompanyToolId: string, ) { const session = agents.sessions.handle(ownedSessionId) return session.send( `Review order ${orderId} and explain the next steps.`, { idempotencyKey: persistedRequestId, subject: { id: userId }, context: { order_id: orderId }, mcp_server_ids: [approvedCompanyToolId], }, ) } ``` Check ownership before sending, reading, streaming, cancelling, replying to interactions, and retrieving child resources. The public browser proxy must not allow a user to: - Register arbitrary MCP endpoints. - Change a privileged profile. - Supply another user's trusted subject. - Choose the upstream service host. ## Forward state, not secrets Use the supplied `/app` route contract when connecting [React](/docs/raw/react?locale=en) or [Next.js](/docs/raw/nextjs?locale=en). The browser `AgentClient` receives a same-origin base URL and a CSRF callback. It has no API-key option. Your backend authenticates the request and verifies ownership. It uses its private SDK client to call Wkala. If you expose a separate business-specific event endpoint, serialize both initial snapshots and subsequent events in a documented application format. Do not strip initial snapshot state and expect a fresh browser to rebuild prior messages from future deltas alone. The supplied example already handles the complete session contract. ## Builtin business tools Use authorized MCP tools to access your database and services. The supplied Python example uses a helper to host tools in FastAPI. TypeScript has no equivalent hosting helper. See [backend tools](/docs/raw/backend-tools?locale=en) for both options. Your functions are not uploaded to the agent infrastructure. ## Test the boundary Test at least these scenarios: - Two distinct application users. - An attempted read of the other user's session. - A forged subject. - A duplicate business request. - A lost stream. - An uncertain tool side effect. A frontend-only ownership check is insufficient. Reconnection must restore observation without admitting another run. --- # Define tools inside your backend Give agents access to authorized Python functions without moving your business logic out of your application. ### Python ## Install the backend helper ```bash python -m pip install "wkala[mcp,postgres] @ https://wkala.okal.io/downloads/wkala-0.1.0-py3-none-any.whl" fastapi uvicorn ``` The optional MCP extra provides the standard server package. The PostgreSQL extra supplies a durable receipt journal. The helper registers a descriptor, checks signed invocation context, and mounts a reachable endpoint. It does not serialize your functions or open a worker tunnel. ## A complete FastAPI tool host Set `INVENTORY_MCP_URL` to the endpoint the Wkala service can reach, for example `https://backend.example/internal/mcp/inventory/`. Set `MCP_STATE_DATABASE_URL` to a private PostgreSQL database. Persist the signing key across restarts. This example's in-memory inventory is deliberately read-only. Replace it with your authorized database lookup. Set `WKALA_API_KEY` in your backend. The client connects to Wkala by default. ```python from contextlib import asynccontextmanager import os from fastapi import FastAPI from mcp.server import MCPServer from pydantic import BaseModel from wkala import AgentClient from wkala.mcp import ( BackendMCP, current_invocation, load_or_create_signing_key, ) class InventoryItem(BaseModel): name: str available: int server = MCPServer("Inventory") @server.tool() async def get_inventory(item: str) -> InventoryItem: authority = current_invocation() owned = { "alice": {"notebook": 12}, "bob": {"pen": 5}, } stock = owned.get(authority.subject, {}) if item not in stock: raise PermissionError("Item is unavailable to this account member") return InventoryItem(name=item, available=stock[item]) binding = BackendMCP( server, name="inventory", url=os.environ["INVENTORY_MCP_URL"], signing_key=load_or_create_signing_key("./data/inventory-signing.key"), allowed_tools=["get_inventory"], state_url=os.environ["MCP_STATE_DATABASE_URL"], ) @asynccontextmanager async def lifespan(app: FastAPI): async with AgentClient( api_key=os.environ["WKALA_API_KEY"], ) as agents: async with binding.lifespan(agents): app.state.agents = agents app.state.inventory = binding yield app = FastAPI(lifespan=lifespan) app.mount(binding.mount_path, binding.app) ``` The key used for registration needs configure scope. Start the HTTP application, then validate the descriptor from a bootstrap task. Do not validate a required endpoint before the server is listening. ```python # Run after your HTTP application is accepting requests. await agents.mcp_servers.validate(registered_server_id) session = await agents.sessions.create(title="Inventory check") run = await session.send( "How many notebooks are available?", idempotency_key=persisted_request_id, subject={"id": authenticated_user_id}, mcp_server_ids=[registered_server_id], ) ``` The registered ID is `binding.attachment.id` after its lifespan registration. Persist or read it from your backend's initialized binding. The trusted subject comes from your application login. It is not an argument the model gets to invent. ## Narrow permissions An empty `allowed_tools` list exposes no tools. `['*']` explicitly permits every discovered tool. Use a named allowlist for a business integration. Required unready tools block admission. Updates retain revision history for already admitted work. `current_invocation()` supplies the verified account, subject, run/session IDs, invocation ID, deadline, request digest, and server revision. Use these values for record-level authorization and audit. A signed invocation proves its source. It does not itself make a side effect exactly once. For writes, record the invocation or business idempotency receipt and side effect in the same database transaction. Reconcile an ambiguous operation instead of retrying it blindly. The shipped customer backend includes this pattern for an order update. ## Network requirements Builtin tools stay in your backend, but their mounted endpoint must be reachable from the Wkala service. Private networking is supported when the operator explicitly permits the destination. No inbound connectivity means this HTTP helper cannot reach your functions. An outbound worker tunnel is not included in this release. ### TypeScript The TypeScript SDK does not include the Python `BackendMCP` hosting helper. Host an MCP server separately and follow [remote MCP guidance](/docs/raw/remote-tools?locale=en). The operator must permit its destination. Keep business authorization and credentials in your backend. --- # Attach a remote MCP server Connect an existing tool service with an explicit endpoint, tool allowlist, and operator-managed credential reference. A remote MCP server is a service you already run or trust. A builtin server can use the Python helper described in [backend tools](/docs/raw/backend-tools?locale=en). Attach either to an agent profile or an admitted run by server ID. The operator must permit the endpoint destination and provision any remote credential reference. Browser callers cannot register endpoints or provide private credential references. Do this from a backend key with configure scope. ### Python ```python server = await agents.mcp_servers.create( name="Knowledge search", kind="remote", url="https://tools.example/mcp/", allowed_tools=["search_documents"], required=True, secret_ref="knowledge-service", ) ready = await agents.mcp_servers.validate(server.id) print(ready.status, ready.tools) session = await agents.sessions.create(title="Research request") run = await session.send( "Find the published support policy and summarize the escalation steps.", idempotency_key=persisted_request_id, mcp_server_ids=[server.id], ) ``` ### TypeScript ```typescript const server = await agents.mcpServers.create({ name: "Knowledge search", kind: "remote", url: "https://tools.example/mcp/", allowed_tools: ["search_documents"], required: true, secret_ref: "knowledge-service", }) const ready = await agents.mcpServers.validate(server.id) console.log(ready.status, ready.tools) const session = await agents.sessions.create({ title: "Research request" }) const run = await session.send( "Find the published support policy and summarize the escalation steps.", { idempotencyKey: persistedRequestId, mcp_server_ids: [server.id], }, ) ``` `secret_ref` is an operator-provisioned reference, not a secret value and not an environment-variable name the user can choose freely. Omit it for a permitted service that needs no credential. The API validates destinations, redirects, and required capabilities. ## Reuse tools through a profile ### Python ```python profile = await agents.profiles.create( name="Support researcher", instructions="Use the approved sources. Cite the document identifiers.", mcp_server_ids=[server.id], max_cost_microusd=300_000, timeout_seconds=120, ) session = await agents.sessions.create( title="Support research", profile_id=profile.id, ) ``` ### TypeScript ```typescript const profile = await agents.profiles.create({ name: "Support researcher", instructions: "Use the approved sources. Cite the document identifiers.", mcp_server_ids: [server.id], max_cost_microusd: 300_000, timeout_seconds: 120, }) const session = await agents.sessions.create({ title: "Support research", profile_id: profile.id, }) ``` The run retains its admitted tool/catalog revision. Reconfiguring a server does not silently broaden the permissions of already running work. Revoking a server prevents future use. Cancellation of already-running work remains an explicit operation. If validation fails, inspect the returned state and safe error. Do not treat a successful TCP connection as proof that the server has the expected tools or usable authorization. --- # Add reusable skills and instructions Package instruction bundles once and attach their immutable versions to an agent profile. A skill is an instruction bundle with a `SKILL.md` file and optional supporting assets. It shapes the agent's behavior. Business operations belong in explicitly authorized tools. Executable skill scripts are not enabled in this release. Create a directory such as `skills/release-review` with this `SKILL.md`: ```markdown # Release review Review a proposed release in three steps: 1. Identify the user-visible change and its acceptance criteria. 2. List meaningful boundary and failure-path checks. 3. Report observed evidence separately from assumptions. Use only attached, authorized tools. Ask for clarification when the target environment or required permissions are missing. ``` Upload the bundle from your backend: ### Python `upload_directory` packages the directory and its assets. ```python skill = await agents.skills.upload_directory( "skills/release-review", name="Release review", description="A repeatable review checklist for application releases.", ) profile = await agents.profiles.create( name="Release reviewer", instructions="Be concise and cite the observed evidence.", skill_ids=[skill.id], max_cost_microusd=300_000, timeout_seconds=120, ) session = await agents.sessions.create( title="Review release candidate", profile_id=profile.id, ) ``` ### TypeScript This example reads only `SKILL.md`. Include every required asset in `files` with a safe relative path and base64-encoded content. ```typescript import { readFile } from "node:fs/promises" const content = await readFile("skills/release-review/SKILL.md") const skill = await agents.skills.create({ name: "Release review", description: "A repeatable review checklist for application releases.", files: [ { path: "SKILL.md", content_base64: content.toString("base64"), }, ], }) const profile = await agents.profiles.create({ name: "Release reviewer", instructions: "Be concise and cite the observed evidence.", skill_ids: [skill.id], max_cost_microusd: 300_000, timeout_seconds: 120, }) const session = await agents.sessions.create({ title: "Review release candidate", profile_id: profile.id, }) ``` Bundles require safe relative paths and a `SKILL.md`. The current limits are 64 files, 1 MiB per file, and 2 MiB total. Binary assets are preserved. Uploaded skill digests and the effective profile revision are retained for an admitted run, so later edits cannot silently change its behavior. The operator controls available models. A profile may choose a permitted model by its advertised ID. It cannot bypass the account's provider assignment or spending limits. If routing changes, start a new session instead of trying to continue native history under a different provider configuration. --- # Build a live React interface Use one shared session store for messages, tools, interactions, usage, and recovery. ## Install ```bash npm install "https://wkala.okal.io/downloads/wkala-client-0.1.0.tgz" "https://wkala.okal.io/downloads/wkala-react-0.1.0.tgz" ``` The React package works with React 19 and has no Next.js, router, shadcn, or styling dependency. It uses the same validated session store as the TypeScript client. The shipped Next application uses that store with shared shadcn components. ## Connect through your backend Your own backend supplies the authenticated `/app` routes, an HttpOnly session cookie, CSRF protection, and ownership checks. `csrfToken` below comes from that backend's authenticated identity response. It is not your Wkala service key. The browser client defaults to same-origin `/app`, not the public API default used by server clients. The `createAppProxy` target must be your customer-backend origin only, without a path. ```tsx "use client" import { useState } from "react" import { AgentClient, isTerminal } from "@wkala/client" import { AgentProvider, useSession } from "@wkala/react" export function AgentWorkspace({ sessionId, csrfToken }: { sessionId: string csrfToken: string }) { const [client] = useState(() => new AgentClient()) client.csrfToken = csrfToken return ( ) } function Execution({ sessionId }: { sessionId: string }) { const session = useSession(sessionId) const [message, setMessage] = useState("") const [error, setError] = useState(null) const [submitting, setSubmitting] = useState(false) const busy = submitting || session.runs.some(run => !isTerminal(run.status)) async function submit() { setSubmitting(true) setError(null) try { await session.send(message, { idempotencyKey: crypto.randomUUID() }) setMessage("") } catch (cause) { setError(cause instanceof Error ? cause.message : "Unable to start work") } finally { setSubmitting(false) } } return (

{session.connection}

{session.error &&

{session.error.message}

} {session.messages.map(message => (
{message.role} {message.parts.map(part => (

{part.type === "text" ? part.text : "[attached content]"}

))}
))} {session.tools.map(tool => (
{tool.title}: {tool.status}
{JSON.stringify(tool.output, null, 2)}
))} {session.interactions.some(item => item.status === "pending") && (

Input is required. Present the offered interaction to the user.

)}
{ event.preventDefault() void submit() }}>