Skip to content

Quickstart: your assistant

Connect your app's assistant to Klaris, so it can ask Klaris questions as each of your signed-in people. Allow about 15 minutes, plus the time for a Klaris admin to add your app.

You'll need Python 3.10+ or Node.js 20+ on your server.

On-premises deployments

These pages use https://app.klarislabs.com. If your company runs Klaris on its own servers, ask the Klaris team for your address and use it instead.

1. Make a signing key

Your server signs a short pass for each person. Klaris checks it with your public key.

pip install "pyjwt[crypto]>=2.10"
"""Make a signing key for Klaris passes: the private key (keep it secret, on your server) and its public key page.

python make_key.py production-2026-11
"""
import json
import sys

from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from jwt.algorithms import RSAAlgorithm

kid = sys.argv[1]  # a name for this key, e.g. production-2026-11
key = rsa.generate_private_key(public_exponent=65537, key_size=2048)

with open(f"{kid}.pem", "wb") as f:
    f.write(key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8,
                              serialization.NoEncryption()))

public = json.loads(RSAAlgorithm.to_jwk(key.public_key()))
with open("jwks.json", "w") as f:
    json.dump({"keys": [{**public, "kid": kid, "alg": "RS256", "use": "sig"}]}, f, indent=2)

print(f"Private key: {kid}.pem (never share it). Public key page: jwks.json")

Publish jwks.json at an https address Klaris can reach, such as https://your-app.example.com/.well-known/jwks.json. That lets you change keys later without asking Klaris for anything. You can also send the page to your Klaris admin to paste in, if you can't publish it.

Keep the private key on your server

Anyone with it can sign in as any of your people. Store it like any other secret, and never put it in a browser or a phone app.

2. Ask a Klaris admin to add your app

They do it on Settings → Partner Apps in Klaris. Send them:

They enter You give
Pass comes from (issuer) A name for your app, such as your-app. It goes in every pass as iss.
Key address Your jwks.json address, or the page itself to paste.
Role rules Each of your roles (agent, manager, …) and the Klaris role it becomes.

They switch on Let its assistant ask Klaris over MCP, and send you back the audience ("pass is for"), which goes in every pass as aud. For a sandbox beside production, see Sign your people in.

3. Ask Klaris as one of your people

Install the official MCP library, then set your details:

pip install "mcp>=2.3" "pyjwt[crypto]>=2.10"
npm install @modelcontextprotocol/sdk jose
export KLARIS_URL="https://app.klarislabs.com"
export KLARIS_ISSUER="your-app"
export KLARIS_AUDIENCE="the audience your admin gave you"
export KLARIS_KEY_ID="production-2026-11"           # the kid from step 1
export KLARIS_PRIVATE_KEY_FILE="production-2026-11.pem"

This signs a pass for the person, swaps it for an MCP token, asks a question, waits for the answer, and reads any file Klaris made:

"""Ask Klaris over MCP from your server, as one of your people.

pip install "mcp>=2.3" "pyjwt[crypto]>=2.10"
"""
import asyncio
import base64
import os
import time
import uuid

import httpx2  # installed with the mcp package
import jwt
from mcp import ClientSession
from mcp.client.streamable_http import streamable_http_client

KLARIS_URL = os.environ["KLARIS_URL"].rstrip("/")  # https://app.klarislabs.com
MCP_URL = f"{KLARIS_URL}/mcp"
ISSUER = os.environ["KLARIS_ISSUER"]              # as set up in Klaris (Settings → Partner Apps)
AUDIENCE = os.environ["KLARIS_AUDIENCE"]
KEY_ID = os.environ["KLARIS_KEY_ID"]              # the kid of your signing key
with open(os.environ["KLARIS_PRIVATE_KEY_FILE"]) as f:
    PRIVATE_KEY = f.read()                        # PEM; keep it on your server


def sign_pass(person: dict) -> str:
    """A short, single-use pass saying who the person is. Signed with your private key (RS256)."""
    now = int(time.time())
    claims = {
        "iss": ISSUER, "aud": AUDIENCE,
        "sub": person["id"],          # your id for them; never changes
        "email": person["email"], "name": person["name"],
        "role": person["role"],       # their role on your side; Klaris maps it to a Klaris role
        "iat": now, "exp": now + 300,  # at most 10 minutes
        "jti": str(uuid.uuid4()),     # new every time: each pass works once
    }
    return jwt.encode(claims, PRIVATE_KEY, algorithm="RS256", headers={"kid": KEY_ID})


