How to Build an AI‑Powered VS Code Extension in Minutes

This guide walks you through the VS Code extension architecture and provides a step‑by‑step example that creates a simple AI text‑explanation plugin, covering preparation, project scaffolding, command registration, API integration, debugging, and best‑practice security tips.

Ops Development & AI Practice
Ops Development & AI Practice
Ops Development & AI Practice
How to Build an AI‑Powered VS Code Extension in Minutes

Extension architecture overview

An extension is a Node.js process described by a package.json manifest. The manifest defines the extension’s identity, activation events, and contribution points that tell VS Code when to load the extension and what UI elements it contributes.

Extension Manifest ( package.json ) : metadata such as name, version, author, and configuration.

Activation Events : conditions that trigger loading, e.g., onCommand:myExtension.doSomething or onLanguage:python.

Contribution Points : declarations that add commands, menus, keybindings, views, settings, etc., to the VS Code UI.

VS Code API : a JavaScript/TypeScript API for interacting with the editor (accessing active text, showing notifications, managing terminals, etc.).

Hands‑on example: AI text‑explanation extension

Prerequisites

Node.js and npm or yarn installed.

Yeoman ( npm install -g yo) and the VS Code Extension Generator ( npm install -g generator-code).

Step 1 – Scaffold the project yo code Select New Extension (TypeScript), provide a name such as ai-text-explainer, set the identifier, description (e.g., "Explains selected text using an AI model."), initialize a Git repository, and choose npm or yarn as the package manager.

Step 2 – Define command and activation event

Edit package.json to add an activation event and a command contribution:

{
  "activationEvents": [
    "onCommand:ai-text-explainer.explainText"
  ],
  "contributes": {
    "commands": [{
      "command": "ai-text-explainer.explainText",
      "title": "AI Explain Selected Text"
    }],
    "keybindings": [{
      "command": "ai-text-explainer.explainText",
      "key": "ctrl+alt+e",
      "mac": "cmd+alt+e"
    }]
  }
}

This registers the command ai-text-explainer.explainText and binds it to Ctrl+Alt+E (Windows/Linux) or Cmd+Alt+E (macOS).

Step 3 – Implement command logic ( src/extension.ts )

import * as vscode from 'vscode';
import fetch from 'node-fetch'; // npm install node-fetch @types/node-fetch

const LLM_API_ENDPOINT = 'YOUR_LLM_API_ENDPOINT_HERE'; // replace with real endpoint
const API_KEY = 'YOUR_API_KEY_HERE'; // replace with real key

export function activate(context: vscode.ExtensionContext) {
  console.log('Extension "ai-text-explainer" is now active');

  const disposable = vscode.commands.registerCommand('ai-text-explainer.explainText', async () => {
    const editor = vscode.window.activeTextEditor;
    if (!editor) {
      vscode.window.showWarningMessage('No active text editor found.');
      return;
    }
    const selection = editor.selection;
    const selectedText = editor.document.getText(selection);
    if (!selectedText) {
      vscode.window.showWarningMessage('No text selected.');
      return;
    }

    vscode.window.withProgress({
      location: vscode.ProgressLocation.Notification,
      title: 'AI is thinking...',
      cancellable: false
    }, async () => {
      try {
        const response = await fetch(LLM_API_ENDPOINT, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${API_KEY}`
          },
          body: JSON.stringify({
            prompt: `Explain the following text:

${selectedText}`
            // add model‑specific parameters here (e.g., max_tokens)
          })
        });
        if (!response.ok) {
          throw new Error(`API request failed with status ${response.status}`);
        }
        const data: any = await response.json();
        const explanation = data.choices?.[0]?.text || data.explanation || 'No explanation received.';
        vscode.window.showInformationMessage(`AI Explanation: ${explanation}`);
      } catch (error: any) {
        console.error('Error calling LLM API:', error);
        vscode.window.showErrorMessage(`Failed to get explanation: ${error.message}`);
      }
    });
  });

  context.subscriptions.push(disposable);
}

export function deactivate() {}

Replace LLM_API_ENDPOINT and API_KEY with actual credentials and store them securely (e.g., VS Code secrets API or environment variables).

Step 4 – Run and debug

Press F5 in VS Code to launch an Extension Development Host window.

Open any text file, select a snippet, and trigger the command via the shortcut or the Command Palette ( Ctrl+Shift+P / Cmd+Shift+P).

Observe the "AI is thinking..." progress notification followed by an information message containing the AI‑generated explanation.

Important considerations

API calls : The example uses node-fetch. Install it with npm install node-fetch @types/node-fetch (or the yarn equivalent).

Security : Do not hard‑code API keys in source files that may be published. Use VS Code’s secrets API, environment variables, or a secure vault.

API compatibility : Different LLM services require different request formats and response parsing. Adjust headers, request body, and result extraction accordingly.

Error handling : The sample includes basic error handling; production code should provide richer user feedback, retry logic, and detailed logging.

Reference: https://code.visualstudio.com/api

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

TypeScriptLLMNode.jsAI integrationVS CodeExtension Development
Ops Development & AI Practice
Written by

Ops Development & AI Practice

DevSecOps engineer sharing experiences and insights on AI, Web3, and Claude code development. Aims to help solve technical challenges, improve development efficiency, and grow through community interaction. Feel free to comment and discuss.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.