Skip to main content

Building Custom AI Agent Extensions

1. Creating VS Code Chat Extensions

Example: Basic VS Code Chat Extension Structure

{
  "name": "my-ai-chat-extension",
  "version": "0.1.0",
  "engines": {
    "vscode": "^1.85.0"
  },
  "main": "dist/extension.js",
  "contributes": {
    "aiChatExtensions": [
      {
        "id": "my-ai-chat-extension",
        "name": "My AI Chat Extension",
        "description": "An extension that provides AI-powered chat capabilities."
      }
    ]
  }
}
Property Description Required
name The name of the extension Yes
version The semantic version of the extension Yes
engines.vscode Minimum VS Code version supported Yes
main Entry point of the extension (compiled JS) Yes
contributes.aiChatExtensions Configuration for AI chat extensions Yes

Example: AI Chat Extension Activation

import * as vscode from 'vscode';

export function activate(context: vscode.ExtensionContext) {
    const provider = new MyAIChatProvider();
    const disposable = vscode.ai.registerChatExtensionProvider(
        'my-ai-chat-extension',
        provider
    );
    context.subscriptions.push(disposable);
}

class MyAIChatProvider implements vscode.ChatExtensionProvider {
    async provideChatResponse(
        request: vscode.ChatRequest,
        context: vscode.ChatContext,
        token: vscode.CancellationToken
    ): Promise<vscode.ChatResponse> {
        return {
            content: [
                {
                    role: 'assistant',
                    content: 'Hello from My AI Chat Extension!'
                }
            ]
        };
    }
}
Note: The provideChatResponse method is where you define the logic for handling chat interactions.
Warning: Ensure that your extension handles cancellation tokens properly to avoid resource leaks.

Key Steps to Create a VS Code Chat Extension

  • Create a new extension project using the VS Code Extension Generator.
  • Define the extension metadata in package.json.
  • Implement the ChatExtensionProvider interface in your main extension file.
  • Register the provider using vscode.ai.registerChatExtensionProvider.
  • Test the extension in the VS Code development instance.

2. Registering Custom Tools via Extension API

Custom tools in AI-assisted development environments can be registered using the Extension API to extend functionality and integrate with external systems.

Property Description Values
tool.name Name of the custom tool string
tool.description Human-readable description of the tool's purpose string
tool.parameters Object defining input parameters for the tool object
tool.handler Function that executes when the tool is invoked function

Example: Registering a Custom Tool

const customTool = {
  name: "sendEmail",
  description: "Sends an email to a specified recipient",
  parameters: {
    to: { type: "string", required: true },
    subject: { type: "string", required: true },
    body: { type: "string", required: false }
  },
  handler: async (params) => {
    const { to, subject, body } = params;
    // Implementation logic here
    return `Email sent to ${to} with subject: ${subject}`;
  }
};

// Register tool via extension API
extension.registerTool(customTool);
Note: The handler function must be asynchronous and return a value that can be interpreted by the AI agent.
Warning: Tool registration must be done before the AI agent starts processing to ensure availability.

3. Publishing Agent Extensions

Field Description Example
name Extension name (must be unique) "my-ai-extension"
version Extension version (semantic versioning) "1.0.0"
description Short description of functionality "Adds code completion for Python"
main Entry point file (relative path) "dist/index.js"
aiAgent Configuration for AI agent integration
{
  "capabilities": ["codeCompletion", "linting"],
  "model": "gpt-4"
}

Example: Package.json Configuration

{
  "name": "my-ai-extension",
  "version": "1.0.0",
  "description": "Adds code completion for Python",
  "main": "dist/index.js",
  "aiAgent": {
    "capabilities": ["codeCompletion", "linting"],
    "model": "gpt-4"
  }
}
Note: Ensure the main entry point is built and available before publishing.
Warning: Extensions must pass AI agent validation to be published in the marketplace.

Publication Steps

  • Build the extension using npm run build
  • Validate AI capabilities with test suite
  • Upload to the AI Agent Marketplace dashboard
  • Submit for review and approval

Extension Types

  • Core Extensions: Built-in features, no external dependencies
  • Plugin Extensions: Extend existing AI capabilities with new models or tools
  • Custom Extensions: Fully custom AI logic, can define new agent behaviors

Deployment Workflow

  1. Create package.json with required fields
  2. Implement AI agent interface in main
  3. Run local validation tests
  4. Publish to marketplace via CLI or web dashboard
  5. Monitor usage and performance in analytics dashboard

