dolibarr 25.0.0-alpha
ToolApiBridge Class Reference

Class ToolApiBridge. More...

Inheritance diagram for ToolApiBridge:
Collaboration diagram for ToolApiBridge:

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.
 

Detailed Description

Class ToolApiBridge.

Exposes enabled REST API endpoints as MCP tools (read-only POC).

Definition at line 67 of file api_bridge.class.php.

Constructor & Destructor Documentation

◆ __construct()

ToolApiBridge::__construct ( $db,
$user = null,
$conf = null )

Constructor.

Parameters
DoliDB$dbDatabase handler
User | null$userActing user provided by McpHandler (the caller; tool calls run with this user's rights)
Conf | null$confDolibarr config (optional)

Reimplemented from McpTool.

Definition at line 238 of file api_bridge.class.php.

References addLineMethod(), addReadEndpoints(), addWritesOnExistingRecords(), conf(), loadExternalEnrichments(), projectUpdateMethod(), and user.

Member Function Documentation

◆ addCreatorContact()

ToolApiBridge::addCreatorContact ( $class,
$id,
$code )
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.

Parameters
string$classBusiness class of the record.
int$idRowid of the record.
string$codeInternal contact type code.
Returns
void

Definition at line 6035 of file api_bridge.class.php.

References $id, dol_syslog(), and user.

◆ addLineMethod()

ToolApiBridge::addLineMethod ( $label,
$lookupTool,
$class,
array $right,
$buy = false,
array $rename = array(),
array $defaults = array() )
private

Enrichment of the postLine method of a document (order, proposal, invoice, and their supplier counterparts): add ONE line to an existing draft.

Parameters
string$labelDocument name, as the model reads it (e.g. 'sale order').
string$lookupToolTool to find the rowid when only the ref is known.
string$classBusiness class of the document.
string[]$rightRight needed to write.
bool$buyTrue 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.
Returns
array<string,mixed> Method enrichment.

Definition at line 2096 of file api_bridge.class.php.

Referenced by __construct(), and addWritesOnExistingRecords().

◆ addReadEndpoints()

ToolApiBridge::addReadEndpoints ( )
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.

Returns
void

Definition at line 1524 of file api_bridge.class.php.

Referenced by __construct().

◆ addWritesOnExistingRecords()

ToolApiBridge::addWritesOnExistingRecords ( )
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.

Returns
void

Definition at line 2144 of file api_bridge.class.php.

References addLineMethod(), deleteMethod(), getDolGlobalInt(), headerUpdateMethod(), isModEnabled(), lineMethod(), setupValue(), updateMethod(), and validateMethod().

Referenced by __construct().

◆ applyFixedParams()

ToolApiBridge::applyFixedParams ( string $toolName,
array $args )
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.

Parameters
string$toolNameTool name.
array<string,mixed>$args Tool arguments as sent.
Returns
array<string,mixed> Arguments with the fixed ones set.

Definition at line 2895 of file api_bridge.class.php.

References methodMetaFor().

Referenced by writeConfirmationPreview(), and writePrecheck().

◆ applyMethodRestriction()

ToolApiBridge::applyMethodRestriction ( array $methods)
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.

Parameters
array<string,array{suffix?:string,description?:string,params?:array<string,string>}>$methods Whitelisted methods
Returns
array<string, array{suffix?:string, description?:string, params?:array<string,string>}> Restricted methods

Definition at line 2914 of file api_bridge.class.php.

References getDolGlobalString().

Referenced by getDefinitions().

◆ buildToolDefinition()

ToolApiBridge::buildToolDefinition ( array $ep,
string $key,
string $method,
string $toolname,
array $meta = [] )
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).

Parameters
array{module:string,path:string,class:string,label:string}$ep Endpoint entry
string$keyEndpoint key (e.g. 'thirdparties')
string$methodWhitelisted API method name (e.g. 'index', 'get')
string$toolnameGenerated tool name
array{suffix?:string,description?:string,params?:array<string,string>}$meta Hand-written enrichment for this method
Returns
array<string, mixed>|null Tool definition, or null on reflection failure

Definition at line 3162 of file api_bridge.class.php.

References docTypeToJson(), liftInlineTags(), McpTool\normalizeInputSchema(), and updateInputSchema().

Referenced by getDefinitions().

◆ canAccessWriteObject()

ToolApiBridge::canAccessWriteObject ( array $access,
$id )
protected

