Troubleshooting Steps for API Connection Issues with AI Providers in Secure Design
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. Each provider’s metadata—including the ID, name, and the configuration key for the API key—is defined in src/providers/types.ts between lines 78-97.
When the extension starts, the CustomAgentService validates whether required keys are present using this logic:
// 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:
-
Open Settings → Extensions → Secure Design.
-
Locate the entry matching your provider (e.g.,
openai.apiKey). -
Ensure the key matches exactly the
metadata.apiKeyConfigKeydefined for that provider insrc/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():
// 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:
// 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:
-
Open the "Secure Design" Output Channel via
View → Output → Secure Design. -
Search for messages containing "error" or "unauthorized".
-
If the
isApiKeyAuthErrorhelper returnstruefor 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:
// 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. You can inspect active registrations via the debug console:
// 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:
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:
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– Defines provider metadata, API-key handling viaisProviderMetadataWithApiKey, the abstractAIProviderclass, and theIProviderRegistryinterface. -
src/services/customAgentService.ts– Central service that validates credentials, detects authentication errors viaisApiKeyAuthError(), and manages the extension workspace. -
src/extension.ts– Activation entry point that registers the sidebar and creates the provider registry. -
src/di/ServiceContainer.ts– Wires up theChatSidebarProviderandCustomAgentService. -
src/providers/chatSidebarProvider.ts– UI layer that surfaces configuration commands to the user.
Summary
-
Verify configuration keys in VS Code settings match the
apiKeyConfigKeydefined insrc/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
isApiKeyAuthErrorto distinguish auth failures from network issues. -
Validate model IDs exist in the provider’s
modelsarray 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. 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 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 defines the registry contract. During a debugging session, you can access the registry instance created in 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 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.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →