From e236aaf55e00a44f425b91e3581e6c61af4dc4e0 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Sun, 8 Nov 2026 23:01:33 -0800 Subject: [PATCH 1/3] feat(gateway): a composed card states each child's environment_name, which lookups by name read (FD-5376) The gateway sets environment_name on each entry of children_environments: an MCP server's key without its mcp- prefix, a website's or a computer's key itself. EnvironmentCard gains the optional field; ChildEnv carries it, and known_as (the stated name, else the card's own) is what child_named, find_child, DeployedEnv.child_env, website_child, legacy_protocol's server listing, the MCP CLI builder and site routing's _served_as look children up by. A server or website whose card is named apart from its environment name is no longer missed by loads, snapshots and clock sync; a card from a gateway that states none resolves as before. Co-Authored-By: Claude Opus 5.5 --- packages/agentenv-protocol/README.md | 5 +++- .../src/agentenv_protocol/client.py | 25 ++++++++++++----- .../src/agentenv_protocol/types.py | 2 ++ .../agentenv-protocol/tests/test_client.py | 16 +++++++++++ src/agent_env/env/env.py | 4 +-- .../env/envs/computer/utils/sites.py | 7 +++-- src/agent_env/env/gateway/gateway.py | 11 +++++++- src/agent_env/env/legacy_protocol.py | 2 +- .../mcp_cli_builder/build_mcp_cli.py | 2 +- tst/unit/env/envs/test_computer_sites.py | 22 +++++++++++++++ tst/unit/env/gateway/gateway_card_test.py | 27 +++++++++++++++++++ tst/unit/env/test_env.py | 16 ++++++++++- tst/unit/env/test_legacy_protocol.py | 8 ++++++ 13 files changed, 131 insertions(+), 16 deletions(-) diff --git a/packages/agentenv-protocol/README.md b/packages/agentenv-protocol/README.md index 0feaec16d..372af663c 100644 --- a/packages/agentenv-protocol/README.md +++ b/packages/agentenv-protocol/README.md @@ -200,7 +200,10 @@ address the card was fetched from. On the client side, `client.mcp_path(card)` r declared path, or `/mcp` for a card without one. A composed card, such as a gateway's, nests each backing environment's card under -`children_environments`, its `url` and endpoints rooted at the route the composer serves it at. +`children_environments`, its `url` and endpoints rooted at the route the composer serves it at, +and its `environment_name`: the name the child env is registered as, which its own card's `name` +needn't be. A lookup by name finds a child by its `environment_name`, else, from a composer that +states none, by its card's `name` (`ChildEnv.known_as`). `client.children(card)` returns each as a `ChildEnv` (its `name`, `url` and `card`, with its `extensions`, `operations` and `serves(method)`, and `base_url(address)`, its data plane resolved against the composed card's address). Two children may share a name, as a website and an MCP diff --git a/packages/agentenv-protocol/src/agentenv_protocol/client.py b/packages/agentenv-protocol/src/agentenv_protocol/client.py index 122c713a0..a895c8fed 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/client.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/client.py @@ -224,11 +224,19 @@ class ChildEnv: """One child env a composed card nests under ``children_environments``: its ``name`` and ``url`` as its card gives them, and that ``card``, which says what it offers. A composer roots each child's ``url`` (and its endpoints) at the route it serves the child at, so two children sharing a name have distinct urls; ``url`` is None for a child - whose card names none.""" + whose card names none. ``environment_name`` is the name the composer states the child is registered as, None + from a composer that states none.""" name: str | None url: str | None card: dict = field(hash=False, repr=False) + environment_name: str | None = None + + @property + def known_as(self) -> str | None: + """The name a lookup finds the child by: the ``environment_name`` its composer states, else its card's + ``name``, which an env built on this SDK serves its environment name as.""" + return self.environment_name or self.name @property def extensions(self) -> list[dict]: @@ -258,7 +266,8 @@ def base_url(self, address: str) -> str: def children(card: dict) -> list[ChildEnv]: """Each child env a composed card nests under ``children_environments``, in its order; none for a leaf card, or one whose ``children_environments`` is missing or null. An entry that isn't an object is skipped.""" - return [ChildEnv(name=child.get("name"), url=child.get("url"), card=child) + return [ChildEnv(name=child.get("name"), url=child.get("url"), card=child, + environment_name=child.get("environment_name")) for child in card.get("children_environments") or [] if isinstance(child, dict)] @@ -279,9 +288,10 @@ class AmbiguousChildError(LookupError): def child_named(card: dict, name: str) -> ChildEnv | None: - """The one child env of a composed card named ``name``, or None when none is; raises ``AmbiguousChildError`` when - several are, as a website and an MCP server sharing a name are, which ``child_at`` tells apart by their urls.""" - found = [child for child in children(card) if child.name == name] + """The one child env of a composed card known as ``name`` (``ChildEnv.known_as``), or None when none is; raises + ``AmbiguousChildError`` when several are, as a website and an MCP server sharing a name are, which ``child_at`` + tells apart by their urls.""" + found = [child for child in children(card) if child.known_as == name] if len(found) > 1: raise AmbiguousChildError(f"{len(found)} child envs are named {name!r} ({', '.join(str(c.url) for c in found)}); " "look one up by its url") @@ -297,10 +307,11 @@ def find_child(card: dict, name: str) -> dict | None: name here, then use the child card with `find_extension`/`invoke_extension`. Tolerates a missing/null `children_environments` so single/leaf cards return None rather than raising. Two children sharing `name` return the first; `child_named` refuses that, and `child_at` - finds a child by its url, which tells them apart. + finds a child by its url, which tells them apart. A child is known by the `environment_name` + its composer states, else by its card's `name`. """ for child in card.get("children_environments") or []: - if child.get("name") == name: + if isinstance(child, dict) and (child.get("environment_name") or child.get("name")) == name: return child return None diff --git a/packages/agentenv-protocol/src/agentenv_protocol/types.py b/packages/agentenv-protocol/src/agentenv_protocol/types.py index 0c91725df..8e4ce6cbf 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/types.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/types.py @@ -200,6 +200,8 @@ class EnvironmentCard(BaseModel): additionalInterfaces: list[EnvironmentInterface] = Field(default_factory=list) capabilities: EnvironmentCapabilities = Field(default_factory=EnvironmentCapabilities) children_environments: Optional[list[EnvironmentCard]] = None + # Set by a composer on each child it nests: the name the child env is registered as, which its own name needn't be. + environment_name: Optional[str] = None EnvironmentCard.model_rebuild() diff --git a/packages/agentenv-protocol/tests/test_client.py b/packages/agentenv-protocol/tests/test_client.py index 96265beda..3c6d3c570 100644 --- a/packages/agentenv-protocol/tests/test_client.py +++ b/packages/agentenv-protocol/tests/test_client.py @@ -250,6 +250,22 @@ def test_child_named_refuses_a_name_two_children_share(): assert protocol_v1.find_child(_SHARED_NAME, "mail")["url"] == "/svc/mcp-mail/agentenv" +_STATED = {"name": "gw", "children_environments": [ + {"name": "Notes", "url": "/svc/notes/agentenv", "environment_name": "notes"}, + {"name": "slack", "url": "/svc/mcp-slack/agentenv"}, +]} + + +def test_a_child_is_known_by_the_environment_name_its_composer_states_else_by_its_cards_name(): + notes, slack = protocol_v1.children(_STATED) + assert (notes.name, notes.environment_name, notes.known_as) == ("Notes", "notes", "notes") + assert (slack.environment_name, slack.known_as) == (None, "slack") # a composer that states none + assert protocol_v1.child_named(_STATED, "notes").url == "/svc/notes/agentenv" + assert protocol_v1.child_named(_STATED, "Notes") is None + assert protocol_v1.find_child(_STATED, "notes")["name"] == "Notes" + assert protocol_v1.find_child(_STATED, "slack")["url"] == "/svc/mcp-slack/agentenv" + + def test_serves_is_what_a_card_declares_of_a_method_and_none_when_it_declares_no_operations(): assert protocol_v1.serves({"capabilities": {"operations": ["data/get"]}}, "data/get") is True assert protocol_v1.serves({"capabilities": {"operations": ["data/add"]}}, "data/get") is False diff --git a/src/agent_env/env/env.py b/src/agent_env/env/env.py index 7d0faa1d9..c3a922065 100644 --- a/src/agent_env/env/env.py +++ b/src/agent_env/env/env.py @@ -146,7 +146,7 @@ def child_env(self, environment_name: str, *, mcp: Optional[bool] = None) -> Opt composed = isinstance(card.get("children_environments"), list) if (not composed or protocol_v1.operations(card)) and card.get("name") == environment_name: return protocol_v1.ChildEnv(name=card.get("name"), url=card.get("url"), card=card) - found = [child for child in protocol_v1.children(card) if child.name == environment_name] + found = [child for child in protocol_v1.children(card) if child.known_as == environment_name] if len(found) > 1 and mcp is not None: found = [child for child in found if website_child(child) is not mcp] if len(found) > 1: @@ -514,7 +514,7 @@ async def load_file_artifact_universe( def website_child(child: protocol_v1.ChildEnv) -> bool: """Whether a child env is a website: its card carries ``website/v1``, or, for a site serving none, its url is at a website's gateway route, ``/svc/{name}`` (an MCP server's is ``/svc/mcp-{name}``).""" - route, url = f"/svc/{child.name}", (child.url or "").rstrip("/") + route, url = f"/svc/{child.known_as}", (child.url or "").rstrip("/") return child.find_extension(WEBSITE_EXTENSION_URI) is not None or url == route or url.startswith(f"{route}/") diff --git a/src/agent_env/env/envs/computer/utils/sites.py b/src/agent_env/env/envs/computer/utils/sites.py index 3820c476b..044dced92 100644 --- a/src/agent_env/env/envs/computer/utils/sites.py +++ b/src/agent_env/env/envs/computer/utils/sites.py @@ -590,8 +590,11 @@ def _env_qualified(found: list[tuple[str, dict]]) -> list[dict]: def _served_as(child) -> str: - """The gateway service a child env is served as: the ```` of the ``/svc//`` route its url is at, which - ``website_frontend_urls`` keys it by, else its card's name.""" + """The name a website child env is served as, which ``website_frontend_urls`` keys it by: the environment_name its + gateway states; from a gateway that states none, the ```` of the ``/svc//`` route its url is at, else + its card's name.""" + if child.environment_name: + return child.environment_name parts = urlsplit(child.url or "").path.strip("/").split("/") return parts[1] if len(parts) > 1 and parts[0] == "svc" and parts[1] else child.name diff --git a/src/agent_env/env/gateway/gateway.py b/src/agent_env/env/gateway/gateway.py index da71d495c..5acf44bdc 100644 --- a/src/agent_env/env/gateway/gateway.py +++ b/src/agent_env/env/gateway/gateway.py @@ -797,10 +797,19 @@ def _backing_keys(self) -> list[str]: # backends). Non-v1 backers (e.g. the injected website_browser) self-omit from the card via 404. return list(self.rest_proxy_urls) + def _environment_name(self, key: str) -> str: + """The name the env behind the backing server ``key`` is registered as: an MCP server's, whose key is its route + ``mcp-``, without the prefix; a website's or another child env's, a computer's, its key itself, even one + whose name starts ``mcp-``.""" + own_name = key in self.website_urls or any(server.name == key for server in self.internal_mcp_servers) + return key if own_name else key.removeprefix("mcp-") + def _rewrite_child_card(self, key: str, card: dict) -> dict: - """One backing server's card rooted at the gateway (``rewrite_child_card``); a website's ``website/v1`` params + """One backing server's card rooted at the gateway (``rewrite_child_card``), stating the ``environment_name`` + the env behind it is registered as, which its own card's name needn't be; a website's ``website/v1`` params also name the route the gateway serves it to a browser at, ``/website//``, as ``browse_url``.""" card = rewrite_child_card(key, card, self._gateway_extensions()) + card["environment_name"] = self._environment_name(key) if key in self.website_urls: for ext in (card.get("capabilities") or {}).get("extensions") or []: if isinstance(ext, dict) and ext.get("uri") == EXT_WEBSITE_URI: diff --git a/src/agent_env/env/legacy_protocol.py b/src/agent_env/env/legacy_protocol.py index c914e51cd..18d78e234 100644 --- a/src/agent_env/env/legacy_protocol.py +++ b/src/agent_env/env/legacy_protocol.py @@ -98,7 +98,7 @@ def card_servers(card: dict, address: str) -> list[BackingServer]: def _listed(child: protocol_v1.ChildEnv, address: str) -> BackingServer: from agent_env.env.env import website_child - return BackingServer(child.name, mcp=not website_child(child), child=child, address=address) + return BackingServer(child.known_as, mcp=not website_child(child), child=child, address=address) async def backing_servers(deployed: Optional[DeployedEnv], gateway_url: Optional[str], env: Any, diff --git a/src/agent_env/task_step/task_steps/mcp_cli_builder/build_mcp_cli.py b/src/agent_env/task_step/task_steps/mcp_cli_builder/build_mcp_cli.py index 62eb55fb6..23c0f22d3 100644 --- a/src/agent_env/task_step/task_steps/mcp_cli_builder/build_mcp_cli.py +++ b/src/agent_env/task_step/task_steps/mcp_cli_builder/build_mcp_cli.py @@ -40,7 +40,7 @@ async def _resolve_manifest_endpoint(gateway_url: str, environment_name: str) -> logger.debug("env card for %r unavailable (%s); constructing the manifest path", environment_name, e) return None - found = [child for child in protocol_v1.children(card) if child.name == environment_name and not website_child(child)] + found = [child for child in protocol_v1.children(card) if child.known_as == environment_name and not website_child(child)] if len(found) != 1: logger.debug("env card has %s MCP server child named %r; constructing the manifest path", len(found) or "no", environment_name) diff --git a/tst/unit/env/envs/test_computer_sites.py b/tst/unit/env/envs/test_computer_sites.py index 4bc79bf62..7222ed005 100644 --- a/tst/unit/env/envs/test_computer_sites.py +++ b/tst/unit/env/envs/test_computer_sites.py @@ -509,6 +509,28 @@ def child(served: str, domain: str) -> dict: {"name": "Site", "url": "https://gw.example/website/blog/", "domains": ["blog.test"]}] # alone, its card's name +@pytest.mark.asyncio +async def test_a_website_is_selected_by_the_environment_name_its_gateway_states(monkeypatch): + from agentenv_protocol import client as protocol_v1 + + from agent_env.env.env import DeployedGatewayEnv + + async def get_card(url, timeout=10, verify=True): + raise AssertionError(f"read {url} live") + + monkeypatch.setattr(protocol_v1, "get_card", get_card) + card = {"name": "env", "children_environments": [{ + "name": "Notes", "url": "/sites/notes-v2/agentenv", "environment_name": "notes", "capabilities": { + "extensions": [{"uri": "urn:agentenv:website/v1", "params": {"domains": ["notes.test"]}}]}}]} + gateway = DeployedGatewayEnv(env_id="sites", env_version=1, sandbox_id="s", gateway_url="https://gw.example", + environment_card=card, + website_frontend_urls={"notes": "https://gw.example/website/notes/"}) + + found = [{"name": "Notes", "url": "https://gw.example/website/notes/", "domains": ["notes.test"]}] + assert await sites.deployed_sites([gateway], services=["notes"]) == found # not the path's notes-v2 + assert await sites.deployed_sites([gateway], services=["notes-v2"]) == [] + + @pytest.mark.asyncio async def test_a_card_that_fails_to_load_is_retried_then_fails_rather_than_dropping_the_sites_names(monkeypatch): from agentenv_protocol import client as protocol_v1 diff --git a/tst/unit/env/gateway/gateway_card_test.py b/tst/unit/env/gateway/gateway_card_test.py index 48979ddfa..e0f7553a6 100644 --- a/tst/unit/env/gateway/gateway_card_test.py +++ b/tst/unit/env/gateway/gateway_card_test.py @@ -9,6 +9,7 @@ from agentenv_protocol import EnvironmentCard, client as protocol_client from agent_env.env.gateway import constants as gateway_constants +from agent_env.env.gateway import InternalMCPServer from agent_env.env.gateway.gateway import Gateway @@ -267,6 +268,32 @@ async def fake_fetch(client, key, base_url): assert {c["url"] for c in card["children_environments"]} == {"/svc/mcp-items/agentenv", "/svc/webitems/agentenv"} +@pytest.mark.asyncio +async def test_each_child_entry_states_the_environment_name_its_env_is_registered_as(monkeypatch): + """An MCP server's key is its route, mcp-; a website's and a computer's is its own name, even one starting + mcp-. Each child's own card is named otherwise, as a card the SDK didn't build can be.""" + gw = Gateway(host="127.0.0.1", port=0, server_name="AgentEnvGateway", + internal_mcp_servers=[InternalMCPServer("email", "http://email:18765/mcp"), + InternalMCPServer("desktop", "http://desktop/mcp"), + InternalMCPServer("mcp-tools", "http://tools/mcp")], + website_urls={"shop": "http://shop-backend:8000"}, + rest_proxy_urls={"mcp-email": "http://email:18765", "shop": "http://shop-backend:8000", + "desktop": "http://desktop", "mcp-tools": "http://tools"}) + + async def fake_fetch(client, key, base_url): + return gw._rewrite_child_card(key, {"name": "Card name", "url": "/agentenv", "capabilities": {"extensions": []}}) + + monkeypatch.setattr(gw, "_fetch_child_card", fake_fetch) + card = json.loads((await gw._serve_env_card()).body) + + assert {child["url"]: child["environment_name"] for child in card["children_environments"]} == { + "/svc/mcp-email/agentenv": "email", "/svc/shop/agentenv": "shop", "/svc/desktop/agentenv": "desktop", + "/svc/mcp-tools/agentenv": "mcp-tools"} + assert {child.environment_name for child in EnvironmentCard.model_validate(card).children_environments} == { + "email", "shop", "desktop", "mcp-tools"} + assert [child.known_as for child in protocol_client.children(card)] == ["email", "shop", "desktop", "mcp-tools"] + + def test_a_website_childs_card_names_the_route_the_gateway_serves_it_to_a_browser_at(): """The website/v1 param naming it mirrors the protocol's, as the gateway image has no agentenv_protocol.""" from agentenv_protocol.website import WEBSITE_BROWSE_URL_PARAM diff --git a/tst/unit/env/test_env.py b/tst/unit/env/test_env.py index 02947560b..a30119dba 100644 --- a/tst/unit/env/test_env.py +++ b/tst/unit/env/test_env.py @@ -23,7 +23,7 @@ from agent_env.env.env import ( _GATEWAY_ONLY_FIELDS, DeployedEnv, DeployedGatewayEnv, DeployedSandboxEnv, Env, EnvCapabilityUnsupported, EnvNeedsGateway, - EnvNeedsSandbox, gateway_url_of, require_gateway_url, require_sandbox, + EnvNeedsSandbox, gateway_url_of, require_gateway_url, require_sandbox, website_child, ) from agent_env.env.gateway.constants import ( EXT_CHANGES_URI, EXT_CLOCK_URI, EXT_DISABLE_TOOL_URI, EXT_ENABLE_TOOL_URI, EXT_STATE_URI, EXT_STEP_URI, EXT_TRAJECTORY_URI, EXT_TRIGGERS_URI, @@ -149,6 +149,20 @@ def test_a_leaf_card_is_its_own_only_child_env_and_a_composed_one_with_a_data_pl assert _record(alone).get_child_env_card("desk") is alone +def test_a_child_whose_card_is_named_otherwise_is_found_by_the_environment_name_its_gateway_states(): + """A card the SDK didn't build can carry another name than the env's; the gateway states the env's beside it, and + a website served at /svc/ is still told from an MCP server by its route.""" + notes = {"name": "Notes App", "url": "/svc/notes/agentenv", "environment_name": "notes"} + mail = {"name": "Mail", "url": "/svc/mcp-mail/agentenv", "environment_name": "mail"} + deployed = _record({"name": "office", "children_environments": [notes, mail]}) + assert deployed.get_child_env_card("notes") is notes and deployed.get_child_env_card("Notes App") is None + assert deployed.child_env("notes", mcp=False).card is notes and deployed.child_env("mail", mcp=True).card is mail + assert website_child(deployed.child_env("notes")) and not website_child(deployed.child_env("mail")) + # A card from a gateway that states none is found by its own name, as before. + assert _record({"name": "office", "children_environments": [{"name": "notes", "url": "/svc/notes/agentenv"}]} + ).get_child_env_card("notes")["url"] == "/svc/notes/agentenv" + + _SITE_MAIL = {"name": "mail", "url": "/svc/mail/agentenv", "capabilities": {"extensions": [{"uri": "urn:agentenv:website/v1", "params": {}}]}} _MCP_MAIL = {"name": "mail", "url": "/svc/mcp-mail/agentenv"} diff --git a/tst/unit/env/test_legacy_protocol.py b/tst/unit/env/test_legacy_protocol.py index 67c2ba8d2..d426e3259 100644 --- a/tst/unit/env/test_legacy_protocol.py +++ b/tst/unit/env/test_legacy_protocol.py @@ -211,6 +211,14 @@ def test_card_servers_are_the_cards_children_a_website_told_apart_by_its_route_o "https://env.example/svc/mcp-slack", "https://env.example/svc/slack", "https://env.example/svc/mcp-docs"] +def test_card_servers_are_named_by_the_environment_name_the_gateway_states_so_snapshots_and_clocks_find_them(): + card = {"name": "office", "children_environments": [ + {"name": "Notes App", "url": "/svc/notes/agentenv", "environment_name": "notes"}, + {"name": "Mail", "url": "/svc/mcp-mail/agentenv", "environment_name": "mail"}]} + assert [(s.environment_name, s.mcp) for s in legacy_protocol.card_servers(card, "https://env.example")] == [ + ("notes", False), ("mail", True)] + + def test_card_servers_of_a_leaf_card_is_the_env_itself_and_a_composed_card_serving_data_get_comes_first(): leaf = {"name": "notes", "url": RPC_PATH} assert [(s.environment_name, s.card) for s in legacy_protocol.card_servers(leaf, "https://n")] == [("notes", leaf)] From 4c17c898b6fe35cb5f0bd0b87b163a4d6644aab8 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Sun, 8 Nov 2026 23:25:29 -0800 Subject: [PATCH 2/3] fix(gateway): a route's environment_name is the one its backend says, so mcp-foo and mcp-mcp-foo stay apart The gateway named a route by whether its key, or the key without mcp-, was an internal MCP server's name, so with MCP servers foo and mcp-foo both routes, mcp-foo and mcp-mcp-foo, were named mcp-foo. route_environment_name now asks the route's backend: of the two readings, the MCP server mcp- or a child env under its own name, the one whose internal MCP endpoint is under the route's base address wins, else the one on its host, as a server whose card is on another port than its MCP endpoint is. With neither, an mcp- key is an MCP server's route, as before. Co-Authored-By: Claude Opus 5.5 --- src/agent_env/env/gateway/gateway.py | 30 +++++++++++++++++++---- tst/unit/env/gateway/gateway_card_test.py | 21 +++++++++++++++- 2 files changed, 45 insertions(+), 6 deletions(-) diff --git a/src/agent_env/env/gateway/gateway.py b/src/agent_env/env/gateway/gateway.py index 5acf44bdc..7dcbed58c 100644 --- a/src/agent_env/env/gateway/gateway.py +++ b/src/agent_env/env/gateway/gateway.py @@ -798,11 +798,9 @@ def _backing_keys(self) -> list[str]: return list(self.rest_proxy_urls) def _environment_name(self, key: str) -> str: - """The name the env behind the backing server ``key`` is registered as: an MCP server's, whose key is its route - ``mcp-``, without the prefix; a website's or another child env's, a computer's, its key itself, even one - whose name starts ``mcp-``.""" - own_name = key in self.website_urls or any(server.name == key for server in self.internal_mcp_servers) - return key if own_name else key.removeprefix("mcp-") + """The name the env behind the backing server ``key`` is registered as (``route_environment_name``).""" + return route_environment_name(key, self.rest_proxy_urls.get(key, ""), self.internal_mcp_servers, + website=key in self.website_urls) def _rewrite_child_card(self, key: str, card: dict) -> dict: """One backing server's card rooted at the gateway (``rewrite_child_card``), stating the ``environment_name`` @@ -1477,6 +1475,28 @@ def reserved_site_path(path: str, reserved: frozenset[str] = frozenset()) -> boo for base in (RPC_PATH, *reserved)) +def route_environment_name(key: str, base_url: str, servers: list[InternalMCPServer], *, website: bool) -> str: + """The name the env behind the backing server ``key``, at ``base_url``, is registered as. A website's key is its + name. Any other key is an MCP server's route, ``mcp-``, or a child env's own name, a computer's, which may + start ``mcp-`` too; the internal MCP server whose endpoint is at the route's backend says which: one under the + route's base address first, else one on its host, as a server whose card is on another port than its MCP endpoint + is. With no such server, an ``mcp-`` key is an MCP server's route.""" + stripped = key.removeprefix("mcp-") + if website or stripped == key: + return key + base = base_url.rstrip("/") + host = urlsplit(base).hostname + + def at_backend(name: str) -> int: + urls = [server.mcp_url for server in servers if server.name == name] + if any(url.startswith(f"{base}/") for url in urls) and base: + return 2 + return 1 if host and any(urlsplit(url).hostname == host for url in urls) else 0 + + route, own = at_backend(stripped), at_backend(key) + return key if own > route else stripped + + def site_mcp_endpoints(servers: list[InternalMCPServer], website_urls: dict[str, str], rest_proxy_urls: dict[str, str]) -> dict[str, str]: """The MCP endpoint, as a path under its /svc// base, of each site that is an internal MCP server too, by diff --git a/tst/unit/env/gateway/gateway_card_test.py b/tst/unit/env/gateway/gateway_card_test.py index e0f7553a6..bd8eadcc2 100644 --- a/tst/unit/env/gateway/gateway_card_test.py +++ b/tst/unit/env/gateway/gateway_card_test.py @@ -10,7 +10,7 @@ from agentenv_protocol import EnvironmentCard, client as protocol_client from agent_env.env.gateway import constants as gateway_constants from agent_env.env.gateway import InternalMCPServer -from agent_env.env.gateway.gateway import Gateway +from agent_env.env.gateway.gateway import Gateway, route_environment_name def _gateway(rest_proxy_urls: dict[str, str]) -> Gateway: @@ -294,6 +294,25 @@ async def fake_fetch(client, key, base_url): assert [child.known_as for child in protocol_client.children(card)] == ["email", "shop", "desktop", "mcp-tools"] +@pytest.mark.parametrize("servers, routes", [ + ({"foo": "http://foo:8000/mcp", "mcp-foo": "http://mcp-foo:8000/mcp"}, + {"mcp-foo": "http://foo:8001", "mcp-mcp-foo": "http://mcp-foo:8001"}), # compose: each on its own host + ({"foo": "https://sb.example:9001/mcp", "mcp-foo": "https://sb.example:9002/mcp"}, + {"mcp-foo": "https://sb.example:9001", "mcp-mcp-foo": "https://sb.example:9002"}), # one host, a port each +], ids=["compose", "one-host"]) +def test_mcp_servers_named_foo_and_mcp_foo_are_each_named_by_the_backend_their_route_reaches(servers, routes): + internal = [InternalMCPServer(name, url) for name, url in servers.items()] + named = {key: route_environment_name(key, url, internal, website=False) for key, url in routes.items()} + assert named == {"mcp-foo": "foo", "mcp-mcp-foo": "mcp-foo"} + + +def test_a_computer_whose_name_starts_mcp_keeps_it_and_a_route_with_no_server_behind_it_drops_the_prefix(): + internal = [InternalMCPServer("mcp-tools", "http://tools-sb:7000/mcp")] + assert route_environment_name("mcp-tools", "http://tools-sb:7000", internal, website=False) == "mcp-tools" + assert route_environment_name("mcp-email", "http://email:8000", [], website=False) == "email" + assert route_environment_name("mcp-shop", "http://shop-backend:8000", [], website=True) == "mcp-shop" + + def test_a_website_childs_card_names_the_route_the_gateway_serves_it_to_a_browser_at(): """The website/v1 param naming it mirrors the protocol's, as the gateway image has no agentenv_protocol.""" from agentenv_protocol.website import WEBSITE_BROWSE_URL_PARAM From af450dcfca53e491cc82147516bf75a0c4f9a1cc Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 9 Nov 2026 08:25:59 -0800 Subject: [PATCH 3/3] test(gateway): the multi env e2e asserts each child's stated environment_name, by which its website is found, listed and snapshotted The shop website's card is named webitems, so the deploy that already serves it beside items and the desktop checks the gateway's card names it shop, child_env finds it, card_servers lists it as a website and the snapshot keeps it as shop. Co-Authored-By: Claude Opus 5.5 --- .../computer/multi_env_computers_test.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/tst/integration/computer/multi_env_computers_test.py b/tst/integration/computer/multi_env_computers_test.py index c30f63ed0..34a1adf6e 100644 --- a/tst/integration/computer/multi_env_computers_test.py +++ b/tst/integration/computer/multi_env_computers_test.py @@ -17,6 +17,7 @@ import httpx import pytest +from agentenv_protocol import client as protocol_v1 from agentenv_protocol.tool_access import (DISABLE, DISABLE_TOOL_EXTENSION_URI, ENABLE, ENABLE_TOOL_EXTENSION_URI, WILDCARD) from agentenv_protocol.tool_context import DEFAULT_ROLE @@ -34,6 +35,7 @@ from agent_env.env.envs.multi_env import MultiEnv from agent_env.env.envs.playwright_mcp import PLAYWRIGHT_MCP_ENVIRONMENT_NAME from agent_env.env.envs.website import WebsiteEnv +from agent_env.env.legacy_protocol import card_servers from agent_env.providers.env_providers.env_gateway_provider import EnvironmentGatewayProvider from agent_env.providers.sandbox_providers.local_docker.provider import LocalSandboxProvider from agent_env.store.routing import namespace_routing @@ -185,6 +187,10 @@ async def test_a_computer_in_a_multi_env_is_served_through_its_gateway_under_its [deployed] = (await step.execute(context)).deployed_envs computer = deployed.child_envs["desktop"] listed, shot = await _tools(deployed) + stated = {child.environment_name: child.name for child in protocol_v1.children(deployed.environment_card)} + site = deployed.child_env("shop", mcp=False) + servers = {(server.environment_name, server.mcp) + for server in card_servers(deployed.environment_card, deployed.environment_url)} async with httpx.AsyncClient(timeout=30) as client: card = (await client.get(f"{deployed.gateway_url}/svc/desktop{WELL_KNOWN_PATH}")).json() # Load, snapshot and reset reach the computer through the multi env, beside its MCP server. @@ -230,6 +236,13 @@ async def test_a_computer_in_a_multi_env_is_served_through_its_gateway_under_its assert json.dumps(deployed.child_envs) # the record stores as JSON assert note == "from the universe" and "snap-x" in listed_items assert {"items", "desktop"} <= set(snapshot) and snapshot["desktop"]["Documents/note.txt"] == b"from the universe" + # The gateway states each child's environment_name, which lookups, servers and snapshots go by: the shop + # website's card is named webitems. + assert {name: stated.get(name) for name in ("items", "shop", "desktop")} == { + "items": "items", "shop": "webitems", "desktop": "desktop"}, stated + assert site is not None and site.url.startswith("/svc/shop/"), site + assert {("items", True), ("shop", False)} <= servers and not any(name == "webitems" for name, _ in servers), servers + assert "shop" in snapshot and "webitems" not in snapshot, sorted(snapshot) assert after_reset == "gone" and all(reset_answers.values()), reset_answers assert computer["metadata"]["computer"]["sites"]["names"]["routes"] == {"shop": ["shop.test"]} assert routed == routed_after_reset == "200"