@abgov/adsp-sdk-mcp-server 1.22.1 → 1.23.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.
package/README.md CHANGED
@@ -52,6 +52,8 @@ at `POST /mcp`, with a liveness check at `GET /health`.
52
52
  | `MCP_TRANSPORT` | `stdio` | `http` to serve HTTP |
53
53
  | `PORT` | `3000` | Port to listen on |
54
54
  | `CORS_ORIGIN` | `*` | Value of `Access-Control-Allow-Origin` |
55
+ | `OTEL_EXPORTER_OTLP_ENDPOINT` | unset | OTLP/HTTP collector base URL. When set, metrics are exported to `<endpoint>/v1/metrics` |
56
+ | `OTEL_METRIC_EXPORT_INTERVAL` | `60000` | Metric export interval, in milliseconds |
55
57
 
56
58
  HTTP mode is stateless: each `POST /mcp` gets its own MCP server, the response is JSON (the server never streams),
57
59
  and nothing is kept between requests. The response carries no `Mcp-Session-Id`, so any replica can serve any request
@@ -60,6 +62,41 @@ there is no stream to open and no session to delete.
60
62
 
61
63
  `SESSION_TTL_MINUTES` has been removed and is ignored: there are no sessions to expire.
62
64
 
65
+ #### Metrics
66
+
67
+ In HTTP mode with `OTEL_EXPORTER_OTLP_ENDPOINT` set, the server exports these OpenTelemetry metrics (meter
68
+ `adsp-sdk-mcp-server`, resource `service.name=adsp-sdk-mcp-server`). With no endpoint, nothing is created and the
69
+ OpenTelemetry SDK isn't loaded. Stdio mode never exports metrics.
70
+
71
+ | Name | Kind | Unit | Labels | Meaning |
72
+ |---|---|---|---|---|
73
+ | `mcp.requests.in_flight` | UpDownCounter | `{request}` | none | `POST /mcp` requests being handled |
74
+ | `mcp.requests.rejected` | Counter | `{request}` | `reason` | Requests or tool calls refused by an overload guard |
75
+ | `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 |
76
+ | `mcp.tool.duration` | Histogram | `s` | `mcp.tool.name`, `error.type` (absent on success) | Time to run a tool call |
77
+ | `mcp.live_tool.upstream.errors` | Counter | `{error}` | `mcp.tool.name`, `error.type` | Failed ADSP calls from `list_service_roles` and `get_service_configuration_schema` |
78
+ | `nodejs.eventloop.delay.p50`, `.p99`, `.max` | Gauge | `s` | none | Event-loop delay since the previous export |
79
+ | `v8js.memory.heap.used` | Gauge | `By` | none | V8 heap in use |
80
+ | `process.memory.usage` | Gauge | `By` | none | Resident set size |
81
+ | `mcp.docs_index.build.duration` | Histogram | `s` | none | Time to build the docs index, once per process at startup |
82
+
83
+ Every label takes a value from a fixed set:
84
+
85
+ - `mcp.tool.name`: one of the six tool names, or `unknown` for any name the server doesn't have.
86
+ - `mcp.method.name`: an MCP method such as `initialize`, `tools/list` or `tools/call`; `other` for any other method;
87
+ `batch` for a JSON-RPC batch; `unparsed` when the body wasn't valid JSON-RPC or was too large.
88
+ - `error.type` on `mcp.request.duration`: `aborted` when the client disconnected before the response was written; the
89
+ status code is then left out.
90
+ - `error.type` on `mcp.tool.duration`: `tool_error` (the tool answered with `isError`), `exception` (the tool threw),
91
+ `unknown_tool`, or `busy` (no live-tool slot was free in time).
92
+ - `error.type` on `mcp.live_tool.upstream.errors`: `http_4xx`, `http_5xx`, `network`, `not_in_directory`,
93
+ `not_authenticated` or `other`. `not_authenticated` covers both a missing `adsp-cli` login and a failed token
94
+ request, which `adsp-cli` reports the same way.
95
+ - `reason` on `mcp.requests.rejected`: `in_flight_cap`, `rate_limit`, `origin` or `live_tool_cap`.
96
+
97
+ This version has no overload guards yet, so `mcp.requests.rejected` and the `busy` error type are defined but never
98
+ recorded.
99
+
63
100
  ### Using `list_service_roles`
64
101
 
65
102
  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: {