Check object visibility with the same resource arguments as REST.

Parameters
array<int,string>$access Resource, table and subfeature
int$idObject ID
Returns
bool Whether the acting user can access the object

Definition at line 3676 of file api_bridge.class.php.

References $id, checkUserAccessToObject(), and user.

Referenced by normaliseUpdateArgs(), and validateProjectUpdate().

◆ canWriteProject()

ToolApiBridge::canWriteProject ( $project)
protected

Apply native project write authorization, not merely read-all visibility.

Parameters
Project$projectProject already checked for visibility and entity
Returns
bool Whether the acting user can edit the project

Definition at line 3687 of file api_bridge.class.php.

References user.

◆ closeProductRefs()

ToolApiBridge::closeProductRefs ( $wanted,
$socid )
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.

Parameters
string$wantedReference as written on the document.
int$socidSupplier whose catalogue is searched, 0 for a customer document.
Returns
string[] Up to five "ref = our ref (label)" strings, closest first.

Definition at line 4664 of file api_bridge.class.php.

References dol_strlen(), and dol_trunc().

Referenced by normaliseWriteLine().

◆ defaultBuyPrice()

ToolApiBridge::defaultBuyPrice ( $prod,
$socid,
$qty )
private

Unit purchase price of a product, for a supplier document line given by product ref: the sale price would be wrong there.

Parameters
Product$prodProduct of the line.
int$socidSupplier of the document, 0 if unknown.
float$qtyQuantity of the line, for the price by quantity.
Returns
float Cheapest price of this supplier, else the cost price, else 0.

Definition at line 3540 of file api_bridge.class.php.

Referenced by normaliseWriteLine().

◆ defaultMethods()

ToolApiBridge::defaultMethods ( )
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.

Returns
array<string, array{}> Method name => empty enrichment

Definition at line 2860 of file api_bridge.class.php.

Referenced by getDefinitions(), and loadExternalEnrichments().

◆ defaultVatRate()

ToolApiBridge::defaultVatRate ( $socid,
$fk_product,
$buy = false )
private

VAT rate core would apply to a line, when the caller gave none.

Parameters
int$socidThird party of the document.
int$fk_productProduct of the line, 0 for a free line.
bool$buyTrue for a supplier document: the third party sells to us.
Returns
float Rate to write.

Definition at line 3518 of file api_bridge.class.php.

References $mysoc, and get_default_tva().

Referenced by normaliseWriteLine().

◆ defaultWarehouseId()

ToolApiBridge::defaultWarehouseId ( )
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.

Returns
int Rowid, 0 when there is no obvious default.

Definition at line 4266 of file api_bridge.class.php.

References getDolGlobalInt(), getEntity(), and user.

Referenced by normaliseWriteLine().

◆ defsCacheFile()

ToolApiBridge::defsCacheFile ( )
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.

Returns
string Absolute cache file path, or '' to skip caching

Definition at line 3046 of file api_bridge.class.php.

References $conf, dol_mkdir(), and getDolGlobalString().

Referenced by getDefinitions().

◆ deleteMethod()

ToolApiBridge::deleteMethod ( $label,
$class,
array $right )
private

Enrichment of the delete method of a document, for its drafts only.

Parameters
string$labelDocument name, as the model reads it.
string$classBusiness class of the document.
string[]$rightRight needed to delete.
Returns
array<string,mixed> Method enrichment.

Definition at line 2533 of file api_bridge.class.php.

Referenced by addWritesOnExistingRecords().

◆ describeRecord()

ToolApiBridge::describeRecord ( $obj)
private

Short description of a document for a confirmation: ref, third party, amount.

Parameters
CommonObject$objRecord.
Returns
string

Definition at line 4883 of file api_bridge.class.php.

References $conf, price(), and socidOf().

Referenced by previewTargetWrite(), and previewValue().

◆ discoverEndpoints()

ToolApiBridge::discoverEndpoints ( )
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.

Returns
array<string, array{module:string, path:string, candidate:string, class:string, label:string}> Endpoints keyed by name

Definition at line 2735 of file api_bridge.class.php.

References $module, dol_buildpath(), dol_osencode(), dolGetModulesDirs(), getModuleDirForApiClass(), and isModEnabled().

Referenced by getDefinitions().

◆ docTypeToJson()

ToolApiBridge::docTypeToJson ( string $type)
private