4. Testing Custom Extensions Locally

Example: Local testing setup with mock AI service

const { createAgent } = require("./agent");
const mockAiService = {
  async generateResponse(prompt) {
    return "Mock response for: " + prompt;
  }
};

const agent = createAgent({ aiService: mockAiService });
agent
  .process("What is the weather?")
  .then((response) => console.log(response));
Feature Description Status
mockAiService Simulates AI responses for local testing NEW
agent.process() Processes input through the agent DEPRECATED

Testing Workflow

  1. Set up local mock AI service
  2. Initialize agent with mock service
  3. Run input through agent.process()
  4. Validate response matches expected output
Note: Use jest or mocha for unit testing custom extensions.
Warning: Avoid real API calls in local tests to prevent rate limits.

5. Handling Extension Authentication

Property Description Values Notes
auth.type Authentication method used by the extension oauth2, api-key, jwt Required for secure extension access
auth.scopes Permissions requested by the extension read:code, write:code Used in OAuth2 flows to define access level
auth.tokenUrl Endpoint to request OAuth2 tokens /auth/token Required for OAuth2 authentication flow
auth.clientId Unique identifier for the extension ext-123abc Registered with the AI agent platform
auth.clientSecret Secret key for client authentication secret-key-here Must be securely stored and never exposed

Example: Configuring OAuth2 Authentication

{
  "auth": {
    "type": "oauth2",
    "scopes": ["read:code", "write:code"],
    "tokenUrl": "/auth/token",
    "clientId": "ext-123abc",
    "clientSecret": "secret-key-here"
  }
}
Note: Ensure that the clientSecret is never exposed in client-side code or logs.
Warning: Misconfigured authentication can lead to unauthorized access to AI agent extensions.

6. Versioning and Updating Extensions

Version Type Description Usage
Major Breaking changes that require user action Increment when API or core logic changes
Minor Backward-compatible features added Increment for new capabilities or enhancements
Patch Backward-compatible bug fixes Increment for hotfixes or minor adjustments

Example: Versioning in Manifest

{
  "name": "custom-ai-agent-extension",
  "version": "2.1.3",
  "description": "Custom extension for AI-assisted development"
}

Workflow: Updating Extension

  1. Update version in manifest (e.g., package.json)
  2. Test changes in isolated environment
  3. Deploy to production or update user installations
  4. Notify users of breaking changes if needed
Note: Use semantic versioning (SemVer) to clearly communicate impact of updates.

7. Distributing Extensions to a Team

Method Description Requirements Notes
Package as NPM Module Wrap the extension in an NPM package for easy distribution and versioning. Valid package.json, published to npm registry or private registry. Supports dependency management and version control.
Share via Git Repository Host the extension code in a Git repository (e.g., GitHub, GitLab) for team access. Git repository with proper structure and documentation. Allows for collaboration and code review before deployment.
Use Extension Store Publish to an internal or public extension store (e.g., VS Code Marketplace, JetBrains Plugin Repository). Compliance with store guidelines and authentication. Provides visibility and discoverability for team members.

Example: Publishing to NPM

npm publish
Note: Ensure that the extension's package.json includes all necessary metadata and dependencies for seamless integration into AI development environments.

Best Practices for Team Distribution

  • Version control using semantic versioning (e.g., v1.0.0).
  • Include a README with usage instructions and examples.
  • Provide clear documentation for configuration options.

8. Deprecating and Removing Extensions

When an AI agent extension is no longer needed or has been superseded, it should be properly deprecated and eventually removed to maintain system integrity and performance.

Action Description Impact Notes
Mark as deprecated Update extension metadata to indicate deprecation status Extension remains functional but flagged for removal Use "deprecated": true in manifest
Set deprecation date Specify a timeline for removal (e.g., "deprecationDate": "2025-06-01") Users are warned about upcoming removal Recommended to provide migration path
Remove from registry Stop publishing new versions to public repositories Prevents new installations May still be available for existing users
Archive repository Move code to read-only archive (e.g., GitHub archive) Preserves historical context Helps with debugging and migration documentation

Example: Deprecation in Manifest

{
  "name": "ai-agent-extension-example",
  "version": "1.2.0",
  "deprecated": true,
  "deprecationDate": "2025-06-01",
  "replacement": "ai-agent-extension-new"
}
Note: Ensure all users are notified via release notes or changelogs before marking an extension as deprecated.
Warning: Removing extensions too abruptly can break existing AI agent workflows. Always provide a clear migration path or alternative solution.

Was this article helpful?