diff --git a/ai_tool_server_action/README.rst b/ai_tool_server_action/README.rst new file mode 100644 index 00000000..0d7a2a94 --- /dev/null +++ b/ai_tool_server_action/README.rst @@ -0,0 +1,128 @@ +===================== +AI Tool Server Action +===================== + +.. + !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + !! This file is generated by oca-gen-addon-readme !! + !! changes will be overwritten. !! + !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + !! source digest: sha256:3607e5a7335eecf5d7886965f487a459b2517a5970d330fca4a9f6e24e294290 + !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + +.. |badge1| image:: https://img.shields.io/badge/maturity-Beta-yellow.png + :target: https://odoo-community.org/page/development-status + :alt: Beta +.. |badge2| image:: https://img.shields.io/badge/licence-AGPL--3-blue.png + :target: http://www.gnu.org/licenses/agpl-3.0-standalone.html + :alt: License: AGPL-3 +.. |badge3| image:: https://img.shields.io/badge/github-OCA%2Fai-lightgray.png?logo=github + :target: https://github.com/OCA/ai/tree/18.0/ai_tool_server_action + :alt: OCA/ai +.. |badge4| image:: https://img.shields.io/badge/weblate-Translate%20me-F47D42.png + :target: https://translation.odoo-community.org/projects/ai-18-0/ai-18-0-ai_tool_server_action + :alt: Translate me on Weblate +.. |badge5| image:: https://img.shields.io/badge/runboat-Try%20me-875A7B.png + :target: https://runboat.odoo-community.org/builds?repo=OCA/ai&target_branch=18.0 + :alt: Try me on Runboat + +|badge1| |badge2| |badge3| |badge4| |badge5| + +This module allows creating and configuring AI tools dynamically via +Odoo Server Actions. Instead of hardcoding tool definitions and logic in +Python, power users and administrators can define LLM-accessible tools +directly from the user interface. + +**Table of contents** + +.. contents:: + :local: + +Configuration +============= + +To configure an AI Tool backed by a Server Action: + +1. Go to *Settings > Technical > Actions > Server Actions*. +2. Create a new Server Action or select an existing one. +3. Open the *AI Tool Configuration* tab. +4. Click on the **Create AI Tool** (or **Configure AI Tool** if it + already exists) button to generate or modify the AI tool for this + action. +5. Provide the *Tool Name*, *Tool Description*, *Input Schema (JSON)* + and *Output Schema (JSON)* in the wizard to strongly type the inputs + and outputs of your tool for the LLM. + +Usage +===== + +1. For Server Actions containing **Python code**, you have access to the + arguments sent by the AI in ``env.context.get('tool_args')``. To + return a result, simply assign a dictionary to the local ``action`` + variable: + + .. code:: python + + args = env.context.get('tool_args', {}) + search_term = args.get('query') + records = env['res.partner'].search([('name', 'ilike', search_term)], limit=5) + action = {'results': records.mapped('display_name')} + +2. **Standard Server Actions** (e.g. Update Record, Create Activity, + Send Email) work out-of-the-box. When they successfully execute, the + AI will automatically receive a ``{"status": "success"}`` response. + Any User Interface actions (like opening a wizard or window) are + silently intercepted to prevent confusing the AI. + +3. **External / MCP Usage:** When the AI invokes these tools externally + (via the MCP protocol or general chat) it won't have an active Odoo + record context. + + - For Standard Actions to work in this scenario, simply declare an + ``active_id`` parameter in your **Input Schema** and the module + will intelligently inject it into the execution context for you. + - The wizard pre-loads these intelligent default schemas + automatically for you based on the action type. + +Bug Tracker +=========== + +Bugs are tracked on `GitHub Issues `_. +In case of trouble, please check there if your issue has already been reported. +If you spotted it first, help us to smash it by providing a detailed and welcomed +`feedback `_. + +Do not contact contributors directly about support or help with technical issues. + +Credits +======= + +Authors +------- + +* SDi + +Maintainers +----------- + +This module is maintained by the OCA. + +.. image:: https://odoo-community.org/logo.png + :alt: Odoo Community Association + :target: https://odoo-community.org + +OCA, or the Odoo Community Association, is a nonprofit organization whose +mission is to support the collaborative development of Odoo features and +promote its widespread use. + +.. |maintainer-amoya@sdi.es| image:: https://github.com/amoya@sdi.es.png?size=40px + :target: https://github.com/amoya@sdi.es + :alt: amoya@sdi.es + +Current `maintainer `__: + +|maintainer-amoya@sdi.es| + +This module is part of the `OCA/ai `_ project on GitHub. + +You are welcome to contribute. To learn how please visit https://odoo-community.org/page/Contribute. diff --git a/ai_tool_server_action/__init__.py b/ai_tool_server_action/__init__.py new file mode 100644 index 00000000..9cc906ad --- /dev/null +++ b/ai_tool_server_action/__init__.py @@ -0,0 +1,5 @@ +# Copyright 2026 SDi +# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). + +from . import models +from . import wizard diff --git a/ai_tool_server_action/__manifest__.py b/ai_tool_server_action/__manifest__.py new file mode 100644 index 00000000..8fa2100b --- /dev/null +++ b/ai_tool_server_action/__manifest__.py @@ -0,0 +1,23 @@ +# Copyright 2026 SDi +# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). + +{ + "name": "AI Tool Server Action", + "summary": "Allow configuring AI Tools using Server Actions", + "version": "18.0.1.0.0", + "category": "Hidden", + "author": "SDi, Odoo Community Association (OCA)", + "maintainers": ["amoya@sdi.es"], + "website": "https://github.com/OCA/ai", + "license": "AGPL-3", + "depends": [ + "ai_tool", + ], + "data": [ + "security/ir.model.access.csv", + "wizard/ai_tool_server_action_wizard_views.xml", + "views/ai_tool_views.xml", + "views/ir_actions_server_views.xml", + ], + "installable": True, +} diff --git a/ai_tool_server_action/models/__init__.py b/ai_tool_server_action/models/__init__.py new file mode 100644 index 00000000..9ce6940c --- /dev/null +++ b/ai_tool_server_action/models/__init__.py @@ -0,0 +1,5 @@ +# Copyright 2026 SDi +# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). + +from . import ai_tool +from . import ir_actions_server diff --git a/ai_tool_server_action/models/ai_tool.py b/ai_tool_server_action/models/ai_tool.py new file mode 100644 index 00000000..de13701d --- /dev/null +++ b/ai_tool_server_action/models/ai_tool.py @@ -0,0 +1,92 @@ +# Copyright 2026 SDi +# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). + +import json + +from odoo import fields, models + + +class AiTool(models.Model): + _inherit = "ai.tool" + + kind = fields.Selection( + selection_add=[("server_action", "Server Action")], + ondelete={"server_action": "cascade"}, + ) + model_id = fields.Many2one(required=False) + function_name = fields.Char(required=False) + + server_action_id = fields.Many2one( + "ir.actions.server", + string="Server Action", + help="The server action to execute when this tool is called.", + ) + input_schema_json = fields.Text( + string="Input Schema (JSON)", + help="Define the expected input schema for the LLM in JSON format.", + ) + output_schema_json = fields.Text( + string="Output Schema (JSON)", + help="Define the expected output schema for the LLM in JSON format.", + ) + + def _get_tool_definition(self): + if self.kind == "server_action": + input_schema = {} + if self.input_schema_json: + try: + input_schema = json.loads(self.input_schema_json) + except ValueError: + input_schema = {} + output_schema = {} + if self.output_schema_json: + try: + output_schema = json.loads(self.output_schema_json) + except ValueError: + output_schema = {} + return { + "name": self.name, + "description": self.description, + "inputSchema": input_schema, + "outputSchema": output_schema, + } + return super()._get_tool_definition() + + def _execute_tool(self, *args, record=None, **kwargs): + if self.kind == "server_action": + # Extract active_id and active_model from record, or fallback + # to kwargs (useful for MCP integration) + active_id = record.id if record else kwargs.get("active_id", False) + active_model = ( + record._name + if record + else kwargs.get("active_model", self.server_action_id.model_id.model) + ) + active_ids = [active_id] if active_id else kwargs.get("active_ids", []) + + action = self.server_action_id.with_context( + tool_args=kwargs, + active_id=active_id, + active_ids=active_ids, + active_model=active_model, + ) + result = action.run() + if isinstance(result, dict): + # If the action returns a UI action (like opening a window), + # we ignore it and return a success message since + # the AI cannot interact with the UI. + if result.get("type") and str(result.get("type")).startswith( + "ir.actions." + ): + return { + "status": "success", + "message": "Action executed successfully (UI action ignored)", + } + return result + + # For actions that return False/None (like Update Record, Send Email) + return { + "status": "success", + "message": "Action executed successfully", + } + return super()._execute_tool(*args, record=record, **kwargs) diff --git a/ai_tool_server_action/models/ir_actions_server.py b/ai_tool_server_action/models/ir_actions_server.py new file mode 100644 index 00000000..470cb974 --- /dev/null +++ b/ai_tool_server_action/models/ir_actions_server.py @@ -0,0 +1,76 @@ +# Copyright 2026 SDi +# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). + +from odoo import api, fields, models + + +class IrActionsServer(models.Model): + _inherit = "ir.actions.server" + + ai_tool_ids = fields.One2many( + "ai.tool", + "server_action_id", + string="AI Tools", + ) + ai_tool_id = fields.Many2one( + "ai.tool", + string="AI Tool", + compute="_compute_ai_tool_id", + ) + ai_tool_description = fields.Text( + compute="_compute_ai_tool_fields", + inverse="_inverse_ai_tool_description", + string="AI Tool Description", + ) + input_schema_json = fields.Text( + compute="_compute_ai_tool_fields", + inverse="_inverse_input_schema_json", + string="AI Tool Input Schema", + ) + output_schema_json = fields.Text( + compute="_compute_ai_tool_fields", + inverse="_inverse_output_schema_json", + string="AI Tool Output Schema", + ) + + @api.depends("ai_tool_ids") + def _compute_ai_tool_id(self): + for rec in self: + rec.ai_tool_id = rec.ai_tool_ids[:1] + + @api.depends( + "ai_tool_ids.input_schema_json", + "ai_tool_ids.output_schema_json", + "ai_tool_ids.description", + ) + def _compute_ai_tool_fields(self): + for rec in self: + rec.ai_tool_description = rec.ai_tool_id.description + rec.input_schema_json = rec.ai_tool_id.input_schema_json + rec.output_schema_json = rec.ai_tool_id.output_schema_json + + def _inverse_ai_tool_description(self): + for rec in self: + if rec.ai_tool_id: + rec.ai_tool_id.sudo().description = rec.ai_tool_description + + def _inverse_input_schema_json(self): + for rec in self: + if rec.ai_tool_id: + rec.ai_tool_id.sudo().input_schema_json = rec.input_schema_json + + def _inverse_output_schema_json(self): + for rec in self: + if rec.ai_tool_id: + rec.ai_tool_id.sudo().output_schema_json = rec.output_schema_json + + def action_open_ai_tool_wizard(self): + self.ensure_one() + return { + "name": "Create AI Tool", + "type": "ir.actions.act_window", + "res_model": "ai.tool.server.action.wizard", + "view_mode": "form", + "target": "new", + "context": {"default_server_action_id": self.id}, + } diff --git a/ai_tool_server_action/pyproject.toml b/ai_tool_server_action/pyproject.toml new file mode 100644 index 00000000..4231d0cc --- /dev/null +++ b/ai_tool_server_action/pyproject.toml @@ -0,0 +1,3 @@ +[build-system] +requires = ["whool"] +build-backend = "whool.buildapi" diff --git a/ai_tool_server_action/readme/CONFIGURE.md b/ai_tool_server_action/readme/CONFIGURE.md new file mode 100644 index 00000000..7c5d8323 --- /dev/null +++ b/ai_tool_server_action/readme/CONFIGURE.md @@ -0,0 +1,7 @@ +To configure an AI Tool backed by a Server Action: + +1. Go to *Settings > Technical > Actions > Server Actions*. +2. Create a new Server Action or select an existing one. +3. Open the *AI Tool Configuration* tab. +4. Click on the **Create AI Tool** (or **Configure AI Tool** if it already exists) button to generate or modify the AI tool for this action. +5. Provide the *Tool Name*, *Tool Description*, *Input Schema (JSON)* and *Output Schema (JSON)* in the wizard to strongly type the inputs and outputs of your tool for the LLM. diff --git a/ai_tool_server_action/readme/DESCRIPTION.md b/ai_tool_server_action/readme/DESCRIPTION.md new file mode 100644 index 00000000..b2f057b8 --- /dev/null +++ b/ai_tool_server_action/readme/DESCRIPTION.md @@ -0,0 +1,4 @@ +This module allows creating and configuring AI tools dynamically via +Odoo Server Actions. Instead of hardcoding tool definitions and logic in +Python, power users and administrators can define LLM-accessible tools +directly from the user interface. diff --git a/ai_tool_server_action/readme/USAGE.md b/ai_tool_server_action/readme/USAGE.md new file mode 100644 index 00000000..f1e12125 --- /dev/null +++ b/ai_tool_server_action/readme/USAGE.md @@ -0,0 +1,14 @@ +1. For Server Actions containing **Python code**, you have access to the arguments sent by the AI in `env.context.get('tool_args')`. To return a result, simply assign a dictionary to the local `action` variable: + + ```python + args = env.context.get('tool_args', {}) + search_term = args.get('query') + records = env['res.partner'].search([('name', 'ilike', search_term)], limit=5) + action = {'results': records.mapped('display_name')} + ``` + +2. **Standard Server Actions** (e.g. Update Record, Create Activity, Send Email) work out-of-the-box. When they successfully execute, the AI will automatically receive a `{"status": "success"}` response. Any User Interface actions (like opening a wizard or window) are silently intercepted to prevent confusing the AI. + +3. **External / MCP Usage:** When the AI invokes these tools externally (via the MCP protocol or general chat) it won't have an active Odoo record context. + - For Standard Actions to work in this scenario, simply declare an `active_id` parameter in your **Input Schema** and the module will intelligently inject it into the execution context for you. + - The wizard pre-loads these intelligent default schemas automatically for you based on the action type. diff --git a/ai_tool_server_action/security/ir.model.access.csv b/ai_tool_server_action/security/ir.model.access.csv new file mode 100644 index 00000000..5564b983 --- /dev/null +++ b/ai_tool_server_action/security/ir.model.access.csv @@ -0,0 +1,2 @@ +id,name,model_id:id,group_id:id,perm_read,perm_write,perm_create,perm_unlink +access_ai_tool_server_action_wizard,ai.tool.server.action.wizard,model_ai_tool_server_action_wizard,base.group_user,1,1,1,1 diff --git a/ai_tool_server_action/static/description/index.html b/ai_tool_server_action/static/description/index.html new file mode 100644 index 00000000..bfb3c03b --- /dev/null +++ b/ai_tool_server_action/static/description/index.html @@ -0,0 +1,471 @@ + + + + + +AI Tool Server Action + + + +
+