Convert a docblock type to a JSON Schema type.

Parameters
string$typeDocblock type (may be a union like int|string)
Returns
string JSON Schema type

Definition at line 3449 of file api_bridge.class.php.

Referenced by buildToolDefinition().

◆ documentObjectExists()

ToolApiBridge::documentObjectExists ( array $args)
private

Whether the object a file list was asked for exists.

Parameters
array<string,mixed>$args Tool arguments (modulepart, id, ref)
Returns
bool

Definition at line 5973 of file api_bridge.class.php.

References $object.

◆ execute()

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.

Parameters
string$nameThe tool name (e.g. 'api_thirdparties_list').
array<string,mixed>$args The tool arguments (named).
Returns
mixed Result array, or ["error" => ...] on failure.

Reimplemented from McpTool.

Definition at line 6055 of file api_bridge.class.php.

References aiStripPersonalExtrafields(), dol_now(), dol_syslog(), dol_trunc(), and user.

◆ extrafieldsElementForEndpoint()

ToolApiBridge::extrafieldsElementForEndpoint ( $key)
private

Map a bridge endpoint key to the element type ExtraFields uses.

Parameters
string$keyEndpoint key from the enrichment map.
Returns
string ExtraFields element type, '' when the objects carry none.

Definition at line 5854 of file api_bridge.class.php.

◆ fetchBusinessObject()

ToolApiBridge::fetchBusinessObject ( $class,
$id,
$ref = '' )
protected

Load a business record of one of the classes the writes declare.

Parameters
string$classBusiness class declared by the write.
int$idRowid of the record.
string$refExact reference when no rowid was supplied.
Returns
Facture|Commande|Propal|FactureFournisseur|CommandeFournisseur|SupplierProposal|Societe|Product|Reception|Expedition|Project|Contrat|Fichinter|null Record, or null when it cannot be read.

Definition at line 3559 of file api_bridge.class.php.

References $id.

Referenced by fetchWriteParent(), normaliseWriteLine(), previewLogisticLines(), previewObjectName(), and writeConfirmationPreview().

◆ fetchRecord()

ToolApiBridge::fetchRecord ( $class,
$id,
$ref = '' )
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).

Parameters
string$classBusiness class declared by the write.
int$idRowid of the record, 0 to look it up by ref.
string$refRef of the record, used when no rowid is given.
Returns
CommonObject|null Record, or null when it cannot be read.

Definition at line 4735 of file api_bridge.class.php.

References $id.

Referenced by normaliseCreateExtras(), normaliseOneRecordArgs(), normaliseWriteArgs(), previewValue(), refOfCreatedObject(), and resolveWriteTarget().

◆ fetchWriteParent()

ToolApiBridge::fetchWriteParent ( array $write,
array $args )
private

Record a line write goes into, for a write declaring a 'parent'.

Parameters
array<string,mixed>$write The 'write' enrichment of the tool.
array<string,mixed>$args Arguments of the call.
Returns
Facture|Commande|Propal|FactureFournisseur|CommandeFournisseur|SupplierProposal|Societe|Product|Project|Contrat|Fichinter|null Record, or null when not found.

Definition at line 3634 of file api_bridge.class.php.

References fetchBusinessObject().

Referenced by normaliseUpdateArgs(), normaliseWriteArgs(), writeConfirmationPreview(), and writePrecheck().

◆ getCategories()

ToolApiBridge::getCategories ( )

Return categories this tool belongs to.

Returns
array<string> List of categories

Reimplemented from McpTool.

Definition at line 5836 of file api_bridge.class.php.

◆ getDefinitions()

ToolApiBridge::getDefinitions ( )

Returns tool definitions derived from the enabled REST API endpoints.

Returns
list<array<string, mixed>> Array of tool definitions.

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().

◆ getRequiredRights()

ToolApiBridge::getRequiredRights ( string $toolName)

Rights are enforced by the REST API classes themselves.

Parameters
string$toolNameTool being executed.
Returns
array<int,array<int,string>>|string Rights triples for a write, or RIGHTS_ENFORCED_DOWNSTREAM for a read.

Reimplemented from McpTool.

Definition at line 3470 of file api_bridge.class.php.

References methodMetaFor().

◆ headerUpdateMethod()

ToolApiBridge::headerUpdateMethod ( $label,
$class,
array $right,
array $readright,
array $access,
$extrafields,
array $fields )
private

