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