@pixlcore/xycli 1.2.5 → 1.2.7

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/docs/mcp.md CHANGED
@@ -165,18 +165,60 @@ This opens only the HTTPS listener. Restart after replacing certificate files. U
165
165
  | `update_event` | Apply changes using an exact ID and the revision returned by `get_event`. |
166
166
  | `delete_event` | Delete an event while retaining historical jobs. Active jobs prevent deletion. |
167
167
  | `run_event` | Launch an enabled event with a manual trigger, optionally supplying parameters and input data. |
168
+ | `list_active_jobs` | Find running, queued, and other in-progress jobs by state, event, category or server. Returns job IDs and status summaries. |
168
169
  | `get_job` | Inspect job state, completion and output. Optional `fields` selects other job properties. |
170
+ | `get_job_log` | Read a completed job's console log, including archived logs, in bounded byte ranges. |
171
+ | `tail_job_log` | Read recent console output from a running job, along with its current state. |
172
+ | `get_workflow_job_outputs` | Inspect paginated direct child results, console output and output data from a completed workflow. |
169
173
  | `search_jobs` | Search completed jobs with query, pagination and sorting. |
170
174
  | `create_ticket` | Create a ticket with a subject, Markdown body and optional classification/assignment. |
171
175
  | `update_ticket` | Apply only supplied fields to a ticket by exact ID. |
172
176
  | `delete_ticket` | Permanently delete a ticket by exact ID. |
173
177
  | `comment_ticket` | Append a Markdown comment with the authenticated key as its author. |
178
+ | `list_plugins` | Find plugin definitions by title or type, including Monitor Plugins. |
179
+ | `get_plugin` | Read a plugin definition and its revision by exact ID. |
180
+ | `create_plugin` | Create a plugin definition, including a Monitor Plugin. |
181
+ | `update_plugin` | Update selected plugin fields by exact ID, with an optional revision check. |
182
+ | `delete_plugin` | Delete a plugin definition by exact ID. |
183
+ | `list_monitors` | Find server monitor definitions by title. |
184
+ | `get_monitor` | Read a monitor definition and its revision by exact ID. |
185
+ | `create_monitor` | Create a server monitor with a source expression and data type. |
186
+ | `update_monitor` | Update selected monitor fields by exact ID, with an optional revision check. |
187
+ | `delete_monitor` | Delete a monitor definition by exact ID. |
188
+ | `list_alerts` | Find alert definitions by title. |
189
+ | `get_alert` | Read an alert definition and its revision by exact ID. |
190
+ | `create_alert` | Create an alert definition with an expression, message and enabled status. |
191
+ | `update_alert` | Update selected alert definition fields by exact ID, with an optional revision check. |
192
+ | `delete_alert` | Delete an alert definition by exact ID. |
193
+ | `list_groups` | Find server group definitions by title. |
194
+ | `get_group` | Read a server group definition and its revision by exact ID. |
195
+ | `create_group` | Create a server group with optional hostname matching. |
196
+ | `update_group` | Update selected server group fields by exact ID, with an optional revision check. |
197
+ | `delete_group` | Delete a server group definition by exact ID. |
198
+ | `set_server_groups` | Replace the manual group memberships for one server. |
199
+ | `test_monitor` | Evaluate a monitor expression against a server's latest saved sample. |
200
+ | `test_alert` | Evaluate an alert expression and render its message using a server's latest saved sample. |
174
201
  | `search_alerts` | Search active and historical alert invocations, rather than alert definitions. |
175
202
  | `search_snapshots` | Search server/group snapshots, optionally including verbose monitoring details. |
176
203
  | `take_snapshot` | Capture the latest monitoring data for exactly one server or group. |
177
204
  | `list_servers` | List connected workers, optionally filtering by hostname, group or enabled state. |
178
-
179
- Pages default to 25 rows, capped by `max_page_size`. Events, servers and lookup collections are paginated locally after fetching the authorized collection; job, alert and snapshot searches are paginated on the server. Each lookup collection has its own total and uses the requested offset/limit.
205
+ | `list_tags` | Find tag IDs for events, jobs and tickets. |
206
+ | `get_tag` | Read a tag's title, icon, notes and revision by exact ID. |
207
+ | `create_tag` | Create a tag with a title and optional ID, icon and notes. |
208
+ | `update_tag` | Update a tag by exact ID, with an optional revision check. |
209
+ | `delete_tag` | Delete a tag by exact ID. |
210
+ | `list_web_hooks` | Find existing Web Hooks by title. Returns IDs, titles and enabled status. |
211
+ | `get_web_hook` | Read a Web Hook's delivery settings and revision by exact ID. |
212
+ | `create_web_hook` | Save a Web Hook with a URL, HTTP method and optional request template. |
213
+ | `update_web_hook` | Update a Web Hook by exact ID, with an optional revision check. |
214
+ | `delete_web_hook` | Delete a Web Hook by exact ID. |
215
+ | `list_channels` | Find existing notification Channels by title. Returns IDs, titles and enabled status. |
216
+ | `get_channel` | Read a notification Channel's configuration and revision by exact ID. |
217
+ | `create_channel` | Create a notification Channel with optional recipients, a Web Hook or an event to run. |
218
+ | `update_channel` | Update a notification Channel by exact ID, with an optional revision check. |
219
+ | `delete_channel` | Delete a notification Channel by exact ID. |
220
+
221
+ Pages default to 25 rows, capped by `max_page_size`. Events, servers and lookup collections are paginated locally after fetching the authorized collection. xyOps paginates active jobs and job, alert and snapshot searches on the server. Each lookup collection has its own total and uses the requested offset/limit.
180
222
 
