@channlize/mcp 0.4.0 → 0.6.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/dist/index.js CHANGED
@@ -30,20 +30,41 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
30
30
  // src/index.ts
31
31
  var index_exports = {};
32
32
  __export(index_exports, {
33
+ AGENT_TASK_STATUSES: () => AGENT_TASK_STATUSES,
34
+ AGENT_TOOLS: () => AGENT_TOOLS,
35
+ AGENT_TOOL_NAMES: () => AGENT_TOOL_NAMES,
33
36
  AuthenticationError: () => import_core4.AuthenticationError,
37
+ CONVERSATION_PRIORITIES: () => CONVERSATION_PRIORITIES,
38
+ CONVERSATION_SORTS: () => CONVERSATION_SORTS,
39
+ CONVERSATION_STATUSES: () => CONVERSATION_STATUSES,
40
+ ChannlizeApi: () => ChannlizeApi,
34
41
  ChannlizeError: () => import_core4.ChannlizeError,
35
42
  ChannlizeMCPServer: () => ChannlizeMCPServer,
36
43
  ConfigError: () => ConfigError,
44
+ INBOX_TOOLS: () => INBOX_TOOLS,
45
+ INBOX_TOOL_NAMES: () => INBOX_TOOL_NAMES,
46
+ QUESTION_WAIT_MAX_SECONDS: () => QUESTION_WAIT_MAX_SECONDS,
47
+ ROUTING_FIELDS: () => ROUTING_FIELDS,
48
+ ROUTING_OPERATORS: () => ROUTING_OPERATORS,
37
49
  RateLimitError: () => import_core4.RateLimitError,
38
50
  ToolError: () => ToolError,
39
51
  VERSION: () => VERSION,
40
52
  ValidationError: () => import_core4.ValidationError,
53
+ agentToolsAsJsonSchema: () => agentToolsAsJsonSchema,
41
54
  buildServer: () => buildServer,
42
55
  configFromEnv: () => configFromEnv,
43
56
  createMCPServer: () => createMCPServer,
44
57
  default: () => index_default,
58
+ getAgentTool: () => getAgentTool,
59
+ getInboxTool: () => getInboxTool,
60
+ inboxToolsAsJsonSchema: () => inboxToolsAsJsonSchema,
45
61
  keyKind: () => import_core2.keyKind,
46
- resolveConfig: () => resolveConfig
62
+ registerAgentTools: () => registerAgentTools,
63
+ registerInboxTools: () => registerInboxTools,
64
+ resolveConfig: () => resolveConfig,
65
+ runAgentTool: () => runAgentTool,
66
+ runInboxTool: () => runInboxTool,
67
+ toToolError: () => toToolError
47
68
  });
48
69
  module.exports = __toCommonJS(index_exports);
49
70
  var import_server2 = require("@modelcontextprotocol/server");
@@ -52,21 +73,110 @@ var import_stdio = require("@modelcontextprotocol/server/stdio");
52
73
  // src/api.ts
53
74
  var import_core = require("@channlize/core");
