CubeLoop — a Pythonic, async-native agent harness core designed for high performance, readability, and production-grade persistence.
Python agent-frameworkagent-harnessagent-runtimeagentic-aiai-agentsai-frameworkanthropicharnessharness-engineeringharness-frameworklanggraphlanggraph-alternativellmmcpopenaipi-agentpi-agent-corepythonpython-agent
fix(mcp): preserve schema constraints, images, and structuredContent
xf gongc10763ac0991
diff --git a/cubepi/mcp/_adapter.py b/cubepi/mcp/_adapter.pyindex ad42926..367b9d6 100644--- a/cubepi/mcp/_adapter.py+++ b/cubepi/mcp/_adapter.py@@ -2,12 +2,12 @@from __future__ import annotations-from typing import Any, Awaitable, Callable+from typing import Any, Awaitable, Callable, Literal-from pydantic import BaseModel, create_model+from pydantic import BaseModel, Field, create_modelfrom cubepi.agent.types import AgentTool, AgentToolResult-from cubepi.providers.base import Content, TextContent+from cubepi.providers.base import Content, ImageContent, TextContentdef mcp_schema_to_pydantic_model(@@ -20,22 +20,66 @@ def mcp_schema_to_pydantic_model(cubepi.AgentTool requires `parameters: type[BaseModel]`. We synthesizea model from the schema's top-level properties.- Limited type coverage: string/integer/number/boolean/array/object.- Nested object schemas become dict[str, Any] (escape hatch).+ Type coverage: string/integer/number/boolean/array/object. Nested+ object schemas become dict[str, Any]. Constraint coverage on top-level+ properties: enum (via Literal), description, pattern, minLength,+ maxLength, minimum/maximum (incl. exclusive variants), minItems,+ maxItems. Anything else is preserved as a plain type without+ validation."""properties = input_schema.get("properties", {})required = set(input_schema.get("required", []))fields: dict[str, Any] = {}for prop_name, prop_schema in properties.items():- py_type = _json_schema_type_to_python(prop_schema)- default = ... if prop_name in required else None- fields[prop_name] = (py_type, default)+ fields[prop_name] = _build_field(prop_schema, prop_name in required)model_name = f"MCP_{tool_name}_Input"return create_model(model_name, **fields)+def _build_field(prop_schema: dict[str, Any], required: bool) -> tuple[Any, Any]:+ """Map one JSON-Schema property to a (type, FieldInfo|default) tuple."""+ if "enum" in prop_schema and isinstance(prop_schema["enum"], list):+ enum_values = tuple(prop_schema["enum"])+ py_type: Any = Literal[enum_values] if enum_values else Any+ else:+ py_type = _json_schema_type_to_python(prop_schema)++ field_kwargs: dict[str, Any] = {}+ if "description" in prop_schema:+ field_kwargs["description"] = prop_schema["description"]++ # string constraints+ if "pattern" in prop_schema:+ field_kwargs["pattern"] = prop_schema["pattern"]+ if "minLength" in prop_schema:+ field_kwargs["min_length"] = prop_schema["minLength"]+ if "maxLength" in prop_schema:+ field_kwargs["max_length"] = prop_schema["maxLength"]++ # numeric constraints+ if "minimum" in prop_schema:+ field_kwargs["ge"] = prop_schema["minimum"]+ if "maximum" in prop_schema:+ field_kwargs["le"] = prop_schema["maximum"]+ if "exclusiveMinimum" in prop_schema:+ field_kwargs["gt"] = prop_schema["exclusiveMinimum"]+ if "exclusiveMaximum" in prop_schema:+ field_kwargs["lt"] = prop_schema["exclusiveMaximum"]++ # array constraints+ if "minItems" in prop_schema:+ field_kwargs["min_length"] = prop_schema["minItems"]+ if "maxItems" in prop_schema:+ field_kwargs["max_length"] = prop_schema["maxItems"]++ default = ... if required else None+ if field_kwargs:+ return (py_type, Field(default=default, **field_kwargs))+ return (py_type, default)++def _json_schema_type_to_python(schema: dict[str, Any]) -> Any:t = schema.get("type")if t == "string":@@ -91,11 +135,22 @@ def make_mcp_agent_tool(result = await call_remote(name, args_dict)content_blocks: list[Content] = []for c in result.get("content", []):- if c.get("type") == "text":+ ctype = c.get("type")+ if ctype == "text":content_blocks.append(TextContent(text=c.get("text", "")))+ elif ctype == "image":+ content_blocks.append(+ ImageContent(+ source=c.get("data", ""),+ media_type=c.get("mimeType", ""),+ )+ )+ details: dict[str, Any] = {"raw_mcp_response": result}+ if "structuredContent" in result:+ details["structuredContent"] = result["structuredContent"]return AgentToolResult(content=content_blocks,- details={"raw_mcp_response": result},+ details=details,is_error=True if result.get("isError") else None,)diff --git a/tests/mcp/test_adapter.py b/tests/mcp/test_adapter.pyindex 5d965c4..a471336 100644--- a/tests/mcp/test_adapter.py+++ b/tests/mcp/test_adapter.py@@ -51,6 +51,86 @@ def test_schema_to_model_boolean_and_number() -> None:assert instance.rate == 1.5+def test_schema_to_model_preserves_enum() -> None:+ """enum becomes Literal — invalid values rejected by Pydantic."""+ schema = {+ "type": "object",+ "properties": {+ "unit": {"type": "string", "enum": ["c", "f"]},+ },+ "required": ["unit"],+ }+ M = mcp_schema_to_pydantic_model(tool_name="weather", input_schema=schema)+ assert M(unit="c").unit == "c"+ with pytest.raises(Exception): # noqa: BLE001 - Pydantic ValidationError+ M(unit="kelvin")+++def test_schema_to_model_preserves_string_constraints() -> None:+ schema = {+ "type": "object",+ "properties": {+ "code": {+ "type": "string",+ "pattern": "^[A-Z]{3}$",+ "minLength": 3,+ "maxLength": 3,+ "description": "ISO airport code",+ },+ },+ "required": ["code"],+ }+ M = mcp_schema_to_pydantic_model(tool_name="ap", input_schema=schema)+ assert M(code="SFO").code == "SFO"+ with pytest.raises(Exception):+ M(code="sfo") # lowercase fails pattern+ with pytest.raises(Exception):+ M(code="TOOLONG") # exceeds maxLength+ assert M.model_fields["code"].description == "ISO airport code"+++def test_schema_to_model_preserves_numeric_bounds() -> None:+ schema = {+ "type": "object",+ "properties": {+ "limit": {+ "type": "integer",+ "minimum": 1,+ "maximum": 100,+ "exclusiveMinimum": 0,+ },+ },+ "required": ["limit"],+ }+ M = mcp_schema_to_pydantic_model(tool_name="pg", input_schema=schema)+ assert M(limit=50).limit == 50+ with pytest.raises(Exception):+ M(limit=0)+ with pytest.raises(Exception):+ M(limit=101)+++def test_schema_to_model_preserves_array_size() -> None:+ schema = {+ "type": "object",+ "properties": {+ "tags": {+ "type": "array",+ "items": {"type": "string"},+ "minItems": 1,+ "maxItems": 3,+ },+ },+ "required": ["tags"],+ }+ M = mcp_schema_to_pydantic_model(tool_name="tag", input_schema=schema)+ assert M(tags=["a", "b"]).tags == ["a", "b"]+ with pytest.raises(Exception):+ M(tags=[])+ with pytest.raises(Exception):+ M(tags=["a", "b", "c", "d"])++def test_schema_to_model_unknown_type_becomes_any() -> None:"""An unrecognized JSON Schema type falls back to typing.Any."""from typing import Any