181
223
  Updates, deletions and executions require exact IDs. Event creation requires an explicit `enabled` value. Ordinary events require category, plugin, targets and a server-selection algorithm. Workflows require a workflow object with nodes and connections. xyOps validates the full definition and permissions.
182
224
 
@@ -184,6 +226,44 @@ Event updates preserve omitted top-level fields. Supplied objects and arrays rep
184
226
 
185
227
  `run_event` returns immediately with a job ID. Use `get_job` until `final` is true, or search with `event:EVENT_ID` or `tags:_error`. Launches accept parameter overrides and `input.data`, but not arbitrary event overrides, test-mode bypasses or local-file uploads.
186
228
 
229
+ ### Job output
230
+
231
+ Use `list_active_jobs` to find job IDs for `get_job` or `tail_job_log`. Jobs are sorted by newest start time. Use `state` to narrow the list, for example `queued`, `active`, or `retry_delay`. The optional `event`, `category` and `server` filters take exact IDs. xyOps applies the caller's category and group restrictions before paging.
232
+
233
+ `get_job` includes structured output `data` and any console `output` stored inline with the job. Use the log tools when you need live console text or a completed log that was archived separately. All three tools are available in read-only mode and use the caller's API-key permissions. Download tokens and generated download URLs are not returned.
234
+
235
+ For a completed job, call `get_job_log` with `{"id":"JOB_ID"}`. The result includes `text`, the requested byte `offset`, a byte `next_offset`, and `truncated`. The default `max_bytes` is 32768 (32 KiB). If `truncated` is `true`, call again using the returned `next_offset`:
236
+
237
+ ```json
238
+ { "id": "JOB_ID", "offset": 32768, "max_bytes": 32768 }
239
+ ```
240
+
241
+ Offsets count bytes in the uncompressed log. Pages preserve UTF-8 character boundaries, so please use the actual `next_offset` from each response. Archived gzip logs are decompressed automatically. The tool retains only the requested range and stops downloading when it detects more text; later pages reread the log from the beginning to reach their offset. A job with no available log returns empty text. Running jobs should use `tail_job_log` instead.
242
+
243
+ For live output, call `tail_job_log` with `{"id":"JOB_ID","max_bytes":32768}`. This returns immediately with recent `text`, `state`, `final`, `requested_bytes`, and `tail_only: true`. xyOps aligns the tail to log lines, so it can return less text than requested. The `truncated` flag describes additional clipping of this returned tail; a `false` value does not mean the text contains the entire log. An empty tail can mean the job is queued or has not produced output yet. When `final` is `true`, switch to `get_job_log` for the completed log.
244
+
245
+ You can repeat live-tail calls to inspect progress. Successive tails may overlap or miss intervening output from a busy job. They do not provide a lossless stream or hold the tool call open until completion. For continuous following, use `xy job stream JOB_ID` or the xyOps `stream_job` API.
246
+
247
+ For a completed workflow, call `get_workflow_job_outputs` with `{"id":"WORKFLOW_JOB_ID","limit":10}`. The result contains `rows`, `total`, `offset`, `limit`, and `next_offset`. Each row includes the child job ID, workflow `node` ID, result details, available inline `output`, and output `data`. Children are ordered by node ID, then execution order within the node, including repeated executions and retries. Use `next_offset` to request the next page while it is less than `total`.
248
+
249
+ Workflow `max_bytes` defaults to 8192 (8 KiB) per child's console output and per child's serialized output data. `output_truncated` identifies clipped inline text. Oversized data is returned as a text `data_preview` with `data_truncated: true`; otherwise `data` retains its original JSON value. `log_available` identifies a captured console log, while `log_inline` identifies output stored in the job record. Use `get_job_log` with the child's ID for an archived or truncated log, and `get_job` with `fields: ["data"]` for larger structured data, subject to the overall result limit.
250
+
251
+ Only direct children are returned. A nested workflow appears as a child with `type: "workflow"`; call `get_workflow_job_outputs` with that child's ID to inspect its children. Missing, expired or inaccessible children return an `error` in their row, while the remaining page is still returned. Every child lookup independently checks the caller's permissions.
252
+
253
+ All three tools accept `max_bytes` from 4 through 262144 (256 KiB). The overall `max_result_bytes` limit still applies, including JSON escaping and metadata. If a response exceeds it, reduce `max_bytes` or the workflow page `limit`.
254
+
255
+ ### Tags and notification destinations
256
+
257
+ `list_tags`, `list_web_hooks` and `list_channels` accept a case-insensitive `title` filter and return summaries in ID order. Use the returned Web Hook and Channel IDs in event or alert actions.
258
+
259
+ Use `create_tag` with `{"tag":{"title":"Needs Review"}}`. This requires `create_tags`. xyOps generates the ID when you omit it, and the result includes the ID to use on events or tickets.
260
+
261
+ `create_web_hook` takes a `web_hook` object with `title`, `url` and an uppercase `method`. It also accepts optional `headers` as `{name, value}` objects and `body` as a template string. The URL, headers and body are write-only through MCP because they can contain credentials. `get_web_hook` returns the saved method and other delivery settings, along with the revision.
262
+
263
+ `create_channel` takes a `channel` object with `title` and optional recipients or actions. Use `users` for an array of usernames, `email` for a comma-separated list of addresses, and exact resource IDs for `web_hook` and `run_event`. `get_channel` returns those saved settings and the revision. New Web Hooks and Channels default to enabled. Set `enabled` to `false` when you want to configure one before using it in an action.
264
+
265
+ The update tools accept `id`, `changes` and an optional expected `revision`. The revision check runs before the write, so a concurrent edit can still land between the check and the write. Omitted fields are preserved. Supplied arrays replace the saved arrays, and an empty string clears an optional Channel link. Delete tools take the exact ID. xyOps enforces the caller's create, edit and delete privileges for each resource.
266
+
187
267
  ### Tickets
