UnboundLocalError: 'os' in serve() when both port and callback_url are explicit
Summary
AgentServerHandler.serve() raises UnboundLocalError: cannot access local variable 'os' when port is passed explicitly and agent.base_url is already set (e.g. via callback_url= on the Agent constructor).
Repro
from agentfield import Agent
app = Agent(
node_id="demo",
agentfield_server="https://example.invalid",
callback_url="http://demo.local:8001",
)
if __name__ == "__main__":
app.serve(host="0.0.0.0", port=8001)
Traceback (most recent call last):
File ".../main.py", line 49, in <module>
app.serve(host="0.0.0.0", port=8001)
File ".../agentfield/agent_server.py", line 1140, in serve
env_log_level = os.getenv("UVICORN_LOG_LEVEL", log_level).lower()
^^
UnboundLocalError: cannot access local variable 'os' where it is not associated with a value
Root cause
agent_server.py imports os at module level (line 3), but serve() also contains two import os statements inside conditional branches:
- Line 838 — only runs when
port is None - Line 902 — only runs when
not self.agent.base_url
Because Python's compiler treats any name assigned anywhere in a function (including via import) as local for the entire function scope, those nested imports shadow the module-level os throughout serve(). When neither branch executes (explicit port + explicit callback_url), the local os is declared but never bound, and line 1140's os.getenv(...) raises UnboundLocalError.
Fix
Drop the two redundant import os lines inside serve() — the module-level import already covers them.
@@ line ~838 @@
if port is None:
# Check for AgentField CLI integration via environment variable
- import os
-
env_port = os.getenv("PORT")
@@ line ~902 @@
if not self.agent.base_url:
# Check AGENT_CALLBACK_URL environment variable before defaulting to localhost
- import os
import urllib.parse
env_callback_url = os.getenv("AGENT_CALLBACK_URL")
Environment
agentfield0.1.9- Python 3.14
- macOS (Darwin 25.3.0, arm64)
I checked current main before opening a PR. This appears to already be fixed there: sdk/python/agentfield/agent_server.py has a module-level import os and the serve() branches no longer contain the nested import os statements described in the issue, so the explicit port + explicit callback_url path should not hit the local-shadowing UnboundLocalError anymore. The fix also appears to be mentioned in the changelog. If this still reproduces from main, please share the commit/version and I can take another look.
Seems to be fixed, please feel free to reopen if not.