how-to

How to Set Up Sourcery AI in VS Code: Complete Guide

Step-by-step guide to install and configure Sourcery AI in VS Code. Covers sign-in, refactoring, custom rules, troubleshooting, and alternatives.

Published:

Why use Sourcery in VS Code

Catching code quality issues after pushing to a pull request is too late in the feedback loop. By the time a reviewer - human or AI - flags a problem on your PR, you have already context-switched to another task. Going back to fix refactoring issues and readability problems adds friction that slows down the entire development cycle.

Sourcery solves this by bringing AI-powered code analysis directly into your editor. The Sourcery VS Code extension analyzes your code as you write it, surfacing refactoring suggestions, readability improvements, and potential issues in real time. Instead of discovering that your nested conditional should be a guard clause during PR review, you see the suggestion inline while you are still thinking about the function.

For Python developers specifically, Sourcery’s VS Code integration is particularly strong. It understands idiomatic Python patterns - list comprehensions, context managers, dataclasses, walrus operators - and suggests transformations that make your code more Pythonic. It also supports over 30 other languages through its LLM-powered analysis layer, though Python remains its deepest specialization.

This guide walks through every step of setting up Sourcery in VS Code - from installing the extension to configuring custom rules and troubleshooting common issues. The entire setup takes under 10 minutes.

Sourcery AI code review tool homepage screenshot
Sourcery homepage

Prerequisites

Before you begin, make sure you have the following ready:

  • VS Code 1.70 or later installed on your machine. Sourcery requires a relatively recent version of VS Code. Check your version by going to Help and then About in the menu bar.
  • A GitHub or Google account for signing in to Sourcery. The extension requires authentication to activate, even on the free tier.
  • Python 3.7 or later installed if you plan to use Sourcery’s Python-specific refactoring features. Sourcery works with other languages too, but Python gets the deepest analysis.
  • An active internet connection during initial setup and authentication. After sign-in, most analysis runs locally, but some features require connectivity.

No API keys, tokens, or separate Sourcery account creation is needed. The extension handles authentication through your existing GitHub or Google credentials.

Step 1 - Install the Sourcery extension

Open VS Code and navigate to the Extensions panel. You can do this by pressing Ctrl+Shift+X on Windows and Linux or Cmd+Shift+X on macOS.

  1. Type Sourcery in the search bar at the top of the Extensions panel
  2. Look for the extension published by sourcery.ai - this is the official extension. Verify the publisher name to avoid installing unofficial copies
  3. Click the Install button
  4. Wait for the installation to complete - this typically takes a few seconds

After installation, you will see the Sourcery icon appear in the VS Code sidebar (the left activity bar). The icon looks like a stylized flame or spark. You may also see a notification in the bottom-right corner confirming that the extension has been installed.

At this point, Sourcery is installed but not yet activated. You need to sign in before it starts analyzing your code.

Extension ID: sourcery.sourcery
Publisher: sourcery.ai
Category: Linters, AI

If you prefer installing from the command line, you can also run:

code --install-extension sourcery.sourcery

Step 2 - Sign in to Sourcery

Click the Sourcery icon in the VS Code sidebar to open the Sourcery panel. You will see a prompt to sign in.

  1. Click Sign in with GitHub or Sign in with Google depending on your preference
  2. A browser window opens and redirects you to the Sourcery authentication page
  3. Authorize Sourcery to access your account when prompted
  4. After successful authorization, the browser displays a confirmation message and VS Code automatically detects the completed sign-in

Back in VS Code, the Sourcery panel should now show your account name and a status indicator confirming that the extension is active. If you see a green checkmark or an “Active” status, you are ready to go.

For teams using the Pro or Team plan, your plan features activate automatically based on your account. There is no separate license key to enter.

Troubleshooting sign-in issues: If the browser does not open automatically, VS Code may display a link in the output panel that you can copy and paste into your browser manually. If sign-in fails repeatedly, check that your firewall or VPN is not blocking connections to sourcery.ai. You can also try signing in from the VS Code command palette by pressing Ctrl+Shift+P (or Cmd+Shift+P on macOS) and typing “Sourcery: Login”.

Step 3 - Get your first refactoring suggestions

Open any Python file in your workspace to see Sourcery in action. Sourcery analyzes the file automatically and displays suggestions inline.

Here is an example of the kind of code Sourcery will flag:

# Before - Sourcery will suggest a refactoring
def get_active_users(users):
    active_users = []
    for user in users:
        if user.is_active:
            active_users.append(user)
    return active_users

