@abgov/adsp-sdk-mcp-server 1.22.1 → 1.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/README.md +83 -1
  2. package/assets/docs/services/agent-service.md +113 -27
  3. package/assets/docs/services/file-service.md +215 -116
  4. package/assets/docs/services/pdf-service.md +20 -0
  5. package/assets/docs/tutorials/file-service/file-types.md +2 -4
  6. package/assets/docs/tutorials/file-service/security.md +1 -1
  7. package/assets/docs/tutorials/file-service/working-with.md +5 -5
  8. package/package.json +6 -1
  9. package/src/config.d.ts +11 -0
  10. package/src/config.js +47 -0
  11. package/src/config.js.map +1 -0
  12. package/src/guards.d.ts +11 -0
  13. package/src/guards.js +94 -0
  14. package/src/guards.js.map +1 -0
  15. package/src/http.d.ts +17 -1
  16. package/src/http.js +39 -15
  17. package/src/http.js.map +1 -1
  18. package/src/main.js +13 -5
  19. package/src/main.js.map +1 -1
  20. package/src/metrics.d.ts +22 -0
  21. package/src/metrics.js +173 -0
  22. package/src/metrics.js.map +1 -0
  23. package/src/semaphore.d.ts +16 -0
  24. package/src/semaphore.js +71 -0
  25. package/src/semaphore.js.map +1 -0
  26. package/src/server.js +28 -3
  27. package/src/server.js.map +1 -1
  28. package/src/tools/liveToolLimit.d.ts +8 -0
  29. package/src/tools/liveToolLimit.js +45 -0
  30. package/src/tools/liveToolLimit.js.map +1 -0
  31. package/src/tools/registerConfigurationSchemaTool.js +7 -2
  32. package/src/tools/registerConfigurationSchemaTool.js.map +1 -1
  33. package/src/tools/registerServiceRolesTool.js +7 -2
  34. package/src/tools/registerServiceRolesTool.js.map +1 -1
  35. package/src/tools/types.d.ts +6 -2
  36. package/src/tools/upstreamErrors.d.ts +2 -0
  37. package/src/tools/upstreamErrors.js +18 -0
  38. package/src/tools/upstreamErrors.js.map +1 -0
package/README.md CHANGED
@@ -51,7 +51,17 @@ at `POST /mcp`, with a liveness check at `GET /health`.
51
51
  |---|---|---|
52
52
  | `MCP_TRANSPORT` | `stdio` | `http` to serve HTTP |
53
53
  | `PORT` | `3000` | Port to listen on |
