{"record":{"id":"b7bed32465248ab7","repo":"datawhalechina/hello-agents","slug":"mx-apikey-export-mx-apikey-your-b7bed3","errorCode":null,"errorMessage":"MX_APIKEY 环境变量未设置，请先设置环境变量：\nexport MX_APIKEY=your_api_key_here\n或者在初始化时传入 api_key 参数","messagePattern":"MX_APIKEY 环境变量未设置，请先设置环境变量：\nexport MX_APIKEY=your_api_key_here\n或者在初始化时传入 api_key 参数","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"Co-creation-projects/lcyting-StockSage-agent/skills/资讯搜索/mx-search/mx_search.py","lineNumber":31,"sourceCode":"\ndef safe_filename(text: str, max_len: int = 80) -> str:\n    \"\"\"Convert query string to safe filenameh\"\"\"\n    cleaned = re.sub(r'[<>:\"/\\\\|?*]', \"_\", text).strip().replace(\" \", \"_\")\n    return (cleaned[:max_len] or \"query\").strip(\"._\")\n\nclass MXSearch:\n    \"\"\"妙想资讯搜索客户端\"\"\"\n    \n    BASE_URL = \"https://mkapi2.dfcfs.com/finskillshub/api/claw/news-search\"\n    \n    def __init__(self, api_key: Optional[str] = None):\n        \"\"\"\n        初始化客户端\n        :param api_key: MX API Key，如果不提供则从环境变量 MX_APIKEY 读取\n        \"\"\"\n        self.api_key = api_key or os.getenv(\"MX_APIKEY\")\n        if not self.api_key:\n            raise ValueError(\n                \"MX_APIKEY 环境变量未设置，请先设置环境变量：\\n\"\n                \"export MX_APIKEY=your_api_key_here\\n\"\n                \"或者在初始化时传入 api_key 参数\"\n            )\n    \n    def search(self, query: str) -> Dict[str, Any]:\n        \"\"\"\n        搜索金融资讯\n        :param query: 搜索问句\n        :return: API 响应结果\n        \"\"\"\n        headers = {\n            \"Content-Type\": \"application/json\",\n            \"apikey\": self.api_key\n        }\n        data = {\n            \"query\": query\n        }","sourceCodeStart":13,"sourceCodeEnd":49,"githubUrl":"https://github.com/datawhalechina/hello-agents/blob/606a07d341a47be773fab7f4b71177f53f96b2c3/Co-creation-projects/lcyting-StockSage-agent/skills/资讯搜索/mx-search/mx_search.py#L13-L49","documentation":"MXSearch.__init__ raises ValueError when neither the api_key parameter nor the MX_APIKEY environment variable yields a non-empty string. This is a startup-time configuration guard: the client refuses to build without credentials because every request to the mx news-search endpoint (https://mkapi2.dfcfs.com/finskillshub/api/claw/news-search) requires the key in its headers. It fires before any network I/O happens, so seeing it means the object was never constructed, not that a request failed.","triggerScenarios":"Calling MXSearch() (or MXSearch(api_key=None)/api_key=\"\") in a shell/process where MX_APIKEY was never exported; exporting it in one terminal but running the Python process from another (or from an IDE/systemd/cron) that does not inherit it; .env file exists but nothing loads it (no load_dotenv() in this skill module); key set only under a different name (MX_API_KEY vs MX_APIKEY).","commonSituations":"Fresh clone of StockSage-agent without copying .env.example; deploying to a server/container where the env var was not added to the service unit/image; running under an IDE launch configuration that bypasses the shell profile; typo in the variable name (MX_APIKEY is not the same as MX_API_KEY).","solutions":["Pass the key explicitly at construction: MXSearch(api_key=os.environ[\"MX_APIKEY\"]) or a literal/secret-manager value.","Export the exact variable in the launching shell: export MX_APIKEY=your_api_key_here, then re-run from that same shell.","If the key lives in .env, load it before constructing: from dotenv import load_dotenv; load_dotenv() (verify the .env line spells MX_APIKEY=... with no quotes/spaces issues).","For containers/services, add MX_APIKEY to the container env / systemd Environment= / CI secret so the process inherits it.","Add a fail-fast check at app startup (os.getenv(\"MX_APIKEY\")) so the error surfaces in logs with context instead of deep in the skill."],"exampleFix":"// before\nclient = MXSearch()\n// after\nimport os\nfrom dotenv import load_dotenv\nload_dotenv()\nclient = MXSearch(api_key=os.getenv(\"MX_APIKEY\"))  # raises early with your own context if still missing","handlingStrategy":"validation","validationCode":"import os\napi_key = os.getenv(\"MX_APIKEY\")\nif not api_key:\n    raise SystemExit(\"MX_APIKEY not set — export it or pass api_key= to MXSearch\")","typeGuard":null,"tryCatchPattern":"try:\n    client = MXSearch(api_key=os.getenv(\"MX_APIKEY\"))\nexcept ValueError as e:\n    # config error, not transient — fix environment, do not retry\n    logger.error(\"MXSearch config missing: %s\", e)\n    raise","preventionTips":["Load .env at the single process entry point with load_dotenv()","Fail fast on missing keys at startup, not at first search call","Never retry a ValueError — it is a config error, not transient"],"tags":["api-key","environment-variables","configuration","python","startup"],"backgroundTag":null,"analyzedSha":"606a07d341a47be773fab7f4b71177f53f96b2c3","analyzedAt":"2026-08-14T22:57:27.446Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}