27if (!defined(
'NOTOKENRENEWAL')) {
28 define(
'NOTOKENRENEWAL', 1);
30if (!defined(
'NOREQUIREMENU')) {
31 define(
'NOREQUIREMENU', 1);
33if (!defined(
'NOREQUIREHTML')) {
34 define(
'NOREQUIREHTML', 1);
36if (!defined(
'NOREQUIREAJAX')) {
37 define(
'NOREQUIREAJAX', 1);
41if (!defined(
'NOCSRFCHECK')) {
42 define(
'NOCSRFCHECK', 1);
45require
'../../main.inc.php';
46require_once DOL_DOCUMENT_ROOT .
'/ai/class/mcp.class.php';
47require_once DOL_DOCUMENT_ROOT .
'/ai/lib/ai.lib.php';
57if (!$user->hasRight(
'ai',
'assistant',
'use')) {
69 $raw = file_get_contents(
'php://input');
70 $input = json_decode($raw,
true);
72 if (!$input || empty($input[
'tool'])) {
73 throw new Exception(
"Invalid Request: No tool specified.");
81 $tStart = microtime(
true);
82 $result = $mcp->executeTool($input[
'tool'], $input[
'arguments'] ?? []);
90 if (is_array($result) && ($result[
'resultType'] ??
'') ===
'input_required' && !empty($result[
'requestState'])) {
91 $confirmedargs = $input[
'arguments'] ?? [];
92 $confirmedargs[
'requestState'] = $result[
'requestState'];
93 $result = $mcp->executeTool($input[
'tool'], $confirmedargs);
104 if ((array_key_exists(
'success', $result) && empty($result[
'success'])) || !empty($result[
'error'])) {
106 $errorMsg = isset($result[
'error']) ? (string) $result[
'error'] :
'';
111 '[Assistant] '.$input[
'tool'].
' '.
aiTruncateForLog((
string) json_encode($input[
'arguments'] ?? []), 20000),
112 [
'tool' => (
string) $input[
'tool']],
114 microtime(
true) - $tStart,
119 (
string) json_encode($result)
122 echo json_encode($result);
123}
catch (Throwable $e) {
125 http_response_code(400);
126 $toolName = (isset($input) && is_array($input) && !empty($input[
'tool'])) ? (
string) $input[
'tool'] :
'';
130 '[Assistant] '.($toolName !==
'' ? $toolName :
'invalid_request'),
131 [
'tool' => $toolName],
137 isset($raw) && is_string($raw) ? $raw :
'',
140 echo json_encode([
"error" => $e->getMessage()]);
aiTruncateForLog($text, $max=60000)
Trim a payload for the request log, keeping the beginning and the end.
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.
aiCheckCsrfToken($context='')
Check the anti-CSRF token of a request sent to one of the AI Assistant endpoints.
Class to handle MCP (Model Context Protocol).
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
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.