[{"source_url":"https://docs.kapa.ai/retrieval/guides/agent-discoverable-retrieval#set-it-up","content":"# Retrieval > Guides > Let agents discover and query your docs\n## Set it up\n\nYou need a Kapa project with public [knowledge sources](https://docs.kapa.ai/knowledge-sources/), a Vercel project, and the [Vercel CLI](https://vercel.com/docs/cli) linked to it.\n\n1. Copy your project ID from **Settings** > **Projects**. Create an API key under **Deploy** > **API Keys**, and an **HTTP API** integration under **Deploy** > **Integrations**. The integration ID marks this endpoint's traffic in analytics. A separate key lets you rotate it without affecting anything else.\n1. Store the key as an environment variable. The project ID is not a secret and goes in the code.\n```\nvercel env add KAPA_API_KEY production --sensitive\n```\n\n3. Create `api/retrieve.ts` and set `PROJECT_ID` and `INTEGRATION_ID`. Vercel deploys files in `api/` as [Functions](https://vercel.com/docs/functions). Each exported function handles one HTTP method.\n\napi/retrieve.ts\n\n```\nconst PROJECT_ID = \"<your-project-id>\";  \nconst INTEGRATION_ID = \"<your-integration-id>\";  \nconst UPSTREAM = `https://api.kapa.ai/query/v1/projects/${PROJECT_ID}/retrieval/`;  \n  \nconst HEADERS = {  \n  \"Content-Type\": \"application/json\",  \n  \"Cache-Control\": \"no-store\",  \n  \"Access-Control-Allow-Origin\": \"*\",  \n  \"Access-Control-Allow-Methods\": \"GET, OPTIONS\",  \n};  \n  \nexport function OPTIONS(): Response {  \n  return new Response(null, { status: 204, headers: HEADERS });  \n}  \n  \nexport async function GET(request: Request): Promise<Response> {  \n  const apiKey = process.env.KAPA_API_KEY;  \n  if (!apiKey) {  \n    return new Response(\"Retrieval proxy is not configured\", { status: 500 });  \n  }  \n  \n  const query = new URL(request.url).searchParams.get(\"q\")?.trim();  \n  if (!query) {  \n    return new Response(  \n      JSON.stringify({ error: \"Pass the question as the q query parameter.\" }),  \n      { status: 400, headers: HEADERS },  \n    );  \n  }  \n  \n  const upstream = await fetch(UPSTREAM, {  \n    method: \"POST\",  \n    headers: { \"X-API-KEY\": apiKey, \"Content-Type\": \"application/json\" },  \n    body: JSON.stringify({ query, integration_id: INTEGRATION_ID }),  \n  });  \n  \n  return new Response(upstream.body, { status: upstream.status, headers: HEADERS });  \n}\n```\n\n4. Add a rewrite in `vercel.json` so the function is served at `/retrieve` instead of `/api/retrieve`. Then deploy with `vercel --prod`.\n\nvercel.json\n\n```\n{ \"rewrites\": [{ \"source\": \"/retrieve\", \"destination\": \"/api/retrieve\" }] }\n```\n\n5. Test it.\n\n```\ncurl -sS 'https://docs.example.com/retrieve?q=How+do+I+rotate+an+API+key'\n```\n\nThe response is a JSON array of `{ \"source_url\", \"content\" }` objects, most relevant first. If you get `500 Retrieval proxy is not configured`, the key is not set for that environment. If you get `403`, the key belongs to a different project than `PROJECT_ID`."},{"source_url":"https://docs.kapa.ai/retrieval/guides/agent-discoverable-retrieval#limits-and-extensions","content":"# Retrieval > Guides > Let agents discover and query your docs\n## Limits and extensions\n\nThe endpoint does not know who is calling. Per-user rate limits do not apply, and all requests count against the [team limits](https://docs.kapa.ai/retrieval/hosted-mcp-server#rate-limits) for the one key. Add a [Vercel Firewall rate limit](https://vercel.com/docs/vercel-firewall/vercel-waf/rate-limiting) on the path. Rotate the key if you see traffic you do not recognize.\n\nYou can change the function to do more. Pass `source_group_ids_include` to limit which sources are searched. Read `top_k` or `max_chars` from the query string and pass them on. Add a second function in front of the [Documents endpoint](https://docs.kapa.ai/retrieval/http-api/#documents) so agents can fetch a full page by URL. The same setup works on Netlify, Cloudflare Workers, or any other platform that runs a function and can read a secret."},{"source_url":"https://docs.kapa.ai/analytics/platform-assistant","content":"# Analytics\n## Platform Assistant\n\nThe Platform Assistant is a natural language assistant built into the Kapa platform. It has access to Kapa's documentation to answer questions about the platform. It also has tools that let you interact with platform functionality directly, from read-only operations like searching conversations and viewing analytics to write operations like creating tags and integrations.\n\nYou can open it by clicking the **Kapa Agent** button at the bottom of the sidebar. It appears as a panel on the right side of the platform.\n\nThe Platform Assistant is built with Kapa's own [Agent SDK](https://docs.kapa.ai/dev/agent).\n\n### Capabilities\n\n#### Answer questions\n\nThe assistant can search Kapa's documentation to answer questions about how to use the platform, configure integrations, set up knowledge sources, and more.\n\nExamples:\n\n- \"How do I add a widget to my website?\"\n- \"How can I see all questions asked in Chinese?\"\n- \"Can I filter top questions by a certain topic or product?\"\n\n#### Analyze conversations\n\nThe assistant can search and filter your conversations by text, date range, tags, confidence level, and reactions. It can count matches, retrieve full question-answer histories with feedback, and add comments to threads.\n\nExamples:\n\n- \"How many questions are related to pricing?\"\n- \"Show me questions where users had trouble understanding result expressions\"\n- \"Can you tell me what the common theme is for this user `<user-id>`?\"\n\n#### Explore analytics and topic clusters\n\nThe assistant can retrieve performance metrics, list top questions and coverage gaps, and drill into individual clusters. It can render inline charts (bar, line, area, donut) to visualize trends.\n\nExamples:\n\n- \"What were the most common queries last week?\"\n- \"Show conversation trends over the past month\"\n- \"Can you make a graph of uncertain answers for the past 12 months?\"\n- \"Based on the uncertain answers, provide me an analysis where I can make improvements in the documentation\"\n- \"Help me address the top 5 common questions so users get the most updated and accurate results\"\n\n#### Manage tags\n\nThe assistant can list, create, and delete both custom tags and status tags. It can also assign status tags to individual conversations or topic clusters to help you track your workflow.\n\nExamples:\n\n- \"Create a custom tag for questions about pricing\"\n- \"Tag this cluster as addressed\"\n\n#### Manage integrations and API keys\n\nThe assistant can list, create, and delete integrations and API keys.\n\nExamples:\n\n- \"Create a new API key for our staging environment\"\n- \"List all my integrations\"\n\n#### Discover users\n\nThe assistant can find end users and view their activity statistics.\n\nExamples:\n\n- \"How many unique users submitted questions last month?\"\n- \"Show me the most active users\"\n\n#### Navigate the platform\n\nThe assistant can take you directly to any page in the platform, including conversations with pre-applied filters and specific topic clusters.\n\nExamples:\n\n- \"Show me all uncertain conversations from last week\"\n- \"Take me to the coverage gaps page\"\n\nWrite operations require your explicit approval before the assistant executes them."},{"source_url":"https://docs.kapa.ai/dev/agent/authentication","content":"# Dev > Agent\n## Authentication\n\nThe Agent SDK runs in your frontend and talks directly to Kapa's backend services. To do this without exposing your API key in the browser, the SDK uses short-lived **session tokens**: your server mints a token from your API key, and the SDK then uses that token for all its calls to Kapa.\n\n### How it works\n\n1. The browser calls your server endpoint (e.g. `POST /api/session`)\n1. Your server calls the Kapa session API with the `X-API-Key` header\n1. Kapa returns a session token (valid for 1 hour)\n1. Your server forwards the token to the browser\n1. The SDK uses the token for all subsequent API calls\n\nThe API key never leaves your server.\n\n### Session endpoint\n\n```\nPOST https://api.kapa.ai/agent/v1/projects/{projectId}/agent/sessions/\n```\n**Headers:**\n\n- `X-API-Key: your-api-key`\n\n**Response:**\n\n```\n{  \n  \"session_token\": \"NRd60UqDpLSeeIFzCfmj5dxiRDOJL8G7aSXVzpQ0pPusbe9kHIjEymznutrJu6uf\",  \n  \"expires_at\": \"2026-03-17T09:54:51.165812Z\"  \n}\n```\n\n### Server-side proxy example\n\nYour `getSessionToken` function should call your own server, which proxies the request:\n```\ngetSessionToken={async () => {  \n  const res = await fetch('/api/session', { method: 'POST' });  \n  if (!res.ok) throw new Error('Session creation failed');  \n  return res.json();  \n}}\n```\n\nYour server just passes through the Kapa API response:\n\n```\nconst response = await fetch(  \n  `https://api.kapa.ai/agent/v1/projects/${projectId}/agent/sessions/`,  \n  { method: 'POST', headers: { 'X-API-Key': apiKey } },  \n);  \nres.json(await response.json());\n```\n\nThe SDK accepts the raw Kapa API response (`{ session_token, expires_at }`) directly. No transformation needed. It also accepts the normalized format (`{ token, expiresAt }`).\n\n### Token lifecycle\n\nThe SDK manages tokens automatically:\n\n- **Lazy fetching.** `getSessionToken` is not called until the user sends their first message\n- **Caching.** Tokens are cached and reused for subsequent requests\n- **Auto-refresh.** Tokens are refreshed 30 seconds before expiry\n- **Retry on 401.** If a request fails with 401, the token is cleared and a fresh one is fetched\n- **Deduplication.** Concurrent refresh calls are deduplicated (only one `getSessionToken` call at a time)\n\n### Conversation history\n\nTo enable conversation history, include `external_owner_id` in the request body when calling the Kapa session API. This is an opaque string that identifies which end user owns the session, for example an internal user ID or a hashed email address.\n\n**Why it works this way.** Conversation history is scoped to the session. When a session is created with `external_owner_id`, Kapa records every conversation thread under that owner. The history endpoints (`listThreads`, `resumeThread`, `deleteThread`) then only return threads owned by the session making the request. One session cannot access another user's threads.\n\n**Why it is safe.** The `external_owner_id` must be set by your trusted backend using your API key. The frontend never passes this value. It only holds a short-lived session token, so there is no way for a user to forge or modify their `external_owner_id` from the browser.\n\nSessions created without `external_owner_id` can still chat normally, but cannot access history endpoints.\n```\nconst response = await fetch(  \n  `https://api.kapa.ai/agent/v1/projects/${projectId}/agent/sessions/`,  \n  {  \n    method: 'POST',  \n    headers: {  \n      'X-API-Key': apiKey,  \n      'Content-Type': 'application/json',  \n    },  \n    body: JSON.stringify({ external_owner_id: currentUser.id }),  \n  },  \n);  \n// forward the response to your client as-is  \nres.json(await response.json());\n```\n\nThe value must be stable across sessions for the same user. All threads created under the same `external_owner_id` are returned by `listThreads`."},{"source_url":"https://docs.kapa.ai/examples/embed-an-ai-assistant-in-your-app-that-answers-questions-and-takes-actions","content":"# Examples > Embed an AI assistant in your app that answers questions and takes actions > See what it can do > Make the assistant take an action\n\n![Screenshot of a workspace settings page showing **API keys** management with an assistant approval flow.\n\n### Left sidebar\n- Workspace name: **Acme**\n- Under **Settings**:\n  - **Members**\n  - **API keys** is selected/highlighted\n\n### Main center panel\n- Page title: **API keys**\n- Subtitle: **Keys that authenticate against the API**\n- A purple **Create key** button near the top right of this section\n- A table with columns **Name** and **Key**\n- Three listed keys:\n  1. **Production** — key begins **ak_live_7f3k…**\n  2. **Staging** — key begins **ak_test_2m9c…**\n  3. **Old integration** — key begins **ak_live_9x1q…**\n- Each row has a red **Delete** action on the right\n\n### Right assistant panel\n- Header: **Assistant**\n- Description: **Answers from your documentation, and manages the workspace for you**\n- A prominent purple button: **Make me an API key**\n- Chat-style conversation:\n  - Assistant asks what the API key should be named\n  - User reply: **call it development**\n- Below, an approval card appears:\n  - Text: **The assistant wants to run create_api_key:**\n  - JSON payload shown:\n    ```json\n    {\n      \"name\": \"development\"\n    }\n    ```\n  - Two decision buttons:\n    - Green **Allow**\n    - Red **Deny**\n- At the bottom is a message input field **Ask the assistant…** with a **Send** button\n\nOverall, the image illustrates an assistant-generated tool action waiting for user approval before creating a new API key.](https://docs.kapa.ai/assets/images/in-product-agent-approval-b3716713b367c5d835a8b64716d6de89.png)"},{"source_url":"https://github.com/kapa-ai/kapa-examples/blob/main/in-product-agent/app/api/settings/route.ts","content":"Kapa-ai > Kapa-examples > Blob > Main > In-product-agent > App > Api > Settings > route.ts\n```\nimport {\n  createApiKey,\n  deleteApiKey,\n  deleteMember,\n  getSettings,\n  inviteMember,\n  type Role,\n} from \"@/lib/store\";\n\nexport const dynamic = \"force-dynamic\";\n\nexport function GET() {\n  return Response.json(getSettings());\n}\n\n// Mutations for the page's own controls. The agent's tools call the same\n// store functions directly in lib/tools.ts; both interfaces drive the same\n// data layer.\nexport async function POST(req: Request) {\n  const body = await req.json();\n  const result = dispatch(body);\n  if (result && typeof result === \"object\" && \"error\" in result) {\n    return Response.json(result, { status: 400 });\n  }\n  return Response.json(result);\n}\n\nfunction dispatch(body: { action: string; [key: string]: unknown }) {\n  switch (body.action) {\n    case \"invite_member\":\n      return inviteMember({ email: String(body.email), role: body.role as Role });\n    case \"delete_member\":\n      return deleteMember(String(body.memberId));\n    case \"create_api_key\":\n      return createApiKey(String(body.name));\n    case \"delete_api_key\":\n      return deleteApiKey(String(body.keyId));\n    default:\n      return { error: `Unknown action \"${body.action}\".` };\n  }\n}\n\n```"},{"source_url":"https://docs.kapa.ai/examples/embed-an-ai-assistant-in-your-app-that-answers-questions-and-takes-actions","content":"# Examples > Embed an AI assistant in your app that answers questions and takes actions > See what it can do > Make the assistant take an action\n\n![The image is a screenshot of an app workspace settings page focused on **API keys**, with an **assistant side panel** demonstrating an approval-based key creation flow.\n\n### Main layout\n- **Left sidebar** under the workspace name **“Acme”**\n  - Section label: **SETTINGS**\n  - Menu items:\n    - **Members**\n    - **API keys** (selected/highlighted)\n\n- **Center panel**\n  - Title: **API keys**\n  - Subtitle: **Keys that authenticate against the API**\n  - A prominent **Create key** button at the top right of this panel\n  - A table listing existing keys with columns:\n    - **Name**\n    - **Key**\n  - Rows shown:\n    - **Production** — key prefix starts with **ak_live_7f3k...**\n    - **Staging** — **ak_test_2m9c...**\n    - **Old integration** — **ak_live_9x1q...**\n    - **development** — **ak_live_bjev...**\n  - Each row has a red **Delete** action on the right\n\n### Assistant panel on the right\n- Header: **Assistant**\n- Description: **Answers from your documentation, and manages the workspace for you**\n- A button near the top: **Make me an API key**\n- Conversation shown:\n  - Assistant asks what to name the API key, giving examples like **“Production server”** or **“CI pipeline”**\n  - User replies: **call it development**\n- Below that is an approval/tool-call card titled **Create an API key**, showing a structured JSON-like payload with:\n  - input name: **\"development\"**\n  - output id: **\"key_13\"**\n  - output name: **\"development\"**\n  - prefix: **\"ak_live_bjev\"**\n- A confirmation message at the bottom says:\n  - **Created the API key development (prefix ak_live_bjev).**\n\n### Overall meaning\nThe screenshot illustrates an assistant that can **create API keys for the workspace**, but only after the user names the key and approves the action. The newly created key appears in the API keys table on the main page.](https://docs.kapa.ai/assets/images/in-product-agent-approved-4dc6a459e99b255461ba79561a29c76d.png)"},{"source_url":"https://docs.kapa.ai/getting-started/connect-an-ai-agent","content":"# Getting-started\n## Connect an AI agent to your knowledge\n\nIn this quickstart, you give an AI agent access to the knowledge you indexed in [Index your first source](https://docs.kapa.ai/getting-started/index-your-first-source): you set up an MCP server over your project and hand it to an LLM as a search tool. We keep the agent as simple as possible, so the whole quickstart fits in one `curl` command. Your real agent will be more than that, but its relationship to your knowledge stays the same: search as a tool.\n\nBy the end, you will have:\n\n- A hosted MCP server exposing search over everything your project has indexed.\n- An agent that searches your knowledge and answers from it, in a single API call.\n\n### Before you start\n\nBefore you start, you should have:\n\n- A project with indexed sources, for example from [Index your first source](https://docs.kapa.ai/getting-started/index-your-first-source).\n- `curl` and `jq`. `curl` comes preinstalled on most operating systems; install `jq` with your package manager, for example `brew install jq` on macOS.\n- An Anthropic or OpenAI API key, for the agent side of the call.\n\n### Create your MCP server\n\n1. In Kapa, click **Integrations** > **+ Add new integration**.\n1. Choose **Hosted MCP Server**.\n1. Click **Continue**.\n1. Configure the **Subdomain**: This becomes the first part of the URL clients use to connect to your MCP server, in the form `<subdomain>.mcp.kapa.ai`. Subdomains are globally unique, so pick one related to your product name.\n1. Configure the **Server name**. This becomes the MCP server label (server_name / serverLabel) that clients see when listing or calling tools from this server; it does not affect the URL or subdomain.\n1. Choose the **Authentication type**.\n\nFor this quickstart, set the **Server name** to `docs` and choose **API key** as the authentication type. The other authentication types are for offering the server to people in their AI tools, such as Claude Code, Cursor, or ChatGPT; the [Hosted MCP server](https://docs.kapa.ai/retrieval/hosted-mcp-server#authentication) page covers them.\n\nClick **Save**, then copy the server URL with **Copy MCP server URL** in the integration row's **Actions** column. It has the form `https://<subdomain>.mcp.kapa.ai`.\n\n![Hosted MCP server creation form with API key authentication selected](https://docs.kapa.ai/img/quickstart-mcp-server-creation.png)\n\n### Your server's tools\n\nYour MCP server exposes [three tools](https://docs.kapa.ai/retrieval/hosted-mcp-server#tools) to agents. The primary one is `search_<PRODUCT_NAME>_knowledge_sources`, in this walkthrough `search_kapa_knowledge_sources`, the tool this quickstart uses: it takes a question or a task, performs [agentic retrieval](https://docs.kapa.ai/retrieval/) over all the sources indexed in your project and returns the most relevant chunks to the caller: each chunk is a short, self-contained snippet of text from a single document in your knowledge base, and the list comes back as Markdown. This is how you give context from your knowledge to your agents.\n\n### Create an API key\n\nThe server authenticates requests with a project API key:\n\n1. Navigate to **API Keys** (under **Deploy** in the sidebar) and click **Add new API key**.\n1. Copy the key."},{"source_url":"https://docs.kapa.ai/retrieval/hosted-mcp-server#authentication","content":"# Retrieval > Hosted MCP server\n## Authentication\n\nThe authentication type is chosen at creation and cannot be changed afterwards. The three options, as they appear in the platform:\n|Type|For|Mechanism|\n|---|---|---|\n|**API key**|Agents and backends you operate|`Authorization: Bearer <API_KEY>` on every request|\n|**Public**|Your external users, in tools like Cursor or Claude Code|OAuth provider picker (Google or GitHub) on first connect; external projects only|\n|**Internal**|Your own team, in ChatGPT or Claude|Kapa account login|\n\n#### API key\n\nYour server requires a project API key via the `Authorization` header on every request:\n```\nAuthorization: Bearer <YOUR_API_KEY>\n```\n\nHow you set this header depends on the MCP client or agent framework you use, but in all cases you must keep the API key in your backend. Never expose it in client-side code or send it to the browser.\n\n#### Public (OAuth)\n\nYour server is publicly accessible, but Kapa requires users to authenticate with a Google or GitHub account. Kapa uses the anonymous user ID from the chosen provider only to enforce per-user [rate limits](https://docs.kapa.ai/retrieval/hosted-mcp-server#rate-limits) and prevent abuse.\n\n- **Google**: Kapa requests only the `openid` scope and receives a stable, opaque user ID. It does not request the `email` or `profile` scopes, so Kapa does not see the user's name, email address, or other personal data. On the Google consent screen this appears as **Associate you with your personal info on Google**, which is Google's generic wording for the `openid` scope.\n- **GitHub**: Kapa requests no OAuth scopes, which grants read-only access to public profile information only. Kapa uses the stable, opaque GitHub user ID solely for rate limiting.\n\nFor agents that cannot complete an OAuth flow, or that only have a web fetch tool, you can [let agents discover and query your docs](https://docs.kapa.ai/retrieval/guides/agent-discoverable-retrieval): a plain GET that returns chunks, with the API key held in a small Vercel Function.\n\n#### Internal (Kapa account)\n\nYour server is restricted to employees with a Kapa account.\n\nWhen a user connects to your internal MCP for the first time, they are directed to the Kapa login page. The user then logs in with their Kapa account, using whichever authentication methods are permitted for your Kapa team, including [SAML SSO](https://docs.kapa.ai/account/authentication#saml-based-sso) if it is enabled.\n\nTo access the internal MCP server, the user account must have the **Use Internal Chat Assistant** permission for the project. Refer to [Roles and permissions](https://docs.kapa.ai/account/role-based-permissions) for more information on managing project permissions."},{"source_url":"https://docs.kapa.ai/dev/agent/authentication#getting-your-credentials","content":"# Dev > Agent > Authentication\n## Getting your credentials\n\n#### API key\n\n1. Log in to your [Kapa platform](https://app.kapa.ai)\n1. Navigate to **Deploy → API Keys**\n1. Create or copy an existing API key\n1. Store it as a server-side environment variable (e.g. `KAPA_API_KEY`)\n\n#### Project ID and Integration ID\n\n1. In your [Kapa platform](https://app.kapa.ai), go to **Integrations → Agent SDK**\n1. Create an Agent SDK integration if you don't have one\n1. Copy the **Project ID** and **Integration ID** from the integration setup page\n1. The **Project ID** is used both in the session endpoint URL and as the `projectId` prop on `AgentProvider`\n1. The **Integration ID** is passed as the `integrationId` prop on `AgentProvider`"},{"source_url":"https://docs.kapa.ai/dev/agent/in-product-agent-best-practices","content":"# Dev > Agent > Best practices for building an in-product agent > Best practices > Require approval for anything that modifies data\n\n![This image is a dark-themed **kapa.ai dashboard UI screenshot** with a left navigation sidebar, a central analytics dashboard, and a right-side **Kapa Agent** approval panel.\n\n### Main layout\n- **Top-left branding:** kapa.ai logo with a purple “k” icon.\n- **Left sidebar navigation:**\n  - Selected item: **Dashboard**\n  - Other items: **Chat**, and under Analytics: **Conversations**, **Users**, **Coverage Gaps**, **Top Questions**, **Source Analytics**\n  - Under Configuration: **Sources**, **Integrations**, **API Keys**\n- **Top-right user area:** shows an account email and a circular avatar with the letter **H**.\n\n### Central dashboard\n- Large title: **Dashboard**\n- Subtitle explains it provides insights into how kapa.ai reduces support workload, improves docs, and delights users.\n- Filters across the top:\n  - **All integrations**\n  - **Last 1 Month**\n  - Date range: **Mar 2, 2026 – Apr 2, 2026**\n\n#### Overview cards\nFour metric cards are visible:\n- **Total questions:** 2651\n- **Uncertain responses:** 173 (7%)\n- **Reactions:** 11 thumbs up, 5 thumbs down\n- **Unique users:** 600\n\n#### Bar chart\n- A stacked bar chart titled **Total Questions Answered**\n- Subtitle: **Question volume trends across all integrations**\n- Weekly bars shown for:\n  - **Mar 2–8**: 359\n  - **Mar 9–15**: 543\n  - **Mar 16–22**: 757\n  - **Mar 23–29**: 648\n  - **Mar 30–5**: 344\n- Bars are colored in multiple stacked segments, mainly purple and pink with smaller colored bands at the bottom, indicating breakdowns within each week.\n\n### Right-side agent panel\n- Header: **Kapa Agent**\n- Includes a **New chat** button and window controls.\n- A chat prompt at the top says: **Create a new API key for our staging environment**\n- The agent response says it will create a new API key named for the staging environment.\n- There is an approval workflow section labeled:\n  - **Create API Key**\n  - Status: **Approval required**\n  - Arguments shown in JSON:\n    ```json\n    {\n      \"name\": \"Staging\"\n    }\n    ```\n](https://docs.kapa.ai/img/agent-guide-approval-flow.png)"},{"source_url":"https://docs.kapa.ai/retrieval/frameworks/langchain#connection-settings","content":"# Retrieval > Frameworks > LangChain\n## Connection settings\n\nAll three components accept these settings. By default, they read the API key and project ID from the environment:\n```\nexport KAPA_API_KEY=\"your-api-key\"  \nexport KAPA_PROJECT_ID=\"your-project-id\"\n```\n\nPass a setting to override its default, for example to read the key from another variable or to search a different project:\n\n```\nimport os  \n  \nfrom langchain_kapa_ai import KapaRetriever  \n  \nretriever = KapaRetriever(  \n    api_key=os.environ[\"SUPPORT_KAPA_API_KEY\"],  \n    project_id=\"your-project-id\",  \n    timeout=30.0,  \n)\n```\n\n|Setting|Type|Default|Description|\n|---|---|---|---|\n|`api_key`|`str`|`KAPA_API_KEY` environment variable|Project API key, sent in the `X-API-KEY` header. It is never shown in representations or error messages.|\n|`project_id`|`str`|`KAPA_PROJECT_ID` environment variable|The project to search.|\n|`base_url`|`str`|`https://api.kapa.ai`|API base URL.|\n|`timeout`|`float`|`60.0`|Timeout in seconds for each request.|\n|`http_client`|`httpx.Client`|`None`|Client for synchronous requests. Without one, each call opens and closes its own client.|\n|`http_async_client`|`httpx.AsyncClient`|`None`|Client for asynchronous requests, with the same default.|\n\nNo component retries a failed request. In a chain, wrap a component with LangChain's `with_retry()` to retry. In an agent, retry tool calls with LangChain's [`ToolRetryMiddleware`](https://docs.langchain.com/oss/python/langchain/middleware/built-in#tool-retry). To turn a `KapaError` into a message the model can read, use [`wrap_tool_call`](https://docs.langchain.com/oss/python/langchain/tools#error-handling)."},{"source_url":"https://docs.kapa.ai/examples/draft-replies-for-your-support-team-in-salesforce#store-your-api-key-in-a-named-credential","content":"# Examples > Draft replies for your support team in Salesforce\n## Store your API key in a named credential\n\nSalesforce keeps API credentials in an [external credential](https://help.salesforce.com/s/articleView?id=sf.nc_named_creds_and_ext_creds.htm). A named credential pairs it with the Kapa API's URL, and flows call Kapa through the named credential, so they never see the key itself.\n\nHow a Salesforce flow sends your Kapa API keySALESFORCEHTTP calloutin the subflowcallsNAMED CREDENTIALKapahttps://api.kapa.aiusesEXTERNAL CREDENTIALKapa_APIPRINCIPALKapaApiKey = your keyHEADERX-API-KEY= ApiKeywith keyKAPAChat APIapi.kapa.airuns asRunning userscreated the case or emailassigned toPERMISSION SETKapa API Accessgrants access\nYou set up three pieces: the external credential that holds the key and adds it as the `X-API-KEY` header, the named credential that the flows call, and a permission set that lets the users the flows run as use the credential. If the user a flow runs as does not have the permission set, the callout fails with \"We couldn't access the credential(s)\".\n\nAll Setup steps in this tutorial use the full Setup menu: click the gear icon in the top right, choose **Setup**, and find each page by name in the **Quick Find** box.\n\n#### Create the external credential\n\n1. In Setup, go to **Named Credentials** and open the **External Credentials** tab. Click **New**.\n\n1. Configure it:\n\n   - **Label**: `Kapa API`\n   - **Name**: `Kapa_API`\n   - **Authentication Protocol**: **Custom**\n\n1. Save. Under **Principals**, click **New**:\n\n   - **Parameter Name**: `Kapa`\n   - **Identity Type**: **Named Principal**\n   - Under **Authentication Parameters**, click **Add** and create a parameter named `ApiKey`, with your Kapa API key as the value.\n\n1. Save. Under **Custom Headers**, click **New**:\n\n   - **Name**: `X-API-KEY`\n   - **Value**: `{!$Credential.Kapa_API.ApiKey}`Kapa rejects requests that send the key under `Authorization` or any other header name.\n\n#### Create the named credential\n\n1. Go back to **Named Credentials** and click **New** on the **Named Credentials** tab.\n1. Configure it:\n   - **Label**: `Kapa`\n   - **Name**: `Kapa`\n   - **URL**: `https://api.kapa.ai`\n   - **Enabled for Callouts**: checked\n   - **External Credential**: `Kapa API`\n   - **Allow Formulas in HTTP Header**: checked. Without it, Salesforce sends the formula text instead of your key.\n1. Save."},{"source_url":"https://docs.kapa.ai/examples/draft-replies-for-your-support-team-in-intercom-fin#create-an-authentication-token-for-your-kapa-api-key","content":"# Examples > Draft replies for your support team in Intercom Fin\n## Create an Authentication token for your Kapa API key\n\nFin keeps API credentials in a dedicated, encrypted store called Authentication tokens, separate from the connector configuration itself. You set the token up once and then reference it from the data connector.\n\n1. In Fin, go to **Settings** > **Authentication** and click **New token**.\n1. Fill in the fields:\n   - **Token title**: a recognizable name, for example `Kapa API Key`.\n   - **Description**: optional and internal-only, for example \"Kapa API key, used by the reply drafting data connector.\"\n   - **Type**: select **text**.\n   - **Token value**: paste your Kapa API key.\n   - **Token prefix**: leave blank. Kapa's API does not use bearer authentication; the key travels in a custom header instead.\n   - **Key for request header**: set to `X-API-KEY`. Kapa rejects requests that send the key under `Authorization` or any other header name.\n1. Save the token.\n\nFin now sends `X-API-KEY: <your_kapa_api_key>` on every request made by any data connector you attach this token to."},{"source_url":"https://docs.kapa.ai/platform-mcp-server#tools","content":"# Platform MCP server\n## Tools\n\nEvery tool except the [server tools](https://docs.kapa.ai/platform-mcp-server#server-tools) calls a Kapa platform endpoint as you. A tool takes only the inputs an agent should set, which can be fewer than the endpoint accepts, and the tool's description in the server's tool list is the reference for its parameters. `search_project_knowledge`, `list_integrations`, `get_project_activity`, and the top questions and coverage gaps tools match their endpoints in the [API reference](https://docs.kapa.ai/api/reference). The tool list comes from Kapa and can change without an update to your client, so the table groups the tools by area rather than listing every one.\n\nStart with `list_projects`: it returns every project in your team, with your permissions on each one. Tools that act on an existing project or object take its ID. Validation and discovery tools take only the connection details of a source.\n|Area|Tools|\n|---|---|\n|Projects|`list_projects`|\n|Sources|`list_sources`, `get_source`, `update_source`, `duplicate_source`, `refresh_source`, `delete_source`, and `list_source_groups`|\n|Source setup|`create_<type>_source` for each source type the agent can set up; `get_<type>_config`, `set_<type>_config`, and `update_<type>_config` to read and write a source's configuration; and `connect_<type>` and `configure_<type>` for sources you authorize in the browser (Google Drive, Salesforce, and Zendesk)|\n|Source checks|`validate_<type>` tools that check access to the third-party system, `check_<type>_connection` for Google Drive and Zendesk, and `list_<type>_*` tools that list what a connector can read, such as spaces, labels, categories, or folders|\n|Web crawling|`preview_crawl`, `list_preview_pages`, `start_crawl`, `start_crawl_with_review`, `get_crawl_status`, and `cancel_crawl`; `get_crawl_config`, `set_crawl_config`, and `update_crawl_config`; the content selector tools `detect_content_selector`, `inspect_content_selector`, `get_content_selector`, `set_content_selector`, and `update_content_selector`; and the review tools `list_pages_for_review` and `approve_pages_for_review`|\n|Custom Answers|`list_custom_qa_pairs`, `add_custom_qa_pair`, `update_custom_qa_pair`, and `delete_custom_qa_pair`|\n|Retrieval|`search_project_knowledge`, the same [agentic retrieval](https://docs.kapa.ai/retrieval/) that the hosted MCP server and the HTTP API expose|\n|Integrations and API keys|`list_integrations`; a `create_<type>_integration` tool for the Website Widget, Slack Bot, Discord Bot, Support Form Deflector, hosted MCP server, API, and Agent SDK integrations; and `create_api_key` and `list_api_keys`|\n|Analytics|Activity: `get_project_activity` and `get_activity_over_time`. Conversations: `search_conversations`, `list_threads`, `get_thread`, and `list_end_users`. Topics: `list_top_questions_periods`, `get_top_questions`, `list_coverage_gaps_periods`, and `get_coverage_gaps`. Sources: `get_source_usage` and `list_source_questions`. Value: `get_time_saved`, `get_self_serve_rate`, and `get_users_and_deflections`. Agents: `list_agent_feedback`, the feedback agents leave through your hosted MCP servers|\n\nSearches made with `search_project_knowledge` are recorded in [Conversations](https://docs.kapa.ai/analytics/conversations) like any other query. Kapa creates an integration for them in the project the first time the server searches it, named **Kapa Platform MCP** by default. It does not count toward your plan's integration limit and does not complete the **Deploy an integration** step under **Get started**."}]