Skip to main content
Version: v5.1

IafAISvc

Use the IafAISvc API to create and manage the AISvc service resources, such as agents, tools, teams and creating conversations.

createAgents#

Creates one or more Agent resource.

ParameterRequiredTypeDescription
agentsYesArray<Agent>Pass an array of Agent objects you define.
ctxNoCtxContext, such as namespaces and authentication token information.
optionsNoObjectPass a JSON object for optional query parameters.
Returns

Promise<Page<Agent>> - A promise with the created Agent objects.

Examples
const agents = [  {    _namespaces: ['building_1234'],    _name: 'HVAC Monitoring Agent',    _background: 'Monitors HVAC system performance and detects anomalies.',    _userType: 'hvac_monitor_agent',    _tools: ['temperature_sensor_tool', 'energy_usage_tool'],    // Note: persisted internally by AISvc as `agent.external_mcp_servers`.    _externalMcpServers: [      {        _userType: 'github_mcp',        _filter: { _names: ['search_repositories', 'list_issues'] }      }    ],    _agentClass: 'HVACMonitoringAgent', // applicable only when Agent have custom source code    _config: {_model: "gpt-4o",_provider: "openai"}  },  {    _namespaces: ['building_1234'],    _name: 'Lighting Optimization Agent',    _background: 'Optimizes lighting schedules based on occupancy and daylight levels.',    _userType: 'lighting_opt_agent',    _externalMcpServers: [      { _userType: 'github_mcp' }    ],_config: {_model: "gpt-4o",_provider: "openai"}  },];
IafAISvc.createAgents(agents, ctx, options);

createConversation#

Creates a new conversation or continues an existing one.

ParameterRequiredTypeDescription
requestYesConversationCreateRequestThe conversation create request object.
ctxNoCtxContext, such as namespaces and authentication token information.
optionsNoOptionsJSON object for optional query parameters.
Returns

Promise<Conversation> - A promise with the Conversation object.

Examples
//1. Create a new conversation with an initial messageconst request = {  _teamId: 'f73d1653-bf1d-4f00-ad58-543ac48f80a3',  _input: { message: 'List all doors that are not compliant with Dutch standards.' }};const conversation = await IafAISvc.createConversation(request, ctx);
//2. Create a new conversation with continuation of an existing conversationconst request = {  _teamId: 'f73d1653-bf1d-4f00-ad58-543ac48f80a3',  _input: { message: 'Filter to show only entrance doors.' },  _id: '94a1eb2b-06bd-426e-a3ce-e7ab609ea231' // existing conversation id for continuation};const conversation = await IafAISvc.createConversation(request, ctx);
//3. Create a new conversation with MCP serverconst request = { _teamId: 'f73d1653-bf1d-4f00-ad58-543ac48f80a3',_input: { message: 'Retrieve all entrance doors and compare their open/closed status with the outside temperature. Return the doors where the outside temperature is below 5°C and the door has remained open for more than 2 minutes.' },_externalMcpAuthTokens: [{ _userType: 'openapi_weather', _token: 'a454abe5635ssw345s23' }]};const conversation = await IafAISvc.createConversation(request, ctx);

createExternalMcpServerConfigs#

Creates one or more External MCP Server Config resources.

ParameterRequiredTypeDescription
externalMcpServerConfigsYesArray<ExternalMcpServerConfig>Array of External MCP Server Config definitions.
ctxNoCtxContext, such as namespaces and authentication token information.
optionsNoObjectOptional control parameters such as pagination hints.
Returns

Promise<Page<ExternalMcpServerConfig>> - A promise with the created External MCP Server Config objects.

Examples
const configs = [  {    _namespaces: ['building_1234'],    _name: 'Open Weather MCP Server',    _userType: 'open_weather_mcp_server',    _connection: {      _url: 'https://mcp.open-mcp.org/api/server/open-weather@latest/mcp',      _headers: { Authorization: { type: 'secret', value: 'OPEN_WEATHER_API_KEY' } }    }  }];await IafAISvc.createExternalMcpServerConfigs(configs, ctx);

createKnowledgeBases#

Creates one or more KnowledgeBase resources in a single transaction.

ParameterRequiredTypeDescription
knowledgeBasesYesArray<KnowledgeBase>Array of KnowledgeBase objects to create. Pass a one-element array to create a single entry.
ctxNoCtxContext, such as namespaces and authentication token information.
optionsNoObjectOptional control parameters (e.g., pagination or query hints).
Returns

Promise<Page<KnowledgeBase>> - A promise with the created KnowledgeBase objects. If any creation fails, nothing is persisted.

Examples
const knowledgeBases = [  { _name: 'Warranty Docs', _fileId: '94a1eb2b-06bd-426e-a3ce-e7ab609ea231', _fileVersionId: '35a1ab2c-16bd-426e-b3ce-a7ab609ea482', _userType: 'warranty_documents', _namespaces: ['ws1'] },  { _name: 'Training Material', _fileId: '14b1db2b-16cd-426e-b3ce-c3ab609ea912', _fileVersionId: '51b1db2b-26cd-426e-b3ce-c3ab609ea913', _userType: 'training_materials', _namespaces: ['ws1'] }];await IafAISvc.createKnowledgeBases(knowledgeBases, ctx);

createMcpToolFilters#

Creates one or more MCP Tool Filter resources.

ParameterRequiredTypeDescription
mcpToolFiltersYesArray<McpToolFilter>Array of MCP Tool Filter definitions that control tool visibility.
ctxNoCtxContext, such as namespaces and authentication token information.
optionsNoObjectOptional control parameters such as pagination hints.
Returns

Promise<Page<McpToolFilter>> - A promise with the created MCP Tool Filter objects.

Examples
const filters = [  {    _namespaces: ['building_1234'],    _name: 'search-by-name',    _description: 'Filters tools that support name based lookup',    _userType: 'search_tool_filter',    _criteria: {      _name: { $regex: '.*search.*' }    }  }];await IafAISvc.createMcpToolFilters(filters, ctx);

createMcpTools#

Creates one or more MCP Tool resources.

ParameterRequiredTypeDescription
mcpToolsYesArray<McpTool>Array of MCP Tool definitions that describe the MCP wrapper for an existing script.
ctxNoCtxContext, such as namespaces and authentication token information.
optionsNoObjectOptional control parameters such as pagination hints..
Returns

Promise<Page<McpTool>> - A promise with the created MCP Tool objects.

Examples
const mcpTools = [  {    _namespaces: ['building_1234'],    _name: 'AssetLookupMcpTool',    _description: 'Wraps an existing script that searches for assets.',    _schema: {      type: 'object',      properties: {        query: { type: 'string', description: 'Free-text string used to match asset names, tags, or metadata.' },        maxResults: { type: 'number', description: 'Optional maximum number of assets to return.' }      },      required: ['query']    },    _script: { _userType: 'asset_scripts', _scriptName: 'assetLookup' }  }];await IafAISvc.createMcpTools(mcpTools, ctx);

createPermissions#

Creates permissions for AISvc resources such as Agents, Tools, Teams, and Conversations.

ParameterRequiredTypeDescription
permissionsYesArray<Permission>Pass an array of Permission objects.
ctxNoCtxContext, such as authorization token requirements, namespaces, or session storage.
Returns

Promise<CreatePermissionsResponse> - A CreatePermissionsResponse object that contains the successful and failed permissions in separate arrays.

createTeam#

Creates a Team resource.

ParameterRequiredTypeDescription
teamYesTeamPass a Team object you define.
ctxNoCtxContext, such as namespaces and authentication token information.
optionsNoObjectOptional control parameters, such as pagination options.
Returns

Promise<Team> - A promise with the created Team object.

Examples
const teamObj = {"_name": "SP - Telemetry Fetcher Team - new","_agents": [{ "_userType": "sp_telemetry_fetcher" },{ "_userType": "sp_anamoly_pressure_checker" }],"_flow": [{ "to": "sp_telemetry_fetcher", "from": "__start__" },{ "to": "sp_anamoly_pressure_checker", "from": "sp_telemetry_fetcher" },{ "to": "__end__", "from": "sp_anamoly_pressure_checker" }],"_namespaces": ["Amoghtestworkspace_m8NrvPU3"]}

createTools#

Creates one or more Tool resource.

ParameterRequiredTypeDescription
toolsYesArray<Tool>Pass an array of Tool objects you define.
ctxNoCtxContext, such as namespaces and authentication token information.
optionsNoObjectPass a JSON object for optional query parameters.
Returns

Promise<Page<Tool>> - A promise with the created Tool objects.

Examples
const tools = [  {    _namespaces: ['building_1234'],    _name: 'Temperature Sensor Tool',    _description: 'Provides real-time temperature readings.',    _userType: 'temperature_sensor_tool',    _toolClass: 'TemperatureSensorTool',  },  {    _namespaces: ['building_1234'],    _name: 'Energy Usage Tool',    _description: 'Calculates energy consumption patterns.',    _userType: 'energy_usage_tool',  },];
IafAISvc.createTools(tools, ctx, options);

deleteAgent#

Deletes an Agent resource .

ParameterRequiredTypeDescription
idYesStringPass the Agent's id.
ctxNoCtxContext, such as namespaces and authentication token information.
Returns

Promise<String> - {ok:204} response.

Examples
await IafAISvc.deleteAgent('e8a53325-fbb5-4a2d-a955-ef5fa74591df', ctx);

deleteExternalMcpServerConfig#

Deletes an External MCP Server Config resource.

ParameterRequiredTypeDescription
idYesStringThe External MCP Server Config id.
ctxNoCtxContext, such as namespaces and authentication token information.
Returns

Promise<String> - {ok:204} response.

Examples
await IafAISvc.deleteExternalMcpServerConfig(configId, ctx);

deleteKnowledgeBase#

Deletes a KnowledgeBase resource.

ParameterRequiredTypeDescription
idYesStringThe KnowledgeBase id.
ctxNoCtxContext, such as namespaces and authentication token information.
Returns

Promise<String> - ok:204 response.

Examples
await IafAISvc.deleteKnowledgeBase('94a1eb2b-06bd-426e-a3ce-e7ab609ea231', ctx);

deleteMcpTool#

Deletes an MCP Tool resource by id.

ParameterRequiredTypeDescription
idYesStringThe MCP Tool's id.
ctxNoCtxContext, such as namespaces and authentication token information.
Returns

Promise<String> - {ok:204} response.

Examples
const toolId = 'd8a53325-dbb5-4a2d-a655-ef5fa74591d3';await IafAISvc.deleteMcpTool(toolId, ctx);

deleteMcpToolFilter#

Deletes an MCP Tool Filter resource.

ParameterRequiredTypeDescription
idYesStringThe MCP Tool Filter id.
ctxNoCtxContext, such as namespaces and authentication token information.
Returns

Promise<String> - {ok:204} response.

Examples
await IafAISvc.deleteMcpToolFilter(filterId, ctx);

deletePermission#

Deletes a permission when you pass its id.

ParameterRequiredTypeDescription
idYesStringThe Permission object's id.
ctxNoCtxContext, such as authorization token requirements, namespaces, or session storage.
Returns

Promise<String> - ok:204 response.

deleteTeam#

Deletes a Team resource.

ParameterRequiredTypeDescription
idYesStringPass the Team's id.
ctxNoCtxContext, such as namespaces and authentication token information.
Returns

Promise<String> - {ok:204} response.

deleteTool#

Deletes a Tool resource.

ParameterRequiredTypeDescription
idYesStringPass the Tool's id.
ctxNoCtxContext, such as namespaces and authentication token information.
Returns

Promise<String> - {ok:204} response.

Examples
await IafAISvc.deleteTool('a8a53325-dbb5-4a2d-a655-ef5fa74591d3', ctx);

getAgent#

Gets an Agent resource object by its id.

ParameterRequiredTypeDescription
idYesStringPass the Agent's id.
ctxNoCtxContext, such as namespaces and authentication token information.
Returns

Promise<Agent> - A promise with the Agent object.

Examples
const agent = await IafAISvc.getAgent('e8a53325-fbb5-4a2d-a955-ef5fa74591df', ctx);

getAgents#

Gets Agent resource objects that match your criteria in the namespace, It also lists down system agents as well

ParameterRequiredTypeDescription
criteriaNoAgentCriteriaPass a JSON object with filter parameters, such as "_userType" or "query".
ctxNoCtxContext, such as namespaces and authentication token information.
optionsNoAisvcOptionsPass a JSON object for optional control parameters, such as pagination options.
Returns

Promise<Page<Agent>> - A promise with a page that contains the Agent objects.

Examples
// Get all agentsconst allAgents = await IafAISvc.getAgents({}, ctx);
// Get agents by userTypeconst hvacAgents = await IafAISvc.getAgents({ _userType: 'hvac_monitor_agent' }, ctx, { _pageSize: 50 });

getAgentSourceCode#

Retrieves source code for an Agent resource.

ParameterRequiredTypeDescription
agentIdYesStringThe Agent's id.
ctxNoCtxContext, such as namespaces and authentication token information.
Returns

Promise<SourceCode> - A Promise resolving to the Agent's SourceCode.

Examples
const agentCode = await IafAISvc.getAgentSourceCode('1201ae31-d2c3-4428-8122-17cd4ce802f3', ctx);

getConversation#

Gets a Conversation resource by its id.

ParameterRequiredTypeDescription
idYesStringPass the Conversation's id.
ctxNoCtxContext, such as namespaces and authentication token information.
optionsNoConversationOptionsJSON object for optional query parameters.
Returns

Promise<Conversation> - A promise with the Conversation object.

getConversations#

Gets Conversation objects in the namespace

ParameterRequiredTypeDescription
criteriaNoJSONPass a JSON object with filter parameters, Currently no criteria supported
ctxNoCtxContext, such as namespaces and authentication token information.
optionsNoAisvcOptionsPass a JSON object for optional control parameters, such as pagination options.
Returns

Promise<Page<Conversation>> - A promise with a page that contains the Agent objects.

Examples
// Get all conversationsconst conversations = await IafAISvc.getConversations({ }, ctx, { _pageSize: 50 });

getExternalMcpServerConfig#

Gets an External MCP Server Config resource object by its id.

ParameterRequiredTypeDescription
idYesStringThe External MCP Server Config id.
ctxNoCtxContext, such as namespaces and authentication token information.
Returns

Promise<ExternalMcpServerConfig> - A promise with the External MCP Server Config object.

Examples
const config = await IafAISvc.getExternalMcpServerConfig('d8a53325-dbb5-4a2d-a655-ef5fa74591d3', ctx);

getExternalMcpServerConfigs#

Gets External MCP Server Config resource objects that match your criteria.

ParameterRequiredTypeDescription
criteriaNoExternalMcpServerConfigCriteriaFilter parameters such as namespace, _name, or query.
ctxNoCtxContext, such as namespaces and authentication token information.
optionsNoAisvcOptionsOptional control parameters, such as pagination options.
Returns

Promise<Page<ExternalMcpServerConfig>> - A promise with a page that contains the External MCP Server Config objects.

Examples
const page = await IafAISvc.getExternalMcpServerConfigs({ namespace: 'building_1234' }, ctx, { _pageSize: 25 });

getKnowledgeBase#

Gets a KnowledgeBase resource by its id.

ParameterRequiredTypeDescription
idYesStringThe KnowledgeBase id.
ctxNoCtxContext, such as namespaces and authentication token information.
Returns

Promise<KnowledgeBase> - A promise with the KnowledgeBase object.

Examples
const kb = await IafAISvc.getKnowledgeBase('94a1eb2b-06bd-426e-a3ce-e7ab609ea231', ctx);

getKnowledgeBases#

Gets KnowledgeBase resources matching criteria.

ParameterRequiredTypeDescription
criteriaNoKnowledgeBaseCriteriaFilter parameters (e.g., _userType, _vectorizedStatus).
ctxNoCtxContext, such as namespaces and authentication token information.
optionsNoAisvcOptionsOptional control parameters like pagination.
Returns

Promise<Page<KnowledgeBase>> - A promise with a page of KnowledgeBase objects.

Examples
const page = await IafAISvc.getKnowledgeBases({ _userType: 'warranty_documents' }, ctx, { _pageSize: 50 });

getLlmModels#

Gets the available LLM models for a provider.Note: AISvc requires the query param for namespace-scoped requests.

ParameterRequiredTypeDescription
criteriaYesObjectFilter parameters.
ctxNoCtxContext, such as namespaces and authentication token information.
optionsNoAisvcOptionsOptional control parameters.
Returns

Promise<Page<LlmModel>> - A promise with a page that contains the provider model list.

Examples
const page = await IafAISvc.getLlmModels({ provider: 'openai', nsfilter: 'building_1234' }, ctx);

getLlmProviders#

Gets the available LLM providers.

ParameterRequiredTypeDescription
criteriaNoObjectFilter criteria.
ctxNoCtxContext, such as namespaces and authentication token information.
optionsNoAisvcOptionsOptional control parameters.
Returns

Promise<Page<Object>> - A promise with a page that contains the provider list.

Examples
const page = await IafAISvc.getLlmProviders({}, ctx);

getMcpTool#

Gets an MCP Tool resource object by its id.

ParameterRequiredTypeDescription
idYesStringThe MCP Tool's id.
ctxNoCtxContext, such as namespaces and authentication token information.
Returns

Promise<McpTool> - A promise with the MCP Tool object.

Examples
const tool = await IafAISvc.getMcpTool('d8a53325-dbb5-4a2d-a655-ef5fa74591d3', ctx);

getMcpToolFilter#

Gets an MCP Tool Filter resource object by its id.

ParameterRequiredTypeDescription
idYesStringThe MCP Tool Filter id.
ctxNoCtxContext, such as namespaces and authentication token information.
Returns

Promise<McpToolFilter> - A promise with the MCP Tool Filter object.

Examples
const filter = await IafAISvc.getMcpToolFilter('d8a53325-dbb5-4a2d-a655-ef5fa74591d3', ctx);

getMcpToolFilters#

Gets MCP Tool Filter resource objects that match your criteria.

ParameterRequiredTypeDescription
criteriaNoGetMcpToolFilterCriteriaFilter parameters such as _name, _userType, or query.
ctxNoCtxContext, such as namespaces and authentication token information.
optionsNoAisvcOptionsOptional control parameters, such as pagination options.
Returns

Promise<Page<McpToolFilter>> - A promise with a page that contains the MCP Tool Filter objects.

Examples
const page = await IafAISvc.getMcpToolFilters({ _userType: 'search_tool_filter' }, ctx, { _pageSize: 25 });

getMcpTools#

Gets MCP Tool resource objects that match your criteria.

ParameterRequiredTypeDescription
criteriaNoMcpToolCriteriaQuery filters. Supported keys: _name, _type, _toolConfig._serviceName, _script._userType, _script._scriptName, filter, query. When filter is provided, AISvc ignores other criteria fields.
ctxNoCtxContext, such as namespaces and authentication token information.
optionsNoAisvcOptionsOptional control parameters, such as pagination options.
Returns

Promise<Page<McpTool>> - A promise with a page that contains the MCP Tool objects.

Examples
const page = await IafAISvc.getMcpTools({ _type: 'user_mcp_tool' }, ctx, { _pageSize: 25 });// Get MCP Tools by script userTypeconst userTypeMatch = await IafAISvc.getMcpTools({ '_script._userType': 'asset_scripts' }, ctx);

getPermissions#

Gets permissions for AISvc resources.

ParameterRequiredTypeDescription
criteriaYesPermissionCriteriaPass a PermissionCriteria object with the properties and values to filter your search.
ctxNoCtxContext, such as authorization token requirements, namespaces, or session storage.
Returns

Promise<Page<Permission>> - A Page object with the Permission objects you want.

getTeam#

Gets a Team resource object by its id.

ParameterRequiredTypeDescription
idYesStringPass the Team's id.
ctxNoCtxContext, such as namespaces and authentication token information.
Returns

Promise<Team> - A promise with the Team object.

getTeams#

Gets Team resource objects that match your criteria.

ParameterRequiredTypeDescription
criteriaNoTeamCriteriaPass a JSON object with filter parameters, such as "_name" or "query".
ctxNoCtxContext, such as namespaces and authentication token information.
optionsNoAisvcOptionsControl parameters, such as pagination options.
Returns

Promise<Page<Team>> - A promise with a page that contains the Team objects.

getTool#

Gets a Tool resource object by its id.

ParameterRequiredTypeDescription
idYesStringPass the Tool's id.
ctxNoCtxContext, such as namespaces and authentication token information.
Returns

Promise<Tool> - A promise with the Tool object.

Examples
const tool = await IafAISvc.getTool('a8a53325-dbb5-4a2d-a655-ef5fa74591d3', ctx);

getTools#

Gets Tool resource objects that match your criteria.

ParameterRequiredTypeDescription
criteriaNoToolCriteriaPass a JSON object with filter parameters, such as "_userType" or "query".
ctxNoCtxContext, such as namespaces and authentication token information.
optionsNoAisvcOptionsPass a JSON object for optional control parameters, such as pagination options.
Returns

Promise<Page<Tool>> - A promise with a page that contains the Tool objects.

Examples
// Get all toolsconst allTools = await IafAISvc.getTools({}, ctx);
// Get tools by userTypeconst sensorTools = await IafAISvc.getTools({ _userType: 'temperature_sensor_tool' }, ctx, { _pageSize: 50 });

getToolSourceCode#

Retrieves source code for a Tool resource.

ParameterRequiredTypeDescription
toolIdYesStringThe Tool's id.
ctxNoCtxContext, such as namespaces and authentication token information.
Returns

Promise<SourceCode> - A Promise resolving to the Tool's SourceCode.

Examples
const toolCode = await IafAISvc.getToolSourceCode('tool-id-1234', ctx);

updateAgent#

Updates an existing Agent resource. Editable fields: _name, _background, _userType, _tools, _externalMcpServers, _agentClass.

ParameterRequiredTypeDescription
idYesStringPass the Agent's id.
agentYesAgentPass an Agent object with the properties you want to update.
ctxNoCtxContext, such as namespaces and authentication token information.
Returns

Promise<Agent> - A promise with the updated Agent object.

Examples
const updates = {  _name: 'Updated Agent Name',  _background: 'Updated background context.',  _tools: ['new_tool_type'],  // Note: persisted internally by AISvc as `agent.external_mcp_servers`.  _externalMcpServers: [    { _userType: 'github_mcp', _filter: { _names: ['search_repositories'] } }  ],_config: {_model: "gpt-4o",_provider: "openai"}};const updatedAgent = await IafAISvc.updateAgent('e8a53325-fbb5-4a2d-a955-ef5fa74591df', updates, ctx);

updateExternalMcpServerConfig#

Updates an existing External MCP Server Config resource.

ParameterRequiredTypeDescription
idYesStringThe External MCP Server Config id.
externalMcpServerConfigYesExternalMcpServerConfigExternal MCP Server Config object with the properties you want to update.
ctxNoCtxContext, such as namespaces and authentication token information.
Returns

Promise<ExternalMcpServerConfig> - A promise with the updated External MCP Server Config object.

Examples
const updated = await IafAISvc.updateExternalMcpServerConfig(configId, {    _namespaces: ['building_1234'],    _name: 'Open Weather MCP Server Updated',    _userType: 'open_weather_mcp_server',    _connection: {      _url: 'https://mcp.open-mcp.org/api/server/open-weather@latest/mcp',      _headers: { Authorization: { type: 'secret', value: 'OPEN_WEATHER_API_KEY' } }    }  }, ctx);

updateKnowledgeBase#

Updates an existing KnowledgeBase resource. Editable fields: _name, _userType.

ParameterRequiredTypeDescription
idYesStringThe KnowledgeBase id.
knowledgeBaseYesKnowledgeBaseKnowledgeBase object with updated properties.
ctxNoCtxContext, such as namespaces and authentication token information.
Returns

Promise<KnowledgeBase> - A promise with the updated KnowledgeBase object.

Examples
const updates = { _name: 'Updated Name',_fileId: '15a1ac2b-96ba-626e-b3ce-e7ab609ea612', _fileVersionId: '55a1bc2a-06bb-923e-a3cd-a7ab609ea609'};await IafAISvc.updateKnowledgeBase('94a1eb2b-06bd-426e-a3ce-e7ab609ea231', updates, ctx);

updateMcpTool#

Updates an existing user MCP Tool resource.

ParameterRequiredTypeDescription
idYesStringThe MCP Tool's id.
mcpToolYesMcpToolMCP Tool object with the properties you want to update.
ctxNoCtxContext, such as namespaces and authentication token information.
Returns

Promise<McpTool> - A promise with the updated MCP Tool object.

Examples
const toolId = 'd8a53325-dbb5-4a2d-a655-ef5fa74591d3';const updatedMcpPlayoad={  _namespaces: ['building_1234'],  _name: 'AssetLookupMcpTool_Updated',  _description: 'Searches assets by tag',  _schema: {      type: 'object',      properties: {        query: { type: 'string', description: 'Free-text string used to match asset names, tags, or metadata.' },        maxResults: { type: 'number', description: 'Optional maximum number of assets to return.' }      },      required: ['query']    },  _script: { _userType: 'asset_scripts', _scriptName: 'assetLookup' }}const updatedTool = await IafAISvc.updateMcpTool(toolId,updatedMcpPlayoad, ctx);

updateMcpToolFilter#

Updates an existing MCP Tool Filter resource. Editable fields: _name, _description, _namespaces, _userType, _criteria.

ParameterRequiredTypeDescription
idYesStringThe MCP Tool Filter id.
mcpToolFilterYesMcpToolFilterMCP Tool Filter object with the properties you want to update.
ctxNoCtxContext, such as namespaces and authentication token information.
Returns

Promise<McpToolFilter> - A promise with the updated MCP Tool Filter object.

Examples
const updated = await IafAISvc.updateMcpToolFilter(filterId, {  _description: 'Updated description',  _criteria: { _serviceName: { $in: ['IafItemSvc'] } }}, ctx);

updatePermissions#

Updates permissions for AISvc resources. If a permission you pass doesn't exist, the method creates the permission.

ParameterRequiredTypeDescription
permissionsYesArray<Permission>Pass an array of Permission objects.
ctxNoCtxContext, such as authorization token requirements, namespaces, or session storage.
Returns

Promise<CreatePermissionsResponse> -

updateTeam#

Updates an existing Team resource. Editable fields: _name, _agents, _flow.

ParameterRequiredTypeDescription
idYesStringPass the Team's id.
teamYesObjectPass a Team object with the properties you want to update.
ctxNoCtxContext, such as namespaces and authentication token information.
Returns

Promise<Team> - A promise with the updated Team object.

updateTool#

Updates an existing Tool resource. Editable fields: _name, _description, _userType, _toolClass.

ParameterRequiredTypeDescription
idYesStringPass the Tool's id.
toolYesToolPass a Tool object with the properties you want to update.
ctxNoCtxContext, such as namespaces and authentication token information.
Returns

Promise<Tool> - A promise with the updated Tool object.

Examples
const updates = {  _description: 'Updated description.',  _toolClass: 'AdvancedEnergyTool',};const updatedTool = await IafAISvc.updateTool('a8a53325-dbb5-4a2d-a655-ef5fa74591d3', updates, ctx);

uploadAgentSourceCode#

Uploads source code for an Agent resource.

ParameterRequiredTypeDescription
agentIdYesStringThe Agent's id.
sourceCodeYesSourceCodeObject containing source code (_content and optional _id).
ctxNoCtxContext, such as namespaces and authentication token information.
optionsYesundefined
Returns

Promise<SourceCode> - A Promise resolving to the uploaded SourceCode.

Examples
//Upload source code as stringconst sourceCode = { "_content": "import { Agent } from '@dtplatform/agent-core';\nimport { IafItemSvc } from '@dtplatform/platform-api';\n\ninterface ChillerRequest {\n    chillerId: string;\n    capacityKw: number;\n    metric: string; // e.g. \"chiller_load_kw\"\n    thresholdPct: number; // e.g. 0.9 for 90%\n    lookbackDays?: number;\n}\n\ntype Reading = {\n  _id: string;\n  _ts: string; // timestamp in UTC\n  chiller_load_kw: number;\n  chiller_load_pct: number;\n};\n\ntype Data = {\n  _list: Reading[];\n};\n\nexport default class ChillerForecastAgent extends Agent {\n    requestContext: any = {}\n    constructor(options: any, requestContext: any) {\n        super(options);\n        this.requestContext = requestContext;\n    }\n\n    async processRequest(\n        type: string,\n        state?: any,\n        prompt?: string,\n        tools?: any[],\n        userId?: string,\n        sessionId?: string,\n        chatHistory?: [],\n        additionalParams?: Record<string, string>,\n    ): Promise<any> {\n\n        // ------------------------------\n        // 1. Interpret prompt (simple parsing via LLM)\n        // ------------------------------\n        const llmRes: any = await this.simpleCall(`Extract structured JSON from the following prompt. \n            Fields: chillerId and lookbackDays (optional).\n            Prompt: ${prompt}`);\n\n        //console.log(llmRes, \">>llmRes\")\n        console.log(llmRes?.content, \">>llmRes?.content\")\n\n        let chillerReq: ChillerRequest;\n\n        try {\n            let rawContent: string = llmRes?.content || \"\";\n\n            // Remove Markdown code fences if they exist\n            rawContent = rawContent.replace(/```json|```/gi, \"\").trim();\n\n            // Try to extract JSON block if extra text is present\n            const jsonMatch = rawContent.match(/\{[\s\S]*\}/);\n            if (jsonMatch) {\n                rawContent = jsonMatch[0];\n            }\n\n            chillerReq = JSON.parse(rawContent);\n\n        } catch (err) {\n            console.error(\"Failed to parse chiller request:\", err);\n            return {\n                messages: [\n                    {\n                        role: \"assistant\",\n                        content: JSON.stringify({ error: \"Invalid LLM JSON response\", raw: llmRes })\n                    }\n                ]\n            };\n        }\n\n        const lookback = chillerReq.lookbackDays ?? 90;\n        const startDate = new Date();\n        startDate.setDate(startDate.getDate() - lookback);\n\n        const aggs = [\n            {\n                $match: {\n                    \"_tsMetadata._sourceId\": { \"$regex\": `.*${chillerReq.chillerId}.*` } ,\n                    \"_ts\": { $gte: startDate.toISOString() }\n                }\n            },\n            { $sort: { ts: 1 } },\n            { $limit: 10 }\n\n        ];\n\n        console.log('Aggs::', JSON.stringify(aggs))\n        \n        let res = await IafItemSvc.aggregateReadings('68c50a58993fee0ea750db6f', aggs, this.requestContext, {});\n        let finalRes = this.predictChiller90(res);\n        console.log(finalRes, 'finalRes')\n        return {\n            messages: [\n                {\n                    role: \"assistant\",\n                    content: `Chiller will cross 90% load around:\", ${finalRes}`\n                }\n            ]\n        };\n    }\n\n\n    predictChiller90(data: Data): Date | null {\n        // Step 1: clean duplicates by unique timestamp\n        const readings: Reading[] = Object.values(\n            data._list.reduce<Record<string, Reading>>((acc, item) => {\n            acc[item._ts] = item; // overwrite duplicates\n            return acc;\n            }, {})\n        );\n\n        if (readings.length < 2) return null; // not enough data to predict\n\n        // Step 2: sort by timestamp\n        readings.sort((a, b) => new Date(a._ts).getTime() - new Date(b._ts).getTime());\n\n        // Step 3: convert timestamps to epoch ms\n        const points = readings.map(r => ({\n            ts: new Date(r._ts).getTime(),\n            load: r.chiller_load_pct\n        }));\n\n        // Step 4: calculate slope & intercept (linear regression)\n        const n = points.length;\n        const sumX = points.reduce((s, p) => s + p.ts, 0);\n        const sumY = points.reduce((s, p) => s + p.load, 0);\n        const sumXY = points.reduce((s, p) => s + p.ts * p.load, 0);\n        const sumX2 = points.reduce((s, p) => s + p.ts * p.ts, 0);\n\n        const denominator = n * sumX2 - sumX * sumX;\n        if (denominator === 0) return null; // avoid division by zero\n\n        const slope = (n * sumXY - sumX * sumY) / denominator;\n        const intercept = (sumY - slope * sumX) / n;\n\n        // Step 5: solve for timestamp when load = 0.9\n        const targetLoad = 0.9;\n        const targetTs = (targetLoad - intercept) / slope;\n\n        if (isNaN(targetTs) || !isFinite(targetTs)) return null;\n\n        return new Date(targetTs);\n    }\n\n}\n"};await IafAISvc.uploadAgentSourceCode('1201ae31-d2c3-4428-8122-17cd4ce802f3', sourceCode, ctx);
//Upload source code as fileconst sourceCode = {_file:fileStream};await IafAISvc.uploadAgentSourceCode('1201ae31-d2c3-4428-8122-17cd4ce802f3', sourceCode, ctx);

uploadToolSourceCode#

Uploads source code for a Tool resource.

ParameterRequiredTypeDescription
toolIdYesStringThe Tool's id.
sourceCodeYesSourceCodeObject containing source code (_content and optional _id).
ctxNoCtxContext, such as namespaces and authentication token information.
optionsYesundefined
Returns

Promise<SourceCode> - A Promise resolving to the uploaded SourceCode.

Examples
//Upload source code as Stringconst sourceCode = { _content: "import { AbstractTool } from '@dtplatform/agent-core';\nimport * as PlatformAPI from '@dtplatform/platform-api';\nconst { IafItemSvc } = PlatformAPI;\nimport { z } from 'zod';\n\nconst toolSchema = z.object({\n  name: z.string().optional().nullable().describe('Filter by asset name. Supports regex'),\n  dtCategory: z.string().optional().nullable().describe('Filter by the dtCategory property. Supports regex'),\n  dtType: z.string().optional().nullable().describe('Filter by dtType property. Supports regex'),\n  _pageSize: z.string().optional().nullable().describe('Sets the number of results to return per Page in the response'),\n  _offset: z.string().optional().nullable().describe('Sets the number of results to skip in the Page response. For example, set to `10` to skip the first 10 results.')\n});\n\nexport default class GetAssetsTool extends AbstractTool {\n  name: string = 'GetAssetsTool';\n  description: string = 'Helps to retrieve Assets based on the provided criteria.';\n  requestContext: any = {};\n  schema: any = toolSchema;\n\n  constructor(...args: any[]) {\n    super(...args);\n    const [{ requestContext }] = args;\n    this.requestContext = requestContext;\n  }\n\n  async _call(args: z.infer<typeof toolSchema>) {\n    let criteria: any = { '$or': [] };\n    let options: any = {};\n    let response: any = {};\n\n    if (args.name || args.dtCategory || args.dtType) {\n      if (args.name) {\n        criteria['$or'].push({\n          'Asset Name': {\n            '$regex': this.toRegexString(args.name),\n            '$options': 'i'\n          }\n        });\n      }\n      if (args.dtCategory) {\n        criteria['$or'].push({\n          'properties.dtCategory.val': {\n            '$regex': this.toRegexString(args.dtCategory),\n            '$options': 'i'\n          }\n        });\n      }\n      if (args.dtType) {\n        criteria['$or'].push({\n          'properties.dtType.val': {\n            '$regex': this.toRegexString(args.dtType),\n            '$options': 'i'\n          }\n        });\n      }\n\n      if (args._pageSize) {\n        options['_pageSize'] = parseInt(args._pageSize, 10);\n      }\n      if (args._offset) {\n        options['_offset'] = parseInt(args._offset, 10);\n      }\n\n      let colQuery = {\n        query: {\n          _userType: 'iaf_ext_asset_coll',\n          _itemClass: 'NamedUserCollection'\n        }\n      };\n\n      const colOptions = {\n        project: { _userType: 1, _itemClass: 1 },\n        sort: { _name: 1 },\n        page: { _offset: 0, _pageSize: 1 }\n      };\n\n      const colResponse = await IafItemSvc.getNamedUserItems(\n        colQuery,\n        this.requestContext,\n        colOptions\n      );\n\n\n\n      let assetCollection: any = null;\n      if (colResponse && Array.isArray(colResponse._list) && colResponse._list.length > 0) {\n        assetCollection = colResponse._list[0];\n        if (assetCollection && assetCollection._id) {\n          response = await IafItemSvc.getRelatedItems(\n            assetCollection._id,\n            {query: criteria},\n            this.requestContext,\n            options            \n          );\n        }\n      }\n    }\n    return response;\n  }\n\n  toRegexString(str) {\n    const quoted = str.match(/^'(.*)'$/);\n    if (quoted) {\n      const escaped = quoted[1].replace(/[.*+?^${}()|[\]\\]/g, '\\$&');\n      return `.*(${escaped}).*`;\n    }\n    const terms = str\n      .split(/\s+/)\n      .map(term => term.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));\n    return `.*(${terms.join('|')}).*`;\n  }\n}\n" };await IafAISvc.uploadToolSourceCode('5202ae41-a2c4-1429-7126-17ab4dc80245', sourceCode, ctx);
//Upload source code as fileconst sourceCode = {_file: fileStream}await IafAISvc.uploadToolSourceCode('5202ae41-a2c4-1429-7126-17ab4dc80245', sourceCode, ctx);