AI Tool Server Action

+ + +

Beta License: AGPL-3 OCA/ai Translate me on Weblate Try me on Runboat

+

This module allows creating and configuring AI tools dynamically via +Odoo Server Actions. Instead of hardcoding tool definitions and logic in +Python, power users and administrators can define LLM-accessible tools +directly from the user interface.

+

Table of contents

+ +
+

Configuration

+

To configure an AI Tool backed by a Server Action:

+
    +
  1. Go to Settings > Technical > Actions > Server Actions.
  2. +
  3. Create a new Server Action or select an existing one.
  4. +
  5. Open the AI Tool Configuration tab.
  6. +
  7. Click on the Create AI Tool (or Configure AI Tool if it +already exists) button to generate or modify the AI tool for this +action.
  8. +
  9. Provide the Tool Name, Tool Description, Input Schema (JSON) +and Output Schema (JSON) in the wizard to strongly type the inputs +and outputs of your tool for the LLM.
  10. +
+
+
+

Usage

+
    +
  1. For Server Actions containing Python code, you have access to the +arguments sent by the AI in env.context.get('tool_args'). To +return a result, simply assign a dictionary to the local action +variable:

    +
    +args = env.context.get('tool_args', {})
    +search_term = args.get('query')
    +records = env['res.partner'].search([('name', 'ilike', search_term)], limit=5)
    +action = {'results': records.mapped('display_name')}
    +
    +
  2. +
  3. Standard Server Actions (e.g. Update Record, Create Activity, +Send Email) work out-of-the-box. When they successfully execute, the +AI will automatically receive a {"status": "success"} response. +Any User Interface actions (like opening a wizard or window) are +silently intercepted to prevent confusing the AI.

    +
  4. +
  5. External / MCP Usage: When the AI invokes these tools externally +(via the MCP protocol or general chat) it won’t have an active Odoo +record context.

    +
      +
    • For Standard Actions to work in this scenario, simply declare an +active_id parameter in your Input Schema and the module +will intelligently inject it into the execution context for you.
    • +
    • The wizard pre-loads these intelligent default schemas +automatically for you based on the action type.
    • +
    +
  6. +
