Skip to content

Commit ebc37c2

Browse files
kingpanther13claude
andcommitted
fix: normalize api_get/api_post endpoints to prevent leading-slash path issues
The httpx client's base_url includes /api, so leading slashes in endpoints cause httpx to treat them as absolute paths from the host root, bypassing the base path. This made api_get("/api/events") 404 and api_get("/events") hit the wrong path. Added _normalize_endpoint() that strips leading slashes and any accidental /api/ prefix, so all three forms work identically: api_get("events"), api_get("/events"), api_get("/api/events") Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
1 parent 2f5a541 commit ebc37c2

1 file changed

Lines changed: 15 additions & 2 deletions

File tree

src/ha_mcp/tools/tools_code.py

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -93,14 +93,27 @@ async def _run_sandboxed_code(
9393
"""
9494
call_count = 0
9595

96+
def _normalize_endpoint(endpoint: str) -> str:
97+
"""Normalize endpoint to be relative to the httpx base URL (/api).
98+
99+
Leading slashes cause httpx to treat the path as absolute from the
100+
host root, bypassing the /api base path. Strip them (and any
101+
accidental /api/ prefix) so all three forms work identically:
102+
"events", "/events", "/api/events" → "events".
103+
"""
104+
ep = endpoint.lstrip("/")
105+
if ep.startswith("api/"):
106+
ep = ep[4:]
107+
return ep
108+
96109
async def _api_get(endpoint: str) -> Any:
97110
"""GET request to Home Assistant REST API."""
98111
nonlocal call_count
99112
call_count += 1
100113
if call_count > settings.code_mode_max_invocations:
101114
return {"error": f"API call limit exceeded ({settings.code_mode_max_invocations})"}
102115
try:
103-
response = await client.httpx_client.request("GET", endpoint)
116+
response = await client.httpx_client.request("GET", _normalize_endpoint(endpoint))
104117
try:
105118
return response.json()
106119
except json.JSONDecodeError:
@@ -118,7 +131,7 @@ async def _api_post(endpoint: str, data: dict[str, Any] | None = None) -> Any:
118131
post_kwargs: dict[str, Any] = {}
119132
if data is not None:
120133
post_kwargs["json"] = data
121-
response = await client.httpx_client.request("POST", endpoint, **post_kwargs)
134+
response = await client.httpx_client.request("POST", _normalize_endpoint(endpoint), **post_kwargs)
122135
try:
123136
return response.json()
124137
except json.JSONDecodeError:

0 commit comments

Comments
 (0)