Enrichment of the put method of a document header: the listed fields of a draft, confirmed with their old and new value.

Parameters
string$labelDocument name, as the model reads it.
string$classBusiness class of the document.
string[]$rightRight needed to write.
string[]$readrightRight needed to read.
string[]$accessFeature, table and subfeature, as the REST class checks them.
string$extrafieldsElement of its extra fields.
array<string,array{0:array<string,mixed>,1:string}>$fields Field => schema and label key.
Returns
array<string,mixed> Method enrichment.

Definition at line 2627 of file api_bridge.class.php.

Referenced by addWritesOnExistingRecords().

◆ liftInlineTags()

ToolApiBridge::liftInlineTags ( $desc,
string $ptype,
array & $constraints )
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.

Parameters
?string$descParameter description, as written in the docblock (may be null)
string$ptypeJSON Schema type already determined for this parameter
array<string,mixed>$constraints Filled with the JSON Schema constraints found
Returns
string The description with every inline tag removed

Definition at line 3343 of file api_bridge.class.php.

References restlerPatternToJsonSchema(), and tagValueToNumber().

Referenced by buildToolDefinition().

◆ lineMethod()

ToolApiBridge::lineMethod ( $action,
$label,
$class,
array $right,
$profile )
private

Enrichment of a line method of a draft document: change, delete or, for an intervention, add one line.

Parameters
string$action'update', 'delete' or 'add'.
string$labelDocument name, as the model reads it.
string$classBusiness class of the document.
string[]$rightRight needed to write.
string$profileLine shape: 'product', 'supplier', 'contract' or 'intervention'.
Returns
array<string,mixed> Method enrichment.

Definition at line 2562 of file api_bridge.class.php.

Referenced by addWritesOnExistingRecords().

◆ lineName()

ToolApiBridge::lineName ( $l)
private

A line as the user knows it: product ref and label, else its text.

Parameters
object$lLine.
Returns
string

Definition at line 5423 of file api_bridge.class.php.

References dol_string_nohtmltag().

Referenced by linesSummary(), and normaliseLineArgs().

◆ linesSummary()

ToolApiBridge::linesSummary ( $doc)
private

Lines of a document, as a numbered list for a message: position, product, quantity.

Parameters
CommonObject$docDocument with its lines.
Returns
string

Definition at line 5403 of file api_bridge.class.php.

References dol_trunc(), and lineName().

Referenced by normaliseLineArgs().

◆ loadApiRuntime()

ToolApiBridge::loadApiRuntime ( )
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.

Returns
void

Definition at line 2697 of file api_bridge.class.php.

Referenced by getDefinitions().

◆ loadExternalEnrichments()

ToolApiBridge::loadExternalEnrichments ( )
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.

Returns
void

Definition at line 1472 of file api_bridge.class.php.

References conf(), defaultMethods(), dol_syslog(), and user.

Referenced by __construct().

◆ methodMetaFor()

ToolApiBridge::methodMetaFor ( $toolName)
private

Find the enrichment of the method a tool name maps to.

Parameters
string$toolNameTool name (api_<endpoint>_<suffix>).
Returns
array<string,mixed> Method enrichment, or array() when unknown.

Definition at line 5792 of file api_bridge.class.php.

Referenced by applyFixedParams(), getRequiredRights(), and writeConfirmationPreview().

◆ normaliseCreateExtras()

ToolApiBridge::normaliseCreateExtras ( array $args,
array $write )
private

Arguments of a create that names a project, or gives dates or hours.

Parameters
array<string,mixed>$args Arguments, third party already resolved.
array<string,mixed>$write The 'write' enrichment of the tool.
Returns
array<string,mixed> Arguments for the REST create.

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().

◆ normaliseLineArgs()

ToolApiBridge::normaliseLineArgs ( array $args,
array $write,
array $out )
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.

Parameters
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).
Returns
array<string,mixed> Arguments for the REST method.

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().

◆ normaliseOneRecordArgs()

ToolApiBridge::normaliseOneRecordArgs ( array $args,
array $write )
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.

Parameters
array<string,mixed>$args Arguments as sent.
array<string,mixed>$write The 'write' enrichment of the tool.
Returns
array<string,mixed> Arguments with the record rowid.

Definition at line 5072 of file api_bridge.class.php.

References fetchRecord(), resolveWriteTarget(), user, and userCanReach().

