biszx-odoo-mcp 1.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of biszx-odoo-mcp might be problematic. Click here for more details.

@@ -0,0 +1,3 @@
1
+ """
2
+ Odoo MCP Server - MCP Server for Odoo Integration
3
+ """
@@ -0,0 +1,49 @@
1
+ """
2
+ Command line entry point for the Odoo MCP Server
3
+ """
4
+
5
+ import sys
6
+
7
+ from loguru import logger
8
+
9
+ from biszx_odoo_mcp.exceptions import OdooMCPError
10
+ from biszx_odoo_mcp.main import mcp
11
+
12
+
13
+ def main() -> int:
14
+ """
15
+ Run the MCP server
16
+ """
17
+ try:
18
+ logger.info("🚀 Odoo MCP Server starting")
19
+
20
+ # Simplified capability check
21
+ logger.debug(f"Python version: {sys.version.split()[0]}")
22
+ logger.debug("MCP server initialized with tools and resources")
23
+
24
+ logger.info("â–ļī¸ Starting MCP server...")
25
+
26
+ mcp.run()
27
+
28
+ logger.info("✅ MCP server stopped")
29
+ return 0
30
+ except KeyboardInterrupt:
31
+ logger.info("âšī¸ Server stopped by user")
32
+ return 0
33
+ except OdooMCPError as e:
34
+ logger.error(f"Odoo MCP Error: {e}")
35
+ logger.debug(
36
+ f"Error details - Type: {e.__class__.__name__}, Code: {e.error_code}"
37
+ )
38
+ if e.details:
39
+ logger.debug(f"Additional details: {e.details}")
40
+ return 1
41
+ except Exception as e:
42
+ logger.error(f"Critical server error: {e}")
43
+ logger.debug(f"Exception type: {type(e)}")
44
+ logger.debug("Traceback:", exc_info=True)
45
+ return 1
46
+
47
+
48
+ if __name__ == "__main__":
49
+ sys.exit(main())
@@ -0,0 +1,226 @@
1
+ """
2
+ Custom exception classes for Odoo MCP Server.
3
+
4
+ This module defines a comprehensive hierarchy of custom exceptions for better
5
+ error handling and debugging in the Odoo MCP Server application.
6
+
7
+ Exception Hierarchy:
8
+ ===================
9
+
10
+ OdooMCPError (Base)
11
+ ├── OdooConnectionError
12
+ │ ├── ConnectionTimeoutError
13
+ │ ├── AuthenticationError
14
+ │ └── SSLVerificationError
15
+ ├── ModelError
16
+ │ └── ModelNotFoundError
17
+ ├── ServerError
18
+ │ ├── OdooRPCError
19
+ │ └── InternalServerError
20
+ └── MCPError
21
+ ├── ResourceError
22
+ └── ToolError
23
+ """
24
+
25
+ from typing import Any, Optional
26
+
27
+ from odoorpc.error import RPCError
28
+
29
+
30
+ class OdooMCPError(Exception):
31
+ """
32
+ Base exception class for all Odoo MCP Server errors.
33
+
34
+ This serves as the base class for all custom exceptions in the application,
35
+ providing a consistent interface for error handling and logging.
36
+
37
+ Attributes:
38
+ message: Human-readable error message
39
+ error_code: Machine-readable error code for programmatic handling
40
+ details: Additional context information about the error
41
+ """
42
+
43
+ def __init__(
44
+ self,
45
+ message: str,
46
+ error_code: Optional[str] = None,
47
+ details: Optional[dict[str, Any]] = None,
48
+ original_error: Optional[Exception] = None,
49
+ ) -> None:
50
+ """
51
+ Initialize the exception.
52
+
53
+ Args:
54
+ message: Human-readable error message
55
+ error_code: Machine-readable error code
56
+ details: Additional context information
57
+ original_error: The original exception that caused this error
58
+ """
59
+ super().__init__(message)
60
+ self.message = message
61
+ self.error_code = error_code or self.__class__.__name__.upper()
62
+ self.details = details or {}
63
+ self.original_error = original_error
64
+
65
+ def to_dict(self) -> dict[str, Any]:
66
+ """
67
+ Convert the exception to a dictionary for JSON serialization.
68
+
69
+ Returns:
70
+ Dictionary representation of the exception
71
+ """
72
+ result = {
73
+ "error_type": self.__class__.__name__,
74
+ "error_code": self.error_code,
75
+ "message": self.message,
76
+ "details": self.details,
77
+ }
78
+
79
+ if self.original_error:
80
+ result["original_error"] = {
81
+ "type": self.original_error.__class__.__name__,
82
+ "message": str(self.original_error),
83
+ }
84
+
85
+ return result
86
+
87
+ def __str__(self) -> str:
88
+ """String representation of the exception."""
89
+ return f"{self.error_code}: {self.message}"
90
+
91
+
92
+ # =============================================================================
93
+ # CONNECTION RELATED ERRORS
94
+ # =============================================================================
95
+
96
+
97
+ class OdooConnectionError(OdooMCPError):
98
+ """Base class for Odoo connection-related errors."""
99
+
100
+
101
+ class ConnectionTimeoutError(OdooConnectionError):
102
+ """Raised when a connection to Odoo times out."""
103
+
104
+ def __init__(
105
+ self,
106
+ message: str = "Connection to Odoo server timed out",
107
+ timeout: Optional[float] = None,
108
+ **kwargs: Any,
109
+ ) -> None:
110
+ details = kwargs.get("details", {})
111
+ if timeout is not None:
112
+ details["timeout_seconds"] = timeout
113
+ kwargs["details"] = details
114
+ super().__init__(message, **kwargs)
115
+
116
+
117
+ class AuthenticationError(OdooConnectionError):
118
+ """Raised when authentication with Odoo fails."""
119
+
120
+ def __init__(
121
+ self,
122
+ message: str = "Authentication with Odoo failed",
123
+ username: Optional[str] = None,
124
+ database: Optional[str] = None,
125
+ **kwargs: Any,
126
+ ) -> None:
127
+ details = kwargs.get("details", {})
128
+ if username:
129
+ details["username"] = username
130
+ if database:
131
+ details["database"] = database
132
+ kwargs["details"] = details
133
+ super().__init__(message, **kwargs)
134
+
135
+
136
+ # =============================================================================
137
+ # MODEL RELATED ERRORS
138
+ # =============================================================================
139
+
140
+
141
+ class ModelError(OdooMCPError):
142
+ """Base class for model-related errors."""
143
+
144
+
145
+ class ModelNotFoundError(ModelError):
146
+ """Raised when a requested model doesn't exist."""
147
+
148
+ def __init__(
149
+ self, model_name: str, message: Optional[str] = None, **kwargs: Any
150
+ ) -> None:
151
+ message = message or f"Model '{model_name}' not found"
152
+ details = kwargs.get("details", {})
153
+ details["model_name"] = model_name
154
+ kwargs["details"] = details
155
+ super().__init__(message, **kwargs)
156
+
157
+
158
+ # =============================================================================
159
+ # SERVER RELATED ERRORS
160
+ # =============================================================================
161
+
162
+
163
+ class ServerError(OdooMCPError):
164
+ """Base class for server-related errors."""
165
+
166
+
167
+ class OdooRPCError(ServerError):
168
+ """Raised when an RPC call to Odoo fails."""
169
+
170
+ def __init__(
171
+ self,
172
+ error: RPCError,
173
+ method: str,
174
+ message: str = "RPC call failed",
175
+ **kwargs: Any,
176
+ ) -> None:
177
+ kwargs["details"] = {
178
+ "method": method,
179
+ "odoo_error": error.info,
180
+ }
181
+ super().__init__(message, **kwargs)
182
+
183
+
184
+ class InternalServerError(ServerError):
185
+ """Raised when an internal server error occurs."""
186
+
187
+
188
+ # =============================================================================
189
+ # MCP RELATED ERRORS
190
+ # =============================================================================
191
+
192
+
193
+ class MCPError(OdooMCPError):
194
+ """Base class for MCP protocol-related errors."""
195
+
196
+
197
+ class ResourceError(MCPError):
198
+ """Raised when an MCP resource operation fails."""
199
+
200
+ def __init__(
201
+ self,
202
+ message: str = "Resource operation failed",
203
+ resource_name: Optional[str] = None,
204
+ **kwargs: Any,
205
+ ) -> None:
206
+ details = kwargs.get("details", {})
207
+ if resource_name:
208
+ details["resource_name"] = resource_name
209
+ kwargs["details"] = details
210
+ super().__init__(message, **kwargs)
211
+
212
+
213
+ class ToolError(MCPError):
214
+ """Raised when an MCP tool operation fails."""
215
+
216
+ def __init__(
217
+ self,
218
+ message: str = "Tool operation failed",
219
+ tool_name: Optional[str] = None,
220
+ **kwargs: Any,
221
+ ) -> None:
222
+ details = kwargs.get("details", {})
223
+ if tool_name:
224
+ details["tool_name"] = tool_name
225
+ kwargs["details"] = details
226
+ super().__init__(message, **kwargs)
biszx_odoo_mcp/main.py ADDED
@@ -0,0 +1,134 @@
1
+ """
2
+ MCP server for Odoo integration
3
+
4
+ Provides MCP tools and resources for interacting with Odoo ERP systems
5
+ """
6
+
7
+ import inspect
8
+ import os
9
+ import sys
10
+ from collections.abc import AsyncIterator, Callable
11
+ from contextlib import asynccontextmanager
12
+ from typing import Any
13
+
14
+ from loguru import logger
15
+ from mcp.server.fastmcp import FastMCP
16
+
17
+ from biszx_odoo_mcp.server import resources, tools
18
+ from biszx_odoo_mcp.server.context import AppContext
19
+ from biszx_odoo_mcp.tools.odoo_client import get_odoo_client
20
+
21
+
22
+ def init() -> None:
23
+ """
24
+ Initialize the Odoo MCP Server environment
25
+ """
26
+ try:
27
+ from dotenv import load_dotenv # pylint: disable=import-outside-toplevel
28
+
29
+ load_dotenv()
30
+ except ImportError:
31
+ pass
32
+
33
+ # Configure loguru with appropriate log level
34
+ logger.remove()
35
+ log_level = os.environ.get("LOG_LEVEL", "INFO").upper()
36
+ logger.add(
37
+ sys.stderr,
38
+ format=(
39
+ "<green>{time:YYYY-MM-DD HH:mm:ss}</green> | "
40
+ "<level>{level: <8}</level> | "
41
+ "<level>{message}</level>"
42
+ ),
43
+ level=log_level,
44
+ colorize=True,
45
+ )
46
+
47
+
48
+ @asynccontextmanager
49
+ async def app_lifespan(_: FastMCP) -> AsyncIterator[AppContext]:
50
+ """Application lifespan for initialization and cleanup"""
51
+ odoo_client = get_odoo_client()
52
+ try:
53
+ yield AppContext(odoo=odoo_client)
54
+ finally:
55
+ pass
56
+
57
+
58
+ # Create MCP server
59
+ mcp = FastMCP(
60
+ name="Odoo MCP Server",
61
+ instructions="MCP Server for interacting with Odoo ERP systems",
62
+ dependencies=["requests"],
63
+ lifespan=app_lifespan,
64
+ )
65
+
66
+
67
+ # Tool registration helper
68
+ def tool(func: Callable[..., Any]) -> Callable[..., Any]:
69
+ """Decorator to register a tool that calls the underlying function with mcp"""
70
+
71
+ # Get the original function signature
72
+ sig = inspect.signature(func)
73
+
74
+ # Create a new signature excluding the 'mcp' parameter
75
+ new_params = [p for name, p in sig.parameters.items() if name != "mcp"]
76
+ new_sig = sig.replace(parameters=new_params)
77
+
78
+ async def wrapper(*args: Any, **kwargs: Any) -> Any:
79
+ return await func(mcp, *args, **kwargs)
80
+
81
+ # Set wrapper properties manually to match the new signature
82
+ wrapper.__name__ = func.__name__
83
+ wrapper.__doc__ = func.__doc__
84
+ wrapper.__annotations__ = {
85
+ k: v for k, v in func.__annotations__.items() if k != "mcp"
86
+ }
87
+
88
+ # Set the corrected signature
89
+ object.__setattr__(wrapper, "__signature__", new_sig)
90
+
91
+ return mcp.tool()(wrapper)
92
+
93
+
94
+ # Resource wrapper functions
95
+ async def search_models_resource(query: str):
96
+ """Search for models by name or description"""
97
+ return await resources.search_models_resource(mcp, query)
98
+
99
+
100
+ async def model_info_resource(model_name: str):
101
+ """Get information about a specific model"""
102
+ return await resources.get_model_info_resource(mcp, model_name)
103
+
104
+
105
+ async def model_fields_resource(model_name: str, query_field: str) -> str:
106
+ """Get field definitions for a specific model"""
107
+ return await resources.get_model_fields_resource(mcp, model_name, query_field)
108
+
109
+
110
+ init()
111
+
112
+ # Register all resources directly
113
+ mcp.resource("odoo://models/search/{query}")(search_models_resource)
114
+ mcp.resource("odoo://models/{model_name}/info")(model_info_resource)
115
+ mcp.resource("odoo://models/{model_name}/fields/{query_field}")(model_fields_resource)
116
+ mcp.resource("odoo://help/domains")(resources.get_domain_help_resource)
117
+ mcp.resource("odoo://help/operations")(resources.get_operations_help_resource)
118
+
119
+
120
+ # Register all tools using the helper
121
+ tool(tools.search_models)
122
+ tool(tools.get_model_info)
123
+ tool(tools.get_model_fields)
124
+ tool(tools.search_records)
125
+ tool(tools.search_ids)
126
+ tool(tools.search_count)
127
+ tool(tools.read_records)
128
+ tool(tools.read_group)
129
+ tool(tools.create_records)
130
+ tool(tools.write_records)
131
+ tool(tools.search_and_write)
132
+ tool(tools.unlink_records)
133
+ tool(tools.search_and_unlink)
134
+ tool(tools.call_method)
File without changes
@@ -0,0 +1,19 @@
1
+ """
2
+ MCP Server Application Context
3
+
4
+ This module defines the application context for the MCP server, which includes
5
+ the Odoo client used to interact with the Odoo server.
6
+ """
7
+
8
+ from dataclasses import dataclass
9
+
10
+ from biszx_odoo_mcp.tools.odoo_client import OdooClient
11
+
12
+
13
+ @dataclass
14
+ class AppContext:
15
+ """
16
+ Application context for the MCP server
17
+ """
18
+
19
+ odoo: OdooClient
@@ -0,0 +1,230 @@
1
+ """
2
+ MCP Resources for Odoo integration
3
+
4
+ This module contains all the MCP resource functions for Odoo data access.
5
+ """
6
+
7
+ from typing import Any, cast
8
+
9
+ from biszx_odoo_mcp.exceptions import OdooMCPError, ResourceError
10
+ from biszx_odoo_mcp.server.context import AppContext
11
+ from biszx_odoo_mcp.server.response import Response
12
+
13
+
14
+ async def search_models_resource(mcp: Any, query: str) -> str:
15
+ """
16
+ Resource for searching models from the Odoo application.
17
+
18
+ This searches through model names and display names to find models that
19
+ match the given query term.
20
+
21
+ Args:
22
+ query: Search term to find models (searches in model name and display name)
23
+
24
+ Returns:
25
+ JSON string with matching models
26
+ """
27
+ # Access lifespan context to get the Odoo client
28
+ ctx = mcp.get_context()
29
+ app_context = cast(AppContext, ctx.request_context.lifespan_context)
30
+
31
+ try:
32
+ data = app_context.odoo.search_models(query)
33
+ return Response(data=data).to_json_string()
34
+ except OdooMCPError as e:
35
+ return Response(error=e.to_dict()).to_json_string()
36
+ except Exception as e:
37
+ resource_error = ResourceError(
38
+ f"Unexpected error searching models: {str(e)}",
39
+ resource_name="search_models_resource",
40
+ details={"query": query},
41
+ original_error=e,
42
+ )
43
+ return Response(error=resource_error.to_dict()).to_json_string()
44
+
45
+
46
+ async def get_model_fields_resource(mcp: Any, model_name: str, query_field: str) -> str:
47
+ """
48
+ Resource containing field definitions for a specific model.
49
+
50
+ Args:
51
+ model_name: Name of the model (e.g., 'res.partner')
52
+ query_field: Search term to find fields (searches in field name and string)
53
+
54
+ Returns:
55
+ JSON string with field definitions
56
+ """
57
+ # Access lifespan context to get the Odoo client
58
+ ctx = mcp.get_context()
59
+ app_context = cast(AppContext, ctx.request_context.lifespan_context)
60
+
61
+ try:
62
+ data = app_context.odoo.get_model_fields(model_name, query_field)
63
+ return Response(data=data).to_json_string()
64
+ except OdooMCPError as e:
65
+ return Response(error=e.to_dict()).to_json_string()
66
+ except Exception as e:
67
+ resource_error = ResourceError(
68
+ f"Unexpected error getting model fields: {str(e)}",
69
+ resource_name="get_model_fields_resource",
70
+ details={"model_name": model_name},
71
+ original_error=e,
72
+ )
73
+ return Response(error=resource_error.to_dict()).to_json_string()
74
+
75
+
76
+ async def get_model_info_resource(mcp: Any, model_name: str) -> str:
77
+ """
78
+ Resource containing information about a specific model.
79
+
80
+ Args:
81
+ model_name: Name of the model (e.g., 'res.partner')
82
+
83
+ Returns:
84
+ JSON string with model information
85
+ """
86
+ # Access lifespan context to get the Odoo client
87
+ ctx = mcp.get_context()
88
+ app_context = cast(AppContext, ctx.request_context.lifespan_context)
89
+
90
+ try:
91
+ data = app_context.odoo.get_model_info(model_name)
92
+ return Response(data=data).to_json_string()
93
+ except OdooMCPError as e:
94
+ return Response(error=e.to_dict()).to_json_string()
95
+ except Exception as e:
96
+ resource_error = ResourceError(
97
+ f"Unexpected error getting model info: {str(e)}",
98
+ resource_name="get_model_info_resource",
99
+ details={"model_name": model_name},
100
+ original_error=e,
101
+ )
102
+ return Response(error=resource_error.to_dict()).to_json_string()
103
+
104
+
105
+ async def get_domain_help_resource() -> str:
106
+ """
107
+ Resource containing help information about Odoo domain syntax.
108
+
109
+ Returns:
110
+ JSON string with domain syntax examples and explanations
111
+ """
112
+ domain_help = {
113
+ "odoo_domain_syntax": {
114
+ "description": "Odoo domains are used for filtering records",
115
+ "syntax": "List of tuples: [('field', 'operator', 'value')]",
116
+ "operators": {
117
+ "=": "equals",
118
+ "!=": "not equals",
119
+ "<": "less than",
120
+ "<=": "less than or equal",
121
+ ">": "greater than",
122
+ ">=": "greater than or equal",
123
+ "in": "in list",
124
+ "not in": "not in list",
125
+ "like": "contains (case insensitive)",
126
+ "ilike": "contains (case insensitive)",
127
+ "=like": "matches pattern",
128
+ "=ilike": "matches pattern (case insensitive)",
129
+ },
130
+ "logical_operators": {
131
+ "&": "AND (default between conditions)",
132
+ "|": "OR",
133
+ "!": "NOT",
134
+ },
135
+ "examples": [
136
+ {
137
+ "description": "Find companies only",
138
+ "domain": "[('is_company', '=', True)]",
139
+ },
140
+ {
141
+ "description": "Find partners with email containing 'gmail'",
142
+ "domain": "[('email', 'ilike', 'gmail')]",
143
+ },
144
+ {
145
+ "description": "Find products with price between 10 and 100",
146
+ "domain": "[('list_price', '>=', 10), ('list_price', '<=', 100)]",
147
+ },
148
+ {
149
+ "description": "Find active products or services",
150
+ "domain": (
151
+ "['|', ('type', '=', 'product'), "
152
+ "('type', '=', 'service'), ('active', '=', True)]"
153
+ ),
154
+ },
155
+ {
156
+ "description": "Find draft or confirmed sales orders",
157
+ "domain": "['|', ('state', '=', 'draft'), ('state', '=', 'sent')]",
158
+ },
159
+ ],
160
+ }
161
+ }
162
+
163
+ response = Response(data=domain_help)
164
+ return response.to_json_string()
165
+
166
+
167
+ async def get_operations_help_resource() -> str:
168
+ """
169
+ Resource containing help information about available MCP tools and operations.
170
+
171
+ Returns:
172
+ JSON string with operations documentation
173
+ """
174
+ operations_help = {
175
+ "mcp_tools": {
176
+ "data_retrieval": {
177
+ "get_odoo_models": "Get list of all available models",
178
+ "get_model_info": "Get information about a specific model",
179
+ "get_model_fields": "Get field definitions for a model",
180
+ "search_records": "Search for records with domain filters",
181
+ "read_records": "Read specific records by IDs",
182
+ "search_ids": "Get only IDs of matching records",
183
+ "search_count": "Count records matching a domain",
184
+ },
185
+ "data_modification": {
186
+ "create_record": "Create a single new record",
187
+ "create_records": "Create multiple records at once",
188
+ "write_record": "Update a single record",
189
+ "write_records": "Update multiple records",
190
+ "unlink_record": "Delete a single record",
191
+ "unlink_records": "Delete multiple records",
192
+ },
193
+ "advanced": {
194
+ "call_method": "Call custom methods on models",
195
+ "search_and_update": "Search and update records in one operation",
196
+ },
197
+ },
198
+ "common_workflows": [
199
+ {
200
+ "name": "Create a new customer",
201
+ "steps": [
202
+ "1. Use create_record with model 'res.partner'",
203
+ (
204
+ "2. Provide values like {'name': 'Customer Name', "
205
+ "'email': 'email@domain.com', 'is_company': True}"
206
+ ),
207
+ ],
208
+ },
209
+ {
210
+ "name": "Search for products",
211
+ "steps": [
212
+ "1. Use search_records with model 'product.template'",
213
+ (
214
+ "2. Use domain like [('name', 'ilike', 'search_term')] "
215
+ "to find products by name"
216
+ ),
217
+ ],
218
+ },
219
+ {
220
+ "name": "Update product price",
221
+ "steps": [
222
+ "1. Use search_ids to find the product",
223
+ "2. Use write_records to update the list_price field",
224
+ ],
225
+ },
226
+ ],
227
+ }
228
+
229
+ response = Response(data=operations_help)
230
+ return response.to_json_string()