188
268
 
189
269
  Create a ticket with `{"ticket":{"subject":"Backup failed","body":"Investigating the logs.","type":"issue"}}`. xyOps generates its ID, number and initial history. Ticket types and statuses follow your xyOps configuration, including custom values. This initial tool set supports text and metadata; file attachments, automatic job/alert templates and attached event definitions are not exposed.
@@ -194,6 +274,16 @@ Use `comment_ticket` with `{"id":"TICKET_ID","body":"The backup is working again
194
274
 
195
275
  ### Monitoring
196
276
 
277
+ Use the definition `list_*` tools to find exact IDs. They return paginated summaries and accept a case-insensitive `title` filter. `list_plugins` also accepts `type`, such as `monitor`. The corresponding `get_*` tools return the full definition by ID. Use `fields` to select properties while retaining the ID and revision.
278
+
279
+ Create tools take a named object (`plugin`, `monitor`, `alert` or `group`) and return a summary with the ID and revision. Set `enabled` explicitly when creating a plugin or alert. For a Monitor Plugin, set `type` to `monitor` and supply the `command`, optional `script`, output `format` and target `groups`. The default output format is `text`. Set `groups` on the plugin, monitor and alert to scope all three to the same servers.
280
+
281
+ Update tools take `id` and `changes`. Pass the `revision` from the get tool to check for an intervening edit before submitting the changes. xyOps increments these definitions' revisions when it saves them. Another edit can still land between the check and the write. Omitted fields keep their current values, and supplied arrays replace the saved arrays. Read the definition again for the new revision. Delete tools take the exact definition ID.
282
+
283
+ For a group with selected servers, create it with `{"group":{"id":"mail","title":"Mail servers"}}`. The default hostname pattern matches no servers. Use `list_servers` to find each target's ID and current groups, then call `set_server_groups` for each target with its complete list of group IDs, including `mail`. This switches those servers to manual group assignment and requires `update_servers`. For servers using automatic assignment, you can instead set `hostname_match` on the group to an anchored regex matching the intended hostnames.
284
+
285
+ Call `test_monitor` with `server`, `source` and `data_type` to get a `value` or `fail: true` for an unresolved result. Call `test_alert` with `server`, `expression` and `message` to get a boolean `result` and the rendered `message`. These calls evaluate against the server's latest saved data without saving definitions or firing alerts. They require `edit_monitors` and `edit_alerts` respectively. All definition and membership tools use the caller's API key and xyOps applies its normal privilege and group checks.
286
+
197
287
  `search_alerts` accepts queries such as `active:true`, `server:SERVER_ID` or `start:>=today`. `search_snapshots` accepts queries such as `type:group`, `groups:GROUP_ID` or `source:alert`. Both support `query`, `offset`, `limit`, `sort_by` and `sort_dir` (`1` ascending, `-1` descending), defaulting to newest IDs first. xyOps applies the API key's resource restrictions. Snapshot search omits heavy nested details unless `verbose` is `true`; use small pages with verbose results to stay within the response size limit.
198
288
 
199
289
  `list_servers` returns connected worker summaries and IDs, excluding offline servers and conductor peers. `hostname` matches a case-insensitive substring, `group` matches an exact group ID, and `enabled` filters the enabled flag.
@@ -204,7 +294,7 @@ API requests are not automatically retried. A lost connection after a mutation m
204
294
 
205
295
  ## Adding a tool
206
296
 
207
- Every bundled `.js` file in `lib/mcp/tools/` exports:
297
+ Every bundled `.js` file in `lib/mcp/tools/` exports one tool or an array of related tools. Each tool provides the following functions.
208
298
 
209
299
  | Function | Contract |
210
300
  | --- | --- |
@@ -213,12 +303,12 @@ Every bundled `.js` file in `lib/mcp/tools/` exports:
213
303
 
214
304
  The registry sorts and loads files once, checks exports/names, and compiles schemas. Helpers belong outside the tools directory. Duplicate names or malformed definitions stop startup.
215
305
 
216
- The context supplies `callAPI(name, params)`, `signal`, `log`, and `limits`. HTTP scopes this context to the incoming key. Tool modules must use `context.callAPI()` so every upstream call uses the correct credentials. Add newly required methods to the shared boundary's read/write API allowlists. Calls use the existing SDK. Cancellation prevents subsequent API calls but cannot undo requests already sent.
306
+ The context supplies `callAPI(name, params)`, `readJobLog(id, offset, max_bytes)`, `signal`, `log`, and `limits`. HTTP scopes this context to the incoming key. Tool modules must use these context methods so every upstream call uses the correct credentials. `readJobLog` handles bounded raw-text downloads; JSON APIs use `callAPI`. Add newly required JSON methods to the shared boundary's read/write API allowlists. Calls use the existing SDK. Cancellation prevents subsequent API calls but cannot undo requests already sent.
217
307
 
218
308
  Both transports invoke the same modules. A tool can combine API calls, simplify inputs and select useful outputs. The runtime validates arguments and returns structured data plus JSON text. Provide pagination or field selection for large results. Keep credentials and raw transport envelopes out of outputs and diagnostics.
219
309
 
220
310
  ## Tests
221
311
 
222
- `npm run test:offline` includes schema, permission-boundary and wire-level STDIO/HTTP/HTTPS checks using fixtures. The TLS key in `test/fixtures/mcp/` is a public test fixture, never a deployment credential.
312
+ `npm run test:offline` includes schema, permission-boundary and wire-level STDIO/HTTP/HTTPS checks using fixtures, including compressed logs, byte pagination, live tails and workflow child output. The TLS key in `test/fixtures/mcp/` is a public test fixture, never a deployment credential.
223
313
 
224
- `node test.js mcp` runs the live suite against `http://localhost:5522`. It requires administrator test credentials, an enabled category, the stock Shell Plugin and a connected worker. It creates disposable events/API keys and a draft ticket, runs a harmless echo job, takes server/group snapshots, verifies restricted-key behavior over STDIO and concurrent HTTP requests, and cleans up its records. Monitoring tests require a worker in a group with a saved monitoring sample. The ticket remains a draft to suppress notifications; the suite deletes only snapshots it created and verifies their removal.
314
+ `node test.js mcp` runs the live suite against `http://localhost:5522`. It requires administrator test credentials, an enabled category, the stock Shell Plugin and a connected worker. It creates disposable events/API keys and a draft ticket, runs harmless echo jobs including a workflow child, checks live tails and completed output, takes server/group snapshots, verifies restricted-key behavior over STDIO and concurrent HTTP requests, and cleans up its records. Monitoring tests require a worker in a group with a saved monitoring sample. The ticket remains a draft to suppress notifications; the suite deletes only snapshots it created and verifies their removal.
@@ -1,6 +1,18 @@
1
1
  // Shared SDK boundary. No terminal formatting, cached records, or global args.