Referenced by normaliseWriteArgs().

◆ normaliseTargetArgs()

ToolApiBridge::normaliseTargetArgs ( array $args,
array $write )
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.

Parameters
array<string,mixed>$args Arguments, request_data already unwrapped.
array<string,mixed>$write The 'write' enrichment of the tool.
Returns
array<string,mixed> Arguments for the REST method.

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().

◆ normaliseUpdateArgs()

ToolApiBridge::normaliseUpdateArgs ( array $args,
array $write )
private

Normalise and validate partial updates without creation defaults.

Parameters
array<string,mixed>$args Incoming arguments
array<string,mixed>$write Write metadata
Returns
array<string,mixed> Flat arguments, with a resolved parent ID
Exceptions
InvalidArgumentExceptionWhen 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().

◆ normaliseWriteArgs()

ToolApiBridge::normaliseWriteArgs ( array $args,
array $write = array() )
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.

Parameters
array<string,mixed>$args Arguments as received.
array<string,mixed>$write The 'write' enrichment of the tool.
Returns
array<string,mixed> Flat arguments with REST field names.

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().

◆ normaliseWriteLine()

ToolApiBridge::normaliseWriteLine ( array $line,
$socid,
$buy = false,
$kind = '',
$defaultWarehouse = 0 )
private

Normalise one document line: field names, product given by ref or label, default VAT rate.

Parameters
array<string,mixed>$line Line as received.
int$socidThird party of the document, 0 if unknown.
bool$buyTrue 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$defaultWarehouseWarehouse given on the header, for the lines that name none.
Returns
array<string,mixed> Line with REST field names.

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().

◆ pickOne()

ToolApiBridge::pickOne ( array $list,
$value,
array $names,
$askKey,
$missingKey,
$noneKey,
$onlyOne = true )
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.

Parameters
array<int,string[]>$list Rowid => names it is known by.
mixed$valueWhat the user said, empty when nothing.
string[]$namesNames to list when asking.
string$askKeyTranslation key when nothing was said and several exist.
string$missingKeyTranslation key when nothing fits what was said.
string$noneKeyTranslation key when the list is empty, '' to never refuse for that.
bool$onlyOneTake the only entry when nothing was said.
Returns
int Rowid, 0 when none or several fit.

Definition at line 5014 of file api_bridge.class.php.

References $id, and dol_strtolower().

Referenced by resolveBankAccount(), resolvePaymentMode(), and resolveWarehouse().

◆ precheckTargetWrite()

ToolApiBridge::precheckTargetWrite ( array $write,
array $args )
private

Why a write on an existing record cannot run, or '' when it can.

Parameters
array<string,mixed>$write The 'write' enrichment of the tool.
array<string,mixed>$args Normalised arguments.
Returns
string

Definition at line 5686 of file api_bridge.class.php.

References price().

Referenced by writePrecheck().

◆ previewLineWrite()

ToolApiBridge::previewLineWrite ( array $write,
$what )
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.

Parameters
array<string,mixed>$write The 'write' enrichment of the tool.
string$whatThe document, as describeRecord() names it.
Returns
string

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().

◆ previewLogisticLines()

ToolApiBridge::previewLogisticLines ( array $lines,
$kind )
private

The lines of a reception or shipment as the confirmation lists them: quantity, product, and for a reception the warehouse and the cost.

Parameters
array<int,mixed>$lines Normalised lines.
string$kind'reception' or 'shipment'.
Returns
string Lines, separated by semicolons.

Definition at line 4223 of file api_bridge.class.php.

References dol_trunc(), fetchBusinessObject(), and price2num().

◆ previewObjectName()

ToolApiBridge::previewObjectName ( $class,
$id )
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.

Parameters
string$classBusiness class of the linked record.
mixed$idRowid, or null.
Returns
string Readable name.

Definition at line 3613 of file api_bridge.class.php.

References $id, and fetchBusinessObject().

Referenced by writeConfirmationPreview().

◆ previewTargetWrite()

ToolApiBridge::previewTargetWrite ( array $write,
array $args )
private

Confirmation sentence of a write on an existing record.

Parameters
array<string,mixed>$write The 'write' enrichment of the tool.
array<string,mixed>$args Normalised arguments.
Returns
string

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().

◆ previewValue()

ToolApiBridge::previewValue ( array $write,
$argname,
$value,
array $args )
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.