Sourcery highlights the function and suggests replacing the loop with a list comprehension:

# After - Sourcery's suggested refactoring
def get_active_users(users):
    return [user for user in users if user.is_active]

Suggestions appear in several ways:

  • Inline decorations - subtle underlines or highlights on code that Sourcery has suggestions for
  • Lightbulb icon - the VS Code lightbulb (quick action) appears when your cursor is on a line with an available suggestion. Click it or press Ctrl+. (or Cmd+. on macOS) to see the suggestion
  • Problems panel - Sourcery findings also appear in the Problems panel (Ctrl+Shift+M or Cmd+Shift+M), making it easy to browse all suggestions in a file
  • Hover tooltips - hovering over underlined code shows the suggestion details and an explanation of why the change improves the code

To apply a suggestion, click the lightbulb and select the refactoring from the quick actions menu. Sourcery applies the change immediately. You can undo with Ctrl+Z if the result is not what you expected.

Sourcery also catches patterns like:

  • Nested conditionals that can be flattened using guard clauses
  • Repeated code blocks that can be extracted into functions
  • Verbose boolean expressions that can be simplified
  • Missing use of context managers for file and resource handling
  • Opportunities to use enumerate() instead of manual index tracking

Step 4 - Configure Sourcery settings

You can configure Sourcery’s behavior through VS Code settings and a project-level configuration file.

VS Code settings

Open VS Code settings (Ctrl+, or Cmd+,) and search for “Sourcery” to see available options:

SettingDescriptionDefault
sourcery.codeLensShow refactoring suggestions as CodeLens above functionstrue
sourcery.diagnosticsShow Sourcery findings in the Problems paneltrue
sourcery.metricsEnabledSend anonymous usage metricstrue

Project configuration with .sourcery.yaml

For project-specific settings, create a .sourcery.yaml file in your repository root:

# .sourcery.yaml
refactor:
  skip:
    - low-code-quality
    - no-suitable-type
  rule_types:
    - refactoring
    - suggestion
    - comment

clone_detection:
  min_lines: 3
  min_duplicates: 2

github:
  labels: []
  ignore_labels:
    - sourcery-ignore

