# Create and version an agent
Source: https://docs.papermap.ai/air/agents/create-agent
Bind immutable instructions, model access, approved tools, and limits into an active AIR agent version.
An agent is the stable identity your application calls. An agent version is the
immutable configuration AIR executes: prompt, model, tools, fallbacks, output
contract, and limits.
## Build the first version
Save reusable instructions under **Prompts**, or write new instructions
directly in the agent composer.
Use a Papermap-managed model when available, connect an OpenAI or Anthropic
provider key, or use `Testing → fake-echo` for a zero-credential staging
smoke test.
Open **Advanced — fallback models, tools, output, and limits** and add only tools
this version should call. Project-level enablement does not grant an agent
access automatically.
Leave **Output schema** blank for free-form text, or provide an object-rooted
JSON Schema when your application needs predictable fields.
Select **Activate immediately** for a new agent, or create an inactive
version when you want to test before moving serving traffic.
## Return structured output
Add a JSON Schema under **Advanced → Output schema** when downstream code needs
a stable response contract. The schema must declare an object at the root.
```json theme={null}
{
"type": "object",
"properties": {
"answer": { "type": "string" },
"needs_human_review": { "type": "boolean" }
},
"required": ["answer", "needs_human_review"],
"additionalProperties": false
}
```
AIR sends the schema to supported model providers and validates the final model
response again before completing the run. A successful run stores the parsed
object directly:
```json theme={null}
{
"answer": "Order 1042 is scheduled for delivery tomorrow.",
"needs_human_review": false
}
```
If the final response is not valid JSON or does not match the schema, AIR marks
the run as `failed` and does not publish a successful final output. The raw
model response remains available in the run trace for debugging.
Without an output schema, AIR preserves the existing free-form response shape
with the model response under the `text` field.
## Test before integrating
The **Try it** panel creates a real run using the selected agent version. Open
the resulting trace to verify the exact configuration and model behavior.
## Change an agent safely
Create a new version whenever you change instructions, model, allowed tools,
output schema, or limits. Test it, then activate it. Existing runs remain tied
to the version with which they started; new runs use the active version.
Do not edit production behavior in place. Version first, test the version,
and then move serving traffic.
# Create and manage runs
Source: https://docs.papermap.ai/air/applications/create-runs
Start, stream, inspect, wait for, and cancel AIR runs from an application.
Install the Python SDK and use a project-scoped app key:
```bash theme={null}
python -m pip install papermap-air
export AIR_BASE_URL="https://dev.airapi.papermap.ai"
export AIR_APP_KEY=""
```
## Create and wait
```python theme={null}
import asyncio
import os
from air import AirClient
async def main() -> None:
async with AirClient(
os.environ["AIR_BASE_URL"],
os.environ["AIR_APP_KEY"],
) as client:
run = await client.runs.create(
agent_id="support-agent",
input={"message": "Where is order 1042?"},
context={"tenant_id": "acme"},
webhook_url="https://example.com/hooks/air",
)
result = await client.runs.wait(
run.id,
timeout=120,
poll_interval=0.5,
)
print(result.status, result.output)
asyncio.run(main())
```
`input` is the task sent to the agent. `context` carries trusted application
data such as a tenant ID; AIR passes it to tools that declare a `context`
parameter. `webhook_url` is optional.
## Consume structured output
When the active agent version has an output schema, `Run.output` is the parsed,
validated object described by that schema:
```python theme={null}
result = await client.runs.wait(run.id, timeout=120)
if result.status == "failed":
raise RuntimeError(result.error)
answer = result.output["answer"]
needs_review = result.output["needs_human_review"]
```
When the agent version has no output schema, the response remains free-form
text and is returned as `result.output["text"]`.
Treat a terminal `Run.output` or `run_succeeded` event as authoritative.
Streaming model deltas are provisional text; for structured runs they contain
the JSON response while it is still being generated and has not yet passed
final validation.
## Stream output as it is generated
Use `stream()` when a UI or CLI should show the model response before the run
finishes:
```python theme={null}
run = await client.runs.create(
agent_id="support-agent",
input={"message": "Write a detailed account summary."},
)
text = ""
async for event in client.runs.stream(run.id):
if event.output_delta is not None:
text += event.output_delta
print(event.output_delta, end="", flush=True)
elif event.type == "model_output_reset":
# AIR retried or used a fallback after a partial response.
text = ""
# Clear the partial text in your UI before showing the new attempt.
final = await client.runs.get(run.id)
print(f"\nRun status: {final.status}")
```
The async iterator ends when the run succeeds, fails, or is cancelled. Each
`RunEvent` includes `seq`, `type`, `data`, and `created_at`. If the connection
drops, the SDK reconnects and requests events after the last sequence number,
so missed output is replayed rather than skipped.
Use `after_seq` when you persist the last processed sequence number yourself:
```python theme={null}
async for event in client.runs.stream(run.id, after_seq=last_seq):
last_seq = event.seq
```
After streaming, read the `Run` with `get()` when you need the authoritative
final status, validated structured output, error, or cost.
## Read or cancel
```python theme={null}
current = await client.runs.get(run.id)
if current.status not in {"succeeded", "failed", "cancelled"}:
await client.runs.cancel(run.id)
```
The returned `Run` exposes `id`, `status`, `output`, `error`, `cost_usd`, and the
complete response as `raw`.
## Inspect the same run visually
Open **Runs** in the console to inspect the event sequence, model request and
response, token usage, cost, and configuration snapshot.
## Handle errors
```python theme={null}
from air import AirProtocolError, RunTimeoutError
try:
result = await client.runs.wait(run.id, timeout=30)
except RunTimeoutError:
# The server-side run may still be active.
result = await client.runs.get(run.id)
except AirProtocolError as exc:
print(exc.status_code)
raise
```
Treat `context` as security-sensitive input. A tool must still verify that
every requested record belongs to the supplied tenant before reading or
changing data.
# How AIR works
Source: https://docs.papermap.ai/air/concepts/how-air-works
Understand projects, agents, runs, workers, tools, and the durable execution loop.
AIR separates hosted orchestration from private tool execution. The hosted
runtime owns the durable agent loop; your worker owns access to your systems.
## Core objects
| Object | Purpose |
| ------------- | ------------------------------------------------------------------------- |
| Project | Security and configuration boundary for agents, tools, keys, and members. |
| Prompt | Reusable, versioned instructions. |
| Agent | Stable API identity used to create runs. |
| Agent version | Immutable prompt, model, allowed tools, fallbacks, and limits. |
| Run | One durable execution of an active agent version. |
| Tool | Reviewed capability an agent may request. |
| Worker | Outbound process that registers and executes private tools. |
## Run lifecycle
`AirClient` sends the agent API ID, input, trusted context, and optional
webhook settings using an app key.
The run is bound to one agent version so later configuration changes cannot
alter an execution already in progress.
Output chunks are recorded as durable events and published live. Each
request, response, token count, latency, and cost is recorded in the trace.
If the model requests an allowed tool, the run waits while an outbound
worker claims the task.
The tool result enters the transcript and the run continues until it
succeeds, fails, or is cancelled.
## Live output and replay
The console and Python SDK consume the same ordered run-event stream. AIR saves
each event in Postgres before publishing it through Redis:
* Redis delivers new events immediately to connected subscribers.
* Postgres remains the source of truth and replays events a subscriber missed.
* Each sequence number lets a reconnecting client continue without losing or
duplicating output.
Redis is the live delivery path, not the permanent record. A console or SDK
client can therefore join after a run starts, reconnect after a network break,
or inspect a completed run and still receive the recorded event sequence.
## Why tools start pending
A worker discovers capability; it does not grant policy. Newly registered tools
start **awaiting approval** until a project owner reviews their description,
schema, timeout, source, and write capability. An agent version can only call
tools explicitly included in that version.
# Projects and keys
Source: https://docs.papermap.ai/air/concepts/projects-and-keys
Choose the correct AIR credential and keep every integration scoped to one project.
Every AIR credential belongs to a project and has one purpose.
| Credential | Used by | Capability |
| --------------- | ---------------- | -------------------------------------------------------------- |
| App key | Your application | Create, read, wait for, and cancel runs. |
| Worker key | Your worker | Register tools, claim tasks, renew leases, and return results. |
| Console session | Human users | Configure projects through the AIR console. |
## Issue a key
Select the project, then open **Settings**.
Select **Issue app key** for application code or **Issue worker key** for an
outbound worker.
AIR shows the complete key once. Put it in a local environment variable for
development or a managed secret store for deployment.
Never commit a key. Avoid passing worker keys with `air worker start --key`
in shared environments because command arguments can appear in shell history
and process listings. Prefer `AIR_WORKER_KEY`.
## Roles are not cloud roles
* **Owner** manages project configuration, members, credentials, and tool approval.
* **Editor** changes agents and prompts.
* **Viewer** reads project state and traces.
* **Platform admin** is an AIR application role with cross-project access. It is
not an Azure role.
# Security
Source: https://docs.papermap.ai/air/guides/security
Protect AIR credentials, tenant data, workers, and tool permissions.
## Use the narrowest credential
* Put an **app key** only in the service that creates runs.
* Put a **worker key** only in the process that executes private tools.
* Never use a console session or platform-admin token in application code.
* Use separate credentials for staging and production.
* Rotate app and worker keys independently.
Store credentials in a managed secret store. Never commit them, bake them into
an image, log them, or pass a worker key through `--key` in a shared environment.
## Authorize inside every tool
Agent-generated arguments are untrusted. Validate every value before using it
in a query, URL, or shell command. When a tool receives `context`, verify that
the requested object belongs to the authenticated tenant.
```python theme={null}
from air import tool
@tool
def get_invoice(invoice_id: str, context: dict) -> dict:
"""Read an invoice owned by the current tenant."""
tenant_id = context["tenant_id"]
invoice = load_invoice(invoice_id=invoice_id, tenant_id=tenant_id)
return invoice.to_safe_dict()
```
## Grant capability in layers
1. A worker registers a manifest.
2. A project owner reviews and enables the tool.
3. An agent version explicitly includes the tool.
4. The tool enforces tenant and object authorization at execution time.
## Respond to an exposed key
Revoke it immediately, issue a replacement, update the affected deployment,
and inspect recent runs, worker registrations, and audit events for unexpected
activity.
# Troubleshooting
Source: https://docs.papermap.ai/air/guides/troubleshooting
Resolve common run, credential, worker, and tool configuration problems.
## A run is rejected
* Confirm `AIR_BASE_URL` is the API URL, not the console URL.
* Confirm the app key and agent belong to the same project.
* Use the agent API ID—not its display name—as `agent_id`.
* Confirm the agent has an active version and usable model access.
`AirProtocolError.status_code` contains the HTTP status. `401` usually means the
key is missing, invalid, or revoked. `403` usually means it has the wrong scope
or project.
## A tool stays awaiting approval
Worker registration only discovers capability. A project owner must open
**Tools**, review the manifest, and select **Enable tool**. Then add the enabled
tool to a new agent version and activate that version.
## A worker receives no tasks
* Confirm the worker key and agent belong to the same project.
* Confirm the tool is enabled and allowed by the active agent version.
* Confirm the model requested the tool in the run trace.
* Confirm the worker remains running after registration.
* Check outbound HTTPS access to the AIR API.
## A tool fails
Every tool must return a dictionary. Inspect the worker log for the original
exception and the run trace for the recorded failure. Validate arguments,
tenant access, downstream credentials, and timeouts.
## Waiting timed out
`RunTimeoutError` only means the local wait deadline expired. The server-side
run may still be active.
```python theme={null}
try:
result = await client.runs.wait(run.id, timeout=30)
except RunTimeoutError:
current = await client.runs.get(run.id)
```
Read the run again, inspect its trace, or cancel it explicitly.
# Papermap AIR
Source: https://docs.papermap.ai/air/index
Build governed AI agents and connect private tools without opening your infrastructure to inbound traffic.
Papermap Agentic Infrastructure Runtime (AIR) hosts your agent loop, prompts,
models, policy, traces, and run state. Your private tools stay close to your
systems in outbound-only workers.
Create a project, activate an agent, and inspect its first successful run.
Turn typed Python functions into governed AIR tools.
Start, wait for, inspect, and cancel runs with the Python SDK.
Reference `AirClient`, workers, tools, errors, and environment variables.
Select any screenshot in these guides to open the full-resolution view.
## One runtime, two connections
```text theme={null}
Your application -- app key --> AIR -- model --> result
|
| queued tool call
v
Your worker <--- outbound claim --+--- worker key
|
+--> your database, APIs, and local MCP servers
```
* Your **application** creates runs with an app key.
* AIR executes the active agent version and records its trace.
* Your **worker** connects outbound with a worker key and executes approved tools.
Staging console: [dev.air.papermap.ai](https://dev.air.papermap.ai). Staging
API: `https://dev.airapi.papermap.ai`.
Start with the [visual quickstart](/air/quickstart). It walks through the same
screens you will use in the console and ends with a real run trace.
# Visual quickstart
Source: https://docs.papermap.ai/air/quickstart
Create a project, prompt, active agent, and first run in the AIR staging console.
In about ten minutes, you will create an active agent and see its first run in
the AIR trace viewer. You do not need a model-provider key for the staging smoke
test.
Select a screenshot to zoom. The screenshots use a disposable staging project
and contain no API keys or provider credentials.
## Before you begin
* Python 3.10 or newer
* Access to the [AIR staging console](https://dev.air.papermap.ai)
* A model-provider key only when you are ready to use a real OpenAI or Anthropic model
Sign in, select **New project**, enter a descriptive name, and select
**Create project**. A project is the boundary for agents, tools, members,
keys, and provider credentials.
Open **Prompts**, select **New prompt**, and name it `Support assistant`.
Open the prompt, select **New version**, and enter:
```text theme={null}
You are a concise support assistant. Answer using the information in the
run input. If information is missing, explain what you need.
```
Add a short change note and create the version.
Open **Agents**, select **New agent**, and name it `Support agent`. Reuse the
prompt version you just created.
For the first staging smoke test, choose **Bring your own provider key**,
then select **Testing** and **fake-echo**. This built-in model requires no
key. Leave **Activate immediately** selected and choose **Create & start
serving**.
For real responses, choose OpenAI or Anthropic and connect the project
provider key when prompted. Keys are encrypted and never shown again.
In the agent's **Try it** panel, enter `When does support open?` and select
**Run test**. The **Output · streaming** panel appears after the first model
chunk and grows while the run is active. The transcript records the same
event sequence without changing the active configuration.
Select **Open full run**. The trace shows the exact agent and prompt
versions, token usage, cost, model latency, request, response, and immutable
configuration snapshot.
Open **Settings** and select **Issue app key**. Copy the key once into your
local environment or secret manager. Do not put it in source control.
Install the published SDK:
```bash theme={null}
python -m pip install papermap-air
export AIR_BASE_URL="https://dev.airapi.papermap.ai"
export AIR_APP_KEY=""
```
Copy the agent API ID from the agent page and use it as `agent_id`:
```python theme={null}
import asyncio
import os
from air import AirClient
async def main() -> None:
async with AirClient(
os.environ["AIR_BASE_URL"],
os.environ["AIR_APP_KEY"],
) as client:
run = await client.runs.create(
agent_id="support-agent",
input={"message": "When does support open?"},
context={"tenant_id": "demo"},
)
result = await client.runs.wait(run.id, timeout=120)
print(result.status, result.output)
asyncio.run(main())
```
You now have a project, versioned instructions, an active agent, a successful
trace, and application access. Next, [connect a private worker](/air/workers/create-worker).
# Environment variables
Source: https://docs.papermap.ai/air/reference/environment-variables
Configuration used by AIR applications and worker processes.
## Applications
The SDK constructor accepts values directly. These conventional names keep
application configuration consistent:
| Variable | Required | Example |
| -------------- | -------- | ------------------------------------ |
| `AIR_BASE_URL` | Yes | `https://dev.airapi.papermap.ai` |
| `AIR_APP_KEY` | Yes | Project app key from the AIR console |
```python theme={null}
import os
from air import AirClient
client = AirClient(
os.environ["AIR_BASE_URL"],
os.environ["AIR_APP_KEY"],
)
```
## Worker CLI
| Variable | Required | Default | Purpose |
| -------------------------- | -------- | --------- | ---------------------------------------- |
| `AIR_BASE_URL` | Yes | None | AIR API origin. |
| `AIR_WORKER_KEY` | Yes | None | Project-scoped worker credential. |
| `AIR_WORKER_ENV` | No | `default` | Label describing the worker environment. |
| `AIR_WORKER_CLAIM_TIMEOUT` | No | `5` | Task long-poll timeout in seconds. |
```bash theme={null}
AIR_BASE_URL="https://dev.airapi.papermap.ai" \
AIR_WORKER_KEY="" \
AIR_WORKER_ENV="staging" \
air worker start --module tools
```
Keep keys out of committed `.env` files. In deployed environments, inject
them from a managed secret store.
# Python SDK
Source: https://docs.papermap.ai/air/reference/python-sdk
Reference for AIR application clients, runs, workers, tools, and errors.
The PyPI distribution is `papermap-air`; the Python import is `air`. Python
3.10 or newer is required and the SDK is async-native.
```bash theme={null}
python -m pip install papermap-air
```
## `AirClient`
```python theme={null}
AirClient(base_url: str, api_key: str)
```
Use it as an async context manager or call `await client.aclose()` explicitly.
### `client.runs.create()`
Creates a run. `agent_id` is required. `model_id`, `input`, `context`, and
`webhook_url` are optional. Returns a `Run`.
### `client.runs.get(run_id)`
Returns the latest state of a run.
### `client.runs.wait(run_id, timeout=60, poll_interval=0.2)`
Polls until `succeeded`, `failed`, or `cancelled`. Raises `RunTimeoutError` when
the local timeout is reached.
### `client.runs.stream(run_id, *, after_seq=0, max_retries=3, retry_delay=0.5)`
Returns an async iterator of `RunEvent` objects. It emits existing events after
`after_seq`, continues with live events, and stops after a terminal
`run_succeeded`, `run_failed`, or `run_cancelled` event.
The SDK reconnects after a temporary stream failure and resumes after the last
sequence number it received. `max_retries` controls the number of reconnect
attempts and `retry_delay` controls the delay between them.
```python theme={null}
text = ""
async for event in client.runs.stream(run.id):
if event.output_delta is not None:
text += event.output_delta
elif event.type == "model_output_reset":
text = ""
```
### `client.runs.cancel(run_id)`
Requests cancellation and returns the server response dictionary.
## `Run`
| Field | Type | Meaning |
| ---------- | -------------- | ------------------------------------------------------------------------ |
| `id` | `str` | Run identifier. |
| `status` | `str` | Current lifecycle status. |
| `output` | `dict \| None` | Validated schema object, or `{ "text": "..." }` for a schema-less agent. |
| `error` | `str \| None` | Failure detail when available. |
| `cost_usd` | `str` | Recorded cost as a decimal string. |
| `raw` | `dict` | Complete server response. |
## `RunEvent`
| Field | Type | Meaning |
| -------------- | ------------- | --------------------------------------------------------------------- |
| `seq` | `int` | Increasing sequence number within the run. |
| `type` | `str` | Event type, such as `model_output_delta` or `run_succeeded`. |
| `data` | `dict` | Event-specific payload. |
| `created_at` | `str \| None` | Server timestamp when available. |
| `output_delta` | `str \| None` | Convenience property containing text for `model_output_delta` events. |
When `type` is `model_output_reset`, discard any partial model text already
rendered. This event means AIR started another model attempt after a retry or
fallback. Terminal run events end the iterator.
## `@tool`
```python theme={null}
from air import tool
@tool(name="lookup_order", timeout=30)
def lookup_order(order_id: str, context: dict) -> dict:
"""Look up one order."""
return {"order_id": order_id}
```
The decorator derives a JSON schema from type annotations. Synchronous tools
run in a thread; async tools are awaited. A `context` parameter receives the
run context. Every tool must return a dictionary.
Use a separate `ToolRegistry` when you want explicit isolation instead of the
process-wide default registry.
## `Worker`
```python theme={null}
Worker(
base_url: str,
worker_key: str,
*,
registry: ToolRegistry | None = None,
environment: str = "default",
)
```
Important methods are `start()`, `poll_once()`, `heartbeat()`, `run()`,
`mount_mcp()`, and `aclose()`.
## Errors
All SDK errors inherit from `AirError`:
* `AirProtocolError` for rejected or unexpected HTTP responses
* `RunTimeoutError` when a local wait deadline expires
* `ToolDefinitionError` for invalid or duplicate tool definitions
* `ToolResultError` when a tool does not return a dictionary
* `McpError` for MCP transport or protocol failures
# Create a private worker
Source: https://docs.papermap.ai/air/workers/create-worker
Register typed Python functions as governed tools over an outbound-only worker connection.
Workers keep database and API access inside your infrastructure. They make
outbound HTTPS requests to AIR; you do not expose an inbound worker port.
```bash theme={null}
python -m pip install papermap-air
```
Create `tools.py`:
```python theme={null}
from air import tool
@tool(timeout=30)
def lookup_order(order_id: str, context: dict) -> dict:
"""Look up an order for the current tenant."""
tenant_id = context["tenant_id"]
# Query your system and verify the order belongs to tenant_id.
return {
"order_id": order_id,
"tenant_id": tenant_id,
"status": "shipped",
}
```
Type annotations become the JSON input schema. The first docstring line is
the description shown during review. Every tool must return a dictionary.
Open **Settings**, select **Issue worker key**, and store the value in an
environment variable or secret manager.
```bash theme={null}
export AIR_BASE_URL="https://dev.airapi.papermap.ai"
export AIR_WORKER_KEY=""
export AIR_WORKER_ENV="staging"
air worker start --module tools
```
The process registers its manifest and begins long-polling for tool calls.
Open **Tools**. A newly discovered capability starts **awaiting approval**;
registration never grants permission by itself.
Select **Review**. Confirm the source, description, timeout, generated input
schema, and whether it needs write access. Then select **Enable tool**.
Create a new agent version, open **Advanced — fallback models, tools, and
limits**, add `lookup_order`, test the version, and activate it. Enabling a
project tool does not automatically add it to existing agent versions.
Registration answers “what can this worker do?” Tool approval answers “does
this project trust it?” The agent version answers “may this agent call it?”
# Deploy a worker
Source: https://docs.papermap.ai/air/workers/deploy-worker
Package and operate AIR workers safely in containers and Kubernetes.
A worker is a long-running Python process. Run it anywhere that can reach AIR
over HTTPS and the private systems used by its tools.
## Container example
```dockerfile theme={null}
FROM python:3.12-slim
WORKDIR /app
RUN python -m pip install --no-cache-dir papermap-air==0.1.0
COPY tools.py /app/tools.py
CMD ["air", "worker", "start", "--module", "tools"]
```
Configure runtime values through your deployment system:
```text theme={null}
AIR_BASE_URL=https://dev.airapi.papermap.ai
AIR_WORKER_KEY=
AIR_WORKER_ENV=staging
AIR_WORKER_CLAIM_TIMEOUT=5
```
## Kubernetes secret reference
```yaml theme={null}
env:
- name: AIR_BASE_URL
value: https://dev.airapi.papermap.ai
- name: AIR_WORKER_KEY
valueFrom:
secretKeyRef:
name: air-worker
key: worker-key
- name: AIR_WORKER_ENV
value: staging
```
## Operational checklist
* Pin the SDK version and test upgrades before rollout.
* Give staging and production separate worker keys.
* Give the worker's database identity the minimum required permissions.
* Let the process receive `SIGTERM`; the CLI stops claiming work and closes its connections.
* Start with one staging replica and scale after observing tool latency and throughput.
* Rotate a key by deploying the new value, confirming reconnection, and revoking the old key.
* Monitor registration, task failure, lease loss, and downstream timeouts.
Do not put real credentials in a Dockerfile, image layer, committed `.env`
file, or Kubernetes manifest. Sync them from a managed vault at runtime.
# Connect MCP tools
Source: https://docs.papermap.ai/air/workers/mcp
Mount local Model Context Protocol servers into an outbound AIR worker.
The Python SDK can mount a local Model Context Protocol server and proxy its
tools through the normal AIR worker connection.
## Stdio server
```python theme={null}
import asyncio
import os
from air import Worker
async def main() -> None:
worker = Worker(
os.environ["AIR_BASE_URL"],
os.environ["AIR_WORKER_KEY"],
environment=os.getenv("AIR_WORKER_ENV", "staging"),
)
stop = asyncio.Event()
try:
names = await worker.mount_mcp(
"stdio",
command=["python", "my_mcp_server.py"],
prefix="inventory",
)
print("registered", names)
await worker.run(stop)
finally:
await worker.aclose()
asyncio.run(main())
```
## Local HTTP server
```python theme={null}
names = await worker.mount_mcp(
"http",
url="http://127.0.0.1:8765/mcp",
prefix="internal",
timeout=30,
)
```
Call `mount_mcp()` before `start()` or `run()` so mounted tools are included in
the registration manifest. AIR normalizes unsupported characters in MCP tool
names and adds deterministic suffixes when names collide.
Mounted tools use the same review flow as Python tools: inspect the manifest,
enable the tool, and add it to a new agent version.
Treat an MCP server as executable infrastructure. Pin and review it, restrict
its credentials, and expose only the capabilities your project needs.
# Create Dashboard
Source: https://docs.papermap.ai/api-reference/create-dashboard
/api-reference/managing-dashboards/dashboard-openapi.json post /api/v1/external/dashboards
Endpoint to create a new dashboard
# Generate Embed Token
Source: https://docs.papermap.ai/api-reference/generate-embed-token
/api-reference/embedding/embed-openapi.json post /api/v1/embed/generate-token
Generate a temporary token for testing embedded dashboards. This token allows you to preview and test your dashboard embedding configuration before implementing it in production.
# Get Tenant Usage History
Source: https://docs.papermap.ai/api-reference/get-tenant-usage-history
/api-reference/tenant-usage/tenant-usage-openapi.json get /api/v1/external/workspaces/{workspace_id}/tenant-usage/{tenant_id}
Retrieve usage history for a specific tenant
# Get Workspace Tenant Usage
Source: https://docs.papermap.ai/api-reference/get-workspace-tenant-usage
/api-reference/tenant-usage/tenant-usage-openapi.json get /api/v1/external/workspaces/{workspace_id}/tenant-usage
Retrieve usage data for all tenants in a workspace
# Developer Platform
Source: https://docs.papermap.ai/changelog/developer-platform
API updates, new endpoints, and SDK releases
API updates, new endpoints, SDK releases, and developer-focused features.
# Release Notes
Source: https://docs.papermap.ai/changelog/release-notes
Follow along with updates across Papermap’s API
# Basic Embedding
Source: https://docs.papermap.ai/documentation/embedding/basic-embedding
## Secure Embedding with JavaScript
The recommended way to embed a dashboard is to fetch a secure token from your backend and dynamically create the iframe. This keeps your API credentials safe.
Although this guide demonstrates iframe embedding, the same backend pattern of
generating a signed token server-side also applies when embedding Papermap
through `@papermap/papermap`. If you are embedding `PaperChat`, `PaperCard`,
or `PaperBoard`, see [React
Components](/documentation/embedding/react-components).
**Security Best Practice:** Never expose your API credentials (API Key ID and
Secret Key) in your frontend code. Always generate tokens on your backend
server and fetch them from your frontend.
To generate tokens on your backend, see the [Backend: Generating Embed
Tokens](#backend%3A-generating-embed-tokens) section below for implementation
examples in Python, TypeScript, PHP, and Go.
To get the `dashboardId` for your dashboard, navigate to your Papermap workspace and click the top-left dropdown menu to view all dashboards. Select the "Show All Dashboards" section to view information about all dashboards including the `dashboardId`
The same `dashboardId` can also be used by the React components package when
rendering `PaperChat`, `PaperCard`, and `PaperBoard`.
### React Example
```tsx theme={null}
import { useEffect, useState } from "react";
function DashboardEmbed({ workspaceId, dashboardId }) {
const [iframeUrl, setIframeUrl] = useState("");
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
async function fetchToken() {
try {
const response = await fetch(
`/api/embed-token?workspaceId=${workspaceId}&dashboardId=${dashboardId}`
);
const data = await response.json();
const url = `https://papermap.ai/embedded/dashboard?embedded-token=${data.token}&workspace-id=${workspaceId}&dashboard-id=${dashboardId}`;
setIframeUrl(url);
setLoading(false);
} catch (err) {
setError(err.message);
setLoading(false);
}
}
fetchToken();
}, [workspaceId, dashboardId]);
if (loading) return Loading dashboard...
;
if (error) return Error: {error}
;
return (
);
}
```
**Why This Approach is Secure:** - Your API credentials stay on the server,
never exposed to the browser - Tokens are time-limited.
Each user gets a fresh token when they load the page - You can add
authentication checks before generating tokens
## Frontend Token Generation (Testing Only)
**For Development/Testing Only:** This approach exposes your API credentials
in the frontend code. Only use this for local development or testing. Never
use this in production applications.
For quick testing or prototyping, you can generate tokens directly in the frontend:
```javascript theme={null}
// Generate token directly in frontend (TESTING ONLY)
import crypto from 'crypto';
export function generateTokenFrontend(
workspaceId: string,
dashboardId: string,
apiKeyId: string,
secretKey: string,
): string {
const oneHour = 3600;
const validUntil = Math.floor(Date.now() / 1000) + oneHour;
const payload = `${workspaceId}${validUntil}`;
const signature = crypto
.createHmac('sha256', secretKey)
.update(payload)
.digest('hex');
const tokenData = {
api_key_id: apiKeyId,
workspace_id: workspaceId,
dashboard_id: dashboardId,
valid_until: validUntil,
signature: signature,
};
return Buffer.from(JSON.stringify(tokenData)).toString('base64url');
}
// Usage
async function embedDashboardWithFrontendToken() {
const workspaceId = "YOUR_WORKSPACE_ID";
const dashboardId = "YOUR_DASHBOARD_ID";
const apiKeyId = "YOUR_API_KEY_ID"; // ⚠️ EXPOSED IN FRONTEND
const secretKey = "YOUR_SECRET_KEY"; // ⚠️ EXPOSED IN FRONTEND
const token = await generateTokenFrontend(
workspaceId,
dashboardId,
apiKeyId,
secretKey
);
const iframeUrl = `https://papermap.ai/embedded/dashboard?embedded-token=${token}&workspace-id=${workspaceId}&dashboard-id=${dashboardId}`;
const iframe = document.getElementById("dashboard-iframe");
iframe.src = iframeUrl;
}
// Call when page loads
embedDashboardWithFrontendToken();
```
```html theme={null}
```
**When to Use Frontend Generation:** - ✅ Local development and testing - ✅
Internal tools with restricted access - ✅ Quick prototypes and demos - ❌
**Never in production** (credentials exposed to users) - ❌ Public-facing
applications - ❌ Applications requiring authentication
## Simple iframe Embedding
For testing purposes, you can also use a static iframe with a pre-generated token:
```html theme={null}
```
### Complete Example
Here's a full HTML example using kebab-case naming:
```html theme={null}
My Dashboard
Sales Dashboard
```
## Responsive Design
### CSS Styling
Make your embedded dashboards responsive:
```css theme={null}
.dashboard-container {
width: 100%;
height: 600px;
border: 1px solid #ddd;
border-radius: 8px;
}
@media (max-width: 768px) {
.dashboard-container {
height: 400px;
}
}
@media (max-width: 480px) {
.dashboard-container {
height: 300px;
border-radius: 4px;
}
}
```
## Backend: Generating Embed Tokens
To securely embed dashboards, you need to generate a signed token from your backend. Here's how to create the token:
### Token Generation
```python Python theme={null}
import hmac
import hashlib
import json
import base64
import time
def generate_embed_token(workspace_id: str, dashboard_id: str, api_key_id: str, secret_key: str):
# Token valid for 1 hour
valid_until = int(time.time()) + 3600
# Create HMAC signature
payload = f"{workspace_id}{valid_until}"
signature = hmac.new(
secret_key.encode(),
payload.encode(),
hashlib.sha256
).hexdigest()
# Create token data
token_data = {
"api_key_id": api_key_id,
"workspace_id": workspace_id,
"dashboard_id": dashboard_id,
"valid_until": valid_until,
"signature": signature
}
# Encode token
token_json = json.dumps(token_data)
encoded_token = base64.urlsafe_b64encode(token_json.encode()).decode()
return encoded_token
```
```typescript TypeScript/Node.js theme={null}
import crypto from "crypto";
function generateEmbedToken(
workspaceId: string,
dashboardId: string,
apiKeyId: string,
secretKey: string
): string {
// Token valid for 1 hour
const validUntil = Math.floor(Date.now() / 1000) + 3600;
// Create HMAC signature
const payload = `${workspaceId}${validUntil}`;
const signature = crypto
.createHmac("sha256", secretKey)
.update(payload)
.digest("hex");
// Create token data
const tokenData = {
api_key_id: apiKeyId,
workspace_id: workspaceId,
dashboard_id: dashboardId,
valid_until: validUntil,
signature: signature,
};
// Encode token
return Buffer.from(JSON.stringify(tokenData)).toString("base64url");
}
```
```php PHP theme={null}
$apiKeyId,
'workspace_id' => $workspaceId,
'dashboard_id' => $dashboardId,
'valid_until' => $validUntil,
'signature' => $signature
];
// Encode token
$token = base64_encode(json_encode($tokenData));
return str_replace(['+', '/', '='], ['-', '_', ''], $token);
}
?>
```
```go Go theme={null}
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"time"
)
func generateEmbedToken(workspaceID, dashboardID, apiKeyID, secretKey string) string {
// Token valid for 1 hour
validUntil := time.Now().Unix() + 3600
// Create HMAC signature
payload := workspaceID + fmt.Sprintf("%d", validUntil)
h := hmac.New(sha256.New, []byte(secretKey))
h.Write([]byte(payload))
signature := hex.EncodeToString(h.Sum(nil))
// Create token data
tokenData := map[string]interface{}{
"api_key_id": apiKeyID,
"workspace_id": workspaceID,
"dashboard_id": dashboardID,
"valid_until": validUntil,
"signature": signature,
}
// Encode token
jsonData, _ := json.Marshal(tokenData)
encoded := base64.URLEncoding.EncodeToString(jsonData)
return strings.TrimRight(encoded, "=")
}
```
### Usage Example
```python Python (FastAPI) theme={null}
from fastapi import APIRouter
router = APIRouter()
@router.get("/embed-token")
async def get_embed_token(workspace_id: str, dashboard_id: str):
token = generate_embed_token(
workspace_id=workspace_id,
dashboard_id=dashboard_id,
api_key_id="your-api-key-id",
secret_key="your-secret-key"
)
return {"token": token}
```
```typescript TypeScript (Express) theme={null}
import express from "express";
const router = express.Router();
router.get("/embed-token", (req, res) => {
const { workspaceId, dashboardId } = req.query;
const token = generateEmbedToken(
workspaceId as string,
dashboardId as string,
"your-api-key-id",
"your-secret-key"
);
res.json({ token });
});
```
**Security Note:** Always store your API credentials in environment variables,
never hardcode them in your source code. The token is valid for how long you set it for but it is recommended to be 1 hour for security sake.
## Next Steps
Learn about advanced configuration options and customization parameters for your embedded dashboards
Explore common parameter combinations and use cases for different embedding scenarios
Common issues and solutions for embedding Papermap dashboards in your application
# Configuration
Source: https://docs.papermap.ai/documentation/embedding/configuration
Learn the various configuation and personalization options availiable when embedding Papermap
## URL Parameters
The embedding URL supports various parameters to customize the dashboard appearance and functionality. All parameters use kebab-case naming convention.
### Required Parameters
| Parameter | Description | Example |
| ----------------- | ------------------------ | -------------- |
| `embedding-token` | Embedding token | `Z0FBQ...` |
| `workspace-id` | The workspace identifier | `dIwIBPYdGmWS` |
| `dashboard-id` | The dashboard id | `dIwIBPYmWS` |
### Display Options
| Parameter | Type | Default | Description |
| ----------------- | ------- | ------- | --------------------------------------- |
| `show-toolbar` | boolean | `true` | Show/hide the chat toolbar |
| `show-header` | boolean | `true` | Show/hide the dashboard header |
| `show-nav` | boolean | `false` | Show/hide navigation elements |
| `show-screenshot` | boolean | `true` | Enable/disable screenshot functionality |
### Dashboard Controls
| Parameter | Type | Default | Description |
| ----------------------- | ------- | ------- | ------------------------------------ |
| `show-dashboard-select` | boolean | `false` | Show dashboard selector dropdown |
| `generate-dashboard` | boolean | `false` | Enable dashboard generation features |
| `edit-mode` | boolean | `false` | Enable edit mode for dashboard |
| `edit-layout` | boolean | `false` | Enable layout editing |
| `edit-chart` | boolean | `false` | Enable chart editing |
| `delete-chart` | boolean | `false` | Enable chart deletion |
| `pin-chart` | boolean | `false` | Enable chart pinning |
### Chat Features
| Parameter | Type | Default | Description |
| ------------------- | ------- | ------- | ------------------ |
| `chat-composer` | boolean | `true` | Show chat composer |
| `show-chat-toolbar` | boolean | `true` | Show chat toolbar |
### Appearance
| Parameter | Type | Options | Default | Description |
| --------- | ------ | ------------------------- | ------- | --------------- |
| `theme` | string | `light`, `dark`, `system` | `light` | Dashboard theme |
## Next Steps
Explore common parameter combinations and use cases for different embedding scenarios
Common issues and solutions for embedding Papermap dashboards in your application
# Getting Your API Key
Source: https://docs.papermap.ai/documentation/embedding/get-api-key
API Keys in Papermap are scoped to workspaces. A workspace is a secure environment connected to a specific data source where you can chat with our AI to obtain insights from your data and build multiple live dashboards.
The API key you create here can be used for both iframe embedding and React
component embedding with `@papermap/papermap`. For the React integration path,
see [React Components](/documentation/embedding/react-components).
Follow the steps below to obtain an API key:
Visit [papermap.ai](https://www.papermap.ai) and sign in with your credentials.
Navigate to your workspace and click the options icon (three dots) in the workspace card, then select **Settings** from the dropdown menu.
Navigate to **API Keys** from the sidebar and click **Create New Key** to generate a new API key.
Copy the generated API key (starts with `ak_`) and SECRET key also. Store it securely!
## Security Considerations
**Never expose your API key in client-side code or public repositories.** Your API key provides full access to your Papermap data and should be treated as a password.
### Best Practices
* **Store securely**: Use environment variables or secure configuration management
* **Never commit**: Add your API key to `.gitignore` and never commit it to version control
* **Rotate regularly**: Generate new API keys periodically and revoke old ones
* **Monitor usage**: Check your API key usage in the Papermap dashboard for any suspicious activity
* **Use HTTPS**: Always use HTTPS when embedding dashboards to protect data in transit
### For Production Applications
* Implement server-side proxy endpoints that generate temporary tokens
* Use proper authentication and authorization before serving embedded content
## Next Steps
Embed `PaperChat`, `PaperCard`, and `PaperBoard` directly in your React application
Start with simple iframe embedding to get your first dashboard up and running
Learn about advanced configuration options and customization parameters for your embedded dashboards
Explore common parameter combinations and use cases for different embedding scenarios
Common issues and solutions for embedding Papermap dashboards in your application
# Embedding Overview
Source: https://docs.papermap.ai/documentation/embedding/overview
Papermap provides powerful embedding capabilities that allow you to integrate conversational analytics, interactive dashboards and visualizations directly into your website or web application.
## Overview
Embedding allows you to:
* Include Papermap conversational analytics directly into your web application
* Display live dashboards in your website
* Customize the appearance and functionality
* Control user interactions and permissions
* Maintain consistent branding with your application
This guide will walk you through the various embedding options and implementation methods.
## Next Steps
Learn how to obtain and configure your API key for embedding Papermap dashboards
Embed `PaperChat`, `PaperCard`, and `PaperBoard` directly in your React application
Start with simple iframe embedding to get your first dashboard up and running
Learn about advanced configuration options and customization parameters for your embedded dashboards
Explore common parameter combinations and use cases for different embedding scenarios
Common issues and solutions for embedding Papermap dashboards in your application
# Parameter Usecases
Source: https://docs.papermap.ai/documentation/embedding/parameter-usecases
### Dashboard Selection Parameters
* **`dashboard-id`**: Use when you want to embed a specific dashboard instead of the default one
* **`show-dashboard-select`**: Enable this to allow users to switch between different dashboards within the embedded view
### Navigation Control
* **`show-nav`**: Set to `true` to show the main navigation sidebar (useful for full-featured embeds)
### Chat Integration
* **`chat-composer`**: Show the AI chat interface for data queries
* **`show-toolbar`**: Control the visibility of the chat toolbar
* **`show-chat-toolbar`**: Control the visibility of the chat toolbar specifically
### Editing and Generation Features
* **`generate-dashboard`**: Enable dashboard generation features for creating new dashboards
* **`edit-mode`**: Enable edit mode to allow users to modify dashboard content
* **`edit-layout`**: Enable layout editing to rearrange dashboard components
* **`edit-chart`**: Enable chart editing to modify individual charts
* **`delete-chart`**: Enable chart deletion functionality
* **`pin-chart`**: Enable chart pinning to keep important charts visible
### Parameter Examples
Here are some common parameter combinations:
Replace `YOUR_TOKEN` with the embedded token generated from your backend. See
the [Get API Key](/documentation/embedding/get-api-key) guide for details.
```html theme={null}
```
## Next Steps
Common issues and solutions for embedding Papermap dashboards in your application
# React Components
Source: https://docs.papermap.ai/documentation/embedding/react-components
Papermap also supports embedding with React components through `@papermap/papermap`. This package lets you embed Papermap-native chat, chart cards, and board layouts directly in your application instead of embedding the full dashboard iframe.
## Main Components
* **`PaperChat`**: Full AI chat assistant with streaming, conversation history, and chart generation.
* **`PaperCard`**: Standalone chart card with toolbar actions. Use `variant="streaming"` for an embedded chart and conversation dialog without the floating assistant.
* **`PaperBoard`**: Responsive grid layout of chart cards, toolbar actions, optional chat assistant, and controlled or uncontrolled layouts.
Each top-level component handles API calls, authentication, and UI internally unless you compose lower-level exports yourself.
### `PaperChat`
Use `PaperChat` when you want the embedded AI assistant experience with chat history, chart generation, and streaming responses.
```tsx theme={null}
import { PaperChat } from '@papermap/papermap'
```
### `PaperCard`
Use `PaperCard` when you want to render a single chart card with Papermap toolbar actions inside your own page layout.
```tsx theme={null}
import { PaperCard } from '@papermap/papermap'
```
### `PaperCard` streaming variant
Use `variant="streaming"` when you want the chart card and the expanded conversation flow together in the same embedded surface.
```tsx theme={null}
import { PaperCard } from '@papermap/papermap'
```
### `PaperBoard`
Use `PaperBoard` when you want a dashboard-style layout with multiple cards, optional chat assistant, and responsive board behavior.
```tsx theme={null}
import { PaperBoard } from '@papermap/papermap'
```
## Quick Start
### 1. Install
```bash npm theme={null}
npm install @papermap/papermap
```
```bash pnpm theme={null}
pnpm add @papermap/papermap
```
**Requirements:** React 18+ and React DOM 18+.
### 2. Import styles once
```tsx theme={null}
import '@papermap/papermap/styles.css'
```
### 3. Before you start
You will need a few Papermap values before the components can render successfully:
* **API key**: Generate this in Papermap before wiring up your app. See [Getting Your API Key](/documentation/embedding/get-api-key).
* **`workspaceId`**: Use the workspace that owns the charts and dashboards you want to embed.
* **`dashboardId`**: Use the dashboard context you want the embedded components to read from and save into. See [Basic Embedding](/documentation/embedding/basic-embedding).
* **Frontend token**: Your app should fetch a signed, base64-encoded token from your backend. See [Basic Embedding](/documentation/embedding/basic-embedding#backend%3A-generating-embed-tokens) for the backend token generation flow.
* **Optional `apiUrl`**: Only set this if your environment uses a non-default Papermap API base URL.
`token` is not the raw API key. Keep the API key and secret on your backend,
and return a short-lived signed token to your frontend instead.
### 4. Minimal integration flow
1. Create an API key in Papermap.
2. Identify the `workspaceId` and `dashboardId` you want to use.
3. Add a backend endpoint that returns a signed token to your frontend.
4. Wrap your app with `PapermapConfigProvider` or pass the values directly to each component.
5. Render `PaperChat`, `PaperCard`, or `PaperBoard`.
If you are implementing tenant-aware dashboard provisioning or server-side
dashboard creation, see [Creating
Dashboards](/documentation/multi-tenancy/creating-dashboards) and [Iframe
Embed Tokens](/documentation/multi-tenancy/iframe-tokens).
### 5. Choose an integration pattern
#### Recommended: provider at app root
`PapermapConfigProvider` is an alias for `PapermapProvider`.
```tsx theme={null}
import {
PapermapConfigProvider,
PaperChat,
PaperCard,
} from '@papermap/papermap'
function App() {
return (
)
}
```
#### Standalone components
Pass `token`, `workspaceId`, and `dashboardId` on each component when you are not using a provider.
```tsx theme={null}
import { PaperChat, PaperCard } from '@papermap/papermap'
function App() {
return (
<>
>
)
}
```
## Props
### `PaperChat`
| Prop | Type | Required | Default | Description |
| ------------- | ------------------- | -------- | ----------------------------- | ---------------------------------------- |
| `token` | `string` | Yes\* | -- | Base64-encoded API token |
| `workspaceId` | `string` | Yes\* | -- | Workspace ID |
| `dashboardId` | `string` | Yes\* | -- | Dashboard ID |
| `apiUrl` | `string` | No | `https://dataapi.papermap.ai` | API base URL |
| `theme` | `'light' \| 'dark'` | No | -- | Force light or dark theme |
| `placeholder` | `string` | No | `"Ask anything..."` | Input placeholder text |
| `shortcutKey` | `string` | No | `"k"` | Keyboard shortcut key |
| `autoFade` | `boolean` | No | `false` | Fade toolbar after inactivity |
| `fadeDelay` | `number` | No | `5000` | Delay before auto-fade in milliseconds |
| `className` | `string` | No | -- | Extra CSS class on the toolbar container |
\*Omit these on the component when values come from `PapermapConfigProvider` or `PapermapProvider`.
### `PaperCard`
| Prop | Type | Required | Default | Description |
| -------------- | -------------------------------------------- | -------- | ----------------------------- | ------------------------------------------------------------- |
| `token` | `string` | Yes\* | -- | Base64-encoded API token |
| `workspaceId` | `string` | Yes\* | -- | Workspace ID |
| `dashboardId` | `string` | Yes\* | -- | Dashboard ID |
| `apiUrl` | `string` | No | `https://dataapi.papermap.ai` | API base URL |
| `chartId` | `string` | No | -- | Backend chat ID to load the latest chart for |
| `chart` | `TChartResponse` | No | -- | Pre-loaded chart data that skips API fetch |
| `theme` | `'light' \| 'dark'` | No | -- | Force light or dark theme |
| `onEditClick` | `(chartId: string) => void` | No | -- | Called when the edit button is clicked |
| `onDelete` | `(chartId: string) => void` | No | -- | Called when chart deletion is confirmed |
| `onPinChange` | `(chartId: string, pinned: boolean) => void` | No | -- | Called when pin state changes |
| `wide` | `boolean` | No | `false` | Wide mode for table charts |
| `hideVariants` | `boolean` | No | `true` | Hide the chart variation selector |
| `showToolbar` | `boolean` | No | `true` | Show toolbar actions |
| `className` | `string` | No | -- | Extra CSS class on the card container |
| `variant` | `'default' \| 'streaming'` | No | `'default'` | Embedded streaming mode opens chart and conversation together |
### Pre-loaded chart example
```tsx theme={null}
import { PaperCard } from '@papermap/papermap'
import type { TChartResponse } from '@papermap/papermap'
const chart: TChartResponse = {
llm_data_chat_id: 'my-chart-id',
name: 'Revenue',
meta: { title: 'Revenue by Quarter', variant: 'default' },
pin: false,
chart_response: {
chart_type: 'bar',
data: [
{ quarter: 'Q1', revenue: 42000 },
{ quarter: 'Q2', revenue: 55000 },
],
response_type: 'chart',
schema_hints: { x_key: 'quarter', y_key: 'revenue', label_key: 'quarter' },
visualization_config: { colors: ['#3b82f6'], width: 600, height: 400 },
},
}
console.log('Edit', id)}
onDelete={(id) => console.log('Delete', id)}
/>
```
### `PaperBoard`
| Prop | Notes |
| ------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------ |
| `token`, `workspaceId`, `dashboardId`, `apiUrl` | Same configuration as the other components; can come from a provider |
| `charts` | Optional pre-loaded charts; otherwise fetched when `enableFetch` is true |
| `layouts` / `onLayoutsChange` | Controlled grid layouts per breakpoint |
| `isEditMode`, `editLayout`, `isViewer` | Edit and view behavior controls |
| `showToolbar`, `showScreenshot`, `showGenerateDashboard`, `showHeader`, `showChatAssistant` | Feature toggles |
| `variant` | `'default' \| 'streaming'` for embedded chart cards |
| `dashboardTheme`, `onDashboardThemeChange`, `persistWorkspaceTheme`, `renderThemeModal` | Theming controls |
| `onEditChart`, `onDeleteChart`, `onPinChange`, `onGenerateDashboard`, `onTakeScreenshot`, `onThemeModalOpen` | Lifecycle and UI callbacks |
See the TypeScript types for `PaperBoardProps` for the full API surface.
### Streaming chart card variant
With `variant="streaming"`, the edit action opens an embedded expanded view with chart, conversation, SSE streaming, save-to-dashboard actions, maximize actions, and assistant audit history.
```tsx theme={null}
import { PaperCard } from '@papermap/papermap'
export function EmbeddedStreamingChart() {
return (
)
}
```
Supported chart types: `bar`, `line`, `area`, `pie`, `radar`, `scatter`, `table`, `tile`.
## Advanced Exports
For custom layouts, the package also exports subcomponents such as `ChatAssistant`, `StreamingChartDialog`, `ChartView`, and `DataTable`, along with Zustand store helpers, hooks like `useAnalyticsStream`, API helpers such as `createApiClient`, `decodeToken`, and `buildAuthHeaders`, plus streaming and chart types.
## Troubleshooting
### Cannot find module `@papermap/papermap/styles.css`
* Use the scoped package name and the `./styles.css` export.
* Reinstall after upgrading.
### Papermap requires `token`, `workspaceId`, or `dashboardId`
* Provide the values once via `PapermapConfigProvider` or `PapermapProvider`.
* Or pass them directly on each component.
### Requests hit the wrong backend
* Set `apiUrl` on the provider or per component. The default is `https://dataapi.papermap.ai`.
### Charts do not appear in `PaperCard`
* Pass a valid backend `chartId`.
* Or provide pre-loaded `chart` data directly.
## How It Works
### Authentication
The `token` prop is base64-encoded JSON:
```json theme={null}
{
"api_key_id": "ak_...",
"workspace_id": "...",
"valid_until": 1773246356,
"signature": "88b34e..."
}
```
The library decodes the token and sends these headers on API requests:
* `X-API-Key-ID`
* `X-Workspace-ID`
* `X-Valid-Until`
* `X-Signature`
* `X-Tenant-ID: da-app`
### Chat data flow
1. The first user message may create a chat via `POST /api/v1/analytics/chats`.
2. Messages are sent to `POST /api/v1/analytics/charts/stream`.
3. SSE connects to `POST /api/v1/analytics/requests/stream` for live updates, with HTTP fallback when needed.
4. History is loaded from chat conversations, dashboard recent chats, and chart history endpoints.
### What users see in `PaperChat`
* Floating input bar with keyboard shortcut support.
* Conversation panel with streaming states, stop action, and new chat flow.
* Recent conversations, per-chat history, feedback, optional execution view, and model selection.
## Next Steps
Generate the API credentials you need before wiring up the React package.
Use iframe embedding if you want the full Papermap dashboard surface instead.
Review common integration issues and fixes.
# Troubleshoot
Source: https://docs.papermap.ai/documentation/embedding/troubleshooting
### Common Issues
* Verify your API key is correct and active
* Check that the workspace ID exists and is accessible
* Ensure you're using HTTPS for the iframe source
* Use CSS to customize the iframe appearance
* Try different theme options (`light`, `dark`, `system`)
* Check for CSS conflicts with your site's styles
* Check if you're using the correct dashboard ID
* Verify your workspace has the latest data
* Clear your browser cache and refresh
### Getting Help
If you're still having issues:
* Verify all required parameters are included in your URL
* Check the browser console for error messages
* Contact [support](mailto:team@papermap.ai) with your specific error details
# API Endpoints
Source: https://docs.papermap.ai/documentation/multi-tenancy/api-endpoints
This guide provides example REST API endpoints for dashboard operations in your backend.
## Overview
Your API should expose endpoints for:
* Creating dashboards for tenants
* Retrieving tenant dashboards
* Generating iframe embed tokens
* Managing dashboard access
## Authentication Middleware
All endpoints should require authentication. Here's an example middleware:
```python Python (FastAPI) theme={null}
from fastapi import Depends, HTTPException, Header
from jose import jwt, JWTError
async def get_authenticated_user(
authorization: str = Header(None)
) -> dict:
"""Verify JWT token and return user info"""
if not authorization or not authorization.startswith("Bearer "):
raise HTTPException(status_code=401, detail="Missing authorization")
token = authorization.replace("Bearer ", "")
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=["HS256"])
return payload
except JWTError:
raise HTTPException(status_code=401, detail="Invalid token")
```
```typescript TypeScript (Express) theme={null}
import jwt from "jsonwebtoken";
function authenticateUser(req, res, next) {
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith("Bearer ")) {
return res.status(401).json({ error: "Missing authorization" });
}
const token = authHeader.replace("Bearer ", "");
try {
const payload = jwt.verify(token, process.env.SECRET_KEY);
req.user = payload;
next();
} catch (error) {
return res.status(401).json({ error: "Invalid token" });
}
}
```
## Create Dashboard Endpoint
The `create_dashboard` function being called in the endpoint below should have already been created in
the [Creating Dashboards](/documentation/multi-tenancy/creating-dashboards#creating-a-dashboard) guide.
Create a new dashboard for a tenant.
```python Python (FastAPI) theme={null}
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel
router = APIRouter(prefix="/api/v1/dashboards", tags=["dashboards"])
class DashboardCreate(BaseModel):
tenant_id: str
workspace_id: str
name: str
description: Optional[str] = None
@router.post("/")
async def create_dashboard(
dashboard: DashboardCreate,
current_user: Dict = Depends(get_authenticated_user),
db: Session = Depends(get_db)
):
"""Create a dashboard for a tenant"""
# Verify user has permission to create dashboard for this tenant
if not has_access(current_user, dashboard.tenant_id):
raise HTTPException(status_code=403, detail="Access denied")
handler = DashboardHandler(db)
result = await handler.create_dashboard(
tenant_id=dashboard.tenant_id,
workspace_id=dashboard.workspace_id,
name=dashboard.name,
description=dashboard.description,
created_by=current_user["user_id"]
)
return {
"success": True,
"data": result
}
```
```typescript TypeScript (Express) theme={null}
import express from "express";
const router = express.Router();
router.post("/dashboards", authenticateUser, async (req, res) => {
const { tenantId, workspaceId, name, description } = req.body;
// Verify user has permission
if (!hasAccess(req.user, tenantId)) {
return res.status(403).json({ error: "Access denied" });
}
try {
const dashboard = await createDashboard(
tenantId,
workspaceId,
name,
description
);
res.json({
success: true,
data: dashboard,
});
} catch (error) {
res.status(500).json({
error: error.message,
});
}
});
```
```php PHP (Laravel) theme={null}
validate([
'tenant_id' => 'required|string',
'workspace_id' => 'required|string',
'name' => 'required|string',
'description' => 'nullable|string',
]);
// Verify user has permission
if (!hasAccess(Auth::user(), $validated['tenant_id'])) {
return response()->json(['error' => 'Access denied'], 403);
}
$dashboard = createDashboardForTenant(
$validated['tenant_id'],
$validated['workspace_id'],
$validated['name'],
$validated['description'] ?? null
);
return response()->json([
'success' => true,
'data' => $dashboard
]);
})->middleware('auth:api');
?>
```
**Request:**
```bash theme={null}
POST /api/v1/dashboards
Authorization: Bearer YOUR_JWT_TOKEN
{
"tenant_id": "org-123",
"workspace_id": "workspace-456",
"name": "Sales Dashboard",
"description": "Q4 Sales Analytics"
}
```
**Response:**
```json theme={null}
{
"success": true,
"data": {
"id": "dashboard-789",
"tenant_id": "org-123",
"workspace_id": "workspace-456",
"dashboard_id": "dashboard-789",
"created_at": "2024-01-15T10:30:00Z"
}
}
```
## Get Dashboard by Tenant
Retrieve the dashboard for a specific tenant.
```python Python (FastAPI) theme={null}
@router.get("/{tenant_id}")
def get_dashboard_by_tenant(
tenant_id: str,
current_user: Dict = Depends(get_authenticated_user),
db: Session = Depends(get_db)
):
"""Get dashboard for a specific tenant"""
# Verify access
if not has_access(current_user, tenant_id):
raise HTTPException(status_code=403, detail="Access denied")
handler = DashboardHandler(db)
dashboard = handler.get_dashboard_by_tenant(tenant_id)
if not dashboard:
raise HTTPException(status_code=404, detail="Dashboard not found")
return {
"success": True,
"data": dashboard
}
```
```typescript TypeScript (Express) theme={null}
router.get("/dashboards/:tenantId", authenticateUser, async (req, res) => {
const { tenantId } = req.params;
// Verify access
if (!hasAccess(req.user, tenantId)) {
return res.status(403).json({ error: "Access denied" });
}
const dashboard = await db.tenantDashboards.findOne({
where: { tenant_id: tenantId },
});
if (!dashboard) {
return res.status(404).json({ error: "Dashboard not found" });
}
res.json({
success: true,
data: dashboard,
});
});
```
**Request:**
```bash theme={null}
GET /api/v1/dashboards/org-123
Authorization: Bearer YOUR_JWT_TOKEN
```
**Response:**
```json theme={null}
{
"success": true,
"data": {
"id": "dashboard-789",
"tenant_id": "org-123",
"workspace_id": "workspace-456",
"dashboard_id": "dashboard-789",
"created_at": "2024-01-15T10:30:00Z"
}
}
```
## Generate Iframe Token
Generate a secure token for embedding a dashboard.
```python Python (FastAPI) theme={null}
class DashboardIframeTokenRequest(BaseModel):
tenant_id: str
workspace_id: str
dashboard_id: str
valid_until: Optional[int] = None
@router.post("/iframe-token")
def create_iframe_token(
request: DashboardIframeTokenRequest,
current_user: Dict = Depends(get_authenticated_user),
db: Session = Depends(get_db)
):
"""Generate secure token for embedding dashboard in iframe"""
# Verify tenant belongs to user
if not has_access(current_user, request.tenant_id):
raise HTTPException(status_code=403, detail="Access denied")
handler = DashboardHandler(db)
token_data = handler.generate_iframe_token(
tenant_id=request.tenant_id,
workspace_id=request.workspace_id,
dashboard_id=request.dashboard_id,
valid_until=request.valid_until
)
return {
"success": True,
"data": token_data
}
```
```typescript TypeScript (Express) theme={null}
router.post("/dashboards/iframe-token", authenticateUser, async (req, res) => {
const { tenantId, workspaceId, dashboardId, validUntil } = req.body;
// Verify tenant belongs to user
if (!hasAccess(req.user, tenantId)) {
return res.status(403).json({ error: "Access denied" });
}
const tokenData = generateIframeToken(
tenantId,
workspaceId,
dashboardId,
validUntil
);
res.json({
success: true,
data: tokenData,
});
});
```
**Request:**
```bash theme={null}
POST /api/v1/dashboards/iframe-token
Authorization: Bearer YOUR_JWT_TOKEN
{
"tenant_id": "org-123",
"workspace_id": "workspace-456",
"dashboard_id": "dashboard-789",
"valid_until": 1700000000 // Optional: Unix timestamp
}
```
**Response:**
```json theme={null}
{
"success": true,
"data": {
"token": "eyJhcGlfa2V5X2lkIjoieW91ci1hcGkta2V5IiwidGVuYW50X2lkIjoib3JnLTEyMyIsImRhc2hib2FyZF9pZCI6ImRhc2hib2FyZC03ODkiLCJ2YWxpZF91bnRpbCI6MTcwMDAwMDAwMCwic2lnbmF0dXJlIjoiYWJjMTIzLi4uIn0=",
"dashboard_id": "dashboard-789",
"expires_at": 1700000000
}
}
```
## List All Dashboards (Optional)
List all dashboards for the authenticated user's organization.
```python Python (FastAPI) theme={null}
@router.get("/")
def list_dashboards(
current_user: Dict = Depends(get_authenticated_user),
db: Session = Depends(get_db),
skip: int = 0,
limit: int = 100
):
"""List all dashboards for user's organization"""
organization_id = current_user.get("organization_id")
handler = DashboardHandler(db)
dashboards = handler.list_dashboards(
organization_id=organization_id,
skip=skip,
limit=limit
)
return {
"success": True,
"data": dashboards,
"total": len(dashboards)
}
```
```typescript TypeScript (Express) theme={null}
router.get("/dashboards", authenticateUser, async (req, res) => {
const organizationId = req.user.organizationId;
const { skip = 0, limit = 100 } = req.query;
const dashboards = await db.tenantDashboards.findAll({
where: { organization_id: organizationId },
offset: parseInt(skip),
limit: parseInt(limit),
});
res.json({
success: true,
data: dashboards,
total: dashboards.length,
});
});
```
## Delete Dashboard (Optional)
Delete a dashboard for a tenant.
```python Python (FastAPI) theme={null}
@router.delete("/{tenant_id}")
async def delete_dashboard(
tenant_id: str,
current_user: Dict = Depends(get_authenticated_user),
db: Session = Depends(get_db)
):
"""Delete dashboard for a tenant"""
# Verify access
if not has_access(current_user, tenant_id):
raise HTTPException(status_code=403, detail="Access denied")
handler = DashboardHandler(db)
success = await handler.delete_dashboard(tenant_id)
if not success:
raise HTTPException(status_code=404, detail="Dashboard not found")
return {
"success": True,
"message": "Dashboard deleted successfully"
}
```
```typescript TypeScript (Express) theme={null}
router.delete("/dashboards/:tenantId", authenticateUser, async (req, res) => {
const { tenantId } = req.params;
// Verify access
if (!hasAccess(req.user, tenantId)) {
return res.status(403).json({ error: "Access denied" });
}
const deleted = await db.tenantDashboards.destroy({
where: { tenant_id: tenantId },
});
if (!deleted) {
return res.status(404).json({ error: "Dashboard not found" });
}
res.json({
success: true,
message: "Dashboard deleted successfully",
});
});
```
## Error Handling
Implement consistent error handling across all endpoints:
```json theme={null}
// Success Response
{
"success": true,
"data": { ... }
}
// Error Response
{
"success": false,
"error": "Error message here",
"code": "ERROR_CODE"
}
```
### Common Error Codes
| Code | Status | Description |
| ------------------ | ------ | ------------------------------------ |
| `UNAUTHORIZED` | 401 | Missing or invalid authentication |
| `FORBIDDEN` | 403 | User doesn't have access to resource |
| `NOT_FOUND` | 404 | Resource not found |
| `VALIDATION_ERROR` | 422 | Invalid request parameters |
| `SERVER_ERROR` | 500 | Internal server error |
## Rate Limiting
Implement rate limiting to prevent abuse:
```python Python (FastAPI) theme={null}
from slowapi import Limiter, _rate_limit_exceeded_handler
from slowapi.util import get_remote_address
limiter = Limiter(key_func=get_remote_address)
@router.post("/iframe-token")
@limiter.limit("10/minute")
async def create_iframe_token(...):
# ... implementation
```
```typescript TypeScript (Express) theme={null}
import rateLimit from "express-rate-limit";
const tokenLimiter = rateLimit({
windowMs: 60 * 1000, // 1 minute
max: 10, // 10 requests per minute
message: "Too many token requests, please try again later",
});
router.post(
"/dashboards/iframe-token",
tokenLimiter,
authenticateUser,
async (req, res) => {
// ... implementation
}
);
```
## Next Steps
Learn about security considerations for production
Set up the frontend to embed dashboards
# HMAC Authentication
Source: https://docs.papermap.ai/documentation/multi-tenancy/authentication
This guide covers the HMAC signature authentication pattern used to secure requests to the Papermap Dashboard API.
## How HMAC Authentication Works
The core security pattern uses HMAC-SHA256 to sign requests to the Papermap API:
1. Concatenate `workspace_id` + `valid_until` timestamp
2. Create HMAC-SHA256 hash using your secret key
3. Send signature + timestamp in headers
4. Papermap API verifies signature with the same secret
### Authentication Flow
```
Your API → Generate HMAC Signature
payload = "workspace-456" + "1699999999"
signature = HMAC-SHA256(payload, secret_key)
Your API → Call Papermap Dashboard API
POST ${PAPERMAP_API_URL}/api/v1/external/dashboards
Headers:
X-API-Key-ID: your-api-key
X-Workspace-ID: workspace-456
X-Valid-Until: 1699999999
X-Signature: abc123...
Papermap API → Verifies Signature
- Extracts workspace_id and valid_until
- Computes: HMAC-SHA256(workspace_id + valid_until, secret_key)
- Compares computed signature with X-Signature header
- Checks valid_until hasn't expired
```
If the signature doesn't match or the timestamp has expired, the request is
rejected with a 401 Unauthorized error.
## Implementation by Language
```python Python theme={null}
import hmac
import hashlib
import time
def _create_signature(workspace_id: str, valid_until: str, secret_key: str) -> str:
"""Create HMAC signature for authentication"""
payload = f"{workspace_id}{valid_until}"
signature = hmac.new(
secret_key.encode(),
payload.encode(),
hashlib.sha256
).hexdigest()
return signature
def _get_auth_headers(workspace_id: str, api_key_id: str, secret_key: str) -> dict:
"""Generate authentication headers with HMAC signature"""
valid_until = str(int(time.time()) + 300) # Valid for 5 minutes
signature = _create_signature(workspace_id, valid_until, secret_key)
return {
"X-API-Key-ID": api_key_id,
"X-Workspace-ID": workspace_id,
"X-Valid-Until": valid_until,
"X-Signature": signature,
"Content-Type": "application/json"
}
```
```typescript TypeScript/Node.js theme={null}
import crypto from "crypto";
class DashboardAPIService {
private config: {
apiKeyId: string;
secretKey: string;
workspaceId: string;
baseUrl: string;
};
constructor(config: any) {
this.config = config;
}
private createSignature(workspaceId: string, validUntil: string): string {
const payload = `${workspaceId}${validUntil}`;
return crypto
.createHmac("sha256", this.config.secretKey)
.update(payload)
.digest("hex");
}
private getAuthHeaders(): Record {
const validUntil = String(Math.floor(Date.now() / 1000) + 300);
const signature = this.createSignature(this.config.workspaceId, validUntil);
return {
"X-API-Key-ID": this.config.apiKeyId,
"X-Workspace-ID": this.config.workspaceId,
"X-Valid-Until": validUntil,
"X-Signature": signature,
"Content-Type": "application/json",
};
}
}
```
```php PHP theme={null}
$apiKeyId,
'X-Workspace-ID' => $workspaceId,
'X-Valid-Until' => (string)$validUntil,
'X-Signature' => $signature,
'Content-Type' => 'application/json'
];
}
?>
```
```java Java theme={null}
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
@Service
public class DashboardAPIService {
@Value("${dashboard.api.key}")
private String apiKeyId;
@Value("${dashboard.secret.key}")
private String secretKey;
private String createSignature(String workspaceId, String validUntil)
throws Exception {
String payload = workspaceId + validUntil;
Mac hmac = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKeySpec = new SecretKeySpec(
secretKey.getBytes(StandardCharsets.UTF_8),
"HmacSHA256"
);
hmac.init(secretKeySpec);
byte[] hash = hmac.doFinal(payload.getBytes(StandardCharsets.UTF_8));
return bytesToHex(hash);
}
private HttpHeaders getAuthHeaders(String workspaceId) throws Exception {
long validUntil = Instant.now().getEpochSecond() + 300;
String signature = createSignature(workspaceId, String.valueOf(validUntil));
HttpHeaders headers = new HttpHeaders();
headers.set("X-API-Key-ID", apiKeyId);
headers.set("X-Workspace-ID", workspaceId);
headers.set("X-Valid-Until", String.valueOf(validUntil));
headers.set("X-Signature", signature);
headers.setContentType(MediaType.APPLICATION_JSON);
return headers;
}
private String bytesToHex(byte[] bytes) {
StringBuilder result = new StringBuilder();
for (byte b : bytes) {
result.append(String.format("%02x", b));
}
return result.toString();
}
}
```
```csharp C# theme={null}
using System;
using System.Security.Cryptography;
using System.Text;
public class DashboardAPIService
{
private readonly string _apiKeyId;
private readonly string _secretKey;
private readonly string _baseUrl;
public DashboardAPIService(string apiKeyId, string secretKey, string baseUrl)
{
_apiKeyId = apiKeyId;
_secretKey = secretKey;
_baseUrl = baseUrl;
}
private string CreateSignature(string workspaceId, string validUntil)
{
var payload = $"{workspaceId}{validUntil}";
var keyBytes = Encoding.UTF8.GetBytes(_secretKey);
var payloadBytes = Encoding.UTF8.GetBytes(payload);
using (var hmac = new HMACSHA256(keyBytes))
{
var hash = hmac.ComputeHash(payloadBytes);
return BitConverter.ToString(hash).Replace("-", "").ToLower();
}
}
private Dictionary GetAuthHeaders(string workspaceId)
{
var validUntil = DateTimeOffset.UtcNow.ToUnixTimeSeconds() + 300;
var signature = CreateSignature(workspaceId, validUntil.ToString());
return new Dictionary
{
{ "X-API-Key-ID", _apiKeyId },
{ "X-Workspace-ID", workspaceId },
{ "X-Valid-Until", validUntil.ToString() },
{ "X-Signature", signature },
{ "Content-Type", "application/json" }
};
}
}
```
```go Go theme={null}
package dashboard
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"time"
)
type DashboardAPIService struct {
APIKeyID string
SecretKey string
BaseURL string
}
func (s *DashboardAPIService) createSignature(workspaceID, validUntil string) string {
payload := workspaceID + validUntil
h := hmac.New(sha256.New, []byte(s.SecretKey))
h.Write([]byte(payload))
return hex.EncodeToString(h.Sum(nil))
}
func (s *DashboardAPIService) getAuthHeaders(workspaceID string) map[string]string {
validUntil := fmt.Sprintf("%d", time.Now().Unix()+300)
signature := s.createSignature(workspaceID, validUntil)
return map[string]string{
"X-API-Key-ID": s.APIKeyID,
"X-Workspace-ID": workspaceID,
"X-Valid-Until": validUntil,
"X-Signature": signature,
"Content-Type": "application/json",
}
}
```
## Token Expiration
* **API requests**: 5 minutes validity(advisable) based on the example above (`valid_until = now + 300`)
* Expired tokens are automatically rejected
## Security Best Practices
**Never hardcode API credentials:** - Always use environment variables or a
secrets management system - The API endpoint URL should be treated as
sensitive configuration - Store credentials securely and rotate them regularly
### Environment Configuration
Store your credentials securely:
```bash .env theme={null}
PAPERMAP_API_KEY_ID=your-api-key-id
PAPERMAP_SECRET_KEY=your-secret-key-never-share
PAPERMAP_API_URL=
```
**Obtaining Your Configuration:** - **API Credentials**: Available in your
Papermap dashboard under **Settings → API Keys** - **API Endpoint**: Available
in **Settings → API Configuration** - Always use the values provided in your
dashboard for your specific workspace
## Next Steps
Learn how to create and manage dashboards for your tenants
Generate secure tokens for embedding dashboards
# Backend Implementation
Source: https://docs.papermap.ai/documentation/multi-tenancy/backend
This guide provides an overview of implementing secure tenant dashboard management using HMAC signature authentication for enterprise-grade multi-tenant security.
## Architecture Overview
```
Your API (Tenant Management)
↓
HMAC Signed Request → Papermap Dashboard API
↓
Dashboard Created/Retrieved
↓
Generate Iframe Token (HMAC Signed)
↓
Frontend Embeds Dashboard
```
### Key Components
1. **TenantDashboard Model** - Maps tenants to Papermap dashboards
2. **HMAC Signature Service** - Securely authenticates API requests
3. **Dashboard Handler** - Creates dashboards and generates embed tokens
4. **Dashboard Router** - API endpoints for dashboard operations
## Quick Start
Follow these guides in order to implement the backend:
Implement HMAC signature authentication to securely communicate with the
Papermap API.
Learn how to implement HMAC-SHA256 signature authentication
Set up the ability to create and manage dashboards for your tenants.
Learn how to create dashboards via the Papermap API
Generate secure tokens to embed dashboards in your frontend.
Learn how to generate secure embed tokens
Create REST API endpoints for your frontend to interact with.
Example REST API endpoints for dashboard operations
Follow security best practices for production deployment.
Learn about security considerations and best practices
## Database Model
First, create a model to link your tenants to their Papermap dashboards:
It is not required to save it this way, but you need to have a way to map your tenant to their dashboards.
```python Python theme={null}
from sqlalchemy import Column, String
from .database import Base
class TenantDashboard(BaseModel):
__tablename__ = 'tenant_dashboards'
tenant_id = Column(String(255), nullable=False, index=True)
workspace_id = Column(String(255), nullable=False)
dashboard_id = Column(String(255), nullable=False)
```
```sql POSTGRESQL theme={null}
CREATE TABLE tenant_dashboards (
id SERIAL PRIMARY KEY,
tenant_id VARCHAR(255) NOT NULL,
workspace_id VARCHAR(255) NOT NULL,
dashboard_id VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX idx_tenant_id ON tenant_dashboards (tenant_id);
```
```sql MYSQL theme={null}
CREATE TABLE tenant_dashboards (
id INT AUTO_INCREMENT PRIMARY KEY,
tenant_id VARCHAR(255) NOT NULL,
workspace_id VARCHAR(255) NOT NULL,
dashboard_id VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
INDEX idx_tenant_id (tenant_id)
);
```
**Purpose**: Links your tenant to a Papermap dashboard ID for secure access and isolation.
## Prerequisites
Before implementing, ensure you have:
* Papermap API credentials (API Key ID and Secret Key)
* Your workspace ID
* API endpoint URL (obtain from your Papermap dashboard settings)
**Security Best Practices:** - Never hardcode API endpoints, keys, or secrets
in your code - Always use environment variables or a secrets management system
* The API endpoint URL should be treated as sensitive configuration - Store
credentials securely and rotate them regularly
## Environment Configuration
Store your credentials securely in environment variables:
```bash .env theme={null}
PAPERMAP_API_KEY_ID=your-api-key-id
PAPERMAP_SECRET_KEY=your-secret-key-never-share
PAPERMAP_API_URL=
```
**Obtaining Your Configuration:** - **API Credentials**: Available in your
Papermap dashboard under **Settings → API Keys** - **API Endpoint**: Available
in **Settings → API Configuration** - Always use the values provided in your
dashboard for your specific workspace
## Implementation Guides
Implement secure HMAC signature authentication
Create and manage dashboards for tenants
Generate secure embed tokens
Build REST API endpoints
Track per-tenant credit consumption
Security best practices
Performance and scalability tips
## Common Pattern Reference
The HMAC signature pattern for tenant dashboards follows this flow:
```
1. Create Payload
payload = workspace_id + valid_until
2. Generate Signature
signature = HMAC-SHA256(payload, secret_key)
3. Send Request with Headers
X-API-Key-ID:
X-Workspace-ID:
X-Valid-Until:
X-Signature:
4. Store Result
tenant_id → dashboard_id mapping
5. Generate Embed Token
Encode {tenant_id, dashboard_id, signature, expires} as base64
```
This pattern ensures secure, time-limited access to tenant-specific dashboards.
## Next Steps
Learn how to embed dashboards in your frontend application
# Best Practices
Source: https://docs.papermap.ai/documentation/multi-tenancy/best-practices
This guide covers security, performance, scalability, and troubleshooting best practices for production multi-tenant applications.
### Performance Optimization
1. **Cache tenant configurations**: Reduce API calls by caching tenant settings
2. **Use CDN for embeds**: Serve embedded dashboards through a CDN
3. **Implement lazy loading**: Load dashboards only when needed
4. **Monitor performance per tenant**: Track load times and API response times
### Security Best Practices
1. **Never expose API keys**: Always generate tokens server-side
2. **Implement CORS**: Restrict embed domains per tenant
3. **Use HTTPS everywhere**: Enforce secure connections
4. **Audit trail**: Log all tenant access and modifications
5. **Regular security audits**: Review tenant access patterns
### Scalability Considerations
1. **Database per tenant**: For large clients, consider dedicated databases
2. **Implement rate limiting**: Prevent resource exhaustion
3. **Queue background jobs**: Process tenant tasks asynchronously
4. **Monitor resource usage**: Alert on unusual patterns
5. **Plan for growth**: Design for 10x current tenant count
## Troubleshooting
### Common Issues
**1. Tenant data mixing**
* Verify workspace IDs are correct
* Check API key scoping
* Review query filters
**2. Branding not applying**
* Clear browser cache
* Verify branding configuration
* Check embed parameter syntax
**3. Performance degradation**
* Review tenant resource usage
* Implement query optimization
* Consider tenant database sharding
**4. Authentication failures**
* Verify API keys are active
* Check token expiration
* Review CORS configuration
### Debugging Multi-Tenant Issues
Enable debug mode in embeds:
```html theme={null}
```
Check browser console for detailed error messages and network requests.
## Migration Guide
### Moving from Single to Multi-Tenant
If you're migrating from a single-tenant to multi-tenant architecture:
1. **Audit current setup**: Document existing data sources and dashboards
2. **Plan tenant structure**: Decide how to split existing data
3. **Create tenant workspaces**: Set up workspaces for each tenant
4. **Migrate data**: Export and import data to appropriate tenants
5. **Update embed codes**: Replace single workspace with tenant-specific embeds
6. **Test thoroughly**: Verify data isolation and permissions
7. **Deploy gradually**: Roll out to tenants in phases
## Next Steps
* Read the [Embedding Guide](/documentation/embedding) for more on embedding
* Join our [Community Forum](https://discord.gg/BbjGm8jW) for discussions
* Contact [team@papermap.ai](mailto:team@papermap.ai) for enterprise guidance
***
*Ready to build a multi-tenant analytics platform? [Book a session](https://calendly.com/admin-pappermap/30min) and we will help you enable multi-tenancy.*
# Creating Dashboards
Source: https://docs.papermap.ai/documentation/multi-tenancy/creating-dashboards
This guide covers how to create dashboards for your tenants using the Papermap Dashboard API.
The `dashboardId` created through this flow can be used in both iframe
embedding and React component embedding with
[`@papermap/papermap`](/documentation/embedding/react-components).
## Prerequisites
Before implementing, ensure you have:
* Papermap API credentials (API Key ID and Secret Key)
* Your workspace ID
* API endpoint URL (obtain from your Papermap dashboard settings)
* HMAC authentication implemented (see [Authentication](/documentation/multi-tenancy/authentication))
## Database Model
First, you should have created a table in your database to store the mapping between your tenant and the
dashboard ID. See the [Database Model section in Backend
Implementation](/documentation/multi-tenancy/backend#database-model) for details.
**Purpose**: Links your tenant to a Papermap dashboard ID for secure access and isolation.
## Creating a Dashboard
The base URL for the Papermap API is `https://prod.dataapi.papermap.ai/`.
The `get_auth_headers` function is a helper function that generates the HMAC signature for the API request found
in the [HMAC Authentication](/documentation/multi-tenancy/authentication)
Create a dashboard via the Papermap API for each tenant:
```python Python theme={null}
import httpx
async def create_dashboard(
tenant_id: str,
workspace_id: str,
name: str,
description: Optional[str] = None,
created_by: Optional[str] = None
):
# 1. Call Papermap API with HMAC signature
headers = _get_auth_headers(workspace_id, API_KEY_ID, SECRET_KEY)
payload = {
"workspace_id": workspace_id,
"title": name,
"description": description
}
async with httpx.AsyncClient() as client:
response = await client.post(
f"{PAPERMAP_API_URL}/api/v1/external/dashboards",
headers=headers,
json=payload
)
external_dashboard = response.json()
dashboard_id = external_dashboard["data"]["data"]["dashboard_id"]
# 2. Store mapping in your database
tenant_dashboard = TenantDashboard.create(
session=db,
tenant_id=tenant_id,
workspace_id=workspace_id,
dashboard_id=dashboard_id,
created_by=created_by
)
return tenant_dashboard
```
```typescript TypeScript/Node.js theme={null}
import axios from "axios";
async function createDashboard(
tenantId: string,
workspaceId: string,
name: string,
description?: string
) {
const service = new DashboardAPIService({
apiKeyId: process.env.PAPERMAP_API_KEY_ID,
secretKey: process.env.PAPERMAP_SECRET_KEY,
workspaceId: workspaceId,
baseUrl: process.env.PAPERMAP_API_URL,
});
const headers = service.getAuthHeaders();
const response = await axios.post(
`${service.config.baseUrl}/api/v1/external/dashboards`,
{
workspace_id: workspaceId,
title: name,
description,
},
{ headers }
);
const dashboardId = response.data.data.dashboard_id;
// Store mapping in your database
await db.tenantDashboards.create({
tenant_id: tenantId,
workspace_id: workspaceId,
dashboard_id: dashboardId,
});
return { dashboardId, ...response.data };
}
```
```php PHP theme={null}
$workspaceId,
'title' => $name,
'description' => $description
];
$ch = curl_init(getenv('PAPERMAP_API_URL') . '/api/v1/external/dashboards');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
$headerArray = [];
foreach ($headers as $key => $value) {
$headerArray[] = "$key: $value";
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray);
$response = curl_exec($ch);
curl_close($ch);
$data = json_decode($response, true);
$dashboardId = $data['data']['data']['id'];
// Store mapping in your database
DB::table('tenant_dashboards')->insert([
'tenant_id' => $tenantId,
'workspace_id' => $workspaceId,
'dashboard_id' => $dashboardId
]);
return ['dashboard_id' => $dashboardId, 'data' => $data];
}
?>
```
```java Java theme={null}
public DashboardResponse createDashboard(
String workspaceId,
String name,
String description
) throws Exception {
HttpHeaders headers = getAuthHeaders(workspaceId);
Map payload = new HashMap<>();
payload.put("workspace_id", workspaceId);
payload.put("title", name);
payload.put("description", description);
HttpEntity
## Workflow Diagram
```
1. Client Request → POST /api/v1/dashboards
{
"tenant_id": "org-123",
"workspace_id": "workspace-456",
"name": "Sales Dashboard"
}
2. Your API → Generate HMAC Signature
payload = "workspace-456" + "1699999999"
signature = HMAC-SHA256(payload, secret_key)
3. Your API → Call Papermap Dashboard API
POST ${PAPERMAP_API_URL}/api/v1/external/dashboards
Headers:
X-API-Key-ID: your-api-key
X-Workspace-ID: workspace-456
X-Valid-Until: 1699999999
X-Signature: abc123...
4. Papermap API → Returns Dashboard
{data:... {data: {dashboard_id: "dashboard-789", ...}}}
5. Your API → Store Mapping in Database
TenantDashboard:
tenant_id: org-123
workspace_id: workspace-456
dashboard_id: dashboard-789
6. Return to Client
{ "success": true, "data": {...} }
```
## Key Considerations
### Tenant Isolation
Each tenant should have their own dashboard:
* One dashboard per tenant ensures data isolation
* Store the tenant-to-dashboard mapping in your database
* Verify tenant ownership before allowing access
### Dashboard Naming
Use clear, consistent naming conventions:
* Include tenant identifier in dashboard name
* Example: `"Dashboard - Acme Corp"` or `"Acme Corp Analytics"`
* Makes management easier in the Papermap admin panel
### Error Handling
Handle common errors gracefully:
```python theme={null}
try:
dashboard = await create_dashboard(tenant_id, workspace_id, name)
except httpx.HTTPStatusError as e:
if e.response.status_code == 401:
# Invalid credentials or expired signature
raise Exception("Authentication failed")
elif e.response.status_code == 409:
# Dashboard already exists
raise Exception("Dashboard already exists for this tenant")
else:
# Other errors
raise Exception(f"Failed to create dashboard: {e}")
```
## Next Steps
Learn how to generate secure embed tokens for your dashboards
Set up REST API endpoints for dashboard operations
# Iframe Embed Tokens
Source: https://docs.papermap.ai/documentation/multi-tenancy/iframe-tokens
This guide covers how to generate secure, time-limited tokens for embedding dashboards in your application.
This page is specifically about the multi-tenant iframe token flow. If you are
embedding Papermap through `@papermap/papermap`, see [React
Components](/documentation/embedding/react-components) for the component
integration flow and how it uses `workspaceId`, `dashboardId`, and backend
token generation.
## Overview
Iframe tokens allow you to securely embed Papermap dashboards in your application. Each token:
* Is signed with HMAC-SHA256 for security
* Has a configurable expiration time
* Is specific to a tenant and dashboard
* Can only be used for the specified dashboard
## Token Structure
The token contains:
* `api_key_id`: Your API key identifier
* `workspace_id`: Your workspace ID
* `tenant_id`: The tenant identifier
* `dashboard_id`: The specific dashboard ID
* `valid_until`: Unix timestamp when token expires
* `signature`: HMAC signature for verification
## Generating Iframe Tokens
This token generation is different from the one in the [Basic
Embedding](/documentation/embedding/basic-embedding#backend%3A-generating-embed-tokens) section. The token
generation in this section is for multi-tenant iframe embedding.
The tenant-aware `dashboardId` and backend provisioning model described here
can still be relevant when your application uses React components, but this
page documents the iframe-specific token flow.
```python Python theme={null}
import json
import base64
import time
def generate_iframe_token(
tenant_id: str,
workspace_id: str,
dashboard_id: str,
valid_until: Optional[int] = None
):
# 1. Get tenant's dashboard
tenant_dashboard = TenantDashboard.read(
session=db,
filter_by={"tenant_id": tenant_id}
)
if not tenant_dashboard:
raise Exception("Dashboard not found for tenant")
# 2. Set expiration (default 1 hour)
if valid_until is None:
valid_until = int(time.time()) + 3600
# 3. Create HMAC signature
payload = f"{workspace_id}{valid_until}"
signature = hmac.new(
SECRET_KEY.encode(),
payload.encode(),
hashlib.sha256
).hexdigest()
# 4. Encode token
token_data = {
"api_key_id": API_KEY_ID,
"workspace_id": workspace_id,
"tenant_id": tenant_id,
"dashboard_id": dashboard_id,
"valid_until": valid_until,
"signature": signature
}
token_json = json.dumps(token_data)
encoded_token = base64.urlsafe_b64encode(token_json.encode()).decode()
return {
"token": encoded_token,
"dashboard_id": dashboard_id,
"expires_at": valid_until
}
```
```typescript TypeScript/Node.js theme={null}
function generateIframeToken(
tenantId: string,
workspaceId: string,
dashboardId: string,
validUntil?: number
): string {
const expiresAt = validUntil || Math.floor(Date.now() / 1000) + 3600;
const validUntilStr = String(expiresAt);
const signature = this.createSignature(workspaceId, validUntilStr);
const tokenData = {
api_key_id: this.config.apiKeyId,
workspace_id: workspaceId,
tenant_id: tenantId,
dashboard_id: dashboardId,
valid_until: expiresAt,
signature,
};
return Buffer.from(JSON.stringify(tokenData)).toString("base64url");
}
// Express endpoint
app.post("/api/dashboards/iframe-token", authenticateUser, async (req, res) => {
const { tenantId, workspaceId, dashboardId } = req.body;
// Verify tenant belongs to user
if (req.user.tenantId !== tenantId) {
return res.status(403).json({ error: "Access denied" });
}
const token = generateIframeToken(tenantId, workspaceId, dashboardId);
res.json({ token, dashboard_id: dashboardId });
});
```
```php PHP theme={null}
getenv('PAPERMAP_API_KEY_ID'),
'workspace_id' => $workspaceId,
'tenant_id' => $tenantId,
'dashboard_id' => $dashboardId,
'valid_until' => $expiresAt,
'signature' => $signature
];
$token = base64_encode(json_encode($tokenData));
$token = str_replace(['+', '/', '='], ['-', '_', ''], $token);
return [
'token' => $token,
'dashboard_id' => $dashboardId,
'expires_at' => $expiresAt
];
}
?>
```
```java Java theme={null}
public String generateIframeToken(
String tenantId,
String workspaceId,
String dashboardId,
Long validUntil
) throws Exception {
if (validUntil == null) {
validUntil = Instant.now().getEpochSecond() + 3600;
}
String signature = createSignature(workspaceId, String.valueOf(validUntil));
Map tokenData = new HashMap<>();
tokenData.put("api_key_id", apiKeyId);
tokenData.put("workspace_id", workspaceId);
tokenData.put("tenant_id", tenantId);
tokenData.put("dashboard_id", dashboardId);
tokenData.put("valid_until", validUntil);
tokenData.put("signature", signature);
String json = objectMapper.writeValueAsString(tokenData);
return Base64.getUrlEncoder()
.withoutPadding()
.encodeToString(json.getBytes(StandardCharsets.UTF_8));
}
```
```csharp C# theme={null}
public string GenerateIframeToken(
string tenantId,
string workspaceId,
string dashboardId,
long? validUntil = null
)
{
var expiresAt = validUntil ?? DateTimeOffset.UtcNow.ToUnixTimeSeconds() + 3600;
var signature = CreateSignature(workspaceId, expiresAt.ToString());
var tokenData = new
{
api_key_id = _apiKeyId,
workspace_id = workspaceId,
tenant_id = tenantId,
dashboard_id = dashboardId,
valid_until = expiresAt,
signature
};
var json = JsonSerializer.Serialize(tokenData);
var bytes = Encoding.UTF8.GetBytes(json);
return Convert.ToBase64String(bytes)
.Replace('+', '-')
.Replace('/', '_')
.TrimEnd('=');
}
```
```go Go theme={null}
func (s *DashboardAPIService) GenerateIframeToken(
tenantID, workspaceID, dashboardID string,
validUntil *int64,
) (string, error) {
var expiresAt int64
if validUntil == nil {
expiresAt = time.Now().Unix() + 3600
} else {
expiresAt = *validUntil
}
signature := s.createSignature(
workspaceID,
fmt.Sprintf("%d", expiresAt),
)
tokenData := map[string]interface{}{
"api_key_id": s.APIKeyID,
"workspace_id": workspaceID,
"tenant_id": tenantID,
"dashboard_id": dashboardID,
"valid_until": expiresAt,
"signature": signature,
}
jsonData, _ := json.Marshal(tokenData)
encoded := base64.URLEncoding.EncodeToString(jsonData)
return strings.TrimRight(encoded, "="), nil
}
```
## Using the Token in Frontend
Once you have the token, embed the dashboard using an iframe:
```html theme={null}
```
### React Example
```tsx theme={null}
import React, { useState, useEffect } from "react";
function DashboardEmbed({ tenantId, workspaceId, dashboardId }) {
const [token, setToken] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
async function fetchToken() {
const response = await fetch("/api/dashboards/iframe-token", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ tenantId, workspaceId, dashboardId }),
});
const data = await response.json();
setToken(data.token);
setLoading(false);
}
fetchToken();
}, [tenantId, workspaceId, dashboardId]);
if (loading) return Loading dashboard...
;
return (
);
}
```
## Workflow Diagram
```
1. Client → Request Embed Token
POST /api/v1/dashboards/iframe-token
{
"tenant_id": "org-123",
"workspace_id": "workspace-456"
}
2. Your API → Generate Token
- Lookup dashboard_id for tenant
- Create HMAC signature
- Encode as base64 token
3. Return Token to Client
{
"token": "eyJhcGlfa2V5X2lkIjoi...",
"dashboard_id": "dashboard-789",
"expires_at": 1700000000
}
4. Frontend → Embed in Iframe
```
## Token Refresh
Since tokens expire, implement a refresh mechanism:
```typescript theme={null}
class DashboardTokenManager {
private token: string | null = null;
private expiresAt: number | null = null;
async getToken(tenantId: string, workspaceId: string, dashboardId: string) {
// Check if token is still valid (with 5 min buffer)
if (
this.token &&
this.expiresAt &&
this.expiresAt > Date.now() / 1000 + 300
) {
return this.token;
}
// Fetch new token
const response = await fetch("/api/dashboards/iframe-token", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ tenantId, workspaceId, dashboardId }),
});
const data = await response.json();
this.token = data.token;
this.expiresAt = data.expires_at;
return this.token;
}
}
```
## Security Considerations
**Always verify tenant ownership before generating tokens**
Never generate a token without verifying that the requesting user has access to the tenant's dashboard.
### Tenant Access Verification
```python Python theme={null}
# Good - Verify tenant access
if current_user["organization_id"] != tenant_id:
raise HTTPException(status_code=403, detail="Access denied")
# Then generate token
token = generate_iframe_token(tenant_id, workspace_id, dashboard_id)
```
```typescript TypeScript theme={null}
// Good - Verify tenant access
if (req.user.tenantId !== tenantId) {
return res.status(403).json({ error: "Access denied" });
}
// Then generate token
const token = generateIframeToken(tenantId, workspaceId, dashboardId);
```
```php PHP theme={null}
// Good - Verify tenant access
if (Auth::user()->tenant_id !== $tenantId) {
return response()->json(['error' => 'Access denied'], 403);
}
// Then generate token
$token = generateIframeToken($tenantId, $workspaceId, $dashboardId);
```
### Token Expiration
* Advisable: 1 hour (3600 seconds)
* Configurable based on your security requirements
* Shorter expiration = more secure, but requires more frequent refreshes
* Longer expiration = better UX, but higher security risk
### Best Practices
1. **Generate tokens on-demand**: Don't pre-generate and store tokens
2. **Use HTTPS**: Always serve your application over HTTPS
3. **Implement token refresh**: Refresh tokens before they expire
4. **Log token generation**: Monitor for unusual access patterns
5. **Rate limit**: Prevent abuse by rate limiting token generation
## Next Steps
Set up REST API endpoints for dashboard operations
Learn about security considerations for production
# Multi-Tenancy Example
Source: https://docs.papermap.ai/documentation/multi-tenancy/multitenancy-example
## Multi-Tenancy in Action
The video below demonstrates Papermap's multi-tenancy capabilities using a tailoring application with multiple tenants accessing embedded dashboards.
### Key Features Demonstrated
**Dashboard Customization**
Each tenant can personalize their embedded dashboard to match their specific business needs and preferences.
**Alan - Embedded AI Agent**
Tenants have access to Alan, an AI agent adept at data analysis. Alan helps users to:
* Query their data using natural language
* Gain deeper insights into business metrics
* Generate actionable recommendations
**Flexible Layout Management**
Tenants can reorder dashboard components by dragging and dropping to create their preferred view.
**Dynamic Component Creation**
Based on query results from Alan, tenants can create new dashboard components directly from their insights, turning ad-hoc analysis into permanent visualizations. Tenants also have the ablitity to auto-generate dashboard components.
# Multi-Tenancy Overview
Source: https://docs.papermap.ai/documentation/multi-tenancy/overview
Papermap's multi-tenancy feature enables you to serve multiple customers, clients, or organizations from a single Papermap instance while maintaining complete data isolation and customization for each tenant.
## Overview
Multi-tenancy in Papermap allows you to:
* **Serve multiple clients** from a single Papermap account
* **Isolate data** completely between different tenants
* **Customize branding** and theming per tenant
* **Manage permissions** at the tenant level
* **Scale efficiently** without managing separate instances
* **Control features** and access rights per tenant
* **Track usage** per tenant for billing and analytics
## What is Multi-Tenancy?
Multi-tenancy is an architecture where a single instance of Papermap serves multiple independent customers (tenants). Each tenant's data, users, and configurations are logically isolated, even though they share the same underlying infrastructure.
## Use Cases
Offer white-labeled analytics to your customers
* Embed Papermap dashboards in your application with your branding
* Each customer sees only their own data
* Centralized management of all customer analytics
Manage multiple client dashboards
* Create separate workspaces for each client
* Maintain consistent reporting across clients
* Scale your analytics offering efficiently
Department or regional separation
* Isolate data between business units
* Maintain compliance and governance
* Provide self-service analytics to different teams
Build analytics products on Papermap
* Create value-added analytics solutions
* Manage customer subscriptions programmatically
* White-label Papermap under your brand
## Architecture
### Tenant Isolation Model
Papermap uses dashboard-based tenant isolation within a single workspace:
```
Your Papermap Account
└── Workspace (ID: workspace-123)
├── Data Sources (with tenant table configured)
├── API Keys & Secrets
└── Dashboards
├── Dashboard A (Tenant: org-abc) → Filters to tenant_id = 'org-abc'
├── Dashboard B (Tenant: org-def) → Filters to tenant_id = 'org-def'
└── Dashboard C (Tenant: org-xyz) → Filters to tenant_id = 'org-xyz'
```
**How it works:**
* **One Workspace** - Your application has a single Papermap workspace
* **Multiple Dashboards** - Each tenant gets their own dashboard within that workspace
* **Automatic Filtering** - Each dashboard is automatically filtered to show only that tenant's data
* **Tenant Table** - You configure which table identifies tenants (e.g., `customers`, `organizations`)
* **Data Isolation** - Queries are automatically scoped to the tenant associated with each dashboard
### Database Structure
Your database should have a tenant identifier table and related tables:
```
Database
├── organizations (tenant table)
│ ├── id (tenant identifier)
│ ├── name
│ └── ...
├── users (direct table - has org_id)
│ ├── id
│ ├── org_id → organizations.id
│ └── ...
├── orders (direct table - has org_id)
│ ├── id
│ ├── org_id → organizations.id
│ └── ...
└── order_items (indirect table - via orders)
├── id
├── order_id → orders.id
└── ...
```
When you configure multi-tenancy:
1. Select `organizations` as your tenant table
2. Papermap automatically identifies relationships
3. Create separate dashboards for each tenant
4. Each dashboard only shows data for that tenant
## Data Isolation
Papermap ensures complete data isolation between tenants:
* **Separate databases**: Each workspace can connect to different databases
* **Query isolation**: All queries are scoped to the workspace
* **User separation**: Users can only access their assigned workspaces
* **API key scoping**: API keys only work for their associated workspace
## Next Steps
Configure multi-tenancy in your Papermap workspace
Implement secure tenant dashboard management with HMAC authentication
Track per-tenant credit consumption and API usage
Security, scaling, and troubleshooting guidance
# Security Best Practices
Source: https://docs.papermap.ai/documentation/multi-tenancy/security
This guide covers security considerations and best practices for implementing multi-tenant dashboards in production.
## HMAC Signature Verification
### How Verification Works
The Papermap API verifies requests by:
1. Extracting `workspace_id` and `valid_until` from headers
2. Computing signature: `HMAC-SHA256(workspace_id + valid_until, secret_key)`
3. Comparing computed signature with provided `X-Signature`
4. Checking `valid_until` hasn't expired
If the signature doesn't match or the timestamp has expired, the request is
rejected with a 401 Unauthorized error.
### Signature Pattern
```
1. Create Payload
payload = workspace_id + valid_until
2. Generate Signature
signature = HMAC-SHA256(payload, secret_key)
3. Send Request with Headers
X-API-Key-ID:
X-Workspace-ID:
X-Valid-Until:
X-Signature:
4. Papermap Verifies
- Recomputes signature with same payload
- Compares with provided signature
- Checks timestamp hasn't expired
```
## Token Expiration
### Papermap API Requests
* **Duration**: 5 minutes vallidity advisable
* **Configuration**: `valid_until = now + 300`
* **Purpose**: Short-lived to prevent replay attacks
### Iframe Tokens
* **Duration**: 1 hour validity (configurable)
* **Configuration**: `valid_until = now + 3600`
* **Purpose**: Long enough for user sessions, short enough for security
### Expired Token Handling
Expired tokens are automatically rejected by Papermap API:
```json theme={null}
{
"error": "Token expired",
"code": "TOKEN_EXPIRED",
"status": 401
}
```
Implement automatic token refresh in your frontend to handle expiration gracefully.
## Secret Key Management
**Never commit secrets to version control!**
Use environment variables or a secrets management service like:
* AWS Secrets Manager
* HashiCorp Vault
* Azure Key Vault
* Google Cloud Secret Manager
### Environment Variables
Store credentials securely in environment variables:
```bash .env theme={null}
PAPERMAP_API_KEY_ID=your-api-key-id
PAPERMAP_SECRET_KEY=your-secret-key-never-share
PAPERMAP_API_URL=
```
**Obtaining Your Configuration:** - **API Credentials**: Available in your
Papermap dashboard under **Settings → API Keys** - **API Endpoint**: Available
in **Settings → API Configuration** - Always use the values provided in your
dashboard for your specific workspace
### Key Rotation
Regularly rotate your API keys:
1. Generate new API key in Papermap dashboard
2. Update environment variables in your application
3. Deploy updated configuration
4. Revoke old API key after confirming new one works
**Recommended rotation schedule**: Every 90 days or immediately if compromised
## Tenant Isolation
### Always Verify Tenant Access
Never generate tokens or retrieve dashboards without verifying the user has access to the tenant:
```python Python theme={null}
# ✅ Good - Verify tenant access
if current_user["organization_id"] != tenant_id:
raise HTTPException(status_code=403, detail="Access denied")
# Then generate token
token = generate_iframe_token(tenant_id, workspace_id, dashboard_id)
# ❌ Bad - No verification
token = generate_iframe_token(tenant_id, workspace_id, dashboard_id)
```
```typescript TypeScript theme={null}
// ✅ Good - Verify tenant access
if (req.user.tenantId !== tenantId) {
return res.status(403).json({ error: "Access denied" });
}
// Then generate token
const token = generateIframeToken(tenantId, workspaceId, dashboardId);
// ❌ Bad - No verification
const token = generateIframeToken(tenantId, workspaceId, dashboardId);
```
```php PHP theme={null}
// ✅ Good - Verify tenant access
if (Auth::user()->tenant_id !== $tenantId) {
return response()->json(['error' => 'Access denied'], 403);
}
// Then generate token
$token = generateIframeToken($tenantId, $workspaceId, $dashboardId);
// ❌ Bad - No verification
$token = generateIframeToken($tenantId, $workspaceId, $dashboardId);
```
### Database-Level Isolation
Ensure your database queries respect tenant boundaries:
```python theme={null}
# ✅ Good - Filter by tenant
dashboard = db.query(TenantDashboard).filter_by(
tenant_id=tenant_id,
organization_id=current_user.organization_id
).first()
# ❌ Bad - No tenant filter
dashboard = db.query(TenantDashboard).filter_by(
dashboard_id=dashboard_id
).first()
```
## HTTPS and Transport Security
**Always use HTTPS in production**
HTTP traffic can be intercepted, exposing your API keys and tokens.
### Force HTTPS
```python Python (FastAPI) theme={null}
from fastapi.middleware.httpsredirect import HTTPSRedirectMiddleware
app.add_middleware(HTTPSRedirectMiddleware)
```
```typescript TypeScript (Express) theme={null}
function forceHTTPS(req, res, next) {
if (req.headers["x-forwarded-proto"] !== "https") {
return res.redirect(301, `https://${req.hostname}${req.url}`);
}
next();
}
app.use(forceHTTPS);
```
### CORS Configuration
Configure CORS properly to prevent unauthorized domains from accessing your API:
```python Python (FastAPI) theme={null}
from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=["https://yourdomain.com"], # Specific domains only
allow_credentials=True,
allow_methods=["GET", "POST"],
allow_headers=["Authorization", "Content-Type"],
)
```
```typescript TypeScript (Express) theme={null}
import cors from "cors";
app.use(
cors({
origin: "https://yourdomain.com", // Specific domain only
credentials: true,
methods: ["GET", "POST"],
allowedHeaders: ["Authorization", "Content-Type"],
})
);
```
## Monitoring Alerts
Set up alerts for suspicious activity:
* Multiple failed authentication attempts
* Unusual number of token generation requests
* Access attempts from unexpected IP addresses
* Expired token usage attempts
## Security Checklist
Use this checklist before going to production:
API keys stored in environment variables (not in code)
HTTPS enforced on all endpoints
Tenant access verification on all endpoints
JWT tokens have proper expiration
Monitoring and alerts configured
Key rotation schedule established
Error messages don't expose sensitive info
API endpoint URL treated as sensitive
## Common Vulnerability to Avoid
### 1. Signature Replay Attacks
The `valid_until` timestamp prevents replay attacks. Never:
* Reuse old signatures
* Set very long expiration times for API requests
* Remove timestamp validation
## Next Steps
Learn about performance optimization and scalability
Deep dive into HMAC authentication
# Multi-Tenancy Setup
Source: https://docs.papermap.ai/documentation/multi-tenancy/setup
Step-by-step guide to configure multi-tenancy in your Papermap workspace, including tenant table selection and API key generation. This guide walks you through configuring multi-tenancy in your Papermap workspace. Follow these steps to set up tenant isolation and data access controls.
## Prerequisites
Before you begin, ensure you have:
* A Papermap account with workspace access
* Connected data sources with tenant-identifiable tables
* Administrative permissions in your workspace
## Configuration Steps
### Step 1: Access Workspace Settings
Navigate to [papermap.ai](https://www.papermap.ai) and sign in with your credentials.
Select the workspace where you want to enable multi-tenancy.
Click on **Settings** in the drop-down options on the workspace card to access workspace configuration.
In the settings editor, find **Multi-Tenant** on the sidebar and click it to open the configuration page and then click the **Get Started** button.
### Step 2: Select Your Tenant Table
The tenant table is the core table that identifies and separates your different tenants. This could be a `customers`, `organizations`, or `users` table - depending on your data model.
In the Multi-Tenant configuration page, you'll see a list of available tables from your connected data sources.
Find the table you want to use as your tenant identifier (e.g., `customers`, `organizations`, `users`).
Click **Use as Tenant** on your chosen table.
In this example, we're using the `organization` table as our tenant identifier.
### Step 3: Understand and Organize Your Tables
You will be redirected to the **Tenant Table Configuration** page. Papermap automatically analyzes your schema and sorts every table into one of three categories based on how it relates to the tenant table.
At the top of the page you'll find:
* **Tenant identifier column** — the column on the tenant table (usually the primary key) that the tenant id from API requests will be compared against.
* **Re-run Analysis** — re-runs the auto-categorization. Use this after schema changes.
* **Enabled** toggle — turns multi-tenant enforcement on or off for this workspace.
#### Table Categories Explained
Tables whose rows are filtered to the active tenant on every query.
Papermap fills this category in two ways:
* **Direct filter** — the table contains a column that points to the tenant table (e.g. `tailor.organizationid`). Filtering is applied directly.
* **Join path** — the table has no direct tenant column, so a chain of joins is used to reach the tenant id. You define this chain using the path builder (see Step 4).
**Examples:** user accounts, orders, transactions, dashboards, anything tenant-owned.
Tables that can be read by every tenant without filtering.
**Examples:**
* Product catalogs
* Country / region reference data
* System configuration
* Lookup tables
Tables that cannot be queried at all in tenant mode.
**Examples:**
* Auth tables (`users`, `sso_providers`, `mfa_factors`, `refresh_tokens`)
* Audit logs and system metadata
* Internal admin or billing tables
#### Organize Your Tables
Review the auto-categorization and adjust anything that doesn't match your security requirements.
Check which tables Papermap placed in **Tenant Data**, **Shared Data**, and **Blocked Data**.
Drag and drop tables between the three columns to override the automatic placement.
Move anything tenants should never see (admin tables, audit logs, billing) into **Blocked Data**.
Put catalogs, lookups, and reference tables into **Shared Data** so they remain readable across tenants.
Click **Save Tenant Policies** at the bottom of the page.
**Quick Reference:**
* **Tenant Data**: any table with tenant-owned rows — direct foreign key or reachable via a join path
* **Shared Data**: product catalogs, country/region reference data, lookups
* **Blocked Data**: auth tables, audit logs, system metadata, billing
In this example, business tables sit in **Tenant Data** while auth and system tables are auto-placed in **Blocked Data**.
### Step 4: Define a Tenant Access Path (when needed)
Some tables in **Tenant Data** don't contain the tenant id directly. For these, you need to tell Papermap how to reach the tenant id by joining through one or more other tables.
On the table card in **Tenant Data**, click the join/path icon in the top-right corner. The **Tenant Access Path** modal opens.
Set the four fields under **Join 1**:
* **Starting table for this join** — the table you're configuring.
* **Table it joins to** — the next table in the path toward the tenant table.
* **Column on \** — the column on the starting table used for the join.
* **Matching column on the joined table** — the column on the joined table that matches.
Click **+ Add Join Table** for multi-hop paths (e.g. `order_items` → `orders` → `organization`). Repeat the four fields for each hop.
Under **Tenant id location**, choose the table and column at the end of the path that hold the actual tenant id.
Click **Save Path**. The card now shows the resolved filter rule.
Use the path builder only when auto-analysis cannot infer a path. Tables with a direct foreign key to the tenant table are detected automatically and need no join configuration.
### Step 5: Create API Keys
After organizing your tables, create API keys for tenant access.
Click **Configure as Tenant Table** to save your table organization.
Go back to **Settings** → **API Keys**.
Click **Create API Key** to generate credentials.
Copy and securely store both the **API Key** and **Secret**.
**Important:** Save both the API Key and Secret securely. The Secret will only be shown once and cannot be retrieved later. Store it in a secure location like a password manager or secrets management system.
### Step 6: Complete Configuration
Your multi-tenancy setup is now complete!
## What Happens Next?
Once configured, your multi-tenant environment will operate as follows:
Each tenant only sees rows from **Tenant Data** tables that belong to them — whether filtered by a direct column or resolved through a join path.
**Shared Data** tables remain accessible to all tenants for common reference data.
**Blocked Data** tables are completely hidden from tenant queries.
Queries are automatically scoped to the tenant context.
## Next Steps
Implement secure tenant dashboard management with HMAC authentication
Learn how to manage tenant lifecycles and operations
## Troubleshooting Setup
* Ensure your data source is properly connected
* Verify the table exists and has the expected schema
* Check that you have read permissions on the table
* Verify foreign key relationships in your database
* Manually move tables to the correct categories
* Check table relationships in your data source
* Ensure you have administrative permissions
* Check that you saved the tenant table configuration first
* Try refreshing the page and generating again
# Tenant Usage Tracking
Source: https://docs.papermap.ai/documentation/multi-tenancy/tenant-usage
Track per-tenant credit consumption and API usage to understand how each tenant utilizes your Papermap integration. This feature enables transparent billing, usage analytics, and resource monitoring.
## Overview
When using API key authentication with the `X-Tenant-ID` header, Papermap automatically tracks:
* **Credits consumed** per tenant per billing period
* **Request count** per tenant per billing period
* **Monthly aggregation** with automatic period bucketing
This allows workspace owners to see which tenants are consuming credits and resources.
## How It Works
```
API Request with X-Tenant-ID header
↓
Papermap processes request
↓
Credits consumed from workspace quota
↓
Usage attributed to tenant (monthly bucket)
↓
Query usage via API endpoints
```
### Billing Period
Usage is automatically bucketed by calendar month:
* **Period Start**: First day of month (e.g., 2025-01-01 00:00:00)
* **Period End**: Last day of month (e.g., 2025-01-31 23:59:59)
Each unique tenant gets a separate usage record per month.
## API Endpoints
The base URL for the Papermap API is `https://prod.dataapi.papermap.ai/`.
### Get Workspace Tenant Usage
Retrieve usage data for all tenants in a workspace.
**Request:**
```bash theme={null}
GET /api/v1/external/workspaces/{workspace_id}/tenant-usage
Authorization:
```
**Query Parameters:**
| Parameter | Type | Required | Description |
| ------------- | ------- | -------- | -------------------------------------- |
| `from_period` | string | No | Start period filter (YYYY-MM format) |
| `to_period` | string | No | End period filter (YYYY-MM format) |
| `page` | integer | No | Page number (default: 1) |
| `per_page` | integer | No | Items per page (default: 50, max: 100) |
**Example Request:**
```bash theme={null}
curl -X GET "${PAPERMAP_API_URL}/api/v1/external/workspaces/ws-123/tenant-usage?from_period=2025-01&to_period=2025-12&page=1&per_page=20" \
-H "X-API-Key-ID: your-api-key-id" \
-H "X-Workspace-ID: ws-123" \
-H "X-Valid-Until: 1735689600" \
-H "X-Signature: "
```
**Response:**
```json theme={null}
{
"success": true,
"message": "Tenant usage retrieved successfully",
"data": {
"workspace_id": "ws-123",
"usage": [
{
"tenant_id": "tenant-abc",
"period": "2025-01",
"period_start": "2025-01-01T00:00:00",
"period_end": "2025-01-31T23:59:59",
"credits_used": 1500,
"request_count": 450
},
{
"tenant_id": "tenant-xyz",
"period": "2025-01",
"period_start": "2025-01-01T00:00:00",
"period_end": "2025-01-31T23:59:59",
"credits_used": 800,
"request_count": 200
}
],
"total_records": 2,
"total_pages": 1
}
}
```
### Get Tenant Usage History
Retrieve usage history for a specific tenant.
**Request:**
```bash theme={null}
GET /api/v1/external/workspaces/{workspace_id}/tenant-usage/{tenant_id}
Authorization:
```
**Query Parameters:**
| Parameter | Type | Required | Description |
| ------------- | ------- | -------- | -------------------------------------- |
| `from_period` | string | No | Start period filter (YYYY-MM format) |
| `to_period` | string | No | End period filter (YYYY-MM format) |
| `page` | integer | No | Page number (default: 1) |
| `per_page` | integer | No | Items per page (default: 50, max: 100) |
**Example Request:**
```bash theme={null}
curl -X GET "${PAPERMAP_API_URL}/api/v1/external/workspaces/ws-123/tenant-usage/tenant-abc?from_period=2024-06&to_period=2025-01" \
-H "X-API-Key-ID: your-api-key-id" \
-H "X-Workspace-ID: ws-123" \
-H "X-Valid-Until: 1735689600" \
-H "X-Signature: "
```
**Response:**
```json theme={null}
{
"success": true,
"message": "Tenant usage history retrieved successfully",
"data": {
"workspace_id": "ws-123",
"tenant_id": "tenant-abc",
"usage": [
{
"tenant_id": "tenant-abc",
"period": "2024-12",
"period_start": "2024-12-01T00:00:00",
"period_end": "2024-12-31T23:59:59",
"credits_used": 2100,
"request_count": 630
},
{
"tenant_id": "tenant-abc",
"period": "2025-01",
"period_start": "2025-01-01T00:00:00",
"period_end": "2025-01-31T23:59:59",
"credits_used": 1500,
"request_count": 450
}
],
"total_records": 2,
"total_pages": 1
}
}
```
## Authentication
These endpoints use the same HMAC signature authentication as other external API endpoints. See the [Authentication Guide](/documentation/multi-tenancy/authentication) for details.
Required headers:
* `X-API-Key-ID`: Your API key identifier
* `X-Workspace-ID`: Your workspace ID
* `X-Valid-Until`: Unix timestamp for request expiration
* `X-Signature`: HMAC-SHA256 signature
## Implementation Examples
The `_get_auth_headers` function is a helper function that generates the HMAC signature for the API request found
in the [HMAC Authentication](/documentation/multi-tenancy/authentication) guide.
```python Python theme={null}
import httpx
from typing import Optional
async def get_tenant_usage(
workspace_id: str,
from_period: Optional[str] = None,
to_period: Optional[str] = None,
page: int = 1,
per_page: int = 50
):
headers = _get_auth_headers(workspace_id, API_KEY_ID, SECRET_KEY)
params = {"page": page, "per_page": per_page}
if from_period:
params["from_period"] = from_period
if to_period:
params["to_period"] = to_period
async with httpx.AsyncClient() as client:
response = await client.get(
f"{PAPERMAP_API_URL}/api/v1/external/workspaces/{workspace_id}/tenant-usage",
headers=headers,
params=params
)
return response.json()
# Example usage
usage = await get_tenant_usage("ws-123", from_period="2025-01", to_period="2025-12")
for item in usage["data"]["usage"]:
print(f"Tenant {item['tenant_id']}: {item['credits_used']} credits")
```
```typescript TypeScript/Node.js theme={null}
import axios from "axios";
interface TenantUsageItem {
tenant_id: string;
period: string;
period_start: string;
period_end: string;
credits_used: number;
request_count: number;
}
async function getTenantUsage(
workspaceId: string,
fromPeriod?: string,
toPeriod?: string,
page: number = 1,
perPage: number = 50
): Promise {
const service = new DashboardAPIService({
apiKeyId: process.env.PAPERMAP_API_KEY_ID,
secretKey: process.env.PAPERMAP_SECRET_KEY,
workspaceId: workspaceId,
baseUrl: process.env.PAPERMAP_API_URL,
});
const headers = service.getAuthHeaders();
const params: Record = {
page: page.toString(),
per_page: perPage.toString(),
};
if (fromPeriod) params.from_period = fromPeriod;
if (toPeriod) params.to_period = toPeriod;
const response = await axios.get(
`${service.config.baseUrl}/api/v1/external/workspaces/${workspaceId}/tenant-usage`,
{ headers, params }
);
return response.data.data.usage;
}
// Example usage
const usage = await getTenantUsage("ws-123", "2025-01", "2025-12");
usage.forEach((item) => {
console.log(`Tenant ${item.tenant_id}: ${item.credits_used} credits`);
});
```
```php PHP theme={null}
$page, 'per_page' => $perPage];
if ($fromPeriod) $params['from_period'] = $fromPeriod;
if ($toPeriod) $params['to_period'] = $toPeriod;
$url = getenv('PAPERMAP_API_URL')
. '/api/v1/external/workspaces/' . $workspaceId . '/tenant-usage?'
. http_build_query($params);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$headerArray = [];
foreach ($headers as $key => $value) {
$headerArray[] = "$key: $value";
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray);
$response = curl_exec($ch);
curl_close($ch);
return json_decode($response, true);
}
// Example usage
$usage = getTenantUsage('ws-123', '2025-01', '2025-12');
foreach ($usage['data']['usage'] as $item) {
echo "Tenant {$item['tenant_id']}: {$item['credits_used']} credits\n";
}
?>
```
```java Java theme={null}
public TenantUsageResponse getTenantUsage(
String workspaceId,
String fromPeriod,
String toPeriod,
int page,
int perPage
) throws Exception {
HttpHeaders headers = getAuthHeaders(workspaceId);
UriComponentsBuilder builder = UriComponentsBuilder
.fromHttpUrl(baseUrl + "/api/v1/external/workspaces/" + workspaceId + "/tenant-usage")
.queryParam("page", page)
.queryParam("per_page", perPage);
if (fromPeriod != null) builder.queryParam("from_period", fromPeriod);
if (toPeriod != null) builder.queryParam("to_period", toPeriod);
HttpEntity request = new HttpEntity<>(headers);
ResponseEntity response = restTemplate.exchange(
builder.toUriString(),
HttpMethod.GET,
request,
TenantUsageResponse.class
);
return response.getBody();
}
```
```csharp C# theme={null}
public async Task GetTenantUsage(
string workspaceId,
string fromPeriod = null,
string toPeriod = null,
int page = 1,
int perPage = 50
)
{
var headers = GetAuthHeaders(workspaceId);
var queryParams = new List
{
$"page={page}",
$"per_page={perPage}"
};
if (!string.IsNullOrEmpty(fromPeriod))
queryParams.Add($"from_period={fromPeriod}");
if (!string.IsNullOrEmpty(toPeriod))
queryParams.Add($"to_period={toPeriod}");
var url = $"{_baseUrl}/api/v1/external/workspaces/{workspaceId}/tenant-usage?{string.Join("&", queryParams)}";
var request = new HttpRequestMessage(HttpMethod.Get, url);
foreach (var header in headers)
{
request.Headers.Add(header.Key, header.Value);
}
var response = await _httpClient.SendAsync(request);
var content = await response.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize(content);
}
```
```go Go theme={null}
func (s *DashboardAPIService) GetTenantUsage(
workspaceID string,
fromPeriod string,
toPeriod string,
page int,
perPage int,
) (*TenantUsageResponse, error) {
headers := s.getAuthHeaders(workspaceID)
url := fmt.Sprintf(
"%s/api/v1/external/workspaces/%s/tenant-usage?page=%d&per_page=%d",
s.BaseURL, workspaceID, page, perPage,
)
if fromPeriod != "" {
url += "&from_period=" + fromPeriod
}
if toPeriod != "" {
url += "&to_period=" + toPeriod
}
req, _ := http.NewRequest("GET", url, nil)
for key, value := range headers {
req.Header.Set(key, value)
}
resp, err := s.Client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var result TenantUsageResponse
json.NewDecoder(resp.Body).Decode(&result)
return &result, nil
}
```
## Use Cases
Generate per-tenant invoices based on actual usage
* Query usage for billing period
* Calculate costs based on credits consumed
* Automate invoice generation
Monitor tenant consumption patterns
* Identify high-usage tenants
* Track usage trends over time
* Plan capacity accordingly
Implement tenant-level quotas
* Compare usage against limits
* Send usage warnings
* Enforce rate limits per tenant
Attribute costs to business units
* Track departmental usage
* Chargeback reporting
* Budget planning
## Response Fields
| Field | Type | Description |
| --------------- | -------- | ----------------------------------------------- |
| `tenant_id` | string | The tenant identifier from `X-Tenant-ID` header |
| `period` | string | Billing period in YYYY-MM format |
| `period_start` | datetime | Start of the billing period |
| `period_end` | datetime | End of the billing period |
| `credits_used` | integer | Total credits consumed in this period |
| `request_count` | integer | Total API requests made in this period |
| `total_records` | integer | Total number of usage records (for pagination) |
| `total_pages` | integer | Total number of pages available |
## Error Responses
| Status | Error | Description |
| ------ | --------------------- | ------------------------------------ |
| 400 | Invalid period format | Period must be in YYYY-MM format |
| 401 | Unauthorized | Invalid or missing authentication |
| 403 | Access denied | No access to the specified workspace |
| 404 | Not found | Workspace or tenant not found |
**Example Error Response:**
```json theme={null}
{
"success": false,
"message": "Invalid from_period format. Use YYYY-MM",
"data": null
}
```
## Next Steps
Learn how to authenticate API requests
Explore other available API endpoints
# TUI Authentication
Source: https://docs.papermap.ai/documentation/tui/authentication
Sign in to Papermap TUI, understand browser login, credential storage, logout, and session behavior.
Authenticate before launching the TUI. Once signed in, `papermap` restores your session automatically and refreshes tokens when possible.
## Sign in
```bash theme={null}
papermap auth login
```
The default login flow opens Papermap in your browser. After you authenticate, the web app sends a short-lived one-time CLI code back to a local callback server running on `127.0.0.1`. The TUI exchanges that code for normal credentials and stores them locally.
Browser login does not put `access_token` or `refresh_token` values in the browser URL. Only the short-lived CLI code returns through the localhost callback.
## Browser login flow
Run `papermap auth login`. The TUI starts a temporary localhost callback server and opens the Papermap login page.
Sign in with your normal Papermap account. The browser preserves the CLI callback URL and a random state value.
Papermap redirects the browser to the local callback with a one-time code. The TUI validates state before exchanging the code.
The TUI saves credentials using the local credential store, warms the workspace cache, and prints the signed-in user.
## Login flags
```bash Browser theme={null}
papermap auth login
papermap auth login --browser
```
```bash Password theme={null}
papermap auth login --password
papermap auth login --password --email you@example.com
```
```bash URLs theme={null}
papermap auth login \
--api-url https://prod.dataapi.papermap.ai \
--frontend-url https://papermap.ai
```
Use password login when a browser cannot be opened, such as SSH-only or headless environments.
## Check current user
```bash theme={null}
papermap auth whoami
# Shortcut
papermap --user
papermap -u
```
If no valid credentials exist, Papermap asks you to run `papermap auth login`.
## Sign out
```bash theme={null}
papermap auth logout
```
Logout clears stored credentials and the local workspace cache.
```text theme={null}
~/.papermap/workspaces.json
```
The deprecated `papermap logout` alias still works, but `papermap auth logout` is the preferred command.
## Credential storage
Papermap uses the operating system keyring when available. If no supported keyring backend is available, the TUI falls back to a local credential file.
```text theme={null}
~/.papermap/credentials
```
The file fallback is written with `0600` permissions so only your user can read it.
Do not commit files from `~/.papermap`. They may contain local session data, workspace cache data, and machine-specific configuration.
## Force file storage
Set this environment variable when you need to bypass the OS keyring, usually for CI, containers, or controlled headless environments.
```bash theme={null}
PAPERMAP_FORCE_FILE_STORE=1 papermap auth login
```
## Custom frontend safety
Browser login only allows `https://papermap.ai` and `https://www.papermap.ai` by default. Internal or development frontends require an explicit opt-in.
```bash theme={null}
PAPERMAP_ALLOW_UNTRUSTED_FRONTEND=1 \
papermap auth login --frontend-url https://internal-frontend.example
```
Only use `PAPERMAP_ALLOW_UNTRUSTED_FRONTEND=1` with frontends you control. It relaxes the default production-host safety check for browser login.
## Session expiration
The TUI checks token expiry before API calls and attempts refresh when possible. If refresh fails, it clears the current app state and sends you back to the signed-out landing message.
Run login again:
```bash theme={null}
papermap auth login
```
## Next steps
Learn the active screens, keyboard controls, and command palette.
Set defaults for API URL, frontend URL, thinking traces, selected model, and shell behavior.
# TUI Configuration
Source: https://docs.papermap.ai/documentation/tui/configuration
Configure Papermap TUI API URLs, frontend login URL, thinking traces, selected model, and shell behavior.
Papermap loads configuration from `~/.papermap/config.yaml`. Built-in defaults are used when the file or a setting is missing.
## Config file
```yaml theme={null}
api_url: https://prod.dataapi.papermap.ai
frontend_url: https://papermap.ai
selected_model: gpt-5.4-mini
show_thinking: false
shell:
windows: pwsh
```
You only need to set values you want to override. Defaults are enough for normal production usage.
## Settings
| Setting | Config key | Default | Purpose |
| -------------- | ---------------- | ---------------------------------- | ---------------------------------------- |
| API URL | `api_url` | `https://prod.dataapi.papermap.ai` | Papermap Data API base URL |
| Frontend URL | `frontend_url` | `https://papermap.ai` | Browser login web app base URL |
| Selected model | `selected_model` | Backend default | Model slug used for insight requests |
| Show thinking | `show_thinking` | `false` | Whether reasoning traces show by default |
| Windows shell | `shell.windows` | `pwsh` | Shell used by TUI `!` mode on Windows |
## CLI overrides
Use flags for one-off runs. Flags do not permanently rewrite `config.yaml`.
```bash Launch theme={null}
papermap --api-url https://prod.dataapi.papermap.ai
```
```bash Login theme={null}
papermap auth login \
--api-url https://prod.dataapi.papermap.ai \
--frontend-url https://papermap.ai
```
```bash Workspaces theme={null}
papermap workspace list --api-url https://prod.dataapi.papermap.ai
papermap workspace create --api-url https://prod.dataapi.papermap.ai
```
## Thinking traces
Set `show_thinking: true` if you want reasoning and tool traces visible by default.
```yaml theme={null}
show_thinking: true
```
You can still toggle traces during a session with `Ctrl+T`.
## Selected model
Papermap persists the model you choose through the model picker or `Tab` cycling.
```yaml theme={null}
selected_model: gpt-5.4-mini
```
If the selected model is empty, unavailable, or removed from your account, the TUI falls back to the backend default.
## Frontend URL safety
Browser login only trusts Papermap production hosts by default.
Allowed without extra configuration:
```text theme={null}
https://papermap.ai
https://www.papermap.ai
```
For internal or development frontends, opt in explicitly:
```bash theme={null}
PAPERMAP_ALLOW_UNTRUSTED_FRONTEND=1 \
papermap auth login --frontend-url https://internal-frontend.example
```
Only enable untrusted frontends for environments you control. This bypasses the default browser-login host allowlist.
## Credential-store environment
Force file-backed credential storage when keyring access is unavailable or undesirable.
```bash theme={null}
PAPERMAP_FORCE_FILE_STORE=1 papermap auth login
```
The fallback credential file lives at:
```text theme={null}
~/.papermap/credentials
```
## Windows shell selection
On Windows, shell mode uses PowerShell 7 by default.
```yaml theme={null}
shell:
windows: pwsh
```
Supported values:
| Value | Shell |
| ------ | -------------------------- |
| `pwsh` | PowerShell 7+ (`pwsh.exe`) |
| `cmd` | Command Prompt (`cmd.exe`) |
To use Command Prompt:
```yaml theme={null}
shell:
windows: cmd
```
If `shell.windows` is `pwsh` and PowerShell 7 cannot be found, Papermap refuses to start and asks you to install PowerShell 7 or change the setting to `cmd`.
The shell is resolved once when the TUI starts. Restart `papermap` after changing `shell.windows`.
## Related local files
| Path | Purpose |
| ----------------------------- | -------------------------------------------------- |
| `~/.papermap/config.yaml` | TUI configuration |
| `~/.papermap/credentials` | File fallback credentials when keyring is not used |
| `~/.papermap/workspaces.json` | Cached workspace metadata |
## Next steps
Understand browser login, password fallback, credential storage, and logout.
Fix configuration, login, workspace, and shell errors.
# Install the TUI
Source: https://docs.papermap.ai/documentation/tui/install
Install Papermap TUI with Homebrew, the install script, Go, or a source build.
Install the `papermap` command, sign in, then launch the terminal interface.
## Installation options
```bash Homebrew theme={null}
brew install papermap-ai/papermap/papermap
# Alias formula
brew install papermap-ai/papermap/tui
```
```bash Tap theme={null}
brew tap papermap-ai/papermap
brew install papermap
```
```bash Script theme={null}
curl -fsSL https://raw.githubusercontent.com/Papermap-ai/papermap-tui/main/install.sh | sh
```
```bash Go theme={null}
go install github.com/papermap/papermap-tui/cmd/papermap@latest
```
```bash Source theme={null}
git clone https://github.com/Papermap-ai/papermap-tui.git
cd papermap-tui
make build
./bin/papermap
```
The install script downloads the latest release, verifies its SHA256 checksum, and installs to `/usr/local/bin` or `~/.local/bin`.
## Install a specific version
Use `VERSION` when you need a pinned release. Use `PREFIX` when you want to install somewhere other than the default location.
```bash theme={null}
PREFIX=$HOME/.local VERSION=v0.0.1 \
curl -fsSL https://raw.githubusercontent.com/Papermap-ai/papermap-tui/main/install.sh | sh
```
## Verify installation
```bash theme={null}
papermap --version
papermap --help
```
You should see the installed version and the supported command list.
```text theme={null}
papermap [flags] Launch the interactive TUI
papermap auth login Sign in to Papermap (opens browser)
papermap auth logout Sign out and clear local credentials
papermap auth whoami Show the signed-in user
papermap workspace create Create a database-backed workspace
papermap workspace list List workspaces visible to the signed-in user
```
## First launch
```bash theme={null}
papermap auth login
```
```bash theme={null}
papermap
```
Type a data question and press `Enter`. Papermap streams the response into the terminal transcript.
## Build from source
If you are developing the TUI locally, use the Makefile commands from the TUI repository.
```bash theme={null}
make build # build into ./bin/papermap
make run # go run ./cmd/papermap
make test # go test ./... -race
make fmt # gofumpt + goimports
make lint # golangci-lint run
make release-snapshot # local GoReleaser snapshot build
```
## Supported platforms
Release builds target macOS and Linux on `amd64` and `arm64`. The Go install path can also build wherever Go and the TUI dependencies are supported.
If `papermap` installs successfully but your shell cannot find it, confirm that `/usr/local/bin`, `~/.local/bin`, or your Go binary path is in `PATH`.
## Next steps
Sign in with browser login or terminal password fallback.
Learn shortcuts, overlays, streaming, shell mode, and model switching.
# Navigate the TUI
Source: https://docs.papermap.ai/documentation/tui/navigation
Use Papermap TUI shortcuts, command palette, streamed answers, conversations, model switching, shell mode, and terminal selection.
Papermap TUI is designed for keyboard-first work. Most actions are available through direct shortcuts and through the `/` command palette.
## Main chat screen
Type a question in the input and press `Enter`. Papermap sends the prompt to the active workspace and streams progress into the transcript.
Examples:
```text theme={null}
Show monthly revenue by customer segment for the last two quarters.
Which products had the highest refund rate last month?
Summarize open invoices over $5,000 and group them by owner.
```
The response can include narrative text, reasoning trace previews, structured tables, tiles, and terminal-friendly chart output.
## Essential shortcuts
| Key | Action |
| -------- | ---------------------------------------------------------------------------- |
| `Enter` | Submit prompt or confirm a focused modal action |
| `/` | Open command palette when the input is empty |
| `Ctrl+P` | Open conversation history for the active dashboard |
| `Ctrl+W` | Open workspace picker |
| `Tab` | Cycle to the next available LLM model |
| `Ctrl+T` | Toggle thinking traces on or off |
| `Ctrl+L` | Clear chat and start a fresh session |
| `Esc` | Cancel streaming, exit shell mode, close overlays, or clear active selection |
| `Ctrl+C` | Quit with confirmation |
| `!` | Enter shell mode when the input is empty |
`/` only opens the command palette when the input is empty. If you already typed text, `/` stays part of your prompt.
## Command palette
Open the palette with `/` from an empty prompt. It exposes the main actions in one place.
| Command | Shortcut | What it does |
| ------------------- | -------- | --------------------------------------- |
| Conversations | `Ctrl+P` | Browse and load prior chats |
| Switch workspace | `Ctrl+W` | Change the active workspace |
| Switch model | `Tab` | Choose or cycle the LLM model |
| Toggle thinking | `Ctrl+T` | Show or hide assistant reasoning traces |
| Shell mode | `!` | Run a one-shot terminal command |
| Clear / new session | `Ctrl+L` | Drop the current chat and start fresh |
| Quit | `Ctrl+C` | Exit Papermap |
Use arrow keys to move, `Enter` to run the highlighted command, and `Esc` to close the palette.
## Streaming and cancellation
While an insight is running, the transcript can show a live status line, a pending assistant response, reasoning events, tool lifecycle events, and final output.
Use `Esc` to cancel an in-flight insight. The TUI tears down the local stream and asks the backend to cancel the run.
If backend cancellation fails after local cancellation succeeds, Papermap shows a non-blocking notice. Your terminal session remains usable.
## Thinking traces
Thinking traces show the assistant's reasoning and tool activity. Toggle them with `Ctrl+T`.
| State | Behavior |
| ------- | -------------------------------------------------------------------------------------- |
| Hidden | Shows minimal live progress while streaming, then hides trace details after completion |
| Visible | Shows the full reasoning/tool timeline while streaming and after completion |
You can set the default in `~/.papermap/config.yaml` with `show_thinking: true`. See [Configuration](/documentation/tui/configuration).
## Conversations history
Open history with `Ctrl+P`. The overlay loads previous chats for the current dashboard and fetches more pages as needed.
| Key | Action |
| --------------------- | -------------------------------- |
| `Up`, `k` | Move up |
| `Down`, `j`, `Ctrl+N` | Move down |
| `Home`, `g` | Jump to first conversation |
| `End`, `G` | Jump to last loaded conversation |
| `Enter` | Open selected conversation |
| `Esc` | Close without changing chat |
If you move past the bottom and more pages exist, the TUI loads more conversations automatically.
## Model switching
Press `Tab` to cycle through available models. Use the command palette's `Switch model` command when you want a visible picker.
| Key | Action |
| --------------------------- | ------------------------ |
| `Up`, `k`, `Ctrl+P` | Move up |
| `Down`, `j`, `Ctrl+N` | Move down |
| `Left`, `h`, `PgUp`, `p` | Previous model page |
| `Right`, `l`, `PgDown`, `n` | Next model page |
| `Home`, `g` | Jump to first model |
| `End`, `G` | Jump to last model |
| `Enter` | Select highlighted model |
| `Esc` | Cancel |
The selected model appears as a badge in the input area and is persisted in your config.
## Shell mode
Shell mode runs a single command from inside the TUI. Type `!` at the start of an empty prompt, enter the command, then press `Enter`.
```text theme={null}
!ls -la
!git status
!psql --version
```
Shell results are local transcript turns. They are not persisted to Papermap chat history and are not sent as assistant prompts.
| Key | Action |
| ----------- | ---------------------------------------------- |
| `!` | Enter shell mode from an empty prompt |
| `Enter` | Run the typed command |
| `Esc` | Cancel running command or exit shell mode |
| `Backspace` | Exit shell mode when the shell prompt is empty |
Shell mode executes commands on your machine. Treat it like your normal terminal and avoid commands you would not run directly.
## Scrolling and selection
Use scroll keys while reviewing long responses.
| Key | Action |
| ------------------------ | -------------------- |
| `Shift+Up` | Scroll up one line |
| `Shift+Down` | Scroll down one line |
| `PgUp`, `Shift+PgUp` | Page up |
| `PgDown`, `Shift+PgDown` | Page down |
| `Home`, `Shift+Home` | Jump to top |
| `End`, `Shift+End` | Jump to bottom |
| `Ctrl+D` | Half page down |
| Mouse wheel | Scroll transcript |
You can drag over transcript text with the mouse to copy a selection to the clipboard. After release, Papermap shows a success toast and clears the highlight. Press `Esc` to clear an active selection without copying.
## Tool confirmations
Some privileged tool actions can require confirmation. When Papermap needs approval, the TUI opens a modal with the action description, available choices, hotkeys, and an optional countdown.
Use `Tab`, arrow keys, `h`, or `l` to change focus. Press `Enter` to choose the focused action. Press an action hotkey when shown. Press `Esc` to dismiss when the modal supports dismissal.
## Next steps
Switch, search, create, list, and cache Papermap workspaces from the terminal.
Fix common login, shell, workspace, and session issues.
# Terminal UI Overview
Source: https://docs.papermap.ai/documentation/tui/overview
Use Papermap directly from your terminal with keyboard-first analytics, streamed insights, workspaces, model switching, and shell mode.
Papermap TUI gives you terminal-native access to Papermap. Sign in once, launch `papermap`, choose your workspace, ask questions, and watch streamed insight responses render without leaving your command line.
## Why use the TUI?
Stay in the terminal, ask natural-language data questions, and move through workspaces, chats, models, and tools with shortcuts.
See progress while Papermap works. Narrative answers, tables, tiles, charts, and reasoning traces render as the request completes.
Launch into your unified workspace by default, then switch to any visible workspace with a searchable picker.
Run one-shot shell commands, copy transcript selections, browse conversation history, and switch LLM models in place.
## Typical workflow
Install `papermap` with Homebrew, the install script, `go install`, or a source build. See [Install the TUI](/documentation/tui/install).
Run `papermap auth login`. The default flow opens Papermap in your browser and returns a short-lived CLI code to your local terminal callback.
Run `papermap`. If your session is valid, Papermap opens directly into the chat workspace.
Submit prompts with `Enter`, use `/` for the command palette, `Ctrl+W` to switch workspaces, and `Ctrl+P` to reopen prior conversations.
## What the TUI can do
Send prompts from the chat input and receive streamed Papermap answers in your terminal.
Papermap renders structured responses as readable terminal tables, tiles, and chart summaries.
Open prior chats for the active dashboard, page through history, and load the conversation you need.
Create Postgres, MySQL, MongoDB, and Supabase workspaces from interactive CLI forms.
The TUI is intentionally focused on terminal workflows: login, workspace selection, conversations, streamed insights, model selection, and shell mode. Use the Papermap web app for broader workspace administration, OAuth integrations, CSV or Sheets uploads, billing, and visual dashboard editing.
## Next steps
Choose the install path that matches your machine and launch `papermap`.
Learn browser login, password fallback, credential storage, and logout behavior.
Master shortcuts, command palette, streaming, conversations, model switching, and shell mode.
Set API URLs, frontend URLs, default thinking traces, selected model, and Windows shell behavior.
# TUI Troubleshooting
Source: https://docs.papermap.ai/documentation/tui/troubleshooting
Fix common Papermap TUI installation, login, workspace, streaming, shell mode, and configuration issues.
Use this guide when the `papermap` command starts but login, workspace loading, streaming, or shell mode does not behave as expected.
## Quick checks
Run these first:
```bash theme={null}
papermap --version
papermap auth whoami
papermap workspace list
```
If `whoami` says you are not signed in, run:
```bash theme={null}
papermap auth login
```
## Common issues
The CLI prints the login URL after attempting to open your browser. Copy the printed URL into your browser manually.
```bash theme={null}
papermap auth login
```
If you are on SSH or a headless machine, use the password fallback instead.
```bash theme={null}
papermap auth login --password
```
Browser login waits for a localhost callback for a limited time. Restart login and complete the browser flow promptly.
```bash theme={null}
papermap auth login
```
Also check that your browser can reach the printed `http://127.0.0.1:/callback` URL after Papermap redirects.
Browser login only allows production Papermap frontend hosts by default. Internal or development frontends require an explicit opt-in.
```bash theme={null}
PAPERMAP_ALLOW_UNTRUSTED_FRONTEND=1 \
papermap auth login --frontend-url https://internal-frontend.example
```
Only use this with frontends you control.
The TUI attempts token refresh before forcing a new sign-in. If refresh fails, sign in again.
```bash theme={null}
papermap auth login
papermap
```
If the issue repeats, log out and start with clean local auth state.
```bash theme={null}
papermap auth logout
papermap auth login
```
Confirm your account has access to workspaces.
```bash theme={null}
papermap workspace list
```
If the CLI returns no rows, create a database-backed workspace or use the web app to configure sources that require browser-based setup.
```bash theme={null}
papermap workspace create
```
Refresh the local workspace cache, then relaunch the TUI.
```bash theme={null}
papermap workspace list
papermap
```
Logout also clears the workspace cache.
```bash theme={null}
papermap auth logout
```
This is expected. `papermap workspace create` creates the workspace row first, then Papermap verifies the database connection in the background.
If the workspace later cannot answer questions, verify the host, port, database name, username, password, network access, and database permissions.
`!` starts shell mode only from an empty prompt. If your prompt already has text, `!` is typed into the prompt instead.
Clear the prompt with `Ctrl+L`, then press `!` again.
Press `Esc` to cancel the running shell command. Shell mode uses one-shot commands; there is no persistent shell session inside the TUI.
The default Windows shell is PowerShell 7 (`pwsh`). Install PowerShell 7 or switch shell mode to Command Prompt.
```yaml theme={null}
shell:
windows: cmd
```
Save the file at `C:\Users\\.papermap\config.yaml`, then restart `papermap`.
Force file-backed credential storage when the OS keyring is unavailable.
```bash theme={null}
PAPERMAP_FORCE_FILE_STORE=1 papermap auth login
```
Keep `~/.papermap/credentials` private and out of source control.
Papermap needs enough room to render the landing panel, chat layout, overlays, and key hints. Resize the terminal to at least roughly `60x20`, then relaunch or continue.
`/` opens the command palette only when the prompt is empty and the TUI is not streaming. Clear the prompt with `Ctrl+L`, then press `/`.
Press `Ctrl+T` to toggle thinking traces. To show them by default, set this in `~/.papermap/config.yaml`.
```yaml theme={null}
show_thinking: true
```
## Reset local state
Use logout when you want to clear credentials and workspace cache.
```bash theme={null}
papermap auth logout
papermap auth login
papermap
```
Local paths to inspect when debugging:
| Path | Purpose |
| ----------------------------- | ------------------------- |
| `~/.papermap/config.yaml` | TUI settings |
| `~/.papermap/credentials` | File fallback credentials |
| `~/.papermap/workspaces.json` | Workspace cache |
Do not paste credential file contents into support tickets or commits. Share error messages and command output only after removing secrets.
## Still need help?
Send the command you ran, the error output, your operating system, and whether you used browser or password login.
Get guided help setting up Papermap for your team.
# TUI Workspaces
Source: https://docs.papermap.ai/documentation/tui/workspaces
Switch workspaces, create database-backed workspaces, list available workspaces, and understand the local workspace cache.
Workspaces decide which data Papermap can query. The TUI launches into your unified workspace when available, then lets you switch to any workspace visible to your account.
## Switch workspaces
Press `Ctrl+W` from the chat screen to open the workspace picker.
| Key | Action |
| ----------------- | ---------------------------- |
| Type text | Filter by workspace name |
| `Up`, `Ctrl+P` | Move up |
| `Down`, `Ctrl+N` | Move down |
| `Left`, `PgUp` | Previous page |
| `Right`, `PgDown` | Next page |
| `Home` | Jump to first workspace |
| `End` | Jump to last workspace |
| `Ctrl+U` | Clear search |
| `Enter` | Switch to selected workspace |
| `Esc` | Cancel |
The current workspace is marked in the picker. Unified workspaces are also labeled so you can quickly return to the combined view.
## List workspaces from the CLI
```bash theme={null}
papermap workspace list
```
The command prints a tab-aligned table of workspaces visible to your account.
```text theme={null}
ID NAME TYPE UNIFIED
ws_123 Acme Production DB POSTGRES no
ws_unified Unified Workspace unified yes
```
Use `--api-url` when testing against a non-default API host.
```bash theme={null}
papermap workspace list --api-url https://prod.dataapi.papermap.ai
```
## Create a database workspace
```bash theme={null}
papermap workspace create
```
The TUI opens an interactive form and asks for:
| Field | Notes |
| -------------- | ---------------------------------------------- |
| Workspace name | Human-readable name shown in Papermap |
| Database type | `Postgres`, `MySQL`, `MongoDB`, or `Supabase` |
| Host | Database host name or address |
| Port | Optional; defaults by database type when blank |
| Database name | Database to connect |
| Username | Database username |
| Password | Hidden password input |
Default ports:
| Database | Default port |
| -------- | ------------ |
| Postgres | `5432` |
| MySQL | `3306` |
| MongoDB | `27017` |
| Supabase | `5432` |
After submission, Papermap creates the workspace row and verifies the database connection asynchronously.
```text theme={null}
Workspace "Acme Production DB" created (id: ws_123).
Verifying connection in background.
```
The command returns when the workspace is created. Connection verification continues in the background.
## Local workspace cache
The TUI caches workspace metadata locally so launch and switching feel fast.
```text theme={null}
~/.papermap/workspaces.json
```
`papermap workspace create` and `papermap workspace list` refresh this cache. `papermap auth logout` clears it.
If the cache is stale, run:
```bash theme={null}
papermap workspace list
```
Then relaunch the TUI:
```bash theme={null}
papermap
```
## What belongs in the web app?
The CLI supports standard database workspace creation today. Use the Papermap web app for flows that need browser-based authorization or richer setup screens.
Stripe, QuickBooks, Google Ads, and similar OAuth-backed sources should be created from the web app.
Sheets and CSV uploads should be configured from the web app.
Use the web app when you need drag-and-drop dashboard building or broader workspace administration.
Manage plans, users, permissions, and billing from the web app.
## Next steps
Learn workspace shortcuts, history, model switching, and shell mode.
Fix missing workspaces, stale cache, login, and shell errors.
# Papermap Apps
Source: https://docs.papermap.ai/features/apps
Open Apps from the bar, then create bookmarks, notes, skills, document extractions, and data entry recipes.
# Apps
Alan's Apps now live in the bar. Use them to open the right tool, then save and review bookmarked chats, notes, skills, extractions, and data entry recipes.
## Open Apps
Click the **Apps** button on the bar to open the app picker.
Choose the app you want to use.
## Bookmarks
### Create a Bookmark
Click the **bookmark** icon on any Alan response to save it.
### View Bookmarks
Open **Notes** from Apps to see saved bookmarks and notes.
Open a bookmarked note from an Alan chat when you want to review the original conversation.
## Skills
### Create a Skill
Open the Skills app to create a new skill for Alan.
Click **Create your first skill** to start defining the skill steps.
Once saved, Alan can use the skill while answering your chats.
## Document Extraction
Use Document Extraction to upload one or more PDFs, tell Alan what to extract, and review the results before writing them to a sheet.
Describe what Alan should extract and how it should be structured.
Review the extracted rows before approving them.
After you verify the results, Alan can write them to your sheet.
## Data Entry
Use Data Entry for spreadsheet-style workspaces to add new rows without scanning the whole sheet. Pick a unique key column, review matching rows, and save the workflow as a recipe.
Choose the primary key column to start an entry workflow.
View all columns and spot duplicates before you add or edit rows.
Add a new column or new record while the entry workflow is open.
Save the workflow as a recipe so you can reuse the same unique column later.
When you return to Data Entry, your saved recipes are ready to use.
# Branching Chats
Source: https://docs.papermap.ai/features/branching-chats
Branch conversations with Alan to explore different questions without losing your original context.
# Branching Chats
When chatting with Alan, you can branch off from any point in the conversation to explore a new direction while keeping your original thread intact.
## How It Works
Spotted an insight worth exploring further? Instead of cluttering your main conversation, click the **branch icon** on any message to start a new chat from that exact point.
Your branched conversation inherits all the context up to that message, so Alan knows exactly where you left off.
## When to Use Branching
* **Explore "what if" scenarios** without losing your original analysis
* **Dive deeper** into a specific insight while keeping the main thread clean
* **Compare different approaches** to the same question side by side
## Get Started
Create your account and start exploring your data in minutes
See Papermap in action with a personalized walkthrough
# Features Overview
Source: https://docs.papermap.ai/features/overview
Discover what makes Papermap the modern data platform for teams who want powerful analytics without the complexity.
# Papermap Features
Highlihting some exciting Papermap features.
Natural language queries, smart insights, and conversational dashboards
Drop interactive analytics into any app or website
Row-level security, SSO, and SOC 2 compliance
50+ connectors, real-time sync, and no-code transforms
## Get Started
Create your account and start exploring your data in minutes
See Papermap in action with a personalized walkthrough
# Web Search
Source: https://docs.papermap.ai/features/web-search
Combine real-time web data with your own data for richer, more contextual insights.
# Web Search
Alan can search the web in real-time, bringing external context directly into your data analysis.
## How It Works
Click the **web icon** in the chat input to enable web search. Alan will pull in relevant information from the web alongside your data.
## What You Can Do
* **Research on the fly** - Ask Alan to look up industry benchmarks, competitor info, or market trends
* **Compare your data to the web** - See how your metrics stack up against public data or industry standards
* **Enrich your analysis** - Combine internal data with external context for deeper insights
## Example Use Cases
| Your Data | + Web Search | = Insight |
| ------------------ | --------------------- | ------------------------------------ |
| Your sales figures | Industry growth rates | How you're performing vs. the market |
| Product pricing | Competitor pricing | Pricing optimization opportunities |
| Customer trends | Market research | Validation of internal findings |
## Get Started
Create your account and start exploring your data in minutes
See Papermap in action with a personalized walkthrough
# Welcome to Papermap
Source: https://docs.papermap.ai/index
Papermap empowers teams to harness the power of AI native data analytics without the complexity of traditional data platforms.
## What is Papermap?
Papermap is a comprehensive data platform designed specifically for teams that need enterprise-grade data capabilities without the overhead. Whether you're a startup, a small business, lean data team within a larger organization, or a developer building an application, Papermap provides the tools you need to collect, process, analyze, and visualize your data effectively with customizable Artificial Intelligence.
## Key Features
Setup your data pipeline in seconds, not months. Our intuitive interface and guided setup process means you can be processing data on day one.
Advanced analytics capabilities that scale with your needs. From simple dashboards to complex data modeling, Papermap grows with your team.
Process data as it arrives with our real-time streaming capabilities. Make decisions based on the most current information available.
Bank-level security features ensure your data is protected. Compliance-ready with industry standards.
## Getting Started
Ready to transform how your team works with data? Here's how to get started:
[Create your Papermap account](https://www.papermap.ai) and get instant access to the platform.
We support dozens of integrations - connect your databases, APIs, and third-party services and we will set up your data pipeline in seconds.
Ask questions, create dashboards and visualize insights in seconds - no coding required.
## Explore the Documentation
Work with Papermap from your command line. Install the TUI, sign in, switch workspaces, stream answers, browse conversations, and use shell mode.
Learn how to embed Papermap into your website or application. Bring real-time conversational analytics and insights where you work.
Ship client-facing analytics fast without building a BI stack. Serve multiple customers from a single Papermap instance with complete data isolation.
## Need Help?
Explore our comprehensive guides and tutorials.
Get help from our support team.
***
*Ready to unlock the power of big data for your team? [Get started with Papermap](https://www.papermap.ai) today.*