Parameters
array<string,mixed>$write The 'write' enrichment of the tool.
string$argnameArgument name.
mixed$valueIts value, after normaliseWriteArgs().
array<string,mixed>$args All the arguments (the source of a contact).
Returns
string Text for the sentence.

Definition at line 4445 of file api_bridge.class.php.

References convertSecondToTime(), describeRecord(), dol_print_date(), fetchRecord(), and userCanReach().

Referenced by writeConfirmationPreview().

◆ projectDirectoryList()

ToolApiBridge::projectDirectoryList ( $output,
$modulepart )
private

Keep what the chat shows of the content of a directory: type, name, path, size, date, and a link for a file.

Parameters
mixed$outputResult of getDocumentsListByDirectory()
string$modulepartArea listed ('ecm' or 'medias')
Returns
mixed Projected list, or $output unchanged if it is not a list

Definition at line 5938 of file api_bridge.class.php.

References dol_print_date(), and dol_print_size().

◆ projectDocumentList()

ToolApiBridge::projectDocumentList ( $output,
$modulepart )
private

Keep what the chat shows of a file list: name, size, date and a link.

Parameters
mixed$outputResult of getDocumentsListByElement()
string$modulepartObject type the caller asked for
Returns
mixed Projected list, or $output unchanged if it is not a list

Definition at line 5903 of file api_bridge.class.php.

References dol_print_date(), and dol_print_size().

◆ projectUpdateMethod()

ToolApiBridge::projectUpdateMethod ( )
private

Describe bounded edits of an existing project.

Returns
array<string,mixed> Method enrichment

Definition at line 2664 of file api_bridge.class.php.

Referenced by __construct().

◆ purgeDefsCache()

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.

Returns
int Number of cache files deleted

Definition at line 3119 of file api_bridge.class.php.

References $conf.

◆ refOfCreatedObject()

ToolApiBridge::refOfCreatedObject ( $class,
$id )
private

Ref of a record just created, for the confirmation shown to the user.

Parameters
string$classBusiness class declared by the write.
int$idRowid returned by the API.
Returns
string Ref, or empty when it cannot be read.

Definition at line 3598 of file api_bridge.class.php.

References $id, and fetchRecord().

◆ resetWriteState()

ToolApiBridge::resetWriteState ( )
private

Forget what the previous normaliseWriteArgs() call found, so a problem of one call is never reported for the next one.

Returns
void

Definition at line 2447 of file api_bridge.class.php.

Referenced by normaliseWriteArgs().

◆ resolveBankAccount()

ToolApiBridge::resolveBankAccount ( $value)
private

Open bank account from the words of the user, or the only one there is.

Parameters
mixed$valueLabel, ref or rowid given; empty when none was said.
Returns
int Rowid, 0 when none or several fit (the reason is in writeProblems).

Definition at line 4950 of file api_bridge.class.php.

References $id, and pickOne().

Referenced by normaliseTargetArgs().

◆ resolveEndpointClass()

ToolApiBridge::resolveEndpointClass ( string $key)
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.

Parameters
string$keyEndpoint key
Returns
bool True when the class is resolved

Definition at line 2817 of file api_bridge.class.php.

Referenced by getDefinitions().

◆ resolvePaymentMode()

ToolApiBridge::resolvePaymentMode ( $value)
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.

Parameters
mixed$valueCode, label, words or rowid given.
Returns
int Rowid in c_paiement, 0 when none fits (the reason is in writeProblems).

Definition at line 4975 of file api_bridge.class.php.

References dol_strtolower(), and pickOne().

Referenced by normaliseTargetArgs().

◆ resolveUserSentinels()

ToolApiBridge::resolveUserSentinels ( array $args)
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.

Parameters
array<string,mixed>$args Tool arguments as sent.
Returns
array<string,mixed> Arguments with 'me' resolved on user fields.

Definition at line 5818 of file api_bridge.class.php.

References user.

◆ resolveWarehouse()

ToolApiBridge::resolveWarehouse ( $value)
private

Open warehouse from the words of the user, or the only one there is.

Parameters
mixed$valueName, ref or rowid given; empty when none was said.
Returns
int Rowid, 0 when none or several fit (the reason is in writeProblems).

Definition at line 4924 of file api_bridge.class.php.

References $id, and pickOne().

Referenced by normaliseTargetArgs(), normaliseWriteArgs(), and normaliseWriteLine().