class Tokens:
    """One MCP token per person, swapped from a pass and reused until shortly before it runs out."""

    def __init__(self):
        self._held: dict[str, tuple[str, float]] = {}

    def get(self, person: dict, fresh: bool = False) -> str:
        held = self._held.get(person["id"])
        if held and not fresh and held[1] - time.time() > 60:
            return held[0]
        reply = httpx2.post(f"{KLARIS_URL}/mcp/token", timeout=20, data={
            "grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
            "assertion": sign_pass(person),
            "resource": MCP_URL,
        })
        if reply.status_code != 200:  # 400 invalid_grant: the pass was refused; don't retry in a loop
            raise RuntimeError(f"Klaris refused the pass: {reply.status_code} {reply.text}")
        token = reply.json()
        self._held[person["id"]] = (token["access_token"], time.time() + token["expires_in"])
        return token["access_token"]


tokens = Tokens()


async def call(person: dict, tool: str, arguments: dict):
    """One tool call as the person. A token Klaris no longer takes (401) is swapped once and the call tried again."""
    for attempt in (1, 2):
        token = tokens.get(person, fresh=attempt == 2)
        try:
            async with httpx2.AsyncClient(headers={"Authorization": f"Bearer {token}"}, timeout=60) as http:
                async with streamable_http_client(MCP_URL, http_client=http) as (read, write):
                    async with ClientSession(read, write) as session:
                        await session.initialize()
                        return await session.call_tool(tool, arguments, read_timeout_seconds=50)
        except Exception:
            if attempt == 2:
                raise


async def ask(person: dict, question: str, conversation_id: str | None = None) -> dict:
    """Ask, and wait for the answer: a slow one comes back as "working", and get_answer fetches it."""
    args = {"question": question, **({"conversation_id": conversation_id} if conversation_id else {})}
    answer = (await call(person, "ask", args)).structured_content
    while answer["status"] == "working":
        answer = (await call(person, "get_answer", {"conversation_id": answer["conversation_id"]})).structured_content
    return answer


async def read_file(person: dict, uri: str) -> tuple[bytes, str]:
    """A file Klaris made (klaris://files/…), as bytes and its type, to offer as a download in your app."""
    token = tokens.get(person)
    async with httpx2.AsyncClient(headers={"Authorization": f"Bearer {token}"}, timeout=60) as http:
        async with streamable_http_client(MCP_URL, http_client=http) as (read, write):
            async with ClientSession(read, write) as session:
                await session.initialize()
                content = (await session.read_resource(uri)).contents[0]
                return base64.b64decode(content.blob), content.mime_type


async def main():
    pat = {"id": "u_4821", "email": "pat@example.com", "name": "Pat Lee", "role": "manager"}
    answer = await ask(pat, "Which kinds of data can you answer questions about?")
    print(answer["status"], "-", answer["answer"])
    if answer["status"] == "needs_answer":
        print("Klaris asks:", answer["question"])
    for output in answer["outputs"]:
        if output["kind"] == "file":
            data, media_type = await read_file(pat, output["file"]["uri"])
            print("File:", output["file"]["filename"], len(data), "bytes", media_type)


if __name__ == "__main__":
    asyncio.run(main())
// Ask Klaris over MCP from your server, as one of your people.
// npm install @modelcontextprotocol/sdk jose
import { randomUUID } from "node:crypto";
import { readFileSync } from "node:fs";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
import { importPKCS8, SignJWT } from "jose";

const KLARIS_URL = process.env.KLARIS_URL!.replace(/\/$/, ""); // https://app.klarislabs.com
const MCP_URL = `${KLARIS_URL}/mcp`;
const ISSUER = process.env.KLARIS_ISSUER!;                     // as set up in Klaris (Settings → Partner Apps)
const AUDIENCE = process.env.KLARIS_AUDIENCE!;
const KEY_ID = process.env.KLARIS_KEY_ID!;                     // the kid of your signing key
const privateKey = await importPKCS8(readFileSync(process.env.KLARIS_PRIVATE_KEY_FILE!, "utf8"), "RS256");

