Linear
Linear
Connect Linear so your agents can review your workspace: find and search issues by team, status, assignee, label, priority or date, read their descriptions, sub-issues and comments, and follow teams, projects, cycles, statuses and labels.
With write access, agents can also file issues, change their status, assignee, labels, priority and other details, and comment or reply on issues. Linear notifies the people subscribed to those issues.
Linear's own permissions still apply: agents see only the teams your account or API key can access. Your credentials stay on Houston's server.
Setup instructions
Setup instructions
Connect Linear
- Open Security & access and create a Personal API key. Grant Read, or Read and Write, and select teams.
- In Houston, choose Personal API key, paste it, select the matching Access level and save.
If key creation is disabled, ask an admin to enable Member API keys under Administration → API. API key guide.
Advanced
Your own OAuth app
- In Houston, select Connect with Linear and copy OAuth callback URL.
- As a Linear admin, create an OAuth app and register that exact URL under Callback URLs. Enable Public to allow other workspaces.
- Enter OAuth client ID and OAuth client secret in Houston, then select Continue with Linear, choose the workspace and allow access.
Each connection has its own callback. Read requests read; Write requests
write, which includes reading. Reauthorize after changing access. For an API key,
create a replacement with the new permissions. Check key team limits if data is
missing. OAuth guide.
Files
Files
connector.luau
-- Linear GraphQL API. Arguments and results keep Linear's native field names. type Options = {[string]: any} type Operation = {field: string, args: {string}, select: string, connection: boolean?, page: string?, write: boolean?, about: string} local API = "https://api.linear.app/graphql" local DOCS = "https://linear.app/developers/graphql" local NULL = json.decode("null") local MAX_PAGE = 250 local MAX_DOCUMENT = 64 * 1024 local MAX_URL = 8 * 1024 -- Read connections send queries with GET, which Linear refuses for mutations (HTTP 405), -- and the manifest allows POST only with write access. local WRITES = houston.allows("data:write") -- Fields each operation selects; with write access graphql() reaches the others. local TEAM_REF = "team { id key name }" local PERSON = "{ id name displayName }" local USER = "id name displayName email active admin guest url timezone createdAt" local TEAM = "id key name displayName description icon color timezone cyclesEnabled createdAt updatedAt archivedAt" local STATE = "id name type color position description " .. TEAM_REF local LABEL = "id name color description isGroup parent { id name } " .. TEAM_REF .. " createdAt updatedAt archivedAt" local PROJECT = "id name slugId url description icon color priority priorityLabel progress health startDate targetDate startedAt completedAt " .. "canceledAt createdAt updatedAt archivedAt status { id name type } lead " .. PERSON .. " teams(first: 10) { nodes { id key name } }" local CYCLE = "id number name description startsAt endsAt completedAt isActive isNext isPrevious progress " .. TEAM_REF .. " createdAt updatedAt archivedAt" local ISSUE = "id identifier number title priority priorityLabel estimate dueDate url branchName createdAt updatedAt startedAt completedAt " .. "canceledAt archivedAt state { id name type } " .. TEAM_REF .. " assignee " .. PERSON .. " creator " .. PERSON .. " project { id name } cycle { id number name } parent { id identifier title } labels(first: 10) { nodes { id name } }" local COMMENT = "id body url createdAt updatedAt editedAt resolvedAt parentId user " .. PERSON .. " issue { id identifier title }" -- Arguments of a Linear connection field, filtered by the given filter type. local function list(filter: string, ...: string): {string} local args = {"filter: " .. filter, "first: Int", "after: String", "last: Int", "before: String", "includeArchived: Boolean", "orderBy: PaginationOrderBy"} for _, extra in {...} do table.insert(args, extra) end return args end -- Query and Mutation fields of Linear's public schema (packages/sdk/src/schema.graphql), checked -- on 2026-10-27. local operations: {[string]: Operation} = { getViewer = {field = "viewer", args = {}, select = USER .. " organization { id name urlKey }", about = "You, with your workspace's id, name and urlKey."}, listUsers = {field = "users", args = list("UserFilter", "includeDisabled: Boolean"), select = USER, connection = true, about = "Workspace members. Filter by name, displayName, email or isMe, as {email={eq='[email protected]'}}."}, listTeams = {field = "teams", args = list("TeamFilter"), select = TEAM, connection = true, about = "Teams you can access."}, getTeam = {field = "team", args = {"id: String!"}, select = TEAM, about = "A team."}, listWorkflowStates = {field = "workflowStates", args = list("WorkflowStateFilter"), select = STATE, connection = true, about = "Issue statuses, as {team={key={eq='ENG'}}}. type: triage, backlog, unstarted, started, completed or canceled."}, listLabels = {field = "issueLabels", args = list("IssueLabelFilter"), select = LABEL, connection = true, about = "Issue labels. Workspace labels have team null; group labels (isGroup) hold child labels."}, listProjects = {field = "projects", args = list("ProjectFilter"), select = PROJECT, connection = true, about = "Projects, as {status={type={eq='started'}}} or {accessibleTeams={some={key={eq='ENG'}}}}."}, getProject = {field = "project", args = {"id: String!"}, select = PROJECT .. " content", about = "A project by id or slugId, with its content in Markdown."}, listCycles = {field = "cycles", args = list("CycleFilter"), select = CYCLE, connection = true, about = "Cycles, as {team={key={eq='ENG'}}, isActive={eq=true}}."}, getCycle = {field = "cycle", args = {"id: String!"}, select = CYCLE, about = "A cycle."}, listIssues = {field = "issues", args = list("IssueFilter"), select = ISSUE, connection = true, about = "Issues, without descriptions; see Filters."}, searchIssues = {field = "searchIssues", args = list("IssueFilter", "term: String!", "teamId: String", "includeComments: Boolean"), select = ISSUE, connection = true, page = "totalCount", about = "Full-text search over titles and descriptions (and comments with includeComments), with totalCount."}, getIssue = {field = "issue", args = {"id: String!"}, select = ISSUE .. " description children(first: 50) { nodes { id identifier title state { id name type } } pageInfo { hasNextPage } }", about = "An issue by id or identifier such as ENG-123, with its Markdown description and first 50 sub-issues; when children.pageInfo.hasNextPage, list the rest with listIssues({filter={parent={id={eq=issue.id}}}})."}, listComments = {field = "comments", args = list("CommentFilter"), select = COMMENT, connection = true, about = "Comments in Markdown, as {issue={id={eq=issue.id}}}. parentId marks a reply."}, createIssue = {field = "issueCreate", args = {"input: IssueCreateInput!"}, select = "success issue { " .. ISSUE .. " }", write = true, about = "input {teamId, title, description?, stateId?, assigneeId?, priority?, labelIds?, projectId?, cycleId?, parentId?, dueDate?, estimate?}. Returns {success, issue}."}, updateIssue = {field = "issueUpdate", args = {"id: String!", "input: IssueUpdateInput!"}, select = "success issue { " .. ISSUE .. " }", write = true, about = "input: the fields to change, such as stateId, assigneeId (null unassigns), priority, labelIds (replaces), addedLabelIds, removedLabelIds, title or description."}, createComment = {field = "commentCreate", args = {"input: CommentCreateInput!"}, select = "success comment { " .. COMMENT .. " }", write = true, about = "input {issueId, body (Markdown), parentId? to reply}. Returns {success, comment}."}, } local function fail(name: string, status: number, retryable: boolean, message: string): never return houston.fail({operation = name, layer = "upstream", upstream_status = status, retryable = retryable, message = message}) end -- Linear errors are {errors: [{message, extensions: {code, userPresentableMessage?}}]}, with HTTP -- 400 for invalid queries, 401 for credentials and 429 (code RATELIMITED) with Retry-After and -- the hourly windows' reset times in Unix milliseconds. local RESETS = {"retry-after", "x-ratelimit-requests-reset", "x-ratelimit-complexity-reset"} local function failed(name: string, response: HttpResponse, body: any, raw: string): never local status = response.statusCode local retryable = status == 429 or status >= 500 local messages: {string} = {} if type(body) == "table" and type(body.errors) == "table" then for index, item in body.errors do if type(index) ~= "number" or index > 3 or type(item) ~= "table" then continue end local extensions = if type(item.extensions) == "table" then item.extensions else {} local code = if type(extensions.code) == "string" then extensions.code .. ": " else "" local text = if type(extensions.userPresentableMessage) == "string" then extensions.userPresentableMessage else item.message if extensions.code == "RATELIMITED" then retryable = true end table.insert(messages, code .. string.sub(if type(text) == "string" then text else "error", 1, 600)) end end local message = "Linear HTTP " .. tostring(status) .. ": " .. (if #messages > 0 then table.concat(messages, "; ") else string.sub(raw, 1, 600)) if retryable then for _, header in RESETS do local values = response.headers[header] if values and values[1] then message ..= "; " .. header .. " " .. string.sub(values[1], 1, 100) end end end return fail(name, status, retryable, message) end -- Linear's whole response, {data, errors?}. GraphQL can answer data with errors, such as for -- nested items the caller cannot see; errors without data fail. local function execute(name: string, document: string, variables: Options, operationName: string?): (any, HttpResponse) local headers: HttpHeaders = {Accept = {"application/json"}} local call: HttpRequest if WRITES then headers["Content-Type"] = {"application/json"} call = {method = "POST", url = API, headers = headers, body = json.encode({query = document, variables = variables, operationName = operationName})} else -- Linear's CSRF protection needs this header on GET requests. headers["apollo-require-preflight"] = {"true"} local query = "?query=" .. url.encode(document) if next(variables) ~= nil then query ..= "&variables=" .. url.encode(json.encode(variables)) end assert(#API + #query <= MAX_URL, "The query is too large for a read-only connection, which sends it in the URL; narrow the filter") call = {method = "GET", url = API .. query, headers = headers} end local response = await(http.request(call)) local success = response.statusCode >= 200 and response.statusCode < 300 local raw: string = await(if success then response.body:readAll() else response.body:readPrefix(16 * 1024)) local ok, body = pcall(json.decode, raw) if not ok then body = nil end if not success then failed(name, response, body, raw) end if type(body) ~= "table" or type(body.data) ~= "table" then if type(body) == "table" and type(body.errors) == "table" and #body.errors > 0 then failed(name, response, body, raw) end fail(name, response.statusCode, false, "Linear returned an invalid GraphQL response") end return body, response end local function options(input: Options?): Options if input == nil then return {} end assert(type(input) == "table", "opts must be an object") for key in input do assert(type(key) == "string", "opts must have named fields") end return table.clone(input) end local function object(value: any, field: string) assert(type(value) == "table", field .. " must be an object") local key = next(value) -- Only an empty table can be json.decode('[]'); others show their keys. assert(if key == nil then json.encode(value) ~= "[]" else type(key) == "string", field .. " must be an object, not an array") end -- The GraphQL variable an argument receives, checked against its declared base type. local function variable(value: any, field: string, base: string) if base == "Int" then assert(type(value) == "number" and value == math.floor(value) and value >= 1 and value <= MAX_PAGE, field .. " must be an integer from 1 to " .. MAX_PAGE) elseif base == "String" then assert(type(value) == "string" and value ~= "", field .. " must be a nonempty string") elseif base == "Boolean" then assert(type(value) == "boolean", field .. " must be true or false") elseif base == "PaginationOrderBy" then assert(value == "createdAt" or value == "updatedAt", field .. " must be 'createdAt' or 'updatedAt'") else object(value, field) end end -- Argument declarations such as "first: Int" or "id: String!", parsed once per operation. type Parameter = {field: string, kind: string, base: string, required: boolean} local function parameters(operation: Operation): {Parameter} local parsed: {Parameter} = {} for _, arg in operation.args do local field, kind = string.match(arg, "^(%w+): (.+)$") assert(field and kind, "invalid argument declaration " .. arg) table.insert(parsed, {field = field, kind = kind, base = (string.gsub(kind, "!$", "")), required = string.sub(kind, -1) == "!"}) end return parsed end local function document(name: string, operation: Operation, params: {Parameter}): string local definitions: {string}, uses: {string} = {}, {} for _, param in params do table.insert(definitions, "$" .. param.field .. ": " .. param.kind) table.insert(uses, param.field .. ": $" .. param.field) end local selection = operation.select if operation.connection then selection = "nodes { " .. selection .. " } pageInfo { hasNextPage endCursor }" .. (if operation.page then " " .. operation.page else "") end local head = (if operation.write then "mutation " else "query ") .. name if #definitions > 0 then head ..= "(" .. table.concat(definitions, ", ") .. ")" end local field = operation.field if #uses > 0 then field ..= "(" .. table.concat(uses, ", ") .. ")" end return head .. " { " .. field .. " { " .. selection .. " } }" end local function signature(params: {Parameter}): string local fields: {string} = {} for _, param in params do table.insert(fields, if param.required then param.field else param.field .. "?") end return if #fields == 0 then "()" else "({" .. table.concat(fields, ", ") .. "})" end local function run(name: string, operation: Operation, params: {Parameter}, source: string, input: Options?): any local args = options(input) local variables: Options = {} for _, param in params do local value = args[param.field] args[param.field] = nil if value == nil or value == NULL then assert(not param.required, param.field .. " is required") else variable(value, param.field, param.base) variables[param.field] = value end end local unknown = next(args) assert(unknown == nil, name .. " has no option " .. tostring(unknown)) local body, response = execute(name, source, variables) local result = body.data[operation.field] if type(body.errors) == "table" and #body.errors > 0 then -- Keep a partial result, such as a created issue with an unreadable nested field. if type(result) ~= "table" then return failed(name, response, body, "") end result.errors = body.errors end return result end local exports: {[string]: any} = {} local signatures: {[string]: string} = {} for name, operation in operations do if not operation.write or WRITES then local params = parameters(operation) local source = document(name, operation, params) signatures[name] = signature(params) exports[name] = function(input: Options?): any return run(name, operation, params, source, input) end end end local function graphql(input: Options?): any local args = options(input) local source, variables, operationName = args.query, args.variables, args.operationName args.query, args.variables, args.operationName = nil, nil, nil local unknown = next(args) assert(unknown == nil, "graphql has no option " .. tostring(unknown)) assert(type(source) == "string" and string.find(source, "%S") ~= nil, "query must be a GraphQL document") assert(#source <= MAX_DOCUMENT, "query must be at most " .. MAX_DOCUMENT .. " bytes") if variables == nil or variables == NULL then variables = {} else object(variables, "variables") end assert(operationName == nil or (type(operationName) == "string" and string.match(operationName, "^[_%a][_%w]*$")), "operationName must be a GraphQL name") return (execute("graphql", source, variables, operationName)) end -- Arbitrary documents can read webhook signing secrets and SSO settings, so they need write access. if WRITES then exports.graphql = graphql end exports.help = function(): string local names: {string} = {} for name in operations do if exports[name] then table.insert(names, name) end end table.sort(names) local lines = { "Linear GraphQL API (" .. DOCS .. "). Every function takes one named options object with Linear's field names; ? marks optional fields. Results are Linear's JSON for the queried field, without the data wrapper; when Linear also reports errors, such as for nested items you cannot see, the result carries them as errors. In arguments, pass json.decode('null') to clear a field (such as assigneeId) and json.decode('[]') for an empty list: nil omits the field and {} is an object. Connector calls return completed values: use them directly, without await.", "Lists return one page {nodes, pageInfo={hasNextPage, endCursor}}: first is 1.." .. MAX_PAGE .. " (default 50); pass pageInfo.endCursor as after while hasNextPage. orderBy: createdAt (default) or updatedAt. includeArchived=true adds archived items.", "Filters use Linear's comparators: eq, neq, in, nin, lt, lte, gt, gte, null, contains, containsIgnoreCase, startsWith; and and/or arrays. Write the Luau keywords in, and, or as ['in'], ['and'], ['or']. Relations nest: {team={key={eq='ENG'}}, state={type={['in']={'unstarted', 'started'}}}, assignee={isMe={eq=true}}, labels={some={name={eq='Bug'}}}, priority={lte=2}}. Dates take ISO 8601 or durations relative to now, as {updatedAt={gt='-P2W'}}.", "ids are UUIDs; getIssue and updateIssue also take identifiers such as ENG-123 and getProject a slugId. Issues show their first 10 labels and projects their first 10 teams. priority: 0 none, 1 urgent, 2 high, 3 medium, 4 low. Descriptions and comment bodies are Markdown.", } for _, name in names do local operation = operations[name] table.insert(lines, name .. signatures[name] .. ": " .. operation.about) end table.insert(lines, "Examples: local me = linear.getViewer(); local page = linear.listIssues({filter={assignee={isMe={eq=true}}, state={type={nin={'completed', 'canceled'}}}}, first=50}); linear.getIssue({id='ENG-123'}); linear.listComments({filter={issue={id={eq=issue.id}}}}).") if WRITES then table.insert(lines, "graphql({query, variables?, operationName?}): any Linear query or mutation document, returning Linear's response {data, errors?}, for fields and operations not listed above, such as attachments, project updates, issue relations or archiving. Schema: https://studio.apollographql.com/public/Linear-API. Example: linear.graphql({query='query($id: String!) { issue(id: $id) { attachments { nodes { title url } } } }', variables={id='ENG-123'}}).") table.insert(lines, "Writes: find teamId with listTeams, stateId with listWorkflowStates, label ids with listLabels and user ids with listUsers. Linear notifies subscribers of new issues, assignments and comments. Houston retries an HTTP 429 at most twice when Retry-After is 5 seconds or less, and nothing else: after any failed write, read the issue again before repeating it, since Linear may have applied it.") else table.insert(lines, "This read-only connection sends queries with GET, which Linear refuses for mutations.") end table.insert(lines, "Errors report the HTTP status with Linear's error codes and messages; RATELIMITED (HTTP 429) is retryable and reports Retry-After and the reset times of the hourly windows. Linear limits API keys to 2,500 requests and 3,000,000 complexity points an hour per user (OAuth apps 5,000 and 2,000,000). A single query may cost at most 10,000 points, counting each list at its first value, so lower first when results nest lists. Your Linear permissions, team access and the API key's or app's permissions still apply.") return table.concat(lines, "\n") end return exportshouston.json
{ "schema_version": 2, "name": "Linear", "files": [ "connector.luau" ], "icon": "icon.svg", "access": [ { "name": "data", "label": "Access", "levels": [ { "value": "read", "label": "Read" }, { "value": "write", "label": "Write" } ], "default": "read" } ], "config": { "client_id": { "label": "OAuth client ID", "order": 1, "type": "string" }, "client_secret": { "label": "OAuth client secret", "order": 2, "type": "secret" } }, "auth": { "token": { "type": "manual", "label": "Personal API key", "order": 1, "config": { "token": { "label": "Personal API key", "required": true, "type": "secret" } } }, "oauth": { "type": "oauth2", "label": "Connect with Linear", "brand": "linear", "order": 2, "authorize_url": "https://linear.app/oauth/authorize", "token_url": "https://api.linear.app/oauth/token", "client_auth": "body", "pkce": "S256", "client_id": "{{config.client_id}}", "client_secret": "{{config.client_secret}}", "require_refresh": true, "scopes": [ { "if": "{{ is access.data \"read\" }}", "values": [ "read" ] }, { "if": "{{ is access.data \"write\" }}", "values": [ "write" ] } ], "account": { "url": "https://api.linear.app/graphql?query=%7Bviewer%7Bemail%7D%7D", "headers": { "Authorization": { "value": "Bearer {{auth.oauth.access_token}}" }, "apollo-require-preflight": { "value": "true" } }, "label": "/data/viewer/email" } } }, "proxy": [ { "if": "{{ isDefined auth.token }}", "match": { "protocol": "http", "host": [ "api.linear.app" ], "method": [ "GET" ], "path": [ "/graphql" ] }, "action": { "headers": { "set": { "Authorization": "{{auth.token.token}}" } } } }, { "if": "{{ isDefined auth.oauth }}", "match": { "protocol": "http", "host": [ "api.linear.app" ], "method": [ "GET" ], "path": [ "/graphql" ] }, "action": { "headers": { "set": { "Authorization": "Bearer {{auth.oauth.access_token}}" } } } }, { "if": "{{ and (allows access.data \"write\") (isDefined auth.token) }}", "match": { "protocol": "http", "host": [ "api.linear.app" ], "method": [ "POST" ], "path": [ "/graphql" ] }, "action": { "headers": { "set": { "Authorization": "{{auth.token.token}}" } } } }, { "if": "{{ and (allows access.data \"write\") (isDefined auth.oauth) }}", "match": { "protocol": "http", "host": [ "api.linear.app" ], "method": [ "POST" ], "path": [ "/graphql" ] }, "action": { "headers": { "set": { "Authorization": "Bearer {{auth.oauth.access_token}}" } } } } ] }icon.svg
README.md
--- description: Review Linear issues, projects and cycles, and file or update issues and comments. --- # Linear Connect Linear so your agents can review your workspace: find and search issues by team, status, assignee, label, priority or date, read their descriptions, sub-issues and comments, and follow teams, projects, cycles, statuses and labels. With write access, agents can also file issues, change their status, assignee, labels, priority and other details, and comment or reply on issues. Linear notifies the people subscribed to those issues. Linear's own permissions still apply: agents see only the teams your account or API key can access. Your credentials stay on Houston's server. [Connect Linear](SETUP.md).SETUP.md
# Connect Linear 1. Open [Security & access](https://linear.app/settings/account/security) and create a **Personal API key**. Grant **Read**, or **Read** and **Write**, and select teams. 2. In Houston, choose **Personal API key**, paste it, select the matching **Access** level and save. If key creation is disabled, ask an admin to enable **Member API keys** under **Administration → API**. [API key guide](https://linear.app/docs/api-and-webhooks#api-keys). ## Advanced ### Your own OAuth app 1. In Houston, select **Connect with Linear** and copy **OAuth callback URL**. 2. As a Linear admin, [create an OAuth app](https://linear.app/settings/api/applications/new) and register that exact URL under **Callback URLs**. Enable **Public** to allow other workspaces. 3. Enter **OAuth client ID** and **OAuth client secret** in Houston, then select **Continue with Linear**, choose the workspace and allow access. Each connection has its own callback. **Read** requests `read`; **Write** requests `write`, which includes reading. Reauthorize after changing access. For an API key, create a replacement with the new permissions. Check key team limits if data is missing. [OAuth guide](https://linear.app/developers/oauth-2-0-authentication).tests
authentication.luau
return { contract = function(m) m.authentication({ { auth = {}, config = { client_id = "synthetic-public-client", client_secret = "synthetic-client-secret", }, endpoint = { "GET", "https://api.linear.app/graphql" }, expected = "Bearer synthetic-oauth-token", header = "Authorization", method = "oauth", oauth = true, publisher = {}, scopes = true, }, { auth = { token = "synthetic-method-secret" }, config = {}, endpoint = { "GET", "https://api.linear.app/graphql" }, expected = "synthetic-method-secret", header = "Authorization", method = "token", publisher = {}, }, }) end, }errors.luau
return { scenario = {publisher = {}, access = {data = "write"}, config = {}, auth_method = "token", auth_config = {token = "fixture-key"}}, configure = function() calls = 0 status = 200 payload = "{}" responseHeaders = {} http = {request = function(req) calls += 1 assert(req.method == "POST" and req.headers.Authorization == nil) return fixture.operation({statusCode = status, headers = responseHeaders, body = fixture.reader(payload)}) end} end, run = function(linear) local function upstream(code, body, headers, expected, unexpected) status, payload, responseHeaders = code, body, headers local before = calls local ok, err = pcall(function() linear.updateIssue({id = "ENG-1", input = {priority = 1}}) end) for _, text in expected do assert(not ok and string.find(tostring(err), text, 1, true), "missing " .. text .. " in " .. tostring(err)) end for _, text in unexpected or {} do assert(not string.find(tostring(err), text, 1, true), "unexpected " .. text .. " in " .. tostring(err)) end assert(calls == before + 1, "failed write was retried") end upstream(401, '{"errors":[{"message":"Authentication required, not authenticated","extensions":{"type":"authentication error","code":"AUTHENTICATION_ERROR","statusCode":401,"userError":true,"userPresentableMessage":"You need to authenticate to access this operation."}}]}', {}, {"Linear HTTP 401", "AUTHENTICATION_ERROR: You need to authenticate", '"retryable":false'}, {"not authenticated"}) upstream(400, '{"errors":[{"message":"Cannot query field \\"nosuchfield\\" on type \\"Issue\\".","extensions":{"code":"GRAPHQL_VALIDATION_FAILED","type":"graphql error"}}]}', {}, {"Linear HTTP 400", "GRAPHQL_VALIDATION_FAILED", "nosuchfield", '"retryable":false'}) upstream(429, '{"errors":[{"message":"Rate limit exceeded","extensions":{"code":"RATELIMITED"}}]}', {["retry-after"] = {"42"}, ["x-ratelimit-requests-reset"] = {"1793145600000"}}, {"Linear HTTP 429", "RATELIMITED", "retry-after 42; x-ratelimit-requests-reset 1793145600000", '"retryable":true'}) -- Linear can answer 200 with errors and no data; a rate-limit code is retryable at any status. upstream(200, '{"data":null,"errors":[{"message":"Entity not found: Issue","extensions":{"code":"INVALID_INPUT","userPresentableMessage":"Could not find referenced Issue."}},{"message":"busy","extensions":{"code":"RATELIMITED"}}]}', {}, {"Linear HTTP 200", "INVALID_INPUT: Could not find referenced Issue.; RATELIMITED: busy", '"retryable":true'}) upstream(400, json.encode({errors = {{message = string.rep("x", 5000), extensions = {code = "INVALID_INPUT"}}, {message = "b"}, {message = "c"}, {message = "fourth"}}}), {}, {"INVALID_INPUT: xxx", "; b; c"}, {"fourth", string.rep("x", 601)}) upstream(502, "<html>Bad gateway</html>", {}, {"Linear HTTP 502: <html>Bad gateway</html>", '"retryable":true'}) upstream(200, '{"errors":[]}', {}, {"invalid GraphQL response"}) upstream(200, '{"data":{"issueUpdate":null},"errors":[{"message":"Forbidden"}]}', {}, {"Linear HTTP 200: Forbidden", '"retryable":false'}) upstream(200, '{"data":{"issueUpdate":null},"errors":[{"message":"Slow down","extensions":{"code":"RATELIMITED"}}]}', {}, {"RATELIMITED: Slow down", '"retryable":true'}) end, }manifest.luau
return { contract = function(m) -- TestLinearScopesAndAccessRoutes do local api = "https://api.linear.app/graphql" for _, method in { "token", "oauth" } do for _, access in { "read", "write" } do local config = {} local input = { token = "lin_api_fixture" } if method == "oauth" then config["client_id"], config["client_secret"], input = "fixture-client", "fixture-secret", nil end local r, err = m.resolve(nil, config, input, method, { data = access }) assert(not err, tostring(err)) local authorization = "lin_api_fixture" if method == "oauth" then local scopes = { "read" } if access == "write" then scopes = { "write" } end if not (m.equal(r.Scopes, scopes)) then m.fail("access=%s scopes %s", access, r.Scopes) end authorization = "Bearer lin_oauth_fixture" r.Context.Auth["oauth"].access_token = "lin_oauth_fixture" end m.routes( r, authorization, true, { "GET " .. api .. "?query=%7Bviewer%7Bid%7D%7D", "GET " .. api } ) m.routes(r, authorization, (access == "write"), { "POST " .. api }) m.routes(r, authorization, false, { "PUT " .. api, "DELETE " .. api, "POST https://api.linear.app/oauth/token", "POST https://api.linear.app/oauth/revoke", "GET https://api.linear.app/graphql/x", "GET https://linear.app/graphql", "GET https://uploads.linear.app/o1/file", "GET https://api.linear.app.example.com/graphql", "GET http://api.linear.app:8080/graphql", }) m.rejectOverrides(r, { "GET " .. api }) end end end end, }oauth_read_only.luau
return { scenario = {publisher = {}, access = {data = "read"}, config = {client_id = "fixture-client", client_secret = "fixture-secret"}, auth_method = "oauth", auth_config = {}}, configure = function() requests = {} http = {request = function(req) table.insert(requests, req) return fixture.operation({statusCode = 200, headers = {}, body = fixture.reader('{"data":{"workflowStates":{"nodes":[{"id":"s1","type":"started"}],"pageInfo":{"hasNextPage":false,"endCursor":"c1"}}}}')}) end} end, run = function(linear) for _, name in {"createIssue", "updateIssue", "createComment", "graphql"} do assert(linear[name] == nil, "read-only leaked " .. name) end local states = linear.listWorkflowStates({filter = {team = {key = {eq = "ENG"}}}}) local request = requests[1] assert(#requests == 1 and request.method == "GET" and request.body == nil and request.headers.Authorization == nil) assert(string.find(request.url, "^https://api%.linear%.app/graphql%?query=query%%20listWorkflowStates%%28"), request.url) assert(string.find(request.url, "&variables=%7B%22filter%22%3A%7B%22team%22%3A%7B%22key%22%3A%7B%22eq%22%3A%22ENG%22%7D%7D%7D%7D", 1, true), request.url) assert(states.nodes[1].type == "started") end, }read_only.luau
return { scenario = {publisher = {}, config = {}, auth_method = "token", auth_config = {token = "fixture-key"}}, configure = function() requests = {} payload = "{}" http = {request = function(req) table.insert(requests, req) return fixture.operation({statusCode = 200, headers = {}, body = fixture.reader(payload)}) end} end, run = function(linear) local API = "https://api.linear.app/graphql" local NULL = json.decode("null") local function last() return requests[#requests] end local function sent(): (string, any) local query = string.match(last().url, "^https://api%.linear%.app/graphql%?query=([^&]+)") assert(query, "not a GET query: " .. last().url) local variables = string.match(last().url, "&variables=(.+)$") local function decode(value: string): string return (string.gsub(value, "%%(%x%x)", function(hex: string) return string.char(tonumber(hex, 16) :: number) end)) end return decode(query), if variables then json.decode(decode(variables)) else nil end local function same(a: any, b: any): boolean if type(a) ~= "table" or type(b) ~= "table" then return a == b end for key, value in a do if not same(value, b[key]) then return false end end for key in b do if a[key] == nil then return false end end return true end local function rejected(fn, expected) local before = #requests local ok, err = pcall(fn) assert(not ok and string.find(tostring(err), expected, 1, true), "wrong validation error: " .. tostring(err)) assert(#requests == before, "invalid input reached Linear") end local names = {} for name in linear do table.insert(names, name) end table.sort(names) assert(table.concat(names, ",") == "getCycle,getIssue,getProject,getTeam,getViewer,listComments,listCycles,listIssues,listLabels,listProjects,listTeams,listUsers,listWorkflowStates,searchIssues", "wrong read-only surface: " .. table.concat(names, ",")) assert(#requests == 0, "initialization reached Linear") payload = '{"data":{"viewer":{"id":"u1","name":"Ada","email":"[email protected]","organization":{"id":"o1","urlKey":"acme"},"timezone":null}}}' local me = linear.getViewer() local query, variables = sent() assert(last().method == "GET" and last().body == nil) assert(last().headers.Accept[1] == "application/json" and last().headers["apollo-require-preflight"][1] == "true") assert(last().headers.Authorization == nil and last().headers["Content-Type"] == nil) assert(string.find(query, "^query getViewer { viewer { id name displayName email ") and variables == nil, query) assert(me.email == "[email protected]" and me.organization.urlKey == "acme" and me.timezone == NULL) payload = '{"data":{"issues":{"nodes":[{"id":"i1","identifier":"ENG-1","labels":{"nodes":[]}}],"pageInfo":{"hasNextPage":true,"endCursor":"c2"}}}}' local filter = {assignee = {isMe = {eq = true}}, state = {type = {nin = {"completed", "canceled"}}}} local page = linear.listIssues({filter = filter, first = 50, after = "c1", orderBy = "updatedAt"}) query, variables = sent() assert(string.find(query, "^query listIssues%(%$filter: IssueFilter, %$first: Int, %$after: String, %$last: Int, %$before: String, %$includeArchived: Boolean, %$orderBy: PaginationOrderBy%) { issues%(filter: %$filter, first: %$first, after: %$after, last: %$last, before: %$before, includeArchived: %$includeArchived, orderBy: %$orderBy%) { nodes { id identifier "), query) assert(string.find(query, " } pageInfo { hasNextPage endCursor } } }$", 1, false), query) assert(not string.find(query, "description", 1, true), "lists leave out descriptions") assert(variables.first == 50 and variables.after == "c1" and variables.orderBy == "updatedAt") assert(json.encode(variables.filter.state.type.nin) == '["completed","canceled"]' and variables.filter.assignee.isMe.eq == true) assert(page.pageInfo.endCursor == "c2" and page.nodes[1].identifier == "ENG-1") assert(json.encode(page.nodes[1].labels.nodes) == "[]") payload = '{"data":{"comments":{"nodes":[],"pageInfo":{"hasNextPage":false,"endCursor":null}}}}' local empty = linear.listComments({filter = {issue = {id = {eq = "i1"}}}}) query, variables = sent() assert(string.find(query, "comments(filter: $filter", 1, true) and variables.filter.issue.id.eq == "i1") assert(json.encode(empty.nodes) == "[]" and empty.pageInfo.endCursor == NULL) payload = '{"data":{"issue":{"id":"i1","identifier":"ENG-123","description":"# Hi","children":{"nodes":[]}}}}' local issue = linear.getIssue({id = "ENG-123"}) query, variables = sent() assert(string.find(query, "^query getIssue%(%$id: String!%) { issue%(id: %$id%) { id identifier ") and string.find(query, " description children(first: 50) { ", 1, true)) assert(variables.id == "ENG-123" and issue.description == "# Hi") payload = '{"data":{"searchIssues":{"nodes":[],"pageInfo":{"hasNextPage":false,"endCursor":null},"totalCount":0}}}' local found = linear.searchIssues({term = "login & crash", teamId = "t1", includeComments = true}) query, variables = sent() assert(string.find(query, "searchIssues(filter: $filter, first: $first, after: $after, last: $last, before: $before, includeArchived: $includeArchived, orderBy: $orderBy, term: $term, teamId: $teamId, includeComments: $includeComments)", 1, true), query) assert(string.find(query, "pageInfo { hasNextPage endCursor } totalCount } }", 1, true)) assert(string.find(last().url, "&variables=", 1, true) and not string.find(last().url, "&", string.find(last().url, "&variables=", 1, true) + 1, true), "variables must be encoded") assert(variables.term == "login & crash" and variables.teamId == "t1" and variables.includeComments == true and found.totalCount == 0) linear.listTeams() assert(select(2, sent()) == nil, "no variables are sent without options") linear.getProject({id = "launch-2a1b"}) query = sent() assert(string.find(query, " content } }$"), query) for _, case in { {function() return linear.listUsers({includeDisabled = true, first = 250}) end, "users", "includeDisabled: $includeDisabled", {first = 250, includeDisabled = true}}, {function() return linear.listWorkflowStates({filter = {team = {key = {eq = "ENG"}}}}) end, "workflowStates", "filter: $filter", json.decode('{"filter":{"team":{"key":{"eq":"ENG"}}}}')}, {function() return linear.listLabels({includeArchived = true}) end, "issueLabels", "includeArchived: $includeArchived", {includeArchived = true}}, {function() return linear.listProjects({filter = {status = {type = {eq = "started"}}}}) end, "projects", "filter: $filter", json.decode('{"filter":{"status":{"type":{"eq":"started"}}}}')}, {function() return linear.listCycles({filter = {isActive = {eq = true}}}) end, "cycles", "filter: $filter", json.decode('{"filter":{"isActive":{"eq":true}}}')}, {function() return linear.getCycle({id = "c1"}) end, "cycle", "id: $id", {id = "c1"}}, {function() return linear.getTeam({id = "t1"}) end, "team", "id: $id", {id = "t1"}}, } do local call, field, use, expected = case[1], case[2], case[3], case[4] payload = json.encode({data = {[field] = {id = "x1"}}}) assert(call().id == "x1", field) query, variables = sent() assert(string.find(query, " { " .. field .. "(", 1, true) and string.find(query, use, 1, true), query) assert(same(variables, expected), field .. " variables " .. json.encode(variables)) end assert(#requests == 14) payload = '{"data":null}' local ok, err = pcall(function() linear.getTeam({id = "t1"}) end) assert(not ok and string.find(tostring(err), "invalid GraphQL response", 1, true), tostring(err)) payload = "<html>" ok, err = pcall(function() linear.getTeam({id = "t1"}) end) assert(not ok and string.find(tostring(err), "invalid GraphQL response", 1, true), tostring(err)) rejected(function() linear.getIssue() end, "id is required") rejected(function() linear.getIssue({id = NULL}) end, "id is required") rejected(function() linear.getIssue({id = ""}) end, "id must be a nonempty string") rejected(function() linear.getIssue({id = 7}) end, "id must be a nonempty string") rejected(function() linear.searchIssues({}) end, "term is required") rejected(function() linear.listIssues({first = 251}) end, "first must be an integer from 1 to 250") rejected(function() linear.listIssues({first = 0}) end, "first must be an integer from 1 to 250") rejected(function() linear.listIssues({first = 2.5}) end, "first must be an integer") rejected(function() linear.listIssues({orderBy = "priority"}) end, "orderBy must be 'createdAt' or 'updatedAt'") rejected(function() linear.listIssues({includeArchived = "yes"}) end, "includeArchived must be true or false") rejected(function() linear.listIssues({filter = "state = started"}) end, "filter must be an object") rejected(function() linear.listIssues({filter = {"started"}}) end, "filter must be an object, not an array") rejected(function() linear.listIssues({filter = json.decode("[]")}) end, "filter must be an object, not an array") rejected(function() linear.listIssues({fitler = {}}) end, "listIssues has no option fitler") local many = {} for index = 1, 600 do many[index] = string.format("00000000-0000-4000-8000-%012d", index) end rejected(function() linear.listIssues({filter = {id = {["in"] = many}}}) end, "too large for a read-only connection") rejected(function() linear.listIssues("ENG") end, "opts must be an object") rejected(function() linear.listIssues({"ENG"}) end, "named fields") end, }writes.luau
return { scenario = {publisher = {}, access = {data = "write"}, config = {client_id = "fixture-client", client_secret = "fixture-secret"}, auth_method = "oauth", auth_config = {}}, configure = function() requests = {} payload = "{}" http = {request = function(req) table.insert(requests, req) return fixture.operation({statusCode = 200, headers = {}, body = fixture.reader(payload)}) end} end, run = function(linear) local API = "https://api.linear.app/graphql" local NULL = json.decode("null") local function last() return requests[#requests] end local function sent() return json.decode(last().body) end local function rejected(fn, expected) local before = #requests local ok, err = pcall(fn) assert(not ok and string.find(tostring(err), expected, 1, true), "wrong validation error: " .. tostring(err)) assert(#requests == before, "invalid input reached Linear") end local names = {} for name in linear do table.insert(names, name) end table.sort(names) assert(table.concat(names, ",") == "createComment,createIssue,getCycle,getIssue,getProject,getTeam,getViewer,graphql,listComments,listCycles,listIssues,listLabels,listProjects,listTeams,listUsers,listWorkflowStates,searchIssues,updateIssue", "wrong read-write surface: " .. table.concat(names, ",")) -- Read-write connections send queries with POST too. payload = '{"data":{"teams":{"nodes":[{"id":"t1","key":"ENG"}],"pageInfo":{"hasNextPage":false,"endCursor":"c1"}}}}' local teams = linear.listTeams({first = 10}) assert(last().method == "POST" and last().url == API and last().headers.Authorization == nil) assert(last().headers["Content-Type"][1] == "application/json" and last().headers["apollo-require-preflight"] == nil) assert(string.find(sent().query, "^query listTeams%(") and sent().variables.first == 10 and teams.nodes[1].key == "ENG") linear.getViewer() assert(last().body == json.encode({query = sent().query, variables = {}}) and string.find(last().body, '"variables":{}', 1, true), "variables are an object even when empty") payload = '{"data":{"issueCreate":{"success":true,"issue":{"id":"i9","identifier":"ENG-9","labels":{"nodes":[]}}}}}' local input = {teamId = "t1", title = "Crash on login", description = "Steps:\n1. Sign in", priority = 2, labelIds = {"l1"}} local opts = {input = input} local created = linear.createIssue(opts) local body = sent() assert(string.find(body.query, "^mutation createIssue%(%$input: IssueCreateInput!%) { issueCreate%(input: %$input%) { success issue { id identifier "), body.query) assert(body.variables.input.title == "Crash on login" and body.variables.input.priority == 2 and json.encode(body.variables.input.labelIds) == '["l1"]') assert(created.success == true and created.issue.identifier == "ENG-9") assert(opts.input == input, "caller options were modified") -- A write that succeeded keeps its result when a nested field errors. payload = '{"data":{"issueCreate":{"success":true,"issue":{"id":"i10","project":null}}},"errors":[{"message":"Entity not found: Project","path":["issueCreate","issue","project"]}]}' local partial = linear.createIssue({input = {teamId = "t1", title = "Partial"}}) assert(partial.success == true and partial.issue.id == "i10" and partial.errors[1].path[3] == "project") payload = '{"data":{"issueUpdate":{"success":true,"issue":{"id":"i9","assignee":null}}}}' local updated = linear.updateIssue({id = "ENG-9", input = {stateId = "s2", assigneeId = NULL, addedLabelIds = {"l2"}}}) body = sent() assert(string.find(body.query, "^mutation updateIssue%(%$id: String!, %$input: IssueUpdateInput!%) { issueUpdate%(id: %$id, input: %$input%) { success issue { "), body.query) assert(body.variables.id == "ENG-9" and body.variables.input.stateId == "s2" and body.variables.input.assigneeId == NULL) assert(string.find(last().body, '"assigneeId":null', 1, true), "null unassigns") assert(updated.issue.assignee == NULL) payload = '{"data":{"commentCreate":{"success":true,"comment":{"id":"c1","body":"Fixed in #42","parentId":null}}}}' local comment = linear.createComment({input = {issueId = "ENG-9", body = "Fixed in #42", parentId = "c0"}}) body = sent() assert(string.find(body.query, "^mutation createComment%(%$input: CommentCreateInput!%) { commentCreate%(input: %$input%) { success comment { id body "), body.query) assert(body.variables.input.parentId == "c0" and comment.comment.id == "c1") payload = '{"data":{"issue":{"attachments":{"nodes":[]}}}}' local document = "query($id: String!) { issue(id: $id) { attachments { nodes { title url } } } }" local response = linear.graphql({query = document, variables = {id = "ENG-9"}}) assert(last().method == "POST" and last().body == json.encode({query = document, variables = {id = "ENG-9"}})) assert(json.encode(response.data.issue.attachments.nodes) == "[]" and response.errors == nil) linear.graphql({query = "query A { viewer { id } } query B { teams { nodes { id } } }", operationName = "B"}) assert(json.decode(last().body).operationName == "B") linear.graphql({query = "{ viewer { id } }"}) assert(string.find(last().body, '"variables":{}', 1, true)) linear.graphql({query = "{ viewer { id } }", variables = NULL}) assert(string.find(last().body, '"variables":{}', 1, true), "null variables are omitted") assert(#requests == 10) rejected(function() linear.createIssue({}) end, "input is required") rejected(function() linear.createIssue({input = {"t1"}}) end, "input must be an object, not an array") rejected(function() linear.createIssue({input = {teamId = "t1"}, teamId = "t1"}) end, "createIssue has no option teamId") rejected(function() linear.updateIssue({input = {stateId = "s2"}}) end, "id is required") rejected(function() linear.createComment({input = "Fixed"}) end, "input must be an object") rejected(function() linear.graphql({}) end, "query must be a GraphQL document") rejected(function() linear.graphql({query = " \n"}) end, "query must be a GraphQL document") rejected(function() linear.graphql({query = string.rep(" ", 64 * 1024) .. "{ viewer { id } }"}) end, "query must be at most") rejected(function() linear.graphql({query = "{ viewer { id } }", variables = {"x"}}) end, "variables must be an object, not an array") rejected(function() linear.graphql({query = "{ viewer { id } }", operationName = "B C"}) end, "operationName must be a GraphQL name") rejected(function() linear.graphql({query = "{ viewer { id } }", operation = "B"}) end, "graphql has no option operation") end, }