2
- const READ_APIS = new Set(['get_events', 'get_event', 'get_categories', 'get_groups', 'get_plugins', 'get_plugin', 'get_job', 'search_jobs', 'search_alerts', 'search_snapshots', 'get_active_servers']);
3
- const WRITE_APIS = new Set(['create_event', 'update_event', 'delete_event', 'run_event', 'create_ticket', 'update_ticket', 'delete_ticket', 'add_ticket_change', 'create_snapshot', 'create_group_snapshot']);
2
+ const READ_APIS = new Set([
3
+ 'get_events', 'get_event', 'get_categories', 'get_job', 'get_active_jobs', 'search_jobs', 'tail_live_job_log',
4
+ 'search_alerts', 'search_snapshots', 'get_active_servers',
5
+ 'get_plugins', 'get_plugin', 'get_monitors', 'get_monitor', 'get_alerts', 'get_alert', 'get_groups', 'get_group',
6
+ 'test_monitor', 'test_alert', 'get_tags', 'get_tag', 'get_web_hooks', 'get_web_hook', 'get_channels', 'get_channel'
7
+ ]);
8
+ const WRITE_APIS = new Set([
9
+ 'create_event', 'update_event', 'delete_event', 'run_event',
10
+ 'create_ticket', 'update_ticket', 'delete_ticket', 'add_ticket_change', 'create_snapshot', 'create_group_snapshot',
11
+ 'create_plugin', 'update_plugin', 'delete_plugin', 'create_monitor', 'update_monitor', 'delete_monitor',
12
+ 'create_alert', 'update_alert', 'delete_alert', 'create_group', 'update_group', 'delete_group', 'update_server',
13
+ 'create_tag', 'update_tag', 'delete_tag', 'create_web_hook', 'update_web_hook', 'delete_web_hook',
14
+ 'create_channel', 'update_channel', 'delete_channel'
15
+ ]);
4
16
 
