# Troubleshooting Steps for API Connection Issues with AI Providers in Secure Design

> Troubleshoot AI provider API connection failures in Secure Design. Verify API keys, check output for errors, and confirm model IDs exist to resolve common issues.

- Repository: [Harold Martin/secure-design](https://github.com/hbmartin/secure-design)
- Tags: how-to-guide
- Published: 2026-03-03

---

**To resolve AI provider connection failures in the Secure Design extension, verify your API key is correctly stored in VS Code settings, check the Secure Design output channel for authentication-specific error messages, and ensure your model ID exists in the provider registry.**

When working with the Secure Design VS Code extension, developers frequently integrate multiple AI providers to analyze code architecture, but connection failures can block functionality. This guide provides actionable troubleshooting steps for API connection issues with AI providers based on the actual source code implementation in the hbmartin/secure-design repository, covering credential validation, error detection, and registry inspection.

## Verify API Key Configuration in VS Code Settings

The extension stores provider credentials in VS Code’s [`settings.json`](https://github.com/hbmartin/secure-design/blob/main/settings.json). Each provider’s metadata—including the ID, name, and the configuration key for the API key—is defined in [`src/providers/types.ts`](https://github.com/hbmartin/secure-design/blob/main/src/providers/types.ts) between lines 78-97.

When the extension starts, the `CustomAgentService` validates whether required keys are present using this logic:

```ts
// src/services/customAgentService.ts
if (!isProviderMetadataWithApiKey(metadata)) {
    // Provider does not need an API key (e.g., local models)
    return true;
}
const primaryKey = config.config.get<string>(metadata.apiKeyConfigKey);
if (!primaryKey?.trim()) {
    return false; // Missing or empty API key
}
if (metadata.additionalConfigKeys) {
    return metadata.additionalConfigKeys.every(key => config.config.get<string>(key));
}

```

To verify your configuration:

1. Open **Settings → Extensions → Secure Design**.

2. Locate the entry matching your provider (e.g., `openai.apiKey`).

3. Ensure the key matches exactly the `metadata.apiKeyConfigKey` defined for that provider in [`src/providers/types.ts`](https://github.com/hbmartin/secure-design/blob/main/src/providers/types.ts).

## Validate Credentials Using Built-in Checks

Most providers implement `validateCredentials` through the abstract `AIProvider` base class. Although concrete implementations reside in external packages, the extension invokes validation before making requests. If validation fails, the user receives a message generated from `getCredentialsErrorMessage()`:

```ts
// src/providers/types.ts
getCredentialsErrorMessage(): string {
    const metadata = (this.constructor as typeof AIProvider).metadata;
    return `${metadata.name} credentials not configured. Please run "${metadata.configureCommand}" command.`;
}

```

When you see this error, run the command shown (e.g., `Secure Design: Configure OpenAI`) from the command palette and re-enter your API key.

## Check Extension Logs for Authentication Errors

All network-related errors are logged via the `ILogger` instance. The `CustomAgentService` includes a helper method to detect common authentication failure patterns:

```ts
// src/services/customAgentService.ts
isApiKeyAuthError(errorMessage: string): boolean {
    const lowerError = errorMessage.toLowerCase();
    return (
        lowerError.includes('api key') ||
        lowerError.includes('authentication') ||
        lowerError.includes('unauthorized') ||
        lowerError.includes('invalid_api_key')
    );
}

```

To inspect logs:

1. Open the **"Secure Design" Output Channel** via `View → Output → Secure Design`.

2. Search for messages containing "error" or "unauthorized".

3. If the `isApiKeyAuthError` helper returns `true` for your error message, the issue is likely an invalid or missing API key rather than a network problem.

## Confirm Network Connectivity and Proxy Settings

The extension performs HTTP calls from the VS Code process. Ensure your machine can reach the provider’s endpoint (e.g., `https://api.openai.com`) using `curl` or a browser request outside VS Code. If you are behind a corporate proxy, configure VS Code’s proxy settings (`http.proxy`) and restart the extension host.

## Validate Model Identifiers

After authentication succeeds, requests are sent to the selected model. The model list is defined in each provider’s implementation, but the abstract base class supplies validation helpers:

```ts
// src/providers/types.ts
getModel(modelId: string): ModelConfig | undefined {
    return this.models.find(m => m.id === modelId);
}

```

Verify that your chosen model ID (e.g., `gpt-4o`) exists in the provider’s `models` array. If the model is unknown, the request will be rejected with a *model not found* error before reaching the provider’s API.

## Re-initialize the Extension Workspace

Sometimes the workspace directory (`.superdesign`) or internal state becomes stale. Run **"Secure Design: Reload Extension"** from the command palette to force `CustomAgentService` to re-run `setupWorkingDirectory()` and reload settings from disk.

## Debug Provider Registration (Advanced)

All provider instances are stored in the `IProviderRegistry` defined in [`src/providers/types.ts`](https://github.com/hbmartin/secure-design/blob/main/src/providers/types.ts). You can inspect active registrations via the debug console:

```ts
// src/providers/types.ts – IProviderRegistry interface
export interface IProviderRegistry {
    register(provider: AIProvider): void;
    getProvider(providerId: ProviderId): AIProvider | undefined;
    getAllProviders(): AIProvider[];
    getAllModels(): ModelConfigWithProvider[];
}

```

During a debugging session, call `registry.getAllProviders()` to confirm your expected provider is registered and that the `metadata.id` matches the configuration key you edited.

## Code Examples

### Testing Provider Credentials Programmatically

This script validates whether your API key is present in the VS Code configuration:

```ts
import * as vscode from 'vscode';
import { isProviderMetadataWithApiKey, ProviderMetadata } from './providers/types';

async function testCredentials(providerId: string) {
    const config = vscode.workspace.getConfiguration('secureDesign');
    const metadata: ProviderMetadata = {
        id: providerId as any,
        name: 'OpenAI',
        configureCommand: 'secureDesign.configureOpenAI',
        apiKeyConfigKey: 'openai.apiKey',
    };

    if (!isProviderMetadataWithApiKey(metadata)) {
        vscode.window.showInformationMessage('Provider does not require an API key.');
        return;
    }

    const apiKey = config.get<string>(metadata.apiKeyConfigKey);
    if (!apiKey?.trim()) {
        vscode.window.showErrorMessage('API key missing. Run the configure command.');
    } else {
        vscode.window.showInformationMessage('API key is present.');
    }
}

testCredentials('openai');

```

### Logging Authentication Failures

Use this pattern to distinguish authentication errors from other failures:

```ts
import { getLogger } from 'react-vscode-webview-icp/host';
import { CustomAgentService } from './services/customAgentService';

const logger = getLogger('AuthDebug');
const service = new CustomAgentService(/* workspaceStateService */);

async function runQuery() {
    try {
        await service.query([], new AbortController(), () => {});
    } catch (e) {
        const msg = e instanceof Error ? e.message : String(e);
        if (service.isApiKeyAuthError(msg)) {
            logger.error('Authentication failed – check your API key', { error: msg });
        } else {
            logger.error('Query failed', { error: msg });
        }
    }
}

runQuery();

```

## Key Files Reference

The following source files contain the essential logic for troubleshooting API connection issues:

- **[`src/providers/types.ts`](https://github.com/hbmartin/secure-design/blob/main/src/providers/types.ts)** – Defines provider metadata, API-key handling via `isProviderMetadataWithApiKey`, the abstract `AIProvider` class, and the `IProviderRegistry` interface.

- **[`src/services/customAgentService.ts`](https://github.com/hbmartin/secure-design/blob/main/src/services/customAgentService.ts)** – Central service that validates credentials, detects authentication errors via `isApiKeyAuthError()`, and manages the extension workspace.

- **[`src/extension.ts`](https://github.com/hbmartin/secure-design/blob/main/src/extension.ts)** – Activation entry point that registers the sidebar and creates the provider registry.

- **[`src/di/ServiceContainer.ts`](https://github.com/hbmartin/secure-design/blob/main/src/di/ServiceContainer.ts)** – Wires up the `ChatSidebarProvider` and `CustomAgentService`.

- **[`src/providers/chatSidebarProvider.ts`](https://github.com/hbmartin/secure-design/blob/main/src/providers/chatSidebarProvider.ts)** – UI layer that surfaces configuration commands to the user.

## Summary

- **Verify configuration keys** in VS Code settings match the `apiKeyConfigKey` defined in [`src/providers/types.ts`](https://github.com/hbmartin/secure-design/blob/main/src/providers/types.ts).

- **Use built-in validation** by running the configure command shown in credential error messages.

- **Check the Output channel** for messages flagged by `isApiKeyAuthError` to distinguish auth failures from network issues.

- **Validate model IDs** exist in the provider’s `models` array before sending requests.

- **Reload the extension** via the command palette if the workspace state becomes stale.

## Frequently Asked Questions

### Why does Secure Design say my credentials are not configured when I already added my API key?

The extension checks for the specific configuration key defined in `metadata.apiKeyConfigKey` within [`src/providers/types.ts`](https://github.com/hbmartin/secure-design/blob/main/src/providers/types.ts). If your settings use a different key name, or if the value is empty/whitespace-only, the `CustomAgentService` validation will fail. Ensure the key matches exactly and reload the extension.

### How can I tell if an API error is due to authentication or network problems?

Check the Secure Design output channel for error messages. The `isApiKeyAuthError` method in [`src/services/customAgentService.ts`](https://github.com/hbmartin/secure-design/blob/main/src/services/customAgentService.ts) specifically scans for keywords like "api key", "authentication", "unauthorized", and "invalid_api_key". If these appear, the issue is credential-related; otherwise, check your network connectivity or proxy settings.

### Where is the provider registry stored, and how can I inspect it?

The `IProviderRegistry` interface in [`src/providers/types.ts`](https://github.com/hbmartin/secure-design/blob/main/src/providers/types.ts) defines the registry contract. During a debugging session, you can access the registry instance created in [`src/extension.ts`](https://github.com/hbmartin/secure-design/blob/main/src/extension.ts) and call `getAllProviders()` to verify that your provider is registered with the correct `metadata.id` and configuration keys.

### What should I do if authentication succeeds but my requests return model errors?

Verify that the model ID you selected exists in the provider’s `models` array. The `getModel(modelId)` method in [`src/providers/types.ts`](https://github.com/hbmartin/secure-design/blob/main/src/providers/types.ts) returns `undefined` if the model is not found, which typically results in a rejection before the API call is made. Check that you are using a valid model identifier supported by your chosen provider.