ignore:
  - data/generated_*.py
  - "*/migrations/*"
  - tests/fixtures/**

The refactor.skip list lets you disable specific suggestion categories that your team finds unhelpful. The ignore section excludes files and directories from analysis - useful for generated code, database migrations, and test fixtures that follow different patterns.

Sourcery reads the .sourcery.yaml file automatically when you open a project. Changes take effect immediately without restarting VS Code.

Step 5 - Create custom rules

Custom rules let you encode your team’s specific coding standards into Sourcery’s analysis. This is available on the Pro and Team plans.

Create custom rules in your .sourcery.yaml file:

rules:
  - id: no-print-statements
    description: Use logging instead of print statements
    pattern: print(...)
    replacement: logger.info(...)
    language: python
    severity: warning

  - id: require-type-hints
    description: Functions should have return type annotations
    pattern: |
      def ${name}(${args}):
          ...
    condition: not args.has_type_annotation
    language: python
    severity: info

  - id: no-bare-except
    description: Catch specific exceptions instead of bare except
    pattern: |
      try:
          ...
      except:
          ...
    language: python
    severity: error
    tags:
      - best-practices

Each rule consists of a pattern that describes the code to match and optionally a replacement that describes the fix. Sourcery uses these rules alongside its built-in analysis to surface custom findings in your editor.

Custom rules are particularly useful for enforcing project-specific conventions that generic linters do not cover - things like requiring specific logging patterns, enforcing naming conventions for domain objects, or flagging deprecated internal APIs that your team is migrating away from.

For a deeper look at Sourcery’s rule engine and how it compares to traditional linters, see our Sourcery vs Pylint comparison.

Tips for getting the most out of Sourcery in VS Code

These practices help you extract maximum value from the extension after the initial setup.

Review suggestions before applying them blindly. Sourcery’s suggestions are not always correct. Roughly half of its recommendations are genuinely actionable, with some falling into the category of valid but unnecessary changes. Read the explanation for each suggestion and decide whether the transformation actually improves your code in context.

Use the chat assistant for complex refactoring. When you need to restructure a larger block of code, open the Sourcery chat from the sidebar and describe what you want to achieve. The assistant understands your file context and can suggest multi-step refactoring approaches that go beyond what the inline suggestions cover.

Combine Sourcery with Ruff or Pylint. Sourcery handles high-level refactoring and AI-powered suggestions while tools like Ruff handle fast, deterministic linting and formatting. Running both in VS Code gives you comprehensive coverage without overlap. Our guide on best code review tools for Python covers the optimal tool combination in detail.

Enable both VS Code and GitHub integration. Using Sourcery in VS Code catches issues while you write code. Using Sourcery on GitHub catches issues during PR review. Together, they provide feedback at two stages of the development workflow, reducing the chance that quality issues slip through. See our Sourcery review for a full breakdown of the platform’s capabilities.

Dismiss unhelpful suggestions actively. When Sourcery shows a suggestion that does not apply to your codebase, dismiss it with an explanation. Sourcery learns from these dismissals and reduces similar suggestions over time. Teams that actively train Sourcery during the first two to three weeks see a meaningful reduction in noise.

Troubleshooting common issues

If Sourcery is not working as expected, work through these solutions.

Extension not activating after install. Restart VS Code completely - not just reload the window. If the extension still does not activate, check the VS Code Output panel (select “Sourcery” from the dropdown) for error messages. Common causes include outdated VS Code versions and network connectivity issues during activation.

No suggestions appearing on Python files. Verify that your Python interpreter is configured in VS Code (check the status bar at the bottom). Sourcery needs to know which Python version you are using to provide accurate suggestions. Also check that the file is not excluded in your .sourcery.yaml ignore patterns.

Suggestions appearing too slowly. Sourcery analyzes files asynchronously. For large files (over 500 lines), analysis may take a few seconds. If performance is consistently slow, check your system resources and consider excluding large generated files from analysis using the ignore configuration.

Authentication token expired. If you see authentication errors after a period of inactivity, sign out and sign back in through the Sourcery sidebar panel. Token refresh usually happens automatically, but network interruptions can occasionally cause token expiration.

Conflicts with other extensions. Sourcery generally coexists well with other Python extensions. If you experience issues, try disabling other AI-powered extensions temporarily to isolate the conflict. Extensions that modify the same code lens or diagnostic channels are the most likely to conflict.

For details on Sourcery’s pricing tiers and what each plan includes, see our Sourcery pricing guide.

Alternatives to Sourcery for VS Code

If Sourcery does not meet your needs, several alternatives offer VS Code integration with different strengths.

CodeAnt AI ($24-40/user/month) is a comprehensive code quality platform that bundles AI-powered code review, static analysis (SAST), secret detection, and DORA metrics into a single tool. While it focuses primarily on PR-level review through GitHub, GitLab, and Bitbucket rather than real-time IDE analysis, it provides broader coverage for teams that need security scanning and compliance reporting alongside code quality feedback.

GitHub Copilot ($19-39/user/month) provides AI code completion, generation, and chat directly in VS Code. It also offers PR review through GitHub. Copilot is a stronger choice if you primarily need code generation and completion rather than refactoring suggestions. However, its code review capabilities are less targeted than Sourcery’s Python-specific analysis.

Ruff (free) is the fastest Python linter available, written in Rust with over 800 rules. It replaces Flake8, isort, Black, and pycodestyle in a single tool. Ruff’s VS Code extension provides instant feedback on style violations and common bugs. It is not an AI tool and does not suggest refactoring, but it is an essential complement to any AI-powered tool.

For a comprehensive comparison, see our Sourcery alternatives guide.

Conclusion

Setting up Sourcery in VS Code takes under 10 minutes and immediately starts providing value through inline refactoring suggestions and code quality feedback. The combination of real-time IDE analysis with Python-specific refactoring intelligence makes it a practical addition to any Python developer’s toolkit.

The key steps are straightforward: install the extension from the marketplace, sign in with GitHub or Google, and start coding. From there, create a .sourcery.yaml file to customize the analysis for your project, add custom rules to enforce team-specific conventions, and actively dismiss unhelpful suggestions so Sourcery learns your preferences over time.

For the strongest setup, combine Sourcery’s VS Code extension with its GitHub integration for PR-level review, and pair it with a deterministic linter like Ruff for comprehensive Python code quality coverage. If you need broader platform support or integrated security scanning, CodeAnt AI ($24-40/user/month) is worth evaluating as an alternative that bundles multiple code quality capabilities into a single platform.

Frequently Asked Questions

How do I install Sourcery in VS Code?

Open VS Code and go to the Extensions panel by pressing Ctrl+Shift+X on Windows/Linux or Cmd+Shift+X on macOS. Search for 'Sourcery' in the marketplace, then click Install on the official Sourcery extension published by sourcery.ai. After installation, click the Sourcery icon in the sidebar and sign in with your GitHub or Google account. The extension activates automatically on supported file types.

Is the Sourcery VS Code extension free?

Yes. The Sourcery VS Code extension is free to install and use with public repositories. The free tier includes AI-powered refactoring suggestions, basic code review feedback, and the ability to chat with Sourcery about your code. For private repositories and advanced features like custom coding guidelines, you need the Pro plan at $10/user/month or the Team plan at $24/user/month.

What languages does Sourcery support in VS Code?

Sourcery supports over 30 programming languages in VS Code including Python, JavaScript, TypeScript, Java, Go, C++, C#, Ruby, PHP, Kotlin, Rust, and Swift. Python has the deepest analysis with rule-based refactoring suggestions for idiomatic patterns. Other languages use Sourcery's LLM-powered analysis layer, which provides useful but less specialized feedback compared to its Python capabilities.

Why is Sourcery not showing suggestions in VS Code?

Check these common causes: you may not be signed in (click the Sourcery icon in the sidebar to verify), your file type may not be supported, or the extension may be disabled for the current workspace. Also ensure the extension is up to date by checking the Extensions panel for available updates. If you are working on a private repository, you need a Pro or Team plan. Restarting VS Code often resolves initialization issues.

Can I use Sourcery and Pylint together in VS Code?

Yes. Sourcery and Pylint serve different purposes and work well together. Pylint is a deterministic linter that enforces coding standards and catches common errors using configurable rules. Sourcery provides AI-powered refactoring suggestions and contextual code review. Running both gives you comprehensive coverage - Pylint handles style enforcement and basic error detection while Sourcery catches higher-level design improvements and idiomatic Python patterns.

How do I configure Sourcery rules in VS Code?

Create a .sourcery.yaml file in your project root. In this file you can define custom rules, set refactoring thresholds, exclude files or directories from analysis, and configure which rule sets to enable or disable. Sourcery reads this file automatically when you open the project in VS Code. Changes to the configuration take effect immediately without restarting the editor.

Does Sourcery slow down VS Code?

Sourcery has minimal impact on VS Code performance. The extension runs analysis asynchronously in the background, so it does not block typing or navigation. Suggestions appear after a short delay when you open or edit a file. For very large files or projects with thousands of files, you may notice slightly longer analysis times, but the extension is designed to prioritize the active file and analyze other files on demand.

Can I use Sourcery's chat feature in VS Code?

Yes. Sourcery includes an AI chat assistant accessible from the sidebar in VS Code. You can ask questions about your code, request explanations of specific functions, ask for refactoring suggestions, or get help debugging. The chat assistant has context about the file you are working on, so its responses are relevant to your actual codebase rather than generic advice.

How do I disable specific Sourcery suggestions in VS Code?

You can disable specific suggestion types in your .sourcery.yaml configuration file by adding rule IDs to the skip list under the refactor section. Alternatively, add a '# sourcery skip' comment above a specific line or block of code to suppress suggestions for that section. You can also hover over a suggestion in VS Code and click the dismiss option to tell Sourcery to deprioritize that pattern.

Does Sourcery work with VS Code remote development?

Yes. Sourcery works with VS Code Remote SSH, Remote Containers, and WSL. The extension runs on the remote host alongside your code, so analysis is performed locally on the remote machine. Install the Sourcery extension on the remote VS Code server instance, sign in, and it functions identically to a local installation. This makes Sourcery compatible with cloud development environments and remote workstations.

What is the difference between Sourcery in VS Code and Sourcery on GitHub?

Sourcery in VS Code provides real-time refactoring suggestions, inline code analysis, and an AI chat assistant as you write code. Sourcery on GitHub reviews pull requests after you push changes, posting review comments on the PR diff. The VS Code extension catches issues during development while the GitHub integration catches issues during code review. Using both together gives you feedback at two stages of the development workflow.

What are the best alternatives to Sourcery for VS Code?

For AI-powered code assistance in VS Code, GitHub Copilot ($19-39/user/month) provides code generation and completion. For broader code quality, CodeAnt AI ($24-40/user/month) combines AI code review, static analysis, secret detection, and DORA metrics. For Python-specific linting, Ruff and Pylint are free and have excellent VS Code extensions. For enterprise code quality with dashboards, SonarQube and DeepSource offer VS Code integrations alongside their platform features.

Explore More

Free Newsletter

Stay ahead with AI dev tools

Weekly insights on AI code review, static analysis, and developer productivity. No spam, unsubscribe anytime.

Join developers getting weekly AI tool insights.

Related Articles