type Person = { id: string; email: string; name: string; role: string };

// A short, single-use pass saying who the person is. Signed with your private key (RS256).
async function signPass(person: Person): Promise<string> {
  return new SignJWT({ email: person.email, name: person.name, role: person.role })
    .setProtectedHeader({ alg: "RS256", kid: KEY_ID })
    .setIssuer(ISSUER)
    .setAudience(AUDIENCE)
    .setSubject(person.id)      // your id for them; never changes
    .setIssuedAt()
    .setExpirationTime("5m")    // at most 10 minutes
    .setJti(randomUUID())       // new every time: each pass works once
    .sign(privateKey);
}

// One MCP token per person, swapped from a pass and reused until shortly before it runs out.
const held = new Map<string, { token: string; until: number }>();

async function tokenFor(person: Person, fresh = false): Promise<string> {
  const known = held.get(person.id);
  if (known && !fresh && known.until - Date.now() > 60_000) return known.token;
  const res = await fetch(`${KLARIS_URL}/mcp/token`, {
    method: "POST",
    headers: { "Content-Type": "application/x-www-form-urlencoded" },
    body: new URLSearchParams({
      grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
      assertion: await signPass(person),
      resource: MCP_URL,
    }),
  });
  // 400 invalid_grant: the pass was refused; don't retry in a loop
  if (!res.ok) throw new Error(`Klaris refused the pass: ${res.status} ${await res.text()}`);
  const token = await res.json();
  held.set(person.id, { token: token.access_token, until: Date.now() + token.expires_in * 1000 });
  return token.access_token;
}

// A connected MCP client for the person. A token Klaris no longer takes (401) is swapped once.
async function connect(person: Person): Promise<Client> {
  for (const fresh of [false, true]) {
    const client = new Client({ name: "your-app", version: "1.0.0" });
    const transport = new StreamableHTTPClientTransport(new URL(MCP_URL), {
      requestInit: { headers: { Authorization: `Bearer ${await tokenFor(person, fresh)}` } },
    });
    try {
      await client.connect(transport);
      return client;
    } catch (err) {
      if (fresh) throw err;
    }
  }
  throw new Error("unreachable");
}

type Answer = {
  conversation_id: string;
  status: "answered" | "needs_answer" | "needs_approval" | "working" | "failed" | "stopped";
  answer: string;
  question?: unknown;
  approvals: { approval_id: string; summary: string; sql?: string }[];
  outputs: any[];
  steps: string[];
};

// Ask, and wait for the answer: a slow one comes back as "working", and get_answer fetches it.
async function ask(person: Person, question: string, conversationId?: string): Promise<Answer> {
  const client = await connect(person);
  try {
    const call = async (name: string, args: Record<string, unknown>) =>
      (await client.callTool({ name, arguments: args }, undefined, { timeout: 50_000 }))
        .structuredContent as Answer;
    let answer = await call("ask", { question, ...(conversationId ? { conversation_id: conversationId } : {}) });
    while (answer.status === "working") {
      answer = await call("get_answer", { conversation_id: answer.conversation_id });
    }
    return answer;
  } finally {
    await client.close();
  }
}

// A file Klaris made (klaris://files/…), as bytes and its type, to offer as a download in your app.
async function readFile(person: Person, uri: string): Promise<{ data: Buffer; mimeType?: string }> {
  const client = await connect(person);
  try {
    const [content] = (await client.readResource({ uri })).contents as { blob: string; mimeType?: string }[];
    return { data: Buffer.from(content.blob, "base64"), mimeType: content.mimeType };
  } finally {
    await client.close();
  }
}

const pat: Person = { id: "u_4821", email: "pat@example.com", name: "Pat Lee", role: "manager" };
const answer = await ask(pat, "Give me the number of orders in each region as an Excel file.");
console.log(answer.status, "-", answer.answer);
for (const output of answer.outputs) {
  if (output.kind === "file") {
    const { data, mimeType } = await readFile(pat, output.file.uri);
    console.log("File:", output.file.filename, data.length, "bytes", mimeType);
  }
}

Run it with npx tsx klaris-mcp.ts (Node.js 20+, as an ES module).

The first pass for a person adds them to the Klaris workspace, with the role your role rules give them. After that, Klaris finds them by sub.

4. Next