mastra-ai/mastra · error · HTTPException
No model with a configured API key found. Please set the req
Error message
No model with a configured API key found. Please set the required environment variable for your model provider.
What it means
This HTTP 400 error is thrown by the agents handler when `findConnectedModel(agent)` returns no model whose provider has a configured API key. The server needs at least one model with credentials present in the environment (or model config) to build a system-prompt agent. It mirrors how chat resolves models: only providers with a usable key are considered connected.
Source
Thrown at packages/server/src/server/handlers/agents.ts:3511
export const ENHANCE_INSTRUCTIONS_ROUTE = createRoute({
method: 'POST',
path: '/agents/:agentId/instructions/enhance',
responseType: 'json',
pathParamSchema: agentIdPathParams,
bodySchema: enhanceInstructionsBodySchema,
responseSchema: enhanceInstructionsResponseSchema,
summary: 'Enhance agent instructions',
description: 'Uses AI to enhance or modify agent instructions based on user feedback',
tags: ['Agents'],
requiresAuth: true,
handler: async ({ mastra, agentId, instructions, comment }) => {
try {
const agent = await getAgentFromSystem({ mastra, agentId });
// Find the first model with a connected provider (similar to how chat works)
const model = await findConnectedModel(agent);
if (!model) {
throw new HTTPException(400, {
message:
'No model with a configured API key found. Please set the required environment variable for your model provider.',
});
}
const systemPromptAgent = new Agent({
id: 'system-prompt-enhancer',
name: 'system-prompt-enhancer',
instructions: ENHANCE_SYSTEM_PROMPT_INSTRUCTIONS,
model,
});
const result = await systemPromptAgent.generate(
`We need to improve the system prompt.
Current: ${instructions}
${comment ? `User feedback: ${comment}` : ''}`,
{
structuredOutput: {View on GitHub (pinned to 75dd419e61)
Solutions
- Set the required environment variable for your model provider (e.g. OPENAI_API_KEY) in the shell or .env file the Mastra server loads, then restart the server.
- Verify the agent's model configuration points at a provider you have credentials for.
- If using a custom/nonstandard provider, ensure its key is registered in the way Mastra's findConnectedModel expects (model-level config or standard env var).
Example fix
// before // server started with: pnpm mastra dev (no OPENAI_API_KEY set) // after // .env OPENAI_API_KEY=sk-... // then: pnpm mastra dev
Defensive patterns
Strategy: validation
Validate before calling
// before calling the endpoint, check the provider key is set
if (!process.env.OPENAI_API_KEY) {
throw new Error('Set OPENAI_API_KEY (or your provider key) before fetching the system prompt');
} Try / catch
try {
const res = await fetch(`/api/agents/${id}/system-prompt`);
if (res.status === 400) throw new Error('No model with configured API key; check provider env vars');
const data = await res.json();
} catch (e) { console.error(e.message); } Prevention
- Keep provider API keys in a .env loaded by the Mastra server process and validate them at startup.
- Add a boot-time check that fails fast when required provider env vars are missing.
- Pin agents to providers you have credentials for.
When it happens
Trigger: Calling the agent system-prompt endpoint (GET on the route at packages/server/src/server/handlers/agents.ts:3511) when `getAgentFromSystem` succeeds but no model attached to the agent has a provider API key set in the environment.
Common situations: Running the Mastra server without provider env vars (e.g. OPENAI_API_KEY), .env not loaded by the server process, using a provider that requires custom env configuration, or an agent whose model config points at a provider with no credentials.
Understand the failure class
Background: "environment variable is not set" and "Missing keys in environment" errors: what missing required env var messages mean and how to fix them — this error's family across 28 libraries.
Related errors
- Parallel API key is required. Pass { apiKey } or set the PAR
- Perplexity API key is required. Pass { apiKey } or set the P
- Tavily API key is required. Pass { apiKey } or set TAVILY_AP
- API key not found for provider mastra. Set MASTRA_GATEWAY_AP
- API key not found for provider ${normalizedConfig.providerId
AI-assisted analysis of mastra-ai/mastra@75dd419e61 (2026-08-30).
Data as JSON: /api/errors/1ebb629455f847f3.
Report an issue: GitHub.