ai*
This commit is contained in:
9
ai_mcp/models/__init__.py
Normal file
9
ai_mcp/models/__init__.py
Normal file
@@ -0,0 +1,9 @@
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
from . import ai_mcp_request_dispatcher
|
||||
from . import ai_tool
|
||||
from . import ir_actions_server
|
||||
from . import res_users_description
|
||||
from . import ir_http
|
||||
from . import oauth_client
|
||||
from . import oauth_authorization_code
|
||||
from . import res_config_settings
|
||||
79
ai_mcp/models/ai_mcp_request_dispatcher.py
Normal file
79
ai_mcp/models/ai_mcp_request_dispatcher.py
Normal file
@@ -0,0 +1,79 @@
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
import json
|
||||
|
||||
from odoo import models
|
||||
from odoo.tools.json import json_default
|
||||
|
||||
from odoo.addons.ai_mcp.utils.exceptions import McpMethodNotFoundError
|
||||
from odoo.addons.ai_mcp.utils.utils import _mcp_get_allowed_tools
|
||||
|
||||
|
||||
class AiMcpRequestDispatcher(models.AbstractModel):
|
||||
_name = "ai.mcp.request.dispatcher"
|
||||
_description = "MCP Request Dispatcher"
|
||||
|
||||
def _mcp_dispatch(self, mcp_request):
|
||||
# A notification from the MCP client doesn't have an 'id'. We ignore notifications and return immediately.
|
||||
if 'id' not in mcp_request:
|
||||
return None
|
||||
|
||||
method = mcp_request.get('method')
|
||||
params = mcp_request.get('params', {})
|
||||
|
||||
if method == 'initialize':
|
||||
return self._mcp_initialize(params)
|
||||
if method == 'ping':
|
||||
return {}
|
||||
if method == 'tools/list':
|
||||
return self._mcp_tools_list(params)
|
||||
if method == 'tools/call':
|
||||
return self._mcp_tools_call(params)
|
||||
raise McpMethodNotFoundError()
|
||||
|
||||
def _mcp_initialize(self, params):
|
||||
return {
|
||||
'protocolVersion': params['protocolVersion'],
|
||||
'capabilities': {'tools': {}},
|
||||
'serverInfo': {'name': 'Odoo', 'version': '1.0.0'},
|
||||
}
|
||||
|
||||
def _mcp_tools_list(self, params):
|
||||
return {
|
||||
'tools': [self._mcp_build_tool_definition(tool) for tool in _mcp_get_allowed_tools(self.env)]
|
||||
}
|
||||
|
||||
def _mcp_build_tool_definition(self, tool):
|
||||
# sudo => internal users should be able to access tools' fields.
|
||||
tool = tool.sudo()
|
||||
schema = json.loads(tool.ai_tool_schema) if tool.ai_tool_schema else {}
|
||||
schema.setdefault('type', 'object')
|
||||
schema.setdefault('properties', {})
|
||||
|
||||
return {
|
||||
'name': tool.ai_tool_name,
|
||||
'title': tool.ai_tool_name,
|
||||
'description': tool.ai_tool_description or tool.ai_tool_name,
|
||||
'inputSchema': schema,
|
||||
'annotations': {
|
||||
'title': tool.ai_tool_name,
|
||||
'readOnlyHint': tool.is_readonly,
|
||||
'destructiveHint': not tool.is_readonly,
|
||||
},
|
||||
'execution': {
|
||||
'taskSupport': 'forbidden'
|
||||
}
|
||||
}
|
||||
|
||||
def _mcp_tools_call(self, params):
|
||||
name = params['name']
|
||||
arguments = params.get('arguments', {})
|
||||
# sudo => internal users should be able to read tools. The sudo is immediately dropped.
|
||||
# Also the access rights to execute the tool will be checked using _can_execute_action_on_records
|
||||
tool = self.env['ir.actions.server'].sudo().search([('ai_tool_name', '=', name), ('use_in_mcp', '=', True)]).sudo(False)
|
||||
if not tool:
|
||||
raise ValueError(f"The tool '{name}' doesn't exist")
|
||||
model_name = tool.sudo().model_id.model
|
||||
tool._can_execute_action_on_records(self.env[model_name])
|
||||
# sudo => internal users should be able to execute tools and access was checked using _can_execute_action_on_records
|
||||
result = tool.sudo()._ai_tool_run(self.env[model_name], arguments, {'tool_request_confirmed': True})
|
||||
return {'content': [{'type': 'text', 'text': json.dumps(result or "The operation has been executed successfully.", default=json_default, ensure_ascii=False)}], 'isError': False}
|
||||
35
ai_mcp/models/ai_tool.py
Normal file
35
ai_mcp/models/ai_tool.py
Normal file
@@ -0,0 +1,35 @@
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
from odoo import models
|
||||
|
||||
|
||||
class AiTool(models.AbstractModel):
|
||||
_inherit = 'ai.tool'
|
||||
|
||||
def _ai_tool_mcp_retrieve_initial_context(self):
|
||||
context = "<odoo_current_context>\n"
|
||||
context += f"## Timezone\n{self.env.user.tz}"
|
||||
user_info = {k: v for k, v in self.env.user._ai_read(['name', 'function', 'partner_id'])[0][0].items() if v}
|
||||
user_info['user_id'] = user_info.pop('id')
|
||||
context += f"\n## User info\n{user_info}"
|
||||
|
||||
# Active companies are passed through context from the web client. However, in mcp, there is no web client. So, we use
|
||||
# the user's default company as the active company. We insist on using 'active' because topics instructions mention
|
||||
# active companies like create_records topic.
|
||||
company = self.env.user.company_id
|
||||
active_company_info = {"model": "res.company", "id": company.id, "name": company.name}
|
||||
if company.country_id.code:
|
||||
active_company_info["country_code"] = company.country_id.code
|
||||
if company.city:
|
||||
active_company_info["country_city"] = company.city
|
||||
context += f"\n## Active company\n{active_company_info}"
|
||||
|
||||
available_companies_info = [{"model": "res.company", "id": company.id, "name": company.name} for company in self.env.user.company_ids]
|
||||
context += f"\n## companies available for the current user \n{available_companies_info}"
|
||||
context += "\n## General Notes \n"
|
||||
context += """
|
||||
All the date/time values retrieved from the database are in UTC format.
|
||||
Always provide the date/time in UTC format when using any tool.
|
||||
Only convert date/time to the user's timezone when displaying date/time to the user.\n
|
||||
"""
|
||||
context += "</odoo_current_context>"
|
||||
return context
|
||||
28
ai_mcp/models/ir_actions_server.py
Normal file
28
ai_mcp/models/ir_actions_server.py
Normal file
@@ -0,0 +1,28 @@
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
from odoo import api, fields, models
|
||||
from odoo.exceptions import ValidationError
|
||||
from odoo.tools import _
|
||||
|
||||
|
||||
class IrActionsServer(models.Model):
|
||||
_inherit = "ir.actions.server"
|
||||
|
||||
use_in_mcp = fields.Boolean(
|
||||
"Available in MCP",
|
||||
store=True,
|
||||
readonly=False,
|
||||
compute="_compute_use_in_mcp",
|
||||
)
|
||||
is_readonly = fields.Boolean("Readonly Tool", help="Does the tool only perform read operations? Required for MCP clients to differentiate between read and write tools.")
|
||||
|
||||
@api.depends("state")
|
||||
def _compute_use_in_mcp(self):
|
||||
for action in self:
|
||||
if not action.ai_tool_is_candidate:
|
||||
action.use_in_mcp = False
|
||||
|
||||
@api.constrains("state", "use_in_mcp")
|
||||
def _check_use_in_mcp(self):
|
||||
for action in self:
|
||||
if action.use_in_mcp and not action.ai_tool_is_candidate:
|
||||
raise ValidationError(_("The action '%s' cannot be used as an MCP tool.", action.name))
|
||||
25
ai_mcp/models/ir_http.py
Normal file
25
ai_mcp/models/ir_http.py
Normal file
@@ -0,0 +1,25 @@
|
||||
from werkzeug.datastructures import WWWAuthenticate
|
||||
from werkzeug.exceptions import Unauthorized
|
||||
|
||||
from odoo import models
|
||||
from odoo.http import request
|
||||
|
||||
from odoo.addons.ai_mcp.utils.oauth_utils import protected_resource_metadata_url
|
||||
|
||||
|
||||
class IrHttp(models.AbstractModel):
|
||||
_inherit = 'ir.http'
|
||||
|
||||
@classmethod
|
||||
def _auth_method_bearer(cls, routing):
|
||||
try:
|
||||
super()._auth_method_bearer(routing)
|
||||
except Unauthorized as error:
|
||||
if not routing.get("bearer_scope") == "mcp":
|
||||
raise
|
||||
|
||||
params = {"resource_metadata": protected_resource_metadata_url(request.env)}
|
||||
if request.httprequest.headers.get("Authorization", "").lower().startswith("bearer "):
|
||||
params["error"] = "invalid_token"
|
||||
|
||||
raise Unauthorized(www_authenticate=WWWAuthenticate('Bearer', params)) from error
|
||||
117
ai_mcp/models/oauth_authorization_code.py
Normal file
117
ai_mcp/models/oauth_authorization_code.py
Normal file
@@ -0,0 +1,117 @@
|
||||
from datetime import timedelta
|
||||
|
||||
from odoo import api, fields, models
|
||||
from odoo.exceptions import AccessDenied
|
||||
from odoo.addons.ai_mcp.utils.oauth_utils import (
|
||||
_generate_hash, _generate_secret, _verify_hash, check_mcp_oauth_user_access,
|
||||
OAUTH_SECRET_INDEX_SIZE, verifier_matches_challenge,
|
||||
)
|
||||
from odoo.tools import SQL
|
||||
|
||||
|
||||
class OauthAuthorizationCode(models.Model):
|
||||
_name = 'oauth.authorization.code'
|
||||
_description = 'OAuth 2.1 Authorization Code'
|
||||
|
||||
# The client_id can't be a Many2one because CIMD clients has no oauth.client records.
|
||||
client_id = fields.Char(required=True)
|
||||
redirect_uri = fields.Char(required=True)
|
||||
code_challenge = fields.Char(required=True)
|
||||
user_id = fields.Many2one('res.users', required=True, ondelete='cascade')
|
||||
expiration_date = fields.Datetime(required=True)
|
||||
apikey_expiration_date = fields.Datetime(
|
||||
help="Expiration date the user consented to for the API key this code will be redeemed for. "
|
||||
"Empty for an API key that never expires.",
|
||||
)
|
||||
|
||||
def init(self):
|
||||
super().init()
|
||||
table = SQL.identifier(self._table)
|
||||
self.env.cr.execute(SQL(
|
||||
"""
|
||||
ALTER TABLE %(table)s
|
||||
ADD COLUMN IF NOT EXISTS code_hash varchar NOT NULL,
|
||||
ADD COLUMN IF NOT EXISTS code_index varchar(%(index_size)s) NOT NULL
|
||||
CHECK (char_length(code_index) = %(index_size)s)
|
||||
""",
|
||||
table=table,
|
||||
index_size=OAUTH_SECRET_INDEX_SIZE,
|
||||
))
|
||||
self.env.cr.execute(SQL(
|
||||
"CREATE INDEX IF NOT EXISTS %s ON %s (code_index)",
|
||||
SQL.identifier(self._table + "_code_index_index"),
|
||||
table,
|
||||
))
|
||||
|
||||
def _generate(self, client_id, redirect_uri, code_challenge, user, apikey_expiration_date, code_ttl_seconds=120):
|
||||
code = _generate_secret()
|
||||
self.env.cr.execute(SQL(
|
||||
"""
|
||||
INSERT INTO %(table)s
|
||||
(code_hash, code_index, client_id, redirect_uri, code_challenge, user_id, expiration_date, apikey_expiration_date)
|
||||
VALUES
|
||||
(%(code_hash)s, %(code_index)s, %(client_id)s, %(redirect_uri)s, %(code_challenge)s, %(user_id)s, %(expiration_date)s, %(apikey_expiration_date)s)
|
||||
""",
|
||||
table=SQL.identifier(self._table),
|
||||
code_hash=_generate_hash(code),
|
||||
code_index=code[:OAUTH_SECRET_INDEX_SIZE],
|
||||
client_id=client_id,
|
||||
redirect_uri=redirect_uri,
|
||||
code_challenge=code_challenge,
|
||||
user_id=user.id,
|
||||
expiration_date=fields.Datetime.now() + timedelta(seconds=code_ttl_seconds),
|
||||
apikey_expiration_date=apikey_expiration_date,
|
||||
))
|
||||
return code
|
||||
|
||||
@api.model
|
||||
def _redeem(self, code, client_id, redirect_uri, code_verifier, client_name) -> dict:
|
||||
authorization_code = self._retrieve_record(code, client_id, redirect_uri)
|
||||
if not authorization_code:
|
||||
raise AccessDenied(self.env._("Invalid authorization code"))
|
||||
if not verifier_matches_challenge(code_verifier, authorization_code.code_challenge):
|
||||
authorization_code.sudo().unlink()
|
||||
raise AccessDenied(self.env._("Invalid PKCE code_verifier"))
|
||||
|
||||
user = authorization_code.user_id
|
||||
apikey_expiration_date = authorization_code.apikey_expiration_date
|
||||
authorization_code.sudo().unlink()
|
||||
check_mcp_oauth_user_access(user)
|
||||
|
||||
# This method is called from a controller with auth='public'. However, the api key
|
||||
# is generated using the user of the environment. Thus, we need to do with_user(user)
|
||||
access_token = self.env['res.users.apikeys'].with_user(user)._generate(
|
||||
'mcp', client_name, apikey_expiration_date,
|
||||
)
|
||||
|
||||
result = {'access_token': access_token, 'token_type': 'Bearer', 'scope': 'mcp'}
|
||||
if apikey_expiration_date:
|
||||
result['expires_in'] = int((apikey_expiration_date - fields.Datetime.now()).total_seconds())
|
||||
return result
|
||||
|
||||
@api.model
|
||||
def _retrieve_record(self, code, client_id, redirect_uri):
|
||||
self.env.cr.execute(SQL(
|
||||
"""
|
||||
SELECT id, code_hash
|
||||
FROM %(table)s
|
||||
WHERE code_index = %(code_index)s
|
||||
AND client_id = %(client_id)s
|
||||
AND redirect_uri = %(redirect_uri)s
|
||||
AND expiration_date > %(now)s
|
||||
""",
|
||||
table=SQL.identifier(self._table),
|
||||
code_index=code[:OAUTH_SECRET_INDEX_SIZE],
|
||||
client_id=client_id,
|
||||
redirect_uri=redirect_uri,
|
||||
now=fields.Datetime.now(),
|
||||
))
|
||||
matching_id = next(
|
||||
(row_id for row_id, code_hash in self.env.cr.fetchall() if _verify_hash(code, code_hash)),
|
||||
None,
|
||||
)
|
||||
return self.sudo().browse(matching_id)
|
||||
|
||||
@api.autovacuum
|
||||
def _gc_expired_codes(self):
|
||||
self.sudo().search([('expiration_date', '<', fields.Datetime.now())]).unlink()
|
||||
56
ai_mcp/models/oauth_client.py
Normal file
56
ai_mcp/models/oauth_client.py
Normal file
@@ -0,0 +1,56 @@
|
||||
import uuid
|
||||
|
||||
from odoo import api, fields, models
|
||||
from odoo.exceptions import UserError
|
||||
|
||||
from odoo.addons.ai_mcp.utils.oauth_utils import normalize_localhost_to_ip, validate_redirect_uris
|
||||
|
||||
|
||||
class OauthClient(models.Model):
|
||||
_name = 'oauth.client'
|
||||
_description = 'OAuth Client Application'
|
||||
_rec_name = 'client_name'
|
||||
|
||||
client_name = fields.Char(required=True)
|
||||
client_id = fields.Char(
|
||||
string="Client ID", required=True, copy=False, readonly=True,
|
||||
default=lambda self: uuid.uuid4().hex,
|
||||
)
|
||||
redirect_uris = fields.Text(
|
||||
required=True,
|
||||
help="One redirect URI per line. Must be HTTPS, except for http:// loopback URIs.",
|
||||
)
|
||||
active = fields.Boolean(
|
||||
default=True,
|
||||
help="Archiving a client makes the authorization server block any new authorization or token request made with its client_id.",
|
||||
)
|
||||
|
||||
_client_id_unique = models.Constraint(
|
||||
'UNIQUE (client_id)',
|
||||
"Another client is already registered with this client ID.",
|
||||
)
|
||||
_redirect_uris_not_empty = models.Constraint(
|
||||
"CHECK (redirect_uris <> '')",
|
||||
"At least one redirect URI is required.",
|
||||
)
|
||||
|
||||
@api.model_create_multi
|
||||
def create(self, vals_list):
|
||||
for vals in vals_list:
|
||||
vals['redirect_uris'] = self._normalize_and_validate_redirect_uris(vals.get('redirect_uris'))
|
||||
return super().create(vals_list)
|
||||
|
||||
def write(self, vals):
|
||||
if 'client_id' in vals:
|
||||
raise UserError(self.env._("The client ID is generated once at registration and can never be changed."))
|
||||
if 'redirect_uris' in vals:
|
||||
vals['redirect_uris'] = self._normalize_and_validate_redirect_uris(vals['redirect_uris'])
|
||||
return super().write(vals)
|
||||
|
||||
def _normalize_and_validate_redirect_uris(self, redirect_uris: str | None) -> str:
|
||||
redirect_uris_list = [
|
||||
normalize_localhost_to_ip(uri.strip())
|
||||
for uri in (redirect_uris or '').splitlines() if uri.strip()
|
||||
]
|
||||
validate_redirect_uris(self.env, redirect_uris_list)
|
||||
return '\n'.join(redirect_uris_list)
|
||||
19
ai_mcp/models/res_config_settings.py
Normal file
19
ai_mcp/models/res_config_settings.py
Normal file
@@ -0,0 +1,19 @@
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
from odoo import fields, models
|
||||
|
||||
|
||||
class ResConfigSettings(models.TransientModel):
|
||||
_inherit = 'res.config.settings'
|
||||
|
||||
mcp_enable_dcr = fields.Boolean(
|
||||
string="Dynamic Client Registration",
|
||||
config_parameter='enable_dcr',
|
||||
groups='base.group_system',
|
||||
help="Allow MCP clients to register automatically.",
|
||||
)
|
||||
mcp_allowed_cimd_urls = fields.Char(
|
||||
string="Allowed Client ID Metadata Document (CIMD)",
|
||||
config_parameter='cimd_allowed_urls',
|
||||
groups='base.group_system',
|
||||
help="One client ID metadata document URL per line.",
|
||||
)
|
||||
10
ai_mcp/models/res_users_description.py
Normal file
10
ai_mcp/models/res_users_description.py
Normal file
@@ -0,0 +1,10 @@
|
||||
from odoo import fields, models
|
||||
|
||||
|
||||
class ResUsersApikeysDescription(models.TransientModel):
|
||||
_inherit = 'res.users.apikeys.description'
|
||||
|
||||
scope = fields.Selection(
|
||||
selection_add=[('mcp', 'MCP')],
|
||||
ondelete={'mcp': 'cascade'},
|
||||
)
|
||||
Reference in New Issue
Block a user