/pachca:pachca-apifrom Pachca
Calls the Pachca REST API from code, scripts, and CI. Handles token scopes, pagination, error retries (401/403/429/5xx), file uploads, and SDK/CLI usage.
Ships in Pachca. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
The judgment around calling the Pachca REST API from a script, a service, CI, an SDK or the pachca CLI. The per-method reference lives elsewhere: MCP tool descriptions, pachca ... --help, and the method .md pages. Do not restate it; look it up.
https://api.pachca.com/api/shared/v1 directly, through an SDK, or through pachca in a shell script or CI job.401, 403, 409, 422, 429, 5xx) and you must decide: fix the request, fix the token, or wait.With MCP tools connected, a one-off action is just a tool call. The rules below still hold underneath: every tool call is an API request under the same token, scopes and limits.
Bulk work belongs in a shell or a script, not in a chain of tool calls: a full list, an export to a file, a walk over thousands of records, a large attachment. Through MCP every page passes through your context and you would copy the records into the file yourself. List records come cut to main fields unless view is full, an answer has a size cap, and a file over the cap comes back as its size only. With a terminal, run pachca users list --all -o csv > users.csv or pachca files get <id> --save <path> and read only the result. The CLI signs in separately from MCP: check pachca auth status, else pachca auth login. Without a terminal, say that a full export needs one, or page through and keep only what the answer needs. A walk sees only what the token sees: its own chats and the open conversations and channels. The Owner on the «Корпорация» plan can also list every conversation and channel of the workspace, closed ones included (not direct chats or threads), but not read them: messages of closed chats the token is not in come only through the message export, which also needs the Owner and that plan → pachca-admin.
Never invent a path, a field name or a body shape. Look it up and stop as soon as you have it:
pachca_...); the tool description is the reference.pachca api ls: every endpoint as METHOD, PATH, SUMMARY, SCOPE (--json for machine-readable).pachca api <METHOD> <path> --describe: parameters, body, scope and the equivalent typed command.--spec: the OpenAPI fragment. --docs: the full markdown reference, same as the site.npx -y @pachca/cli api ls.pachca commands --available: the commands whose scope the current token holds, plus those that need no scope. Plan, role and bot-token-only limits are not checked, so a listed command can still be refused..md. https://dev.pachca.com/api/llms.txt is the API-only slice. Any docs page comes as Markdown with .md appended to its URL.Before writing a raw request, confirm three things: the required scope, whether the body is wrapped in a root key, and which pagination group a list method belongs to.
The token decides whose name the request runs under and which data it can reach. Scopes only open methods; they never widen what the owner can see.
| Situation | Token |
|---|---|
| By hand or with an agent on your own machine | Personal, via pachca auth login (browser) |
| Script, utility or one-off export on your behalf | Personal token from Интеграции > API |
| CI, server, cloud worker with no employee present | Bot token |
| Chat bot, notifications, webhook handling, forms | Bot token → pachca-bots |
| A bot that needs one employee's own data | Token by authorization → pachca-oauth |
| An AI app connected to the MCP server | By authorization via browser, or personal → pachca |
email and phone_number come back null for a bot or employee token unless the workspace shows personal data, and always for a multi-guest. Owner and admin tokens always get them. Before a contacts export, read one other employee's record (your own always has them). If it is null, run the export on an admin's personal token rather than reporting the data as missing.Personal token from the UI versus CLI browser login:
| UI token | pachca auth login | |
|---|---|---|
| Scopes | chosen at creation, editable later | whole catalogue cut by your role, frozen at login |
| Lifetime | never expires | one hour, refreshed automatically |
| Value | shown once | never printed |
| Fits | scripts and exports on your behalf | work on this machine |
A UI token carries its owner's rights wherever it is copied. Treat it as a password.
A personal token works only while its owner's access does. Suspend the employee and every request on their tokens answers 403 with errors[].code access_denied. Restoring access brings the tokens back. A deleted employee's tokens never come back. Lower their role and the scopes the new role lacks answer 403 role_forbidden. A job that must keep running after one employee leaves or changes role runs on a bot token: it outlives whoever created it.
Scope rules that surprise:
display_name / display_avatar_url on a message. Another token gets 403 for those two fields and for the bot's own webhook and token methods. The other methods fail with a different code (404, 410, 422), so check the token kind first.bots:read, bots:write, drafts:read, drafts:write. A bot token gets 403.If the user cannot get a token at all: by default only admins create personal tokens, and then employees and multi-guests also cannot log in to the CLI or authorize bots and MCP apps. Once an admin allows it, a multi-guest works with tokens like an employee but cannot create bots or their tokens. Guests cannot create any token under any setting. Changing that is an admin task → pachca-admin.
Before a long job, check what the current token can do: pachca_get_token_info / pachca oauth token-info -o json returns its scopes (the CLI's terminal table leaves them out). In the CLI, pachca auth status shows login method, time left and scopes of a saved profile (it does not read PACHCA_TOKEN); --remote re-reads them from the server.
Authorization: Bearer <token> on every request, with two exceptions: the file upload to direct_url (no auth at all), and the OAuth token exchange and revocation, where the app proves itself with its client credentials (→ pachca-oauth). POST, PUT and PATCH send Content-Type: application/json; charset=utf-8, except avatar uploads (multipart/form-data, a JSON body gets 422; let the HTTP client set the header with its boundary) and the OAuth token methods (application/x-www-form-urlencoded). Check the method.fetch from your site fails with a CORS error. Do not work around it with no-cors (the response stays unreadable) or a public CORS proxy (the token passes through a third party). A token in front-end code is readable by every visitor. A web page sends its requests through your own backend, which holds the token.{"message": {...}}), but not all of them. Check the method.data and a list as a data array plus meta, but not all. POST /uploads returns the upload fields at the top level (read direct_url, not data.direct_url), an added reaction comes without data, and the custom-field list has no meta. Check the method's response schema. Deletes and actions with nothing to return (adding members, pinning, archiving) answer 204 with no body.snake_case and empty values are null. Ids of employees, chats, messages and other entities are integers, but some ids are strings: an audit-log event's id, actor_id and entity_id, a bot event history record's id, the form identifiers (trigger_id, view_id, submit_id) and OAuth client_id. Take an id's type from the method's schema and do not cast it to a number.Cursor-based everywhere, in groups with different meta:
| Group | meta | End of data |
|---|---|---|
| List methods | paginate: next_page, prev_page, has_next, has_prev, always present | has_next: false |
| Search (users, chats, messages) | total, and paginate with next_page and has_next | has_next: false (never on total) |
Employee list with query | paginate: next_page, has_next only | has_next: false |
limit explicitly; the maximum differs by method.limit and cursor only. page, per and offset are not documented parameters, so do not send them. The chat list ignores page and returns the first page on every request, so a loop over page numbers repeats the same chats and never reaches an empty page.limit mid-list, or empty with more to come. Stop on the flag, not on the length.prev_page, never a half-finished walk's next_page.*All() methods and CLI --all walk every page for you. CLI --all stops at a page cap with only a warning on stderr. Without --all a typed CLI list command prints only data, so the next cursor comes only from pachca api GET <path> --query ....Polling for new records (prev_page in newest-first lists, the last next_page in oldest-first ones), batch order, dedup and the --all cap: references/pagination.md.
entity_id), with a cap across all recipients, and a daily cap per sender per chat. Workspace inventory (all chats, all bots of the workspace) and the bot event history have their own per-token caps, far below the general one. Numbers are approximate and change: read https://dev.pachca.com/api/limits.md, do not hard-code them.429 wait at least Retry-After. A Retry-After longer than a minute means a retry will not help (daily chat cap or overload block): stop and hand the error back with that time.5xx on GET, PUT and DELETE (except a 504 timeout, below) with exponential backoff and jitter, at most 3 times. A 5xx, timeout or network error on a POST (a send, a create) may already be applied: look for the message or object first and send again only if it is missing.400, 401, 403, 404, 422: fix the request or the token. The few codes that clear on their own are in the reference.504 with code timeout from search or the employee list with query: the query is too heavy. Do not just repeat it, with or without backoff: the same request will likely time out again. Narrow it first: for message search, fewer chats (chat_ids), a shorter period (created_from, created_to) or an author (user_ids); for chat and employee search, a more specific query or the method's filters; for the employee list, a more specific query.429 for Retry-After and hand one with a Retry-After over a minute straight back. They retry 500, 502, 503 and 504 only on GET, HEAD, OPTIONS, PUT and DELETE, never on a POST, and hand a 504 timeout straight back. The CLI also retries a network error on those methods. So a failed POST (a send, a create) always reaches your code: look for the message or object before sending again. A CLI timeout (PACHCA_TIMEOUT_ERROR) is not retried either.The error shapes, which 403 is which, and the full retry policy: references/errors-and-retries.md.
Upload takes three steps, and step 1 is repeated for every file:
pachca_get_upload_params / pachca files uploads.multipart/form-data to the returned direct_url with every returned field as is (except direct_url itself) and the file as the last field. No Authorization: direct_url is the storage, not Pachca. Success is 204.key, replace ${filename} with the real file name and change nothing else. Pass key, name, file_type, size in files of a new or edited message or draft. A voice file also needs duration_ms and waveform, or the request is rejected (→ pachca-messaging).In the CLI, pachca upload <file> does steps 1 and 2 and returns the key.
name must match the one in key, or you get 422 wrong_params. The base name may differ.403 at step 2: the form does not match what was signed (a field changed, left out or added, the file not last) or the signature expired. Request new parameters and send them exactly as returned. 400: the request went as JSON instead of multipart, or, where the parameters came with bucket, the file is over 4 GB.Download:
url is a direct link that needs no auth, valid up to 7 days from issue and often less. Download right away; on 403 fetch the message again for a fresh link.url points to the Download file method instead: it needs Authorization and files:read. The link itself tells you which case it is.403 confidential_download_denied. The same code comes from any address for a file in which the antivirus found a virus (workspaces with the secure perimeter): another address does not help.id: pachca_download_file / pachca files get <id> --save <path>.Deleting a message, or removing an attachment by edit, erases the file from storage at once, with no trash (a file stays only while another message, such as a forward, still references it). Do either only when the user asked for it, and ask first when the message is a guess.
@pachca/sdk, Python pachca-sdk, Go, Kotlin, Swift, C#. Each has a typed method per API method, auto-pagination (*All(), *_all() in Python, *AllAsync() in C#), retries (429 on every method, 5xx on GET, PUT and DELETE only), typed ApiError and OAuthError, and field names in each language's convention (camelCase in TypeScript, Kotlin and Swift, PascalCase in Go and C#, snake_case kept in Python). The token is passed once, when the client is created.429 handling are already right.POST after a 5xx: a failed send or create comes to your code, and the first attempt may still have gone through. Before sending again, read the chat's latest messages or find the object. Never wrap your own retry around an SDK create.ApiError carries the HTTP status (status in TypeScript; the field name per language is on the SDK page), and an answer with an empty or non-JSON body comes with errors empty. Retry-After is not exposed. Branch on the codes: errors[].code of ApiError (rate_limit, already_exists, invalid, …) and error of OAuthError (invalid_token, insufficient_scope, role_forbidden).rate_limit that reaches your code means the SDK has already given up: the wait is over a minute (daily per-chat cap or overload block), or its retries are spent. Do not catch and retry. Stop that job and resume it later without probing: every attempt during a daily-cap pause lengthens it.await client.close(), client.close(), client.Dispose()).npx -y @pachca/generator --output ./generated --lang <langs> builds it from the live spec. Commit the result and rerun generation in CI as an API compatibility check.PACHCA_TOKEN from the CI or agent secret store. Do not save it to a profile and never commit it. An explicit --profile wins over PACHCA_TOKEN. pachca auth login without --token fails in non-interactive mode: a browser login needs an employee at the screen.CI or PACHCA_PROMPT_DISABLED is set, or with --no-input. Missing required flags are then an error, not a prompt.defaults.output in the CLI config says otherwise, so scripts pass -o json. Data goes to stdout, errors and progress to stderr.--dry-run. Typed commands that send DELETE ask for confirmation in a terminal and refuse without --force in non-interactive mode. Add --force only for a deletion the user asked for. pachca api DELETE ... has no such guard.0 ok, 1 API or runtime error (including a 403 with an errors array, such as a closed chat or a chat rule), 2 bad flags or an API 422, 3 token or scope (401, or a 403 with insufficient_scope / role_forbidden), 4 not found. To tell a token problem from an access refusal, branch on type in the error JSON, not on the HTTP code. A PACHCA_API_ERROR with validation_code access_denied means the token's owner lost access, not the object.Token sources, auth diagnostics, output modes, error JSON and raw pachca api requests: references/cli-scripting.md.
limit.Retry-After as a minimum. Add jitter upward only.5xx may have gone through. Before re-sending, read the chat's latest messages instead of retrying blind.401 is the token itself (missing, unknown, expired, revoked), not a permission.403 role_forbidden: neither a new token nor a re-login helps. Someone with the needed role does the action, or an admin changes the role; Owner-only scopes need the Owner.403 with an errors array (ApiError) is not about scopes. With code access_denied it is the token's owner: a guest, or an employee whose access is suspended or deleted, and a new token will not help. Any other code is not about scopes either. Usually it is the object: a closed chat, a chat rule, a role in the chat or workspace. It can also be a feature the workspace plan lacks (not_authorized, which does not say which case it is: check membership before blaming the plan), display_name / display_avatar_url sent with a token that is not a bot token, or a protected file requested from outside the secure perimeter or a file the antivirus flagged (confidential_download_denied).prev_page: search results cannot be polled by cursor.limit outside the allowed range is clamped silently; a non-integer gives 400 invalid.409 already_exists with the field in errors[].key; a taken tag name gives 400 taken.402: the workspace is suspended because the plan's message limit is used up. Nothing to retry.429 with a plain-text body, not JSON.422 daily_invites_limit, and the request is not applied.--entity-id), the API is snake_case (entity_id).What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
pachca-api, rest-api, pagination, error-handling, file-upload, ci-integration
npx claudepluginhub pachca/openapi --plugin pachca9 skills in this plugin
/pachcaВход в Пачку (Pachca) для агента: подключить агента или MCP-клиента (MCP через браузер или токеном, плагин, CLI), проверить подключение, выбрать токен, разобрать отказ 401/403 инструмента или CLI и отсутствие инструмента (роль, тариф, тип токена, участие в чате). Когда: «подключи Пачку», «настрой MCP Пачки», «войди в Пачку через CLI», «каким токеном подключить агента», «экран входа MCP», «агент получил 403 insufficient_scope», «нет инструмента Пачки (экспорт, журнал аудита)», «что умеет Пачка», "connect Pachca", "set up Pachca MCP", "Pachca CLI login", "which token for my agent or MCP client", "MCP sign-in screen", "MCP tool or CLI returned 401/403", "a Pachca tool is missing". Not for: writing messages → pachca-messaging; search and summaries → pachca-search; administration, who may create tokens → pachca-admin; building a bot → pachca-bots; an agent living in Pachca → pachca-ai-agent; OAuth for employees → pachca-oauth; a token for a script or service, 401/403 in your own code → pachca-api./pachca-adminАдминистрирование пространства Пачки: сотрудники (пригласить, сменить роль, приостановить, удалить), теги и участники чатов, доступ к API и «Все токены», журнал аудита, экспорт, DLP, безопасный контур и шифрование, и что требует владельца, администратора или «Корпорации». Load before a tool call that changes an employee: delete only after a yes to your question. Когда: «пригласи сотрудника», «уволь / удали сотрудника», «сделай администратором», «добавь в тег», «добавь / удали участника чата», «кто в закрытом канале, где я не состою», «доступ к API ограничен», «отзови доступ сотрудника к API», «журнал аудита», «выгрузи переписку», «правило DLP», "invite an employee", "offboard a user", "change role", "add or remove chat members", "let employees create tokens", "export messages". Not for: a missing tool or a general 401/403 → pachca; who is in a tag or chat → pachca-search; writing messages → pachca-messaging; a bot's own token → pachca-bots; an app acting for employees → pachca-oauth; scripts → pachca-api./pachca-ai-agentРешить, бот или MCP, и сделать AI-агента в Пачке в виде бота: его зовут упоминанием в чате или треде либо пишут ему в личный чат, он собирает контекст треда, показывает таймер agent-thinking, отвечает в треде и оформляет длинный ответ карточкой .md. Когда: «AI-агент в Пачке», «агент отвечает по упоминанию в треде», «агент не слышит упоминание», «бот-агент в личных сообщениях», «как агенту собрать контекст треда», «реакция agent-thinking», «длинный ответ агента карточкой .md», «бот или MCP», "AI agent bot in Pachca", "agent replies when mentioned", "agent does not hear a mention", "read thread context", "thinking indicator", "agent reply as an .md card", "bot vs MCP". Not for: working in Pachca from Claude or Cursor through MCP → pachca, pachca-messaging, pachca-search; drafts and scheduled messages (a bot cannot make them), sending a file or report from Claude, Cursor or the CLI → pachca-messaging; webhooks, tokens and settings of any bot → pachca-bots; acting on behalf of an employee → pachca-oauth./pachca-botsБот или интеграция в Пачке: что выбрать (входящий вебхук, бот с событиями, приложение с авторизацией), создание и настройки бота, токены и права, доступ к чатам, приём событий (подпись, повторы, защита от дублей, история событий), кнопки, формы, разворачивание ссылок, витрина. Когда: «сделать бота», «уведомления из CRM или CI в чат», «входящий вебхук», «исходящий вебхук», «бот команд или уведомлений не получает сообщения», «проверить подпись вебхука», «кнопки в сообщении бота», «форма, модальное окно», «превью ссылок, unfurl», «права токена бота», «токен бота утёк», «опубликовать бота в витрине», "build a Pachca bot", "incoming webhook", "outgoing webhook", "bot gets no events", "verify webhook signature", "message buttons", "modal form", "link unfurling", "reissue a leaked bot token". Not for: an AI agent that answers in threads or does not hear a mention → pachca-ai-agent; an app acting for an employee → pachca-oauth; scripts, pagination, 429 → pachca-api; writing messages yourself → pachca-messaging./pachca-messagingПисать в Пачку: разметка, упоминания, куда писать (тред, ответ с цитатой, личный чат), черновик, который отправит сотрудник, пост об изменениях, отложенные и регулярные сообщения в чат, файлы, пересылка, реакции, закрепление, «Важное», правка, удаление, поиск нужного сообщения, когда сначала спросить, лимиты. Когда: «напиши в чат», «отправь сообщение», «ответь в треде», «напиши в личку», «упомяни», «подготовь черновик, я отправлю сам», «напиши пост об изменениях», «запланируй сообщение», «напоминай в канал каждый понедельник», «отправь отчёт файлом .md», «перешли сообщение», «поставь реакцию», «закрепи сообщение», «отметь как важное», «исправь сообщение», "send a message", "reply in the thread", "DM someone", "draft for me to send", "schedule a message", "pin". Not for: search or summaries as the goal, a reminder for an employee → pachca-search; watch a thread, wait for replies → pachca-watch-thread; buttons, forms, clicks → pachca-bots; an AI agent as a bot → pachca-ai-agent; uploads from code → pachca-api./pachca-oauthАвторизация от имени сотрудника в Пачке (OAuth 2.0 с PKCE): когда боту нужен собственный токен сотрудника, вкладка OAuth, адреса возврата и набор прав, ссылка на авторизацию, обмен кода на токен, проверка владельца токена, хранение токена каждого сотрудника, повторная авторизация, отзыв доступа, список проверок перед запуском. Когда: «бот от имени сотрудника», «авторизация от имени сотрудника», «OAuth в Пачке», «client_id и client_secret», «redirect URI», «обменять код на токен», «PKCE», «экран согласия моего бота», «кнопка Предоставить доступ», «сотрудник отозвал доступ», «токен сотрудника вернул 401 или 403», "Pachca OAuth", "act on behalf of a user", "authorization code flow", "exchange code for token", "my bot's OAuth consent screen", "per-user token for my bot". Not for: a bot acting as itself, webhooks, showcase, a leaked bot token → pachca-bots; MCP sign-in, a 401/403 from an MCP tool or the CLI → pachca; your own token in a script → pachca-api; revoking access on the All tokens tab → pachca-admin.Other plugins' skills for the same job