5
17
  function checkKeys(value) {
6
18
  // Prevent prototype-bearing keys from reaching downstream merge helpers.
@@ -18,6 +30,15 @@ function createContext(api, options = {}) {
18
30
 
19
31
  return {
20
32
  limits, log, redact, readOnly: !!options.read_only,
33
+ async readJobLog(id, offset, bytes, signal) {
34
+ // Raw log downloads need a bounded Writable rather than the JSON API
35
+ // path. Keep credentials scoped here just like every other API call.
36
+ if (signal?.aborted) throw new Error('Request cancelled before contacting xyOps.');
37
+ const requestOptions = { retries: 0, signal };
38
+ if (options.api_key) requestOptions.headers = { 'X-API-Key': options.api_key };
39
+ try { return await require('./job-output.js').download(api, id, offset, bytes, requestOptions); }
40
+ catch (err) { throw new Error(redact(err.message || err)); }
41
+ },
21
42
  withApiKey(api_key) {
22
43
  // HTTP requests get their own immutable credential scope, including
23
44
  // error redaction. Never change environment variables or SDK defaults.
@@ -0,0 +1,52 @@
1
+ const S = require('./schemas.js');
2
+
3
+ module.exports = function definitionTools({ name, label, properties, required, createOnly, defaults, summaryFields, readFields }) {
4
+ const getAPI = 'get_' + name;
5
+ // For definitions with sensitive fields, use the same allowlist for field
6
+ // selection and the default response. A field selector cannot bypass it.
7
+ const fieldSelector = readFields ? { ...S.strings, items: { type: 'string', enum: readFields } } : S.strings;
8
+
9
+ return [
10
+ {
11
+ describe: () => S.describe(getAPI, `Read a ${label} by exact ID. Use fields to select which properties to return.`, { id: S.id, fields: fieldSelector }, ['id']),
12
+ async run({ id, fields }, context) {
13
+ const data = await context.callAPI(getAPI, { id });
14
+ const record = readFields ? S.pick(data[name], readFields) : data[name];
15
+ return { [name]: fields ? S.pick(record, ['id', 'revision', ...fields]) : record };
16
+ }
17
+ },
18
+ {
19
+ describe: () => S.describe('create_' + name, `Create a ${label} and return a summary.`, {
20
+ [name]: S.input({ id: S.id, ...properties, ...createOnly }, required)
21
+ }, [name], false),
22
+ async run(args, context) {
23
+ const data = await context.callAPI('create_' + name, { ...defaults?.(args[name]), ...args[name] });
24
+ return { [name]: S.pick(data[name], summaryFields) };
25
+ }
26
+ },
27
+ {
28
+ describe: () => S.describe('update_' + name, `Update a ${label} by exact ID. Omitted fields are preserved and supplied arrays replace their saved values. Optionally check the revision before writing.`, {
29
+ id: S.id,
30
+ revision: { type: 'integer', minimum: 1, description: 'Expected revision from the get tool. Checked before the update request.' },
31
+ changes: { ...S.input(properties), minProperties: 1 }
32
+ }, ['id', 'changes'], false),
33
+ async run({ id, revision, changes }, context) {
34
+ // xyOps increments these revisions but has no atomic revision precondition.
35
+ // Check the caller's revision when supplied, then send only the patch.
36
+ if (revision !== undefined) {
37
+ const data = await context.callAPI(getAPI, { id });
38
+ if (data[name].revision !== revision) throw new Error(`Revision mismatch for ${label} ${id}. Read the current definition before updating.`);
39
+ }
40
+ await context.callAPI('update_' + name, { ...changes, id });
41
+ return { id, updated: true };
42
+ }
43
+ },
44
+ {
45
+ describe: () => S.describe('delete_' + name, `Delete a ${label} by exact ID.`, { id: S.id }, ['id'], false),
46
+ async run({ id }, context) {
47
+ await context.callAPI('delete_' + name, { id });
48
+ return { id, deleted: true };
49
+ }
50
+ }
51
+ ];
52
+ };
@@ -0,0 +1,86 @@
1
+ // Shared output bounds. Keep log transport details outside the tool catalog.
2
+ const { Writable } = require('node:stream');
3
+
4
+ const maxBytes = { type: 'integer', minimum: 4, maximum: 262144, default: 32768, description: 'Maximum UTF-8 bytes of text to return (4 - 262144).' };
5
+ const offset = { type: 'integer', minimum: 0, maximum: Number.MAX_SAFE_INTEGER - 262145, default: 0, description: 'Byte offset in the uncompressed log. Use next_offset from the previous response.' };
6
+
7
+ function prefix(buffer, bytes) {
8
+ // Leave a partial UTF-8 character for the next page rather than replacing it.
9
+ let end = Math.min(buffer.length, bytes);
10
+ if (end < buffer.length) {
11
+ let lead = end;
12
+ while (lead > 0 && (buffer[lead] & 0xc0) === 0x80) lead--;
13
+ const value = buffer[lead];
14
+ const width = value >= 0xc2 && value <= 0xdf ? 2 : (value >= 0xe0 && value <= 0xef ? 3 : (value >= 0xf0 && value <= 0xf4 ? 4 : 0));
15
+ if (lead < end && width && lead + width > end) end = lead;
16
+ }
17
+ return buffer.subarray(0, end);
18
+ }
19
+
20
+ function textOutput(text, bytes) {
21
+ const buffer = Buffer.from(text || '', 'utf8');
22
+ const output = prefix(buffer, bytes);
23
+ return { text: output.toString('utf8'), truncated: buffer.length > output.length };
24
+ }
25
+
26
+ async function download(api, id, start, bytes, options) {
27
+ const chunks = [];
28
+ let received = 0;
29
+ let clipped = false;
30
+ let status;
31
+
32
+ // The SDK decompresses archived logs before writing here. Retain only the
33
+ // requested range plus one lookahead byte, even for very large log files.
34
+ const sink = new Writable({ write(chunk, encoding, callback) {
35
+ const end = Math.min(chunk.length, start + bytes + 1 - received);
36
+ const begin = Math.max(0, start - received);
37
+ if (end > begin) chunks.push(Buffer.from(chunk.subarray(begin, end)));
38
+ received += chunk.length;
39
+
40
+ // Stop downloading as soon as we can prove another page exists. Only a
41
+ // successful HTTP response may turn this deliberate stop into a result.
42
+ // A Writable error lets the SDK clean up its socket and request timers.
43
+ if (received > start + bytes) {
44
+ clipped = true;
45
+ return callback(new Error('MCP log range complete.'));
46
+ }
47
+ callback();
48
+ } });
49
+ sink.on('error', () => {});
50
+
51
+ // Cancel through the Writable error path as well, so the request library
52
+ // releases its download socket and timers. Wait until the SDK attaches the
53
+ // source pipe before destroying the sink, including for an empty response.
54
+ const { signal, ...requestOptions } = options;
55
+ let piped = false;
56
+ const cancel = () => { if (piped) sink.destroy(new Error('Request cancelled while reading the job log.')); };
57
+ sink.once('pipe', () => {
58
+ piped = true;
59
+ if (signal?.aborted) cancel();
60
+ });
61
+ signal?.addEventListener('abort', cancel, { once: true });
62
+
63
+ try {
64
+ const response = await api.get_job_log({ id }, {
65
+ ...requestOptions, download: sink,
66
+ progress(chunk, response) { status = response.statusCode; }
67
+ });
68
+ if (options.signal?.aborted) throw new Error('Request cancelled while reading the job log.');
69
+ if (response?.err && !(clipped && status >= 200 && status < 300)) throw new Error(String(response.err));
70
+ if (!response || (!response.err && !response.resp)) throw new Error('Invalid xyOps log response.');
71
+
72
+ const buffer = Buffer.concat(chunks);
73
+ const output = prefix(buffer, bytes);
74
+
75
+ // Offsets count source bytes, even when invalid UTF-8 is displayed using
76
+ // replacement characters that take a different number of encoded bytes.
77
+ return { id, text: output.toString('utf8'), offset: start, next_offset: start + output.length, truncated: clipped };
78
+ }
79
+ finally {
80
+ // The request library does not own caller-supplied Writable streams.
81
+ signal?.removeEventListener('abort', cancel);
82
+ sink.destroy();
83
+ }
84
+ }
85
+
86
+ module.exports = { maxBytes, offset, prefix, textOutput, download };
@@ -7,21 +7,24 @@ module.exports = function loadTools(directory = Path.join(__dirname, 'tools')) {
7
7
  const tools = new Map();
8
8
 
9
9
  for (const file of fs.readdirSync(directory).filter(file => file.endsWith('.js')).sort()) {
10
- const tool = require(Path.join(directory, file));
11
- if (typeof tool.describe !== 'function' || typeof tool.run !== 'function') {
12
- throw new Error('Invalid MCP tool exports: ' + file);
10
+ const exported = require(Path.join(directory, file));
11
+ // Related operations can share a module, but each still publishes its own schema.
12
+ for (const tool of [].concat(exported)) {
13
+ if (typeof tool?.describe !== 'function' || typeof tool.run !== 'function') {
14
+ throw new Error('Invalid MCP tool exports: ' + file);
15
+ }
16
+ const description = tool.describe();
17
+ if (!description || !/^[a-z][a-z0-9_]*$/.test(description.name) || !description.description ||
18
+ !description.inputSchema || description.inputSchema.type !== 'object' ||
19
+ typeof description.annotations?.readOnlyHint !== 'boolean') {
20
+ throw new Error('Invalid MCP tool description: ' + file);
21
+ }
22
+ if (tools.has(description.name)) throw new Error('Duplicate MCP tool: ' + description.name);
23
+
24
+ // Compile once, rather than rebuilding validators for each HTTP request.
25
+ const inputSchema = fromJsonSchema(description.inputSchema);
26
+ tools.set(description.name, { ...tool, description, inputSchema });
13
27
  }
14
- const description = tool.describe();
15
- if (!description || !/^[a-z][a-z0-9_]*$/.test(description.name) || !description.description ||
16
- !description.inputSchema || description.inputSchema.type !== 'object' ||
17
- typeof description.annotations?.readOnlyHint !== 'boolean') {
18
- throw new Error('Invalid MCP tool description: ' + file);
19
- }
20
- if (tools.has(description.name)) throw new Error('Duplicate MCP tool: ' + description.name);
21
-
22
- // Compile once, rather than rebuilding validators for each HTTP request.
23
- const inputSchema = fromJsonSchema(description.inputSchema);
24
- tools.set(description.name, { ...tool, description, inputSchema });
25
28
  }
26
29
  return tools;
27
30
  };
package/lib/mcp/server.js CHANGED
@@ -23,6 +23,7 @@ module.exports = function serverFactory(tools, context) {
23
23
  checkKeys(args);
24
24
  const invocation = { ...scoped, signal: request.mcpReq.signal };
25
25
  invocation.callAPI = (name, params) => scoped.callAPI(name, params, invocation.signal);
26
+ invocation.readJobLog = (id, offset, bytes) => scoped.readJobLog(id, offset, bytes, invocation.signal);
26
27
  return result(await tool.run(args, invocation), scoped.limits.max_result_bytes);
27
28
  }
28
29
  catch (err) { return failure(err, scoped.redact); }
@@ -0,0 +1,112 @@
1
+ // Core definition tools use the same schemas and API boundary as events.
2
+ const S = require('../schemas.js');
3
+ const definitionTools = require('../definition-tools.js');
4
+
5
+ const nonempty = { ...S.text, pattern: '\\S' };
6
+ const common = { title: nonempty, icon: S.text, notes: S.text };
7
+ const bool = { type: 'boolean' };
8
+ const groups = { type: 'array', items: S.id, uniqueItems: true, description: 'Exact server group IDs. An empty list applies to all groups.' };
9
+ const pluginType = { type: 'string', enum: ['event', 'monitor', 'action', 'scheduler'] };
10
+ const dataType = { type: 'string', enum: ['integer', 'float', 'bytes', 'seconds', 'milliseconds'] };
11
+ const monitorExpression = {
12
+ source: { ...nonempty, description: 'JEXL expression evaluated against server monitoring data.' },
13
+ data_type: dataType,
14
+ data_match: { ...S.text, description: 'Optional regular expression to extract a numeric value from text.' }
15
+ };
16
+ const alertExpression = {
17
+ expression: { ...nonempty, description: 'JEXL expression that evaluates to true when the alert should fire.' },
18
+ message: { ...nonempty, description: 'Alert message template, with optional {{expression}} substitutions.' }
19
+ };
20
+
21
+ function monitoringDefinitionTools({ summary, ...definition }) {
22
+ const { name, label } = definition;
23
+ const fields = ['id', 'title', 'revision', ...summary];
24
+ const pluginFilter = name === 'plugin' ? { type: pluginType } : {};
25
+
26
+ return [
27
+ {
28
+ describe: () => S.describe('list_' + name + 's', `List ${label} summaries. Title matches a case-insensitive substring.`, {
29
+ ...S.pagination, title: S.text, ...pluginFilter
30
+ }),
31
+ async run(args, context) {
32
+ // Page the collection returned for this key, keeping large definitions out of list results.
33
+ const data = await context.callAPI('get_' + name + 's');
34
+ const rows = data.rows.filter(row =>
35
+ (!args.title || row.title.toLowerCase().includes(args.title.toLowerCase())) &&
36
+ (!args.type || row.type === args.type)
37
+ ).sort((a, b) => a.id.localeCompare(b.id));
38
+ const { offset, limit } = S.page(args, context);
39
+ return { rows: rows.slice(offset, offset + limit).map(row => S.pick(row, fields)), total: rows.length, offset, limit };
40
+ }
41
+ },
42
+ ...definitionTools({ ...definition, summaryFields: fields })
43
+ ];
44
+ }
45
+
46
+ module.exports = [
47
+ ...monitoringDefinitionTools({
48
+ name: 'plugin', label: 'plugin', summary: ['type', 'enabled', 'groups'],
49
+ properties: {
50
+ ...common, enabled: bool, command: nonempty, script: S.text,
51
+ params: { ...S.objects, description: 'Parameter definitions for non-monitor plugins.' },
52
+ groups: { ...groups, description: 'Server group IDs for a monitor plugin. An empty list applies to all groups.' },
53
+ format: { type: 'string', enum: ['text', 'json', 'xml'], description: 'Monitor plugin output format. Defaults to text on creation.' },
54
+ quick: { ...bool, description: 'Also run this monitor plugin every second with QuickMon.' },
55
+ uid: { type: ['string', 'integer'] }, gid: { type: ['string', 'integer'] },
56
+ kill: { type: 'string', enum: ['none', 'parent', 'all'] }, runner: bool
57
+ },
58
+ createOnly: { type: pluginType }, required: ['title', 'type', 'command', 'enabled'],
59
+ defaults: plugin => plugin.type === 'monitor' ? { groups: [], format: 'text', quick: false } : { params: [] }
60
+ }),
61
+ ...monitoringDefinitionTools({
62
+ name: 'monitor', label: 'monitor', summary: ['display', 'data_type', 'groups'],
63
+ properties: {
64
+ ...common, ...monitorExpression, groups, display: bool, suffix: S.text,
65
+ min_vert_scale: { type: 'number', minimum: 0 }, delta: bool, divide_by_delta: bool,
66
+ delta_min_value: { anyOf: [{ type: 'number' }, { const: false }] }
67
+ },
68
+ required: ['title', 'source', 'data_type'], defaults: () => ({ groups: [], display: true })
69
+ }),
70
+ ...monitoringDefinitionTools({
71
+ name: 'alert', label: 'alert definition', summary: ['enabled', 'groups', 'monitor_id'],
72
+ properties: {
73
+ ...common, ...alertExpression, groups, enabled: bool, actions: S.objects,
74
+ monitor_id: { ...S.text, pattern: '^[a-z0-9_]*$', description: 'Exact monitor ID, or empty to clear the link.' },
75
+ samples: { type: 'integer', minimum: 1 }, exclusive_actions: bool, limit_jobs: bool, abort_jobs: bool
76
+ },
77
+ required: ['title', 'expression', 'message', 'enabled'], defaults: () => ({ groups: [], actions: [], samples: 1 })
78
+ }),
79
+ ...monitoringDefinitionTools({
80
+ name: 'group', label: 'server group', summary: ['hostname_match'],
81
+ properties: {
82
+ ...common, hostname_match: { ...nonempty, description: 'Regex for automatic hostname assignment. Use (?!) for manual membership only.' },
83
+ alert_actions: S.objects, max_jobs_per_server: { type: 'integer', minimum: 0 }
84
+ },
85
+ required: ['title'], defaults: () => ({ hostname_match: '(?!)' })
86
+ }),
87
+ {
88
+ describe: () => S.describe('test_monitor', 'Evaluate a monitor expression against the latest saved sample for one server. Requires edit_monitors.', {
89
+ server: S.id, ...monitorExpression
90
+ }, ['server', 'source', 'data_type']),
91
+ async run(args, context) {
92
+ return S.pick(await context.callAPI('test_monitor', args), ['value', 'fail']);
93
+ }
94
+ },
95
+ {
96
+ describe: () => S.describe('test_alert', 'Evaluate an alert expression and render its message against the latest saved sample for one server. Requires edit_alerts.', {
97
+ server: S.id, ...alertExpression
98
+ }, ['server', 'expression', 'message']),
99
+ async run(args, context) {
100
+ return S.pick(await context.callAPI('test_alert', args), ['result', 'message']);
101
+ }
102
+ },
103
+ {
104
+ describe: () => S.describe('set_server_groups', 'Set manual group membership for one exact server ID. Replaces all group memberships and disables automatic hostname assignment. Requires update_servers.', {
105
+ id: S.id, groups: { type: 'array', items: S.id, uniqueItems: true, description: 'Complete list of group IDs to assign to this server.' }
106
+ }, ['id', 'groups'], false),
107
+ async run({ id, groups }, context) {
108
+ await context.callAPI('update_server', { id, groups, autoGroup: false });
109
+ return { id, groups, autoGroup: false };
110
+ }
111
+ }
112
+ ];
@@ -0,0 +1,10 @@
1
+ const S = require('../schemas.js');
2
+ const O = require('../job-output.js');
3
+
4
+ exports.describe = () => S.describe('get_job_log', 'Read a completed job console log, including archived logs. Returns bounded text and a byte next_offset. Repeat with that offset while truncated is true. Uses API-key permissions; no download tokens are returned.', {
5
+ id: S.id, offset: O.offset, max_bytes: O.maxBytes
6
+ }, ['id']);
7
+
8
+ exports.run = async function(args, context) {
9
+ return context.readJobLog(args.id, args.offset ?? 0, args.max_bytes ?? 32768);
10
+ };
@@ -1,6 +1,6 @@
1
1
  const S = require('../schemas.js');
2
2
 
3
- exports.describe = () => S.describe('get_job', 'Inspect a running or completed job. Returns status, completion details and output data. Optional fields selects additional job properties. Download tokens are not returned.', { id: S.id, fields: S.strings }, ['id']);
3
+ exports.describe = () => S.describe('get_job', 'Inspect a running or completed job. Returns status, completion details, output data and inline console output. Use get_job_log for completed archived logs, tail_job_log for live console text, and get_workflow_job_outputs for child results. Optional fields selects additional job properties. Download tokens are not returned.', { id: S.id, fields: S.strings }, ['id']);
4
4
 
5
5
  exports.run = async function(args, context) {
6
6
  const { job } = await context.callAPI('get_job', { id: args.id });
@@ -0,0 +1,48 @@
1
+ const S = require('../schemas.js');
2
+ const O = require('../job-output.js');
3
+
4
+ exports.describe = () => S.describe('get_workflow_job_outputs', 'Inspect direct child jobs of a completed workflow. Returns paginated results, bounded console output and output data. Nested workflows are returned as children; call this tool with their IDs to descend. Each child is read with the caller\'s permissions. Use get_job_log for full child logs.', {
5
+ id: S.id, ...S.pagination,
6
+ max_bytes: { ...O.maxBytes, default: 8192, description: 'Maximum UTF-8 bytes per child console output and per child serialized output data. Defaults to 8192.' }
7
+ }, ['id']);
8
+
9
+ exports.run = async function(args, context) {
10
+ const { job } = await context.callAPI('get_job', { id: args.id });
11
+ if (job.type !== 'workflow' || !job.workflow?.jobs) throw new Error('Job is not a workflow with child job records.');
12
+ if (!job.final) throw new Error('Workflow is still running. Use get_job to inspect its current state.');
13
+
14
+ // Sort by node and attempt order so pagination stays stable after completion.
15
+ // Keep repeated executions of a node, including retries and multiplexed jobs.
16
+ const children = Object.keys(job.workflow.jobs).sort().flatMap(node => job.workflow.jobs[node].map(stub => ({ node, id: stub.id })));
17
+ const { offset, limit } = S.page(args, context);
18
+ const bytes = args.max_bytes ?? 8192;
19
+ const rows = [];
20
+ for (const child of children.slice(offset, offset + limit)) {
21
+ let subJob;
22
+ try { subJob = (await context.callAPI('get_job', { id: child.id })).job; }
23
+ catch (err) {
24
+ // Missing, expired or inaccessible children should not hide the rest
25
+ // of the page. Never swallow cancellation and continue fetching jobs.
26
+ if (context.signal?.aborted) throw err;
27
+ rows.push({ ...child, error: err.message });
28
+ continue;
29
+ }
30
+
31
+ const row = { ...S.pick(subJob, ['id', 'title', 'type', 'state', 'final', 'code', 'description', 'started', 'completed', 'elapsed', 'log_file_size']), node: child.node };
32
+ const output = O.textOutput(subJob.output, bytes);
33
+ row.output = output.text;
34
+ row.output_truncated = output.truncated;
35
+ // Large archived logs are not inline. Make their availability explicit
36
+ // without downloading every log or returning shareable token URLs.
37
+ row.log_available = !!(subJob.output || subJob.log_file_size);
38
+ row.log_inline = typeof subJob.output === 'string';
39
+ if (subJob.data !== undefined) {
40
+ const data = O.textOutput(JSON.stringify(subJob.data), bytes);
41
+ row.data_truncated = data.truncated;
42
+ if (data.truncated) row.data_preview = data.text;
43
+ else row.data = subJob.data;
44
+ }
45
+ rows.push(row);
46
+ }
47
+ return { id: args.id, rows, total: children.length, offset, limit, next_offset: offset + rows.length };
48
+ };
@@ -0,0 +1,19 @@
1
+ const S = require('../schemas.js');
2
+
3
+ const filters = {
4
+ event: S.id, category: S.id, server: S.id,
5
+ state: { type: 'string', enum: ['queued', 'start_delay', 'retry_delay', 'ready', 'starting', 'active', 'finishing'] }
6
+ };
7
+
8
+ exports.describe = () => S.describe('list_active_jobs', 'List active jobs, including queued and delayed jobs, newest start time first. Filter by state or exact event, category and server IDs. xyOps applies the API key\'s category and group restrictions.', {
9
+ ...S.pagination, ...filters
10
+ });
11
+
12
+ exports.run = async function(args, context) {
13
+ const { offset, limit } = S.page(args, context);
14
+ // Let xyOps apply filters and permissions before paging. Pick summary fields
15
+ // because active records also hold scripts, environment variables and job data.
16
+ const data = await context.callAPI('get_active_jobs', { ...S.pick(args, Object.keys(filters)), offset, limit });
17
+ const fields = ['id', 'event', 'title', 'type', 'category', 'server', 'state', 'started', 'progress', 'position', 'until'];
18
+ return { rows: data.rows.map(job => S.pick(job, fields)), total: data.list.length, offset, limit };
19
+ };