54
75
  var ToolError = class extends Error {
55
- constructor(message, statusCode, code) {
56
- super(message);
76
+ constructor(message2, statusCode, code, retryAt) {
77
+ super(message2);
57
78
  this.statusCode = statusCode;
58
79
  this.code = code;
80
+ this.retryAt = retryAt;
59
81
  this.name = "ToolError";
60
82
  }
61
83
  statusCode;
62
84
  code;
85
+ retryAt;
63
86
  };
64
- function hintFor(status, apiMessage) {
87
+ function scopeFor(apiMessage) {
88
+ const perm = /permission:\s*([\w:*-]+)/i.exec(apiMessage)?.[1] ?? "";
89
+ switch (perm) {
90
+ case "inbox:read":
91
+ return "inbox:read (or read)";
92
+ case "inbox:write":
93
+ return "inbox:write";
94
+ case "routing:read":
95
+ return "routing:write, inbox:read (or read)";
96
+ case "routing:write":
97
+ return "routing:write";
98
+ case "analytics:read":
99
+ return "analytics:read (or read)";
100
+ case "agents:send":
101
+ return "agents:send";
102
+ case "agents:read":
103
+ return "agents:read";
104
+ case "agents:ask_human":
105
+ return "agents:ask_human";
106
+ case "agents:admin":
107
+ return "agents:admin (an unbound key)";
108
+ default:
109
+ return /write|notify/.test(apiMessage) ? "write" : "read";
110
+ }
111
+ }
112
+ function retryText(retryAt) {
113
+ return retryAt ? ` Retry after ${retryAt}, not before.` : "";
114
+ }
115
+ function agentHint(code, body = {}) {
116
+ const retryAt = typeof body.retryAt === "string" ? body.retryAt : void 0;
117
+ switch (code) {
118
+ case "AGENT_KEY_REQUIRED":
119
+ return "Agent tools need an agent key or a multi-agent key: create one under SDK & Integration \u2192 API keys and pick the agents.";
120
+ case "AGENT_NOT_ALLOWED":
121
+ return "The key can't act as that agent: pass one of the key's agents as agentId (list_agents), or fix CHANNLIZE_AGENT_ID.";
122
+ case "NOT_A_CHANNEL_MEMBER":
123
+ return "Only channel members can post (observers only read): use list_agent_channels, or ask an admin to add the agent to the channel.";
124
+ case "AGENT_PAUSED":
125
+ case "AGENT_RETIRED":
126
+ return "Only active agents can act: ask an admin to reactivate it in the dashboard.";
127
+ case "AGENT_RATE_LIMITED":
128
+ return "The agent is sending too fast: wait a minute before sending again.";
129
+ case "AGENT_THREAD_PAUSED": {
130
+ const why = body.reason === "ping_pong" ? " (two agents were going back and forth)" : body.reason === "duplicate_content" ? " (the same message kept being posted)" : "";
131
+ return `The loop guard paused this thread${why}: stop sending in it until a person replies or resumes it. Don't rephrase and retry.`;
132
+ }
133
+ case "HUMAN_TAKEOVER":
134
+ return `A person took over this thread: don't post in it until the takeover ends or they hand it back.${retryText(retryAt)}`;
135
+ case "POLICY_RATE_LIMITED":
136
+ case "POLICY_BUDGET_EXHAUSTED":
137
+ case "POLICY_OUTSIDE_WORKING_HOURS":
138
+ return `The agent's policy refuses this for now: wait, don't retry in a loop.${retryText(retryAt)}`;
139
+ case "POLICY_CHANNEL_NOT_ALLOWED":
140
+ case "POLICY_DM_NOT_ALLOWED":
141
+ case "POLICY_ASK_HUMAN_NOT_ALLOWED":
142
+ case "POLICY_URGENCY_NOT_ALLOWED":
143
+ case "POLICY_MAX_DEPTH":
144
+ return "The agent's policy forbids this: retrying won't help. Pick another channel, agent or urgency, or ask an admin to change the policy.";
145
+ case "TASK_CLOSED":
146
+ return "The task is closed (completed, failed, canceled or rejected) and cannot change: create a new task instead.";
147
+ case "ALREADY_ASSIGNED":
148
+ return "The task is already assigned to that agent.";
149
+ case "AGENT_NOT_IN_CHANNEL":
150
+ return "The other agent isn't a member of the task's channel: pick a member (list_agent_channels), or ask an admin to add it.";
151
+ case "NOT_TASK_PARTICIPANT":
152
+ return "Only the task's assignee or creator can change it or hand it off.";
153
+ case "QUESTION_CLOSED":
154
+ return "The question is already closed (answered, expired or canceled): the first answer wins. Read it with get_answer.";
155
+ case "APPROVAL_ROLE_REQUIRED":
156
+ return "This approval needs a person with the required role: an agent cannot answer it.";
157
+ case "AGENT_ADMIN_KEY_REQUIRED":
158
+ return "This needs an unbound agents:admin key (not a key bound to agents): create one under SDK & Integration \u2192 API keys.";
159
+ case "CHANNEL_NOT_VISIBLE":
160
+ return "Your key's agents can't read that channel: leave channelId out, or pick one from list_agent_channels.";
161
+ case "INVALID_ANSWER":
162
+ return "Answer with one of the question's option ids (approve / deny for approvals), or text when free text is allowed.";
163
+ default:
164
+ return void 0;
165
+ }
166
+ }
167
+ function hintFor(status, apiMessage, code, body) {
168
+ const agent = agentHint(code, body);
169
+ if (agent) return `${apiMessage}. ${agent}`;
170
+ if (status === 400 && /agent_id is required/i.test(apiMessage)) {
171
+ return `${apiMessage}. Pass agentId (from list_agents), or set CHANNLIZE_AGENT_ID / --agent-id on the MCP server.`;
172
+ }
65
173
  switch (status) {
66
174
  case 401:
67
175
  return `${apiMessage}. The server API key is invalid, revoked or expired: create a new one under SDK & Integration \u2192 API keys and update CHANNLIZE_SERVER_API_KEY.`;
68
176
  case 403:
69
- return /permission/i.test(apiMessage) ? `${apiMessage}. This needs a server API key with the ${/write|notify/.test(apiMessage) ? "write" : "read"} scope: create one under SDK & Integration \u2192 API keys.` : apiMessage;
177
+ return /permission/i.test(apiMessage) ? `${apiMessage}. This needs a server API key with the ${scopeFor(
178
+ apiMessage
179
+ )} scope: create one under SDK & Integration \u2192 API keys.` : apiMessage;
70
180
  case 404:
71
181
  return `${apiMessage}. Check the ID (and CHANNLIZE_PROJECT_ID): it must belong to the key's organization.`;
72
182
  case 429:
@@ -79,9 +189,15 @@ function toToolError(err) {
79
189
  if (err instanceof ToolError) return err;
80
190
  if (err instanceof import_core.ChannlizeError) {
81
191
  return new ToolError(
82
- err.statusCode ? hintFor(err.statusCode, err.message.replace(/\.$/, "")) : err.message,
192
+ err.statusCode ? hintFor(
193
+ err.statusCode,
194
+ err.message.replace(/\.$/, ""),
195
+ err.code,
196
+ err.details
197
+ ) : err.message,
83
198
  err.statusCode,
84
- err.code
199
+ err.code,
200
+ err.retryAt
85
201
  );
86
202
  }
87
203
  return new ToolError(err instanceof Error ? err.message : String(err));
@@ -99,6 +215,10 @@ var ChannlizeApi = class {
99
215
  get hasWidgetKey() {
100
216
  return !!this.config.widgetKey;
101
217
  }
218
+ /** The default agent for the agent tools (`CHANNLIZE_AGENT_ID`). */
219
+ get agentId() {
220
+ return this.config.agentId;
221
+ }
102
222
  requireServerKey() {
103
223
  if (!this.config.serverApiKey) {
104
224
  throw new ToolError(
@@ -107,9 +227,10 @@ var ChannlizeApi = class {
107
227
  }
108
228
  return this.config.serverApiKey;
109
229
  }
110
- async request(method, path, options = {}) {
230
+ async request(method, path2, options = {}) {
111
231
  const key = this.requireServerKey();
112
- const url2 = new URL(`${this.config.baseUrl}${path}`);
232
+ const timeout = options.timeout ?? this.config.timeout;
233
+ const url2 = new URL(`${this.config.baseUrl}${path2}`);
113
234
  for (const [k, v] of Object.entries(options.query ?? {})) {
114
235
  if (v !== void 0 && v !== "") url2.searchParams.set(k, String(v));
115
236
  }
@@ -125,13 +246,13 @@ var ChannlizeApi = class {
125
246
  },
126
247
  // oxlint-disable-next-line unicorn/no-invalid-fetch-options -- `method` is dynamic; GET calls never pass a body.
127
248
  body: options.body !== void 0 ? JSON.stringify(options.body) : void 0,
128
- signal: AbortSignal.timeout(this.config.timeout)
249
+ signal: AbortSignal.timeout(timeout)
129
250
  });
130
251
  } catch (err) {
131
252
  const e = err;
132
253
  if (e.name === "TimeoutError" || e.name === "AbortError") {
133
254
  throw new ToolError(
134
- `Channlize API timed out after ${this.config.timeout} ms (${method} ${url2.pathname}). Retry, or raise CHANNLIZE_TIMEOUT.`,
255
+ `Channlize API timed out after ${timeout} ms (${method} ${url2.pathname}). Retry, or raise CHANNLIZE_TIMEOUT.`,
135
256
  408,
136
257
  "TIMEOUT"
137
258
  );
@@ -141,28 +262,34 @@ var ChannlizeApi = class {
141
262
  );
142
263
  }
143
264
  const text = await res.text();
144
- let data = void 0;
265
+ let data2 = void 0;
145
266
  if (text) {
146
267
  try {
147
- data = JSON.parse(text);
268
+ data2 = JSON.parse(text);
148
269
  } catch {
149
- data = void 0;
270
+ data2 = void 0;
150
271
  }
151
272
  }
152
273
  if (!res.ok) {
153
- const { message, code } = (0, import_core.parseApiError)(res.status, data, res.statusText);
274
+ const { message: message2, code, body } = (0, import_core.parseApiError)(
275
+ res.status,
276
+ data2,
277
+ res.statusText
278
+ );
279
+ const retryAt = typeof body.retryAt === "string" ? body.retryAt : void 0;
154
280
  throw new ToolError(
155
- hintFor(res.status, message.replace(/\.$/, "")),
281
+ hintFor(res.status, message2.replace(/\.$/, ""), code, body),
156
282
  res.status,
157
- code
283
+ code,
284
+ retryAt
158
285
  );
159
286
  }
160
- if (data === void 0) {
287
+ if (data2 === void 0) {
161
288
  throw new ToolError(
162
289
  `Unexpected non-JSON response from ${method} ${url2.pathname}`
163
290
  );
164
291
  }
165
- return data;
292
+ return data2;
166
293
  }
167
294
  /**
168
295
  * `CHANNLIZE_PROJECT_ID`, or the first project of the key's organization
@@ -218,11 +345,12 @@ var ChannlizeApi = class {
218
345
  // src/config.ts
219
346
  var import_core2 = require("@channlize/core");
220
347
  var ConfigError = class extends Error {
221
- constructor(message) {
222
- super(message);
348
+ constructor(message2) {
349
+ super(message2);
223
350
  this.name = "ConfigError";
224
351
  }
225
352
  };
353
+ var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
226
354
  function clean(value) {
227
355
  const v = value?.trim();
228
356
  return v ? v : void 0;
@@ -267,17 +395,33 @@ function resolveConfig(config) {
267
395
  `Invalid base URL "${config.baseUrl}": use e.g. ${import_core2.DEFAULT_BASE_URL}`
268
396
  );
269
397
  }
398
+ const agentId2 = clean(config.agentId);
399
+ if (agentId2 && !UUID.test(agentId2)) {
400
+ throw new ConfigError(
401
+ `Invalid agent ID "${agentId2}": CHANNLIZE_AGENT_ID / --agent-id takes the agent's ID (a UUID, shown in the dashboard under Agents), not its slug.`
402
+ );
403
+ }
270
404
  return {
271
405
  serverApiKey,
272
406
  widgetKey,
273
407
  projectId: clean(config.projectId),
408
+ agentId: agentId2,
274
409
  baseUrl,
275
410
  timeout
276
411
  };
277
412
  }
278
413
  function configFromEnv(env = process.env) {
279
- const { timeout, ...rest } = (0, import_core2.readChannlizeEnv)(env);
280
- return { ...rest, timeout: timeout ? Number(timeout) : void 0 };
414
+ const { timeout, serverApiKey, widgetKey, apiKey, projectId, baseUrl } = (0, import_core2.readChannlizeEnv)(env);
415
+ return {
416
+ serverApiKey,
417
+ widgetKey,
418
+ apiKey,
419
+ projectId,
420
+ baseUrl,
421
+ timeout: timeout ? Number(timeout) : void 0,
422
+ // Read here rather than from core, so older @channlize/core versions work.
423
+ agentId: clean(env.CHANNLIZE_AGENT_ID)
424
+ };
281
425
  }
282
426
 
283
427
  // src/prompts.ts
@@ -457,12 +601,12 @@ function registerServerPrompts(server) {
457
601
  },
458
602
  ({ status, limit }) => user(`Triage my Channlize support inbox.
459
603
 
460
- 1. Call list_conversations with status "${status || "open"}" and limit ${Number(limit) || 10}.
604
+ 1. Call list_conversations with status ["${status || "open"}"] and limit ${Number(limit) || 10}.
461
605
  2. For each conversation, call get_conversation to read the thread.
462
606
  3. Return a table sorted by urgency: subject, customer, how long it has waited, current priority, a suggested priority (low / normal / high / urgent) and a one-line reason.
463
607
  4. Under the table, draft a short, friendly reply for each conversation that needs one, and flag anything that looks like a bug, an outage or a billing problem.
464
608
 
465
- Replies and status or priority changes are made by the team in the Slack thread or the Channlize dashboard, so present the drafts for me to send; don't invent facts about my product.`)
609
+ Present the drafts for me to review; don't invent facts about my product. Only if I confirm, and the key has the inbox:write scope, send them with reply_to_conversation, or post them for the team with add_internal_note; tag, assign or close with the matching tools.`)
466
610
  );
467
611
  server.registerPrompt(
468
612
  "summarize-conversation",
@@ -473,8 +617,8 @@ Replies and status or priority changes are made by the team in the Slack thread
473
617
  conversationId: z.string().describe("Conversation ID")
474
618
  })
475
619
  },
476
- ({ conversationId }) => user(
477
- `Call get_conversation with conversationId "${conversationId}". Summarize it in five bullet points or fewer: what the customer wants, what has been answered, what is still open, and the customer's mood. Then suggest the next step and draft a reply if one is needed.`
620
+ ({ conversationId: conversationId2 }) => user(
621
+ `Call get_conversation with conversationId "${conversationId2}". Summarize it in five bullet points or fewer: what the customer wants, what has been answered, what is still open, and the customer's mood. Then suggest the next step and draft a reply if one is needed.`
478
622
  )
479
623
  );
480
624
  server.registerPrompt(
@@ -605,14 +749,1832 @@ function registerResources(server, api) {
605
749
  }
606
750
 
607
751
  // src/tools.ts
608
- var z2 = __toESM(require("zod/v4"));
752
+ var z4 = __toESM(require("zod/v4"));
609
753
  var import_core3 = require("@channlize/core");
610
- var STATUSES = ["open", "pending", "resolved", "closed"];
611
- var PRIORITIES = ["low", "normal", "high", "urgent"];
612
- function ok(data) {
754
+
755
+ // src/agents.ts
756
+ var z2 = __toESM(require("zod/v4"));
757
+
758
+ // src/agents-summary.ts
759
+ var num = (v) => typeof v === "number" ? v : Number(v) || 0;
760
+ var arr = (v) => Array.isArray(v) ? v : [];
761
+ var obj = (v) => v && typeof v === "object" ? v : {};
762
+ var str = (v) => typeof v === "string" ? v : null;
763
+ function money(v) {
764
+ return Math.round(num(v) * 1e4) / 1e4;
765
+ }
766
+ function fmtMoney(v) {
767
+ return money(v).toFixed(4).replace(/\.?0+$/, "") || "0";
768
+ }
769
+ function pct(v) {
770
+ return v === null || v === void 0 ? "n/a" : `${Math.round(num(v) * 1e3) / 10}%`;
771
+ }
772
+ function fmtMs(v) {
773
+ if (v === null || v === void 0) return "n/a";
774
+ const ms = num(v);
775
+ if (ms < 1e3) return `${Math.round(ms)}ms`;
776
+ if (ms < 6e4) return `${Math.round(ms / 100) / 10}s`;
777
+ if (ms < 36e5) return `${Math.round(ms / 6e3) / 10}m`;
778
+ return `${Math.round(ms / 36e4) / 10}h`;
779
+ }
780
+ function highlightText(html) {
781
+ return html.replace(/<mark>/g, "**").replace(/<\/mark>/g, "**").replace(/<[^>]*>/g, "").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&amp;/g, "&");
782
+ }
783
+ function clip(text, max) {
784
+ const s = typeof text === "string" ? text : "";
785
+ return s.length > max ? `${s.slice(0, max - 1)}\u2026` : s;
786
+ }
787
+ function rangeSummary(range2) {
788
+ const r = obj(range2);
789
+ return {
790
+ from: String(r.from ?? ""),
791
+ to: String(r.to ?? ""),
792
+ days: num(r.days),
793
+ historyStart: str(r.history_start),
794
+ retentionDays: r.retention_days === void 0 ? null : num(r.retention_days),
795
+ clamped: Boolean(r.clamped),
796
+ empty: Boolean(r.empty)
797
+ };
798
+ }
799
+ function rangeNote(r) {
800
+ const base = `${r.from}..${r.to} (${r.days} day${r.days === 1 ? "" : "s"}, UTC)`;
801
+ return r.clamped ? `${base}; clamped to the plan's history start ${r.historyStart}` : base;
802
+ }
803
+ function latency(v) {
804
+ const l = obj(v);
805
+ return {
806
+ count: num(l.count),
807
+ avgMs: l.avg_ms === null || l.avg_ms === void 0 ? null : num(l.avg_ms),
808
+ p50Ms: l.p50_ms === null || l.p50_ms === void 0 ? null : num(l.p50_ms),
809
+ p90Ms: l.p90_ms === null || l.p90_ms === void 0 ? null : num(l.p90_ms)
810
+ };
811
+ }
812
+ function summarizeSearch(r) {
813
+ const results = arr(r.results).map((x) => {
814
+ const channel = x.channel ? obj(x.channel) : null;
815
+ const base = {
816
+ kind: String(x.kind),
817
+ highlight: clip(highlightText(String(x.highlight ?? "")), 400),
818
+ rank: Math.round(num(x.rank) * 1e3) / 1e3,
819
+ channel: channel ? str(channel.slug) ?? str(channel.id) : null,
820
+ channelId: channel ? str(channel.id) : null,
821
+ threadId: str(x.thread_id),
822
+ slackPermalink: str(x.slack_permalink)
823
+ };
824
+ if (x.kind === "question") {
825
+ const q = obj(x.question);
826
+ const answer = q.answer ? obj(q.answer) : null;
827
+ return {
828
+ ...base,
829
+ id: String(q.id ?? ""),
830
+ type: "question",
831
+ text: clip(q.question, 500),
832
+ status: str(q.status),
833
+ answer: answer ? clip(
834
+ [answer.option_label ?? answer.option_id, answer.text].filter(Boolean).join(" / "),
835
+ 200
836
+ ) || null : null,
837
+ sender: str(q.agent_id) ? `agent:${String(q.agent_id)}` : null,
838
+ createdAt: str(q.created_at)
839
+ };
840
+ }
841
+ const m = obj(x.message);
842
+ const sender = obj(m.sender);
843
+ const senderId = sender.agent_id ?? sender.user_id ?? sender.slack_user_id;
844
+ return {
845
+ ...base,
846
+ id: String(m.id ?? ""),
847
+ type: String(m.type ?? "message"),
848
+ text: clip(m.text, 500),
849
+ status: str(m.task_status),
850
+ answer: null,
851
+ sender: sender.kind ? `${String(sender.kind)}${senderId ? `:${String(senderId)}` : ""}` : null,
852
+ createdAt: str(m.created_at)
853
+ };
854
+ });
855
+ const window = obj(r.window);
856
+ return {
857
+ results,
858
+ nextCursor: str(r.next_cursor),
859
+ window: { from: String(window.from ?? ""), days: num(window.days) }
860
+ };
861
+ }
862
+ function summarizeGraph(r, top2) {
863
+ const range2 = rangeSummary(r.range);
864
+ const nodes = arr(r.nodes);
865
+ const labels = new Map(nodes.map((n) => [String(n.id), String(n.label)]));
866
+ const topNodes = [...nodes].sort(
867
+ (a, b) => num(b.sent) + num(b.received) - (num(a.sent) + num(a.received))
868
+ ).slice(0, top2).map((n) => ({
869
+ id: String(n.id),
870
+ kind: String(n.kind),
871
+ label: String(n.label),
872
+ slug: str(n.slug),
873
+ sent: num(n.sent),
874
+ received: num(n.received),
875
+ tokens: num(n.tokens),
876
+ cost: money(n.cost)
877
+ }));
878
+ const edges = arr(r.edges);
879
+ const topEdges = [...edges].sort((a, b) => num(b.messages) - num(a.messages)).slice(0, top2).map((e) => {
880
+ const l = latency(e.reply_latency);
881
+ return {
882
+ source: String(e.source),
883
+ target: String(e.target),
884
+ from: labels.get(String(e.source)) ?? String(e.source),
885
+ to: labels.get(String(e.target)) ?? String(e.target),
886
+ messages: num(e.messages),
887
+ replies: num(e.replies),
888
+ cost: money(e.cost),
889
+ replyAvgMs: l.avgMs,
890
+ replyP90Ms: l.p90Ms,
891
+ lastAt: str(e.last_at)
892
+ };
893
+ });
894
+ const totals = obj(r.totals);
895
+ const truncated = obj(r.truncated);
896
+ const t = {
897
+ nodes: num(totals.nodes),
898
+ edges: num(totals.edges),
899
+ messages: num(totals.messages),
900
+ tokens: num(totals.tokens),
901
+ cost: money(totals.cost)
902
+ };
903
+ const busiest = topEdges[0];
904
+ return {
905
+ range: range2,
906
+ totals: t,
907
+ topNodes,
908
+ topEdges,
909
+ /** Not shown here: beyond `top`, or folded / dropped by the API's cap. */
910
+ omitted: {
911
+ nodes: Math.max(0, nodes.length - topNodes.length),
912
+ edges: Math.max(0, edges.length - topEdges.length),
913
+ cappedNodes: num(truncated.nodes),
914
+ cappedEdges: num(truncated.edges)
915
+ },
916
+ summary: range2.empty ? `No visible activity in ${rangeNote(range2)}.` : `${t.nodes} participants, ${t.edges} edges, ${t.messages} messages, cost ${fmtMoney(t.cost)} over ${rangeNote(range2)}.` + (busiest ? ` Busiest edge: ${busiest.from} \u2192 ${busiest.to} (${busiest.messages} messages, reply avg ${fmtMs(busiest.replyAvgMs)}).` : "")
917
+ };
918
+ }
919
+ function summarizeCost(r, top2) {
920
+ const range2 = rangeSummary(r.range);
921
+ const totals = obj(r.totals);
922
+ const t = {
923
+ messages: num(totals.messages),
924
+ pricedMessages: num(totals.priced_messages),
925
+ tokens: num(totals.tokens),
926
+ cost: money(totals.cost)
927
+ };
928
+ const all = arr(r.groups);
929
+ const groups = all.slice(0, top2).map((g) => ({
930
+ key: String(g.key),
931
+ label: clip(g.label, 120),
932
+ messages: num(g.messages),
933
+ tokens: num(g.tokens),
934
+ cost: money(g.cost),
935
+ share: g.share === null || g.share === void 0 ? null : num(g.share)
936
+ }));
937
+ const active = arr(r.series).filter(
938
+ (d) => num(d.messages) > 0 || num(d.cost) > 0
939
+ );
940
+ const daily = active.slice(-31).map((d) => ({
941
+ day: String(d.day),
942
+ messages: num(d.messages),
943
+ tokens: num(d.tokens),
944
+ cost: money(d.cost)
945
+ }));
946
+ const peak = active.reduce(
947
+ (best, d) => !best || num(d.cost) > num(best.cost) ? d : best,
948
+ null
949
+ );
950
+ const groupBy = String(r.group_by ?? "agent");
951
+ const head = groups.slice(0, 3).map((g) => `${g.label} ${fmtMoney(g.cost)} (${pct(g.share)})`).join(", ");
952
+ return {
953
+ range: range2,
954
+ groupBy,
955
+ totals: t,
956
+ groups,
957
+ omittedGroups: Math.max(0, all.length - groups.length),
958
+ /** The API had more groups than it returned. */
959
+ truncated: Boolean(r.truncated),
960
+ daily,
961
+ peakDay: peak ? { day: String(peak.day), cost: money(peak.cost) } : null,
962
+ summary: range2.empty ? `No visible activity in ${rangeNote(range2)}.` : `Total cost ${fmtMoney(t.cost)} (as reported by agents), ${t.tokens} tokens, ${t.messages} messages (${t.pricedMessages} priced) over ${rangeNote(range2)}.` + (head ? ` Top by ${groupBy}: ${head}.` : "")
963
+ };
964
+ }
965
+ function pair(v) {
966
+ const p = obj(v);
967
+ const l = latency(p.latency);
968
+ return {
969
+ messages: num(p.messages),
970
+ replied: num(p.replied),
971
+ replyRate: p.reply_rate === null || p.reply_rate === void 0 ? null : num(p.reply_rate),
972
+ avgMs: l.avgMs,
973
+ p50Ms: l.p50Ms,
974
+ p90Ms: l.p90Ms
975
+ };
976
+ }
977
+ function summarizeMetrics(r, top2) {
978
+ const range2 = rangeSummary(r.range);
979
+ const replies = obj(r.replies);
980
+ const q = obj(r.questions);
981
+ const qLatency = latency(q.time_to_human_answer);
982
+ const byUrgency = obj(q.by_urgency);
983
+ const d = obj(r.deliveries);
984
+ const byMode = obj(d.by_mode);
985
+ const backlog = obj(r.backlog);
986
+ const rate = (v) => v === null || v === void 0 ? null : num(v);
987
+ const out = {
988
+ range: range2,
989
+ replies: {
990
+ agentToAgent: pair(replies.agent_to_agent),
991
+ humanToAgent: pair(replies.human_to_agent),
992
+ agentToHuman: pair(replies.agent_to_human),
993
+ byAgent: arr(replies.by_agent).slice(0, top2).map((a) => {
994
+ const l = latency(a.latency);
995
+ return {
996
+ agentId: String(a.agent_id),
997
+ name: str(a.name),
998
+ messages: num(a.messages),
999
+ replied: num(a.replied),
1000
+ avgMs: l.avgMs,
1001
+ p90Ms: l.p90Ms
1002
+ };
1003
+ })
1004
+ },
1005
+ questions: {
1006
+ asked: num(q.asked),
1007
+ answered: num(q.answered),
1008
+ answeredByUser: num(q.answered_by_user),
1009
+ answeredByAgent: num(q.answered_by_agent),
1010
+ expired: num(q.expired),
1011
+ expiredDefault: num(q.expired_default),
1012
+ canceled: num(q.canceled),
1013
+ answerRate: rate(q.answer_rate),
1014
+ timeToHumanAnswer: {
1015
+ count: qLatency.count,
1016
+ avgMs: qLatency.avgMs,
1017
+ p50Ms: qLatency.p50Ms,
1018
+ p90Ms: qLatency.p90Ms
1019
+ },
1020
+ byUrgency: Object.fromEntries(
1021
+ ["low", "normal", "high", "urgent"].map((u) => {
1022
+ const b = obj(byUrgency[u]);
1023
+ return [
1024
+ u,
1025
+ {
1026
+ asked: num(b.asked),
1027
+ answerRate: rate(b.answer_rate),
1028
+ p50Ms: latency(b.time_to_human_answer).p50Ms
1029
+ }
1030
+ ];
1031
+ })
1032
+ )
1033
+ },
1034
+ deliveries: {
1035
+ deliveries: num(d.deliveries),
1036
+ failed: num(d.failed),
1037
+ retried: num(d.retried),
1038
+ failureRate: rate(d.failure_rate),
1039
+ retryRate: rate(d.retry_rate),
1040
+ byMode: Object.fromEntries(
1041
+ ["webhook", "inbox", "a2a"].map((m) => {
1042
+ const b = obj(byMode[m]);
1043
+ return [
1044
+ m,
1045
+ {
1046
+ deliveries: num(b.deliveries),
1047
+ failed: num(b.failed),
1048
+ held: num(b.held),
1049
+ failureRate: rate(b.failure_rate),
1050
+ retryRate: rate(b.retry_rate)
1051
+ }
1052
+ ];
1053
+ })
1054
+ )
1055
+ },
1056
+ backlog: {
1057
+ asOf: String(backlog.as_of ?? ""),
1058
+ unacked: num(backlog.unacked),
1059
+ held: num(backlog.held),
1060
+ agentsWithBacklog: num(backlog.agents_with_backlog),
1061
+ agents: arr(backlog.agents).slice(0, top2).map((a) => ({
1062
+ agentId: String(a.agent_id),
1063
+ name: str(a.name),
1064
+ delivery: str(a.delivery),
1065
+ unacked: num(a.unacked),
1066
+ held: num(a.held),
1067
+ oldestAgeSeconds: a.oldest_age_seconds === null || a.oldest_age_seconds === void 0 ? null : num(a.oldest_age_seconds)
1068
+ }))
1069
+ },
1070
+ summary: ""
1071
+ };
1072
+ const h2a = out.replies.humanToAgent;
1073
+ const a2a = out.replies.agentToAgent;
1074
+ out.summary = `Over ${rangeNote(range2)}: agents answered people in avg ${fmtMs(h2a.avgMs)} (p90 ${fmtMs(h2a.p90Ms)}, ${pct(h2a.replyRate)} replied) and other agents in avg ${fmtMs(a2a.avgMs)} (p90 ${fmtMs(a2a.p90Ms)}). Questions: ${out.questions.asked} asked, ${pct(out.questions.answerRate)} answered, human answer p50 ${fmtMs(out.questions.timeToHumanAnswer.p50Ms)}. Deliveries: ${out.deliveries.deliveries}, ${pct(out.deliveries.failureRate)} failed, ${pct(out.deliveries.retryRate)} retried. Backlog now: ${out.backlog.unacked} unacked, ${out.backlog.held} held.`;
1075
+ return out;
1076
+ }
1077
+
1078
+ // src/agents.ts
1079
+ function defineTool(tool) {
1080
+ return tool;
1081
+ }
1082
+ var AGENT_TASK_STATUSES = [
1083
+ "open",
1084
+ "working",
1085
+ "input_required",
1086
+ "completed",
1087
+ "failed",
1088
+ "canceled",
1089
+ "rejected"
1090
+ ];
1091
+ var uuid = (what) => z2.string().uuid().describe(what);
1092
+ var agentId = uuid(
1093
+ "The agent to act as (from list_agents). Needed with a multi-agent key unless the server has a default agent (CHANNLIZE_AGENT_ID); leave it out with an agent key."
1094
+ ).optional();
1095
+ var channelId = uuid("Agent channel ID (from list_agent_channels)");
1096
+ var threadId = uuid(
1097
+ "Reply in this thread: the id of any message in it (thread_id or id from read_agent_inbox)"
1098
+ ).optional();
1099
+ var mentions = z2.array(z2.string().uuid()).max(50).optional().describe("Agent IDs to mention (from list_agents)");
1100
+ var data = z2.record(z2.string(), z2.unknown()).optional().describe("Structured data for the recipients (JSON object)");
1101
+ var usage = {
1102
+ tokens: z2.number().int().min(0).optional().describe("Tokens you used for this message (reporting)"),
1103
+ cost: z2.number().min(0).optional().describe("What this message cost you, in USD (reporting)")
1104
+ };
1105
+ var message = z2.looseObject({
1106
+ id: z2.string(),
1107
+ channel_id: z2.string(),
1108
+ thread_id: z2.string().nullable(),
1109
+ type: z2.string(),
1110
+ text: z2.string(),
1111
+ sender: z2.looseObject({ kind: z2.string() }),
1112
+ task_status: z2.string().nullable().optional()
1113
+ });
1114
+ var sendOutput = z2.object({
1115
+ message,
1116
+ deliveries: z2.array(
1117
+ z2.looseObject({ id: z2.string(), agent_id: z2.string(), status: z2.string() })
1118
+ )
1119
+ });
1120
+ var dueAt = z2.string().max(40).optional().describe("Due date: an ISO date (2026-11-30) or date-time");
1121
+ var task = z2.looseObject({
1122
+ id: z2.string(),
1123
+ channel_id: z2.string(),
1124
+ text: z2.string(),
1125
+ board_status: z2.string(),
1126
+ assignee_agent_id: z2.string().nullable(),
1127
+ due_at: z2.string().nullable()
1128
+ });
1129
+ var deliveries = z2.array(
1130
+ z2.looseObject({ id: z2.string(), agent_id: z2.string(), status: z2.string() })
1131
+ );
1132
+ var question = z2.looseObject({
1133
+ id: z2.string(),
1134
+ kind: z2.string(),
1135
+ question: z2.string(),
1136
+ status: z2.string(),
1137
+ answer: z2.looseObject({}).nullable()
1138
+ });
1139
+ var questionId = uuid("The question ID (from ask_human or list_questions)");
1140
+ var BOARD_STATUSES = [
1141
+ "open",
1142
+ "in_progress",
1143
+ "blocked",
1144
+ "done",
1145
+ "failed"
1146
+ ];
1147
+ var QUESTION_WAIT_MAX_SECONDS = 25;
1148
+ var READ = {
1149
+ readOnlyHint: true,
1150
+ destructiveHint: false,
1151
+ idempotentHint: true,
1152
+ openWorldHint: false
1153
+ };
1154
+ var SEND = {
1155
+ readOnlyHint: false,
1156
+ destructiveHint: false,
1157
+ idempotentHint: false,
1158
+ openWorldHint: true
1159
+ };
1160
+ function actingAs(api, id2) {
1161
+ return id2 ?? api.agentId;
1162
+ }
1163
+ function requireAgent(api, id2) {
1164
+ const agent = actingAs(api, id2);
1165
+ if (!agent) {
1166
+ throw new ToolError(
1167
+ "Pass agentId (from list_agents), or set CHANNLIZE_AGENT_ID / --agent-id on the MCP server."
1168
+ );
1169
+ }
1170
+ return agent;
1171
+ }
1172
+ async function send(api, body) {
1173
+ const r = await api.request(
1174
+ "POST",
1175
+ "/v1/agents/messages",
1176
+ { body }
1177
+ );
1178
+ return { message: r.message, deliveries: r.deliveries ?? [] };
1179
+ }
1180
+ var enc = encodeURIComponent;
1181
+ function outcomeMessage(status, q) {
1182
+ const answer = q.answer ?? {};
1183
+ const choice = answer.option_label ?? answer.option_id;
1184
+ const comment = answer.comment ? `: ${String(answer.comment)}` : "";
1185
+ switch (status) {
1186
+ case "answered":
1187
+ if (q.kind === "approval") {
1188
+ return answer.approved ? `Approved${comment}. Go ahead.` : `Denied${comment}. Don't do it.`;
1189
+ }
1190
+ return `Answered: ${[choice, answer.text].filter(Boolean).join(" / ") || "(empty)"}.`;
1191
+ case "expired_default":
1192
+ return `Nobody answered by the deadline: the default option applies (${String(choice ?? "none")}).`;
1193
+ case "expired":
1194
+ return "Nobody answered by the deadline and there is no default: decide whether to ask again or drop it. For an approval, treat it as not approved.";
1195
+ case "canceled":
1196
+ return "The question was canceled.";
1197
+ default:
1198
+ return `Status: ${status}.`;
1199
+ }
1200
+ }
1201
+ var AGENT_MESSAGE_TYPES = [
1202
+ "message",
1203
+ "task",
1204
+ "question",
1205
+ "escalation",
1206
+ "status"
1207
+ ];
1208
+ var insightsDay = (what) => z2.string().regex(/^\d{4}-\d{2}-\d{2}$/, "expected a YYYY-MM-DD date").optional().describe(what);
1209
+ var insightsRange = {
1210
+ from: insightsDay(
1211
+ "First UTC day, YYYY-MM-DD (default: 30 days before to). Clamped to the plan history window."
1212
+ ),
1213
+ to: insightsDay("Last UTC day, inclusive, YYYY-MM-DD (default: today)"),
1214
+ channelId: channelId.optional().describe("Only this agent channel")
1215
+ };
1216
+ var insightsAgent = uuid(
1217
+ "Only this agent (from list_agents): pass your own id to see your own numbers"
1218
+ ).optional();
1219
+ var mine = z2.boolean().optional().describe(
1220
+ "true: only your own agent (the server's default agent, CHANNLIZE_AGENT_ID), when you don't know your id"
1221
+ );
1222
+ var top = (dflt) => z2.number().int().min(1).max(50).default(dflt).describe(`How many rows to return in each list (1-50, default ${dflt})`);
1223
+ function filterAgent(api, a) {
1224
+ if (a.agentId) return a.agentId;
1225
+ return a.mine ? requireAgent(api, void 0) : void 0;
1226
+ }
1227
+ var range = z2.looseObject({
1228
+ from: z2.string(),
1229
+ to: z2.string(),
1230
+ days: z2.number(),
1231
+ clamped: z2.boolean(),
1232
+ empty: z2.boolean()
1233
+ });
1234
+ var nullableNumber = z2.number().nullable();
1235
+ var AGENT_TOOLS = [
1236
+ defineTool({
1237
+ name: "send_agent_message",
1238
+ title: "Send agent message",
1239
+ description: "Post a message to an agent channel as your agent. Every other agent in the channel receives it (webhook, inbox or A2A), people see it in Slack and the dashboard, and it counts as one Event. Reply in a thread with threadId; mention agents with mentions. Needs the agents:send scope, and the agent must be a member of the channel.",
1240
+ scope: "agents:send",
1241
+ endpoint: "POST /v1/agents/messages",
1242
+ inputSchema: z2.object({
1243
+ agentId,
1244
+ channelId,
1245
+ text: z2.string().min(1).max(4e4).describe("Message text"),
1246
+ threadId,
1247
+ mentions,
1248
+ data,
1249
+ ...usage
1250
+ }),
1251
+ outputSchema: sendOutput,
1252
+ annotations: SEND,
1253
+ handler: (api, a) => send(api, {
1254
+ agent_id: actingAs(api, a.agentId),
1255
+ channel_id: a.channelId,
1256
+ type: "message",
1257
+ text: a.text,
1258
+ thread_id: a.threadId,
1259
+ mentions: a.mentions,
1260
+ data: a.data,
1261
+ tokens: a.tokens,
1262
+ cost: a.cost
1263
+ })
1264
+ }),
1265
+ defineTool({
1266
+ name: "create_task",
1267
+ title: "Create task",
1268
+ description: "Hand a task to an agent of a channel: creates a task (board status open) that starts its own thread, optionally assigned to a member agent (assigneeAgentId, who is mentioned) and with a due date. The returned taskId is for update_task, update_task_status and handoff_task. Your policy may refuse the channel or the assignee (POLICY_* errors). Needs the agents:send scope.",
1269
+ scope: "agents:send",
1270
+ endpoint: "POST /v1/agents/tasks",
1271
+ inputSchema: z2.object({
1272
+ agentId,
1273
+ channelId,
1274
+ text: z2.string().min(1).max(4e4).describe("What should be done, with enough context to do it"),
1275
+ assigneeAgentId: uuid(
1276
+ "The agent that should do it: a member of the channel (from list_agents)"
1277
+ ).optional(),
1278
+ dueAt,
1279
+ threadId,
1280
+ mentions,
1281
+ data
1282
+ }),
1283
+ // `message` is the task too (a task is its `task` message plus board fields).
1284
+ outputSchema: z2.object({ taskId: z2.string(), task, message, deliveries }),
1285
+ annotations: SEND,
1286
+ handler: async (api, a) => {
1287
+ const r = await api.request(
1288
+ "POST",
1289
+ "/v1/agents/tasks",
1290
+ {
1291
+ body: {
1292
+ agent_id: actingAs(api, a.agentId),
1293
+ channel_id: a.channelId,
1294
+ text: a.text,
1295
+ assignee_agent_id: a.assigneeAgentId,
1296
+ due_at: a.dueAt,
1297
+ thread_id: a.threadId,
1298
+ mentions: a.mentions,
1299
+ data: a.data
1300
+ }
1301
+ }
1302
+ );
1303
+ return {
1304
+ taskId: String(r.task.id),
1305
+ task: r.task,
1306
+ message: r.task,
1307
+ deliveries: r.deliveries ?? []
1308
+ };
1309
+ }
1310
+ }),
1311
+ defineTool({
1312
+ name: "update_task_status",
1313
+ title: "Update task status",
1314
+ description: "Report progress on a task (from create_task or a task in your inbox): working, input_required, completed, failed, canceled or rejected, with an optional note and result data. It is posted in the task thread and moves the task on the board (working \u2192 in_progress, input_required \u2192 blocked, completed \u2192 done; canceled and rejected show as failed). completed, failed, canceled and rejected are final: a closed task cannot be reopened (TASK_CLOSED). To change the due date, use update_task. Needs the agents:send scope.",
1315
+ scope: "agents:send",
1316
+ endpoint: "POST /v1/agents/messages",
1317
+ inputSchema: z2.object({
1318
+ agentId,
1319
+ channelId,
1320
+ taskId: uuid("The task message ID"),
1321
+ status: z2.enum(AGENT_TASK_STATUSES).describe("The new status of the task"),
1322
+ text: z2.string().max(4e4).optional().describe("What changed, e.g. the result or what input is needed"),
1323
+ data,
1324
+ ...usage
1325
+ }),
1326
+ outputSchema: sendOutput,
1327
+ annotations: SEND,
1328
+ handler: (api, a) => send(api, {
1329
+ agent_id: actingAs(api, a.agentId),
1330
+ channel_id: a.channelId,
1331
+ type: "status",
1332
+ text: a.text ?? "",
1333
+ task_id: a.taskId,
1334
+ task_status: a.status,
1335
+ data: a.data,
1336
+ tokens: a.tokens,
1337
+ cost: a.cost
1338
+ })
1339
+ }),
1340
+ defineTool({
1341
+ name: "update_task",
1342
+ title: "Update task",
1343
+ description: "Move a task on the board (open, in_progress, blocked, done, failed) and/or change its due date, with a note: posted as a status update in the task thread, recorded in the task's history and shown on its Slack card. Only the task's assignee or creator can change it (NOT_TASK_PARTICIPANT), and a closed task can't change (TASK_CLOSED). To cancel or reject, or to attach result data, use update_task_status. Needs the agents:send scope.",
1344
+ scope: "agents:send",
1345
+ endpoint: "PATCH /v1/agents/tasks/:taskId",
1346
+ inputSchema: z2.object({
1347
+ agentId,
1348
+ taskId: uuid("The task ID"),
1349
+ status: z2.enum(BOARD_STATUSES).optional().describe("The board column"),
1350
+ dueAt: z2.string().max(40).nullable().optional().describe("New due date (ISO date or date-time); null clears it"),
1351
+ note: z2.string().max(2e3).optional().describe("What changed, shown with the update")
1352
+ }),
1353
+ outputSchema: z2.object({ task, changed: z2.boolean() }),
1354
+ annotations: SEND,
1355
+ handler: async (api, a) => {
1356
+ if (a.status === void 0 && a.dueAt === void 0) {
1357
+ throw new ToolError("Pass status or dueAt.");
1358
+ }
1359
+ const r = await api.request(
1360
+ "PATCH",
1361
+ `/v1/agents/tasks/${enc(a.taskId)}`,
1362
+ {
1363
+ body: {
1364
+ agent_id: actingAs(api, a.agentId),
1365
+ status: a.status,
1366
+ due_at: a.dueAt,
1367
+ note: a.note
1368
+ }
1369
+ }
1370
+ );
1371
+ return { task: r.task, changed: Boolean(r.changed) };
1372
+ }
1373
+ }),
1374
+ defineTool({
1375
+ name: "handoff_task",
1376
+ title: "Hand off task",
1377
+ description: "Hand a task you are assigned to (or created) to another member agent of its channel, with the reason: the new and the previous assignee get a status message (data.handoff), and it's recorded in the task's history. Use it when another agent is better placed, then stop working on the task. Errors: ALREADY_ASSIGNED, AGENT_NOT_IN_CHANNEL, TASK_CLOSED, NOT_TASK_PARTICIPANT, POLICY_DM_NOT_ALLOWED. Needs the agents:send scope.",
1378
+ scope: "agents:send",
1379
+ endpoint: "POST /v1/agents/tasks/:taskId/handoff",
1380
+ inputSchema: z2.object({
1381
+ agentId,
1382
+ taskId: uuid("The task ID"),
1383
+ toAgentId: uuid("The new assignee (from list_agents or get_org_chart)"),
1384
+ reason: z2.string().max(2e3).optional().describe("Why, and what the new assignee needs to know")
1385
+ }),
1386
+ outputSchema: z2.object({ task, deliveries }),
1387
+ annotations: SEND,
1388
+ handler: async (api, a) => {
1389
+ const r = await api.request(
1390
+ "POST",
1391
+ `/v1/agents/tasks/${enc(a.taskId)}/handoff`,
1392
+ {
1393
+ body: {
1394
+ agent_id: actingAs(api, a.agentId),
1395
+ to_agent_id: a.toAgentId,
1396
+ reason: a.reason
1397
+ }
1398
+ }
1399
+ );
1400
+ return {
1401
+ task: r.task,
1402
+ deliveries: r.deliveries ?? []
1403
+ };
1404
+ }
1405
+ }),
1406
+ defineTool({
1407
+ name: "list_tasks",
1408
+ title: "List tasks",
1409
+ description: "List a channel's tasks, newest first, with their board status (open, in_progress, blocked, done, failed), assignee, due date and last handoff. Filter by assignee (your own agent id for your work) or status. channelId is required unless the key is an agents:admin key. Needs the agents:read scope.",
1410
+ scope: "agents:read",
1411
+ endpoint: "GET /v1/agents/tasks",
1412
+ inputSchema: z2.object({
1413
+ agentId,
1414
+ channelId: channelId.optional(),
1415
+ assigneeAgentId: uuid("Only tasks assigned to this agent").optional(),
1416
+ status: z2.enum(BOARD_STATUSES).optional(),
1417
+ limit: z2.number().int().min(1).max(500).default(50).describe("How many to return (1-500, default 50)")
1418
+ }),
1419
+ outputSchema: z2.object({ tasks: z2.array(task) }),
1420
+ annotations: READ,
1421
+ handler: async (api, a) => {
1422
+ const r = await api.request(
1423
+ "GET",
1424
+ "/v1/agents/tasks",
1425
+ {
1426
+ query: {
1427
+ agent_id: actingAs(api, a.agentId),
1428
+ channel_id: a.channelId,
1429
+ assignee_agent_id: a.assigneeAgentId,
1430
+ status: a.status,
1431
+ limit: a.limit
1432
+ }
1433
+ }
1434
+ );
1435
+ return { tasks: r.tasks ?? [] };
1436
+ }
1437
+ }),
1438
+ defineTool({
1439
+ name: "get_task_board",
1440
+ title: "Get task board",
1441
+ description: "A channel's task board: tasks grouped by column (open, in_progress, blocked, done, failed), counts per column, and the agents on it. Needs the agents:read scope.",
1442
+ scope: "agents:read",
1443
+ endpoint: "GET /v1/agents/tasks/board",
1444
+ inputSchema: z2.object({
1445
+ agentId,
1446
+ channelId,
1447
+ assigneeAgentId: uuid("Only tasks assigned to this agent").optional()
1448
+ }),
1449
+ outputSchema: z2.object({
1450
+ channel_id: z2.string(),
1451
+ columns: z2.record(z2.string(), z2.array(task)),
1452
+ counts: z2.record(z2.string(), z2.number()),
1453
+ agents: z2.array(z2.looseObject({ id: z2.string() })),
1454
+ truncated: z2.boolean()
1455
+ }),
1456
+ annotations: READ,
1457
+ handler: async (api, a) => await api.request("GET", "/v1/agents/tasks/board", {
1458
+ query: {
1459
+ agent_id: actingAs(api, a.agentId),
1460
+ channel_id: a.channelId,
1461
+ assignee_agent_id: a.assigneeAgentId
1462
+ }
1463
+ })
1464
+ }),
1465
+ defineTool({
1466
+ name: "ask_human",
1467
+ title: "Ask a human",
1468
+ description: "Ask people a question, or for an approval (kind approval: Approve / Deny), when you can't or shouldn't decide alone. It's posted in Slack (the channel's linked Slack channel, else the escalation channel) with a button per option, and escalates (manager, owner, supervisors, escalation channel) until someone answers or the deadline passes; with a defaultOption, the default applies at the deadline. Returns at once with the questionId: then call get_answer, which waits for the answer. Don't act on what you asked about before the answer. Counts as one Event. Your policy may refuse (POLICY_ASK_HUMAN_NOT_ALLOWED, POLICY_URGENCY_NOT_ALLOWED). Needs the agents:ask_human scope.",
1469
+ scope: "agents:ask_human",
1470
+ endpoint: "POST /v1/agents/questions",
1471
+ inputSchema: z2.object({
1472
+ agentId,
1473
+ kind: z2.enum(["question", "approval"]).default("question").describe("question (default) or approval (answered Approve / Deny)"),
1474
+ question: z2.string().min(1).max(3e3).describe("The question, with what people need to answer it"),
1475
+ options: z2.array(
1476
+ z2.object({
1477
+ id: z2.string().min(1).max(100),
1478
+ label: z2.string().min(1).max(75)
1479
+ })
1480
+ ).max(10).optional().describe("Up to 10 answers to pick from (ignored for approvals)"),
1481
+ freeText: z2.boolean().optional().describe("Allow a typed answer (always on without options)"),
1482
+ urgency: z2.enum(["low", "normal", "high", "urgent"]).optional().describe("How fast it escalates (default normal)"),
1483
+ deadline: z2.string().max(40).optional().describe("ISO date-time, at most 30 days away"),
1484
+ defaultOption: z2.string().max(100).optional().describe("Option id applied at the deadline when nobody answered"),
1485
+ channelId: channelId.optional().describe("Post it in this agent channel (from list_agent_channels)"),
1486
+ threadId,
1487
+ context: z2.record(z2.string(), z2.unknown()).optional().describe("Facts shown with the question (JSON object)"),
1488
+ amount: z2.number().min(0).optional().describe("Approvals: the amount at stake"),
1489
+ currency: z2.string().regex(/^[A-Za-z]{3}$/).optional().describe("Approvals: ISO 4217 currency code"),
1490
+ resource: z2.record(z2.string(), z2.unknown()).optional().describe("Approvals: what is being approved (JSON object)"),
1491
+ requiredRoles: z2.array(z2.string().min(1).max(40)).max(10).optional().describe('Approvals: roles that may answer, e.g. ["admin"]')
1492
+ }),
1493
+ outputSchema: z2.object({ questionId: z2.string(), question }),
1494
+ annotations: SEND,
1495
+ handler: async (api, a) => {
1496
+ const r = await api.request(
1497
+ "POST",
1498
+ "/v1/agents/questions",
1499
+ {
1500
+ body: {
1501
+ agent_id: actingAs(api, a.agentId),
1502
+ kind: a.kind,
1503
+ question: a.question,
1504
+ options: a.options,
1505
+ free_text: a.freeText,
1506
+ urgency: a.urgency,
1507
+ deadline: a.deadline,
1508
+ default_option: a.defaultOption,
1509
+ channel_id: a.channelId,
1510
+ thread_id: a.threadId,
1511
+ context: a.context,
1512
+ amount: a.amount,
1513
+ currency: a.currency,
1514
+ resource: a.resource,
1515
+ required_roles: a.requiredRoles
1516
+ }
1517
+ }
1518
+ );
1519
+ return {
1520
+ questionId: String(r.question.id),
1521
+ question: r.question
1522
+ };
1523
+ }
1524
+ }),
1525
+ defineTool({
1526
+ name: "get_answer",
1527
+ title: "Get answer",
1528
+ description: `Wait for the answer to a question from ask_human: holds up to waitSeconds (default and maximum ${QUESTION_WAIT_MAX_SECONDS}) and returns as soon as it closes. status is answered (answer.option_id / answer.text; approvals have answer.approved), expired_default (the default option applied), expired (no answer by the deadline) or canceled. When waiting is true nobody has answered yet: call get_answer again, or do other work and come back. Needs the agents:ask_human scope (or agents:read).`,
1529
+ scope: "agents:ask_human",
1530
+ endpoint: "GET /v1/agents/questions/:id/wait",
1531
+ inputSchema: z2.object({
1532
+ agentId,
1533
+ questionId,
1534
+ waitSeconds: z2.number().int().min(0).max(QUESTION_WAIT_MAX_SECONDS).default(QUESTION_WAIT_MAX_SECONDS).describe(
1535
+ `Seconds to wait for an answer (0-${QUESTION_WAIT_MAX_SECONDS}, default ${QUESTION_WAIT_MAX_SECONDS}); 0 only checks`
1536
+ )
1537
+ }),
1538
+ outputSchema: z2.object({
1539
+ questionId: z2.string(),
1540
+ status: z2.string(),
1541
+ waiting: z2.boolean(),
1542
+ answer: z2.looseObject({}).nullable(),
1543
+ message: z2.string(),
1544
+ question
1545
+ }),
1546
+ annotations: READ,
1547
+ handler: async (api, a) => {
1548
+ const r = await api.request(
1549
+ "GET",
1550
+ `/v1/agents/questions/${enc(a.questionId)}/wait`,
1551
+ {
1552
+ query: {
1553
+ agent_id: actingAs(api, a.agentId),
1554
+ timeout: a.waitSeconds
1555
+ },
1556
+ // The API holds the request for up to waitSeconds.
1557
+ timeout: (a.waitSeconds + 10) * 1e3
1558
+ }
1559
+ );
1560
+ const status = String(r.question.status);
1561
+ const waiting = status === "open";
1562
+ return {
1563
+ questionId: a.questionId,
1564
+ status,
1565
+ waiting,
1566
+ answer: r.question.answer ?? null,
1567
+ message: waiting ? `Still waiting: nobody has answered yet. Call get_answer again with questionId ${a.questionId}, or check back later; don't act on the question meanwhile.` : outcomeMessage(status, r.question),
1568
+ question: r.question
1569
+ };
1570
+ }
1571
+ }),
1572
+ defineTool({
1573
+ name: "list_questions",
1574
+ title: "List questions",
1575
+ description: "List your questions and the ones escalated to you as a manager agent, newest first. Filter with status open to find what still needs an answer (answer_escalated_question). Needs the agents:read scope (or agents:ask_human).",
1576
+ scope: "agents:read",
1577
+ endpoint: "GET /v1/agents/questions",
1578
+ inputSchema: z2.object({
1579
+ agentId,
1580
+ status: z2.enum(["open", "answered", "expired_default", "expired", "canceled"]).optional(),
1581
+ kind: z2.enum(["question", "approval"]).optional(),
1582
+ channelId: channelId.optional(),
1583
+ cursor: z2.string().max(300).optional().describe("nextCursor of the previous call"),
1584
+ limit: z2.number().int().min(1).max(200).default(20).describe("How many to return (1-200, default 20)")
1585
+ }),
1586
+ outputSchema: z2.object({
1587
+ questions: z2.array(question),
1588
+ nextCursor: z2.string().nullable()
1589
+ }),
1590
+ annotations: READ,
1591
+ handler: async (api, a) => {
1592
+ const r = await api.request("GET", "/v1/agents/questions", {
1593
+ query: {
1594
+ agent_id: actingAs(api, a.agentId),
1595
+ status: a.status,
1596
+ kind: a.kind,
1597
+ channel_id: a.channelId,
1598
+ cursor: a.cursor,
1599
+ limit: a.limit
1600
+ }
1601
+ });
1602
+ return {
1603
+ questions: r.questions ?? [],
1604
+ nextCursor: r.next_cursor ?? null
1605
+ };
1606
+ }
1607
+ }),
1608
+ defineTool({
1609
+ name: "cancel_question",
1610
+ title: "Cancel question",
1611
+ description: "Cancel one of your open questions when it no longer matters (you found the answer, the work was dropped): its Slack post is updated and escalation stops. Only the agent that asked can cancel, and a closed question can't be (QUESTION_CLOSED). Needs the agents:ask_human scope.",
1612
+ scope: "agents:ask_human",
1613
+ endpoint: "DELETE /v1/agents/questions/:id",
1614
+ inputSchema: z2.object({ agentId, questionId }),
1615
+ outputSchema: z2.object({ question }),
1616
+ annotations: {
1617
+ readOnlyHint: false,
1618
+ destructiveHint: true,
1619
+ idempotentHint: false,
1620
+ openWorldHint: true
1621
+ },
1622
+ handler: async (api, a) => {
1623
+ const r = await api.request(
1624
+ "DELETE",
1625
+ `/v1/agents/questions/${enc(a.questionId)}`,
1626
+ { query: { agent_id: actingAs(api, a.agentId) } }
1627
+ );
1628
+ return { question: r.question };
1629
+ }
1630
+ }),
1631
+ defineTool({
1632
+ name: "answer_escalated_question",
1633
+ title: "Answer escalated question",
1634
+ description: "Answer a question another agent asked, when it was escalated to you as its manager agent (a question.escalated delivery, or list_questions with status open). Pick an optionId (approve / deny for approvals, with a comment), or give text when free text is allowed. The first answer wins (QUESTION_CLOSED after), approvals that require a role need a person (APPROVAL_ROLE_REQUIRED), and you can't answer your own question. Needs the agents:send scope.",
1635
+ scope: "agents:send",
1636
+ endpoint: "POST /v1/agents/questions/:id/answer",
1637
+ inputSchema: z2.object({
1638
+ agentId,
1639
+ questionId,
1640
+ optionId: z2.string().min(1).max(100).optional().describe("One of the question options (approve / deny for approvals)"),
1641
+ text: z2.string().max(3e3).optional().describe("A typed answer, when the question allows free text"),
1642
+ comment: z2.string().max(2e3).optional().describe("Why (shown with the answer; say why on a deny)")
1643
+ }),
1644
+ outputSchema: z2.object({ question }),
1645
+ annotations: SEND,
1646
+ handler: async (api, a) => {
1647
+ if (!a.optionId && !a.text) throw new ToolError("Pass optionId or text.");
1648
+ const r = await api.request(
1649
+ "POST",
1650
+ `/v1/agents/questions/${enc(a.questionId)}/answer`,
1651
+ {
1652
+ body: {
1653
+ agent_id: actingAs(api, a.agentId),
1654
+ option_id: a.optionId,
1655
+ text: a.text,
1656
+ comment: a.comment
1657
+ }
1658
+ }
1659
+ );
1660
+ return { question: r.question };
1661
+ }
1662
+ }),
1663
+ defineTool({
1664
+ name: "get_org_chart",
1665
+ title: "Get org chart",
1666
+ description: "The organization's agents with their manager (an agent or a person), owner and teams, the teams, and the reporting tree. Use it to find who to hand a task off to, or who manages an agent. Needs the agents:read scope.",
1667
+ scope: "agents:read",
1668
+ endpoint: "GET /v1/agents/org-chart",
1669
+ inputSchema: z2.object({
1670
+ teamId: uuid("Only this team").optional(),
1671
+ channelId: uuid("Only the agents of this channel").optional(),
1672
+ includeRetired: z2.boolean().optional().describe("Include retired agents (default false)")
1673
+ }),
1674
+ outputSchema: z2.object({
1675
+ agents: z2.array(z2.looseObject({ id: z2.string() })),
1676
+ users: z2.array(z2.looseObject({ id: z2.string() })),
1677
+ teams: z2.array(z2.looseObject({ id: z2.string() })),
1678
+ tree: z2.array(z2.looseObject({}))
1679
+ }),
1680
+ annotations: READ,
1681
+ handler: async (api, a) => await api.request("GET", "/v1/agents/org-chart", {
1682
+ query: {
1683
+ team_id: a.teamId,
1684
+ channel_id: a.channelId,
1685
+ include_retired: a.includeRetired ? "true" : void 0
1686
+ }
1687
+ })
1688
+ }),
1689
+ defineTool({
1690
+ name: "get_effective_policy",
1691
+ title: "Get effective policy",
1692
+ description: "The policy in force for an agent (in a channel): the merged rules (allowed channels, direct messages, asking humans, rate, budgets, working hours, thread depth, humans-win minutes), which policy set each, current usage, working hours now, and with a channel whether it may post and read there now. Read-only. Needs an unbound key with the agents:admin scope: a key bound to agents gets 403 AGENT_ADMIN_KEY_REQUIRED.",
1693
+ scope: "agents:admin",
1694
+ endpoint: "GET /v1/agents/policies/preview",
1695
+ inputSchema: z2.object({
1696
+ agentId: uuid(
1697
+ "The agent (from list_agents). Default: the server agent (CHANNLIZE_AGENT_ID)"
1698
+ ).optional(),
1699
+ channelId: channelId.optional()
1700
+ }),
1701
+ outputSchema: z2.looseObject({
1702
+ agent_id: z2.string(),
1703
+ channel_id: z2.string().nullable(),
1704
+ rules: z2.looseObject({}),
1705
+ working_hours: z2.looseObject({}),
1706
+ usage: z2.looseObject({}),
1707
+ checks: z2.looseObject({}).nullable()
1708
+ }),
1709
+ annotations: READ,
1710
+ handler: async (api, a) => await api.request("GET", "/v1/agents/policies/preview", {
1711
+ query: {
1712
+ agent_id: requireAgent(api, a.agentId),
1713
+ channel_id: a.channelId
1714
+ }
1715
+ })
1716
+ }),
1717
+ defineTool({
1718
+ name: "read_agent_inbox",
1719
+ title: "Read agent inbox",
1720
+ description: "Read your agent's unacknowledged messages, oldest first: messages, tasks and task status updates from other agents and people, each with its channel, thread and sender. Messages stay until ack_agent_messages acknowledges them, so read, handle, then ack. Needs the agents:read scope.",
1721
+ scope: "agents:read",
1722
+ endpoint: "GET /v1/agents/:id/inbox",
1723
+ inputSchema: z2.object({
1724
+ agentId,
1725
+ cursor: z2.string().max(200).optional().describe("Read after this cursor (nextCursor of the previous call)"),
1726
+ limit: z2.number().int().min(1).max(200).default(20).describe("How many to return (1-200, default 20)")
1727
+ }),
1728
+ outputSchema: z2.object({
1729
+ agentId: z2.string(),
1730
+ messages: z2.array(
1731
+ z2.looseObject({
1732
+ delivery_id: z2.string(),
1733
+ cursor: z2.string(),
1734
+ message
1735
+ })
1736
+ ),
1737
+ nextCursor: z2.string().nullable(),
1738
+ hasMore: z2.boolean()
1739
+ }),
1740
+ annotations: READ,
1741
+ handler: async (api, a) => {
1742
+ const id2 = requireAgent(api, a.agentId);
1743
+ const r = await api.request("GET", `/v1/agents/${enc(id2)}/inbox`, {
1744
+ query: { cursor: a.cursor, limit: a.limit }
1745
+ });
1746
+ return {
1747
+ agentId: id2,
1748
+ messages: r.messages ?? [],
1749
+ nextCursor: r.next_cursor ?? null,
1750
+ hasMore: Boolean(r.has_more)
1751
+ };
1752
+ }
1753
+ }),
1754
+ defineTool({
1755
+ name: "ack_agent_messages",
1756
+ title: "Acknowledge agent messages",
1757
+ description: "Acknowledge inbox messages you handled so read_agent_inbox stops returning them: upTo acks everything up to and including that delivery or message ID, ids acks just those. Acking twice is harmless. Needs the agents:read scope.",
1758
+ scope: "agents:read",
1759
+ endpoint: "POST /v1/agents/:id/inbox/ack",
1760
+ inputSchema: z2.object({
1761
+ agentId,
1762
+ upTo: z2.string().uuid().optional().describe("Ack everything up to and including this delivery_id"),
1763
+ ids: z2.array(z2.string().uuid()).min(1).max(500).optional().describe("Ack these delivery (or message) IDs")
1764
+ }),
1765
+ outputSchema: z2.object({ acked: z2.number() }),
1766
+ annotations: {
1767
+ readOnlyHint: false,
1768
+ destructiveHint: false,
1769
+ idempotentHint: true,
1770
+ openWorldHint: false
1771
+ },
1772
+ handler: async (api, a) => {
1773
+ if (!a.upTo === !a.ids) {
1774
+ throw new ToolError("Pass either upTo or ids.");
1775
+ }
1776
+ const id2 = requireAgent(api, a.agentId);
1777
+ const r = await api.request(
1778
+ "POST",
1779
+ `/v1/agents/${enc(id2)}/inbox/ack`,
1780
+ { body: a.upTo ? { up_to: a.upTo } : { ids: a.ids } }
1781
+ );
1782
+ return { acked: Number(r.acked ?? 0) };
1783
+ }
1784
+ }),
1785
+ defineTool({
1786
+ name: "search_agent_messages",
1787
+ title: "Search agent messages",
1788
+ description: `Full-text search over agent channel history: messages, tasks, status updates and questions to people (with their answers), best match first. Use it to find what was said or decided before, a past task, or an answer a human already gave, instead of asking again. q takes websearch syntax: "exact phrase", or, -word; codes and ids match as substrings (INV-20 finds INV-2041). Each result has a highlight (hits in **bold**), the channel, threadId and a Slack link when mirrored. Searches the channels your key's agents can read and their own questions (the whole org for an agents:admin key), within the plan's history window. Page with cursor. Needs the agents:read scope.`,
1789
+ scope: "agents:read",
1790
+ endpoint: "GET /v1/agents/search",
1791
+ inputSchema: z2.object({
1792
+ q: z2.string().trim().min(2).max(200).describe("What to look for (2-200 characters)"),
1793
+ agentId: uuid(
1794
+ "Only messages sent by or mentioning this agent, and questions it asked (from list_agents). With a multi-agent key it also picks whose channels are searched."
1795
+ ).optional(),
1796
+ channelId: channelId.optional().describe("Only this agent channel"),
1797
+ type: z2.enum(AGENT_MESSAGE_TYPES).optional().describe("Only this message type"),
1798
+ include: z2.enum(["messages", "questions", "both"]).default("both").describe("messages, questions, or both (default)"),
1799
+ from: z2.string().max(40).optional().describe("ISO date-time: the earliest to search"),
1800
+ to: z2.string().max(40).optional().describe("ISO date-time: the latest to search"),
1801
+ cursor: z2.string().max(300).optional().describe("nextCursor of the previous call"),
1802
+ limit: z2.number().int().min(1).max(50).default(10).describe("How many results (1-50, default 10)")
1803
+ }),
1804
+ outputSchema: z2.object({
1805
+ results: z2.array(
1806
+ z2.looseObject({
1807
+ kind: z2.string(),
1808
+ id: z2.string(),
1809
+ type: z2.string(),
1810
+ text: z2.string(),
1811
+ highlight: z2.string(),
1812
+ channel: z2.string().nullable(),
1813
+ threadId: z2.string().nullable()
1814
+ })
1815
+ ),
1816
+ nextCursor: z2.string().nullable(),
1817
+ window: z2.object({ from: z2.string(), days: z2.number() })
1818
+ }),
1819
+ annotations: READ,
1820
+ handler: async (api, a) => {
1821
+ const r = await api.request("GET", "/v1/agents/search", {
1822
+ query: {
1823
+ q: a.q,
1824
+ agent_id: a.agentId,
1825
+ channel_id: a.channelId,
1826
+ type: a.type,
1827
+ include: a.include === "both" ? void 0 : a.include,
1828
+ from: a.from,
1829
+ to: a.to,
1830
+ cursor: a.cursor,
1831
+ limit: a.limit
1832
+ }
1833
+ });
1834
+ return summarizeSearch(r);
1835
+ }
1836
+ }),
1837
+ defineTool({
1838
+ name: "get_agent_graph",
1839
+ title: "Get agent communication graph",
1840
+ description: "Who talks to whom among agents and people over a range of days: the busiest participants (messages sent and received, tokens, cost) and the busiest sender \u2192 recipient edges (messages, replies, reply latency), with totals and a one-line summary. Rows beyond top are counted in omitted. Filter to one agent (agentId, or mine for your own), a team or a channel. Sees the channels your key's agents can read (the whole org for an agents:admin key). Needs the agents:read scope.",
1841
+ scope: "agents:read",
1842
+ endpoint: "GET /v1/agents/insights/graph",
1843
+ inputSchema: z2.object({
1844
+ ...insightsRange,
1845
+ agentId: insightsAgent,
1846
+ mine,
1847
+ teamId: uuid("Only edges touching this team").optional(),
1848
+ top: top(10)
1849
+ }),
1850
+ outputSchema: z2.object({
1851
+ range,
1852
+ totals: z2.object({
1853
+ nodes: z2.number(),
1854
+ edges: z2.number(),
1855
+ messages: z2.number(),
1856
+ tokens: z2.number(),
1857
+ cost: z2.number()
1858
+ }),
1859
+ topNodes: z2.array(
1860
+ z2.looseObject({ id: z2.string(), label: z2.string(), sent: z2.number() })
1861
+ ),
1862
+ topEdges: z2.array(
1863
+ z2.looseObject({
1864
+ source: z2.string(),
1865
+ target: z2.string(),
1866
+ messages: z2.number(),
1867
+ replyAvgMs: nullableNumber
1868
+ })
1869
+ ),
1870
+ omitted: z2.looseObject({ nodes: z2.number(), edges: z2.number() }),
1871
+ summary: z2.string()
1872
+ }),
1873
+ annotations: READ,
1874
+ handler: async (api, a) => {
1875
+ const r = await api.request("GET", "/v1/agents/insights/graph", {
1876
+ query: {
1877
+ from: a.from,
1878
+ to: a.to,
1879
+ channel_id: a.channelId,
1880
+ agent_id: filterAgent(api, a),
1881
+ team_id: a.teamId
1882
+ }
1883
+ });
1884
+ return summarizeGraph(r, a.top);
1885
+ }
1886
+ }),
1887
+ defineTool({
1888
+ name: "get_agent_cost",
1889
+ title: "Get agent cost",
1890
+ description: "What agents spent, from the tokens and cost they reported on their messages: the range's totals, the top groups by cost (groupBy agent, channel, team, task or day) with their share, the active days and the peak day, and a one-line summary. Check your own spend with mine (or agentId), e.g. before starting expensive work or to report it. Cost is in whatever currency agents report (usually USD). Sees the channels your key's agents can read (the whole org for an agents:admin key). Needs the agents:read scope.",
1891
+ scope: "agents:read",
1892
+ endpoint: "GET /v1/agents/insights/cost",
1893
+ inputSchema: z2.object({
1894
+ ...insightsRange,
1895
+ groupBy: z2.enum(["agent", "channel", "team", "task", "day"]).default("agent").describe("How to break the cost down (default agent)"),
1896
+ agentId: insightsAgent,
1897
+ mine,
1898
+ teamId: uuid("Only what this team's agents sent").optional(),
1899
+ top: top(10)
1900
+ }),
1901
+ outputSchema: z2.object({
1902
+ range,
1903
+ groupBy: z2.string(),
1904
+ totals: z2.object({
1905
+ messages: z2.number(),
1906
+ pricedMessages: z2.number(),
1907
+ tokens: z2.number(),
1908
+ cost: z2.number()
1909
+ }),
1910
+ groups: z2.array(
1911
+ z2.looseObject({
1912
+ key: z2.string(),
1913
+ label: z2.string(),
1914
+ cost: z2.number(),
1915
+ share: nullableNumber
1916
+ })
1917
+ ),
1918
+ omittedGroups: z2.number(),
1919
+ truncated: z2.boolean(),
1920
+ daily: z2.array(z2.looseObject({ day: z2.string(), cost: z2.number() })),
1921
+ peakDay: z2.object({ day: z2.string(), cost: z2.number() }).nullable(),
1922
+ summary: z2.string()
1923
+ }),
1924
+ annotations: READ,
1925
+ handler: async (api, a) => {
1926
+ const r = await api.request("GET", "/v1/agents/insights/cost", {
1927
+ query: {
1928
+ from: a.from,
1929
+ to: a.to,
1930
+ channel_id: a.channelId,
1931
+ agent_id: filterAgent(api, a),
1932
+ team_id: a.teamId,
1933
+ group_by: a.groupBy,
1934
+ // Day groups come back whole; the others only need the top ones.
1935
+ limit: a.groupBy === "day" ? void 0 : a.top
1936
+ }
1937
+ });
1938
+ return summarizeCost(r, a.top);
1939
+ }
1940
+ }),
1941
+ defineTool({
1942
+ name: "get_agent_metrics",
1943
+ title: "Get agent metrics",
1944
+ description: "Response metrics over a range of days: reply latency (agent \u2192 agent, human \u2192 agent, agent \u2192 human: avg, p50, p90 and reply rate) and per responding agent, questions to people (answer rate, time to a human answer, by urgency), delivery failure and retry rates per mode, and the inbox backlog right now, with a one-line summary. Use mine (or agentId) to check how fast you answer and whether your inbox is backing up. Needs the agents:read scope.",
1945
+ scope: "agents:read",
1946
+ endpoint: "GET /v1/agents/insights/metrics",
1947
+ inputSchema: z2.object({
1948
+ ...insightsRange,
1949
+ agentId: insightsAgent,
1950
+ mine,
1951
+ top: top(5)
1952
+ }),
1953
+ outputSchema: z2.object({
1954
+ range,
1955
+ replies: z2.looseObject({
1956
+ agentToAgent: z2.looseObject({ avgMs: nullableNumber }),
1957
+ humanToAgent: z2.looseObject({ avgMs: nullableNumber }),
1958
+ agentToHuman: z2.looseObject({ avgMs: nullableNumber }),
1959
+ byAgent: z2.array(z2.looseObject({ agentId: z2.string() }))
1960
+ }),
1961
+ questions: z2.looseObject({ asked: z2.number() }),
1962
+ deliveries: z2.looseObject({ deliveries: z2.number() }),
1963
+ backlog: z2.looseObject({ unacked: z2.number(), held: z2.number() }),
1964
+ summary: z2.string()
1965
+ }),
1966
+ annotations: READ,
1967
+ handler: async (api, a) => {
1968
+ const r = await api.request("GET", "/v1/agents/insights/metrics", {
1969
+ query: {
1970
+ from: a.from,
1971
+ to: a.to,
1972
+ channel_id: a.channelId,
1973
+ agent_id: filterAgent(api, a)
1974
+ }
1975
+ });
1976
+ return summarizeMetrics(r, a.top);
1977
+ }
1978
+ }),
1979
+ defineTool({
1980
+ name: "list_agents",
1981
+ title: "List agents",
1982
+ description: "List the organization's agents: id, slug, name, role, description, status (active, paused, retired) and how they receive messages. Use the ids for mentions and agentId. Needs the agents:read scope.",
1983
+ scope: "agents:read",
1984
+ endpoint: "GET /v1/agents",
1985
+ inputSchema: z2.object({
1986
+ includeRetired: z2.boolean().optional().describe("Include retired agents (default false)")
1987
+ }),
1988
+ outputSchema: z2.object({
1989
+ agents: z2.array(
1990
+ z2.looseObject({
1991
+ id: z2.string(),
1992
+ slug: z2.string(),
1993
+ name: z2.string(),
1994
+ status: z2.string()
1995
+ })
1996
+ )
1997
+ }),
1998
+ annotations: READ,
1999
+ handler: async (api, a) => {
2000
+ const r = await api.request("GET", "/v1/agents", {
2001
+ query: { include_retired: a.includeRetired || void 0 }
2002
+ });
2003
+ return { agents: r.agents ?? [] };
2004
+ }
2005
+ }),
2006
+ defineTool({
2007
+ name: "list_agent_channels",
2008
+ title: "List agent channels",
2009
+ description: "List the agent channels your key's agents are members or observers of: id, slug, name, description and whether they are archived. Post with send_agent_message (members only). Needs the agents:read scope.",
2010
+ scope: "agents:read",
2011
+ endpoint: "GET /v1/agents/channels",
2012
+ inputSchema: z2.object({
2013
+ includeArchived: z2.boolean().optional().describe("Include archived channels (default false)")
2014
+ }),
2015
+ outputSchema: z2.object({
2016
+ channels: z2.array(
2017
+ z2.looseObject({
2018
+ id: z2.string(),
2019
+ slug: z2.string(),
2020
+ name: z2.string(),
2021
+ archived: z2.boolean()
2022
+ })
2023
+ )
2024
+ }),
2025
+ annotations: READ,
2026
+ handler: async (api, a) => {
2027
+ const r = await api.request(
2028
+ "GET",
2029
+ "/v1/agents/channels",
2030
+ { query: { include_archived: a.includeArchived || void 0 } }
2031
+ );
2032
+ return { channels: r.channels ?? [] };
2033
+ }
2034
+ })
2035
+ ];
2036
+ var AGENT_TOOL_NAMES = AGENT_TOOLS.map((t) => t.name);
2037
+ function getAgentTool(name) {
2038
+ return AGENT_TOOLS.find((t) => t.name === name);
2039
+ }
2040
+ async function runAgentTool(api, name, args) {
2041
+ const tool = getAgentTool(name);
2042
+ if (!tool) throw new ToolError(`Unknown agent tool "${name}"`);
2043
+ const parsed = tool.inputSchema.safeParse(args ?? {});
2044
+ if (!parsed.success) {
2045
+ throw new ToolError(
2046
+ `Invalid arguments for ${name}: ${parsed.error.issues.map((i) => `${i.path.join(".") || "input"}: ${i.message}`).join("; ")}`
2047
+ );
2048
+ }
2049
+ return await tool.handler(api, parsed.data);
2050
+ }
2051
+ function agentToolsAsJsonSchema(filter = () => true) {
2052
+ return AGENT_TOOLS.filter(filter).map((t) => ({
2053
+ name: t.name,
2054
+ description: t.description,
2055
+ parameters: z2.toJSONSchema(t.inputSchema, { io: "input" })
2056
+ }));
2057
+ }
2058
+
2059
+ // src/inbox.ts
2060
+ var z3 = __toESM(require("zod/v4"));
2061
+ function defineTool2(tool) {
2062
+ return tool;
2063
+ }
2064
+ var CONVERSATION_STATUSES = [
2065
+ "open",
2066
+ "pending",
2067
+ "resolved",
2068
+ "closed"
2069
+ ];
2070
+ var CONVERSATION_PRIORITIES = [
2071
+ "low",
2072
+ "normal",
2073
+ "high",
2074
+ "urgent"
2075
+ ];
2076
+ var CONVERSATION_SORTS = [
2077
+ "recent",
2078
+ "oldest",
2079
+ "newest",
2080
+ "priority"
2081
+ ];
2082
+ var loose = z3.looseObject({});
2083
+ var id = (what) => z3.string().uuid().describe(`${what} ID`);
2084
+ var conversationId = id(
2085
+ "Conversation (from list_conversations or search_conversations)"
2086
+ );
2087
+ var person = z3.looseObject({
2088
+ id: z3.string(),
2089
+ name: z3.string().nullable().optional(),
2090
+ email: z3.string().nullable().optional()
2091
+ }).nullable();
2092
+ var conversationSummary = z3.looseObject({
2093
+ id: z3.string(),
2094
+ subject: z3.string().nullable().optional(),
2095
+ status: z3.string(),
2096
+ priority: z3.string().optional(),
2097
+ source: z3.string().nullable().optional(),
2098
+ tags: z3.array(z3.string()).optional(),
2099
+ customer: person.optional(),
2100
+ assignee: person.optional(),
2101
+ triage: z3.record(z3.string(), z3.unknown()).nullable().optional(),
2102
+ needsReply: z3.boolean().optional(),
2103
+ lastActivityAt: z3.string().nullable().optional()
2104
+ });
2105
+ var page = {
2106
+ total: z3.number(),
2107
+ limit: z3.number(),
2108
+ offset: z3.number(),
2109
+ hasMore: z3.boolean()
2110
+ };
2111
+ var listOutput = z3.object({
2112
+ conversations: z3.array(conversationSummary),
2113
+ ...page
2114
+ });
2115
+ var changeOutput = z3.object({
2116
+ conversation: z3.looseObject({ id: z3.string(), status: z3.string() }),
2117
+ changes: z3.array(z3.string())
2118
+ });
2119
+ var slackOutcome = z3.string().describe(
2120
+ "Slack mirror: queued, posted, no_thread (not in Slack), not_connected or failed"
2121
+ );
2122
+ var tags = z3.array(z3.string().trim().min(1).max(50)).max(20);
2123
+ var paging = {
2124
+ limit: z3.number().int().min(1).max(100).default(20).describe("How many to return (1-100, default 20)"),
2125
+ offset: z3.number().int().min(0).default(0).describe("Skip this many")
2126
+ };
2127
+ function oneOrMany(values) {
2128
+ return z3.union([z3.enum(values), z3.array(z3.enum(values)).max(10)]).optional();
2129
+ }
2130
+ var asList = (v) => v === void 0 ? void 0 : Array.isArray(v) ? v.join(",") : v;
2131
+ var listFilters = {
2132
+ status: oneOrMany(CONVERSATION_STATUSES).describe(
2133
+ 'Only these statuses: "open" or a list like ["open", "pending"]'
2134
+ ),
2135
+ priority: oneOrMany(CONVERSATION_PRIORITIES).describe(
2136
+ 'Only these priorities: "urgent" or a list'
2137
+ ),
2138
+ assignee: z3.string().max(255).optional().describe('A teammate (user ID or email), "unassigned" or "assigned"'),
2139
+ projectId: id("Project").optional(),
2140
+ updatedSince: z3.iso.datetime({ offset: true }).optional().describe("Updated or with a new message since (ISO 8601)"),
2141
+ tag: z3.string().max(50).optional().describe("Carrying this tag"),
2142
+ source: z3.string().max(32).optional().describe("Entry point, e.g. live_chat, contact_form, api, email"),
2143
+ intent: z3.string().max(64).optional().describe("AI triage intent (triaged conversations only)"),
2144
+ urgency: z3.string().max(64).optional().describe("AI triage urgency (triaged conversations only)"),
2145
+ sort: z3.enum(CONVERSATION_SORTS).optional().describe(
2146
+ "recent (last activity, default), oldest, newest (created) or priority"
2147
+ )
2148
+ };
2149
+ async function list(api, a) {
2150
+ const r = await api.request("GET", "/v1/conversations", {
2151
+ query: {
2152
+ status: asList(a.status),
2153
+ priority: asList(a.priority),
2154
+ assignee: a.assignee,
2155
+ projectId: a.projectId,
2156
+ updatedSince: a.updatedSince,
2157
+ tag: a.tag,
2158
+ source: a.source,
2159
+ intent: a.intent,
2160
+ urgency: a.urgency,
2161
+ sort: a.sort,
2162
+ q: a.q,
2163
+ limit: a.limit,
2164
+ offset: a.offset
2165
+ }
2166
+ });
2167
+ return {
2168
+ conversations: r.conversations ?? [],
2169
+ total: Number(r.total ?? 0),
2170
+ limit: Number(r.limit ?? a.limit),
2171
+ offset: Number(r.offset ?? a.offset),
2172
+ hasMore: Boolean(r.hasMore)
2173
+ };
2174
+ }
2175
+ var path = (cid, rest = "") => `/v1/conversations/${encodeURIComponent(cid)}${rest}`;
2176
+ async function patch(api, cid, body) {
2177
+ const r = await api.request(
2178
+ "PATCH",
2179
+ path(cid),
2180
+ { body }
2181
+ );
613
2182
  return {
614
- content: [{ type: "text", text: JSON.stringify(data, null, 2) }],
615
- structuredContent: data
2183
+ conversation: r.conversation,
2184
+ changes: r.changes ?? []
2185
+ };
2186
+ }
2187
+ var READ2 = {
2188
+ readOnlyHint: true,
2189
+ destructiveHint: false,
2190
+ idempotentHint: true,
2191
+ openWorldHint: false
2192
+ };
2193
+ var CHANGE = {
2194
+ readOnlyHint: false,
2195
+ destructiveHint: false,
2196
+ idempotentHint: true,
2197
+ openWorldHint: true
2198
+ };
2199
+ var ROUTING_FIELDS = [
2200
+ "source",
2201
+ "project",
2202
+ "widget",
2203
+ "connection",
2204
+ "page_url",
2205
+ "page_domain",
2206
+ "customer_email",
2207
+ "customer_email_domain",
2208
+ "message",
2209
+ "subject",
2210
+ "tags",
2211
+ "priority",
2212
+ "language"
2213
+ ];
2214
+ var ROUTING_OPERATORS = [
2215
+ "equals",
2216
+ "not_equals",
2217
+ "contains",
2218
+ "not_contains",
2219
+ "starts_with",
2220
+ "ends_with",
2221
+ "matches"
2222
+ ];
2223
+ var routingConditions = z3.object({
2224
+ match: z3.enum(["all", "any"]).describe("all = every condition holds, any = one is enough"),
2225
+ conditions: z3.array(
2226
+ z3.object({
2227
+ field: z3.enum(ROUTING_FIELDS),
2228
+ operator: z3.enum(ROUTING_OPERATORS),
2229
+ value: z3.union([z3.string(), z3.array(z3.string())]).describe(
2230
+ "A value, or a list (positive operators: any matches; negative: none does). Case-insensitive; matches uses * and ? wildcards."
2231
+ )
2232
+ })
2233
+ ).max(50).describe("Empty = matches every new conversation (catch-all)")
2234
+ }).describe(
2235
+ 'Which new conversations the rule catches, tested on the first message, e.g. { "match": "any", "conditions": [{ "field": "message", "operator": "contains", "value": ["refund", "invoice"] }] }'
2236
+ );
2237
+ var ruleFields = {
2238
+ name: z3.string().trim().min(1).max(255).describe("Rule name"),
2239
+ targetChannelId: z3.string().regex(/^[A-Z0-9]{2,30}$/, "a Slack channel ID like C0123ABCD").describe("Slack channel ID to post matching conversations to"),
2240
+ conditions: routingConditions,
2241
+ projectId: id("Project (default: the oldest project)").optional(),
2242
+ widgetId: id("Widget").nullable().optional(),
2243
+ integrationId: id("Integration (default: the Slack workspace)").optional(),
2244
+ assignToUserId: id("Teammate to assign matching conversations to").nullable().optional(),
2245
+ isActive: z3.boolean().optional().describe("Default true"),
2246
+ priority: z3.number().int().min(-1e6).max(1e6).optional().describe("Higher runs first (default: after every rule)")
2247
+ };
2248
+ var rule = z3.looseObject({
2249
+ id: z3.string(),
2250
+ name: z3.string(),
2251
+ priority: z3.number(),
2252
+ is_active: z3.boolean(),
2253
+ target_channel_id: z3.string()
2254
+ });
2255
+ var INBOX_TOOLS = [
2256
+ defineTool2({
2257
+ name: "list_conversations",
2258
+ title: "List conversations",
2259
+ description: "List support conversations, most recent activity first, filtered by status, priority, assignee, project, tag, source, last update or AI triage (intent/urgency). Each row has the customer, assignee, needsReply (the customer spoke last) and a preview of the latest message. Use get_conversation for the thread. Needs the inbox:read (or read) scope.",
2260
+ scope: "inbox:read",
2261
+ endpoint: "GET /v1/conversations",
2262
+ inputSchema: z3.object({ ...listFilters, ...paging }),
2263
+ outputSchema: listOutput,
2264
+ annotations: READ2,
2265
+ handler: (api, a) => list(api, a)
2266
+ }),
2267
+ defineTool2({
2268
+ name: "search_conversations",
2269
+ title: "Search conversations",
2270
+ description: "Find conversations whose subject, customer name or email, or any message contains the text (case-insensitive), with the same filters as list_conversations. Needs the inbox:read (or read) scope.",
2271
+ scope: "inbox:read",
2272
+ endpoint: "GET /v1/conversations?q=",
2273
+ inputSchema: z3.object({
2274
+ query: z3.string().trim().min(1).max(200).describe("Text to look for"),
2275
+ ...listFilters,
2276
+ ...paging
2277
+ }),
2278
+ outputSchema: listOutput,
2279
+ annotations: READ2,
2280
+ handler: (api, { query, ...a }) => list(api, { ...a, q: query })
2281
+ }),
2282
+ defineTool2({
2283
+ name: "get_conversation",
2284
+ title: "Get conversation",
2285
+ description: "Read one conversation with its full thread: customer, agent, system and bot messages in order, internal notes included (isInternal: true, never seen by the customer), plus status, priority, tags, assignee, customer, triage and its Slack thread. Needs the inbox:read (or read) scope.",
2286
+ scope: "inbox:read",
2287
+ endpoint: "GET /v1/conversations/:id",
2288
+ inputSchema: z3.object({ conversationId }),
2289
+ outputSchema: z3.object({
2290
+ conversation: z3.looseObject({
2291
+ id: z3.string(),
2292
+ status: z3.string(),
2293
+ messages: z3.array(loose)
2294
+ })
2295
+ }),
2296
+ annotations: READ2,
2297
+ handler: async (api, { conversationId: cid }) => {
2298
+ const r = await api.request("GET", path(cid));
2299
+ return { conversation: r.conversation };
2300
+ }
2301
+ }),
2302
+ defineTool2({
2303
+ name: "reply_to_conversation",
2304
+ title: "Reply to conversation",
2305
+ description: 'Send a reply to the customer, as this API key (shown as "<key name> (agent)"). It reaches the customer like a dashboard reply (chat widget, email, SMS, ...) and is mirrored to the Slack thread; an open conversation becomes pending. Confirm the text with the user before sending. For a note only the team sees, use add_internal_note. Needs the inbox:write scope.',
2306
+ scope: "inbox:write",
2307
+ endpoint: "POST /v1/conversations/:id/reply",
2308
+ inputSchema: z3.object({
2309
+ conversationId,
2310
+ content: z3.string().trim().min(1).max(1e4).describe("Reply text, as the customer will read it")
2311
+ }),
2312
+ outputSchema: z3.object({
2313
+ message: z3.looseObject({ id: z3.string() }),
2314
+ conversationStatus: z3.string(),
2315
+ slack: slackOutcome
2316
+ }),
2317
+ annotations: {
2318
+ readOnlyHint: false,
2319
+ destructiveHint: false,
2320
+ idempotentHint: false,
2321
+ openWorldHint: true
2322
+ },
2323
+ handler: async (api, { conversationId: cid, content }) => {
2324
+ const r = await api.request("POST", path(cid, "/reply"), {
2325
+ body: { content }
2326
+ });
2327
+ return {
2328
+ message: r.message,
2329
+ conversationStatus: String(r.conversationStatus ?? ""),
2330
+ slack: String(r.slack ?? "")
2331
+ };
2332
+ }
2333
+ }),
2334
+ defineTool2({
2335
+ name: "add_internal_note",
2336
+ title: "Add internal note",
2337
+ description: "Add an internal note to a conversation: posted in its Slack thread for the team and kept in the conversation, never sent to the customer. Use it for findings, handoffs and suggested replies. Needs the inbox:write scope.",
2338
+ scope: "inbox:write",
2339
+ endpoint: "POST /v1/conversations/:id/notes",
2340
+ inputSchema: z3.object({
2341
+ conversationId,
2342
+ content: z3.string().trim().min(1).max(1e4).describe("Note text")
2343
+ }),
2344
+ outputSchema: z3.object({
2345
+ note: z3.looseObject({ id: z3.string() }),
2346
+ slack: slackOutcome
2347
+ }),
2348
+ annotations: {
2349
+ readOnlyHint: false,
2350
+ destructiveHint: false,
2351
+ idempotentHint: false,
2352
+ openWorldHint: true
2353
+ },
2354
+ handler: async (api, { conversationId: cid, content }) => {
2355
+ const r = await api.request("POST", path(cid, "/notes"), {
2356
+ body: { content }
2357
+ });
2358
+ return { note: r.note, slack: String(r.slack ?? "") };
2359
+ }
2360
+ }),
2361
+ defineTool2({
2362
+ name: "assign_conversation",
2363
+ title: "Assign conversation",
2364
+ description: "Assign a conversation to a teammate (by user ID or email; owners, admins and agents, not viewers), or unassign it with null. The teammate is notified, and the change shows in the timeline and Slack. Needs the inbox:write scope.",
2365
+ scope: "inbox:write",
2366
+ endpoint: "PATCH /v1/conversations/:id",
2367
+ inputSchema: z3.object({
2368
+ conversationId,
2369
+ assignee: z3.string().min(1).max(255).nullable().describe("User ID or email of the teammate, or null to unassign")
2370
+ }),
2371
+ outputSchema: changeOutput,
2372
+ annotations: CHANGE,
2373
+ handler: (api, { conversationId: cid, assignee }) => patch(
2374
+ api,
2375
+ cid,
2376
+ assignee === null ? { assigneeId: null } : assignee.includes("@") ? { assigneeEmail: assignee } : { assigneeId: assignee }
2377
+ )
2378
+ }),
2379
+ defineTool2({
2380
+ name: "tag_conversation",
2381
+ title: "Tag conversation",
2382
+ description: "Add or remove tags on a conversation, or replace them all with `set`. Tags are lowercased; at most 20. Needs the inbox:write scope.",
2383
+ scope: "inbox:write",
2384
+ endpoint: "PATCH /v1/conversations/:id",
2385
+ inputSchema: z3.object({
2386
+ conversationId,
2387
+ add: tags.optional().describe("Tags to add"),
2388
+ remove: tags.optional().describe("Tags to remove"),
2389
+ set: tags.optional().describe("Replace every tag with these ([] clears them)")
2390
+ }),
2391
+ outputSchema: changeOutput,
2392
+ annotations: CHANGE,
2393
+ handler: (api, { conversationId: cid, add, remove, set }) => {
2394
+ if (!add?.length && !remove?.length && !set) {
2395
+ throw new ToolError("Pass tags to add, remove, or set.");
2396
+ }
2397
+ return patch(api, cid, {
2398
+ ...set ? { tags: set } : {},
2399
+ ...add?.length ? { addTags: add } : {},
2400
+ ...remove?.length ? { removeTags: remove } : {}
2401
+ });
2402
+ }
2403
+ }),
2404
+ defineTool2({
2405
+ name: "close_conversation",
2406
+ title: "Close conversation",
2407
+ description: "Close a conversation (or mark it resolved). Nothing is sent to the customer; the change shows in the timeline and the Slack root post. Reply first if the customer should hear back. Needs the inbox:write scope.",
2408
+ scope: "inbox:write",
2409
+ endpoint: "PATCH /v1/conversations/:id",
2410
+ inputSchema: z3.object({
2411
+ conversationId,
2412
+ status: z3.enum(["closed", "resolved"]).default("closed").describe("closed (default) or resolved")
2413
+ }),
2414
+ outputSchema: changeOutput,
2415
+ annotations: CHANGE,
2416
+ handler: (api, { conversationId: cid, status }) => patch(api, cid, { status })
2417
+ }),
2418
+ defineTool2({
2419
+ name: "reopen_conversation",
2420
+ title: "Reopen conversation",
2421
+ description: "Reopen a closed or resolved conversation (status open). Needs the inbox:write scope.",
2422
+ scope: "inbox:write",
2423
+ endpoint: "PATCH /v1/conversations/:id",
2424
+ inputSchema: z3.object({ conversationId }),
2425
+ outputSchema: changeOutput,
2426
+ annotations: CHANGE,
2427
+ handler: (api, { conversationId: cid }) => patch(api, cid, { status: "open" })
2428
+ }),
2429
+ defineTool2({
2430
+ name: "get_analytics_summary",
2431
+ title: "Get analytics summary",
2432
+ description: "Support KPIs for a period (default the last 30 days): conversations started and resolved, median first-response and resolution times, messages in and out, each with the previous period; plus the inbox right now (open, pending, unassigned, urgent, awaiting a reply). Needs the analytics:read (or read) scope.",
2433
+ scope: "analytics:read",
2434
+ endpoint: "GET /v1/analytics/summary",
2435
+ inputSchema: z3.object({
2436
+ days: z3.number().int().min(1).max(366).optional().describe("Period length in days, ending today (default 30)"),
2437
+ from: z3.iso.date().optional().describe("First day, YYYY-MM-DD"),
2438
+ to: z3.iso.date().optional().describe("Last day, YYYY-MM-DD"),
2439
+ tz: z3.string().max(64).optional().describe("IANA time zone for day boundaries (default UTC)"),
2440
+ projectId: id("Project").optional()
2441
+ }),
2442
+ outputSchema: z3.looseObject({ range: loose, kpis: loose, inbox: loose }),
2443
+ annotations: READ2,
2444
+ handler: async (api, args) => api.request(
2445
+ "GET",
2446
+ "/v1/analytics/summary",
2447
+ { query: args }
2448
+ )
2449
+ }),
2450
+ defineTool2({
2451
+ name: "list_routing_rules",
2452
+ title: "List routing rules",
2453
+ description: "List the routing rules in evaluation order (highest priority first): which new conversations each one sends to which Slack channel, and who it assigns. Needs the routing:write, inbox:read or read scope.",
2454
+ scope: "routing:read",
2455
+ endpoint: "GET /v1/routing-rules",
2456
+ inputSchema: z3.object({}),
2457
+ outputSchema: z3.object({ rules: z3.array(rule) }),
2458
+ annotations: READ2,
2459
+ handler: async (api) => {
2460
+ const r = await api.request(
2461
+ "GET",
2462
+ "/v1/routing-rules"
2463
+ );
2464
+ return { rules: r.routing_rules ?? [] };
2465
+ }
2466
+ }),
2467
+ defineTool2({
2468
+ name: "create_routing_rule",
2469
+ title: "Create routing rule",
2470
+ description: "Create a routing rule: new conversations whose first message matches `conditions` are posted to `targetChannelId` instead of the default channel (and optionally assigned). It runs after the existing rules unless `priority` is given. Confirm with the user first. Needs the routing:write scope.",
2471
+ scope: "routing:write",
2472
+ endpoint: "POST /v1/routing-rules",
2473
+ inputSchema: z3.object(ruleFields),
2474
+ outputSchema: z3.object({ rule }),
2475
+ annotations: {
2476
+ readOnlyHint: false,
2477
+ destructiveHint: false,
2478
+ idempotentHint: false,
2479
+ openWorldHint: false
2480
+ },
2481
+ handler: async (api, body) => {
2482
+ const r = await api.request(
2483
+ "POST",
2484
+ "/v1/routing-rules",
2485
+ { body }
2486
+ );
2487
+ return { rule: r.routing_rule };
2488
+ }
2489
+ }),
2490
+ defineTool2({
2491
+ name: "update_routing_rule",
2492
+ title: "Update routing rule",
2493
+ description: "Change a routing rule (from list_routing_rules); omitted fields keep their value, and `conditions` replaces the whole condition group. Use isActive: false to pause a rule. Needs the routing:write scope.",
2494
+ scope: "routing:write",
2495
+ endpoint: "PATCH /v1/routing-rules/:id",
2496
+ inputSchema: z3.object({
2497
+ ruleId: id("Routing rule"),
2498
+ name: ruleFields.name.optional(),
2499
+ targetChannelId: ruleFields.targetChannelId.optional(),
2500
+ conditions: routingConditions.optional(),
2501
+ projectId: ruleFields.projectId,
2502
+ widgetId: ruleFields.widgetId,
2503
+ integrationId: ruleFields.integrationId,
2504
+ assignToUserId: ruleFields.assignToUserId,
2505
+ isActive: ruleFields.isActive,
2506
+ priority: ruleFields.priority
2507
+ }),
2508
+ outputSchema: z3.object({ rule }),
2509
+ annotations: {
2510
+ readOnlyHint: false,
2511
+ destructiveHint: false,
2512
+ idempotentHint: true,
2513
+ openWorldHint: false
2514
+ },
2515
+ handler: async (api, { ruleId, ...body }) => {
2516
+ if (Object.values(body).every((v) => v === void 0)) {
2517
+ throw new ToolError("Pass at least one field to change.");
2518
+ }
2519
+ const r = await api.request(
2520
+ "PATCH",
2521
+ `/v1/routing-rules/${encodeURIComponent(ruleId)}`,
2522
+ { body }
2523
+ );
2524
+ return { rule: r.routing_rule };
2525
+ }
2526
+ }),
2527
+ defineTool2({
2528
+ name: "delete_routing_rule",
2529
+ title: "Delete routing rule",
2530
+ description: "Delete a routing rule for good. To stop it temporarily, use update_routing_rule with isActive: false instead. Confirm with the user first. Needs the routing:write scope.",
2531
+ scope: "routing:write",
2532
+ endpoint: "DELETE /v1/routing-rules/:id",
2533
+ inputSchema: z3.object({ ruleId: id("Routing rule") }),
2534
+ outputSchema: z3.object({ deleted: z3.boolean(), ruleId: z3.string() }),
2535
+ annotations: {
2536
+ readOnlyHint: false,
2537
+ destructiveHint: true,
2538
+ idempotentHint: true,
2539
+ openWorldHint: false
2540
+ },
2541
+ handler: async (api, { ruleId }) => {
2542
+ await api.request(
2543
+ "DELETE",
2544
+ `/v1/routing-rules/${encodeURIComponent(ruleId)}`
2545
+ );
2546
+ return { deleted: true, ruleId };
2547
+ }
2548
+ })
2549
+ ];
2550
+ var INBOX_TOOL_NAMES = INBOX_TOOLS.map((t) => t.name);
2551
+ function getInboxTool(name) {
2552
+ return INBOX_TOOLS.find((t) => t.name === name);
2553
+ }
2554
+ async function runInboxTool(api, name, args) {
2555
+ const tool = getInboxTool(name);
2556
+ if (!tool) throw new ToolError(`Unknown inbox tool "${name}"`);
2557
+ const parsed = tool.inputSchema.safeParse(args ?? {});
2558
+ if (!parsed.success) {
2559
+ throw new ToolError(
2560
+ `Invalid arguments for ${name}: ${parsed.error.issues.map((i) => `${i.path.join(".") || "input"}: ${i.message}`).join("; ")}`
2561
+ );
2562
+ }
2563
+ return await tool.handler(api, parsed.data);
2564
+ }
2565
+ function inboxToolsAsJsonSchema(filter = () => true) {
2566
+ return INBOX_TOOLS.filter(filter).map((t) => ({
2567
+ name: t.name,
2568
+ description: t.description,
2569
+ parameters: z3.toJSONSchema(t.inputSchema, { io: "input" })
2570
+ }));
2571
+ }
2572
+
2573
+ // src/tools.ts
2574
+ function ok(data2) {
2575
+ return {
2576
+ content: [{ type: "text", text: JSON.stringify(data2, null, 2) }],
2577
+ structuredContent: data2
616
2578
  };
617
2579
  }
618
2580
  async function run(fn) {
@@ -626,25 +2588,15 @@ async function run(fn) {
626
2588
  };
627
2589
  }
628
2590
  }
629
- var record2 = z2.record(z2.string(), z2.unknown());
630
- var loose = z2.looseObject({});
631
- var page = {
632
- total: z2.number(),
633
- limit: z2.number(),
634
- offset: z2.number(),
635
- hasMore: z2.boolean()
2591
+ var record4 = z4.record(z4.string(), z4.unknown());
2592
+ var loose2 = z4.looseObject({});
2593
+ var page2 = {
2594
+ total: z4.number(),
2595
+ limit: z4.number(),
2596
+ offset: z4.number(),
2597
+ hasMore: z4.boolean()
636
2598
  };
637
- var conversationSummary = z2.looseObject({
638
- id: z2.string(),
639
- subject: z2.string().nullable().optional(),
640
- status: z2.string(),
641
- priority: z2.string().nullable().optional(),
642
- customerEmail: z2.string().nullable().optional(),
643
- customerName: z2.string().nullable().optional(),
644
- tags: z2.array(z2.string()).nullable().optional(),
645
- createdAt: z2.string().optional()
646
- });
647
- var READ = {
2599
+ var READ3 = {
648
2600
  readOnlyHint: true,
649
2601
  destructiveHint: false,
650
2602
  idempotentHint: true,
@@ -656,9 +2608,9 @@ function registerServerTools(server, api) {
656
2608
  {
657
2609
  title: "Get project",
658
2610
  description: "Show the Channlize project behind the server API key: name, ID, totals, the key's permissions and whether Slack is connected. Start here to check the setup.",
659
- inputSchema: z2.object({}),
660
- outputSchema: z2.object({ project: loose }),
661
- annotations: READ
2611
+ inputSchema: z4.object({}),
2612
+ outputSchema: z4.object({ project: loose2 }),
2613
+ annotations: READ3
662
2614
  },
663
2615
  () => run(async () => {
664
2616
  const r = await api.request("GET", "/projects/me");
@@ -670,9 +2622,9 @@ function registerServerTools(server, api) {
670
2622
  {
671
2623
  title: "Get analytics",
672
2624
  description: "Daily support activity for the last 30 days (UTC): conversations created and resolved, customer and agent messages.",
673
- inputSchema: z2.object({}),
674
- outputSchema: z2.object({ analytics: loose }),
675
- annotations: READ
2625
+ inputSchema: z4.object({}),
2626
+ outputSchema: z4.object({ analytics: loose2 }),
2627
+ annotations: READ3
676
2628
  },
677
2629
  () => run(async () => {
678
2630
  const r = await api.request(
@@ -682,75 +2634,20 @@ function registerServerTools(server, api) {
682
2634
  return { analytics: r.analytics };
683
2635
  })
684
2636
  );
685
- server.registerTool(
686
- "list_conversations",
687
- {
688
- title: "List conversations",
689
- description: "List the organization's most recent support conversations (newest first, from the latest 50), optionally filtered by status or priority. Use get_conversation for the messages.",
690
- inputSchema: z2.object({
691
- status: z2.enum(STATUSES).optional().describe("Only conversations with this status"),
692
- priority: z2.enum(PRIORITIES).optional().describe("Only conversations with this priority"),
693
- limit: z2.number().int().min(1).max(50).default(20).describe("How many to return (1-50, default 20)")
694
- }),
695
- outputSchema: z2.object({
696
- conversations: z2.array(conversationSummary),
697
- returned: z2.number(),
698
- matched: z2.number(),
699
- scanned: z2.number()
700
- }),
701
- annotations: READ
702
- },
703
- ({ status, priority, limit }) => run(async () => {
704
- const r = await api.request(
705
- "GET",
706
- "/conversations"
707
- );
708
- const all = r.conversations ?? [];
709
- const matched = all.filter(
710
- (c) => (!status || c.status === status) && (!priority || c.priority === priority)
711
- );
712
- const conversations = matched.slice(0, limit);
713
- return {
714
- conversations,
715
- returned: conversations.length,
716
- matched: matched.length,
717
- scanned: all.length
718
- };
719
- })
720
- );
721
- server.registerTool(
722
- "get_conversation",
723
- {
724
- title: "Get conversation",
725
- description: "Read one conversation with its full message thread (customer, agent and system messages), status, priority and tags.",
726
- inputSchema: z2.object({
727
- conversationId: z2.string().uuid().describe("Conversation ID (from list_conversations)")
728
- }),
729
- outputSchema: z2.object({ conversation: loose }),
730
- annotations: READ
731
- },
732
- ({ conversationId }) => run(async () => {
733
- const conversation = await api.request(
734
- "GET",
735
- `/conversations/${encodeURIComponent(conversationId)}`
736
- );
737
- return { conversation };
738
- })
739
- );
740
2637
  server.registerTool(
741
2638
  "create_conversation",
742
2639
  {
743
2640
  title: "Create conversation",
744
2641
  description: "Open a new support conversation on behalf of a customer. It is posted to Slack (the given channel, else routing rules, else the default channel). Needs the write scope. Repeating the same customer, subject and message within 30 seconds returns the existing conversation.",
745
- inputSchema: z2.object({
746
- customerEmail: z2.email().describe("Customer's email address"),
747
- customerName: z2.string().max(255).optional().describe("Customer's name"),
748
- subject: z2.string().min(1).max(500).describe("Subject line"),
749
- message: z2.string().min(1).describe("First message, from the customer"),
750
- channel: z2.string().optional().describe("Slack channel ID to post to, overriding routing rules"),
751
- tags: z2.array(z2.string()).max(20).optional().describe("Tags")
2642
+ inputSchema: z4.object({
2643
+ customerEmail: z4.email().describe("Customer's email address"),
2644
+ customerName: z4.string().max(255).optional().describe("Customer's name"),
2645
+ subject: z4.string().min(1).max(500).describe("Subject line"),
2646
+ message: z4.string().min(1).describe("First message, from the customer"),
2647
+ channel: z4.string().optional().describe("Slack channel ID to post to, overriding routing rules"),
2648
+ tags: z4.array(z4.string()).max(20).optional().describe("Tags")
752
2649
  }),
753
- outputSchema: z2.object({ conversation: loose }),
2650
+ outputSchema: z4.object({ conversation: loose2 }),
754
2651
  annotations: {
755
2652
  readOnlyHint: false,
756
2653
  destructiveHint: false,
@@ -770,12 +2667,12 @@ function registerServerTools(server, api) {
770
2667
  {
771
2668
  title: "List contacts",
772
2669
  description: "List the customers who contacted the organization, with their conversation count. Paginate with limit/offset.",
773
- inputSchema: z2.object({
774
- limit: z2.number().int().min(1).max(100).default(50),
775
- offset: z2.number().int().min(0).default(0)
2670
+ inputSchema: z4.object({
2671
+ limit: z4.number().int().min(1).max(100).default(50),
2672
+ offset: z4.number().int().min(0).default(0)
776
2673
  }),
777
- outputSchema: z2.object({ contacts: z2.array(loose), ...page }),
778
- annotations: READ
2674
+ outputSchema: z4.object({ contacts: z4.array(loose2), ...page2 }),
2675
+ annotations: READ3
779
2676
  },
780
2677
  ({ limit, offset }) => run(async () => {
781
2678
  const r = await api.request("GET", "/contacts", {
@@ -795,11 +2692,11 @@ function registerServerTools(server, api) {
795
2692
  {
796
2693
  title: "Get contact",
797
2694
  description: "Read one contact (customer) by ID.",
798
- inputSchema: z2.object({
799
- contactId: z2.string().uuid().describe("Contact ID (from list_contacts)")
2695
+ inputSchema: z4.object({
2696
+ contactId: z4.string().uuid().describe("Contact ID (from list_contacts)")
800
2697
  }),
801
- outputSchema: z2.object({ contact: loose }),
802
- annotations: READ
2698
+ outputSchema: z4.object({ contact: loose2 }),
2699
+ annotations: READ3
803
2700
  },
804
2701
  ({ contactId }) => run(async () => {
805
2702
  const contact = await api.request(
@@ -814,14 +2711,14 @@ function registerServerTools(server, api) {
814
2711
  {
815
2712
  title: "Create contact",
816
2713
  description: "Add a customer by email, or return the existing one with that email. Needs the write scope.",
817
- inputSchema: z2.object({
818
- email: z2.email(),
819
- name: z2.string().max(255).optional(),
820
- company: z2.string().optional(),
821
- phone: z2.string().optional(),
822
- tags: z2.array(z2.string()).max(20).optional()
2714
+ inputSchema: z4.object({
2715
+ email: z4.email(),
2716
+ name: z4.string().max(255).optional(),
2717
+ company: z4.string().optional(),
2718
+ phone: z4.string().optional(),
2719
+ tags: z4.array(z4.string()).max(20).optional()
823
2720
  }),
824
- outputSchema: z2.object({ contact: loose }),
2721
+ outputSchema: z4.object({ contact: loose2 }),
825
2722
  annotations: {
826
2723
  readOnlyHint: false,
827
2724
  destructiveHint: false,
@@ -841,23 +2738,23 @@ function registerServerTools(server, api) {
841
2738
  {
842
2739
  title: "Send an Event to Slack",
843
2740
  description: 'Post an Event to Slack: the event key (e.g. "user.subscribed") picks the channel and message template set under Events in the dashboard, and `data` fills its {{placeholders}}. An unknown key is saved as a disabled draft and answered with status "skipped". Needs the write scope. Pass an idempotencyKey so a retry never posts twice.',
844
- inputSchema: z2.object({
845
- event: z2.string().max(100).regex(
2741
+ inputSchema: z4.object({
2742
+ event: z4.string().max(100).regex(
846
2743
  import_core3.EVENT_KEY_PATTERN,
847
2744
  "lowercase letters, digits, dots, underscores or dashes"
848
2745
  ).describe("Event key, e.g. user.subscribed"),
849
- data: record2.optional().describe(
2746
+ data: record4.optional().describe(
850
2747
  'Template fields, e.g. { "username": "ada", "plan": "Pro" }'
851
2748
  ),
852
- idempotencyKey: z2.string().min(1).max(255).optional().describe("Send at most once per key (retry-safe)"),
853
- channel: z2.string().optional().describe("Slack channel ID instead of the event's channel")
2749
+ idempotencyKey: z4.string().min(1).max(255).optional().describe("Send at most once per key (retry-safe)"),
2750
+ channel: z4.string().optional().describe("Slack channel ID instead of the event's channel")
854
2751
  }),
855
- outputSchema: z2.looseObject({
856
- id: z2.string(),
857
- event: z2.string(),
858
- status: z2.string(),
859
- reason: z2.string().optional(),
860
- duplicate: z2.boolean().optional()
2752
+ outputSchema: z4.looseObject({
2753
+ id: z4.string(),
2754
+ event: z4.string(),
2755
+ status: z4.string(),
2756
+ reason: z4.string().optional(),
2757
+ duplicate: z4.boolean().optional()
861
2758
  }),
862
2759
  annotations: {
863
2760
  readOnlyHint: false,
@@ -866,9 +2763,9 @@ function registerServerTools(server, api) {
866
2763
  openWorldHint: true
867
2764
  }
868
2765
  },
869
- ({ event, data, idempotencyKey, channel }) => run(async () => {
2766
+ ({ event, data: data2, idempotencyKey, channel }) => run(async () => {
870
2767
  const client = await api.notifier();
871
- const r = await client.notify(event, data, { idempotencyKey, channel });
2768
+ const r = await client.notify(event, data2, { idempotencyKey, channel });
872
2769
  return {
873
2770
  id: r.id,
874
2771
  event: r.event,
@@ -883,12 +2780,12 @@ function registerServerTools(server, api) {
883
2780
  {
884
2781
  title: "List Events",
885
2782
  description: "List the Events configured on the project (key, name, Slack channel, message template, enabled), including disabled drafts created by unknown keys sent with notify_event.",
886
- inputSchema: z2.object({}),
887
- outputSchema: z2.object({
888
- projectId: z2.string(),
889
- definitions: z2.array(loose)
2783
+ inputSchema: z4.object({}),
2784
+ outputSchema: z4.object({
2785
+ projectId: z4.string(),
2786
+ definitions: z4.array(loose2)
890
2787
  }),
891
- annotations: READ
2788
+ annotations: READ3
892
2789
  },
893
2790
  () => run(async () => {
894
2791
  const projectId = await api.projectId();
@@ -904,15 +2801,15 @@ function registerServerTools(server, api) {
904
2801
  {
905
2802
  title: "List Event deliveries",
906
2803
  description: "Recent notify_event deliveries on the project, newest first, with their status (queued, sent, failed, skipped) and the reason when not sent. Use it to check why an Event did not reach Slack.",
907
- inputSchema: z2.object({
908
- definitionId: z2.string().uuid().optional().describe("Only this Event (ID from list_event_definitions)"),
909
- limit: z2.number().int().min(1).max(100).default(20)
2804
+ inputSchema: z4.object({
2805
+ definitionId: z4.string().uuid().optional().describe("Only this Event (ID from list_event_definitions)"),
2806
+ limit: z4.number().int().min(1).max(100).default(20)
910
2807
  }),
911
- outputSchema: z2.object({
912
- projectId: z2.string(),
913
- deliveries: z2.array(loose)
2808
+ outputSchema: z4.object({
2809
+ projectId: z4.string(),
2810
+ deliveries: z4.array(loose2)
914
2811
  }),
915
- annotations: READ
2812
+ annotations: READ3
916
2813
  },
917
2814
  ({ definitionId, limit }) => run(async () => {
918
2815
  const projectId = await api.projectId();
@@ -929,20 +2826,20 @@ function registerServerTools(server, api) {
929
2826
  {
930
2827
  title: "Query logs",
931
2828
  description: "Search log tracking (trackEvent / trackServerEvent / track_log), newest first. Filter by severity, source, text (matches the name and properties) and time range; paginate with limit/offset. Covers all projects unless projectId is given.",
932
- inputSchema: z2.object({
933
- severity: z2.enum(import_core3.EVENT_SEVERITIES).optional(),
934
- source: z2.enum(["client_sdk", "server_api", "system"]).optional().describe(
2829
+ inputSchema: z4.object({
2830
+ severity: z4.enum(import_core3.EVENT_SEVERITIES).optional(),
2831
+ source: z4.enum(["client_sdk", "server_api", "system"]).optional().describe(
935
2832
  "client_sdk = browser (widget key), server_api = server key"
936
2833
  ),
937
- search: z2.string().max(200).optional().describe("Text to look for"),
938
- from: z2.iso.datetime({ offset: true }).optional().describe("ISO 8601 start"),
939
- to: z2.iso.datetime({ offset: true }).optional().describe("ISO 8601 end"),
940
- projectId: z2.string().uuid().optional(),
941
- limit: z2.number().int().min(1).max(100).default(50),
942
- offset: z2.number().int().min(0).default(0)
2834
+ search: z4.string().max(200).optional().describe("Text to look for"),
2835
+ from: z4.iso.datetime({ offset: true }).optional().describe("ISO 8601 start"),
2836
+ to: z4.iso.datetime({ offset: true }).optional().describe("ISO 8601 end"),
2837
+ projectId: z4.string().uuid().optional(),
2838
+ limit: z4.number().int().min(1).max(100).default(50),
2839
+ offset: z4.number().int().min(0).default(0)
943
2840
  }),
944
- outputSchema: z2.object({ events: z2.array(loose), ...page }),
945
- annotations: READ
2841
+ outputSchema: z4.object({ events: z4.array(loose2), ...page2 }),
2842
+ annotations: READ3
946
2843
  },
947
2844
  (args) => run(async () => {
948
2845
  const r = await api.request("GET", "/v1/events", { query: args });
@@ -960,12 +2857,12 @@ function registerServerTools(server, api) {
960
2857
  {
961
2858
  title: "Record a log",
962
2859
  description: "Record a log line under Log tracking from a trusted server context (source server_api). Needs the write scope. For Slack messages about product events use notify_event instead.",
963
- inputSchema: z2.object({
964
- name: z2.string().min(1).max(255).describe("Log name, e.g. payment.failed"),
965
- severity: z2.enum(import_core3.EVENT_SEVERITIES).default("info"),
966
- properties: record2.optional().describe("Extra fields")
2860
+ inputSchema: z4.object({
2861
+ name: z4.string().min(1).max(255).describe("Log name, e.g. payment.failed"),
2862
+ severity: z4.enum(import_core3.EVENT_SEVERITIES).default("info"),
2863
+ properties: record4.optional().describe("Extra fields")
967
2864
  }),
968
- outputSchema: z2.object({ id: z2.string(), projectId: z2.string() }),
2865
+ outputSchema: z4.object({ id: z4.string(), projectId: z4.string() }),
969
2866
  annotations: {
970
2867
  readOnlyHint: false,
971
2868
  destructiveHint: false,
@@ -994,16 +2891,16 @@ function registerWidgetTools(server, api) {
994
2891
  {
995
2892
  title: "Submit contact form",
996
2893
  description: "Submit the website contact form as a visitor (widget key). Creates a conversation that is posted to Slack. Useful to test the setup end to end.",
997
- inputSchema: z2.object({
998
- name: z2.string().min(1).describe("Visitor's name"),
999
- email: z2.email().describe("Visitor's email"),
1000
- subject: z2.string().optional(),
1001
- message: z2.string().min(1),
1002
- pageUrl: z2.url().optional().describe("Page the form was sent from")
2894
+ inputSchema: z4.object({
2895
+ name: z4.string().min(1).describe("Visitor's name"),
2896
+ email: z4.email().describe("Visitor's email"),
2897
+ subject: z4.string().optional(),
2898
+ message: z4.string().min(1),
2899
+ pageUrl: z4.url().optional().describe("Page the form was sent from")
1003
2900
  }),
1004
- outputSchema: z2.looseObject({
1005
- conversationId: z2.string().optional(),
1006
- message: z2.string().optional()
2901
+ outputSchema: z4.looseObject({
2902
+ conversationId: z4.string().optional(),
2903
+ message: z4.string().optional()
1007
2904
  }),
1008
2905
  annotations: VISITOR
1009
2906
  },
@@ -1017,12 +2914,12 @@ function registerWidgetTools(server, api) {
1017
2914
  {
1018
2915
  title: "Start chat session",
1019
2916
  description: "Start a live chat session as a website visitor (widget key). Returns the session ID for send_message.",
1020
- inputSchema: z2.object({
1021
- metadata: record2.optional().describe("Metadata to attach (e.g. user info)")
2917
+ inputSchema: z4.object({
2918
+ metadata: record4.optional().describe("Metadata to attach (e.g. user info)")
1022
2919
  }),
1023
- outputSchema: z2.looseObject({
1024
- sessionId: z2.string(),
1025
- status: z2.string()
2920
+ outputSchema: z4.looseObject({
2921
+ sessionId: z4.string(),
2922
+ status: z4.string()
1026
2923
  }),
1027
2924
  annotations: VISITOR
1028
2925
  },
@@ -1040,13 +2937,13 @@ function registerWidgetTools(server, api) {
1040
2937
  {
1041
2938
  title: "Send chat message",
1042
2939
  description: "Send a visitor message in a chat session (widget key); it is posted to the Slack thread.",
1043
- inputSchema: z2.object({
1044
- sessionId: z2.string().min(1).describe("From create_chat_session"),
1045
- content: z2.string().min(1).max(5e3)
2940
+ inputSchema: z4.object({
2941
+ sessionId: z4.string().min(1).describe("From create_chat_session"),
2942
+ content: z4.string().min(1).max(5e3)
1046
2943
  }),
1047
- outputSchema: z2.looseObject({
1048
- messageId: z2.string(),
1049
- sessionStatus: z2.string()
2944
+ outputSchema: z4.looseObject({
2945
+ messageId: z4.string(),
2946
+ sessionStatus: z4.string()
1050
2947
  }),
1051
2948
  annotations: VISITOR
1052
2949
  },
@@ -1060,16 +2957,16 @@ function registerWidgetTools(server, api) {
1060
2957
  {
1061
2958
  title: "Read chat messages",
1062
2959
  description: "Read a chat session's messages, including agent replies from Slack (widget key).",
1063
- inputSchema: z2.object({
1064
- sessionId: z2.string().min(1),
1065
- limit: z2.number().int().min(1).max(100).default(50),
1066
- offset: z2.number().int().min(0).default(0)
2960
+ inputSchema: z4.object({
2961
+ sessionId: z4.string().min(1),
2962
+ limit: z4.number().int().min(1).max(100).default(50),
2963
+ offset: z4.number().int().min(0).default(0)
1067
2964
  }),
1068
- outputSchema: z2.object({
1069
- sessionId: z2.string(),
1070
- messages: z2.array(loose)
2965
+ outputSchema: z4.object({
2966
+ sessionId: z4.string(),
2967
+ messages: z4.array(loose2)
1071
2968
  }),
1072
- annotations: { ...READ, openWorldHint: true }
2969
+ annotations: { ...READ3, openWorldHint: true }
1073
2970
  },
1074
2971
  ({ sessionId, limit, offset }) => run(async () => {
1075
2972
  const messages = await api.widget().getChatMessages(sessionId, limit, offset);
@@ -1091,10 +2988,10 @@ function registerWidgetTools(server, api) {
1091
2988
  {
1092
2989
  title: "End chat session",
1093
2990
  description: "End a chat session as the visitor (widget key).",
1094
- inputSchema: z2.object({ sessionId: z2.string().min(1) }),
1095
- outputSchema: z2.looseObject({
1096
- sessionId: z2.string(),
1097
- status: z2.string()
2991
+ inputSchema: z4.object({ sessionId: z4.string().min(1) }),
2992
+ outputSchema: z4.looseObject({
2993
+ sessionId: z4.string(),
2994
+ status: z4.string()
1098
2995
  }),
1099
2996
  annotations: { ...VISITOR, idempotentHint: true }
1100
2997
  },
@@ -1104,6 +3001,27 @@ function registerWidgetTools(server, api) {
1104
3001
  })
1105
3002
  );
1106
3003
  }
3004
+ function registerAll(server, api, tools) {
3005
+ for (const tool of tools) {
3006
+ server.registerTool(
3007
+ tool.name,
3008
+ {
3009
+ title: tool.title,
3010
+ description: tool.description,
3011
+ inputSchema: tool.inputSchema,
3012
+ outputSchema: tool.outputSchema,
3013
+ annotations: tool.annotations
3014
+ },
3015
+ (args) => run(async () => await tool.handler(api, args))
3016
+ );
3017
+ }
3018
+ }
3019
+ function registerInboxTools(server, api) {
3020
+ registerAll(server, api, INBOX_TOOLS);
3021
+ }
3022
+ function registerAgentTools(server, api) {
3023
+ registerAll(server, api, AGENT_TOOLS);
3024
+ }
1107
3025
 
1108
3026
  // src/http.ts
1109
3027
  var import_node_http = require("http");
@@ -1135,7 +3053,7 @@ async function toRequest(req, origin) {
1135
3053
  async function startHttpServer(factory, options = {}) {
1136
3054
  const host = options.host ?? "127.0.0.1";
1137
3055
  const port = options.port ?? 3333;
1138
- const path = options.path ?? "/mcp";
3056
+ const path2 = options.path ?? "/mcp";
1139
3057
  const local = LOCAL_HOSTS.has(host);
1140
3058
  const handler = (0, import_server.createMcpHandler)(() => factory(), {
1141
3059
  onerror: (err) => console.error("[channlize-mcp]", err.message)
@@ -1147,8 +3065,8 @@ async function startHttpServer(factory, options = {}) {
1147
3065
  `http://${req.headers.host ?? `${host}:${port}`}`
1148
3066
  );
1149
3067
  const url2 = new URL(request.url);
1150
- if (url2.pathname !== path) {
1151
- res.writeHead(404, { "Content-Type": "text/plain" }).end(`Not found: use ${path}`);
3068
+ if (url2.pathname !== path2) {
3069
+ res.writeHead(404, { "Content-Type": "text/plain" }).end(`Not found: use ${path2}`);
1152
3070
  return;
1153
3071
  }
1154
3072
  const rejected = local ? (0, import_server.hostHeaderValidationResponse)(request, (0, import_server.localhostAllowedHostnames)()) ?? (0, import_server.originValidationResponse)(request, (0, import_server.localhostAllowedOrigins)()) : void 0;
@@ -1175,7 +3093,7 @@ async function startHttpServer(factory, options = {}) {
1175
3093
  const actualPort = typeof address === "object" && address ? address.port : port;
1176
3094
  const shownHost = host.includes(":") ? `[${host}]` : host;
1177
3095
  return {
1178
- url: `http://${shownHost}:${actualPort}${path}`,
3096
+ url: `http://${shownHost}:${actualPort}${path2}`,
1179
3097
  server,
1180
3098
  close: () => new Promise((r) => server.close(() => r()))
1181
3099
  };
@@ -1183,12 +3101,18 @@ async function startHttpServer(factory, options = {}) {
1183
3101
 
1184
3102
  // src/index.ts
1185
3103
  var import_core4 = require("@channlize/core");
1186
- var VERSION = true ? "0.4.0" : "0.0.0";
3104
+ var VERSION = true ? "0.6.0" : "0.0.0";
1187
3105
  var INSTRUCTIONS = `Channlize routes website conversations and app events to the team's Slack.
1188
- - Inbox: list_conversations / get_conversation, then contacts. Replies and status changes happen in Slack or the dashboard.
3106
+ - Inbox: list_conversations / search_conversations, then get_conversation for the thread. reply_to_conversation sends to the customer as this key ("<key name> (agent)"), so confirm the text first; add_internal_note only reaches the team in Slack. assign_conversation, tag_conversation, close_conversation and reopen_conversation change it.
3107
+ - get_analytics_summary gives KPIs and the inbox right now; list/create/update/delete_routing_rule manage which Slack channel new conversations go to.
1189
3108
  - Events (notify_event) post a Slack message per event key; list_event_definitions and list_event_deliveries explain what was sent or skipped.
1190
3109
  - Logs: query_logs searches log tracking; track_log records one.
1191
- - Write tools need a server API key with the write scope; a 403 means the key is read-only.`;
3110
+ - Agents (Channlize for Agents): talk to other agents and people in agent channels. list_agents, list_agent_channels and get_org_chart show who and where; send_agent_message posts; read_agent_inbox returns what was sent to your agent, and ack_agent_messages clears what you handled. With a multi-agent key, pass agentId (or set CHANNLIZE_AGENT_ID).
3111
+ - Tasks: create_task hands work to an agent (assignee, due date); update_task moves it on the board, update_task_status reports progress or the result, handoff_task passes it to a better-placed agent; list_tasks and get_task_board show the work.
3112
+ - Humans in the loop: ask_human asks people a question or for an approval, then get_answer waits (up to 25 s per call; call it again while it says still waiting). Don't act on what you asked about until it's answered; an expired approval is not an approval. cancel_question withdraws one; answer_escalated_question answers one escalated to you as a manager agent (list_questions).
3113
+ - History and numbers: search_agent_messages finds past messages, tasks and answered questions (search before asking a person again). get_agent_cost, get_agent_metrics and get_agent_graph report spend, reply latency, backlog and who talks to whom over a range of UTC days; pass mine: true for your own agent. They return the top rows plus totals and a summary line.
3114
+ - Refusals: a POLICY_* error with a retry time means wait until then, without one the policy forbids it (don't retry). HUMAN_TAKEOVER means a person took over the thread: stay out of it until the time it gives. AGENT_THREAD_PAUSED means stop posting in that thread. get_effective_policy (agents:admin key) shows the rules.
3115
+ - Scopes: read / write for contacts, Events and logs; inbox:read, inbox:write, routing:write and analytics:read for the inbox tools; agents:send, agents:read and agents:ask_human for the agent tools. A 403 names the scope the key is missing.`;
1192
3116
  function buildServer(config, info = {}) {
1193
3117
  const api = new ChannlizeApi(resolveConfig(config));
1194
3118
  const server = new import_server2.McpServer(
@@ -1196,6 +3120,8 @@ function buildServer(config, info = {}) {
1196
3120
  { instructions: INSTRUCTIONS }
1197
3121
  );
1198
3122
  if (api.hasServerKey) {
3123
+ registerInboxTools(server, api);
3124
+ registerAgentTools(server, api);
1199
3125
  registerServerTools(server, api);
1200
3126
  registerServerPrompts(server);
1201
3127
  }
@@ -1238,18 +3164,39 @@ function createMCPServer(options) {
1238
3164
  var index_default = ChannlizeMCPServer;
1239
3165
  // Annotate the CommonJS export names for ESM import in node:
1240
3166
  0 && (module.exports = {
3167
+ AGENT_TASK_STATUSES,
3168
+ AGENT_TOOLS,
3169
+ AGENT_TOOL_NAMES,
1241
3170
  AuthenticationError,
3171
+ CONVERSATION_PRIORITIES,
3172
+ CONVERSATION_SORTS,
3173
+ CONVERSATION_STATUSES,
3174
+ ChannlizeApi,
1242
3175
  ChannlizeError,
1243
3176
  ChannlizeMCPServer,
1244
3177
  ConfigError,
3178
+ INBOX_TOOLS,
3179
+ INBOX_TOOL_NAMES,
3180
+ QUESTION_WAIT_MAX_SECONDS,
3181
+ ROUTING_FIELDS,
3182
+ ROUTING_OPERATORS,
1245
3183
  RateLimitError,
1246
3184
  ToolError,
1247
3185
  VERSION,
1248
3186
  ValidationError,
3187
+ agentToolsAsJsonSchema,
1249
3188
  buildServer,
1250
3189
  configFromEnv,
1251
3190
  createMCPServer,
3191
+ getAgentTool,
3192
+ getInboxTool,
3193
+ inboxToolsAsJsonSchema,
1252
3194
  keyKind,
1253
- resolveConfig
3195
+ registerAgentTools,
3196
+ registerInboxTools,
3197
+ resolveConfig,
3198
+ runAgentTool,
3199
+ runInboxTool,
3200
+ toToolError
1254
3201
  });
1255
3202
  //# sourceMappingURL=index.js.map