fix: ensure API key detection properly reads .env in MCP context

Problem:
- Task Master model configuration wasn't properly checking for API keys in the project's .env file when running through MCP
- The isApiKeySet function was only checking session.env and process.env but not inspecting the .env file directly
- This caused incorrect API key status reporting in MCP tools even when keys were properly set in .env

Solution:
- Modified resolveEnvVariable function in utils.js to properly read from .env file at projectRoot
- Updated isApiKeySet to correctly pass projectRoot to resolveEnvVariable
- Enhanced the key detection logic to have consistent behavior between CLI and MCP contexts
- Maintains the correct precedence: session.env → .env file → process.env

Testing:
- Verified working correctly with both MCP and CLI tools
- API keys properly detected in .env file in both contexts
- Deleted .cursor/mcp.json to confirm introspection of .env as fallback works
This commit is contained in:
Eyal Toledano
2025-05-01 13:23:52 -04:00
parent d4a2e34b3b
commit 40df57f969
6 changed files with 105 additions and 46 deletions

View File

@@ -424,12 +424,13 @@ function getParametersForRole(role, explicitRoot = null) {
/**
* Checks if the API key for a given provider is set in the environment.
* Checks process.env first, then session.env if session is provided.
* Checks process.env first, then session.env if session is provided, then .env file if projectRoot provided.
* @param {string} providerName - The name of the provider (e.g., 'openai', 'anthropic').
* @param {object|null} [session=null] - The MCP session object (optional).
* @param {string|null} [projectRoot=null] - The project root directory (optional, for .env file check).
* @returns {boolean} True if the API key is set, false otherwise.
*/
function isApiKeySet(providerName, session = null) {
function isApiKeySet(providerName, session = null, projectRoot = null) {
// Define the expected environment variable name for each provider
if (providerName?.toLowerCase() === 'ollama') {
return true; // Indicate key status is effectively "OK"
@@ -454,7 +455,7 @@ function isApiKeySet(providerName, session = null) {
}
const envVarName = keyMap[providerKey];
const apiKeyValue = resolveEnvVariable(envVarName, session);
const apiKeyValue = resolveEnvVariable(envVarName, session, projectRoot);
// Check if the key exists, is not empty, and is not a placeholder
return (