Agent service
Agent service provides AI-powered agents that can assist users with various tasks. The service supports configurable agents with custom instructions, tools, and role-based access control. Agents can be accessed via REST API or WebSocket for real-time streaming interactions.
Client roles
client urn:ads:platform:agent-service
| name | description |
|---|---|
| agent-user | Role for users with access to agents. Included in tenant admin role. |
| agent-tool | Agent tool role assigned to agent service service account. Used to grant resource access to agent tools. |
Access to agents is checked in two places:
- socket.io connections require the
urn:ads:platform:agent-service:agent-userrole in the tenant. Connections without it are disconnected. - Each agent can be configured with
userRoles. When it has any, the user needs at least one of them in the tenant to message the agent or delete its threads, over REST or socket.io. Agents withoutuserRolesare open to any authenticated user of the REST API.
The REST API itself only requires an authenticated user: listing agents, reading an agent, and GET /access/scope need no role, and the REST message and thread endpoints check only the agent’s userRoles.
The service also registers the agent-attachments file type for files users attach to messages. Users with agent-user can upload them, and only the agent service account (agent-tool) can read them. They are deleted after 7 days.
Tenancy
Agents, threads, and workspaces are scoped to a tenant.
- Tenant users and service accounts always act on the tenant of their token. Any
tenantIdquery parameter, and the socket.io namespace, are ignored. - Core (platform) users act on the tenant in the
tenantIdquery parameter (for example,?tenantId=urn:ads:platform:tenant-service:v2:/tenants/{id}). Without it they only see the platform agents. AtenantIdthat is not an ADSP ID responds400. Core users have no tenant roles, so they can only use agents withoutuserRoles, and they can’t connect over socket.io. - Platform and tenant agents are combined. The platform provides core agents (for example,
formGenerationAgent) to every tenant, and tenants add their own in theirplatform:agent-serviceconfiguration. A platform agent replaces a tenant agent with the same ID, so give tenant agents distinct IDs. - Threads belong to the user and tenant that created them. Deleting another user’s thread, or a thread from another tenant, responds
{ "deleted": false }rather than an error, so callers can’t tell whether it exists.
API overview
REST endpoints are under https://agent-service.adsp.alberta.ca/agent/v1 and require a bearer token. See the API documentation for request and response schemas.
| Area | Endpoints | Required role |
|---|---|---|
| Access scope | GET /access/scope | Any authenticated user |
| Agents | GET /agents, GET /agents/{agentId} | Any authenticated user |
| Messages | POST /agents/{agentId} | Any authenticated user, or one of the agent’s userRoles when it has any |
| Threads | DELETE /agents/{agentId}/threads/{threadId} | Any authenticated user, or one of the agent’s userRoles when it has any |
POST /agents/{agentId} responds with the complete reply and starts a new thread for every request. Each message needs content as a string or an array of parts; anything else responds 400 without calling the model, the same as over socket.io. Streaming replies, multi-turn conversations, and workspaces are only available over socket.io. socket.io isn’t a REST transport, so it isn’t in the API documentation; its events are described below.
Agents are configured through the configuration service; there are no agent-service endpoints for changing them.
Concepts
Agent
An agent is an AI assistant configured with specific instructions, tools, and optional access to other agents. Agents are configured in the configuration service under the platform:agent-service namespace and name. The service reloads agents when their configuration changes.
Each agent configuration includes:
- name: Display name for the agent
- description: Optional description of the agent’s purpose
- instructions: System prompt that defines the agent’s behavior
- outputSchema: Optional JSON Schema object that defines the structure of the agent’s response. When configured, the agent will return structured output matching this schema alongside text responses.
- userRoles: Optional array of roles required to use the agent
- agents: Optional array of other agent IDs this agent can delegate to
- tools: Optional array of tools available to the agent
- mcp: Optional MCP server configuration that adds tools from external MCP servers. You can optionally limit access with
capabilitiesper server. - maxSteps: Optional maximum number of steps (model calls, including tool calls) in one reply.
- timeoutMs: Optional time limit for one request, in milliseconds.
Tools
Tools extend agent capabilities by allowing them to perform specific actions. The service provides built-in tools and supports custom API request tools.
Built-in tools include:
schemaDefinitionTool: Retrieves JSON schema definitionsformConfigurationRetrievalToolandformConfigurationUpdateTool: Retrieve and update form configurationspdfConfigurationRetrievalToolandpdfConfigurationUpdateTool: Retrieve and update PDF templatesformDataRetrievalToolandformDataUpdateTool: Retrieve and update form datafileDownloadTool,fileCopyTool, anddocumentExtractTool: Download, copy, and extract text from files in the file servicedataRegisterListTool,dataRegisterGetTool,dataRegisterCreateTool, anddataRegisterUpdateTool: Manage data registersemailNotificationGenerateTool: Proposes notification email template changes and saves them to the notification typesearchAdspDocsTool,readAdspDocTool, andsearchAdspSdkReferenceTool: Search the ADSP documentation and SDK reference
Custom API tools can be configured to call external APIs on behalf of the agent.
Threads
Conversations with agents are organized into threads. Each thread maintains context across multiple messages, allowing for coherent multi-turn conversations. Thread IDs can be provided by the client or generated automatically.
A thread’s context belongs only to that thread, so a client can start a fresh conversation by sending messages with a new thread ID. Threads expire after a period of inactivity (AGENT_THREAD_TTL_MINUTES, 30 minutes by default) and are then deleted; a user can also delete one of their own threads right away (see Delete a thread).
Threads only carry context across messages sent over socket.io. Each REST POST /agents/{agentId} request uses a new thread.
Workspaces
Some agents, such as the builder agents, work on files in a workspace that belongs to the thread. A client initializes the workspace from a file service tarball, can read and update its files, and receives workspace-change events when the agent changes them. Workspaces are deleted with their thread.
Structured Output
Agents can be configured with a JSON Schema that defines the structure of their output. When an agent has an outputSchema defined, it will return both text responses and structured JSON objects matching that schema. This is useful for extracting machine-readable data from agent responses, such as:
- Parsing form data
- Extracting entities or classifications
- Standardized API responses
- Validating response format
The agent will attempt to return data matching the schema; if schema validation fails, the agent will fall back to text-only responses with a warning in the conversation logs.
socket.io interface
Clients connect with socket.io to stream replies and hold multi-turn conversations.
- Connect to
https://agent-service.adsp.alberta.ca/<tenant name>(or the default namespace/) with the access token inauth.token. The user needs theagent-userrole in the tenant. The tenant of a tenant user’s token is used whatever the namespace. - Wait for ready: once agent configuration is loaded, the service sends a
messageevent (Connected as user ... for tenant ...). Send messages after it arrives. - Token expiry: shortly before the token expires the service sends
session-expired({ code: 'USER_TOKEN_EXPIRED' }) and disconnects, after any reply in progress is sent. Reconnect with a new token. - Errors in handling an event, such as an unknown agent or invalid payload, are sent as an
errorevent with a message string.
Events the client sends:
| Event | Payload | Service responds with |
|---|---|---|
message | { agent, threadId?, messageId?, content, context?, rawChunks? }. content is a string or an array of text, image, and file parts. | stream events, then conversation-status |
workspace-init | { agent, threadId?, workspaceTarball }. workspaceTarball is the file service URN of a .tar.gz file. | workspace-ready with revision and updatedAt |
workspace-read | { agent, threadId? } | workspace-state with revision, updatedAt, and files |
workspace-update | { agent, threadId?, writes?: [{ path, content }], deletes?: [path] } | workspace-updated with revision, writeCount, and deleteCount |
A missing threadId or messageId is generated. stream events carry agent, threadId, messageId (of the reply), and replyTo (the message ID). By default each carries a text content delta. With rawChunks: true, each instead carries a chunk of { type, payload }, including tool-call, tool-result, and reasoning-delta chunks, and the service also sends workspace-change events. In both modes the service sends a chunk of type heartbeat every 15 seconds while a reply is in progress. The last stream event has done: true, with output and usage; when a reply stops early, for example at the agent’s time or step limit, it has an error chunk with a code of GENERATION_DEADLINE or MAX_STEPS.
Events
The agent service sends the following domain events under the agent-service namespace:
| Event | Description |
|---|---|
thread-created | A user started a conversation thread with an agent. |
thread-deleted | A thread was deleted, because the user deleted it or it expired. |
workspace-created | A thread’s workspace was created from an uploaded file. |
workspace-creation-failed | Creating a thread’s workspace from an uploaded file failed. |
The service doesn’t consume domain events, but it listens for configuration service updates so that changed agent configuration applies without waiting for its cache to expire.
Audit actions
Agent service records audit events in the agent-service namespace of the audit service. Records are written to the tenant of the agent configuration. Agent interactions have the agent as the resource ({ type: 'agent', id: <agent ID>, name: <agent name> }); thread deletion has the thread as the resource ({ type: 'thread', id: <thread ID> }). The thread ID is the correlation ID, and agentId and threadId are in the metadata. All actions are version 1.
| action | category | severity | retention class | recorded when |
|---|---|---|---|---|
| agent.message.sent | data-access | info | compliance | A message to an agent is accepted, over REST or socket.io, with messageLength (characters of text) and attachmentCount in the metadata. |
| agent.response.completed | runtime | info | compliance | An agent’s response finishes, with responseLength and hasStructuredOutput in the metadata. See the statuses below. |
| agent.tool.invoked | runtime | info | compliance | An agent calls a tool, with toolId and toolType (builtin, api or mcp) in the metadata. See the statuses below. |
| agent.delegation.started | runtime | info | compliance | An agent delegates a subtask to another agent, with the delegating agent as the resource and delegateAgentId in the metadata. |
| thread.deleted | administrative | info | standard | A user deletes one of their own threads through the API. |
The outcome is in the status of the record, not in the action name, so failures can be found with the status query filter:
agent.tool.invokedhas statusfailurewhen the tool throws, fails input or output validation, or an MCP tool returns an error.errorCodein the metadata is the code of the error, or its name when it has no code (for exampleValidationError).agent.response.completedhas statusfailurewhen the response stops with an error, witherrorCodesuch asGENERATION_DEADLINE(time limit),MAX_STEPS(step limit),ABORTED, or the error name. It has statusblockedwhen a guardrail stops the response, witherrorCode: 'TRIPWIRE'and theprocessorIdof the guardrail.- Other records have status
success.
The actor is the user who sent the message, or the service account for service-triggered calls. Tool calls and delegations made by a delegated agent are recorded with that agent’s ID and the same user and thread, so each delegation in an agentic loop has its own record. Each tool call produces one agent.tool.invoked record.
Message and response content, tool inputs and outputs, delegation prompts, error messages, structured output values, and token counts are never recorded. Messages rejected because the user lacks a required role, or that cannot be processed (for example, an attachment cannot be read), are not recorded.
Not recorded by agent service:
- Changes to agent configuration. Agents are configured in the configuration service, which records
configuration.updatedandconfiguration.deletedwith a change set, including changes toinstructions,tools,userRolesandmcp, in theconfiguration-servicenamespace. - Threads deleted when they expire. These are signalled by the
thread-deletedevent.
Tool calls can be high volume, so agent service sends audit events in batches of up to 100 events, and sends any remaining events on shutdown. Audit failures are logged by the SDK and do not fail the agent interaction. The agent service account requires the audit-writer role of urn:ads:platform:audit-service.
Audit recording is on by default. Set the environment variable AGENT_AUDIT_ENABLED=false on agent service to turn it off, or true to turn it on regardless of the SDK AUDIT_ENABLED variable, which applies when AGENT_AUDIT_ENABLED is not set. The action catalog is still registered while recording is off, so turning it back on needs only a restart.
Code examples
Configure an agent
Agents are configured using the configuration service. This requires the configuration service configuration-admin role.
const configurationServiceUrl = 'https://configuration-service.adsp.alberta.ca';
const request = {
operation: 'UPDATE',
update: {
'my-assistant': {
name: 'My Assistant',
description: 'A helpful assistant for my application',
instructions: 'You are a helpful assistant. Answer questions clearly and concisely.',
userRoles: ['my-app-user'],
tools: ['schemaDefinitionTool'],
},
},
};
await fetch(`${configurationServiceUrl}/configuration/v2/configuration/platform/agent-service`, {
method: 'PATCH',
headers: {
Authorization: `Bearer ${accessToken}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(request),
});
List available agents
const agentServiceUrl = 'https://agent-service.adsp.alberta.ca';
const response = await fetch(`${agentServiceUrl}/agent/v1/agents`, {
method: 'GET',
headers: {
Authorization: `Bearer ${accessToken}`,
},
});
// For example: { agents: [{ id: 'formGenerationAgent', name: 'Form Generation Agent' }] }
const { agents } = await response.json();
Message an agent (REST API)
Send a message to an agent and receive a complete response. Each request starts a new thread, so include any earlier messages the agent needs in the request (the body can be an array of messages). If the agent has an outputSchema configured, the response will also include an output field with structured data.
const agentServiceUrl = 'https://agent-service.adsp.alberta.ca';
const agentId = 'my-assistant';
const response = await fetch(`${agentServiceUrl}/agent/v1/agents/${agentId}`, {
method: 'POST',
headers: {
Authorization: `Bearer ${accessToken}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
content: 'Hello, can you help me with a question?',
}),
});
const { agent, content, output } = await response.json();
// content contains the text response
// output contains structured data if outputSchema was configured (absent otherwise)
if (output) {
console.log('Structured response:', output);
}
Stream agent responses (WebSocket)
Connect via WebSocket for real-time streaming responses. The WebSocket endpoint uses Socket.IO, with the tenant name as the namespace, and requires the agent-user role (see socket.io interface). When the response is complete, the done event will include any structured output if the agent has an outputSchema configured.
import { io } from 'socket.io-client';
const socket = io('https://agent-service.adsp.alberta.ca/My Tenant', {
auth: {
token: accessToken,
},
});
// The service sends a message once it is ready to receive messages.
socket.once('message', () => {
// Send a message to an agent
socket.send({
agent: 'my-assistant',
threadId: 'optional-thread-id',
messageId: 'optional-message-id',
content: 'Hello, can you help me?',
context: {
// Optional context data for the agent
},
});
});
// Receive streaming response
socket.on('stream', (data) => {
const { agent, threadId, messageId, replyTo, content, chunk, output, done } = data;
if (chunk?.type === 'heartbeat') {
return;
} else if (chunk?.type === 'error') {
console.error('Reply stopped:', chunk.payload.code, chunk.payload.message);
} else if (done) {
console.log('Response complete');
// If the agent has a outputSchema, structured data is included here
if (output) {
console.log('Structured response:', output);
}
} else {
// Streaming text content arrives as deltas
process.stdout.write(content);
}
});
// Handle errors
socket.on('error', (message) => {
console.error('Agent error:', message);
});
socket.on('session-expired', () => {
// Reconnect with a fresh access token.
});
Token usage and conversation length
When the provider reports token usage, the done event also includes usage:
| Field | Meaning |
|---|---|
contextTokens | Input tokens of the agent’s last model call: how much of the context window the conversation takes up |
contextWindowTokens | The model’s context window, from AGENT_MODEL_CONTEXT_TOKENS (default 256,000) |
totalTokens | Every token the reply used across its model calls, including calls tools make, such as form generation, and the prompt injection check |
outputTokens | Tokens the model wrote |
modelCalls | Number of model calls the reply made |
After each reply, a conversation-status event says how the conversation stands. state is one of:
ok: nothing to tell the user.notice: memory has started keeping the conversation short, which is normal but means early details may be missed.reasonissummarised(observational memory has replaced older messages with notes) orolder-messages-dropped(an agent without observational memory now reads only its most recentmessageLimitmessages). For the Access Service agent,reasoncan also belong-conversation: the conversation takes up at leastAGENT_ACCESS_LONG_CONVERSATION_TOKENStokens (default 6,000), so a new chat would answer more cheaply.warning: the conversation is close to what the assistant can handle well.reasonisnear-context-limit(it takes up at least 70% of the context window) ornotes-condensed(observational memory has condensed its notes, which takes a very long conversation).
socket.on('conversation-status', ({ threadId, contextTokens, contextWindowTokens, state, reason }) => {
if (state === 'warning') {
console.log(`Thread ${threadId} is close to the assistant's limit (${reason}); suggest starting a new chat.`);
}
});
Observational memory summarises older messages at AGENT_OM_MESSAGE_TOKENS unobserved tokens (default 30,000) and condenses its notes at AGENT_OM_OBSERVATION_TOKENS (default 40,000).
Shared token budget
Every agent uses the same model key, so the service can hold agents to a token budget for that key. Before a message reaches the model, the service estimates the reply from the agent’s recent replies; when the estimate does not fit, the model is not called and the client gets a final stream event (done: true) with an error chunk with code RATE_LIMITED and a message saying how many seconds to wait. A rate-limit failure (HTTP 429) from the model provider during a reply is sent as an error chunk with the same code.
| Variable | Default | Meaning |
|---|---|---|
AGENT_TOKEN_LIMIT_PER_MINUTE | 0 | Tokens per minute across all agents; 0 is off |
AGENT_TOKEN_LIMIT_PER_5_MINUTES | 0 | Tokens per 5 minutes across all agents; 0 is off |
AGENT_TOKEN_AGENT_SHARES | '' | Share of each limit an agent may use, such as AccessServiceAgent=0.3,formGenerationAgent=0.5 |
AGENT_USER_TOKEN_LIMIT_PER_MINUTE | 0 | Tokens per minute for one user; 0 is off |
AGENT_TOKEN_WARN_RATIO | 0.7 | Share of a limit at which a warning is logged, once each time usage crosses it |
Shares are clamped to 0..1, and malformed entries are logged and ignored. Agents without a share, or with a share of 0, are held only to the overall limits. A message holds its estimate against the budget from the moment it is allowed until its reply’s usage is known, so messages sent at the same time cannot overshoot a limit; a reply that fails keeps its estimate counted until it leaves the window. Each pod enforces its own budget, so with several pods set the limits to the key’s limit divided by the number of pods.
socket.on('stream', ({ chunk }) => {
if (chunk?.type === 'error' && chunk.payload?.code === 'RATE_LIMITED') {
console.log(chunk.payload.message); // The AI service is busy right now. Please try again in about 40 seconds.
}
});
Model endpoint
Every agent calls one OpenAI-compatible endpoint, MODEL_URL, with the key MODEL_API_KEY. MODEL is the model for agents that don’t set model.id in their configuration. On the Government of Alberta network the endpoint is MaaS (https://maas.int.gov.ab.ca/v1). MaaS certificates are signed by the GoA Root CA, so the pod trusts it through NODE_EXTRA_CA_CERTS=/etc/certs/goa-root.pem, mounted from the optional agent-service-ca secret (key certificate).
Models differ in what they can do, so each limit is a comma-separated list of model IDs:
| Variable | Default | Meaning |
|---|---|---|
MODELS_WITHOUT_STREAMING | '' | Models called without streaming. The whole reply is then sent to the client as a stream, in one block, so a model that garbles streamed tool calls can still be used |
MODELS_WITHOUT_IMAGES | '' | Models that can’t read images. Each attached image is replaced with a note, so the model says it couldn’t see it instead of guessing |
MODELS_WITHOUT_TOOLS | '' | Models that can’t call tools. An agent with tools, sub-agents or a workspace configured with one uses MODEL instead, and a warning is logged |
MODEL_CONNECTION_RETRIES | 2 | Retries, with a growing delay, of a model call whose connection fails or that gets a 502 or 503 before any reply. A rate limit (429) is not retried |
For example, on MaaS:
MODEL_URL=https://maas.int.gov.ab.ca/v1
MODEL=qwen3-coder/Qwen/Qwen3-Coder-Next
MODELS_WITHOUT_STREAMING=GOA-Default,gemma4/google/gemma-4-31b-it
MODELS_WITHOUT_IMAGES=qwen3-coder/Qwen/Qwen3-Coder-Next,gpt-oss-120b/openai/gpt-oss-120b
MODELS_WITHOUT_TOOLS=gpt-oss-120b/openai/gpt-oss-120b
AGENT_FORM_GENERATION_MODEL=gemma4/google/gemma-4-31b-it
The form generation agent runs on Gemma there: Qwen sends the edit lists of formSchemaPatch as text rather than arrays, so the tool rejects its form edits.
The endpoint’s own error messages are never sent to the client, because they can name the key’s owner. A failed model call ends the reply with an error chunk with code MODEL_ERROR and a plain message: the service isn’t responding (no answer, a refused key, or a server error), or it couldn’t answer this message (400, 413 or 422, such as a conversation too long for the model). A MaaS token limit is sent as RATE_LIMITED with the key’s window, such as “Please try again within 5 minutes.”
Access Service agent
AccessServiceAgent answers Access Service and Keycloak questions with read-only live tools and documented guidance. To keep each model call small:
- Each call gets only the tools and instruction sections its question needs: environment and realm tools, client and app tools, or people and role tools, picked from the predefined question hint, the question’s words (an ADSP ID such as
urn:ads:platform:form-servicebrings the client and app tools) and the tools used in the last few messages. A question that matches none gets every tool. - How-to and concept questions are answered from the
getAccessGuidetool, which returns one documented topic. The same topics are available without a model call atGET /agent/v1/access/guide/:topic, which returns{ topic, title, markdown }; the tenant admin app uses it to answer predefined questions about documented topics. - Tool results are shown to the user as cards, so the model gets a compact summary of each result, and results from turns before the previous one are replaced with a short note in later requests (the thread keeps them). After a tool whose card fully answers a request to list or show something, the reply ends without a written answer.
- It keeps its own short history without observational memory.
| Variable | Default | Meaning |
|---|---|---|
AGENT_ACCESS_LAST_MESSAGES | 8 | Messages of the thread the agent reads |
AGENT_ACCESS_MAX_OUTPUT_TOKENS | 1000 | Longest reply the model may write in one call |
AGENT_ACCESS_LONG_CONVERSATION_TOKENS | 6000 | Context tokens at which to suggest a new chat; 0 is off |
curl -H "Authorization: Bearer $TOKEN" "$AGENT_SERVICE_URL/agent/v1/access/guide/token-expiry"
Form Generation agent
formGenerationAgent builds and edits a form definition from the form editor’s AI tab (with formDefinitionId in the message context). To keep each model call small:
- Each call gets core instructions plus only the sections and tools its question needs: common components, data registers, rules, computed fields, documents or layout, picked from the question’s words, the user’s previous message, an attached document and the tools used in the last few messages. A greeting or thanks gets no tools.
- The saved form is described in the instructions of every call (pages, fields with labels, types, enum values, required status, UI pointers, rules and conditional requirements), read again before each call, so the agent does not spend a tool call reading it.
formSchemaIndexremains for detail the description leaves out. - Worked examples load on demand with
formExamplesTool, as single-line JSON; the anti-patterns are a one-line checklist in the instructions.schemaDefinitionToolreturns only the common definitions asked for. - Tool results from turns before the previous one are replaced with a short note in later requests (the thread keeps them), and the agent keeps its own short history without observational memory.
- A large document (8,000 characters or 4 pages and up) reaches the agent as an outline of its sections: each section’s ID, title and length.
formGenerationRunreads the section text itself, and the agent reads one section withdocumentExtractTooland itssectionIdwhen it needs the exact wording. The text stays in the message, so the prompt injection check still reads it once, when it is attached.
| Variable | Default | Meaning |
|---|---|---|
AGENT_FORM_GENERATION_LAST_MESSAGES | 10 | Messages of the thread the agent reads |
AGENT_FORM_GENERATION_MAX_OUTPUT_TOKENS | 4000 | Longest output, including reasoning, of one chat model call; 0 is no limit |
Notification email template agent
notificationEmailTemplateAgent writes and edits the email template of a notification type event from the template editor in the tenant admin app. The editor sends its state with each message as context:
| Field | Meaning |
|---|---|
emailTemplate | The email template in the editor (subject, title, subtitle, body), including unsaved changes |
handlebarsVariables | Variables the template may use, as full paths such as event.payload.form.definition.name |
notificationType | The event as namespace:name |
notificationTypeId | The notification type; emailNotificationGenerateTool saves proposals to this type’s event |
Each model call gets the agent’s instructions followed by this context as text; a body longer than 30,000 characters is cut off with a note not to rebuild it. To keep each call small:
- The model gets a one-line summary of each
emailNotificationGenerateToolresult (the fields saved, or why the save failed); the client still gets the full proposal in thetool-resultchunk. - When the model says what it changed in the same response as a proposal that was saved, the reply ends there. Otherwise the next call writes the reply without the template rules, the editor context or the tool.
- Bodies proposed in earlier turns are replaced with a short note in later requests, since the editor sends the current template with every message. Attachments and pasted content from turns before the previous one are replaced too. The thread keeps every message.
- Text extracted from an attached document is cut off at 16,000 characters.
- It keeps its own short history without observational memory, and makes at most 3 model calls per message.
| Variable | Default | Meaning |
|---|---|---|
AGENT_NOTIFICATION_LAST_MESSAGES | 8 | Messages of the thread the agent reads |
AGENT_NOTIFICATION_MAX_OUTPUT_TOKENS | 6000 | Longest reply the model may write in one call, including the body |
PDF template agent
pdfGenerationAgent edits the PDF template open in the tenant admin PDF Template Editor; the client sends { pdfDefinitionId } as the message context. To keep each model call small:
- Each call gets short instructions and the saved template itself, so the agent edits and saves in one call instead of first calling
pdfConfigurationRetrievalTool. The guidance on files from the user (design references and uploaded images) is added only while a file is part of the conversation. - Long data URIs, such as the logo in the default header and footer, and long comments are shown to the model as placeholders like
[[elided-asset-1]].pdfConfigurationUpdateToolputs the original content back when it saves, and rejects a save that uses a placeholder the template does not have. Test data wrapped in adataobject is saved at the root, where the template reads it. - The model gets a short note for each save, while the client still gets the saved template in the tool result. Template copies from earlier turns are replaced with notes in later requests (the thread keeps them), and files from turns before the previous one are left out.
- A save is followed by a short closing reply that needs neither the template nor the tools.
- It keeps its own short history without observational memory.
| Variable | Default | Meaning |
|---|---|---|
AGENT_PDF_LAST_MESSAGES | 8 | Messages of the thread the agent reads |
AGENT_PDF_MAX_OUTPUT_TOKENS | 10000 | Longest reply the model may write in one call |
Delete a thread
Delete one of your own threads, with its stored messages, context, and workspace, for example when the user starts a new chat. The response is { "deleted": false } when you have no thread with that ID, so repeating the request is harmless. The thread ID is the threadId used on socket.io.
const agentServiceUrl = 'https://agent-service.adsp.alberta.ca';
const response = await fetch(`${agentServiceUrl}/agent/v1/agents/${agentId}/threads/${threadId}`, {
method: 'DELETE',
headers: {
Authorization: `Bearer ${accessToken}`,
},
});
const { deleted } = await response.json();
Configure a custom API tool
Agents can be configured with custom tools that call external APIs.
const request = {
operation: 'UPDATE',
update: {
'api-assistant': {
name: 'API Assistant',
instructions: 'You help users interact with external APIs.',
tools: [
'schemaDefinitionTool',
{
id: 'getWeather',
type: 'api',
description: 'Gets current weather for a location',
inputSchema: {
type: 'object',
properties: {
location: { type: 'string', description: 'City name' },
},
required: ['location'],
},
outputSchema: {
type: 'object',
properties: {
temperature: { type: 'number' },
conditions: { type: 'string' },
},
},
method: 'GET',
api: 'urn:ads:platform:weather-service:v1',
path: '/weather',
userContext: true,
},
],
},
},
};
Configure MCP server capabilities
Agents can be configured to use tools exposed by external MCP servers.
const request = {
operation: 'UPDATE',
update: {
'mcp-assistant': {
name: 'MCP Assistant',
instructions: 'Use MCP tools when they help answer user requests.',
mcp: {
servers: [
{
id: 'goa-design-system',
url: 'https://example.com/mcp',
headers: {
Authorization: 'Bearer <mcp-token>',
},
// Optional: restrict to a subset of tools from this MCP server.
capabilities: ['getComponent', 'searchTokens'],
},
],
},
},
},
};
When loaded, MCP tools are namespaced as <serverId>_<toolName> to avoid naming collisions across servers.
Configure structured output
Agents can be configured with a JSON Schema to return structured data. This is useful for extracting machine-readable information from agent responses.
const configurationServiceUrl = 'https://configuration-service.adsp.alberta.ca';
const request = {
operation: 'UPDATE',
update: {
'data-extractor': {
name: 'Data Extractor',
description: 'Extracts structured data from unstructured text',
instructions:
'You are an expert at extracting structured information. Extract all relevant data and return it as valid JSON matching the provided schema.',
outputSchema: {
type: 'object',
properties: {
entities: {
type: 'array',
items: {
type: 'object',
properties: {
name: { type: 'string' },
type: { type: 'string', enum: ['person', 'organization', 'location'] },
confidence: { type: 'number', minimum: 0, maximum: 1 },
},
required: ['name', 'type'],
},
},
sentiment: {
type: 'string',
enum: ['positive', 'neutral', 'negative'],
},
summary: { type: 'string' },
},
required: ['entities', 'sentiment'],
},
tools: ['schemaDefinitionTool'],
},
},
};
await fetch(`${configurationServiceUrl}/configuration/v2/configuration/platform/agent-service`, {
method: 'PATCH',
headers: {
Authorization: `Bearer ${accessToken}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(request),
});