+
+
+

Bug Tracker

+

Bugs are tracked on GitHub Issues. +In case of trouble, please check there if your issue has already been reported. +If you spotted it first, help us to smash it by providing a detailed and welcomed +feedback.

+

Do not contact contributors directly about support or help with technical issues.

+
+
+

Credits

+
+

Authors

+
    +
  • SDi
  • +
+
+
+

Maintainers

+

This module is maintained by the OCA.

+ +Odoo Community Association + +

OCA, or the Odoo Community Association, is a nonprofit organization whose +mission is to support the collaborative development of Odoo features and +promote its widespread use.

+

Current maintainer:

+

amoya@sdi.es

+

This module is part of the OCA/ai project on GitHub.

+

You are welcome to contribute. To learn how please visit https://odoo-community.org/page/Contribute.

+
+
+
+ + diff --git a/ai_tool_server_action/tests/__init__.py b/ai_tool_server_action/tests/__init__.py new file mode 100644 index 00000000..b1edce3b --- /dev/null +++ b/ai_tool_server_action/tests/__init__.py @@ -0,0 +1 @@ +from . import test_ai_tool_server_action diff --git a/ai_tool_server_action/tests/test_ai_tool_server_action.py b/ai_tool_server_action/tests/test_ai_tool_server_action.py new file mode 100644 index 00000000..3c32613e --- /dev/null +++ b/ai_tool_server_action/tests/test_ai_tool_server_action.py @@ -0,0 +1,254 @@ +# Copyright 2026 SDi +# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). + +from odoo.tests.common import TransactionCase + + +class TestAiToolServerAction(TransactionCase): + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.server_action = cls.env["ir.actions.server"].create( + { + "name": "Test Server Action", + "model_id": cls.env.ref("base.model_res_partner").id, + "state": "code", + "code": """ +args = env.context.get('tool_args', {}) +action = { + 'received_query': args.get('query'), + 'status': 'ok' +} +""", + } + ) + cls.ai_tool = cls.env["ai.tool"].create( + { + "name": "test_server_action_tool", + "description": "Test tool description", + "kind": "server_action", + "server_action_id": cls.server_action.id, + "input_schema_json": ( + '{"type": "object", "properties": {"query": {"type": "string"}}}' + ), + "output_schema_json": '{"type": "object"}', + } + ) + + def test_tool_creation(self): + """Test that the tool is correctly created without model_id and function_name""" + self.assertEqual(self.ai_tool.kind, "server_action") + self.assertEqual(self.ai_tool.server_action_id, self.server_action) + self.assertFalse(self.ai_tool.model_id) + self.assertFalse(self.ai_tool.function_name) + + def test_get_tool_definition(self): + """Test that _get_tool_definition correctly parses JSON schemas""" + definition = self.ai_tool._get_tool_definition() + self.assertEqual(definition["name"], "test_server_action_tool") + self.assertEqual(definition["description"], "Test tool description") + self.assertEqual( + definition["inputSchema"], + {"type": "object", "properties": {"query": {"type": "string"}}}, + ) + self.assertEqual(definition["outputSchema"], {"type": "object"}) + + def test_get_tool_definition_invalid_json(self): + """Test that _get_tool_definition handles invalid JSON gracefully""" + self.ai_tool.write( + { + "input_schema_json": "invalid json", + "output_schema_json": "also invalid", + } + ) + definition = self.ai_tool._get_tool_definition() + self.assertEqual(definition["inputSchema"], {}) + self.assertEqual(definition["outputSchema"], {}) + + def test_execute_tool(self): + """Test that _execute_tool correctly delegates to the server action""" + result = self.ai_tool._execute_tool(query="test_query") + self.assertEqual(result.get("status"), "ok") + self.assertEqual(result.get("received_query"), "test_query") + + def test_execute_tool_no_dict_return(self): + """Test that _execute_tool handles server actions that do not return a dict""" + server_action_empty = self.env["ir.actions.server"].create( + { + "name": "Empty Server Action", + "model_id": self.env.ref("base.model_res_partner").id, + "state": "code", + "code": "action = False", + } + ) + self.ai_tool.server_action_id = server_action_empty + result = self.ai_tool._execute_tool() + self.assertEqual( + result, {"status": "success", "message": "Action executed successfully"} + ) + + def test_execute_tool_ui_action(self): + """Test that UI actions are intercepted and return a success message""" + server_action_ui = self.env["ir.actions.server"].create( + { + "name": "UI Server Action", + "model_id": self.env.ref("base.model_res_partner").id, + "state": "code", + "code": "action = {'type': 'ir.actions.act_window', 'name': 'Test'}", + } + ) + self.ai_tool.server_action_id = server_action_ui + result = self.ai_tool._execute_tool() + self.assertEqual( + result, + { + "status": "success", + "message": "Action executed successfully (UI action ignored)", + }, + ) + + def test_ir_actions_server_ai_tool_id(self): + """Test the computed fields on ir.actions.server""" + self.assertEqual(self.server_action.ai_tool_id, self.ai_tool) + self.assertEqual( + self.server_action.input_schema_json, self.ai_tool.input_schema_json + ) + self.assertEqual( + self.server_action.output_schema_json, self.ai_tool.output_schema_json + ) + + def test_action_open_ai_tool_wizard(self): + """Test the button action returns correct dictionary""" + action = self.server_action.action_open_ai_tool_wizard() + self.assertEqual(action["type"], "ir.actions.act_window") + self.assertEqual(action["res_model"], "ai.tool.server.action.wizard") + self.assertEqual( + action["context"]["default_server_action_id"], self.server_action.id + ) + + def test_wizard_default_get_existing(self): + """Test wizard default_get when ai_tool already exists""" + wizard_vals = ( + self.env["ai.tool.server.action.wizard"] + .with_context(default_server_action_id=self.server_action.id) + .default_get( + [ + "server_action_id", + "ai_tool_id", + "name", + "description", + "input_schema_json", + "output_schema_json", + ] + ) + ) + self.assertEqual(wizard_vals["ai_tool_id"], self.ai_tool.id) + self.assertEqual(wizard_vals["name"], self.ai_tool.name) + self.assertEqual(wizard_vals["description"], self.ai_tool.description) + + def test_wizard_default_get_new(self): + """Test wizard default_get when ai_tool does not exist""" + new_action = self.env["ir.actions.server"].create( + { + "name": "New Action", + "model_id": self.env.ref("base.model_res_partner").id, + "state": "code", + "code": "action = False", + } + ) + wizard_vals = ( + self.env["ai.tool.server.action.wizard"] + .with_context(default_server_action_id=new_action.id) + .default_get(["server_action_id", "name"]) + ) + self.assertFalse(wizard_vals.get("ai_tool_id")) + self.assertEqual(wizard_vals["name"], "New Action") + + def test_wizard_action_apply_create(self): + """Test wizard creating a new ai.tool""" + new_action = self.env["ir.actions.server"].create( + { + "name": "New Action 2", + "model_id": self.env.ref("base.model_res_partner").id, + "state": "code", + "code": "action = False", + } + ) + wizard = ( + self.env["ai.tool.server.action.wizard"] + .with_context(default_server_action_id=new_action.id) + .create( + { + "server_action_id": new_action.id, + "name": "New Tool", + "description": "Desc", + "input_schema_json": "{}", + "output_schema_json": "{}", + } + ) + ) + wizard.action_apply() + self.assertTrue(new_action.ai_tool_id) + self.assertEqual(new_action.ai_tool_id.name, "New Tool") + + def test_wizard_action_apply_update(self): + """Test wizard updating an existing ai.tool""" + wizard = ( + self.env["ai.tool.server.action.wizard"] + .with_context(default_server_action_id=self.server_action.id) + .create( + { + "server_action_id": self.server_action.id, + "ai_tool_id": self.ai_tool.id, + "name": "Updated Tool", + "description": "Updated Desc", + "input_schema_json": '{"test": 1}', + } + ) + ) + wizard.action_apply() + self.assertEqual(self.ai_tool.name, "Updated Tool") + self.assertEqual(self.ai_tool.description, "Updated Desc") + self.assertEqual(self.ai_tool.input_schema_json, '{"test": 1}') + + def test_ir_actions_server_inverse_fields(self): + """Test that writing fields updates the underlying ai.tool""" + self.server_action.write( + { + "ai_tool_description": "New inverse description", + "input_schema_json": '{"type": "object"}', + "output_schema_json": '{"type": "string"}', + } + ) + self.assertEqual(self.ai_tool.description, "New inverse description") + self.assertEqual(self.ai_tool.input_schema_json, '{"type": "object"}') + self.assertEqual(self.ai_tool.output_schema_json, '{"type": "string"}') + + def test_execute_tool_super(self): + """Test that _execute_tool handles non-server-action tools via super()""" + generic_tool = self.env["ai.tool"].create( + { + "name": "get_date_tool", + "description": "Get current date", + "kind": "generic", + "model_id": self.env.ref("ai_tool.model_ai_tool").id, + "function_name": "_ai_get_date", + } + ) + result = generic_tool._execute_tool() + self.assertIn("date", result) + + def test_get_tool_definition_super(self): + """Test that _get_tool_definition handles non-server-action tools via super()""" + generic_tool = self.env["ai.tool"].create( + { + "name": "get_date_tool", + "description": "Get current date", + "kind": "generic", + "model_id": self.env.ref("ai_tool.model_ai_tool").id, + "function_name": "_ai_get_date", + } + ) + definition = generic_tool._get_tool_definition() + self.assertEqual(definition["name"], "get_date_tool") + self.assertIn("date", definition["outputSchema"].get("properties", {})) diff --git a/ai_tool_server_action/views/ai_tool_views.xml b/ai_tool_server_action/views/ai_tool_views.xml new file mode 100644 index 00000000..e3a5c0a8 --- /dev/null +++ b/ai_tool_server_action/views/ai_tool_views.xml @@ -0,0 +1,35 @@ + + + + ai.tool.server.action.form + ai.tool + + + + + + + + + + + + + + + + + + diff --git a/ai_tool_server_action/views/ir_actions_server_views.xml b/ai_tool_server_action/views/ir_actions_server_views.xml new file mode 100644 index 00000000..969f6280 --- /dev/null +++ b/ai_tool_server_action/views/ir_actions_server_views.xml @@ -0,0 +1,45 @@ + + + + ir.actions.server.view.form.ai.tool + ir.actions.server + + + + +
+

