Работа с задачами Linear через API
Ищет и создаёт задачи в Linear, меняет их состояние и исполнителя, комментирует и показывает проекты и циклы.
- Что делает
- Ищет и создаёт задачи в Linear, меняет их состояние и исполнителя, комментирует и показывает проекты и циклы.
- Когда брать
- Когда нужно вывести свои задачи, найти задачу, создать или обновить её, перевести в другое состояние, оставить комментарий или посмотреть проект и цикл в Linear.
- Пример запроса
- Покажи мои открытые задачи в Linear и переведи ENG-123 в «В работе».
- Нужно подключить
- терминал, доступ к Linear
Входит в плагин linear. В Cowork и Claude Code можно поставить плагин целиком.
Как включить
- Скачайте архив и распакуйте его.
- Положите папку
linear-apiв~/.claude/skills/. - Откройте Claude Code и опишите задачу своими словами: Claude подхватит скилл по описанию.
Текст
---
name: linear-api
description: Читай и веди задачи, проекты, циклы, команды, комментарии и метки в Linear. Используй этот скилл всякий раз, когда пользователь хочет вывести свои задачи, найти задачи, создать или обновить задачу, перевести задачу из одного состояния в другое, добавить комментарий, посмотреть проект или цикл, найти команду или спрашивает «что у меня сейчас в Linear», даже если слов «API» или «GraphQL» он не говорит. Также применяй его для любой ссылки linear.app или идентификатора задачи вроде «ENG-123». Всегда начинай с этого скилла, когда работаешь с этим сервисом: его готовые скрипты и рецепты — самый быстрый путь.
---
У Linear единственная точка входа GraphQL — REST API нет. Любое чтение — это query, любая запись — mutation, и всё отправляется на один адрес. Не ищи пути вроде /api/v1/issues: их не существует.
POST https://api.linear.app/graphql
Сосуществуют две системы идентификаторов:
- UUID (
id) — то, что API использует повсюду для поиска и мутаций. - Идентификатор (
identifier, напримерENG-123) — понятный человеку ключ, который виден в интерфейсе. Получить задачу по идентификатору можно черезissue(id: "ENG-123")(Linear принимает оба варианта).
Настройка запросов
Аутентификацию обеспечивает среда выполнения — учётные данные подставляются в исходящие запросы к этому API, так что настраивать ничего не нужно. Не пытайся создавать, выпускать, обновлять или проверять токены и ключи. Переменные с учётными данными нужны только для того, чтобы запросы были составлены правильно; если какая-то из них не задана, подставь любое значение-заглушку. Постоянная ошибка 401/403 означает, что для этого рабочего пространства учётные данные не настроены — сообщи об этом, а не разбирайся с авторизацией.
Linear ждёт учётные данные в заголовке Authorization **как само значение, без префикса Bearer** — отправляй заголовок ровно так, как показано в рецептах ниже.
export LINEAR_API_KEY="placeholder" # injected by the runtime; any value works
Проверка подключения — убедись, что рабочее пространство подключено, и посмотри, чья это настроенная учётная запись:
curl -sS "https://api.linear.app/graphql" \
-H "Authorization: ${LINEAR_API_KEY}" \
-H "Content-Type: application/json" \
-d '{"query": "{ viewer { id name email } }"}' | jq .
Определи вспомогательную функцию один раз за сессию, чтобы не повторять один и тот же шаблонный код. Она принимает строку запроса и необязательный JSON-объект с переменными:
linear_gql() {
local query="$1" vars="${2:-null}"
jq -n --arg q "$query" --argjson v "$vars" '{query:$q, variables:$v}' | \
curl -sS "https://api.linear.app/graphql" \
-H "Authorization: ${LINEAR_API_KEY}" \
-H "Content-Type: application/json" \
-d @-
}
**Всегда проверяй .errors, прежде чем верить .data** — GraphQL возвращает HTTP 200 даже при сбоях:
linear_gql '{ viewer { id } }' | jq 'if .errors then .errors else .data end'
Основные операции
1. Кто я / что назначено на меня
linear_gql '{
viewer {
id name email
assignedIssues(first: 25, orderBy: updatedAt, filter: {state: {type: {nin: ["completed","canceled"]}}}) {
nodes { identifier title state { name type } priority team { key } updatedAt }
}
}
}' | jq '.errors // .data.viewer'
Приоритет: 0 = без приоритета, 1 = срочный (Urgent), 2 = высокий (High), 3 = средний (Medium), 4 = низкий (Low).
2. Поиск задач
linear_gql 'query($q: String!) {
searchIssues(term: $q, first: 25) {
nodes { identifier title state { name } assignee { name } team { key } priority url }
}
}' '{"q": "login crash"}' | jq '.data.searchIssues.nodes'
3. Получить одну задачу (по идентификатору или UUID)
linear_gql 'query($id: String!) {
issue(id: $id) {
id identifier title description url priority estimate
state { name type }
assignee { name email }
creator { name }
team { id key name }
project { id name }
cycle { id number name }
labels { nodes { name color } }
comments(first: 50) { nodes { body user { name } createdAt } }
children { nodes { identifier title state { name } } }
parent { identifier title }
createdAt updatedAt dueDate
}
}' '{"id": "ENG-123"}' | jq '.data.issue'
4. Список задач с фильтрами (scripts/linear_issues.sh)
Выводи задачи через входящий в комплект скрипт (путь указан относительно папки этого скилла): он собирает IssueFilter из флагов, проходит по страницам через pageInfo.endCursor, проверяет .errors в каждом ответе и выдаёт TSV или JSONL.
scripts/linear_issues.sh --team ENG --state-type started --assignee me --limit 100
- Все флаги фильтрации необязательны и комбинируются по «И»:
--team KEY,--state NAME,--state-type TYPE(одно изbacklogunstartedstartedcompletedcanceledtriageduplicate),--assignee EMAIL(илиme— сначала определяется id текущего пользователя),--label NAME. Параметры подключения берутся изLINEAR_API_KEY, см. выше. --query TEXTищет подстроку в заголовке и описании без учёта регистра; вместе с другими флагами он оборачивается вand: [ {…flags}, {or: [title, description]} ].--limit Nограничивает общее число получаемых задач (по умолчанию 50,0= все);--page-size N(максимум 100) задаёт размер страницы;--jsonвыдаёт по одному JSON-объекту на задачу вместо TSV с заголовком (identifier,title,state,assignee,updatedAt,url). Число строк выводится в stderr.- Коды завершения:
0— успех,1— запрос не удался, в ответе GraphQL есть.errorsили неверные аргументы; собственное сообщение API иextensions.codeвыводятся в stderr.
Если скрипт выдаёт ошибку, прочитай его: это обычные curl + jq, — и разбирайся по references/api.md.
Для форм фильтров, которые флаги не покрывают, — операторы сравнения вроде lte/gte, группы or, вложенные some/every — передай объект filter сам через linear_gql:
linear_gql 'query($teamKey: String!) {
issues(first: 50, orderBy: updatedAt, filter: {
team: { key: { eq: $teamKey } }
priority: { lte: 2, gte: 1 }
state: { type: { nin: ["completed", "canceled"] } }
}) { nodes { identifier title priority state { name } assignee { name } } }
}' '{"teamKey": "ENG"}' | jq '.data.issues.nodes'
Полная грамматика фильтров: references/api.md, раздел Filter operators.
5. Создать задачу
Нужен UUID команды (не её ключ). Получи его один раз (рецепт 8), затем:
linear_gql 'mutation($input: IssueCreateInput!) {
issueCreate(input: $input) {
success
issue { id identifier url }
}
}' '{"input": {
"teamId": "TEAM_UUID",
"title": "Crash on empty input",
"description": "Steps to reproduce…\n\n1. …",
"priority": 2,
"assigneeId": "USER_UUID",
"labelIds": ["LABEL_UUID"]
}}' | jq '.data.issueCreate'
description — это Markdown.
6. Обновить задачу (сменить состояние, исполнителя, приоритет и т. д.)
linear_gql 'mutation($id: String!, $input: IssueUpdateInput!) {
issueUpdate(id: $id, input: $input) {
success
issue { identifier state { name } assignee { name } }
}
}' '{"id": "ENG-123", "input": {"stateId": "STATE_UUID", "priority": 1}}' | jq '.data.issueUpdate'
Чтобы перевести задачу в «Done» / «In Progress» и т. п., нужен UUID состояния рабочего процесса, свой у каждой команды (как получить их список, показывает рецепт 8).
7. Прокомментировать задачу
linear_gql 'mutation($input: CommentCreateInput!) {
commentCreate(input: $input) { success comment { id url } }
}' '{"input": {"issueId": "ISSUE_UUID", "body": "Reproduced on main — looking into it."}}' \
| jq '.data.commentCreate'
body — Markdown. issueId должен быть UUID, а не идентификатором — сначала получи его по рецепту 3.
8. Узнать команды, состояния рабочего процесса, метки, участников
Эти UUID понадобятся для мутаций создания и обновления.
linear_gql '{
teams {
nodes {
id key name
states { nodes { id name type position } }
labels { nodes { id name color } }
members { nodes { id name email } }
}
}
}' | jq '.data.teams.nodes'
type состояния ∈ backlog, unstarted, started, completed, canceled, triage, duplicate.
9. Проекты и циклы
linear_gql '{
projects(first: 25, orderBy: updatedAt, filter: {status: {type: {neq: "completed"}}}) {
nodes {
id name description progress targetDate url
status { name type }
lead { name }
teams { nodes { key } }
issues(first: 5) { nodes { identifier title state { name } } }
}
}
}' | jq '.data.projects.nodes'
# current cycle for a team
linear_gql 'query($teamId: String!) {
team(id: $teamId) {
activeCycle {
id number name startsAt endsAt progress
issues { nodes { identifier title state { name } assignee { name } } }
}
}
}' '{"teamId": "TEAM_UUID"}' | jq '.data.team.activeCycle'
У соединений (connections) нет поля totalCount — чтобы посчитать задачи, проходи по страницам и считай nodes либо читай агрегатное поле вроде team { issueCount }. Исключение: ответы поиска (searchIssues, searchProjects, searchDocuments) totalCount возвращают.
10. Недавняя активность во всём рабочем пространстве
linear_gql '{
issues(first: 25, orderBy: updatedAt) {
nodes { identifier title state { name } assignee { name } team { key } updatedAt }
}
}' | jq '.data.issues.nodes'
Постраничная выдача
Каждое списковое поле (issues, nodes, projects, comments и т. д.) — это соединение (connection) с курсорной пагинацией. В ответе есть pageInfo:
linear_gql 'query($cursor: String) {
issues(first: 50, after: $cursor, orderBy: createdAt) {
pageInfo { hasNextPage endCursor }
nodes { identifier title }
}
}' '{"cursor": null}' | jq '.data.issues'
Цикл: передай pageInfo.endCursor как $cursor и остановись, когда hasNextPage равно false. Останавливайся также (и печатай тело ответа), если в ответе есть .errors, либо полученный курсор пуст или равен строке null — иначе ответ с ошибкой зациклит перебор. Всегда ограничивай цикл максимальным числом страниц. first не больше 250 на страницу (по умолчанию 50). Для обратной пагинации используй last / before.
Лимиты запросов
Linear вводит лимиты запросов на пользователя и лимиты сложности (примерно пропорциональны числу узлов, которых может коснуться запрос). Каждый ответ содержит:
X-RateLimit-Requests-Limit / -Remaining / -Reset
X-Complexity
X-RateLimit-Complexity-Limit / -Remaining / -Reset
При аутентификации по API-ключу доступно 5000 запросов в час и 3 000 000 баллов сложности в час (приложения OAuth: 5000 запросов и 2 000 000 баллов на пользователя в час); один запрос не может превышать 10 000 баллов. При превышении Linear возвращает **HTTP 400** (а не 429) с errors[].extensions.code: "RATELIMITED". Заголовки -Reset содержат время в миллисекундах эпохи UTC — это работает и с BSD/macOS, и с GNU date:
sleep $(( reset_ms / 1000 - $(date +%s) + 1 )) # reset_ms from X-RateLimit-Requests-Reset
Чтобы снизить сложность, запрашивай меньше полей, ограничивай first: и не вкладывай глубоко соединения, которые тебе не нужны (например, не выбирай comments у каждой задачи в списке).
Обработка ошибок
GraphQL возвращает HTTP 200 для большинства прикладных ошибок — **всегда проверяй errors[] в теле ответа**.
- **HTTP
400+code: "GRAPHQL_VALIDATION_FAILED"** — не пройдена проверка схемы (неизвестное поле или тип).errors[].messageназывает неверное поле — исправь запрос, а не разбирайся с кавычками. - **HTTP
500+code: "GRAPHQL_VALIDATION_FAILED"— синтаксическая** ошибка GraphQL (несбалансированные скобки и т. п.).errors[].messageпоказывает место разбора. - **HTTP
401** — неверный или отсутствующий API-ключ. ПроверьLINEAR_API_KEY. Персональные ключи передаются вAuthorization:без префиксаBearer. - **HTTP
400+code: "RATELIMITED"** — достигнут лимит запросов или сложности. Подожди доX-RateLimit-…-Reset(эпоха в мс) и повтори; либо упрости запрос (меньше полей, меньшеfirst:). - **
errors[].extensions.code: "INVALID_INPUT"/"INPUT_ERROR"** — проверка не пройдена.messageназывает неверное поле. Частые причины: передан ключ (ENG) там, где нужен UUID, или запрос превысил порог сложности в 10 000 баллов. - **
errors[].extensions.code: "ENTITY_NOT_FOUND"** — такого ID нет или он не виден. Проверь ID. Права API-ключа распространяются на всё рабочее пространство, но учитывают доступ к командам и проектам. - **
errors[].message: "Cannot query field …"** — опечатка или несоответствие схеме. Такого поля нет. Проверь написание; используй интроспекцию (references/api.md).
Мутации возвращают булево поле success, даже когда HTTP и errors в порядке, — проверяй его, прежде чем считать, что запись прошла.
Подробнее
В references/api.md — более полный каталог: все основные типы объектов и их поля, грамматика операторов фильтров, настройка вебхуков, вложенные файлы, реакции, уведомления, избранное, запросы по рабочему пространству и организации, а также интроспекция схемы. Читай его, когда нужен объект или мутация, которых нет выше, или нужна точная форма входных данных для создания и обновления.
Перевод: iiuniversitet. Оригинал: https://github.com/anthropics/claude-tag-plugins/tree/main/linear/skills/linear-api, лицензия Apache-2.0. Изменения: перевод на русский язык.
Оригинал на английском
---
name: linear-api
description: Read and manage Linear issues, projects, cycles, teams, comments, and labels. Use this whenever the user wants to list their issues, search issues, create or update an issue, move an issue between states, add a comment, check a project or cycle, look up a team, or ask "what's on my plate in Linear" — even if they don't say "API" or "GraphQL". Also use it for any linear.app URL or an issue identifier like "ENG-123". Always start from this skill when interacting with this service — its bundled scripts and recipes are the fastest path.
---
Linear has a **single GraphQL endpoint** — there is no REST API. Every read is a `query`, every
write is a `mutation`, and everything goes to one URL. Don't look for `/api/v1/issues`-style paths;
they don't exist.
```
POST https://api.linear.app/graphql
```
Two ID systems coexist:
- **UUID** (`id`) — what the API uses everywhere for lookups and mutations.
- **Identifier** (`identifier`, e.g. `ENG-123`) — the human-readable key shown in the UI. You can
fetch an issue by identifier with `issue(id: "ENG-123")` (Linear accepts both).
## Request setup
Authentication is handled by the runtime — credentials are injected into outbound requests to this
API, so there is nothing to set up. Do not try to create, mint, refresh, or validate tokens or keys.
Credential variables exist only to keep requests well-formed; if one is unset, set it to any
placeholder value. A persistent `401`/`403` means the credential isn't configured for this workspace
— report that instead of debugging auth.
Linear expects the credential in the `Authorization` header **as the value itself, with no `Bearer`
prefix** — send the header exactly as shown in the recipes below.
```bash
export LINEAR_API_KEY="placeholder" # injected by the runtime; any value works
```
**Sanity check** — confirm the workspace is wired up and see who the configured identity is:
```bash
curl -sS "https://api.linear.app/graphql" \
-H "Authorization: ${LINEAR_API_KEY}" \
-H "Content-Type: application/json" \
-d '{"query": "{ viewer { id name email } }"}' | jq .
```
Define a helper once per session so you don't repeat the boilerplate. It takes a query string and an
optional variables JSON object:
```bash
linear_gql() {
local query="$1" vars="${2:-null}"
jq -n --arg q "$query" --argjson v "$vars" '{query:$q, variables:$v}' | \
curl -sS "https://api.linear.app/graphql" \
-H "Authorization: ${LINEAR_API_KEY}" \
-H "Content-Type: application/json" \
-d @-
}
```
**Always check `.errors` before trusting `.data`** — GraphQL returns HTTP `200` even on failures:
```bash
linear_gql '{ viewer { id } }' | jq 'if .errors then .errors else .data end'
```
## Core operations
### 1. Who am I / what's assigned to me
```bash
linear_gql '{
viewer {
id name email
assignedIssues(first: 25, orderBy: updatedAt, filter: {state: {type: {nin: ["completed","canceled"]}}}) {
nodes { identifier title state { name type } priority team { key } updatedAt }
}
}
}' | jq '.errors // .data.viewer'
```
Priority: `0` = no priority, `1` = Urgent, `2` = High, `3` = Medium, `4` = Low.
### 2. Search issues
```bash
linear_gql 'query($q: String!) {
searchIssues(term: $q, first: 25) {
nodes { identifier title state { name } assignee { name } team { key } priority url }
}
}' '{"q": "login crash"}' | jq '.data.searchIssues.nodes'
```
### 3. Get one issue (by identifier or UUID)
```bash
linear_gql 'query($id: String!) {
issue(id: $id) {
id identifier title description url priority estimate
state { name type }
assignee { name email }
creator { name }
team { id key name }
project { id name }
cycle { id number name }
labels { nodes { name color } }
comments(first: 50) { nodes { body user { name } createdAt } }
children { nodes { identifier title state { name } } }
parent { identifier title }
createdAt updatedAt dueDate
}
}' '{"id": "ENG-123"}' | jq '.data.issue'
```
### 4. List and filter issues (`scripts/linear_issues.sh`)
List issues through the bundled script (path is relative to this skill's directory): it builds an
`IssueFilter` from flags, pages through `pageInfo.endCursor`, checks `.errors` on every response,
and emits TSV or JSONL.
```bash
scripts/linear_issues.sh --team ENG --state-type started --assignee me --limit 100
```
- All filter flags are optional and combine (AND): `--team KEY`, `--state NAME`, `--state-type
TYPE` (one of `backlog` `unstarted` `started` `completed` `canceled` `triage` `duplicate`),
`--assignee EMAIL` (or `me` — resolves the viewer id first), `--label NAME`. Instance specifics come from
`LINEAR_API_KEY` above.
- `--query TEXT` does a case-insensitive substring match over title and description; combined with
other flags it's wrapped as `and: [ {…flags}, {or: [title, description]} ]`.
- `--limit N` caps total issues fetched (default 50, `0` = everything); `--page-size N` (max 100)
sets the per-page size; `--json` emits one JSON object per issue instead of TSV with a header
(`identifier`, `title`, `state`, `assignee`, `updatedAt`, `url`). Row counts go to stderr.
- Exit codes: `0` success, `1` request failed, GraphQL `.errors`, or bad arguments — the API's own
message and `extensions.code` are on stderr.
If the script errors, read it — it's plain `curl` + `jq` — and debug against `references/api.md`.
For filter shapes the flags don't cover — comparators like `lte`/`gte`, `or` groups, nested
`some`/`every` — pass the `filter` object yourself with `linear_gql`:
```bash
linear_gql 'query($teamKey: String!) {
issues(first: 50, orderBy: updatedAt, filter: {
team: { key: { eq: $teamKey } }
priority: { lte: 2, gte: 1 }
state: { type: { nin: ["completed", "canceled"] } }
}) { nodes { identifier title priority state { name } assignee { name } } }
}' '{"teamKey": "ENG"}' | jq '.data.issues.nodes'
```
Full filter grammar: `references/api.md`, section Filter operators.
### 5. Create an issue
You need the team's UUID (not its key). Get it once (recipe 8), then:
```bash
linear_gql 'mutation($input: IssueCreateInput!) {
issueCreate(input: $input) {
success
issue { id identifier url }
}
}' '{"input": {
"teamId": "TEAM_UUID",
"title": "Crash on empty input",
"description": "Steps to reproduce…\n\n1. …",
"priority": 2,
"assigneeId": "USER_UUID",
"labelIds": ["LABEL_UUID"]
}}' | jq '.data.issueCreate'
```
`description` is **Markdown**.
### 6. Update an issue (change state, assignee, priority, …)
```bash
linear_gql 'mutation($id: String!, $input: IssueUpdateInput!) {
issueUpdate(id: $id, input: $input) {
success
issue { identifier state { name } assignee { name } }
}
}' '{"id": "ENG-123", "input": {"stateId": "STATE_UUID", "priority": 1}}' | jq '.data.issueUpdate'
```
To move to "Done" / "In Progress" / etc. you need the workflow **state UUID**, which is per-team
(recipe 8 shows how to list them).
### 7. Comment on an issue
```bash
linear_gql 'mutation($input: CommentCreateInput!) {
commentCreate(input: $input) { success comment { id url } }
}' '{"input": {"issueId": "ISSUE_UUID", "body": "Reproduced on main — looking into it."}}' \
| jq '.data.commentCreate'
```
`body` is Markdown. `issueId` must be the UUID, not the identifier — fetch it with recipe 3 first.
### 8. Discover teams, workflow states, labels, members
You'll need these UUIDs for create/update mutations.
```bash
linear_gql '{
teams {
nodes {
id key name
states { nodes { id name type position } }
labels { nodes { id name color } }
members { nodes { id name email } }
}
}
}' | jq '.data.teams.nodes'
```
State `type` ∈ `backlog`, `unstarted`, `started`, `completed`, `canceled`, `triage`, `duplicate`.
### 9. Projects and cycles
```bash
linear_gql '{
projects(first: 25, orderBy: updatedAt, filter: {status: {type: {neq: "completed"}}}) {
nodes {
id name description progress targetDate url
status { name type }
lead { name }
teams { nodes { key } }
issues(first: 5) { nodes { identifier title state { name } } }
}
}
}' | jq '.data.projects.nodes'
# current cycle for a team
linear_gql 'query($teamId: String!) {
team(id: $teamId) {
activeCycle {
id number name startsAt endsAt progress
issues { nodes { identifier title state { name } assignee { name } } }
}
}
}' '{"teamId": "TEAM_UUID"}' | jq '.data.team.activeCycle'
```
Connections have no `totalCount` field — to count issues, paginate and count `nodes`, or read an
aggregate field like `team { issueCount }`. Exception: the search payloads (`searchIssues`,
`searchProjects`, `searchDocuments`) do return `totalCount`.
### 10. Recent activity across the workspace
```bash
linear_gql '{
issues(first: 25, orderBy: updatedAt) {
nodes { identifier title state { name } assignee { name } team { key } updatedAt }
}
}' | jq '.data.issues.nodes'
```
## Pagination
Every list field (`issues`, `nodes`, `projects`, `comments`, …) is a **connection** with cursor
pagination. The response carries `pageInfo`:
```bash
linear_gql 'query($cursor: String) {
issues(first: 50, after: $cursor, orderBy: createdAt) {
pageInfo { hasNextPage endCursor }
nodes { identifier title }
}
}' '{"cursor": null}' | jq '.data.issues'
```
Loop: pass `pageInfo.endCursor` as `$cursor`, stop when `hasNextPage` is `false`. Also stop (and
print the body) if the response has `.errors` or the extracted cursor is empty or the literal string
`null` — otherwise an error envelope loops forever. Always bound the loop with a max page count.
`first` caps at **250** per page (default 50). For reverse pagination use `last` / `before`.
## Rate limits
Linear enforces **per-user request limits** and **complexity limits** (roughly proportional to how
many nodes a query could touch). Every response carries:
```
X-RateLimit-Requests-Limit / -Remaining / -Reset
X-Complexity
X-RateLimit-Complexity-Limit / -Remaining / -Reset
```
API-key auth gets 5,000 requests/hour and 3,000,000 complexity points/hour (OAuth apps: 5,000
requests and 2,000,000 points per user per hour); a single query may not exceed 10,000 points. When
you're over, Linear returns **HTTP `400`** (not `429`) with
`errors[].extensions.code: "RATELIMITED"`. The `-Reset` headers are **UTC epoch milliseconds** —
works on both BSD/macOS and GNU date:
```bash
sleep $(( reset_ms / 1000 - $(date +%s) + 1 )) # reset_ms from X-RateLimit-Requests-Reset
```
To lower complexity, request fewer fields, cap `first:`, and don't deeply nest connections you don't
need (e.g. don't select `comments` on every issue in a list).
## Error handling
GraphQL returns HTTP `200` for most application errors — **always check the body's `errors[]`**.
- **HTTP `400` + `code: "GRAPHQL_VALIDATION_FAILED"`** — Schema validation failed (unknown field/type). `errors[].message` names the bad field — fix the query, don't debug quoting.
- **HTTP `500` + `code: "GRAPHQL_VALIDATION_FAILED"`** — GraphQL **syntax** error (unbalanced braces, etc.). `errors[].message` shows the parse position.
- **HTTP `401`** — Bad or missing API key. Check `LINEAR_API_KEY`. Personal keys go in `Authorization:` with **no** `Bearer` prefix.
- **HTTP `400` + `code: "RATELIMITED"`** — Rate or complexity limit hit. Sleep until `X-RateLimit-…-Reset` (epoch **ms**), retry; or simplify the query (fewer fields, smaller `first:`).
- **`errors[].extensions.code: "INVALID_INPUT"` / `"INPUT_ERROR"`** — Validation failed. `message` names the bad field. Common: passing a key (`ENG`) where a UUID is required, or a query over the 10,000-point complexity cap.
- **`errors[].extensions.code: "ENTITY_NOT_FOUND"`** — ID doesn't exist or not visible. Check the ID. API-key scope is workspace-wide but respects team/project access.
- **`errors[].message: "Cannot query field …"`** — Typo or schema mismatch. Field doesn't exist. Check spelling; use introspection (`references/api.md`).
Mutations return a `success` boolean even when HTTP and `errors` are clean — check it before
assuming the write landed.
## Going deeper
`references/api.md` has the fuller catalog: all major object types and their fields, the filter
operator grammar, webhook config, file attachments, reactions, notifications, favorites,
workspace/organization queries, and schema introspection. Read it when you need an object or
mutation not covered above, or when you need the exact input shape for a create/update.
Источник: anthropics/claude-tag-plugins / linear / linear-api ↗. Ссылка проверена 2026-10-10.