# 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.
