|
dolibarr 25.0.0-alpha
|
Class ToolApiBridge. More...


Public Member Functions | |
| __construct ($db, $user=null, $conf=null) | |
| Constructor. | |
| getDefinitions () | |
| Returns tool definitions derived from the enabled REST API endpoints. | |
| purgeDefsCache () | |
| Delete every bridge_tooldefs_*.json cache file of the ai temp directories (current entity and the other ones), so the tool definitions are rebuilt from scratch on the next request. | |
| getRequiredRights (string $toolName) | |
| Rights are enforced by the REST API classes themselves. | |
| writeConfirmationPreview (string $toolName, array $args) | |
| Preview of what a bridge write would do, for the confirmation gate. | |
| writePrecheck (string $toolName, array $args) | |
| Refuse, before any confirmation, a write that could only fail, so the user is never asked to approve it: | |
| getCategories () | |
| Return categories this tool belongs to. | |
| execute (string $name, array $args) | |
| Execute a bridged tool: authenticate the acting user, call the API method in-process with positional arguments, catch RestException. | |
| toolRoute (string $name) | |
| Endpoint and method a bridge tool calls, for a page that shows the tool to a person (the palette of the chat) under a plain name. | |
Public Member Functions inherited from McpTool | |
| isSystem () | |
| Return true if this is a system/infrastructure tool that must always remain visible and executable regardless of the admin allow-list. | |
Public Attributes | |
| const | ENDPOINT_CATEGORIES |
| Endpoint key -> intent categories of the assistant's query classifier (classifyIntentUniversal() in parse_intent.php: billing, commercial, thirdparty, stock, project, reporting). | |
| const | BRIDGE_DEFAULT_LIMIT = 25 |
| Default and ceiling applied to list 'limit' parameters when called through the bridge. | |
Public Attributes inherited from McpTool | |
| const | RIGHTS_UNDECLARED = 'undeclared' |
| Default of getRequiredRights(): the class never declared anything, deny. | |
| const | NO_WRITE = '' |
| Returned by writeConfirmationPreview() when the tool writes nothing. | |
Protected Member Functions | |
| fetchBusinessObject ($class, $id, $ref='') | |
| Load a business record of one of the classes the writes declare. | |
| canAccessWriteObject (array $access, $id) | |
| Check object visibility with the same resource arguments as REST. | |
| canWriteProject ($project) | |
| Apply native project write authorization, not merely read-all visibility. | |
Private Member Functions | |
| loadExternalEnrichments () | |
| Merge endpoint enrichments declared by external modules through the 'addMcpApiBridgeEnrichments' hook (aimcp context). | |
| addReadEndpoints () | |
| Read-only tools the whitelist did not reach yet: new endpoints (bank, donations, leave, manufacturing, lots, knowledge base, member types, partnerships, workstations, taxes, currencies, contacts) and the read methods of endpoints already exposed (stock per warehouse, prices, time spent, contacts of a document, discounts, tags...). | |
| addLineMethod ($label, $lookupTool, $class, array $right, $buy=false, array $rename=array(), array $defaults=array()) | |
| Enrichment of the postLine method of a document (order, proposal, invoice, and their supplier counterparts): add ONE line to an existing draft. | |
| addWritesOnExistingRecords () | |
| Writes on records that already exist, and the creates that need more than a third party and lines: edits, validation, payment, deletion of drafts, contacts, interventions, contracts, projects and tasks. | |
| setupValue ($name) | |
| A setup constant read while the tools are declared. | |
| resetWriteState () | |
| Forget what the previous normaliseWriteArgs() call found, so a problem of one call is never reported for the next one. | |
| updateMethod ($label, $class, array $right, array $fields, $lookup) | |
| Enrichment of the put method of a record: change some of its fields. | |
| validateMethod ($label, $class, $preview, array $right, array $fixed, $stockconst) | |
| Enrichment of the validate method of a document. | |
| deleteMethod ($label, $class, array $right) | |
| Enrichment of the delete method of a document, for its drafts only. | |
| lineMethod ($action, $label, $class, array $right, $profile) | |
| Enrichment of a line method of a draft document: change, delete or, for an intervention, add one line. | |
| headerUpdateMethod ($label, $class, array $right, array $readright, array $access, $extrafields, array $fields) | |
| Enrichment of the put method of a document header: the listed fields of a draft, confirmed with their old and new value. | |
| projectUpdateMethod () | |
| Describe bounded edits of an existing project. | |
| loadApiRuntime () | |
| Load the REST API runtime (Restler autoloader + DolibarrApi base classes), mirroring the bootstrap sequence of htdocs/api/index.php, so that the endpoint classes (which extend DolibarrApi and throw RestException) can be loaded and executed outside the Restler HTTP runtime. | |
| discoverEndpoints () | |
| Discover the REST API endpoints of every enabled module. | |
| resolveEndpointClass (string $key) | |
| Load an endpoint's api file and resolve its real class name (lazy, cached in $this->endpoints). | |
| defaultMethods () | |
| Methods exposed for an endpoint carrying no hand-written entry. | |
| toolGroups () | |
| Groups of tools to build: enrichment key => key of the discovered endpoint whose REST class it calls. | |
| applyFixedParams (string $toolName, array $args) | |
| Arguments a tool forces on its call ('fixed_params' of its enrichment), whatever the caller sent: the documents area of a group of documents tools. | |
| applyMethodRestriction (array $methods) | |
| Apply the AI_MCP_API_BRIDGE_METHODS restriction. | |
| setupAllows (array $consts) | |
| Whether one of these setup constants is on. | |
| defsCacheFile () | |
| Path of the definitions cache file for the CURRENT state, or '' when no writable temp directory exists. | |
| writeDefsCache (string $cachefile) | |
| Persist the generated definitions/routes/endpoints, pruning cache files of previous states so stale signatures do not pile up. | |
| buildToolDefinition (array $ep, string $key, string $method, string $toolname, array $meta=[]) | |
| Build one MCP tool definition from an API class method: reflection + docblock give the skeleton, then the hand-written per-method enrichment is merged over it ('description' appended, 'params' overriding parameter docs, shared common docs as last fallback). | |
| liftInlineTags ($desc, string $ptype, array &$constraints) | |
| Lift Restler's inline validation tags out of a parameter description. | |
| tagValueToNumber (string $value) | |
| Convert a numeric tag value to the PHP number JSON encodes as a number. | |
| restlerPatternToJsonSchema (string $value) | |
| Convert a Restler {@pattern} value to a JSON Schema pattern. | |
| docTypeToJson (string $type) | |
| Convert a docblock type to a JSON Schema type. | |
| defaultVatRate ($socid, $fk_product, $buy=false) | |
| VAT rate core would apply to a line, when the caller gave none. | |
| defaultBuyPrice ($prod, $socid, $qty) | |
| Unit purchase price of a product, for a supplier document line given by product ref: the sale price would be wrong there. | |
| refOfCreatedObject ($class, $id) | |
| Ref of a record just created, for the confirmation shown to the user. | |
| previewObjectName ($class, $id) | |
| A record linked by a header field, as the confirmation names it: its ref and label, or null (as the other fields print it) when the field is empty. | |
| fetchWriteParent (array $write, array $args) | |
| Record a line write goes into, for a write declaring a 'parent'. | |
| updateInputSchema (array $write) | |
| Schema of a partial update declared by an endpoint's write metadata. | |
| validateProjectUpdate (array $args, $parent) | |
| Check resulting dates, project write access and native update side effects. | |
| normaliseUpdateArgs (array $args, array $write) | |
| Normalise and validate partial updates without creation defaults. | |
| unitIdFromName ($name) | |
| Unit id from the word a user used for it: code, short label or label, in the user's language, singular or plural ("piece", "pieces", "pcs"). | |
| normaliseWriteArgs (array $args, array $write=array()) | |
| Normalise the arguments of a write before they are previewed or executed. | |
| normaliseWriteLine (array $line, $socid, $buy=false, $kind='', $defaultWarehouse=0) | |
| Normalise one document line: field names, product given by ref or label, default VAT rate. | |
| writeDate ($field, $value, $gmt=1) | |
| A date written as text, as a timestamp. | |
| previewLogisticLines (array $lines, $kind) | |
| The lines of a reception or shipment as the confirmation lists them: quantity, product, and for a reception the warehouse and the cost. | |
| defaultWarehouseId () | |
| Warehouse a logistic line goes to when none is named: the user's default warehouse, else the one set up for the company, else the only active one. | |
| previewValue (array $write, $argname, $value, array $args) | |
| One value of a confirmation sentence, the way the user knows it: the record an id stands for, hours rather than the seconds the API takes, a date as a date. | |
| closeProductRefs ($wanted, $socid) | |
| References close to one that matched no product, for the user to pick from: the supplier's references when the document is a supplier one (the note says "33303", the catalogue has "33303-6"), else our own references. | |
| unresolvedProductsMessage () | |
| Message refusing a write whose products could not be resolved, with the close references found for each, so the user (or the model) can pick one. | |
| fetchRecord ($class, $id, $ref='') | |
| Record of a write on an existing record, by rowid or by ref: the business documents of fetchBusinessObject() and the records only these writes use (contacts, projects, tasks, interventions, contracts, tickets). | |
| resolveWriteTarget (array $write, $value) | |
| Record a targeted write is about, from the id or the words the model sent. | |
| userCanReach ($class, $id) | |
| Whether the acting user may reach a record, with the same check the REST class makes before touching it (sales representative restriction, entity). | |
| socidOf ($obj) | |
| Third party of a record, 0 for a record that has none (product, third party). | |
| describeRecord ($obj) | |
| Short description of a document for a confirmation: ref, third party, amount. | |
| resolveWarehouse ($value) | |
| Open warehouse from the words of the user, or the only one there is. | |
| resolveBankAccount ($value) | |
| Open bank account from the words of the user, or the only one there is. | |
| resolvePaymentMode ($value) | |
| Active payment mode from the words of the user: its code, its label in the dictionary or in the user's language, or the usual words for it. | |
| pickOne (array $list, $value, array $names, $askKey, $missingKey, $noneKey, $onlyOne=true) | |
| One entry of a short list from what the user said: its rowid, one of its names said in full, else the only entry whose name contains the words. | |
| normaliseOneRecordArgs (array $args, array $write) | |
| Arguments of a write on one existing record that is not a targeted write (a ticket reply, a ticket or task edit, a ticket contact): the record given by rowid or ref is found here, with the user's access, so a ref works as the id and an unknown record is refused before the confirmation. | |
| normaliseTargetArgs (array $args, array $write) | |
| Arguments of a write on an existing record (update, validation, deletion, payment): the record found from what the user said, and only what the REST method may receive. | |
| normaliseLineArgs (array $args, array $write, array $out) | |
| Arguments of a line write on a draft: the line found from what the user said, and the full body the REST method needs, its unchanged values kept. | |
| linesSummary ($doc) | |
| Lines of a document, as a numbered list for a message: position, product, quantity. | |
| lineName ($l) | |
| A line as the user knows it: product ref and label, else its text. | |
| validationMovesStock (array $write, $obj) | |
| Whether validating this document moves stock, so a warehouse is needed. | |
| normaliseCreateExtras (array $args, array $write) | |
| Arguments of a create that names a project, or gives dates or hours. | |
| previewTargetWrite (array $write, array $args) | |
| Confirmation sentence of a write on an existing record. | |
| previewLineWrite (array $write, $what) | |
| Confirmation sentence of a line write: the line by its position and product, each change from its old to its new value, and the new line total. | |
| unitLabel ($id) | |
| Label of a unit, as the user reads it. | |
| precheckTargetWrite (array $write, array $args) | |
| Why a write on an existing record cannot run, or '' when it can. | |
| writeMetaFor ($toolName) | |
| The 'write' enrichment of a tool, when it has one. | |
| methodMetaFor ($toolName) | |
| Find the enrichment of the method a tool name maps to. | |
| resolveUserSentinels (array $args) | |
| Resolve 'me' sent as an argument value on user-referencing fields. | |
| extrafieldsElementForEndpoint ($key) | |
| Map a bridge endpoint key to the element type ExtraFields uses. | |
| projectDocumentList ($output, $modulepart) | |
| Keep what the chat shows of a file list: name, size, date and a link. | |
| projectDirectoryList ($output, $modulepart) | |
| Keep what the chat shows of the content of a directory: type, name, path, size, date, and a link for a file. | |
| documentObjectExists (array $args) | |
| Whether the object a file list was asked for exists. | |
| shapeReadOutput (array $output, array $meta) | |
| Shape a read result as its enrichment asks: drop the fields that must not leave the server, and cap a list the REST method returns unbounded. | |
| addCreatorContact ($class, $id, $code) | |
| Link the acting user to a record just created, with the role the card gives its creator (the leader of a project). | |
Additional Inherited Members | |
Static Public Member Functions inherited from McpTool | |
| static | normalizeInputSchema (array $schema) |
| Normalize a tool input schema to ensure broad compatibility with LLM function-calling APIs (e.g. | |
Class ToolApiBridge.
Exposes enabled REST API endpoints as MCP tools (read-only POC).
Definition at line 67 of file api_bridge.class.php.
| ToolApiBridge::__construct | ( | $db, | |
| $user = null, | |||
| $conf = null ) |
Constructor.
| DoliDB | $db | Database handler |
| User | null | $user | Acting user provided by McpHandler (the caller; tool calls run with this user's rights) |
| Conf | null | $conf | Dolibarr config (optional) |
Reimplemented from McpTool.
Definition at line 238 of file api_bridge.class.php.
References addLineMethod(), addReadEndpoints(), addWritesOnExistingRecords(), conf(), loadExternalEnrichments(), projectUpdateMethod(), and user.
|
private |
Link the acting user to a record just created, with the role the card gives its creator (the leader of a project).
A role missing from the dictionary is logged, not fatal: the record exists, as on the card.
| string | $class | Business class of the record. |
| int | $id | Rowid of the record. |
| string | $code | Internal contact type code. |
Definition at line 6035 of file api_bridge.class.php.
References $id, dol_syslog(), and user.
|
private |
Enrichment of the postLine method of a document (order, proposal, invoice, and their supplier counterparts): add ONE line to an existing draft.
| string | $label | Document name, as the model reads it (e.g. 'sale order'). |
| string | $lookupTool | Tool to find the rowid when only the ref is known. |
| string | $class | Business class of the document. |
| string[] | $right | Right needed to write. |
| bool | $buy | True for a supplier document: purchase price and VAT. |
| array<string,string> | $rename Line fields the REST endpoint names differently. | |
| array<string,mixed> | $defaults Line fields always sent, unless given. |
Definition at line 2096 of file api_bridge.class.php.
Referenced by __construct(), and addWritesOnExistingRecords().
|
private |
Read-only tools the whitelist did not reach yet: new endpoints (bank, donations, leave, manufacturing, lots, knowledge base, member types, partnerships, workstations, taxes, currencies, contacts) and the read methods of endpoints already exposed (stock per warehouse, prices, time spent, contacts of a document, discounts, tags...).
Each REST class checks its own read right. Salaries, recruitment candidates and event attendees stay out: they are personal data about people.
Definition at line 1524 of file api_bridge.class.php.
Referenced by __construct().
|
private |
Writes on records that already exist, and the creates that need more than a third party and lines: edits, validation, payment, deletion of drafts, contacts, interventions, contracts, projects and tasks.
Each one is a whitelisted REST method with its own preview and precheck, behind the same confirmation as the other writes.
Definition at line 2144 of file api_bridge.class.php.
References addLineMethod(), deleteMethod(), getDolGlobalInt(), headerUpdateMethod(), isModEnabled(), lineMethod(), setupValue(), updateMethod(), and validateMethod().
Referenced by __construct().
|
private |
Arguments a tool forces on its call ('fixed_params' of its enrichment), whatever the caller sent: the documents area of a group of documents tools.
| string | $toolName | Tool name. |
| array<string,mixed> | $args Tool arguments as sent. |
Definition at line 2895 of file api_bridge.class.php.
References methodMetaFor().
Referenced by writeConfirmationPreview(), and writePrecheck().
|
private |
Apply the AI_MCP_API_BRIDGE_METHODS restriction.
Intersection only: the constant can narrow what the whitelist exposes — on every endpoint, enriched or not — but can never add a method to it, so it can never turn on a write method behind the whitelist's back.
| array<string,array{suffix?:string,description?:string,params?:array<string,string>}> | $methods Whitelisted methods |
Definition at line 2914 of file api_bridge.class.php.
References getDolGlobalString().
Referenced by getDefinitions().
|
private |
Build one MCP tool definition from an API class method: reflection + docblock give the skeleton, then the hand-written per-method enrichment is merged over it ('description' appended, 'params' overriding parameter docs, shared common docs as last fallback).
| array{module:string,path:string,class:string,label:string} | $ep Endpoint entry | |
| string | $key | Endpoint key (e.g. 'thirdparties') |
| string | $method | Whitelisted API method name (e.g. 'index', 'get') |
| string | $toolname | Generated tool name |
| array{suffix?:string,description?:string,params?:array<string,string>} | $meta Hand-written enrichment for this method |
Definition at line 3162 of file api_bridge.class.php.
References docTypeToJson(), liftInlineTags(), McpTool\normalizeInputSchema(), and updateInputSchema().
Referenced by getDefinitions().
|
protected |
Check object visibility with the same resource arguments as REST.
| array<int,string> | $access Resource, table and subfeature | |
| int | $id | Object ID |
Definition at line 3676 of file api_bridge.class.php.
References $id, checkUserAccessToObject(), and user.
Referenced by normaliseUpdateArgs(), and validateProjectUpdate().
|
protected |
Apply native project write authorization, not merely read-all visibility.
Definition at line 3687 of file api_bridge.class.php.
References user.
|
private |
References close to one that matched no product, for the user to pick from: the supplier's references when the document is a supplier one (the note says "33303", the catalogue has "33303-6"), else our own references.
| string | $wanted | Reference as written on the document. |
| int | $socid | Supplier whose catalogue is searched, 0 for a customer document. |
Definition at line 4664 of file api_bridge.class.php.
References dol_strlen(), and dol_trunc().
Referenced by normaliseWriteLine().
|
private |
Unit purchase price of a product, for a supplier document line given by product ref: the sale price would be wrong there.
| Product | $prod | Product of the line. |
| int | $socid | Supplier of the document, 0 if unknown. |
| float | $qty | Quantity of the line, for the price by quantity. |
Definition at line 3540 of file api_bridge.class.php.
Referenced by normaliseWriteLine().
|
private |
Methods exposed for an endpoint carrying no hand-written entry.
Deliberately the read-only pair, per the review that merged this bridge ("we must start with only few methods exposed"). Discovery widens which endpoints are reachable, never what may be done to them: a write method still has to be whitelisted consciously, behind a confirmation gate.
Definition at line 2860 of file api_bridge.class.php.
Referenced by getDefinitions(), and loadExternalEnrichments().
|
private |
VAT rate core would apply to a line, when the caller gave none.
| int | $socid | Third party of the document. |
| int | $fk_product | Product of the line, 0 for a free line. |
| bool | $buy | True for a supplier document: the third party sells to us. |
Definition at line 3518 of file api_bridge.class.php.
References $mysoc, and get_default_tva().
Referenced by normaliseWriteLine().
|
private |
Warehouse a logistic line goes to when none is named: the user's default warehouse, else the one set up for the company, else the only active one.
Definition at line 4266 of file api_bridge.class.php.
References getDolGlobalInt(), getEntity(), and user.
Referenced by normaliseWriteLine().
|
private |
Path of the definitions cache file for the CURRENT state, or '' when no writable temp directory exists.
The state signature is part of the file name, so any relevant change - a module (de)activated, a Dolibarr upgrade, another entity, an edit of this file (which holds the enrichments), or a change of the DB-driven restrictions (AI_MCP_API_BRIDGE_METHODS) - simply points to a different file: no explicit invalidation hook to maintain, and an administrator RESTRICTING what the AI may reach takes effect on the very next request (review sonikf). External-module API updates that change none of these are covered by the TTL.
Definition at line 3046 of file api_bridge.class.php.
References $conf, dol_mkdir(), and getDolGlobalString().
Referenced by getDefinitions().
|
private |
Enrichment of the delete method of a document, for its drafts only.
| string | $label | Document name, as the model reads it. |
| string | $class | Business class of the document. |
| string[] | $right | Right needed to delete. |
Definition at line 2533 of file api_bridge.class.php.
Referenced by addWritesOnExistingRecords().
|
private |
Short description of a document for a confirmation: ref, third party, amount.
| CommonObject | $obj | Record. |
Definition at line 4883 of file api_bridge.class.php.
References $conf, price(), and socidOf().
Referenced by previewTargetWrite(), and previewValue().
|
private |
Discover the REST API endpoints of every enabled module.
Mirrors the scan htdocs/api/index.php performs to register endpoints with Restler, so the bridge exposes exactly the API surface the REST layer exposes — external modules included — instead of a list maintained by hand.
The walk is the same in both places: dolGetModulesDirs() gives the module directories, each mod*.class.php names a module, getModuleDirForApiClass() maps it to the directory holding its API classes, and every api_<key>.class.php there is one endpoint. A few modules are named differently in their descriptor and in isModEnabled(); those exceptions are copied from api/index.php rather than reinvented, so the two stay in step.
Note the class name is resolved through class_exists(), which is case-insensitive in PHP: api_agendaevents.class.php yields the candidate "Agendaevents" and still matches the declared AgendaEvents. Reflection is then used to recover the real spelling for display.
Definition at line 2735 of file api_bridge.class.php.
References $module, dol_buildpath(), dol_osencode(), dolGetModulesDirs(), getModuleDirForApiClass(), and isModEnabled().
Referenced by getDefinitions().
|
private |
Convert a docblock type to a JSON Schema type.
| string | $type | Docblock type (may be a union like int|string) |
Definition at line 3449 of file api_bridge.class.php.
Referenced by buildToolDefinition().
|
private |
Whether the object a file list was asked for exists.
| array<string,mixed> | $args Tool arguments (modulepart, id, ref) |
Definition at line 5973 of file api_bridge.class.php.
References $object.
| ToolApiBridge::execute | ( | string | $name, |
| array | $args ) |
Execute a bridged tool: authenticate the acting user, call the API method in-process with positional arguments, catch RestException.
| string | $name | The tool name (e.g. 'api_thirdparties_list'). |
| array<string,mixed> | $args The tool arguments (named). |
Reimplemented from McpTool.
Definition at line 6055 of file api_bridge.class.php.
References aiStripPersonalExtrafields(), dol_now(), dol_syslog(), dol_trunc(), and user.
|
private |
Map a bridge endpoint key to the element type ExtraFields uses.
| string | $key | Endpoint key from the enrichment map. |
Definition at line 5854 of file api_bridge.class.php.
|
protected |
Load a business record of one of the classes the writes declare.
| string | $class | Business class declared by the write. |
| int | $id | Rowid of the record. |
| string | $ref | Exact reference when no rowid was supplied. |
Definition at line 3559 of file api_bridge.class.php.
References $id.
Referenced by fetchWriteParent(), normaliseWriteLine(), previewLogisticLines(), previewObjectName(), and writeConfirmationPreview().
|
private |
Record of a write on an existing record, by rowid or by ref: the business documents of fetchBusinessObject() and the records only these writes use (contacts, projects, tasks, interventions, contracts, tickets).
| string | $class | Business class declared by the write. |
| int | $id | Rowid of the record, 0 to look it up by ref. |
| string | $ref | Ref of the record, used when no rowid is given. |
Definition at line 4735 of file api_bridge.class.php.
References $id.
Referenced by normaliseCreateExtras(), normaliseOneRecordArgs(), normaliseWriteArgs(), previewValue(), refOfCreatedObject(), and resolveWriteTarget().
|
private |
Record a line write goes into, for a write declaring a 'parent'.
| array<string,mixed> | $write The 'write' enrichment of the tool. |
| array<string,mixed> | $args Arguments of the call. |
Definition at line 3634 of file api_bridge.class.php.
References fetchBusinessObject().
Referenced by normaliseUpdateArgs(), normaliseWriteArgs(), writeConfirmationPreview(), and writePrecheck().
| ToolApiBridge::getCategories | ( | ) |
Return categories this tool belongs to.
Reimplemented from McpTool.
Definition at line 5836 of file api_bridge.class.php.
| ToolApiBridge::getDefinitions | ( | ) |
Returns tool definitions derived from the enabled REST API endpoints.
Reimplemented from McpTool.
Definition at line 2929 of file api_bridge.class.php.
References applyMethodRestriction(), buildToolDefinition(), defaultMethods(), defsCacheFile(), discoverEndpoints(), dol_now(), getDolGlobalInt(), isModEnabled(), loadApiRuntime(), resolveEndpointClass(), setupAllows(), toolGroups(), and writeDefsCache().
| ToolApiBridge::getRequiredRights | ( | string | $toolName | ) |
Rights are enforced by the REST API classes themselves.
| string | $toolName | Tool being executed. |
Reimplemented from McpTool.
Definition at line 3470 of file api_bridge.class.php.
References methodMetaFor().
|
private |
Enrichment of the put method of a document header: the listed fields of a draft, confirmed with their old and new value.
| string | $label | Document name, as the model reads it. |
| string | $class | Business class of the document. |
| string[] | $right | Right needed to write. |
| string[] | $readright | Right needed to read. |
| string[] | $access | Feature, table and subfeature, as the REST class checks them. |
| string | $extrafields | Element of its extra fields. |
| array<string,array{0:array<string,mixed>,1:string}> | $fields Field => schema and label key. |
Definition at line 2627 of file api_bridge.class.php.
Referenced by addWritesOnExistingRecords().
|
private |
Lift Restler's inline validation tags out of a parameter description.
The REST API documents constraints the way Restler reads them to build swagger.json: {@min 1}, {@max 100}, {@choice yes,no}, {@pattern /re/flags}, {@const value}. Those carry exactly what JSON Schema calls minimum, maximum, enum and pattern, so they are translated instead of being shown to the model as part of the sentence. Tags with no JSON Schema equivalent ({@type} names a PHP class, {@from} names the HTTP source, which in-process calls have no use for) are removed from the text and otherwise ignored.
| ?string | $desc | Parameter description, as written in the docblock (may be null) |
| string | $ptype | JSON Schema type already determined for this parameter |
| array<string,mixed> | $constraints Filled with the JSON Schema constraints found |
Definition at line 3343 of file api_bridge.class.php.
References restlerPatternToJsonSchema(), and tagValueToNumber().
Referenced by buildToolDefinition().
|
private |
Enrichment of a line method of a draft document: change, delete or, for an intervention, add one line.
| string | $action | 'update', 'delete' or 'add'. |
| string | $label | Document name, as the model reads it. |
| string | $class | Business class of the document. |
| string[] | $right | Right needed to write. |
| string | $profile | Line shape: 'product', 'supplier', 'contract' or 'intervention'. |
Definition at line 2562 of file api_bridge.class.php.
Referenced by addWritesOnExistingRecords().
|
private |
A line as the user knows it: product ref and label, else its text.
| object | $l | Line. |
Definition at line 5423 of file api_bridge.class.php.
References dol_string_nohtmltag().
Referenced by linesSummary(), and normaliseLineArgs().
|
private |
Lines of a document, as a numbered list for a message: position, product, quantity.
| CommonObject | $doc | Document with its lines. |
Definition at line 5403 of file api_bridge.class.php.
References dol_trunc(), and lineName().
Referenced by normaliseLineArgs().
|
private |
Load the REST API runtime (Restler autoloader + DolibarrApi base classes), mirroring the bootstrap sequence of htdocs/api/index.php, so that the endpoint classes (which extend DolibarrApi and throw RestException) can be loaded and executed outside the Restler HTTP runtime.
Definition at line 2697 of file api_bridge.class.php.
Referenced by getDefinitions().
|
private |
Merge endpoint enrichments declared by external modules through the 'addMcpApiBridgeEnrichments' hook (aimcp context).
An external module declares the part of the whitelist that core cannot know: which methods of its own api_*.class.php files are exposed, with the parameter docs and 'write' blocks they carry. The declaration is what makes an external endpoint exposed at all — the scan only decides what is reachable — and a module can never shadow a core entry: keys already populated here are kept, the module's own are appended.
Every other layer stays in place for module endpoints: the endpoint is discovered only while its module is enabled, the tools pass the per-context allow-lists, their 'right' blocks are checked per call, and every 'write' goes through the confirmation gate.
Expected module return (in $this->results of its actions class), nested under the module name since the results of all modules are merged: array('mymodule' => array('endpointkey' => array('label' => ..., 'methods' => array(...)))) where 'endpointkey' is the X of the module's api_X.class.php file.
Definition at line 1472 of file api_bridge.class.php.
References conf(), defaultMethods(), dol_syslog(), and user.
Referenced by __construct().
|
private |
Find the enrichment of the method a tool name maps to.
| string | $toolName | Tool name (api_<endpoint>_<suffix>). |
Definition at line 5792 of file api_bridge.class.php.
Referenced by applyFixedParams(), getRequiredRights(), and writeConfirmationPreview().
|
private |
Arguments of a create that names a project, or gives dates or hours.
| array<string,mixed> | $args Arguments, third party already resolved. |
| array<string,mixed> | $write The 'write' enrichment of the tool. |
Definition at line 5460 of file api_bridge.class.php.
References dol_now(), dol_print_date(), dol_strtolower(), fetchRecord(), resolveWriteTarget(), userCanReach(), and writeDate().
Referenced by normaliseWriteArgs().
|
private |
Arguments of a line write on a draft: the line found from what the user said, and the full body the REST method needs, its unchanged values kept.
| array<string,mixed> | $args Arguments as received. |
| array<string,mixed> | $write The 'write' enrichment of the tool. |
| array<string,mixed> | $out Arguments already resolved (the document id). |
Definition at line 5245 of file api_bridge.class.php.
References dol_now(), dol_string_nohtmltag(), dol_strtolower(), lineName(), linesSummary(), price2num(), unitIdFromName(), and writeDate().
Referenced by normaliseTargetArgs().
|
private |
Arguments of a write on one existing record that is not a targeted write (a ticket reply, a ticket or task edit, a ticket contact): the record given by rowid or ref is found here, with the user's access, so a ref works as the id and an unknown record is refused before the confirmation.
A contact is checked the same way, and a value another tool handles (a ticket closed or assigned) is pointed to that tool.
| array<string,mixed> | $args Arguments as sent. |
| array<string,mixed> | $write The 'write' enrichment of the tool. |
Definition at line 5072 of file api_bridge.class.php.
References fetchRecord(), resolveWriteTarget(), user, and userCanReach().
Referenced by normaliseWriteArgs().
|
private |
Arguments of a write on an existing record (update, validation, deletion, payment): the record found from what the user said, and only what the REST method may receive.
| array<string,mixed> | $args Arguments, request_data already unwrapped. |
| array<string,mixed> | $write The 'write' enrichment of the tool. |
Definition at line 5160 of file api_bridge.class.php.
References dol_getIdFromCode(), dol_now(), dol_print_date(), dol_stringtotime(), isModEnabled(), normaliseLineArgs(), price2num(), resolveBankAccount(), resolvePaymentMode(), resolveWarehouse(), resolveWriteTarget(), user, and validationMovesStock().
Referenced by normaliseWriteArgs().
|
private |
Normalise and validate partial updates without creation defaults.
| array<string,mixed> | $args Incoming arguments |
| array<string,mixed> | $write Write metadata |
| InvalidArgumentException | When the update cannot be applied |
Definition at line 3724 of file api_bridge.class.php.
References canAccessWriteObject(), dol_strlen(), fetchWriteParent(), sanitizeVal(), user, and validateProjectUpdate().
Referenced by normaliseWriteArgs().
|
private |
Normalise the arguments of a write before they are previewed or executed.
A model may send the record as a request_data body (sometimes a JSON string) instead of flat fields, and may name line fields the way the custom tools do. Both are accepted here so the preview describes what the API will actually write.
| array<string,mixed> | $args Arguments as received. |
| array<string,mixed> | $write The 'write' enrichment of the tool. |
Definition at line 3845 of file api_bridge.class.php.
References aiFindThirdpartiesInText(), fetchRecord(), fetchWriteParent(), normaliseCreateExtras(), normaliseOneRecordArgs(), normaliseTargetArgs(), normaliseUpdateArgs(), normaliseWriteLine(), resetWriteState(), resolveWarehouse(), socidOf(), and writeDate().
Referenced by writeConfirmationPreview(), and writePrecheck().
|
private |
Normalise one document line: field names, product given by ref or label, default VAT rate.
| array<string,mixed> | $line Line as received. | |
| int | $socid | Third party of the document, 0 if unknown. |
| bool | $buy | True for a supplier document: purchase price and VAT. |
| string | $kind | '' for a commercial document, 'reception' or 'shipment' for a logistic one (warehouse, batch, cost price; no VAT). |
| int | $defaultWarehouse | Warehouse given on the header, for the lines that name none. |
Definition at line 4029 of file api_bridge.class.php.
References closeProductRefs(), defaultBuyPrice(), defaultVatRate(), defaultWarehouseId(), fetchBusinessObject(), Product\hasbatch(), isModEnabled(), resolveWarehouse(), unitIdFromName(), and writeDate().
Referenced by normaliseWriteArgs().
|
private |
One entry of a short list from what the user said: its rowid, one of its names said in full, else the only entry whose name contains the words.
| array<int,string[]> | $list Rowid => names it is known by. | |
| mixed | $value | What the user said, empty when nothing. |
| string[] | $names | Names to list when asking. |
| string | $askKey | Translation key when nothing was said and several exist. |
| string | $missingKey | Translation key when nothing fits what was said. |
| string | $noneKey | Translation key when the list is empty, '' to never refuse for that. |
| bool | $onlyOne | Take the only entry when nothing was said. |
Definition at line 5014 of file api_bridge.class.php.
References $id, and dol_strtolower().
Referenced by resolveBankAccount(), resolvePaymentMode(), and resolveWarehouse().
|
private |
Why a write on an existing record cannot run, or '' when it can.
| array<string,mixed> | $write The 'write' enrichment of the tool. |
| array<string,mixed> | $args Normalised arguments. |
Definition at line 5686 of file api_bridge.class.php.
References price().
Referenced by writePrecheck().
|
private |
Confirmation sentence of a line write: the line by its position and product, each change from its old to its new value, and the new line total.
| array<string,mixed> | $write The 'write' enrichment of the tool. | |
| string | $what | The document, as describeRecord() names it. |
Definition at line 5602 of file api_bridge.class.php.
References convertSecondToTime(), dol_print_date(), dol_string_nohtmltag(), dol_trunc(), price(), and unitLabel().
Referenced by previewTargetWrite().
|
private |
The lines of a reception or shipment as the confirmation lists them: quantity, product, and for a reception the warehouse and the cost.
| array<int,mixed> | $lines Normalised lines. | |
| string | $kind | 'reception' or 'shipment'. |
Definition at line 4223 of file api_bridge.class.php.
References dol_trunc(), fetchBusinessObject(), and price2num().
|
private |
A record linked by a header field, as the confirmation names it: its ref and label, or null (as the other fields print it) when the field is empty.
| string | $class | Business class of the linked record. |
| mixed | $id | Rowid, or null. |
Definition at line 3613 of file api_bridge.class.php.
References $id, and fetchBusinessObject().
Referenced by writeConfirmationPreview().
|
private |
Confirmation sentence of a write on an existing record.
| array<string,mixed> | $write The 'write' enrichment of the tool. |
| array<string,mixed> | $args Normalised arguments. |
Definition at line 5525 of file api_bridge.class.php.
References describeRecord(), dol_getIdFromCode(), dol_print_date(), dol_stringtotime(), dol_trunc(), previewLineWrite(), and price().
Referenced by writeConfirmationPreview().
|
private |
One value of a confirmation sentence, the way the user knows it: the record an id stands for, hours rather than the seconds the API takes, a date as a date.
Anything else is shown as given.
| array<string,mixed> | $write The 'write' enrichment of the tool. | |
| string | $argname | Argument name. |
| mixed | $value | Its value, after normaliseWriteArgs(). |
| array<string,mixed> | $args All the arguments (the source of a contact). |
Definition at line 4445 of file api_bridge.class.php.
References convertSecondToTime(), describeRecord(), dol_print_date(), fetchRecord(), and userCanReach().
Referenced by writeConfirmationPreview().
|
private |
Keep what the chat shows of the content of a directory: type, name, path, size, date, and a link for a file.
| mixed | $output | Result of getDocumentsListByDirectory() |
| string | $modulepart | Area listed ('ecm' or 'medias') |
Definition at line 5938 of file api_bridge.class.php.
References dol_print_date(), and dol_print_size().
|
private |
Keep what the chat shows of a file list: name, size, date and a link.
| mixed | $output | Result of getDocumentsListByElement() |
| string | $modulepart | Object type the caller asked for |
Definition at line 5903 of file api_bridge.class.php.
References dol_print_date(), and dol_print_size().
|
private |
Describe bounded edits of an existing project.
Definition at line 2664 of file api_bridge.class.php.
Referenced by __construct().
| ToolApiBridge::purgeDefsCache | ( | ) |
Delete every bridge_tooldefs_*.json cache file of the ai temp directories (current entity and the other ones), so the tool definitions are rebuilt from scratch on the next request.
Called by the /reload command of the assistant chat.
Definition at line 3119 of file api_bridge.class.php.
References $conf.
|
private |
Ref of a record just created, for the confirmation shown to the user.
| string | $class | Business class declared by the write. |
| int | $id | Rowid returned by the API. |
Definition at line 3598 of file api_bridge.class.php.
References $id, and fetchRecord().
|
private |
Forget what the previous normaliseWriteArgs() call found, so a problem of one call is never reported for the next one.
Definition at line 2447 of file api_bridge.class.php.
Referenced by normaliseWriteArgs().
|
private |
Open bank account from the words of the user, or the only one there is.
| mixed | $value | Label, ref or rowid given; empty when none was said. |
Definition at line 4950 of file api_bridge.class.php.
References $id, and pickOne().
Referenced by normaliseTargetArgs().
|
private |
Load an endpoint's api file and resolve its real class name (lazy, cached in $this->endpoints).
class_exists() is case-insensitive, so the candidate "Agendaevents" matches the declared AgendaEvents; reflection then recovers the real spelling.
| string | $key | Endpoint key |
Definition at line 2817 of file api_bridge.class.php.
Referenced by getDefinitions().
|
private |
Active payment mode from the words of the user: its code, its label in the dictionary or in the user's language, or the usual words for it.
| mixed | $value | Code, label, words or rowid given. |
Definition at line 4975 of file api_bridge.class.php.
References dol_strtolower(), and pickOne().
Referenced by normaliseTargetArgs().
|
private |
Resolve 'me' sent as an argument value on user-referencing fields.
The model may answer "assign this task to me" with fk_user_assign: 'me' — the same sentinel the write defaults already expand to the acting user. Only fields whose name references a user are touched: a literal 'me' in a text field (subject, label, note) is left alone.
| array<string,mixed> | $args Tool arguments as sent. |
Definition at line 5818 of file api_bridge.class.php.
References user.
|
private |
Open warehouse from the words of the user, or the only one there is.
| mixed | $value | Name, ref or rowid given; empty when none was said. |
Definition at line 4924 of file api_bridge.class.php.
References $id, and pickOne().
Referenced by normaliseTargetArgs(), normaliseWriteArgs(), and normaliseWriteLine().
|
private |
Record a targeted write is about, from the id or the words the model sent.
| array<string,mixed> | $write The 'write' enrichment of the tool. | |
| mixed | $value | Rowid, ref or name given by the model. |
Definition at line 4782 of file api_bridge.class.php.
References $c, aiFindThirdpartiesInText(), and fetchRecord().
Referenced by normaliseCreateExtras(), normaliseOneRecordArgs(), and normaliseTargetArgs().
|
private |
Convert a Restler {@pattern} value to a JSON Schema pattern.
JSON Schema patterns are ECMA-262 regexps with no delimiters and no flags, so the PCRE delimiters are stripped. A flag that changes what the regexp accepts cannot be carried over; rather than silently tightening the constraint, the pattern is then dropped and only the description keeps the information. The one exception is /i on a regexp holding no letter, where the flag has nothing to act on.
| string | $value | Raw tag value, e.g. "/^[0-9,]*$/i" |
Definition at line 3426 of file api_bridge.class.php.
Referenced by liftInlineTags().
|
private |
Whether one of these setup constants is on.
| string[] | $consts | Constant names. |
Definition at line 3021 of file api_bridge.class.php.
References getDolGlobalString().
Referenced by getDefinitions().
|
private |
A setup constant read while the tools are declared.
The tools are also declared outside a full Dolibarr environment (unit tests), where no setup is loaded: the constant then reads as not set.
| string | $name | Constant name. |
Definition at line 2436 of file api_bridge.class.php.
References getDolGlobalString().
Referenced by addWritesOnExistingRecords().
|
private |
Shape a read result as its enrichment asks: drop the fields that must not leave the server, and cap a list the REST method returns unbounded.
| array<mixed> | $output Result of the REST method. |
| array<string,mixed> | $meta Enrichment of the method. |
Definition at line 5987 of file api_bridge.class.php.
|
private |
Third party of a record, 0 for a record that has none (product, third party).
| CommonObject | null | $obj | Record. |
Definition at line 4870 of file api_bridge.class.php.
Referenced by describeRecord(), and normaliseWriteArgs().
|
private |
Convert a numeric tag value to the PHP number JSON encodes as a number.
{@min 0} must reach the model as 0, not "0": a JSON Schema minimum given as a string is not a minimum.
| string | $value | Numeric tag value, already checked with is_numeric() |
Definition at line 3408 of file api_bridge.class.php.
Referenced by liftInlineTags().
|
private |
Groups of tools to build: enrichment key => key of the discovered endpoint whose REST class it calls.
An enrichment calls the endpoint of the same name, unless it names another one with 'endpoint' (several groups of tools can share one REST class). Ordered by endpoint, as discovered.
Definition at line 2873 of file api_bridge.class.php.
Referenced by getDefinitions().
| ToolApiBridge::toolRoute | ( | string | $name | ) |
Endpoint and method a bridge tool calls, for a page that shows the tool to a person (the palette of the chat) under a plain name.
| string | $name | Tool name. |
Definition at line 6343 of file api_bridge.class.php.
|
private |
Unit id from the word a user used for it: code, short label or label, in the user's language, singular or plural ("piece", "pieces", "pcs").
| string | $name | Unit as written |
Definition at line 3826 of file api_bridge.class.php.
References aiUnitIdFromName().
Referenced by normaliseLineArgs(), and normaliseWriteLine().
|
private |
Label of a unit, as the user reads it.
| int | $id | Rowid of the unit, 0 for none. |
Definition at line 5666 of file api_bridge.class.php.
References $id.
Referenced by previewLineWrite().
|
private |
Message refusing a write whose products could not be resolved, with the close references found for each, so the user (or the model) can pick one.
Definition at line 4715 of file api_bridge.class.php.
Referenced by writePrecheck().
|
private |
Schema of a partial update declared by an endpoint's write metadata.
| array<string,mixed> | $write Write metadata |
Definition at line 3652 of file api_bridge.class.php.
Referenced by buildToolDefinition().
|
private |
Enrichment of the put method of a record: change some of its fields.
| string | $label | Record name, as the model reads it. |
| string | $class | Business class of the record. |
| string[] | $right | Right needed to write. |
| array<string,string> | $fields Fields that may be changed, with their doc. | |
| string | $lookup | How a non numeric id is found: 'thirdparty' (by name), 'ref', or '' (rowid only). |
Definition at line 2465 of file api_bridge.class.php.
Referenced by addWritesOnExistingRecords().
|
private |
Whether the acting user may reach a record, with the same check the REST class makes before touching it (sales representative restriction, entity).
| string | $class | Business class of the record. |
| int | $id | Rowid of the record. |
Definition at line 4834 of file api_bridge.class.php.
References $id, checkUserAccessToObject(), and user.
Referenced by normaliseCreateExtras(), normaliseOneRecordArgs(), previewValue(), and writePrecheck().
|
private |
Enrichment of the validate method of a document.
| string | $label | Document name, as the model reads it. |
| string | $class | Business class of the document. |
| string | $preview | Translation key of the confirmation. |
| string[] | $right | Right needed to validate. With advanced permissions (a module, perm, subperm triple) the REST method still checks the module's 'creer', which is then required too. |
| array<string,mixed> | $fixed Arguments the call always carries, whatever the model sends. | |
| string | $stockconst | Constant that makes the validation move stock, '' for none. |
Definition at line 2497 of file api_bridge.class.php.
Referenced by addWritesOnExistingRecords().
|
private |
Check resulting dates, project write access and native update side effects.
| array<string,mixed> | $args Normalized update arguments | |
| Project | $parent | Existing record |
| InvalidArgumentException | When the edit is not safe |
Definition at line 3700 of file api_bridge.class.php.
References canAccessWriteObject().
Referenced by normaliseUpdateArgs().
|
private |
Whether validating this document moves stock, so a warehouse is needed.
| array<string,mixed> | $write The 'write' enrichment of the tool. | |
| CommonObject | $obj | Document to validate. |
Definition at line 5439 of file api_bridge.class.php.
References getDolGlobalString(), and isModEnabled().
Referenced by normaliseTargetArgs().
| ToolApiBridge::writeConfirmationPreview | ( | string | $toolName, |
| array | $args ) |
Preview of what a bridge write would do, for the confirmation gate.
Read tools return NO_WRITE and run as before. A method declaring a 'write' block in its enrichment is gated: the sentence below is what the user approves, so it names the third party and the lines rather than echoing arguments.
| string | $toolName | Tool being called. |
| array<string,mixed> | $args Arguments as received. |
Reimplemented from McpTool.
Definition at line 4296 of file api_bridge.class.php.
References $context, applyFixedParams(), dol_print_date(), dol_trunc(), fetchBusinessObject(), fetchWriteParent(), methodMetaFor(), McpTool\NO_WRITE, normaliseWriteArgs(), previewObjectName(), previewTargetWrite(), previewValue(), price(), price2num(), and writeMetaFor().
|
private |
A date written as text, as a timestamp.
A date that cannot be read is refused before the confirmation, never dropped or replaced by today.
| string | $field | Field name, for the message. |
| mixed | $value | Date as written. |
| int | $gmt | 1 to read it in GMT (logistic dates), 0 in the server time zone. |
Definition at line 4197 of file api_bridge.class.php.
References dol_stringtotime().
Referenced by normaliseCreateExtras(), normaliseLineArgs(), normaliseWriteArgs(), and normaliseWriteLine().
|
private |
Persist the generated definitions/routes/endpoints, pruning cache files of previous states so stale signatures do not pile up.
Written to a temporary name then renamed, so a concurrent reader never sees a truncated file.
| string | $cachefile | Target file from defsCacheFile() |
Definition at line 3094 of file api_bridge.class.php.
Referenced by getDefinitions().
|
private |
The 'write' enrichment of a tool, when it has one.
| string | $toolName | Tool name as exposed. |
Definition at line 5779 of file api_bridge.class.php.
Referenced by writeConfirmationPreview(), and writePrecheck().
| ToolApiBridge::writePrecheck | ( | string | $toolName, |
| array | $args ) |
Refuse, before any confirmation, a write that could only fail, so the user is never asked to approve it:
| string | $toolName | Tool being called. |
| array<string,mixed> | $args Arguments as received. |
Reimplemented from McpTool.
Definition at line 4507 of file api_bridge.class.php.
References $c, aiFindThirdpartiesInText(), applyFixedParams(), fetchWriteParent(), getDolGlobalString(), normaliseWriteArgs(), precheckTargetWrite(), unresolvedProductsMessage(), user, userCanReach(), and writeMetaFor().
| const ToolApiBridge::BRIDGE_DEFAULT_LIMIT = 25 |
Default and ceiling applied to list 'limit' parameters when called through the bridge.
API methods default to 100 full objects — too much model context for a single call; everything stays reachable via 'page'.
Definition at line 126 of file api_bridge.class.php.
| const ToolApiBridge::ENDPOINT_CATEGORIES |
Endpoint key -> intent categories of the assistant's query classifier (classifyIntentUniversal() in parse_intent.php: billing, commercial, thirdparty, stock, project, reporting).
On Latin-script queries the classifier prefilters which tools the model sees, so bridge tools MUST carry this vocabulary — anything else gets every bridge tool filtered out of the prompt. Endpoints absent from this map (external modules) fall back to all categories so they stay selectable.
Definition at line 79 of file api_bridge.class.php.