+ This Server Action is not currently configured as an AI Tool. +

+
+ + + + + + + + + + + +
+
+
+
+
diff --git a/ai_tool_server_action/wizard/__init__.py b/ai_tool_server_action/wizard/__init__.py new file mode 100644 index 00000000..54e6f54f --- /dev/null +++ b/ai_tool_server_action/wizard/__init__.py @@ -0,0 +1,4 @@ +# Copyright 2026 SDi +# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). + +from . import ai_tool_server_action_wizard diff --git a/ai_tool_server_action/wizard/ai_tool_server_action_wizard.py b/ai_tool_server_action/wizard/ai_tool_server_action_wizard.py new file mode 100644 index 00000000..e1c21f82 --- /dev/null +++ b/ai_tool_server_action/wizard/ai_tool_server_action_wizard.py @@ -0,0 +1,85 @@ +# Copyright 2026 SDi +# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). + +from odoo import api, fields, models + + +class AiToolServerActionWizard(models.TransientModel): + _name = "ai.tool.server.action.wizard" + _description = "Wizard to create AI Tool from Server Action" + + server_action_id = fields.Many2one("ir.actions.server", required=True) + ai_tool_id = fields.Many2one("ai.tool") + name = fields.Char(string="Tool Name", required=True) + description = fields.Text(string="Tool Description", required=True) + input_schema_json = fields.Text(string="Input Schema (JSON)", required=True) + output_schema_json = fields.Text(string="Output Schema (JSON)", required=True) + + @api.model + def default_get(self, fields_list): + res = super().default_get(fields_list) + server_action_id = self.env.context.get("default_server_action_id") + if server_action_id: + server_action = self.env["ir.actions.server"].browse(server_action_id) + res["server_action_id"] = server_action.id + if server_action.ai_tool_id: + res["ai_tool_id"] = server_action.ai_tool_id.id + res["name"] = server_action.ai_tool_id.name + res["description"] = server_action.ai_tool_id.description + res["input_schema_json"] = server_action.ai_tool_id.input_schema_json + res["output_schema_json"] = server_action.ai_tool_id.output_schema_json + else: + res["name"] = server_action.name + + res["input_schema_json"] = ( + "{\n" + ' "type": "object",\n' + ' "properties": {\n' + ' "active_id": {\n' + ' "type": "integer",\n' + ' "description": "Record ID (Required for MCP ' + 'or generic usage)"\n' + " },\n" + ' "active_ids": {\n' + ' "type": "array",\n' + ' "items": {"type": "integer"},\n' + ' "description": "Record IDs (Required for MCP ' + 'or generic usage)"\n' + " }\n" + " }\n" + "}" + ) + + if server_action.state != "code": + res["output_schema_json"] = ( + "{\n" + ' "type": "object",\n' + ' "properties": {\n' + ' "status": {"type": "string"},\n' + ' "message": {"type": "string"}\n' + " }\n" + "}" + ) + else: + res["output_schema_json"] = "{}" + return res + + def action_apply(self): + self.ensure_one() + vals = { + "name": self.name, + "description": self.description, + "input_schema_json": self.input_schema_json, + "output_schema_json": self.output_schema_json, + } + if self.ai_tool_id: + self.ai_tool_id.sudo().write(vals) + else: + vals.update( + { + "kind": "server_action", + "server_action_id": self.server_action_id.id, + } + ) + self.env["ai.tool"].sudo().create(vals) + return {"type": "ir.actions.act_window_close"} diff --git a/ai_tool_server_action/wizard/ai_tool_server_action_wizard_views.xml b/ai_tool_server_action/wizard/ai_tool_server_action_wizard_views.xml new file mode 100644 index 00000000..6963f3ce --- /dev/null +++ b/ai_tool_server_action/wizard/ai_tool_server_action_wizard_views.xml @@ -0,0 +1,40 @@ + + + + ai.tool.server.action.wizard.form + ai.tool.server.action.wizard + +
+ + + + + + + + + + + + + +
+
+
+