Skip to content

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

fix(backend/copilot): Align graph validator with runtime for MCP tool args and nested field chains (#13615)

Reinier van der Leer81178409dc50
diff --git a/autogpt_platform/backend/backend/copilot/tools/agent_generator/validator.py b/autogpt_platform/backend/backend/copilot/tools/agent_generator/validator.py
index c14f3a7fd5..c07c5b711b 100644
--- a/autogpt_platform/backend/backend/copilot/tools/agent_generator/validator.py
+++ b/autogpt_platform/backend/backend/copilot/tools/agent_generator/validator.py
@@ -390,71 +390,15 @@ class AgentValidator:
# Handle nested source names (with _#_ notation)
if DICT_SPLIT in source_name:
- parent, child = source_name.split(DICT_SPLIT, 1)
-
- parent_schema = output_props.get(parent)
- if not parent_schema:
+ detail = _check_nested_chain(output_props, source_name)
+ if detail:
self.add_error(
- f"Invalid source output field '{source_name}' "
- f"in link '{link_id}' from node '{source_id}' "
- f"(block '{block_name}' - {block_id}): Parent "
- f"property '{parent}' does not exist in the "
- f"block's output schema."
+ f"Invalid nested source output field "
+ f"'{source_name}' in link '{link_id}' from "
+ f"node '{source_id}' (block "
+ f"'{block_name}' - {block_id}): {detail}"
)
valid = False
- continue
-
- # Check if additionalProperties is allowed either directly
- # or via anyOf
- allows_additional_properties = parent_schema.get(
- "additionalProperties", False
- )
- if not allows_additional_properties and "anyOf" in parent_schema:
- any_of_schemas = parent_schema.get("anyOf", [])
- if isinstance(any_of_schemas, list):
- for schema_option in any_of_schemas:
- if isinstance(schema_option, dict) and schema_option.get(
- "additionalProperties"
- ):
- allows_additional_properties = True
- break
- # Also allow when items have
- # additionalProperties (array of objects)
- if (
- isinstance(schema_option, dict)
- and "items" in schema_option
- ):
- items_schema = schema_option.get("items")
- if isinstance(items_schema, dict) and items_schema.get(
- "additionalProperties"
- ):
- allows_additional_properties = True
- break
-
- # Only require child in properties when
- # additionalProperties is not allowed
- if not allows_additional_properties:
- if not (
- isinstance(parent_schema, dict)
- and "properties" in parent_schema
- and isinstance(parent_schema["properties"], dict)
- and child in parent_schema["properties"]
- ):
- available_props = (
- list(parent_schema.get("properties", {}).keys())
- if isinstance(parent_schema, dict)
- else []
- )
- self.add_error(
- f"Invalid nested source output field "
- f"'{source_name}' in link '{link_id}' from "
- f"node '{source_id}' (block "
- f"'{block_name}' - {block_id}): Child "
- f"property '{child}' does not exist in "
- f"parent '{parent}' output schema. "
- f"Available properties: {available_props}"
- )
- valid = False
else:
# Check simple (non-nested) source name
if source_name not in output_props:
@@ -509,9 +453,14 @@ class AgentValidator:
def get_input_props(node: dict[str, Any]) -> dict[str, Any]:
block_id = node.get("block_id", "")
- if block_id == AGENT_EXECUTOR_BLOCK_ID:
+ if block_id in (AGENT_EXECUTOR_BLOCK_ID, MCP_TOOL_BLOCK_ID):
input_default = node.get("input_default", {})
- dynamic_input_schema = input_default.get("input_schema", {})
+ dynamic_input_schema_field = (
+ "input_schema"
+ if block_id == AGENT_EXECUTOR_BLOCK_ID
+ else "tool_input_schema" # MCPToolBlock
+ )
+ dynamic_input_schema = input_default.get(dynamic_input_schema_field, {})
if not isinstance(dynamic_input_schema, dict):
dynamic_input_schema = {}
dynamic_props = dynamic_input_schema.get("properties", {})
@@ -528,54 +477,13 @@ class AgentValidator:
block_name: str,
block_id: str,
) -> bool:
- parent, child = field_name.split(DICT_SPLIT, 1)
- parent_schema = input_props.get(parent)
- if not parent_schema:
+ detail = _check_nested_chain(input_props, field_name)
+ if detail:
self.add_error(
- f"{context}: Parent property '{parent}' does not "
- f"exist in block '{block_name}' ({block_id}) input "
- f"schema."
+ f"{context}: {detail} "
+ f"(block '{block_name}' - {block_id} input schema)"
)
return False
-
- allows_additional = parent_schema.get("additionalProperties", False)
- # Only anyOf is checked here because Pydantic's JSON schema
- # emits optional/union fields via anyOf. allOf and oneOf are
- # not currently used by any block's dict-typed inputs, so
- # false positives from them are not a concern in practice.
- if not allows_additional and "anyOf" in parent_schema:
- for schema_option in parent_schema.get("anyOf", []):
- if not isinstance(schema_option, dict):
- continue
- if schema_option.get("additionalProperties"):
- allows_additional = True
- break
- items_schema = schema_option.get("items")
- if isinstance(items_schema, dict) and items_schema.get(
- "additionalProperties"
- ):
- allows_additional = True
- break
-
- if not allows_additional:
- if not (
- isinstance(parent_schema, dict)
- and "properties" in parent_schema
- and isinstance(parent_schema["properties"], dict)
- and child in parent_schema["properties"]
- ):
- available = (
- list(parent_schema.get("properties", {}).keys())
- if isinstance(parent_schema, dict)
- else []
- )
- self.add_error(
- f"{context}: Child property '{child}' does not "
- f"exist in parent '{parent}' of block "
- f"'{block_name}' ({block_id}) input schema. "
- f"Available properties: {available}"
- )
- return False
return True
for link in agent.get("links", []):
@@ -1221,3 +1129,130 @@ class AgentValidator:
logger.warning(f"Agent validation failed: {error_message}")
return False, error_message
+
+
+def _check_nested_chain(props: dict[str, Any], field_name: str) -> str | None:
+ """Walk a ``_#_`` chain through declared schema levels.
+
+ Returns an error detail string, or None when the chain is valid or can
+ only be resolved at runtime. Levels that declare ``properties`` are
+ verified strictly; levels that allow additional properties, or are
+ untyped (``Any`` / object without declared properties), accept any
+ remaining chain — the executor's dynamic field delivery resolves those
+ at run time. Scalar/array levels reject further nesting.
+ """
+ parts = field_name.split(DICT_SPLIT)
+ schema = props.get(parts[0])
+ if schema is None:
+ return (
+ f"Parent property '{parts[0]}' does not exist. "
+ f"Available properties: {list(props)}"
+ )
+
+ path = parts[0]
+ for child in parts[1:]:
+ if not isinstance(schema, dict):
+ return None
+ if _allows_additional_properties(schema):
+ return None
+ resolved = _resolve_optional_union(schema)
+ if resolved is not None:
+ schema = resolved
+ declared = schema.get("properties")
+ if isinstance(declared, dict) and declared:
+ if child not in declared:
+ return (
+ f"Child property '{child}' does not exist in parent "
+ f"'{path}'. Available properties: {list(declared)}"
+ )
+ schema = declared[child]
+ path = f"{path}{DICT_SPLIT}{child}"
+ continue
+ if _is_scalar_schema(schema):
+ return (
+ f"Parent '{path}' has type '{_schema_display_type(schema)}' "
+ f"and has no extractable sub-fields"
+ )
+ # Untyped / Any / object without declared shape: cannot be verified
+ # statically, resolved dynamically at run time.
+ return None
+ return None
+
+
+def _allows_additional_properties(schema: dict[str, Any]) -> bool:
+ """True when *schema* accepts arbitrary keys (directly or via anyOf).
+
+ Only anyOf is checked because Pydantic's JSON schema emits optional /
+ union fields via anyOf; allOf and oneOf are not used by any block's
+ dict-typed fields.
+ """
+ if schema.get("additionalProperties"):
+ return True
+ for option in schema.get("anyOf", []):
+ if not isinstance(option, dict):
+ continue
+ if option.get("additionalProperties"):
+ return True
+ items = option.get("items")
+ if isinstance(items, dict) and items.get("additionalProperties"):
+ return True
+ return False
+
+
+def _is_scalar_schema(schema: dict[str, Any]) -> bool:
+ """True when *schema* is a concrete non-object type (no sub-fields)."""
+ schema_type = schema.get("type")
+ if isinstance(schema_type, str) and schema_type in (
+ "string",
+ "integer",
+ "number",
+ "boolean",
+ "array",
+ ):
+ return True
+ if "anyOf" in schema:
+ options = [
+ option
+ for option in schema["anyOf"]
+ if isinstance(option, dict) and option.get("type") != "null"
+ ]
+ return bool(options) and all(_is_scalar_schema(o) for o in options)
+ return False
+
+
+def _resolve_optional_union(schema: dict[str, Any]) -> dict[str, Any] | None:
+ """Pick the single non-null branch of an optional-union schema.
+
+ Pydantic emits ``Optional[X]`` as ``anyOf: [X, {type: null}]``. Descending
+ into the X branch keeps declared object properties strictly validated
+ instead of the whole level being treated as untyped (which would accept
+ nonexistent children). Multi-branch unions keep the permissive fallback —
+ they cannot be verified statically.
+ """
+ options = [
+ o
+ for o in schema.get("anyOf", [])
+ if isinstance(o, dict) and o.get("type") != "null"
+ ]
+ if len(options) == 1:
+ return options[0]
+ return None
+
+
+def _schema_display_type(schema: dict[str, Any]) -> str:
+ """Human-readable type label for error messages.
+
+ anyOf schemas have no direct ``type`` key — render the union of their
+ branch types (e.g. ``string | null``) instead of the literal ``None``.
+ """
+ schema_type = schema.get("type")
+ if isinstance(schema_type, str):
+ return schema_type
+ options = [
+ o["type"]
+ for o in schema.get("anyOf", [])
+ if isinstance(o, dict) and isinstance(o.get("type"), str)
+ ]
+ if options:
+ return " | ".join(options)
+ return "unknown"
diff --git a/autogpt_platform/backend/backend/copilot/tools/agent_generator/validator_test.py b/autogpt_platform/backend/backend/copilot/tools/agent_generator/validator_test.py
index 85338f69d9..dd42ef8fe8 100644
--- a/autogpt_platform/backend/backend/copilot/tools/agent_generator/validator_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/agent_generator/validator_test.py
@@ -993,3 +993,368 @@ class TestValidateMCPToolBlocks:
v.validate_mcp_tool_blocks(agent)
assert len(v.errors) == 2
+
+
+class TestMCPToolDynamicSinks:
+ """Dynamic tool arguments declared by a node's tool_input_schema are valid
+ sinks / input_default keys on MCPToolBlock nodes — the executor collects
+ them into tool_arguments at run time."""
+
+ def _mcp_block(self) -> dict:
+ return _make_block(
+ block_id=MCP_TOOL_BLOCK_ID,
+ name="MCPToolBlock",
+ input_schema={
+ "properties": {
+ "server_url": {"type": "string"},
+ "selected_tool": {"type": "string"},
+ "tool_input_schema": {"type": "object"},
+ "tool_arguments": {
+ "type": "object",
+ "additionalProperties": True,
+ },
+ },
+ "required": ["server_url"],
+ },
+ )
+
+ def _mcp_node(self, **extra_defaults) -> dict:
+ return _make_node(
+ node_id="mcp-1",
+ block_id=MCP_TOOL_BLOCK_ID,
+ input_default={
+ "server_url": "https://mcp.notion.com/mcp",
+ "selected_tool": "notion-query-data-sources",
+ "tool_input_schema": {
+ "type": "object",
+ "properties": {
+ "data": {"type": "object"},
+ "limit": {"type": "integer"},
+ },
+ "required": ["data"],
+ },
+ **extra_defaults,
+ },
+ )
+
+ def test_dynamic_tool_arg_sink_passes(self):
+ v = AgentValidator()
+ link = _make_link(
+ source_id="src", source_name="out", sink_id="mcp-1", sink_name="data"
+ )
+ agent = _make_agent(nodes=[self._mcp_node()], links=[link])
+ assert v.validate_sink_input_existence(agent, [self._mcp_block()]) is True
+
+ def test_unknown_sink_still_fails(self):
+ v = AgentValidator()
+ link = _make_link(
+ source_id="src", source_name="out", sink_id="mcp-1", sink_name="bogus"
+ )
+ agent = _make_agent(nodes=[self._mcp_node()], links=[link])
+ v_result = v.validate_sink_input_existence(agent, [self._mcp_block()])
+ assert v_result is False
+ assert any("bogus" in e for e in v.errors)
+
+ def test_dynamic_tool_arg_in_input_default_passes(self):
+ v = AgentValidator()
+ node = self._mcp_node(limit=10)
+ agent = _make_agent(nodes=[node])
+ assert v.validate_sink_input_existence(agent, [self._mcp_block()]) is True
+
+
+class TestNestedChainsThroughUntypedFields:
+ """_#_ chains through untyped/Any levels are resolved dynamically at run
+ time and must not be rejected statically; scalar levels still reject."""
+
+ def _code_block(self) -> dict:
+ return _make_block(
+ block_id="code-1",
+ name="ExecuteCodeBlock",
+ output_schema={
+ "properties": {
+ "main_result": {
+ "type": "object",
+ "properties": {
+ "text": {"anyOf": [{"type": "string"}, {"type": "null"}]},
+ "json": {"anyOf": [{}, {"type": "null"}]},
+ },
+ },
+ "response": {"type": "string"},
+ }
+ },
+ )
+
+ def _link(self, source_name: str) -> dict:
+ return _make_link(
+ source_id="n1", source_name=source_name, sink_id="n2", sink_name="input"
+ )
+
+ def _agent(self, source_name: str) -> dict:
+ nodes = [
+ _make_node(node_id="n1", block_id="code-1"),
+ _make_node(node_id="n2", block_id="sink-1"),
+ ]
+ return _make_agent(nodes=nodes, links=[self._link(source_name)])
+
+ def _blocks(self) -> list[dict]:
+ return [
+ self._code_block(),
+ _make_block(
+ block_id="sink-1",
+ input_schema={"properties": {"input": {}}, "required": []},
+ ),
+ ]
+
+ def test_chain_through_untyped_field_passes(self):
+ v = AgentValidator()
+ agent = self._agent("main_result_#_json_#_has_new")
+ assert v.validate_source_output_existence(agent, self._blocks()) is True
+
+ def test_declared_child_still_verified(self):
+ v = AgentValidator()
+ agent = self._agent("main_result_#_nonexistent")
+ assert v.validate_source_output_existence(agent, self._blocks()) is False
+ assert any("nonexistent" in e for e in v.errors)
+
+ def test_chain_into_scalar_fails(self):
+ v = AgentValidator()
+ agent = self._agent("response_#_field")
+ assert v.validate_source_output_existence(agent, self._blocks()) is False
+ assert any("no extractable sub-fields" in e for e in v.errors)
+
+ def test_chain_through_scalar_anyof_fails(self):
+ v = AgentValidator()
+ agent = self._agent("main_result_#_text_#_deeper")
+ assert v.validate_source_output_existence(agent, self._blocks()) is False
+ assert any("no extractable sub-fields" in e for e in v.errors)
+ # _resolve_optional_union unwraps [string, null] to its non-null
+ # branch, so the message names the concrete type — never 'None'.
+ assert any("type 'string'" in e for e in v.errors)
+
+ def test_sink_side_chain_through_untyped_field_passes(self):
+ """The shared walker also guards sink chains — an untyped declared
+ input accepts nested delivery."""
+ v = AgentValidator()
+ link = _make_link(
+ source_id="n1",
+ source_name="response",
+ sink_id="n2",
+ sink_name="input_#_nested_#_deep",
+ )
+ nodes = [
+ _make_node(node_id="n1", block_id="code-1"),
+ _make_node(node_id="n2", block_id="sink-1"),
+ ]
+ agent = _make_agent(nodes=nodes, links=[link])
+ assert v.validate_sink_input_existence(agent, self._blocks()) is True
+
+
+class TestNestedChainEdgeCases:
+ """Regressions from review: empty schemas are present-but-untyped, and
+ Optional[X] unions resolve to X for strict validation."""
+
+ def _agent_with_source(self, source_name: str, output_schema: dict) -> tuple:
+ blocks = [
+ _make_block(block_id="src-1", output_schema=output_schema),
+ _make_block(
+ block_id="sink-1",
+ input_schema={"properties": {"input": {}}, "required": []},
+ ),
+ ]
+ nodes = [
+ _make_node(node_id="n1", block_id="src-1"),
+ _make_node(node_id="n2", block_id="sink-1"),
+ ]
+ link = _make_link(
+ source_id="n1", source_name=source_name, sink_id="n2", sink_name="input"
+ )
+ return _make_agent(nodes=nodes, links=[link]), blocks
+
+ def test_empty_schema_property_is_present_and_untyped(self):
+ v = AgentValidator()
+ agent, blocks = self._agent_with_source(
+ "value_#_child", {"properties": {"value": {}}}
+ )
+ assert v.validate_source_output_existence(agent, blocks) is True
+
+ def test_optional_declared_object_valid_child_passes(self):
+ v = AgentValidator()
+ schema = {
+ "properties": {
+ "cfg": {
+ "anyOf": [
+ {"type": "object", "properties": {"key": {"type": "string"}}},
+ {"type": "null"},
+ ]
+ }
+ }
+ }
+ agent, blocks = self._agent_with_source("cfg_#_key", schema)
+ assert v.validate_source_output_existence(agent, blocks) is True
+
+ def test_optional_declared_object_invalid_child_fails(self):
+ v = AgentValidator()
+ schema = {
+ "properties": {
+ "cfg": {
+ "anyOf": [
+ {"type": "object", "properties": {"key": {"type": "string"}}},
+ {"type": "null"},
+ ]
+ }
+ }
+ }
+ agent, blocks = self._agent_with_source("cfg_#_missing", schema)
+ assert v.validate_source_output_existence(agent, blocks) is False
+ assert any("missing" in e for e in v.errors)
+
+ def test_optional_scalar_still_rejects_descent(self):
+ v = AgentValidator()
+ schema = {
+ "properties": {"name": {"anyOf": [{"type": "string"}, {"type": "null"}]}}
+ }
+ agent, blocks = self._agent_with_source("name_#_x", schema)
+ assert v.validate_source_output_existence(agent, blocks) is False
+
+
+class TestAdditionalPropertiesChains:
+ """Levels that allow additionalProperties accept the remaining chain —
+ the executor delivers arbitrary keys into such dicts at run time."""
+
+ def _agent_and_blocks(self, output_schema: dict) -> tuple[dict, list[dict]]:
+ nodes = [
+ _make_node(node_id="n1", block_id="src-1"),
+ _make_node(node_id="n2", block_id="sink-1"),
+ ]
+ link = _make_link(
+ source_id="n1",
+ source_name="payload_#_anything_#_deeper",
+ sink_id="n2",
+ sink_name="input",
+ )
+ agent = _make_agent(nodes=nodes, links=[link])
+ blocks = [
+ _make_block(block_id="src-1", output_schema=output_schema),
+ _make_block(
+ block_id="sink-1",
+ input_schema={"properties": {"input": {}}, "required": []},
+ ),
+ ]
+ return agent, blocks
+
+ def test_direct_additional_properties_accepts_chain(self):
+ v = AgentValidator()
+ agent, blocks = self._agent_and_blocks(
+ {
+ "properties": {
+ "payload": {"type": "object", "additionalProperties": True}
+ }
+ }
+ )
+ assert v.validate_source_output_existence(agent, blocks) is True
+
+ def test_anyof_additional_properties_accepts_chain(self):
+ v = AgentValidator()
+ agent, blocks = self._agent_and_blocks(
+ {
+ "properties": {
+ "payload": {
+ "anyOf": [
+ {"type": "object", "additionalProperties": True},
+ {"type": "null"},
+ ]
+ }
+ }
+ }
+ )
+ assert v.validate_source_output_existence(agent, blocks) is True
+
+ def test_anyof_items_additional_properties_accepts_chain(self):
+ v = AgentValidator()
+ agent, blocks = self._agent_and_blocks(
+ {
+ "properties": {
+ "payload": {
+ "anyOf": [
+ {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "additionalProperties": True,
+ },
+ },
+ {"type": "null"},
+ ]
+ }
+ }
+ }
+ )
+ assert v.validate_source_output_existence(agent, blocks) is True
+
+ def test_missing_top_level_property_lists_available(self):
+ v = AgentValidator()
+ agent, blocks = self._agent_and_blocks(
+ {"properties": {"other": {"type": "string"}}}
+ )
+ assert v.validate_source_output_existence(agent, blocks) is False
+ assert any("Available properties" in e and "other" in e for e in v.errors)
+
+
+class TestDeepDeclaredChains:
+ """Arbitrary-depth strict validation through multiple *declared* object
+ levels — each declared level is verified, and a miss names the level."""
+
+ def _agent_and_blocks(self, source_name: str) -> tuple[dict, list[dict]]:
+ nodes = [
+ _make_node(node_id="n1", block_id="src-1"),
+ _make_node(node_id="n2", block_id="sink-1"),
+ ]
+ link = _make_link(
+ source_id="n1", source_name=source_name, sink_id="n2", sink_name="input"
+ )
+ agent = _make_agent(nodes=nodes, links=[link])
+ blocks = [
+ _make_block(
+ block_id="src-1",
+ output_schema={
+ "properties": {
+ "a": {
+ "type": "object",
+ "properties": {
+ "b": {
+ "type": "object",
+ "properties": {"c": {}},
+ }
+ },
+ }
+ }
+ },
+ ),
+ _make_block(
+ block_id="sink-1",
+ input_schema={"properties": {"input": {}}, "required": []},
+ ),
+ ]
+ return agent, blocks
+
+ def test_three_declared_levels_pass(self):
+ v = AgentValidator()
+ agent, blocks = self._agent_and_blocks("a_#_b_#_c")
+ assert v.validate_source_output_existence(agent, blocks) is True
+
+ def test_miss_at_third_declared_level_names_it(self):
+ v = AgentValidator()
+ agent, blocks = self._agent_and_blocks("a_#_b_#_x")
+ assert v.validate_source_output_existence(agent, blocks) is False
+ assert any("'x'" in e and "'a_#_b'" in e for e in v.errors)
+
+ def test_miss_at_second_declared_level_names_it(self):
+ v = AgentValidator()
+ agent, blocks = self._agent_and_blocks("a_#_x_#_c")
+ assert v.validate_source_output_existence(agent, blocks) is False
+ assert any("'x'" in e and "'a'" in e for e in v.errors)
+
+ def test_untyped_leaf_after_declared_levels_accepts_further_descent(self):
+ v = AgentValidator()
+ agent, blocks = self._agent_and_blocks("a_#_b_#_c_#_anything")
+ assert v.validate_source_output_existence(agent, blocks) is True