FoundationAgents/MetaGPT · error · EnvKeyNotFoundError
EnvKeyNotFoundError: {key}, app_name:{app_name or ''}
Error message
EnvKeyNotFoundError: {key}, app_name:{app_name or ''} What it means
EnvKeyNotFoundError from get_env in metagpt/tools/libs/env.py: the requested key was not found as an environment variable (with the app-name prefix, '-' replaced by '_') nor in the shared Context.kwargs mapping. It signals a missing configuration value, not a broken API call.
Source
Thrown at metagpt/tools/libs/env.py:45
async def default_get_env(key: str, app_name: str = None) -> str:
app_key = to_app_key(key=key, app_name=app_name)
if app_key in os.environ:
return os.environ[app_key]
env_app_key = app_key.replace("-", "_") # "-" is not supported by linux environment variable
if env_app_key in os.environ:
return os.environ[env_app_key]
from metagpt.context import Context
context = Context()
val = context.kwargs.get(app_key, None)
if val is not None:
return val
raise EnvKeyNotFoundError(f"EnvKeyNotFoundError: {key}, app_name:{app_name or ''}")
async def default_get_env_description() -> Dict[str, str]:
result = {}
for k in os.environ.keys():
app_name, key = split_app_key(k)
call = f'await get_env(key="{key}", app_name="{app_name}")'
result[call] = f"Return the value of environment variable `{k}`."
from metagpt.context import Context
context = Context()
for k in context.kwargs.__dict__.keys():
app_name, key = split_app_key(k)
call = f'await get_env(key="{key}", app_name="{app_name}")'
result[call] = f"Get the value of environment variable `{k}`."
return result
View on GitHub (pinned to 11cdf466d0)
Solutions
- Export the correctly prefixed variable: the tool derives it from app_name + key with '-' mapped to '_' (e.g. APPNAME_KEY)
- Or put the value into Context kwargs under the app-qualified key
- Inspect `await default_get_env_description()` to see the exact call/naming the tool expects
Example fix
# before val = await get_env(key="API_KEY", app_name="my-app") # raises # after export MY_APP_API_KEY=sk-... # '-' becomes '_', prefixed by app name val = await get_env(key="API_KEY", app_name="my-app")
Defensive patterns
Strategy: validation
Validate before calling
import os
from metagpt.tools.libs.env import split_app_key
composed = (app_name + "_" + key).replace("-", "_") if app_name else key.replace("-", "_")
if composed not in os.environ and not Context().kwargs.get(f"{app_name}_{key}".replace("-", "_") if app_name else key):
raise SystemExit(f"missing env value: {composed}") Try / catch
try:
val = await get_env(key=key, app_name=app_name)
except EnvKeyNotFoundError:
val = default_value # or prompt the user to configure Prevention
- Run `await default_get_env_description()` once to learn the exact expected names
- Centralize secrets in .env / secret manager and load before startup
- Remember '-' becomes '_' and app_name prefixes the variable
When it happens
Trigger: await get_env(key='SERPER_API_KEY', app_name='metagpt') when neither METAGPT_SERPER_API_KEY-style env var exists nor context.kwargs contains the key under the app-qualified name.
Common situations: Forgot to export the variable or add it to .env; app_name/key mismatch so the composed env var name doesn't match what was set; running in a fresh shell/CI where secrets were never injected; the key exists under a different app namespace.
Related errors
- Please set your API key in {root_config_path}. If you also s
- Please set your API key in {repo_config_path}
- Please set your API key in config2.yaml
- device-id: {device_id} not found
- create device path: {folder_path} failed
AI-assisted analysis of FoundationAgents/MetaGPT@11cdf466d0 (2026-08-14).
Data as JSON: /api/errors/4d21097c031ec4be.
Report an issue: GitHub.