Skip to content

Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.

fix(mcp): properly handle nested objects in tool parameters

claude[bot]9c9e8df254b9
diff --git a/browser_use/mcp/client.py b/browser_use/mcp/client.py
index 7ab2d7166..aa48b53ac 100644
--- a/browser_use/mcp/client.py
+++ b/browser_use/mcp/client.py
@@ -261,7 +261,7 @@ class MCPClient:
for param_name, param_schema in properties.items():
# Convert JSON Schema type to Python type
- param_type = self._json_schema_to_python_type(param_schema)
+ param_type = self._json_schema_to_python_type(param_schema, f'{action_name}_{param_name}')
# Determine if field is required
if param_name in required:
@@ -438,11 +438,12 @@ class MCPClient:
# Direct result or unknown format
return str(result)
- def _json_schema_to_python_type(self, schema: dict) -> Any:
+ def _json_schema_to_python_type(self, schema: dict, model_name: str = 'NestedModel') -> Any:
"""Convert JSON Schema type to Python type.
Args:
schema: JSON Schema definition
+ model_name: Name for nested models
Returns:
Python type corresponding to the schema
@@ -456,7 +457,6 @@ class MCPClient:
'integer': int,
'boolean': bool,
'array': list,
- 'object': dict,
'null': type(None),
}
@@ -464,7 +464,38 @@ class MCPClient:
if 'enum' in schema:
return str
- # Get base type
+ # Handle objects with nested properties
+ if json_type == 'object':
+ properties = schema.get('properties', {})
+ if properties:
+ # Create nested pydantic model for objects with properties
+ nested_fields = {}
+ required_fields = set(schema.get('required', []))
+
+ for prop_name, prop_schema in properties.items():
+ # Recursively process nested properties
+ prop_type = self._json_schema_to_python_type(prop_schema, f'{model_name}_{prop_name}')
+
+ # Determine if field is required
+ if prop_name in required_fields:
+ default = ... # Required field
+ else:
+ default = prop_schema.get('default', None)
+
+ # Add field with description if available
+ field_kwargs = {}
+ if 'description' in prop_schema:
+ field_kwargs['description'] = prop_schema['description']
+
+ nested_fields[prop_name] = (prop_type, Field(default, **field_kwargs))
+
+ # Create and return nested pydantic model
+ return create_model(model_name, __base__=BaseModel, **nested_fields)
+ else:
+ # Object without properties - just return dict
+ return dict
+
+ # Get base type for non-object types
base_type = type_mapping.get(json_type, str)
# Handle arrays with specific item types
diff --git a/tests/ci/test_mcp_client.py b/tests/ci/test_mcp_client.py
index 27378aaf4..59c3f430e 100644
--- a/tests/ci/test_mcp_client.py
+++ b/tests/ci/test_mcp_client.py
@@ -58,6 +58,42 @@ class MockMCPServer:
description='Get some test data as JSON',
inputSchema={'type': 'object', 'properties': {}},
),
+ types.Tool(
+ name='process_trace_update',
+ description='Process a cognitive trace update with nested object parameter',
+ inputSchema={
+ 'type': 'object',
+ 'properties': {
+ 'trace': {
+ 'type': 'object',
+ 'properties': {
+ 'recent_actions': {
+ 'type': 'array',
+ 'items': {'type': 'string'},
+ 'description': 'List of recent action names',
+ },
+ 'current_context': {
+ 'type': 'string',
+ 'description': 'Current environment context or state',
+ },
+ 'goal': {
+ 'type': 'string',
+ 'description': 'Current goal being pursued',
+ },
+ },
+ 'required': ['recent_actions', 'goal'],
+ 'additionalProperties': False,
+ },
+ 'window_size': {
+ 'type': 'number',
+ 'description': 'Size of the monitoring window',
+ 'default': 10,
+ },
+ },
+ 'required': ['trace'],
+ 'additionalProperties': False,
+ },
+ ),
]
@self.server.call_tool()
@@ -82,6 +118,17 @@ class MockMCPServer:
data = {'status': 'success', 'items': ['apple', 'banana', 'cherry'], 'count': 3}
result = json.dumps(data, indent=2)
+ elif name == 'process_trace_update':
+ assert arguments is not None
+ trace = arguments.get('trace', {})
+ window_size = arguments.get('window_size', 10)
+
+ recent_actions = trace.get('recent_actions', [])
+ current_context = trace.get('current_context', 'unknown')
+ goal = trace.get('goal', 'no goal')
+
+ result = f'Processed trace update: {len(recent_actions)} actions, goal: {goal}, context: {current_context}, window: {window_size}'
+
else:
result = f'Unknown tool: {name}'
@@ -145,10 +192,11 @@ async def test_mcp_client_basic_connection(test_mcp_server_script):
await mcp_client.connect()
# Verify tools were discovered
- assert len(mcp_client._tools) == 3
+ assert len(mcp_client._tools) == 4
assert 'count_to_n' in mcp_client._tools
assert 'echo_message' in mcp_client._tools
assert 'get_test_data' in mcp_client._tools
+ assert 'process_trace_update' in mcp_client._tools
# Register tools to controller
await mcp_client.register_to_controller(controller)
@@ -536,3 +584,96 @@ Use tools from both servers to complete the task.""",
await mcp_server1.disconnect()
await mcp_server2.disconnect()
await browser_session.kill()
+
+
+async def test_mcp_nested_object_parameters(test_mcp_server_script):
+ """Test that MCP tools with nested object parameters are properly handled."""
+ controller = Controller()
+
+ mcp_client = MCPClient(server_name='test-server', command=sys.executable, args=[test_mcp_server_script])
+
+ try:
+ await mcp_client.connect()
+ await mcp_client.register_to_controller(controller)
+
+ # Get the process_trace_update action
+ trace_action = controller.registry.registry.actions['process_trace_update']
+
+ # Verify the parameter model has nested structure
+ param_model = trace_action.param_model
+ assert param_model is not None
+
+ # Verify the main parameters exist
+ assert 'trace' in param_model.model_fields
+ assert 'window_size' in param_model.model_fields
+
+ # Verify trace is required and window_size is optional
+ assert param_model.model_fields['trace'].is_required()
+ assert not param_model.model_fields['window_size'].is_required()
+
+ # Verify window_size has a default value of 10
+ assert param_model.model_fields['window_size'].default == 10
+
+ # Verify the trace parameter has nested structure
+ trace_field = param_model.model_fields['trace']
+ trace_annotation = trace_field.annotation
+
+ # Should be a nested pydantic model, not just dict
+ assert trace_annotation is not dict
+
+ # Verify nested model has the expected fields
+ nested_model = trace_annotation
+ nested_fields = nested_model.model_fields
+ assert 'recent_actions' in nested_fields
+ assert 'current_context' in nested_fields
+ assert 'goal' in nested_fields
+
+ # Verify field requirements in nested model
+ assert nested_fields['recent_actions'].is_required()
+ assert nested_fields['goal'].is_required()
+ assert not nested_fields['current_context'].is_required()
+
+ # Test creating an instance with nested parameters
+ trace_data = nested_model(
+ recent_actions=['click', 'type', 'navigate'],
+ current_context='web page',
+ goal='complete form'
+ )
+
+ # Test the full parameter model
+ params = param_model(trace=trace_data, window_size=5)
+
+ # Verify the parameter structure
+ assert params.trace.recent_actions == ['click', 'type', 'navigate']
+ assert params.trace.current_context == 'web page'
+ assert params.trace.goal == 'complete form'
+ assert params.window_size == 5
+
+ # Test calling the tool with nested parameters
+ result = await trace_action.function(params=params)
+
+ # Verify the result contains the nested data
+ assert result.success
+ assert 'Processed trace update' in result.extracted_content
+ assert '3 actions' in result.extracted_content
+ assert 'goal: complete form' in result.extracted_content
+ assert 'context: web page' in result.extracted_content
+ assert 'window: 5' in result.extracted_content
+
+ # Test with default window_size
+ params_default = param_model(trace=trace_data)
+ result_default = await trace_action.function(params=params_default)
+ assert 'window: 10' in result_default.extracted_content
+
+ # Test with minimal required parameters
+ minimal_trace = nested_model(
+ recent_actions=['action1', 'action2'],
+ goal='test goal'
+ )
+ params_minimal = param_model(trace=minimal_trace)
+ result_minimal = await trace_action.function(params=params_minimal)
+ assert 'goal: test goal' in result_minimal.extracted_content
+ assert 'context: unknown' in result_minimal.extracted_content # Default from handler
+
+ finally:
+ await mcp_client.disconnect()