54
- | `CORS_ORIGIN` | `*` | Value of `Access-Control-Allow-Origin` |
54
+ | `CORS_ORIGIN` | unset | Comma-separated browser origins allowed to call `/mcp`, for example `https://a.example,https://b.example`. Unset allows none; `*` allows any (not for hosted use) |
55
+ | `MCP_MAX_IN_FLIGHT` | `64` | `POST /mcp` requests handled at once per process |
56
+ | `MCP_IN_FLIGHT_WAIT_MS` | `1000` | How long a request waits for a free slot before getting `503`. Also how long a live tool waits for a free upstream slot |
57
+ | `MCP_RATE_LIMIT_PER_MINUTE` | `1200` | `POST /mcp` requests allowed per client IP per minute, per process. `0` turns the limit off |
58
+ | `MCP_LIVE_TOOL_MAX_CONCURRENT` | `8` | Live-tool calls to ADSP running at once per process, across both live tools |
59
+ | `TRUSTED_PROXY` | `uniquelocal` | Express [`trust proxy`](https://expressjs.com/en/guide/behind-proxies.html) setting, so the client IP comes from the router's `X-Forwarded-For` |
60
+ | `OTEL_EXPORTER_OTLP_ENDPOINT` | unset | OTLP/HTTP collector base URL. When set, metrics are exported to `<endpoint>/v1/metrics` |
61
+ | `OTEL_METRIC_EXPORT_INTERVAL` | `60000` | Metric export interval, in milliseconds |
62
+
63
+ An invalid value for one of the `MCP_*` numbers, or `*` mixed with origins in `CORS_ORIGIN`, stops the server at
64
+ startup with an error naming the variable.
55
65
 
56
66
  HTTP mode is stateless: each `POST /mcp` gets its own MCP server, the response is JSON (the server never streams),
57
67
  and nothing is kept between requests. The response carries no `Mcp-Session-Id`, so any replica can serve any request
@@ -60,6 +70,78 @@ there is no stream to open and no session to delete.
60
70
 
61
71
  `SESSION_TTL_MINUTES` has been removed and is ignored: there are no sessions to expire.
62
72
 
73
+ #### Overload guards
74
+
75
+ `POST /mcp` passes these checks in order. `GET /health` skips all of them. Every rejection is a JSON-RPC error body
76
+ (`code: -32000`) and is counted in `mcp.requests.rejected`.
77
+
78
+ 1. **Origin.** A request with an `Origin` header not in `CORS_ORIGIN` gets `403` (`Origin not allowed`), as the MCP
79
+ specification requires. `Origin: null` is never allowed. A request without an `Origin` header, which is what
80
+ non-browser clients such as agent-service and the MCP SDK send, passes. `Access-Control-Allow-Origin` is sent only
81
+ for an allowed origin.
82
+ 2. **Rate limit.** Over `MCP_RATE_LIMIT_PER_MINUTE` from one client IP, a request gets `429` with `Retry-After`
83
+ (`Rate limit exceeded`).
84
+ 3. **In-flight cap.** With `MCP_MAX_IN_FLIGHT` requests already running, a request waits up to
85
+ `MCP_IN_FLIGHT_WAIT_MS` for a slot, so a short burst completes. A request still waiting after that, or arriving
86
+ when as many requests are already waiting as `MCP_MAX_IN_FLIGHT`, gets `503` with `Retry-After: 1`
87
+ (`Server busy`). Requests already running are never affected. A request is admitted before its body arrives, so
88
+ the server allows 20 s for the headers and 30 s for the whole request. A client that sends more slowly is closed
89
+ and its slot freed. These limits don't apply to how long a tool call takes.
90
+
91
+ The live tools also share `MCP_LIVE_TOOL_MAX_CONCURRENT` slots for their calls to ADSP. A live-tool call that can't
92
+ get one within `MCP_IN_FLIGHT_WAIT_MS` answers with the tool error `ADSP upstream is busy. Retry shortly.` instead of
93
+ waiting on a slow upstream. A live-tool call whose client cancels it or disconnects while it waits gives up its
94
+ place and never calls ADSP. This applies in stdio mode too.
95
+
96
+ Things to know when sizing and tuning these:
97
+
98
+ - **The limits are per process.** With N replicas, the cluster takes about N times each limit.
99
+ - **The rate limit is per client IP until authentication is added.** Every agent-service pod is then one client, and
100
+ so is any group of users behind one NAT or proxy. Connecting and calling one tool is 3 `POST`s, so the default
101
+ allows about 400 such client sessions a minute from one IP. Retune it once the deployment shows which client IPs
102
+ reach the pod.
103
+ - **Clients don't retry.** Measured locally with `MCP_MAX_IN_FLIGHT=2` and both slots held:
104
+
105
+ | Client | Over the cap for longer than `MCP_IN_FLIGHT_WAIT_MS` | Over the cap briefly (`MCP_IN_FLIGHT_WAIT_MS=3000`, slots freed after 0.5 s) |
106
+ |---|---|---|
107
+ | `@modelcontextprotocol/sdk` 1.32.1 | `connect()` throws `StreamableHTTPError` (code 503) after the wait. One request, no retry, `Retry-After` ignored | Connects and calls the tool after about 0.5 s |
108
+ | `@mastra/mcp` 1.8.1 | Logs `MCP_CLIENT_GET_TOOLS_FAILED` and `listTools()` returns no tools from this server, without throwing. One request, no retry | Lists all six tools and calls one after about 0.5 s |
109
+
110
+ So a `503` becomes a failed tool call, or an agent turn with no ADSP tools at all. Size `MCP_MAX_IN_FLIGHT` and
111
+ the replica count so it stays rare, and watch `mcp.requests.rejected`.
112
+
113
+ #### Metrics
114
+
115
+ In HTTP mode with `OTEL_EXPORTER_OTLP_ENDPOINT` set, the server exports these OpenTelemetry metrics (meter
116
+ `adsp-sdk-mcp-server`, resource `service.name=adsp-sdk-mcp-server`). With no endpoint, nothing is created and the
117
+ OpenTelemetry SDK isn't loaded. Stdio mode never exports metrics.
118
+
119
+ | Name | Kind | Unit | Labels | Meaning |
120
+ |---|---|---|---|---|
121
+ | `mcp.requests.in_flight` | UpDownCounter | `{request}` | none | `POST /mcp` requests admitted by the in-flight cap and not yet answered (waiting requests aren't counted) |
122
+ | `mcp.requests.rejected` | Counter | `{request}` | `reason` | Requests or tool calls refused by an overload guard |
123
+ | `mcp.request.duration` | Histogram | `s` | `mcp.method.name`, and `http.response.status_code` or `error.type=aborted` | Time to answer a `POST /mcp` request, or until the client disconnected |
124
+ | `mcp.tool.duration` | Histogram | `s` | `mcp.tool.name`, `error.type` (absent on success) | Time to run a tool call |
125
+ | `mcp.live_tool.upstream.errors` | Counter | `{error}` | `mcp.tool.name`, `error.type` | Failed ADSP calls from `list_service_roles` and `get_service_configuration_schema` |
126
+ | `nodejs.eventloop.delay.p50`, `.p99`, `.max` | Gauge | `s` | none | Event-loop delay since the previous export |
127
+ | `v8js.memory.heap.used` | Gauge | `By` | none | V8 heap in use |
128
+ | `process.memory.usage` | Gauge | `By` | none | Resident set size |
129
+ | `mcp.docs_index.build.duration` | Histogram | `s` | none | Time to build the docs index, once per process at startup |
130
+
131
+ Every label takes a value from a fixed set:
132
+
133
+ - `mcp.tool.name`: one of the six tool names, or `unknown` for any name the server doesn't have.
134
+ - `mcp.method.name`: an MCP method such as `initialize`, `tools/list` or `tools/call`; `other` for any other method;
135
+ `batch` for a JSON-RPC batch; `unparsed` when the body wasn't valid JSON-RPC or was too large.
136
+ - `error.type` on `mcp.request.duration`: `aborted` when the client disconnected before the response was written; the
137
+ status code is then left out.
138
+ - `error.type` on `mcp.tool.duration`: `tool_error` (the tool answered with `isError`), `exception` (the tool threw),
139
+ `unknown_tool`, or `busy` (no live-tool slot was free in time).
140
+ - `error.type` on `mcp.live_tool.upstream.errors`: `http_4xx`, `http_5xx`, `network`, `not_in_directory`,
141
+ `not_authenticated` or `other`. `not_authenticated` covers both a missing `adsp-cli` login and a failed token
142
+ request, which `adsp-cli` reports the same way.
143
+ - `reason` on `mcp.requests.rejected`: `in_flight_cap`, `rate_limit`, `origin` or `live_tool_cap`.
144
+
63
145
  ### Using `list_service_roles`
64
146
 
65
147
  That one tool needs a real ADSP environment and a logged-in session (via `@abgov/adsp-cli`, a separate package this
@@ -17,13 +17,44 @@ client `urn:ads:platform:agent-service`
17
17
  | agent-user | Role for users with access to agents. Included in tenant admin role. |
18
18
  | agent-tool | Agent tool role assigned to agent service service account. Used to grant resource access to agent tools. |
19
19
 
20
- Users must have the `urn:ads:platform:agent-service:agent-user` client role to interact with agents. Additionally, agents can be configured with specific `userRoles` to restrict access to particular user roles.
20
+ Access to agents is checked in two places:
21
+
22
+ - **socket.io connections** require the `urn:ads:platform:agent-service:agent-user` role in the tenant. Connections without it are disconnected.
23
+ - **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 without `userRoles` are open to any authenticated user of the REST API.
24
+
25
+ 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`.
26
+
27
+ 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.
28
+
29
+ ## Tenancy
30
+
31
+ Agents, threads, and workspaces are scoped to a tenant.
32
+
33
+ - **Tenant users and service accounts** always act on the tenant of their token. Any `tenantId` query parameter, and the socket.io namespace, are ignored.
34
+ - **Core (platform) users** act on the tenant in the `tenantId` query parameter (for example, `?tenantId=urn:ads:platform:tenant-service:v2:/tenants/{id}`). Without it they only see the platform agents. A `tenantId` that is not an ADSP ID responds `400`. Core users have no tenant roles, so they can only use agents without `userRoles`, and they can't connect over socket.io.
35
+ - **Platform and tenant agents** are combined. The platform provides core agents (for example, `formGenerationAgent`) to every tenant, and tenants add their own in their `platform:agent-service` configuration. A platform agent replaces a tenant agent with the same ID, so give tenant agents distinct IDs.
36
+ - **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.
37
+
38
+ ## API overview
39
+
40
+ REST endpoints are under `https://agent-service.adsp.alberta.ca/agent/v1` and require a bearer token. See the [API documentation](https://api.adsp.alberta.ca) for request and response schemas.
41
+
42
+ | Area | Endpoints | Required role |
43
+ | :----------- | :-------------------------------------------- | :------------------------------------------------------------------------ |
44
+ | Access scope | `GET /access/scope` | Any authenticated user |
45
+ | Agents | `GET /agents`, `GET /agents/{agentId}` | Any authenticated user |
46
+ | Messages | `POST /agents/{agentId}` | Any authenticated user, or one of the agent's `userRoles` when it has any |
47
+ | Threads | `DELETE /agents/{agentId}/threads/{threadId}` | Any authenticated user, or one of the agent's `userRoles` when it has any |
48
+
49
+ `POST /agents/{agentId}` responds with the complete reply and starts a new thread for every request. Streaming replies, multi-turn conversations, and workspaces are only available over [socket.io](#socketio-interface). socket.io isn't a REST transport, so it isn't in the API documentation; its events are described below.
50
+
51
+ Agents are configured through the [configuration service](configuration-service.md); there are no agent-service endpoints for changing them.
21
52
 
22
53
  ## Concepts
23
54
 
24
55
  ### Agent
25
56
 
26
- An agent is an AI assistant configured with specific instructions, tools, and optional access to other agents. Agents are configured in the [configuration service](configuration-service.md) under the `platform:agent-service` namespace and name.
57
+ An agent is an AI assistant configured with specific instructions, tools, and optional access to other agents. Agents are configured in the [configuration service](configuration-service.md) under the `platform:agent-service` namespace and name. The service reloads agents when their configuration changes.
27
58
 
28
59
  Each agent configuration includes:
29
60
 
@@ -35,17 +66,23 @@ Each agent configuration includes:
35
66
  - **agents**: Optional array of other agent IDs this agent can delegate to
36
67
  - **tools**: Optional array of tools available to the agent
37
68
  - **mcp**: Optional MCP server configuration that adds tools from external MCP servers. You can optionally limit access with `capabilities` per server.
69
+ - **maxSteps**: Optional maximum number of steps (model calls, including tool calls) in one reply.
70
+ - **timeoutMs**: Optional time limit for one request, in milliseconds.
38
71
 
39
72
  ### Tools
40
73
 
41
74
  Tools extend agent capabilities by allowing them to perform specific actions. The service provides built-in tools and supports custom API request tools.
42
75
 
43
- Built-in tools:
76
+ Built-in tools include:
44
77
 
45
78
  - `schemaDefinitionTool`: Retrieves JSON schema definitions
46
- - `formConfigurationRetrievalTool`: Retrieves form configurations
47
- - `formConfigurationUpdateTool`: Updates form configurations
48
- - `fileDownloadTool`: Downloads files from the file service
79
+ - `formConfigurationRetrievalTool` and `formConfigurationUpdateTool`: Retrieve and update form configurations
80
+ - `pdfConfigurationRetrievalTool` and `pdfConfigurationUpdateTool`: Retrieve and update PDF templates
81
+ - `formDataRetrievalTool` and `formDataUpdateTool`: Retrieve and update form data
82
+ - `fileDownloadTool`, `fileCopyTool`, and `documentExtractTool`: Download, copy, and extract text from files in the file service
83
+ - `dataRegisterListTool`, `dataRegisterGetTool`, `dataRegisterCreateTool`, and `dataRegisterUpdateTool`: Manage data registers
84
+ - `emailNotificationGenerateTool`: Generates notification email templates
85
+ - `searchAdspDocsTool`, `readAdspDocTool`, and `searchAdspSdkReferenceTool`: Search the ADSP documentation and SDK reference
49
86
 
50
87
  Custom API tools can be configured to call external APIs on behalf of the agent.
51
88
 
@@ -53,7 +90,13 @@ Custom API tools can be configured to call external APIs on behalf of the agent.
53
90
 
54
91
  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.
55
92
 
56
- 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 and are then deleted; a user can also delete one of their own threads right away (see [Delete a thread](#delete-a-thread)).
93
+ 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](#delete-a-thread)).
94
+
95
+ Threads only carry context across messages sent over socket.io. Each REST `POST /agents/{agentId}` request uses a new thread.
96
+
97
+ ### Workspaces
98
+
99
+ 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.
57
100
 
58
101
  ### Structured Output
59
102
 
@@ -66,11 +109,44 @@ Agents can be configured with a JSON Schema that defines the structure of their
66
109
 
67
110
  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.
68
111
 
112
+ ### socket.io interface
113
+
114
+ Clients connect with [socket.io](https://socket.io) to stream replies and hold multi-turn conversations.
115
+
116
+ - **Connect** to `https://agent-service.adsp.alberta.ca/<tenant name>` (or the default namespace `/`) with the access token in `auth.token`. The user needs the `agent-user` role in the tenant. The tenant of a tenant user's token is used whatever the namespace.
117
+ - **Wait for ready**: once agent configuration is loaded, the service sends a `message` event (`Connected as user ... for tenant ...`). Send messages after it arrives.
118
+ - **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.
119
+ - **Errors** in handling an event, such as an unknown agent or invalid payload, are sent as an `error` event with a message string.
120
+
121
+ Events the client sends:
122
+
123
+ | Event | Payload | Service responds with |
124
+ | :----------------- | :----------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------- |
125
+ | `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` |
126
+ | `workspace-init` | `{ agent, threadId?, workspaceTarball }`. `workspaceTarball` is the file service URN of a `.tar.gz` file. | `workspace-ready` with `revision` and `updatedAt` |
127
+ | `workspace-read` | `{ agent, threadId? }` | `workspace-state` with `revision`, `updatedAt`, and `files` |
128
+ | `workspace-update` | `{ agent, threadId?, writes?: [{ path, content }], deletes?: [path] }` | `workspace-updated` with `revision`, `writeCount`, and `deleteCount` |
129
+
130
+ 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`.
131
+
132
+ ## Events
133
+
134
+ The agent service sends the following domain events under the `agent-service` namespace:
135
+
136
+ | Event | Description |
137
+ | :-------------------------- | :--------------------------------------------------------------- |
138
+ | `thread-created` | A user started a conversation thread with an agent. |
139
+ | `thread-deleted` | A thread was deleted, because the user deleted it or it expired. |
140
+ | `workspace-created` | A thread's workspace was created from an uploaded file. |
141
+ | `workspace-creation-failed` | Creating a thread's workspace from an uploaded file failed. |
142
+
143
+ 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.
144
+
69
145
  ## Code examples
70
146
 
71
147
  ### Configure an agent
72
148
 
73
- Agents are configured using the [configuration service](configuration-service.md). Note that new configuration may take up to 15 mins to apply.
149
+ Agents are configured using the [configuration service](configuration-service.md). This requires the configuration service `configuration-admin` role.
74
150
 
75
151
  ```typescript
76
152
  const configurationServiceUrl = 'https://configuration-service.adsp.alberta.ca';
@@ -110,12 +186,13 @@ const response = await fetch(`${agentServiceUrl}/agent/v1/agents`, {
110
186
  },
111
187
  });
112
188
 
189
+ // For example: { agents: [{ id: 'formGenerationAgent', name: 'Form Generation Agent' }] }
113
190
  const { agents } = await response.json();
114
191
  ```
115
192
 
116
193
  ### Message an agent (REST API)
117
194
 
118
- Send a message to an agent and receive a complete response. If the agent has a `outputSchema` configured, the response will also include a `output` field with structured data.
195
+ 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.
119
196
 
120
197
  ```typescript
121
198
  const agentServiceUrl = 'https://agent-service.adsp.alberta.ca';
@@ -135,7 +212,7 @@ const response = await fetch(`${agentServiceUrl}/agent/v1/agents/${agentId}`, {
135
212
  const { agent, content, output } = await response.json();
136
213
 
137
214
  // content contains the text response
138
- // output contains structured data if outputSchema was configured (null otherwise)
215
+ // output contains structured data if outputSchema was configured (absent otherwise)
139
216
  if (output) {
140
217
  console.log('Structured response:', output);
141
218
  }
@@ -143,7 +220,7 @@ if (output) {
143
220
 
144
221
  ### Stream agent responses (WebSocket)
145
222
 
146
- Connect via WebSocket for real-time streaming responses. The WebSocket endpoint uses Socket.IO and requires the tenant name as the namespace. When the response is complete, the done event will include any structured `output` if the agent has an `outputSchema` configured.
223
+ 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](#socketio-interface)). When the response is complete, the done event will include any structured `output` if the agent has an `outputSchema` configured.
147
224
 
148
225
  ```typescript
149
226
  import { io } from 'socket.io-client';
@@ -154,25 +231,28 @@ const socket = io('https://agent-service.adsp.alberta.ca/My Tenant', {
154
231
  },
155
232
  });
156
233
 
157
- socket.on('connect', () => {
158
- console.log('Connected to agent service');
159
- });
160
-
161
- // Send a message to an agent
162
- socket.send({
163
- agent: 'my-assistant',
164
- threadId: 'optional-thread-id',
165
- messageId: 'optional-message-id',
166
- content: 'Hello, can you help me?',
167
- context: {
168
- // Optional context data for the agent
169
- },
234
+ // The service sends a message once it is ready to receive messages.
235
+ socket.once('message', () => {
236
+ // Send a message to an agent
237
+ socket.send({
238
+ agent: 'my-assistant',
239
+ threadId: 'optional-thread-id',
240
+ messageId: 'optional-message-id',
241
+ content: 'Hello, can you help me?',
242
+ context: {
243
+ // Optional context data for the agent
244
+ },
245
+ });
170
246
  });
171
247
 
172
248
  // Receive streaming response
173
249
  socket.on('stream', (data) => {
174
- const { agent, threadId, messageId, replyTo, content, output, done } = data;
175
- if (done) {
250
+ const { agent, threadId, messageId, replyTo, content, chunk, output, done } = data;
251
+ if (chunk?.type === 'heartbeat') {
252
+ return;
253
+ } else if (chunk?.type === 'error') {
254
+ console.error('Reply stopped:', chunk.payload.code, chunk.payload.message);
255
+ } else if (done) {
176
256
  console.log('Response complete');
177
257
  // If the agent has a outputSchema, structured data is included here
178
258
  if (output) {
@@ -188,6 +268,10 @@ socket.on('stream', (data) => {
188
268
  socket.on('error', (message) => {
189
269
  console.error('Agent error:', message);
190
270
  });
271
+
272
+ socket.on('session-expired', () => {
273
+ // Reconnect with a fresh access token.
274
+ });
191
275
  ```
192
276
 
193
277
  #### Token usage and conversation length
@@ -220,9 +304,11 @@ Observational memory summarises older messages at `AGENT_OM_MESSAGE_TOKENS` unob
220
304
 
221
305
  ### Delete a thread
222
306
 
223
- Delete one of your own threads, with its stored messages and context, 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.
307
+ 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.
224
308
 
225
309
  ```typescript
310
+ const agentServiceUrl = 'https://agent-service.adsp.alberta.ca';
311
+
226
312
  const response = await fetch(`${agentServiceUrl}/agent/v1/agents/${agentId}/threads/${threadId}`, {
227
313
  method: 'DELETE',
228
314
  headers: {