◆ resolveWriteTarget()

ToolApiBridge::resolveWriteTarget ( array $write,
$value )
private

Record a targeted write is about, from the id or the words the model sent.

Parameters
array<string,mixed>$write The 'write' enrichment of the tool.
mixed$valueRowid, ref or name given by the model.
Returns
CommonObject|null Record, or null when none or several fit (the reason is in writeProblems).

Definition at line 4782 of file api_bridge.class.php.

References $c, aiFindThirdpartiesInText(), and fetchRecord().

Referenced by normaliseCreateExtras(), normaliseOneRecordArgs(), and normaliseTargetArgs().

◆ restlerPatternToJsonSchema()

ToolApiBridge::restlerPatternToJsonSchema ( string $value)
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.

Parameters
string$valueRaw tag value, e.g. "/^[0-9,]*$/i"
Returns
string JSON Schema pattern, or '' when it cannot be expressed

Definition at line 3426 of file api_bridge.class.php.

Referenced by liftInlineTags().

◆ setupAllows()

ToolApiBridge::setupAllows ( array $consts)
private

Whether one of these setup constants is on.

Parameters
string[]$constsConstant names.
Returns
bool

Definition at line 3021 of file api_bridge.class.php.

References getDolGlobalString().

Referenced by getDefinitions().

◆ setupValue()

ToolApiBridge::setupValue ( $name)
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.

Parameters
string$nameConstant name.
Returns
string Its value, or '' when not set or not loaded.

Definition at line 2436 of file api_bridge.class.php.

References getDolGlobalString().

Referenced by addWritesOnExistingRecords().

◆ shapeReadOutput()

ToolApiBridge::shapeReadOutput ( array $output,
array $meta )
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.

Parameters
array<mixed>$output Result of the REST method.
array<string,mixed>$meta Enrichment of the method.
Returns
array<mixed> Shaped result.

Definition at line 5987 of file api_bridge.class.php.

◆ socidOf()

ToolApiBridge::socidOf ( $obj)
private

Third party of a record, 0 for a record that has none (product, third party).

Parameters
CommonObject | null$objRecord.
Returns
int

Definition at line 4870 of file api_bridge.class.php.

Referenced by describeRecord(), and normaliseWriteArgs().

◆ tagValueToNumber()

ToolApiBridge::tagValueToNumber ( string $value)
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.

Parameters
string$valueNumeric tag value, already checked with is_numeric()
Returns
int|float

Definition at line 3408 of file api_bridge.class.php.

Referenced by liftInlineTags().

◆ toolGroups()

ToolApiBridge::toolGroups ( )
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.

Returns
array<string, string> Enrichment key => endpoint key

Definition at line 2873 of file api_bridge.class.php.

Referenced by getDefinitions().

◆ toolRoute()

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.

Parameters
string$nameTool name.
Returns
array{endpoint:string,method:string,suffix:string,label:string}|null Route, or null when the name is not a bridge tool.

Definition at line 6343 of file api_bridge.class.php.

◆ unitIdFromName()

ToolApiBridge::unitIdFromName ( $name)
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").

Parameters
string$nameUnit as written
Returns
int Rowid of the unit, 0 when none or several match

Definition at line 3826 of file api_bridge.class.php.

References aiUnitIdFromName().

Referenced by normaliseLineArgs(), and normaliseWriteLine().

◆ unitLabel()

ToolApiBridge::unitLabel ( $id)
private

Label of a unit, as the user reads it.

Parameters
int$idRowid of the unit, 0 for none.
Returns
string

Definition at line 5666 of file api_bridge.class.php.

References $id.

Referenced by previewLineWrite().

◆ unresolvedProductsMessage()

ToolApiBridge::unresolvedProductsMessage ( )
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.

Returns
string Message for the caller.

Definition at line 4715 of file api_bridge.class.php.

Referenced by writePrecheck().

◆ updateInputSchema()

ToolApiBridge::updateInputSchema ( array $write)
private

Schema of a partial update declared by an endpoint's write metadata.

Parameters
array<string,mixed>$write Write metadata
Returns
array<string,mixed> JSON Schema

Definition at line 3652 of file api_bridge.class.php.

Referenced by buildToolDefinition().

◆ updateMethod()

ToolApiBridge::updateMethod ( $label,
$class,
array $right,
array $fields,
$lookup )
private

Enrichment of the put method of a record: change some of its fields.

