dolibarr 25.0.0-alpha
execute_tool.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2026 Laurent Destailleur <eldy@users.sourceforge.net>
3 * Copyright (C) 2026 Nick Fragoulis
4 * Copyright (C) 2026 Anthony Damhet <a.damhet@progiseize.fr>
5 * Copyright (C) 2026 Jose Martinez <jose.martinez@pichinov.com>
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
19 */
20
27if (!defined('NOTOKENRENEWAL')) {
28 define('NOTOKENRENEWAL', 1);
29}
30if (!defined('NOREQUIREMENU')) {
31 define('NOREQUIREMENU', 1);
32}
33if (!defined('NOREQUIREHTML')) {
34 define('NOREQUIREHTML', 1);
35}
36if (!defined('NOREQUIREAJAX')) {
37 define('NOREQUIREAJAX', 1);
38}
39// The payload is read from the raw php://input body, so the CSRF token cannot be checked by
40// main.inc.php. It is checked explicitly below by aiCheckCsrfToken().
41if (!defined('NOCSRFCHECK')) {
42 define('NOCSRFCHECK', 1);
43}
44
45require '../../main.inc.php';
46require_once DOL_DOCUMENT_ROOT . '/ai/class/mcp.class.php';
47require_once DOL_DOCUMENT_ROOT . '/ai/lib/ai.lib.php';
48
49// Security check
50if (!isModEnabled('ai') || !getDolGlobalString('AI_ASSISTANT_ENABLED')) {
51 accessforbidden('Module or feature not allowed');
52}
53
54global $db, $user, $conf;
55
56// Per-user gate: same right as the assistant page and parse_intent.php
57if (!$user->hasRight('ai', 'assistant', 'use')) {
59}
60
61// This endpoint creates, updates and deletes documents, so it must not be reachable from
62// another site. Must stay after the login is done by main.inc.php (the session is needed).
63aiCheckCsrfToken('ai/assistant/execute_tool.php');
64
65
66
67/*
68 * View
69 */
70
71if (getDolGlobalString("AI_DEBUG")) {
72 dol_syslog("execute_tool.php ***** BEGIN", LOG_INFO, 0, '_ai');
73}
74
75top_httphead('application/json');
76
77
78try {
79 $raw = file_get_contents('php://input');
80 $input = json_decode($raw, true);
81
82 if (!$input || empty($input['tool'])) {
83 throw new Exception("Invalid Request: No tool specified.");
84 }
85
86 // Initialize Handler with the private assistant context so that the correct
87 // allow-list (AI_ASSISTANT_ALLOWED_TOOLS) is enforced on both schema and execution.
88 $mcp = new McpHandler($db, $user, $conf, McpHandler::CTX_ASSISTANT);
89 $mcp->loadTools();
90
91 $tStart = microtime(true);
92
93 if (getDolGlobalString("AI_DEBUG")) {
94 dol_syslog("execute_tool.php tool = ".$input['tool'].", arguments = ".json_encode($input['arguments'] ?? []), LOG_DEBUG, 0, '_ai');
95 }
96
97 $result = $mcp->executeTool($input['tool'], $input['arguments'] ?? []);
98
99 // This endpoint runs the executions the user confirmed - the calls that actually
100 // create, update or delete data - so they must land in the audit table just like
101 // the parse rounds (parse_intent.php) and the MCP server calls already do.
102 $status = 'Success';
103 $errorMsg = '';
104 // Two failure conventions coexist: the write tools return success=false,
105 // everything else (missing record, unknown tool, bridge error, rights
106 // refusal) returns a bare non-empty 'error' key - both must log as Error.
107 if ((array_key_exists('success', $result) && empty($result['success'])) || !empty($result['error'])) {
108 $status = 'Error';
109 $errorMsg = isset($result['error']) ? (string) $result['error'] : '';
110 }
111 // A write answers its first call with a confirmation request, which is not an
112 // execution: log it as a confirmation, as parse_intent.php does, not as a success.
113 if (is_array($result) && ($result['resultType'] ?? '') === 'input_required') {
114 $status = 'Confirm';
115 }
117 $db,
118 $user,
119 '[Assistant] '.$input['tool'].' '.aiTruncateForLog((string) json_encode($input['arguments'] ?? []), 20000),
120 ['tool' => (string) $input['tool']],
121 'assistant',
122 microtime(true) - $tStart,
123 1.0,
124 $status,
125 $errorMsg,
126 $raw,
127 (string) json_encode($result)
128 );
129
130 if (getDolGlobalString("AI_DEBUG")) {
131 dol_syslog("execute_tool.php answer = ".var_export($result, true), LOG_DEBUG, 0, '_ai');
132 dol_syslog("execute_tool.php answer = ".count($result)." lines", LOG_INFO, 0, '_ai');
133 }
134
135 echo json_encode($result);
136} catch (Throwable $e) {
137 // Set HTTP response code to error (400 Bad Request)
138 http_response_code(400);
139 $toolName = (isset($input) && is_array($input) && !empty($input['tool'])) ? (string) $input['tool'] : '';
141 $db,
142 $user,
143 '[Assistant] '.($toolName !== '' ? $toolName : 'invalid_request'),
144 ['tool' => $toolName],
145 'assistant',
146 0.0,
147 0.0,
148 'Error',
149 $e->getMessage(),
150 isset($raw) && is_string($raw) ? $raw : '',
151 ''
152 );
153 echo json_encode(["error" => $e->getMessage()]);
154}
aiTruncateForLog($text, $max=60000)
Trim a payload for the request log, keeping the beginning and the end.
Definition ai.lib.php:383
ai_log_request($db, $user, $query, array $response, $provider, float $time, float $confidence, $status, $error='', $rawReq='', $rawRes='', array $context=array(), &$logId=null)
Log AI Request with Raw Payloads.
Definition ai.lib.php:416
aiCheckCsrfToken($context='')
Check the anti-CSRF token of a request sent to one of the AI Assistant endpoints.
Definition ai.lib.php:1260
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
Class to handle MCP (Model Context Protocol).
Definition mcp.class.php:40
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
if(!defined( 'NOREQUIREMENU')) if(!empty(GETPOST('seteventmessages', 'alpha'))) if(!function_exists("llxHeader")) top_httphead($contenttype='text/html', $forcenocache=0)
Show HTTP header.
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.