Skip to content

armgit / camel

Public Imported from GitHub
0

🐫 CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org

feat: Agent as MCP server (#2144)

Xiaotian Jin367bb3b647be
diff --git a/camel/utils/__init__.py b/camel/utils/__init__.py
index 363ace51f..f226edabd 100644
--- a/camel/utils/__init__.py
+++ b/camel/utils/__init__.py
@@ -44,7 +44,7 @@ from .constants import Constants
from .deduplication import DeduplicationResult, deduplicate_internally
from .filename import sanitize_filename
from .mcp import MCPServer
-from .response_format import get_pydantic_model
+from .response_format import get_pydantic_model, model_from_json_schema
from .token_counting import (
AnthropicTokenCounter,
BaseTokenCounter,
@@ -92,6 +92,7 @@ __all__ = [
"BatchProcessor",
"with_timeout",
"MCPServer",
+ "model_from_json_schema",
"sanitize_filename",
"browser_toolkit_save_auth_cookie",
]
diff --git a/camel/utils/response_format.py b/camel/utils/response_format.py
index 80e6b5248..6a50157b3 100644
--- a/camel/utils/response_format.py
+++ b/camel/utils/response_format.py
@@ -16,9 +16,9 @@ from __future__ import annotations
import inspect
import json
-from typing import Callable, Type, Union
+from typing import Any, Callable, Dict, List, Optional, Type, Union
-from pydantic import BaseModel, create_model
+from pydantic import BaseModel, Field, create_model
def get_pydantic_model(
@@ -61,3 +61,85 @@ def get_pydantic_model(
if issubclass(input_data, BaseModel):
return input_data
raise ValueError("Invalid input data provided.")
+
+
+TYPE_MAPPING = {
+ "integer": int,
+ "number": float,
+ "string": str,
+ "boolean": bool,
+ "array": list,
+ "object": dict,
+}
+
+
+def model_from_json_schema(
+ name: str,
+ schema: Dict[str, Any],
+) -> Type[BaseModel]:
+ r"""Create a Pydantic model from a JSON schema.
+
+ Args:
+ name (str): The name of the model.
+ schema (Dict[str, Any]): The JSON schema to create the model from.
+
+ Returns:
+ Type[BaseModel]: The Pydantic model.
+ """
+ properties = schema.get("properties", {})
+ required_fields = set(schema.get("required", []))
+ fields: Dict[str, Any] = {}
+
+ for field_name, field_schema in properties.items():
+ json_type = field_schema.get("type", "string")
+ # Handle nested objects recursively.
+ if json_type == "object" and "properties" in field_schema:
+ py_type = model_from_json_schema(
+ f"{name}_{field_name}", field_schema
+ )
+ elif json_type == "array":
+ # Process array items if available.
+ items_schema = field_schema.get("items", {"type": "string"})
+ items_type: Type[Any] = TYPE_MAPPING.get(
+ items_schema.get("type", "string"), str
+ )
+ if (
+ items_schema.get("type") == "object"
+ and "properties" in items_schema
+ ):
+ items_type = model_from_json_schema(
+ f"{name}_{field_name}_item", items_schema
+ )
+ py_type = List[items_type] # type: ignore[assignment, valid-type]
+ else:
+ py_type = TYPE_MAPPING.get(json_type, str)
+
+ # Handle nullable fields.
+ if field_schema.get("nullable", False):
+ py_type = Optional[py_type] # type: ignore[assignment]
+
+ # Construct constraints if available.
+ constraints = {}
+ if "minLength" in field_schema:
+ constraints["min_length"] = field_schema["minLength"]
+ if "maxLength" in field_schema:
+ constraints["max_length"] = field_schema["maxLength"]
+ if "minimum" in field_schema:
+ constraints["ge"] = field_schema["minimum"]
+ if "maximum" in field_schema:
+ constraints["le"] = field_schema["maximum"]
+ if "enum" in field_schema:
+ constraints["enum"] = field_schema["enum"]
+ if "description" in field_schema:
+ constraints["description"] = field_schema["description"]
+
+ default_value = field_schema.get("default", None)
+ if field_name in required_fields:
+ fields[field_name] = (py_type, Field(..., **constraints))
+ else:
+ fields[field_name] = (
+ Optional[py_type],
+ Field(default_value, **constraints),
+ )
+
+ return create_model(name, **fields) # type: ignore[call-overload]
diff --git a/services/README.md b/services/README.md
new file mode 100644
index 000000000..4f407b9c6
--- /dev/null
+++ b/services/README.md
@@ -0,0 +1,147 @@
+# CAMEL Model Context Protocol (MCP) Server
+
+This directory contains the implementation for exposing CAMEL agents through the Model Context Protocol (MCP).
+
+## What is MCP?
+
+The [Model Context Protocol (MCP)](https://modelcontextprotocol.io) lets you build servers that expose data and functionality to LLM applications in a standardized way. It acts like a web API specifically designed for LLM interactions, allowing you to:
+
+- Expose data through **Resources** (like GET endpoints to load information into LLM context)
+- Provide functionality through **Tools** (like POST endpoints to execute code or produce side effects)
+- Define interaction patterns through **Prompts** (reusable templates for LLM interactions)
+
+## CAMEL Agent MCP Server
+
+The CAMEL Agent MCP Server allows you to expose your CAMEL agents as MCP services, making them accessible to any MCP-compatible client like Claude Desktop. This enables seamless integration of CAMEL's powerful agent capabilities with various applications.
+
+> **IMPORTANT**: Before using the server, customize your agents in `agent_config.py` to set up your preferred models, system messages, and tools. The default configuration uses 3 different model platforms, but you can configure it to use any model supported by CAMEL.
+
+### Available Agents
+
+The default config file provides the following agents:
+
+- **General Agent**: A helpful assistant for answering questions and helping with tasks
+- **Search Agent**: An assistant with web search capabilities
+- **Reasoning Agent**: An assistant specialized in reasoning tasks
+
+### Tools and Resources
+
+The server exposes the following MCP tools:
+
+- `step`: Execute a single conversation step with a specified agent
+- `reset`: Reset all agents to their initial state
+- `set_output_language`: Set the output language for all agents
+- `get_agents_info`: Get information about all available agents
+- `get_chat_history`: Get the chat history for a specific agent
+- `get_agent_info`: Get detailed information about a specific agent
+- `get_available_tools`: Get a list of tools available to a specific agent
+
+## Client Configuration
+
+To connect MCP clients (such as Claude Desktop or Cursor) to your CAMEL agent server, you need to provide a JSON configuration. Here's an example configuration:
+
+```json
+{
+ "camel-agents": {
+ "command": "/path/to/your/python",
+ "args": [
+ "/path/to/camel/services/agent_mcp_server.py"
+ ],
+ "env": {
+ "OPENAI_API_KEY": "...",
+ "OPENROUTER_API_KEY": "...",
+ "BRAVE_API_KEY": "..."
+ }
+ }
+}
+```
+
+Replace the paths and API keys with your own values. This configuration tells the MCP client where to find your Python interpreter and the server script, as well as providing necessary environment variables for API access.
+
+## Getting Started
+
+### Prerequisites
+
+- Python 3.10 or higher
+- CAMEL library (`pip install camel-ai[all]`)
+- MCP library (`pip install mcp`)
+
+### Configuration
+
+1. Configure your agents in `agent_config.py`:
+ - Define the models to use
+ - Create custom agents with specific capabilities
+ - Set system messages and tools
+
+2. Set necessary environment variables:
+ - `OPENROUTER_API_KEY`: For OpenRouter API access
+ - Other API keys as needed for specific models
+
+### Running the Server
+
+You can run the MCP server in different ways:
+
+#### Development Mode
+
+Test and debug your server with the MCP Inspector:
+
+```bash
+mcp dev services/agent_mcp_server.py
+```
+
+#### Claude Desktop Integration
+
+Install your server in Claude Desktop:
+
+```bash
+mcp install services/agent_mcp_server.py --name "CAMEL Agents"
+```
+
+#### Direct Execution
+
+Run the server directly:
+
+```bash
+python services/agent_mcp_server.py
+```
+
+or
+
+```bash
+mcp run services/agent_mcp_server.py
+```
+
+## Usage Examples
+
+### Using the Step Tool
+
+```python
+# Example of using the step tool
+response = await step(
+ name="search",
+ message="What is the latest news about artificial intelligence?",
+ ctx=context
+)
+```
+
+### Using Resources
+
+```python
+# Get information about available agents
+agent_info = await get_agents_info()
+
+# Get chat history for a specific agent
+history = await get_chat_history(name="general")
+```
+
+## Customization
+
+You can customize the agents by modifying `agent_config.py`:
+
+- Change models and parameters
+- Add new agents with specific capabilities
+- Configure tools and system messages
+
+## License
+
+Licensed under the Apache License, Version 2.0. See LICENSE for details.
diff --git a/services/agent_config.py b/services/agent_config.py
new file mode 100644
index 000000000..8d6a82f0e
--- /dev/null
+++ b/services/agent_config.py
@@ -0,0 +1,99 @@
+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
+import logging
+import os
+
+from camel.agents import ChatAgent
+from camel.models import ModelFactory
+from camel.toolkits import SearchToolkit
+from camel.types import ModelPlatformType
+from camel.types.enums import ModelType
+
+# Prevent logging since MCP needs to use stdout
+root_logger = logging.getLogger()
+root_logger.handlers = []
+root_logger.addHandler(logging.NullHandler())
+
+
+# ========================================================================
+# CUSTOMIZATION SECTION - YOU CAN MODIFY THIS PART TO DEFINE YOUR OWN AGENT
+# ========================================================================
+
+# Define the model - replace with your preferred model configuration
+chat_model = ModelFactory.create(
+ model_platform=ModelPlatformType.OPENAI_COMPATIBLE_MODEL,
+ model_type="nvidia/llama-3.1-nemotron-70b-instruct:free",
+ url="https://openrouter.ai/api/v1",
+ api_key=os.getenv("OPENROUTER_API_KEY"), # Set this environment variable
+)
+
+reasoning_model = ModelFactory.create(
+ model_platform=ModelPlatformType.DEEPSEEK,
+ model_type=ModelType.DEEPSEEK_REASONER,
+ api_key=os.getenv("DEEPSEEK_API_KEY"), # Set this environment variable
+)
+
+search_model = ModelFactory.create(
+ model_platform=ModelPlatformType.OPENAI,
+ model_type=ModelType.GPT_4_1_MINI,
+ api_key=os.getenv("OPENAI_API_KEY"), # Set this environment variable
+)
+
+# Create a default chat agent - customize as needed
+chat_agent = ChatAgent(
+ model=chat_model,
+ system_message="You are a helpful assistant.",
+ # Uncomment to set a specific output language
+ # output_language="en", # or "zh", "es", "fr", etc.
+)
+
+chat_agent_description = """
+The general agent is a helpful assistant that can answer questions and help
+with tasks.
+"""
+
+reasoning_agent = ChatAgent(
+ model=reasoning_model,
+ system_message="You are a helpful assistant.",
+)
+
+reasoning_agent_description = """
+The reasoning agent is a helpful assistant that can reason about the world.
+"""
+
+
+# Create another agent for searching the web
+search_agent = ChatAgent(
+ model=search_model,
+ system_message="You are a helpful assistant.",
+ tools=SearchToolkit().get_tools(), # Add search tool
+)
+
+search_agent_description = """
+The search agent is a helpful assistant that can search the web.
+"""
+
+# Provide a list of agents with names
+agents_dict = {
+ "general": chat_agent,
+ "search": search_agent,
+ "reasoning": reasoning_agent,
+}
+
+# Provide descriptions for each agent
+description_dict = {
+ "general": chat_agent_description,
+ "search": search_agent_description,
+ "reasoning": reasoning_agent_description,
+}
diff --git a/services/agent_mcp_server.py b/services/agent_mcp_server.py
new file mode 100644
index 000000000..973779be2
--- /dev/null
+++ b/services/agent_mcp_server.py
@@ -0,0 +1,190 @@
+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
+from typing import Any, Dict, Optional
+
+from mcp.server.fastmcp import Context, FastMCP
+
+from camel.utils import model_from_json_schema
+from services.agent_config import agents_dict, description_dict
+
+mcp = FastMCP("ChatAgentMCP", dependencies=["camel-ai[all]"])
+
+
+async def step(
+ name: str,
+ message: str,
+ ctx: Context,
+ response_format: Optional[Dict[str, Any]] = None,
+) -> Dict[str, Any]:
+ r"""Execute a single step in the chat session with the agent.
+
+ Args:
+ name (str): The name of the agent to use.
+ message (str): The input message for the agent.
+ ctx (Context): The context object for the tool.
+ response_format (Optional[Dict[str, Any]]): Optional schema for
+ structured response. (default: :obj:`None`)
+
+ Returns:
+ Dict[str, Any]: A dictionary containing the response from the agent.
+ """
+ try:
+ agent = agents_dict[name]
+ except KeyError:
+ return {
+ "status": "error",
+ "message": f"Agent with name {name} not found",
+ }
+
+ format_cls = None
+ if response_format:
+ format_cls = model_from_json_schema(
+ "DynamicResponseFormat", response_format
+ )
+
+ ctx.info(f"The agent {name} is processing the message: {message}")
+ response = await agent.astep(message, format_cls)
+
+ return {
+ "status": "success",
+ "messages": [msg.to_dict() for msg in response.msgs],
+ "terminated": response.terminated,
+ "info": response.info,
+ }
+
+
+def reset(ctx: Context) -> Dict[str, str]:
+ r"""Reset the chat agent to its initial state.
+
+ Args:
+ ctx (Context): The context object for the tool.
+
+ Returns:
+ Dict[str, str]: A dictionary containing the status of the reset
+ operation.
+ """
+ for agent in agents_dict.values():
+ agent.reset()
+ ctx.info("All agents reset successfully")
+ return {"status": "success", "message": "All agents reset successfully"}
+
+
+def set_output_language(language: str, ctx: Context) -> Dict[str, str]:
+ r"""Set the output language for the chat agent.
+
+ Args:
+ language (str): The language to set the output language to.
+ ctx (Context): The context object for the tool.
+
+ Returns:
+ Dict[str, str]: A dictionary containing the status of the language
+ setting operation
+ """
+ for agent in agents_dict.values():
+ agent.output_language = language
+ ctx.info(f"Output language set to '{language}'")
+ return {
+ "status": "success",
+ "message": f"Output language set to '{language}'",
+ }
+
+
[email protected]("agent://")
+def get_agents_info() -> Dict[str, Any]:
+ r"""Get information about all agents provided by the server.
+
+ Returns:
+ Dict[str, Any]: A dictionary containing information about all agents.
+ """
+ return description_dict
+
+
[email protected]("history://{name}")
+def get_chat_history(name: str) -> Dict[str, Any]:
+ r"""Get the chat history for the given agent.
+
+ Args:
+ name (str): The name of the agent to get the chat history for.
+
+ Returns:
+ Dict[str, Any]: A dictionary containing the chat history for the
+ given agent.
+ """
+ try:
+ agent = agents_dict[name]
+ except KeyError:
+ return {
+ "status": "error",
+ "message": f"Agent with name {name} not found",
+ }
+ return agent.chat_history
+
+
[email protected]("agent://{name}")
+def get_agent_info(name: str) -> Dict[str, Any]:
+ r"""Get information about the given agent.
+
+ Args:
+ name (str): The name of the agent to get information for.
+
+ Returns:
+ Dict[str, Any]: A dictionary containing information about the given
+ agent.
+ """
+ try:
+ agent = agents_dict[name]
+ except KeyError:
+ return {
+ "status": "error",
+ "message": f"Agent with name {name} not found",
+ }
+ info = {
+ "agent_id": agent.agent_id,
+ "model_type": str(agent.model_type),
+ "token_limit": agent.token_limit,
+ "output_language": agent.output_language,
+ "description": description_dict[name],
+ }
+ return info
+
+
[email protected]("tool://{name}")
+def get_available_tools(name: str) -> Dict[str, Any]:
+ r"""Get a list of available internal tools.
+
+ Args:
+ name (str): The name of the agent to get the available tools for.
+
+ Returns:
+ Dict[str, Any]: A dictionary containing the available internal tools.
+ """
+ try:
+ agent = agents_dict[name]
+ except KeyError:
+ return {
+ "status": "error",
+ "message": f"Agent with name {name} not found",
+ }
+ return agent.tool_dict
+
+
+if __name__ == "__main__":
+ mcp.run(transport='stdio')
diff --git a/test/services/test_agent_mcp_server.py b/test/services/test_agent_mcp_server.py
new file mode 100644
index 000000000..5c4a4a564
--- /dev/null
+++ b/test/services/test_agent_mcp_server.py
@@ -0,0 +1,152 @@
+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
+from unittest.mock import AsyncMock, Mock, patch
+
+import pytest
+
+from camel.messages import BaseMessage
+from camel.responses import ChatAgentResponse
+from camel.toolkits import FunctionTool
+from services.agent_config import agents_dict, description_dict
+from services.agent_mcp_server import (
+ get_agent_info,
+ get_agents_info,
+ get_available_tools,
+ get_chat_history,
+ reset,
+ set_output_language,
+ step,
+)
+
+
+def mock_agent():
+ mock_tool = FunctionTool(lambda query: "Mock response")
+ agent = Mock()
+ agent.agent_id = "test_agent"
+ agent.model_type = "test_model"
+ agent.output_language = "en"
+ agent.chat_history = [
+ {'role': 'system', 'content': 'You are a helpful assistant.'}
+ ]
+ agent.tool_dict = {"test_tool": mock_tool}
+ agent.astep = AsyncMock()
+ return agent
+
+
+def mock_message():
+ message = Mock(spec=BaseMessage)
+ message.to_dict.return_value = {
+ "role": "assistant",
+ "content": "Test response",
+ }
+ return message
+
+
+def mock_response(mock_message):
+ response = Mock(spec=ChatAgentResponse)
+ response.msgs = [mock_message]
+ response.terminated = False
+ response.info = {}
+ return response
+
+
+async def test_step_success(mock_agent, mock_response):
+ with patch.dict(agents_dict, {"test": mock_agent}):
+ mock_agent.astep.return_value = mock_response
+ result = await step("test", "Hello")
+
+ assert result["status"] == "success"
+ assert len(result["messages"]) == 1
+ assert result["messages"][0]["content"] == "Test response"
+ assert not result["terminated"]
+ assert result["info"] == {}
+
+ mock_agent.astep.assert_called_once_with("Hello", None)
+
+
+async def test_step_with_format(mock_agent, mock_response):
+ response_format = {
+ "type": "object",
+ "properties": {"answer": {"type": "string"}},
+ }
+
+ with patch.dict(agents_dict, {"test": mock_agent}):
+ mock_agent.astep.return_value = mock_response
+ result = await step("test", "Hello", response_format)
+
+ assert result["status"] == "success"
+ mock_agent.astep.assert_called_once()
+
+
+async def test_step_agent_not_found():
+ # Ensure agents_dict is empty
+ with patch.dict(agents_dict, {}, clear=True):
+ result = await step("nonexistent", "Hello")
+ assert result["status"] == "error"
+ assert "not found" in result["message"]
+
+
+def test_reset(mock_agent):
+ with patch.dict(agents_dict, {"test": mock_agent}):
+ result = reset()
+
+ assert result["status"] == "success"
+ assert "successfully" in result["message"]
+ mock_agent.reset.assert_called_once()
+
+
+def test_set_output_language(mock_agent):
+ with patch.dict(agents_dict, {"test": mock_agent}):
+ result = set_output_language("fr")
+
+ assert result["status"] == "success"
+ assert "fr" in result["message"]
+ assert mock_agent.output_language == "fr"
+
+
+def test_get_agents_info():
+ result = get_agents_info()
+ assert result == description_dict
+
+
+def test_get_chat_history(mock_agent):
+ with patch.dict(agents_dict, {"test": mock_agent}):
+ result = get_chat_history("test")
+ assert result == mock_agent.chat_history
+
+
+def test_get_agent_info(mock_agent):
+ test_description = "Test agent description"
+ with (
+ patch.dict(agents_dict, {"test": mock_agent}),
+ patch.dict(description_dict, {"test": test_description}),
+ ):
+ result = get_agent_info("test")
+
+ assert result["agent_id"] == "test_agent"
+ assert result["model_type"] == "test_model"
+ assert result["output_language"] == "en"
+ assert result["description"] == test_description
+
+
+def test_get_available_tools(mock_agent):
+ with patch.dict(agents_dict, {"test": mock_agent}):
+ result = get_available_tools("test")
+ assert result == mock_agent.tool_dict
diff --git a/test/utils/test_response_format.py b/test/utils/test_response_format.py
new file mode 100644
index 000000000..868b752f6
--- /dev/null
+++ b/test/utils/test_response_format.py
@@ -0,0 +1,173 @@
+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
+import unittest
+
+from pydantic import BaseModel, ValidationError
+
+from camel.utils.response_format import model_from_json_schema
+
+
+class TestModelFromJsonSchema(unittest.TestCase):
+ def test_simple_types(self):
+ schema = {
+ "type": "object",
+ "properties": {
+ "name": {"type": "string"},
+ "age": {"type": "integer"},
+ "score": {"type": "number"},
+ "active": {"type": "boolean"},
+ },
+ "required": ["name", "age"],
+ }
+ Model = model_from_json_schema("SimpleUser", schema)
+
+ # Test successful instantiation with required fields.
+ instance = Model(name="Alice", age=30)
+ self.assertEqual(instance.name, "Alice")
+ self.assertEqual(instance.age, 30)
+ # Optional fields should default to None.
+ self.assertIsNone(getattr(instance, "score", None))
+ self.assertIsNone(getattr(instance, "active", None))
+
+ # Missing required field "name" should raise a validation error.
+ with self.assertRaises(ValidationError):
+ Model(age=30)
+
+ def test_defaults_and_constraints(self):
+ schema = {
+ "type": "object",
+ "properties": {
+ "username": {
+ "type": "string",
+ "minLength": 3,
+ "maxLength": 10,
+ "default": "user123",
+ },
+ "rating": {
+ "type": "number",
+ "minimum": 0,
+ "maximum": 5,
+ "default": 3.0,
+ },
+ },
+ "required": [],
+ }
+ Model = model_from_json_schema("UserWithDefaults", schema)
+ instance = Model()
+ self.assertEqual(instance.username, "user123")
+ self.assertEqual(instance.rating, 3.0)
+
+ # Constraint violation for username (too short)
+ with self.assertRaises(ValidationError):
+ Model(username="ab")
+
+ # Constraint violation for rating (exceeds maximum)
+ with self.assertRaises(ValidationError):
+ Model(rating=6)
+
+ def test_nested_objects(self):
+ schema = {
+ "type": "object",
+ "properties": {
+ "address": {
+ "type": "object",
+ "properties": {
+ "street": {"type": "string"},
+ "zipcode": {"type": "integer"},
+ },
+ "required": ["street"],
+ }
+ },
+ "required": ["address"],
+ }
+ Model = model_from_json_schema("UserWithAddress", schema)
+ # Correct usage with nested object.
+ instance = Model(address={"street": "Main St", "zipcode": 12345})
+ self.assertEqual(instance.address.street, "Main St")
+ self.assertEqual(instance.address.zipcode, 12345)
+
+ # Missing required nested field "street" should raise an error.
+ with self.assertRaises(ValidationError):
+ Model(address={"zipcode": 12345})
+
+ def test_array_items(self):
+ schema = {
+ "type": "object",
+ "properties": {
+ "tags": {"type": "array", "items": {"type": "string"}}
+ },
+ "required": ["tags"],
+ }
+ Model = model_from_json_schema("UserWithTags", schema)
+ instance = Model(tags=["python", "pydantic"])
+ self.assertIsInstance(instance.tags, list)
+ self.assertEqual(instance.tags, ["python", "pydantic"])
+
+ # Passing a non-list should raise a validation error.
+ with self.assertRaises(ValidationError):
+ Model(tags="not a list")
+
+ def test_nullable_fields(self):
+ schema = {
+ "type": "object",
+ "properties": {"nickname": {"type": "string", "nullable": True}},
+ "required": [],
+ }
+ Model = model_from_json_schema("UserNullable", schema)
+ # Test explicit None value.
+ instance = Model(nickname=None)
+ self.assertIsNone(instance.nickname)
+
+ # Test valid string value.
+ instance = Model(nickname="Sam")
+ self.assertEqual(instance.nickname, "Sam")
+
+ def test_array_of_objects(self):
+ schema = {
+ "type": "object",
+ "properties": {
+ "items": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "name": {"type": "string"},
+ "age": {"type": "integer"},
+ },
+ "required": ["name", "age"],
+ },
+ },
+ },
+ "required": ["items"],
+ }
+ Model = model_from_json_schema("UserWithArrayOfObjects", schema)
+ instance = Model(
+ items=[{"name": "Alice", "age": 30}, {"name": "Bob", "age": 25}]
+ )
+ self.assertIsInstance(instance.items, list)
+ self.assertEqual(len(instance.items), 2)
+ self.assertIsInstance(instance.items[0], BaseModel)
+ self.assertIsInstance(instance.items[1], BaseModel)
+ self.assertEqual(instance.items[0].name, "Alice")
+ self.assertEqual(instance.items[1].name, "Bob")
+ self.assertEqual(instance.items[0].age, 30)
+ self.assertEqual(instance.items[1].age, 25)
+
+ # Passing a non-list should raise a validation error.
+ with self.assertRaises(ValidationError):
+ Model(items="not a list")
+
+
+if __name__ == "__main__":
+ unittest.main()