Parameters
string$labelRecord name, as the model reads it.
string$classBusiness class of the record.
string[]$rightRight needed to write.
array<string,string>$fields Fields that may be changed, with their doc.
string$lookupHow a non numeric id is found: 'thirdparty' (by name), 'ref', or '' (rowid only).
Returns
array<string,mixed> Method enrichment.

Definition at line 2465 of file api_bridge.class.php.

Referenced by addWritesOnExistingRecords().

◆ userCanReach()

ToolApiBridge::userCanReach ( $class,
$id )
private

Whether the acting user may reach a record, with the same check the REST class makes before touching it (sales representative restriction, entity).

Parameters
string$classBusiness class of the record.
int$idRowid of the record.
Returns
bool

Definition at line 4834 of file api_bridge.class.php.

References $id, checkUserAccessToObject(), and user.

Referenced by normaliseCreateExtras(), normaliseOneRecordArgs(), previewValue(), and writePrecheck().

◆ validateMethod()

ToolApiBridge::validateMethod ( $label,
$class,
$preview,
array $right,
array $fixed,
$stockconst )
private

Enrichment of the validate method of a document.

Parameters
string$labelDocument name, as the model reads it.
string$classBusiness class of the document.
string$previewTranslation key of the confirmation.
string[]$rightRight 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$stockconstConstant that makes the validation move stock, '' for none.
Returns
array<string,mixed> Method enrichment.

Definition at line 2497 of file api_bridge.class.php.

Referenced by addWritesOnExistingRecords().

◆ validateProjectUpdate()

ToolApiBridge::validateProjectUpdate ( array $args,
$parent )
private

Check resulting dates, project write access and native update side effects.

Parameters
array<string,mixed>$args Normalized update arguments
Project$parentExisting record
Returns
void
Exceptions
InvalidArgumentExceptionWhen the edit is not safe

Definition at line 3700 of file api_bridge.class.php.

References canAccessWriteObject().

Referenced by normaliseUpdateArgs().

◆ validationMovesStock()

ToolApiBridge::validationMovesStock ( array $write,
$obj )
private

Whether validating this document moves stock, so a warehouse is needed.

Parameters
array<string,mixed>$write The 'write' enrichment of the tool.
CommonObject$objDocument to validate.
Returns
bool

Definition at line 5439 of file api_bridge.class.php.

References getDolGlobalString(), and isModEnabled().

Referenced by normaliseTargetArgs().

◆ writeConfirmationPreview()

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.

Parameters
string$toolNameTool being called.
array<string,mixed>$args Arguments as received.
Returns
string Preview sentence, or McpTool\NO_WRITE.

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().

◆ writeDate()

ToolApiBridge::writeDate ( $field,
$value,
$gmt = 1 )
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.

Parameters
string$fieldField name, for the message.
mixed$valueDate as written.
int$gmt1 to read it in GMT (logistic dates), 0 in the server time zone.
Returns
int|null Timestamp, or null when empty or unreadable.

Definition at line 4197 of file api_bridge.class.php.

References dol_stringtotime().

Referenced by normaliseCreateExtras(), normaliseLineArgs(), normaliseWriteArgs(), and normaliseWriteLine().

◆ writeDefsCache()

ToolApiBridge::writeDefsCache ( string $cachefile)
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.

Parameters
string$cachefileTarget file from defsCacheFile()
Returns
void

Definition at line 3094 of file api_bridge.class.php.

Referenced by getDefinitions().

◆ writeMetaFor()

ToolApiBridge::writeMetaFor ( $toolName)
private

The 'write' enrichment of a tool, when it has one.

Parameters
string$toolNameTool name as exposed.
Returns
array<string,mixed> Empty when the tool is a read.

Definition at line 5779 of file api_bridge.class.php.

Referenced by writeConfirmationPreview(), and writePrecheck().

◆ 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:

  • a document for a third party that is missing, unknown, or that several third parties fit (the API would answer "Thirdparty with id=0 not found");
  • a line for a record that is missing or no longer a draft, or for an unknown product.
Parameters
string$toolNameTool being called.
array<string,mixed>$args Arguments as received.
Returns
string Error message, or '' to proceed.

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().

Member Data Documentation

◆ BRIDGE_DEFAULT_LIMIT

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.

◆ ENDPOINT_CATEGORIES

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.


The documentation for this class was generated from the following file: