dolibarr 25.0.0-alpha
configure_tools.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2004-2017 Laurent Destailleur <eldy@users.sourceforge.net>
3 * Copyright (C) 2022 Alice Adminson <aadminson@example.com>
4 * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
5 * Copyright (C) 2024 Frédéric France <frederic.france@free.fr>
6 * Coryright (C) 2024 Alexandre Spangaro <alexandre@inovea-conseil.com>
7 * Copyright (C) 2026 Nick Fragoulis
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 3 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY, without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program. If not, see <https://www.gnu.org/licenses/>.
21 */
22
41require '../../main.inc.php';
42
51require_once DOL_DOCUMENT_ROOT . '/core/lib/admin.lib.php';
52require_once DOL_DOCUMENT_ROOT . '/core/class/html.form.class.php';
53require_once DOL_DOCUMENT_ROOT . '/ai/lib/ai.lib.php';
54require_once DOL_DOCUMENT_ROOT . '/ai/class/mcp.class.php';
55require_once DOL_DOCUMENT_ROOT . '/core/lib/functions2.lib.php';
56
57$langs->loadLangs(array('admin', 'other', 'main'));
58
59// Access control
60if (!$user->admin) {
62}
63if (!isModEnabled('ai')) {
64 accessforbidden('Module AI not activated.');
65}
66
67// Parameters
68$action = GETPOST('action', 'aZ09');
69$toolcontext = GETPOST('toolcontext', 'alpha');
70$toolname = GETPOST('toolname', 'alpha');
71$mode = GETPOST('mode', 'alpha');
72$backtopage = GETPOST('backtopage', 'alpha');
73
74// Load unfiltered schema
84function aiToolIsWrite($handler, $name)
85{
86 $tool = $handler->toolsByName[$name] ?? null;
87 if (is_object($tool) && method_exists($tool, 'writeConfirmationPreview') && $tool->writeConfirmationPreview($name, array()) !== McpTool::NO_WRITE) {
88 return true;
89 }
90
91 return (bool) preg_match('/^(create|update|delete|add|remove|change|write|edit|validate|pay|send)/i', $name);
92}
93
94$mcpHandler = new McpHandler($db, $user, $conf, McpHandler::CTX_ASSISTANT);
95$mcpHandler->loadTools();
96
97$unfilteredSchema = $mcpHandler->getToolsSchemaUnfiltered();
98
99// Build grouped lists from the schema metadata set by getToolsSchemaUnfiltered()
100$allDiscoveredTools = array(); // names of all non-system tools
101$groupedNormalTools = array(); // non-system tools grouped by class_name
102$groupedSystemTools = array(); // system tools grouped by class_name
103
104if (!empty($unfilteredSchema) && is_array($unfilteredSchema)) {
105 foreach ($unfilteredSchema as $def) {
106 $name = $def['name'];
107 $isSystem = !empty($def['is_system']);
108 $classNameKey = !empty($def['class_name']) ? (string) $def['class_name'] : 'DefaultTools';
109
110 if (!$isSystem) {
111 $allDiscoveredTools[] = $name;
112 $groupedNormalTools[$classNameKey][] = $def;
113 } else {
114 $groupedSystemTools[$classNameKey][] = $def;
115 }
116 }
117}
118
119$rawAst = getDolGlobalString('AI_ASSISTANT_ALLOWED_TOOLS');
120$rawMcp = getDolGlobalString('AI_MCP_SERVER_ALLOWED_TOOLS');
121// When the chat assistant or the MCP server is disabled, its active switches are dimmed: they have no effect
122$astEnabled = getDolGlobalBool('AI_ASSISTANT_ENABLED');
123$mcpEnabled = getDolGlobalBool('AI_MCP_ENABLED');
124$astAllowed = McpHandler::resolveAllowList($rawAst, $allDiscoveredTools);
125$mcpAllowed = McpHandler::resolveAllowList($rawMcp, $allDiscoveredTools);
126
131if ($action == 'addrights' || $action == 'delrights') {
132 if (GETPOST('token', 'alpha') !== $_SESSION['token']) {
133 accessforbidden('Bad token');
134 }
135
136 if (!empty($toolcontext) && !empty($toolname)) {
137 if ($toolcontext === 'ast') {
138 if ($action == 'addrights') {
139 if (!in_array($toolname, $astAllowed, true)) {
140 $astAllowed[] = $toolname;
141 }
142 } else {
143 $astAllowed = array_values(array_diff($astAllowed, array($toolname)));
144 }
145 $val = empty($astAllowed) ? 'NONE' : implode(',', $astAllowed);
146 dolibarr_set_const($db, 'AI_ASSISTANT_ALLOWED_TOOLS', $val, 'chaine', 0, '', $conf->entity);
147 }
148
149 if ($toolcontext === 'mcp') {
150 if ($action == 'addrights') {
151 if (!in_array($toolname, $mcpAllowed, true)) {
152 $mcpAllowed[] = $toolname;
153 }
154 } else {
155 $mcpAllowed = array_values(array_diff($mcpAllowed, array($toolname)));
156 }
157 $val = empty($mcpAllowed) ? 'NONE' : implode(',', $mcpAllowed);
158 dolibarr_set_const($db, 'AI_MCP_SERVER_ALLOWED_TOOLS', $val, 'chaine', 0, '', $conf->entity);
159 }
160 }
161
162 // Keep page_y (added by the .reposition links) so the scroll position is restored after redirect
163 $page_y = GETPOSTINT('page_y');
164 header('Location: ' . $_SERVER['PHP_SELF'] . ($page_y > 0 ? '?page_y=' . $page_y : ''));
165 exit;
166}
167
168if ($action == 'apply_preset' && !empty($toolcontext) && !empty($mode)) {
169 if (GETPOST('token', 'alpha') !== $_SESSION['token']) {
170 accessforbidden('Bad token');
171 }
172
173 $resultSet = array();
174
175 if ($mode === 'all') {
176 $resultSet = $allDiscoveredTools;
177 } elseif ($mode === 'none') {
178 $resultSet = array();
179 } elseif ($mode === 'readonly') {
180 foreach ($allDiscoveredTools as $tName) {
181 if (!aiToolIsWrite($mcpHandler, $tName)) {
182 $resultSet[] = $tName;
183 }
184 }
185 }
186
187 $val = empty($resultSet) ? 'NONE' : implode(',', $resultSet);
188 $constTarget = ($toolcontext === 'mcp') ? 'AI_MCP_SERVER_ALLOWED_TOOLS' : 'AI_ASSISTANT_ALLOWED_TOOLS';
189 dolibarr_set_const($db, $constTarget, $val, 'chaine', 0, '', $conf->entity);
190
191 header('Location: ' . $_SERVER['PHP_SELF']);
192 exit;
193}
194
195/*
196 * VIEW
197 */
198
200$title = 'AiSetup';
201
202llxHeader('', $langs->trans($title), '', '', 0, 0, array('/ai/js/ai.js'), array(), '', 'mod-ai page-admin');
203
204$linkback = '<a href="' . ($backtopage ? $backtopage : DOL_URL_ROOT . '/admin/modules.php?restore_lastsearch_values=1') . '">' . img_picto($langs->trans("BackToModuleList"), 'back', 'class="pictofixedwidth"') . '<span class="hideonsmartphone">' . $langs->trans("BackToModuleList") . '</span></a>';
205
206print load_fiche_titre($langs->trans($title), $linkback, 'title_setup');
207
208$head = aiAdminPrepareHead();
209print dol_get_fiche_head($head, 'tools', 'MCP Server', -1, 'ai');
210
211print '<!-- Tools quick setup -->';
212print '<div class="info">' . $langs->trans("ToolAccessControlHelp") . '<br>' . $langs->trans("ToolAccessControlHelp2") . '</div>';
213
214print '<div class="marginleftonly" style="display:flex; flex-wrap:wrap; gap:40px; margin-top:15px; padding-top:15px;">';
215
216// Presets For Chat Assistant
217print '<div>';
218print '<strong>' . $langs->trans('PresetsForChatAssistant') . '</strong><br>';
219print '<a class="button" href="' . dolBuildUrl($_SERVER['PHP_SELF'], array('action' => 'apply_preset', 'toolcontext' => 'ast', 'mode' => 'none'), true) . '" style="margin:4px 2px;">' . $langs->trans('None') . '</a>';
220print '<a class="button" href="' . dolBuildUrl($_SERVER['PHP_SELF'], array('action' => 'apply_preset', 'toolcontext' => 'ast', 'mode' => 'readonly'), true) . '" style="margin:4px 2px;">' . $langs->trans('ViewOnly') . '</a>';
221print '<a class="button" href="' . dolBuildUrl($_SERVER['PHP_SELF'], array('action' => 'apply_preset', 'toolcontext' => 'ast', 'mode' => 'all'), true) . '" style="margin:4px 2px;">' . $langs->trans('AllTools') . '</a>';
222print '</div>';
223
224// Presets For MCP Server
225print '<div>';
226print '<strong>' . $langs->trans('PresetsForMcpServer') . '</strong><br>';
227print '<a class="button" href="' . dolBuildUrl($_SERVER['PHP_SELF'], array('action' => 'apply_preset', 'toolcontext' => 'mcp', 'mode' => 'none'), true) . '" style="margin:4px 2px;">' . $langs->trans('None') . '</a>';
228print '<a class="button" href="' . dolBuildUrl($_SERVER['PHP_SELF'], array('action' => 'apply_preset', 'toolcontext' => 'mcp', 'mode' => 'readonly'), true) . '" style="margin:4px 2px;">' . $langs->trans('ViewOnly') . '</a>';
229print '<a class="button" href="' . dolBuildUrl($_SERVER['PHP_SELF'], array('action' => 'apply_preset', 'toolcontext' => 'mcp', 'mode' => 'all'), true) . '" style="margin:4px 2px;">' . $langs->trans('AllTools') . '</a>';
230print '</div>';
231
232print '</div>';
233
234print '<br>';
235
236// Tools table
237print '<div class="div-table-responsive-no-min">';
238print '<table class="noborder centpercent" id="toolsTable">';
239print '<tr class="liste_titre">';
240print '<td class="tdoverflowmax250" style="min-width: 130px;">' . $langs->trans('Tool') . '</td>';
241print '<td class="hideonsmartphone">' . $langs->trans('ToolDescription') . '</td>';
242print '<td class="center" style="min-width: 60px;">' . $langs->trans('ToolActionType') . '</td>';
243print '<td class="center nowraponall">' . $langs->trans('ChatAssistant') . '</td>';
244print '<td class="center nowraponall">' . $langs->trans('McpServer') . '</td>';
245print '</tr>';
246
247if (empty($groupedNormalTools) && empty($groupedSystemTools)) {
248 print '<tr class="oddeven"><td colspan="5" class="opacitymedium">' . $langs->trans('NoMcpToolsDiscovered') . '</td></tr>';
249} else {
250 $groupId = 0;
251 $finalGroupsList = array_merge($groupedNormalTools, $groupedSystemTools);
252
253 foreach ($finalGroupsList as $categoryName => $definitions) {
254 $groupId++;
255
256 print '<tr class="trgroup trforbreaknobg" data-group="group-' . $groupId . '">';
257 print '<td colspan="5" class="mcp-trigger-collapse" style="cursor:pointer;">';
258 print '<span class="toggle-icon">▼</span> ' . dol_escape_htmltag($categoryName);
259 print '</td>';
260 print '</tr>';
261
262 foreach ($definitions as $def) {
263 $name = $def['name'];
264 $desc = !empty($def['description']) ? $def['description'] : '-';
265 $isSystem = !empty($def['is_system']);
266
267 $isAstOn = $isSystem ? true : in_array($name, $astAllowed, true);
268 $isMcpOn = $isSystem ? true : in_array($name, $mcpAllowed, true);
269
270 if (aiToolIsWrite($mcpHandler, $name)) {
271 $type = 'write';
272 $typeBadge = '<span class="badge badge-status2" style="display: inline-block;">' . $langs->trans('Modify') . '</span>';
273 } else {
274 $type = 'read';
275 $typeBadge = '<span class="badge badge-status4" style="display: inline-block;">' . $langs->trans('ViewOnly') . '</span>';
276 }
277
278 print '<tr class="oddeven group-' . $groupId . '" data-tool-name="' . dol_escape_htmltag($name) . '" data-tool-type="' . $type . '">';
279
280 // Tool
281 print '<td style="padding-left:20px; min-width: 130px; word-break: break-all;" class="tdoverflowmax250">';
282 print '<strong>' . dol_escape_htmltag($name) . '</strong>';
283 if ($isSystem) {
284 print '<br><span class="badgeneutral">' . $langs->trans('System') . '</span>';
285 }
286 print '</td>';
287
288 // Tool Description (hidden on mobile)
289 print '<td class="small opacitymedium hideonsmartphone">' . dol_escape_htmltag($desc) . '</td>';
290
291 // Type Badge
292 print '<td class="center">' . $typeBadge . '</td>';
293
294
295 $lockCssClass = $isSystem ? ' opacitymedium disabled' : '';
296
297 // Chat Assistant Switch
298 print '<td class="center nowraponall">';
299 if ($isSystem) {
300 print img_picto($langs->trans('Active'), 'switch_on', '', 0, 0, 0, '', 'opacitymedium');
301 } else {
302 $actAst = $isAstOn ? 'delrights' : 'addrights';
303 $pictoAst = $isAstOn ? 'switch_on'.($type == 'write' ? '_warning' : '') : 'switch_off';
304 $urlAst = dolBuildUrl($_SERVER["PHP_SELF"], [
305 'action' => $actAst,
306 'toolcontext' => 'ast',
307 'toolname' => $name
308 ], true);
309
310 print '<a class="ctx-ast-link reposition' . $lockCssClass . (($isAstOn && !$astEnabled) ? ' opacitymedium' : '') . '" href="' . $urlAst . '">';
311 print img_picto($langs->trans($isAstOn ? 'Remove' : 'Add'), $pictoAst, '', 0, 0, 0, '', !$isAstOn ? 'font-status6' : ($type == 'write' ? 'font-status2' : 'font-status4'));
312 print '</a>';
313 }
314 print '</td>';
315
316 // MCP Server Switch
317 print '<td class="center nowraponall">';
318 if ($isSystem) {
319 print img_picto($langs->trans('Active'), 'switch_on', '', 0, 0, 0, '', 'opacitymedium');
320 } else {
321 $actMcp = $isMcpOn ? 'delrights' : 'addrights';
322 $pictoMcp = $isMcpOn ? 'switch_on'.($type == 'write' ? '_warning' : '') : 'switch_off';
323 $urlMcp = dolBuildUrl($_SERVER["PHP_SELF"], [
324 'action' => $actMcp,
325 'toolcontext' => 'mcp',
326 'toolname' => $name
327 ], true);
328
329 print '<a class="ctx-mcp-link reposition' . $lockCssClass . (($isMcpOn && !$mcpEnabled) ? ' opacitymedium' : '') . '" href="' . $urlMcp . '">';
330 print img_picto($langs->trans($isMcpOn ? 'Remove' : 'Add'), $pictoMcp, '', 0, 0, 0, '', !$isMcpOn ? 'font-status6' : ($type == 'write' ? 'font-status2' : 'font-status4'));
331 print '</a>';
332 }
333 print '</td>';
334
335 print '</tr>' . "\n";
336 }
337 }
338}
339
340print '</table>';
341print '</div>';
342
343print dol_get_fiche_end();
344
345llxFooter();
346$db->close();
dolibarr_set_const($db, $name, $value, $type='chaine', $visible=0, $note='', $entity=1)
Insert a parameter (key,value) into database (delete old key then insert it again).
aiAdminPrepareHead()
Prepare admin pages header.
Definition ai.lib.php:548
llxFooter($comment='', $zone='private', $disabledoutputofmessages=0)
Empty footer.
Definition wrapper.php:91
if(!defined('NOREQUIRESOC')) if(!defined( 'NOREQUIRETRAN')) if(!defined('NOTOKENRENEWAL')) if(!defined( 'NOREQUIREMENU')) if(!defined('NOREQUIREHTML')) if(!defined( 'NOREQUIREAJAX')) llxHeader($head='', $title='', $help_url='', $target='', $disablejs=0, $disablehead=0, $arrayofjs='', $arrayofcss='', $morequerystring='', $morecssonbody='', $replacemainareaby='', $disablenofollow=0, $disablenoindex=0)
Empty header.
Definition wrapper.php:73
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
static resolveAllowList($raw, $allDiscoveredTools)
Resolves a raw allow-list constant value into an explicit PHP array of tool names.
const NO_WRITE
Returned by writeConfirmationPreview() when the tool writes nothing.
aiToolIsWrite($handler, $name)
Whether a tool writes.
if( $action=='addrights'||$action=='delrights') if($action=='apply_preset' &&!empty($toolcontext) &&!empty($mode) $help_url)
ACTIONS.
dolBuildUrl($url, $params=[], $addtoken=false, $anchor='')
Return path of url.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0, $nodefault=0)
Return value of a param into GET or POST supervariable.
GETPOSTINT($paramname, $method=0, $nodefault=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
getDolGlobalBool($key, $default=false)
Return a Dolibarr global constant boolean value.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
dol_get_fiche_head($links=array(), $active='', $title='', $notab=0, $picto='', $pictoisfullpath=0, $morehtmlright='', $morecss='', $limittoshow=0, $moretabssuffix='', $dragdropfile=0, $morecssdiv='')
Show tabs of a record.
Definition html.lib.php:542
dol_get_fiche_end($notab=0)
Return tab footer of a card.
Definition html.lib.php:740
load_fiche_titre($title, $morehtmlright='', $picto='generic', $pictoisfullpath=0, $id='', $morecssontable='', $morehtmlcenter='', $morecssonpicto='widthpictotitle')
Load a title with picto.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Definition html.lib.php:183
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.