Skip to main content
Glama
BetterLinearMCP

BetterLinearMCP

README.md
<!-- mcp-name: io.github.achintyaashok/better-linear-mcp -->

# BetterLinearMCP

[![Python 3.12+](https://img.shields.io/badge/python-3.12+-3776AB?logo=python&logoColor=white)](https://www.python.org/)
[![FastMCP 3.x](https://img.shields.io/badge/FastMCP-3.x-00ADD8?logo=data:image/svg+xml;base64,PHN2Zy8+&logoColor=white)](https://gofastmcp.com)
[![Pydantic v2](https://img.shields.io/badge/pydantic-v2-E92063?logo=pydantic&logoColor=white)](https://docs.pydantic.dev/)
[![uv](https://img.shields.io/badge/uv-package%20manager-DE5FE9?logo=astral&logoColor=white)](https://docs.astral.sh/uv/)
[![OAuth 2.1 + PKCE](https://img.shields.io/badge/OAuth_2.1-PKCE-4A154B)](#scope-based-access-control)
[![Linear API](https://img.shields.io/badge/Linear-API-5E6AD2?logo=linear&logoColor=white)](https://developers.linear.app/)

A remote MCP server that gives AI agents secure, scoped access to [Linear](https://linear.app). Built with [FastMCP 3.x](https://gofastmcp.com) — OAuth 2.1 + PKCE, granular scope enforcement, and 20+ tools covering discovery, read, write, and admin operations over Streamable HTTP.

## Quick Start

No Linear account needed — sandbox mode runs against local seed data:

```bash
uv sync
make run-sandbox-http   # terminal 1: start the sandbox server
make repl               # terminal 2: launch the interactive REPL
```

Or run the self-contained smoke test (starts server, tests all tools, stops):

```bash
make smoke-test-sandbox
```

![REPL demo](demo/repl-quickstart.gif)

The REPL auto-discovers all tools from the server and exposes them as commands with tab-completion, `--help` per tool, and JSON output. Type `help` inside the REPL for the full guide.

## Connecting to Linear

To use real Linear data, you need an OAuth application and a few secrets:

1. **Create an OAuth app** in Linear Settings > API > OAuth Applications
   - Redirect URI: `http://localhost:8000/oauth/callback`
   - Scopes: `read`, `write`, `issues:create`, `admin`
2. **Generate secrets:** `make generate-key`
3. **Configure `.env`:** `cp .env.example .env` and fill in your credentials

Full walkthrough: **[guides/SETUP_LINEAR.md](guides/SETUP_LINEAR.md)**

**Using Claude Code?** The setup wizard handles everything interactively:
```
/blmcp-setup
```

## Running the Server

The server reads `.env` automatically on startup via [pydantic-settings](https://docs.pydantic.dev/latest/concepts/pydantic_settings/).

### Local Development

```bash
make run-sandbox-http   # Sandbox over HTTP (no Linear account needed)
make run-http           # Real Linear over HTTP (requires .env configured)
make run                # Real Linear over stdio (local dev, Claude Desktop)
```

### Agent Loop (Claude Code)

**Sandbox mode** — the agent spawns the server directly via stdio. Works out of the box:

```json
{
  "mcpServers": {
    "better-linear-mcp": {
      "command": "uv",
      "args": ["run", "python", "-m", "rl_linear_mcp.server"],
      "env": {
        "MCP_SANDBOX_ENABLED": "true"
      }
    }
  }
}
```

A ready-made config is included — just run:

```bash
claude --mcp-config .mcp.sample.json
```

**Real Linear** — OAuth requires HTTP transport for the browser callback flow, so you run the server separately and connect via [`mcp-remote`](https://www.npmjs.com/package/mcp-remote):

```bash
# Terminal 1: start the server (with .env configured)
make run-http
```

Then point your MCP client at it:

```json
{
  "mcpServers": {
    "better-linear-mcp": {
      "command": "npx",
      "args": ["-y", "mcp-remote", "http://localhost:8000/mcp"]
    }
  }
}
```

`mcp-remote` bridges stdio↔HTTP — the agent talks stdio to `mcp-remote`, which proxies requests to the running HTTP server. This is necessary because the OAuth 2.1 + PKCE flow requires HTTP transport for the browser redirect callback.

### Docker

```bash
make docker-build
make docker-run       # HTTP transport, port 8000
```

The container binds to `0.0.0.0`. Pass env vars with `-e` or `--env-file .env`.

### Docker + OpenTelemetry

Full observability stack — server + OTel Collector + Tempo + Prometheus + Grafana:

```bash
make compose-up       # start everything
make compose-down     # tear down
```

Grafana dashboard at `http://localhost:3000`. Requires `uv sync --extra otel`.

## Interactive REPL

The built-in REPL client connects to a running server and auto-discovers all tools. Every MCP tool becomes a command with argparse-generated `--help`, tab-completion, and JSON output.

```bash
make run-sandbox-http   # terminal 1
make repl               # terminal 2 (sandbox — no auth needed)
make repl-oauth         # terminal 2 (real Linear — opens browser for OAuth)
```

```
mcp> help                          # comprehensive usage guide
mcp> tools                         # list all tools
mcp> get_issue --help              # show params for a tool
mcp> get_issue issue-001           # call a tool
mcp> create_issue --team_id team-eng-001 --title "Fix it"
mcp> search_issues bug             # positional args for required params
mcp> get_audit_trail               # view scope enforcement audit log
mcp> quit
```

Supports stdin piping for agent-driven workflows:

```bash
echo -e "list_teams\nget_issue issue-001\nquit" | make repl
```

### MCP Inspector

For a web-based UI, use the [MCP Inspector](https://modelcontextprotocol.io/docs/tools/inspector) (requires Node.js):

```bash
make inspect            # stdio — inspector manages the server process
make inspect-sandbox    # stdio with sandbox data
make inspect-http       # HTTP — run make run-http first
```

## Scope-Based Access Control

Linear's OAuth grants broad permissions (`read`, `write`, `admin`). BetterLinearMCP maps these to granular **domain-based MCP scopes** (`linear:{domain}:{read|write|admin}`) and enforces them per-tool.

| Linear Scope | What It Unlocks |
|---|---|
| `read` | All discovery and read tools — list teams, get issues, search, etc. |
| `write` | Mutation tools — create/update issues, create projects and labels, manage cycles |
| `admin` | Workspace info and team member management |

Linear's `issues:create` and `comments:create` scopes are folded into the `:write` tier — our model uses `read`, `write`, and `admin` consistently across all domains.

Meta tools (`get_access_info`, `echo`) are **always accessible** regardless of scopes — they help users discover what they can do.

When a tool call requires scopes the user doesn't have, the server returns a `403` with the specific missing scopes.

Admins can grant additional MCP scopes to users via the `manage_user_scopes` tool. A user's effective scopes are the union of what Linear granted and what an admin has added. All scope mutations are audit-logged.

### Admin-Granted Privilege Escalation

The `manage_user_scopes` tool lets workspace admins dynamically grant, revoke, and list scopes for any user — without requiring a new OAuth flow. This enables runtime privilege management: an admin can temporarily elevate a user's access for a sprint, then revoke it when done.

Actions: `grant` (add scopes), `revoke` (remove scopes), `list` (view current grants). Every mutation records `granted_by`, `reason`, and timestamp in the audit log.

```
 ┌─────────────────────────────────────────────────────────────────┐
 │                  Scope Grant / Revoke Lifecycle                 │
 │                                                                 │
 │  Bob (admin)                          Alice (regular user)      │
 │  ═══════════                          ════════════════════      │
 │                                                                 │
 │  ┌─────────────┐                      Scopes: [issues:read]    │
 │  │ list_teams  │ ✅ allowed                                     │
 │  │ create_issue│ ✅ allowed           ┌─────────────┐           │
 │  │ manage_user │ ✅ allowed           │ list_teams  │ ✅        │
 │  │   _scopes   │                      │ create_issue│ ❌ 403   │
 │  └─────────────┘                      │  "missing:  │           │
 │                                       │   issues:   │           │
 │        │                              │   write"    │           │
 │        ▼                              └─────────────┘           │
 │  ┌─────────────────────┐                                        │
 │  │ manage_user_scopes  │                                        │
 │  │ action: "grant"     │──────────────────┐                     │
 │  │ target: alice       │                  │                     │
 │  │ scopes:             │                  ▼                     │
 │  │  [issues:write]     │     Scopes: [issues:read,             │
 │  │ reason: "sprint     │              issues:write] ← granted  │
 │  │   planning"         │                                        │
 │  └─────────────────────┘              ┌─────────────┐           │
 │                                       │ create_issue│ ✅        │
 │        │                              │  now works! │           │
 │        ▼                              └─────────────┘           │
 │  ┌─────────────────────┐                                        │
 │  │ manage_user_scopes  │                                        │
 │  │ action: "revoke"    │──────────────────┐                     │
 │  │ target: alice       │                  │                     │
 │  │ scopes:             │                  ▼                     │
 │  │  [issues:write]     │     Scopes: [issues:read] ← reverted │
 │  │ reason: "sprint     │                                        │
 │  │   complete"         │              ┌─────────────┐           │
 │  └─────────────────────┘              │ create_issue│ ❌ 403   │
 │                                       │  blocked    │           │
 │        │                              │  again      │           │
 │        ▼                              └─────────────┘           │
 │  ┌─────────────────────────────────────────────────────────┐    │
 │  │                     Audit Trail                         │    │
 │  │─────────────────────────────────────────────────────────│    │
 │  │ scope.enforce │ bob   │ list_teams    │ allowed         │    │
 │  │ scope.enforce │ bob   │ create_issue  │ allowed         │    │
 │  │ scope.enforce │ alice │ list_teams    │ allowed         │    │
 │  │ scope.enforce │ alice │ create_issue  │ denied          │    │
 │  │ scope.grant   │ alice │ issues:write  │ "sprint plan."  │    │
 │  │ scope.enforce │ alice │ create_issue  │ allowed         │    │
 │  │ scope.revoke  │ alice │ issues:write  │ "sprint done"   │    │
 │  │ scope.enforce │ alice │ create_issue  │ denied          │    │
 │  └─────────────────────────────────────────────────────────┘    │
 └─────────────────────────────────────────────────────────────────┘
```

This flow is tested end-to-end in **[tests/test_scope_grant_story.py](tests/test_scope_grant_story.py)** — run it with `uv run pytest tests/test_scope_grant_story.py -v -s`.

Full scope mapping, admin grants, and per-tool requirements: **[guides/SCOPES.md](guides/SCOPES.md)**

## Tools

### Core Tools

| Tool | Scopes | Description |
|------|--------|-------------|
| **Discovery** | | |
| `list_teams` | `linear:teams:read` | List all teams in the workspace |
| `list_projects` | `linear:projects:read` | List all projects in the workspace |
| `list_cycles` | `linear:cycles:read` | List cycles, optionally filtered by team |
| `list_labels` | `linear:labels:read` | List all issue labels |
| `list_workflow_states` | `linear:teams:read` | List workflow states, optionally filtered by team |
| **Read** | | |
| `get_issue` | `linear:issues:read` | Get issue details by ID or identifier (e.g., `ENG-123`) |
| `get_project` | `linear:projects:read` | Get project details |
| `get_team` | `linear:teams:read` | Get team details |
| `search_issues` | `linear:issues:read` | Search issues by query string |
| **Write** | | |
| `create_issue` | `linear:issues:write` | Create a new issue in a team |
| `update_issue` | `linear:issues:write` | Update an existing issue (only provided fields change) |
| `create_project` | `linear:projects:write` | Create a new project |
| `create_label` | `linear:labels:write` | Create a new issue label |
| `add_issue_to_cycle` | `linear:issues:write` | Add an issue to a cycle |
| `assign_issue` | `linear:issues:write` | Assign or unassign an issue |
| `transition_issue` | `linear:issues:write` | Change an issue's workflow state |
| **Admin** | | |
| `get_workspace_info` | `linear:workspace:admin` | Get workspace name, URL key, user count, creation date |
| `manage_team_members` | `linear:teams:admin` | List team members with name, email, and active status |
| `manage_user_scopes` | `linear:workspace:admin` | Grant, revoke, or list MCP scopes for any user. Actions: `grant` (add scopes + reason), `revoke` (remove scopes + reason), `list` (show all grants with metadata). All mutations are audit-logged. See [diagram above](#admin-granted-privilege-escalation). |
| **Meta** | | |
| `get_access_info` | _(none)_ | View full tool catalog with your access level |
| `echo` | _(none)_ | Echo a message (connectivity test) |

### Extensions

Enabled by default, togglable via environment variables:

| Tool | Toggle | Description |
|------|--------|-------------|
| `search_capability` | `MCP_SEARCH_ENABLED` | Semantic search across MCP tools by natural-language description |
| `run_workflow` | `MCP_WORKFLOW_ENABLED` | Execute multi-step workflow pipelines |

Detailed tool reference with parameters and return shapes: **[guides/TOOLS.md](guides/TOOLS.md)**

## Configuration

Key environment variables (full reference: **[guides/CONFIGURATION.md](guides/CONFIGURATION.md)**):

| Variable | Default | Purpose |
|----------|---------|---------|
| `MCP_TRANSPORT` | `stdio` | `stdio` or `http` |
| `MCP_AUTH_ENABLED` | `false` | Enable OAuth 2.1 + PKCE on HTTP transport |
| `MCP_SANDBOX_ENABLED` | `false` | File-backed sandbox (no Linear API calls) |
| `MCP_OTEL_ENABLED` | `false` | OpenTelemetry tracing (requires `uv sync --extra otel`) |
| `MCP_SEARCH_ENABLED` | `true` | Semantic tool search |
| `MCP_WORKFLOW_ENABLED` | `true` | Compound workflow tool |

All variables managed via `pydantic-settings`. Booleans accept `true`/`false`/`1`/`0`/`yes`/`no`. Precedence: CLI flags > env vars > `.env` file > defaults.

## Design Decisions

- **OAuth proxy pattern** — The server exchanges auth codes for Linear tokens, stores them encrypted, and issues its own JWTs to MCP clients. Two tokens because Linear tokens are opaque (require API calls to verify) while JWTs are self-contained.

- **Client abstraction** — An ABC (`LinearClientBase`) defines 18 typed async methods with two implementations (GraphQL and file-backed sandbox). A factory returns the right one based on config. Tools never import a specific client class.

- **Domain-based 3-tier scopes** — Linear's coarse `read`/`write`/`admin` OAuth scopes are mapped to granular MCP scopes (`linear:{domain}:{tier}`). Per-tool enforcement via middleware, not per-tool `if` checks.

- **Middleware chain architecture** — Identity injection, scope enforcement, rate limiting, caching, and logging are all middleware. Conditionally wired based on settings — no dead code paths in production.

- **Auth bridge token propagation** — In OAuth mode, the auth bridge middleware overrides the tool's `access_token` argument with the upstream Linear token resolved from the JWT. Tools don't need to know whether they're running behind OAuth or with a direct API key.

- **Structured error hierarchy** — All application errors inherit from `BaseAppError` with typed context (entity IDs, step indices, missing scopes). Replaces generic `ValueError`/`KeyError` with catchable, inspectable exceptions. See **[DESIGN_CHOICES.md](DESIGN_CHOICES.md)**.

- **Sandbox user profiles** — The sandbox identity middleware supports multiple user profiles keyed by `access_token`, enabling multi-user integration tests (admin + regular user) without multiple server instances.

- **Additive scope resolution** — A user's effective scopes are `OAuth-derived ∪ admin-granted`. Admin grants are stored in a scope store (in-memory), resolved at enforcement time, and fully audit-logged.

- **Pydantic-validated seed data** — Sandbox seed data (`seed_data.json`) is validated at load time by a `SeedData` model. Schema drift is caught before runtime, not at request time.

- **Hand-written entity models** — `Linear*` models in `clients/models.py` are manually maintained to match the GQL fields we query. Auto-generation from Linear's public schema is a future improvement.

- **Import order discipline** — `telemetry.py` must be imported before FastMCP (OTel captures `TracerProvider` at import time). `server.py` enforces this with an `# isort: split` comment.

- **Settings as leaf dependency** — All config is centralized in `settings.py` via `pydantic-settings`. No module reads `os.environ` directly (exception: `telemetry.py` to avoid import-order coupling).

### Architecture & PRDs

- System architecture and diagrams: **[prd/prd-001-architecture/ARCHITECTURE.md](prd/prd-001-architecture/ARCHITECTURE.md)**
- Authorization flow and token lifecycle: **[AUTHORIZATION_FLOW.md](AUTHORIZATION_FLOW.md)**
- All PRDs: **[prd/](prd/)** — covers architecture, Linear integration, OAuth, client design, tool surface, search, DX, workflows, and sandbox mode.

## Trade-offs

### What we shipped

- **21 core tools** across discovery, read, write, and admin — broad enterprise surface over deep feature polish
- **Full OAuth 2.1 + PKCE** with encrypted token storage — production-grade auth, not a shortcut
- **Sandbox mode** with Pydantic-validated seed data — zero-config testing without a Linear account
- **Per-tool scope enforcement** with domain-based 3-tier model — goes beyond Linear's coarse `read`/`write`/`admin` scopes
- **Structured error hierarchy** — typed exceptions with context, not string parsing. See **[DESIGN_CHOICES.md](DESIGN_CHOICES.md)**

### What we cut

- **Token refresh probing** — the OAuthProxy handles upstream refresh, but we don't proactively refresh before expiry. Tokens refresh on next use after expiry.
- **Webhook/real-time events** — Linear supports webhooks for push-based updates. We're pull-only (tool calls). Adding a `subscribe_to_issue` resource would enable real-time.
- **Pagination cursors in REPL** — the REPL doesn't support `--after` cursor chaining for multi-page results. You get the first page only.
- **Auto-generated entity models** — `Linear*` models are hand-written to match our GQL queries. `ariadne-codegen` or `datamodel-code-generator` from Linear's public schema would keep them in sync automatically.
- **Persistent scope store** — admin-granted scopes use an in-memory store. A SQLite-backed store would survive restarts.
- **Rate limiting against Linear** — we have per-client rate limiting middleware, but don't track Linear's own API rate limits (1,500 req/hr).

### What we'd do next

- **Comments and attachments** — `create_comment`, `list_comments`, `attach_file` tools for richer issue interaction
- **Bulk operations** — `bulk_create_issues`, `bulk_transition` for project management workflows
- **GraphQL subscriptions** — real-time issue updates via MCP resources
- **Multi-workspace** — current design assumes one workspace per server instance
- **Persistent token + scope storage** — swap SQLite for the in-memory stores

## Testing Tools

### Interactive REPL

A `cmd2`-based REPL client that auto-discovers tools from a running server and exposes them as commands with tab-completion, `--help`, and JSON output:

```bash
make run-sandbox-http   # terminal 1
make repl               # terminal 2
```

```
mcp> help                          # comprehensive usage guide
mcp> tools                         # list all tools
mcp> get_issue --help              # show params for a tool
mcp> get_issue issue-001           # call a tool
mcp> search_issues bug             # positional args for required params
mcp> create_issue --team_id team-eng-001 --title "Fix it"  # --flags for optional
```

Supports stdin piping for agent-driven workflows:

```bash
echo -e "list_teams\nget_issue issue-001\nquit" | make repl
```

### Smoke Tests

Non-interactive contract tests against a running server:

```bash
make smoke-test-sandbox # self-contained: starts sandbox, runs tests, stops server
make run-sandbox-http   # or start manually in terminal 1...
make smoke-test         # ...and run tests in terminal 2
make list-tools         # list tools with input schemas
```

## Claude Code Slash Commands

This project includes [Claude Code](https://claude.ai/claude-code) slash commands for common workflows. Run them from the Claude Code CLI:

| Command | Description |
|---------|-------------|
| `/blmcp-setup` | Interactive setup wizard — walks through OAuth credentials, secret generation, `.env` configuration, and server verification. Supports Full OAuth, Personal API Key, and Sandbox modes. |
| `/blmcp-repl` | Launch the interactive MCP REPL to test tools against a running server. Starts the sandbox server if needed, connects, and guides you through tool discovery and testing. |
| `/blmcp-int-test` | Run read-only integration tests against a real Linear workspace. Authenticates via OAuth browser flow and exercises discovery/read tools. |

Commands are defined in `.claude/commands/` and can be extended by adding new `.md` files.

TDQS

C2.7/5.0

Scored across 24 tools

Disambiguation4/5

Most tools map to distinct resources or actions, so an agent can usually tell them apart. However, search_capability and get_access_info both expose tool catalogs/access policy, and manage_team_members only lists members despite its manage prefix, which could be confused with get_team or list_teams.

Naming Consistency4/5

The set predominantly follows a consistent snake_case verb_noun convention (list_teams, create_issue, get_project, update_issue). Minor deviations exist: manage_team_members/manage_user_scopes use manage_ instead of list_/get_, and echo is a single bare verb.

Tool Count3/5

24 tools is on the heavy side for a Linear-focused MCP server. Several meta/utility tools (echo, search_capability, get_access_info, run_workflow) inflate the surface beyond the core workspace/issue/project operations.

Completeness3/5

Core issue create/get/update/search and project create/get/list are covered, with some admin scope support. But lifecycle coverage is notably incomplete: there are no delete operations for issues, projects, or labels; no update/delete for projects or labels; and cycle/team management is thin (no create/update cycle, no team provisioning).