architecture.md
| source_path | references/architecture.md |
|---|---|
| source_sha256 | 6ba32c5a1498c6660f79db3feeb0f49226344054bae7cdc1d84d8440147d5509 |
| source_url | https://github.com/adithya-s-k/FineEnvs/blob/fee6f71a70d0df315c2e2712859eb15689968b3a/.claude/skills/generate-openenv-env/references/architecture.md |
| supporting_skill_id | 40341 |
| upstream_revision | fee6f71a70d0df315c2e2712859eb15689968b3a |
OpenEnv architecture (deep)
Wire protocol
OpenEnv uses MCP over HTTP. The server exposes:
GET /health→{"status": "healthy"}GET /metadata→ env name + descriptionGET /openapi.json→ full OpenAPI schemaPOST /reset→ start a new episode (body matchesreset()'s kwargs)POST /step→ execute anAction(CallToolActionfor tool calls)GET /state→ fetch the currentStateobjectGET /web/...→ optional Gradio UI mount (whenENABLE_WEB_INTERFACE=true)
The MCP-specific surface lives behind /step: a CallToolAction(tool_name="x", arguments={...}) returns a CallToolObservation(result={"content": [...], "data": ..., "is_error": ...}). Tool discovery is via a list-tools action, not a separate REST endpoint — MCPToolClient.list_tools() does this transparently.
MCPEnvironment lifecycle
__init__— register tools on aFastMCPinstance, thensuper().__init__(mcp). Don't allocate per-episode state here; it'll outlive episodes.reset(seed, episode_id, **kwargs)— called once per episode. Allocate the sandbox, store session ids inself._state, return anObservation(done=False, reward=None, metadata={...}).step(action, timeout_s, **kwargs)— inherited; dispatchesCallToolActionto the right@mcp.toolfunction. Override only if you need pre/post hooks (step counter, terminate detection).step_async(...)— same but async. If you overridestep, override this too._step_impl(action, ...)— fallback for non-MCPActiontypes. Usually return an error observation.stateproperty — returns the current state for/stateendpoint.
Concurrent sessions
SUPPORTS_CONCURRENT_SESSIONS = True enables the framework to multiplex sessions inside one process. Only set this if you actually isolate state per session-id — otherwise sessions clobber each other.
For sandbox-per-episode envs: usually don't set this true. Run multiple replicas of the env instead (set max_concurrent_envs in create_app).
Tool returns
FastMCP serializes tool returns by inspecting the type:
| Return type | Becomes | Model sees |
|---|---|---|
str |
TextContent(type="text", text=...) |
the string |
Image(data=bytes, format="png") |
ImageContent(type="image", data=<base64>, mimeType="image/png") |
the actual pixels |
dict |
TextContent with JSON-serialized text |
the JSON string |
| Pydantic model | structured data field |
depends on client |
For computer-use / vision envs, always use Image. Returning base64 in a string makes the model effectively blind.
Custom Gradio UI
Pass gradio_builder= to create_app. The signature is:
def builder(web_manager, action_fields, metadata, is_chat_env, title, quick_start_md) -> gr.Blocks: ...
You can ignore most args and just instantiate the env yourself inside the builder. For computer-use envs, the canonical pattern includes an iframe panel showing the E2B sandbox stream URL alongside text controls.
Dual-import idiom
Inside server/, files use:
try:
from .models import State # works in repo (PYTHONPATH=src:envs)
except ImportError:
from models import State # works in Docker (PYTHONPATH=/app/env)
Same applies inside server/<env>_environment.py for sibling modules. Always include both. OpenEnv's CLI builds Docker images that flatten the package layout; the relative import will fail there.
Production deployment
Dockerfile uses ghcr.io/huggingface/openenv-base:latest as a multi-stage builder. The runtime image copies the venv and source. Healthcheck via /health. For HF Spaces:
app_port: 8000in README frontmatterbase_path: /webif you want the Gradio UI mountedE2B_API_KEY(and any other secrets) as Space secrets, not env varsMAX_CONCURRENT_ENVS=2typically — sandbox-per-episode is RAM-heavy
What can go wrong
KeyError: 'tools'fromPOST /list_tools— that endpoint doesn't exist. UseMCPToolClient.- Screenshot returns
Nonefromenv.call_tool("screenshot")— the convenience method strips to structureddata. Useenv.step(CallToolAction(...))and readobs.result["content"]. from ..module import Xfails in Docker — missing dual-import.ENABLE_WEB_INTERFACE=trueset but nogradio_builderpassed — Gradio mounts a default UI; setos.environ["ENABLE_WEB_INTERFACE"]beforecreate_appif you want the custom one.
Children
No children yet.
Like how this is organised?
Build your own Memory tree on knowen.md: notes, decisions and tasks in one connected markdown graph, shared with your team and your AI agents.