@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.mjs CHANGED
@@ -9,21 +9,110 @@ import {
9
9
  parseApiError
10
10
  } from "@channlize/core";
11
11
  var ToolError = class extends Error {
12
- constructor(message, statusCode, code) {
13
- super(message);
12
+ constructor(message2, statusCode, code, retryAt) {
13
+ super(message2);
14
14
  this.statusCode = statusCode;
15
15
  this.code = code;
16
+ this.retryAt = retryAt;
16
17
  this.name = "ToolError";
17
18
  }
18
19
  statusCode;
19
20
  code;
21
+ retryAt;
20
22
  };
21
- function hintFor(status, apiMessage) {
23
+ function scopeFor(apiMessage) {
24
+ const perm = /permission:\s*([\w:*-]+)/i.exec(apiMessage)?.[1] ?? "";
25
+ switch (perm) {
26
+ case "inbox:read":
27
+ return "inbox:read (or read)";
28
+ case "inbox:write":
29
+ return "inbox:write";
30
+ case "routing:read":
31
+ return "routing:write, inbox:read (or read)";
32
+ case "routing:write":
33
+ return "routing:write";
34
+ case "analytics:read":
35
+ return "analytics:read (or read)";
36
+ case "agents:send":
37
+ return "agents:send";
38
+ case "agents:read":
39
+ return "agents:read";
40
+ case "agents:ask_human":
41
+ return "agents:ask_human";
42
+ case "agents:admin":
43
+ return "agents:admin (an unbound key)";
44
+ default:
45
+ return /write|notify/.test(apiMessage) ? "write" : "read";
46
+ }
47
+ }
48
+ function retryText(retryAt) {
49
+ return retryAt ? ` Retry after ${retryAt}, not before.` : "";
50
+ }
51
+ function agentHint(code, body = {}) {
52
+ const retryAt = typeof body.retryAt === "string" ? body.retryAt : void 0;
53
+ switch (code) {
54
+ case "AGENT_KEY_REQUIRED":
55
+ return "Agent tools need an agent key or a multi-agent key: create one under SDK & Integration \u2192 API keys and pick the agents.";
56
+ case "AGENT_NOT_ALLOWED":
57
+ 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.";
58
+ case "NOT_A_CHANNEL_MEMBER":
59
+ return "Only channel members can post (observers only read): use list_agent_channels, or ask an admin to add the agent to the channel.";
60
+ case "AGENT_PAUSED":
61
+ case "AGENT_RETIRED":
62
+ return "Only active agents can act: ask an admin to reactivate it in the dashboard.";
63
+ case "AGENT_RATE_LIMITED":
64
+ return "The agent is sending too fast: wait a minute before sending again.";
65
+ case "AGENT_THREAD_PAUSED": {
66
+ const why = body.reason === "ping_pong" ? " (two agents were going back and forth)" : body.reason === "duplicate_content" ? " (the same message kept being posted)" : "";
67
+ return `The loop guard paused this thread${why}: stop sending in it until a person replies or resumes it. Don't rephrase and retry.`;
68
+ }
69
+ case "HUMAN_TAKEOVER":
70
+ return `A person took over this thread: don't post in it until the takeover ends or they hand it back.${retryText(retryAt)}`;
71
+ case "POLICY_RATE_LIMITED":
72
+ case "POLICY_BUDGET_EXHAUSTED":
73
+ case "POLICY_OUTSIDE_WORKING_HOURS":
74
+ return `The agent's policy refuses this for now: wait, don't retry in a loop.${retryText(retryAt)}`;
75
+ case "POLICY_CHANNEL_NOT_ALLOWED":
76
+ case "POLICY_DM_NOT_ALLOWED":
77
+ case "POLICY_ASK_HUMAN_NOT_ALLOWED":
78
+ case "POLICY_URGENCY_NOT_ALLOWED":
79
+ case "POLICY_MAX_DEPTH":
80
+ 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.";
81
+ case "TASK_CLOSED":
82
+ return "The task is closed (completed, failed, canceled or rejected) and cannot change: create a new task instead.";
83
+ case "ALREADY_ASSIGNED":
84
+ return "The task is already assigned to that agent.";
85
+ case "AGENT_NOT_IN_CHANNEL":
86
+ 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.";
87
+ case "NOT_TASK_PARTICIPANT":
88
+ return "Only the task's assignee or creator can change it or hand it off.";
89
+ case "QUESTION_CLOSED":
90
+ return "The question is already closed (answered, expired or canceled): the first answer wins. Read it with get_answer.";
91
+ case "APPROVAL_ROLE_REQUIRED":
92
+ return "This approval needs a person with the required role: an agent cannot answer it.";
93
+ case "AGENT_ADMIN_KEY_REQUIRED":
94
+ return "This needs an unbound agents:admin key (not a key bound to agents): create one under SDK & Integration \u2192 API keys.";
95
+ case "CHANNEL_NOT_VISIBLE":
96
+ return "Your key's agents can't read that channel: leave channelId out, or pick one from list_agent_channels.";
97
+ case "INVALID_ANSWER":
98
+ return "Answer with one of the question's option ids (approve / deny for approvals), or text when free text is allowed.";
99
+ default:
100
+ return void 0;
101
+ }
102
+ }
103
+ function hintFor(status, apiMessage, code, body) {
104
+ const agent = agentHint(code, body);
105
+ if (agent) return `${apiMessage}. ${agent}`;
106
+ if (status === 400 && /agent_id is required/i.test(apiMessage)) {
107
+ return `${apiMessage}. Pass agentId (from list_agents), or set CHANNLIZE_AGENT_ID / --agent-id on the MCP server.`;
108
+ }
22
109
  switch (status) {
23
110
  case 401:
24
111
  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.`;
25
112
  case 403:
26
- 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;
113
+ return /permission/i.test(apiMessage) ? `${apiMessage}. This needs a server API key with the ${scopeFor(
114
+ apiMessage
115
+ )} scope: create one under SDK & Integration \u2192 API keys.` : apiMessage;
27
116
  case 404:
28
117
  return `${apiMessage}. Check the ID (and CHANNLIZE_PROJECT_ID): it must belong to the key's organization.`;
29
118
  case 429:
@@ -36,9 +125,15 @@ function toToolError(err) {
36
125
  if (err instanceof ToolError) return err;
37
126
  if (err instanceof ChannlizeError) {
38
127
  return new ToolError(
39
- err.statusCode ? hintFor(err.statusCode, err.message.replace(/\.$/, "")) : err.message,
128
+ err.statusCode ? hintFor(
129
+ err.statusCode,
130
+ err.message.replace(/\.$/, ""),
131
+ err.code,
132
+ err.details
133
+ ) : err.message,
40
134
  err.statusCode,
41
- err.code
135
+ err.code,
136
+ err.retryAt
42
137
  );
43
138
  }
44
139
  return new ToolError(err instanceof Error ? err.message : String(err));
@@ -56,6 +151,10 @@ var ChannlizeApi = class {
56
151
  get hasWidgetKey() {
57
152
  return !!this.config.widgetKey;
58
153
  }
154
+ /** The default agent for the agent tools (`CHANNLIZE_AGENT_ID`). */
155
+ get agentId() {
156
+ return this.config.agentId;
157
+ }
59
158
  requireServerKey() {
60
159
  if (!this.config.serverApiKey) {
61
160
  throw new ToolError(
@@ -64,9 +163,10 @@ var ChannlizeApi = class {
64
163
  }
65
164
  return this.config.serverApiKey;
66
165
  }
67
- async request(method, path, options = {}) {
166
+ async request(method, path2, options = {}) {
68
167
  const key = this.requireServerKey();
69
- const url2 = new URL(`${this.config.baseUrl}${path}`);
168
+ const timeout = options.timeout ?? this.config.timeout;
169
+ const url2 = new URL(`${this.config.baseUrl}${path2}`);
70
170
  for (const [k, v] of Object.entries(options.query ?? {})) {
71
171
  if (v !== void 0 && v !== "") url2.searchParams.set(k, String(v));
72
172
  }
@@ -82,13 +182,13 @@ var ChannlizeApi = class {
82
182
  },
83
183
  // oxlint-disable-next-line unicorn/no-invalid-fetch-options -- `method` is dynamic; GET calls never pass a body.
84
184
  body: options.body !== void 0 ? JSON.stringify(options.body) : void 0,
85
- signal: AbortSignal.timeout(this.config.timeout)
185
+ signal: AbortSignal.timeout(timeout)
86
186
  });
87
187
  } catch (err) {
88
188
  const e = err;
89
189
  if (e.name === "TimeoutError" || e.name === "AbortError") {
90
190
  throw new ToolError(
91
- `Channlize API timed out after ${this.config.timeout} ms (${method} ${url2.pathname}). Retry, or raise CHANNLIZE_TIMEOUT.`,
191
+ `Channlize API timed out after ${timeout} ms (${method} ${url2.pathname}). Retry, or raise CHANNLIZE_TIMEOUT.`,
92
192
  408,
93
193
  "TIMEOUT"
94
194
  );
@@ -98,28 +198,34 @@ var ChannlizeApi = class {
98
198
  );
99
199
  }
100
200
  const text = await res.text();
101
- let data = void 0;
201
+ let data2 = void 0;
102
202
  if (text) {
103
203
  try {
104
- data = JSON.parse(text);
204
+ data2 = JSON.parse(text);
105
205
  } catch {
106
- data = void 0;
206
+ data2 = void 0;
107
207
  }
108
208
  }
109
209
  if (!res.ok) {
110
- const { message, code } = parseApiError(res.status, data, res.statusText);
210
+ const { message: message2, code, body } = parseApiError(
211
+ res.status,
212
+ data2,
213
+ res.statusText
214
+ );
215
+ const retryAt = typeof body.retryAt === "string" ? body.retryAt : void 0;
111
216
  throw new ToolError(
112
- hintFor(res.status, message.replace(/\.$/, "")),
217
+ hintFor(res.status, message2.replace(/\.$/, ""), code, body),
113
218
  res.status,
114
- code
219
+ code,
220
+ retryAt
115
221
  );
116
222
  }
117
- if (data === void 0) {
223
+ if (data2 === void 0) {
118
224
  throw new ToolError(
119
225
  `Unexpected non-JSON response from ${method} ${url2.pathname}`
120
226
  );
121
227
  }
122
- return data;
228
+ return data2;
123
229
  }
124
230
  /**
125
231
  * `CHANNLIZE_PROJECT_ID`, or the first project of the key's organization
@@ -180,11 +286,12 @@ import {
180
286
  readChannlizeEnv
181
287
  } from "@channlize/core";
182
288
  var ConfigError = class extends Error {
183
- constructor(message) {
184
- super(message);
289
+ constructor(message2) {
290
+ super(message2);
185
291
  this.name = "ConfigError";
186
292
  }
187
293
  };
294
+ var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
188
295
  function clean(value) {
189
296
  const v = value?.trim();
190
297
  return v ? v : void 0;
@@ -229,17 +336,33 @@ function resolveConfig(config) {
229
336
  `Invalid base URL "${config.baseUrl}": use e.g. ${DEFAULT_BASE_URL}`
230
337
  );
231
338
  }
339
+ const agentId2 = clean(config.agentId);
340
+ if (agentId2 && !UUID.test(agentId2)) {
341
+ throw new ConfigError(
342
+ `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.`
343
+ );
344
+ }
232
345
  return {
233
346
  serverApiKey,
234
347
  widgetKey,
235
348
  projectId: clean(config.projectId),
349
+ agentId: agentId2,
236
350
  baseUrl,
237
351
  timeout
238
352
  };
239
353
  }
240
354
  function configFromEnv(env = process.env) {
241
- const { timeout, ...rest } = readChannlizeEnv(env);
242
- return { ...rest, timeout: timeout ? Number(timeout) : void 0 };
355
+ const { timeout, serverApiKey, widgetKey, apiKey, projectId, baseUrl } = readChannlizeEnv(env);
356
+ return {
357
+ serverApiKey,
358
+ widgetKey,
359
+ apiKey,
360
+ projectId,
361
+ baseUrl,
362
+ timeout: timeout ? Number(timeout) : void 0,
363
+ // Read here rather than from core, so older @channlize/core versions work.
364
+ agentId: clean(env.CHANNLIZE_AGENT_ID)
365
+ };
243
366
  }
244
367
 
245
368
  // src/prompts.ts
@@ -419,12 +542,12 @@ function registerServerPrompts(server) {
419
542
  },
420
543
  ({ status, limit }) => user(`Triage my Channlize support inbox.
421
544
 
422
- 1. Call list_conversations with status "${status || "open"}" and limit ${Number(limit) || 10}.
545
+ 1. Call list_conversations with status ["${status || "open"}"] and limit ${Number(limit) || 10}.
423
546
  2. For each conversation, call get_conversation to read the thread.
424
547
  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.
425
548
  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.
426
549
 
427
- 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.`)
550
+ 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.`)
428
551
  );
429
552
  server.registerPrompt(
430
553
  "summarize-conversation",
@@ -435,8 +558,8 @@ Replies and status or priority changes are made by the team in the Slack thread
435
558
  conversationId: z.string().describe("Conversation ID")
436
559
  })
437
560
  },
438
- ({ conversationId }) => user(
439
- `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.`
561
+ ({ conversationId: conversationId2 }) => user(
562
+ `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.`
440
563
  )
441
564
  );
442
565
  server.registerPrompt(
@@ -567,14 +690,1832 @@ function registerResources(server, api) {
567
690
  }
568
691
 
569
692
  // src/tools.ts
570
- import * as z2 from "zod/v4";
693
+ import * as z4 from "zod/v4";
571
694
  import { EVENT_KEY_PATTERN, EVENT_SEVERITIES } from "@channlize/core";
572
- var STATUSES = ["open", "pending", "resolved", "closed"];
573
- var PRIORITIES = ["low", "normal", "high", "urgent"];
574
- function ok(data) {
695
+
696
+ // src/agents.ts
697
+ import * as z2 from "zod/v4";
698
+
699
+ // src/agents-summary.ts
700
+ var num = (v) => typeof v === "number" ? v : Number(v) || 0;
701
+ var arr = (v) => Array.isArray(v) ? v : [];
702
+ var obj = (v) => v && typeof v === "object" ? v : {};
703
+ var str = (v) => typeof v === "string" ? v : null;
704
+ function money(v) {
705
+ return Math.round(num(v) * 1e4) / 1e4;
706
+ }
707
+ function fmtMoney(v) {
708
+ return money(v).toFixed(4).replace(/\.?0+$/, "") || "0";
709
+ }
710
+ function pct(v) {
711
+ return v === null || v === void 0 ? "n/a" : `${Math.round(num(v) * 1e3) / 10}%`;
712
+ }
713
+ function fmtMs(v) {
714
+ if (v === null || v === void 0) return "n/a";
715
+ const ms = num(v);
716
+ if (ms < 1e3) return `${Math.round(ms)}ms`;
717
+ if (ms < 6e4) return `${Math.round(ms / 100) / 10}s`;
718
+ if (ms < 36e5) return `${Math.round(ms / 6e3) / 10}m`;
719
+ return `${Math.round(ms / 36e4) / 10}h`;
720
+ }
721
+ function highlightText(html) {
722
+ 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, "&");
723
+ }
724
+ function clip(text, max) {
725
+ const s = typeof text === "string" ? text : "";
726
+ return s.length > max ? `${s.slice(0, max - 1)}\u2026` : s;
727
+ }
728
+ function rangeSummary(range2) {
729
+ const r = obj(range2);
730
+ return {
731
+ from: String(r.from ?? ""),
732
+ to: String(r.to ?? ""),
733
+ days: num(r.days),
734
+ historyStart: str(r.history_start),
735
+ retentionDays: r.retention_days === void 0 ? null : num(r.retention_days),
736
+ clamped: Boolean(r.clamped),
737
+ empty: Boolean(r.empty)
738
+ };
739
+ }
740
+ function rangeNote(r) {
741
+ const base = `${r.from}..${r.to} (${r.days} day${r.days === 1 ? "" : "s"}, UTC)`;
742
+ return r.clamped ? `${base}; clamped to the plan's history start ${r.historyStart}` : base;
743
+ }
744
+ function latency(v) {
745
+ const l = obj(v);
746
+ return {
747
+ count: num(l.count),
748
+ avgMs: l.avg_ms === null || l.avg_ms === void 0 ? null : num(l.avg_ms),
749
+ p50Ms: l.p50_ms === null || l.p50_ms === void 0 ? null : num(l.p50_ms),
750
+ p90Ms: l.p90_ms === null || l.p90_ms === void 0 ? null : num(l.p90_ms)
751
+ };
752
+ }
753
+ function summarizeSearch(r) {
754
+ const results = arr(r.results).map((x) => {
755
+ const channel = x.channel ? obj(x.channel) : null;
756
+ const base = {
757
+ kind: String(x.kind),
758
+ highlight: clip(highlightText(String(x.highlight ?? "")), 400),
759
+ rank: Math.round(num(x.rank) * 1e3) / 1e3,
760
+ channel: channel ? str(channel.slug) ?? str(channel.id) : null,
761
+ channelId: channel ? str(channel.id) : null,
762
+ threadId: str(x.thread_id),
763
+ slackPermalink: str(x.slack_permalink)
764
+ };
765
+ if (x.kind === "question") {
766
+ const q = obj(x.question);
767
+ const answer = q.answer ? obj(q.answer) : null;
768
+ return {
769
+ ...base,
770
+ id: String(q.id ?? ""),
771
+ type: "question",
772
+ text: clip(q.question, 500),
773
+ status: str(q.status),
774
+ answer: answer ? clip(
775
+ [answer.option_label ?? answer.option_id, answer.text].filter(Boolean).join(" / "),
776
+ 200
777
+ ) || null : null,
778
+ sender: str(q.agent_id) ? `agent:${String(q.agent_id)}` : null,
779
+ createdAt: str(q.created_at)
780
+ };
781
+ }
782
+ const m = obj(x.message);
783
+ const sender = obj(m.sender);
784
+ const senderId = sender.agent_id ?? sender.user_id ?? sender.slack_user_id;
785
+ return {
786
+ ...base,
787
+ id: String(m.id ?? ""),
788
+ type: String(m.type ?? "message"),
789
+ text: clip(m.text, 500),
790
+ status: str(m.task_status),
791
+ answer: null,
792
+ sender: sender.kind ? `${String(sender.kind)}${senderId ? `:${String(senderId)}` : ""}` : null,
793
+ createdAt: str(m.created_at)
794
+ };
795
+ });
796
+ const window = obj(r.window);
797
+ return {
798
+ results,
799
+ nextCursor: str(r.next_cursor),
800
+ window: { from: String(window.from ?? ""), days: num(window.days) }
801
+ };
802
+ }
803
+ function summarizeGraph(r, top2) {
804
+ const range2 = rangeSummary(r.range);
805
+ const nodes = arr(r.nodes);
806
+ const labels = new Map(nodes.map((n) => [String(n.id), String(n.label)]));
807
+ const topNodes = [...nodes].sort(
808
+ (a, b) => num(b.sent) + num(b.received) - (num(a.sent) + num(a.received))
809
+ ).slice(0, top2).map((n) => ({
810
+ id: String(n.id),
811
+ kind: String(n.kind),
812
+ label: String(n.label),
813
+ slug: str(n.slug),
814
+ sent: num(n.sent),
815
+ received: num(n.received),
816
+ tokens: num(n.tokens),
817
+ cost: money(n.cost)
818
+ }));
819
+ const edges = arr(r.edges);
820
+ const topEdges = [...edges].sort((a, b) => num(b.messages) - num(a.messages)).slice(0, top2).map((e) => {
821
+ const l = latency(e.reply_latency);
822
+ return {
823
+ source: String(e.source),
824
+ target: String(e.target),
825
+ from: labels.get(String(e.source)) ?? String(e.source),
826
+ to: labels.get(String(e.target)) ?? String(e.target),
827
+ messages: num(e.messages),
828
+ replies: num(e.replies),
829
+ cost: money(e.cost),
830
+ replyAvgMs: l.avgMs,
831
+ replyP90Ms: l.p90Ms,
832
+ lastAt: str(e.last_at)
833
+ };
834
+ });
835
+ const totals = obj(r.totals);
836
+ const truncated = obj(r.truncated);
837
+ const t = {
838
+ nodes: num(totals.nodes),
839
+ edges: num(totals.edges),
840
+ messages: num(totals.messages),
841
+ tokens: num(totals.tokens),
842
+ cost: money(totals.cost)
843
+ };
844
+ const busiest = topEdges[0];
845
+ return {
846
+ range: range2,
847
+ totals: t,
848
+ topNodes,
849
+ topEdges,
850
+ /** Not shown here: beyond `top`, or folded / dropped by the API's cap. */
851
+ omitted: {
852
+ nodes: Math.max(0, nodes.length - topNodes.length),
853
+ edges: Math.max(0, edges.length - topEdges.length),
854
+ cappedNodes: num(truncated.nodes),
855
+ cappedEdges: num(truncated.edges)
856
+ },
857
+ 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)}).` : "")
858
+ };
859
+ }
860
+ function summarizeCost(r, top2) {
861
+ const range2 = rangeSummary(r.range);
862
+ const totals = obj(r.totals);
863
+ const t = {
864
+ messages: num(totals.messages),
865
+ pricedMessages: num(totals.priced_messages),
866
+ tokens: num(totals.tokens),
867
+ cost: money(totals.cost)
868
+ };
869
+ const all = arr(r.groups);
870
+ const groups = all.slice(0, top2).map((g) => ({
871
+ key: String(g.key),
872
+ label: clip(g.label, 120),
873
+ messages: num(g.messages),
874
+ tokens: num(g.tokens),
875
+ cost: money(g.cost),
876
+ share: g.share === null || g.share === void 0 ? null : num(g.share)
877
+ }));
878
+ const active = arr(r.series).filter(
879
+ (d) => num(d.messages) > 0 || num(d.cost) > 0
880
+ );
881
+ const daily = active.slice(-31).map((d) => ({
882
+ day: String(d.day),
883
+ messages: num(d.messages),
884
+ tokens: num(d.tokens),
885
+ cost: money(d.cost)
886
+ }));
887
+ const peak = active.reduce(
888
+ (best, d) => !best || num(d.cost) > num(best.cost) ? d : best,
889
+ null
890
+ );
891
+ const groupBy = String(r.group_by ?? "agent");
892
+ const head = groups.slice(0, 3).map((g) => `${g.label} ${fmtMoney(g.cost)} (${pct(g.share)})`).join(", ");
893
+ return {
894
+ range: range2,
895
+ groupBy,
896
+ totals: t,
897
+ groups,
898
+ omittedGroups: Math.max(0, all.length - groups.length),
899
+ /** The API had more groups than it returned. */
900
+ truncated: Boolean(r.truncated),
901
+ daily,
902
+ peakDay: peak ? { day: String(peak.day), cost: money(peak.cost) } : null,
903
+ 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}.` : "")
904
+ };
905
+ }
906
+ function pair(v) {
907
+ const p = obj(v);
908
+ const l = latency(p.latency);
909
+ return {
910
+ messages: num(p.messages),
911
+ replied: num(p.replied),
912
+ replyRate: p.reply_rate === null || p.reply_rate === void 0 ? null : num(p.reply_rate),
913
+ avgMs: l.avgMs,
914
+ p50Ms: l.p50Ms,
915
+ p90Ms: l.p90Ms
916
+ };
917
+ }
918
+ function summarizeMetrics(r, top2) {
919
+ const range2 = rangeSummary(r.range);
920
+ const replies = obj(r.replies);
921
+ const q = obj(r.questions);
922
+ const qLatency = latency(q.time_to_human_answer);
923
+ const byUrgency = obj(q.by_urgency);
924
+ const d = obj(r.deliveries);
925
+ const byMode = obj(d.by_mode);
926
+ const backlog = obj(r.backlog);
927
+ const rate = (v) => v === null || v === void 0 ? null : num(v);
928
+ const out = {
929
+ range: range2,
930
+ replies: {
931
+ agentToAgent: pair(replies.agent_to_agent),
932
+ humanToAgent: pair(replies.human_to_agent),
933
+ agentToHuman: pair(replies.agent_to_human),
934
+ byAgent: arr(replies.by_agent).slice(0, top2).map((a) => {
935
+ const l = latency(a.latency);
936
+ return {
937
+ agentId: String(a.agent_id),
938
+ name: str(a.name),
939
+ messages: num(a.messages),
940
+ replied: num(a.replied),
941
+ avgMs: l.avgMs,
942
+ p90Ms: l.p90Ms
943
+ };
944
+ })
945
+ },
946
+ questions: {
947
+ asked: num(q.asked),
948
+ answered: num(q.answered),
949
+ answeredByUser: num(q.answered_by_user),
950
+ answeredByAgent: num(q.answered_by_agent),
951
+ expired: num(q.expired),
952
+ expiredDefault: num(q.expired_default),
953
+ canceled: num(q.canceled),
954
+ answerRate: rate(q.answer_rate),
955
+ timeToHumanAnswer: {
956
+ count: qLatency.count,
957
+ avgMs: qLatency.avgMs,
958
+ p50Ms: qLatency.p50Ms,
959
+ p90Ms: qLatency.p90Ms
960
+ },
961
+ byUrgency: Object.fromEntries(
962
+ ["low", "normal", "high", "urgent"].map((u) => {
963
+ const b = obj(byUrgency[u]);
964
+ return [
965
+ u,
966
+ {
967
+ asked: num(b.asked),
968
+ answerRate: rate(b.answer_rate),
969
+ p50Ms: latency(b.time_to_human_answer).p50Ms
970
+ }
971
+ ];
972
+ })
973
+ )
974
+ },
975
+ deliveries: {
976
+ deliveries: num(d.deliveries),
977
+ failed: num(d.failed),
978
+ retried: num(d.retried),
979
+ failureRate: rate(d.failure_rate),
980
+ retryRate: rate(d.retry_rate),
981
+ byMode: Object.fromEntries(
982
+ ["webhook", "inbox", "a2a"].map((m) => {
983
+ const b = obj(byMode[m]);
984
+ return [
985
+ m,
986
+ {
987
+ deliveries: num(b.deliveries),
988
+ failed: num(b.failed),
989
+ held: num(b.held),
990
+ failureRate: rate(b.failure_rate),
991
+ retryRate: rate(b.retry_rate)
992
+ }
993
+ ];
994
+ })
995
+ )
996
+ },
997
+ backlog: {
998
+ asOf: String(backlog.as_of ?? ""),
999
+ unacked: num(backlog.unacked),
1000
+ held: num(backlog.held),
1001
+ agentsWithBacklog: num(backlog.agents_with_backlog),
1002
+ agents: arr(backlog.agents).slice(0, top2).map((a) => ({
1003
+ agentId: String(a.agent_id),
1004
+ name: str(a.name),
1005
+ delivery: str(a.delivery),
1006
+ unacked: num(a.unacked),
1007
+ held: num(a.held),
1008
+ oldestAgeSeconds: a.oldest_age_seconds === null || a.oldest_age_seconds === void 0 ? null : num(a.oldest_age_seconds)
1009
+ }))
1010
+ },
1011
+ summary: ""
1012
+ };
1013
+ const h2a = out.replies.humanToAgent;
1014
+ const a2a = out.replies.agentToAgent;
1015
+ 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.`;
1016
+ return out;
1017
+ }
1018
+
1019
+ // src/agents.ts
1020
+ function defineTool(tool) {
1021
+ return tool;
1022
+ }
1023
+ var AGENT_TASK_STATUSES = [
1024
+ "open",
1025
+ "working",
1026
+ "input_required",
1027
+ "completed",
1028
+ "failed",
1029
+ "canceled",
1030
+ "rejected"
1031
+ ];
1032
+ var uuid = (what) => z2.string().uuid().describe(what);
1033
+ var agentId = uuid(
1034
+ "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."
1035
+ ).optional();
1036
+ var channelId = uuid("Agent channel ID (from list_agent_channels)");
1037
+ var threadId = uuid(
1038
+ "Reply in this thread: the id of any message in it (thread_id or id from read_agent_inbox)"
1039
+ ).optional();
1040
+ var mentions = z2.array(z2.string().uuid()).max(50).optional().describe("Agent IDs to mention (from list_agents)");
1041
+ var data = z2.record(z2.string(), z2.unknown()).optional().describe("Structured data for the recipients (JSON object)");
1042
+ var usage = {
1043
+ tokens: z2.number().int().min(0).optional().describe("Tokens you used for this message (reporting)"),
1044
+ cost: z2.number().min(0).optional().describe("What this message cost you, in USD (reporting)")
1045
+ };
1046
+ var message = z2.looseObject({
1047
+ id: z2.string(),
1048
+ channel_id: z2.string(),
1049
+ thread_id: z2.string().nullable(),
1050
+ type: z2.string(),
1051
+ text: z2.string(),
1052
+ sender: z2.looseObject({ kind: z2.string() }),
1053
+ task_status: z2.string().nullable().optional()
1054
+ });
1055
+ var sendOutput = z2.object({
1056
+ message,
1057
+ deliveries: z2.array(
1058
+ z2.looseObject({ id: z2.string(), agent_id: z2.string(), status: z2.string() })
1059
+ )
1060
+ });
1061
+ var dueAt = z2.string().max(40).optional().describe("Due date: an ISO date (2026-11-30) or date-time");
1062
+ var task = z2.looseObject({
1063
+ id: z2.string(),
1064
+ channel_id: z2.string(),
1065
+ text: z2.string(),
1066
+ board_status: z2.string(),
1067
+ assignee_agent_id: z2.string().nullable(),
1068
+ due_at: z2.string().nullable()
1069
+ });
1070
+ var deliveries = z2.array(
1071
+ z2.looseObject({ id: z2.string(), agent_id: z2.string(), status: z2.string() })
1072
+ );
1073
+ var question = z2.looseObject({
1074
+ id: z2.string(),
1075
+ kind: z2.string(),
1076
+ question: z2.string(),
1077
+ status: z2.string(),
1078
+ answer: z2.looseObject({}).nullable()
1079
+ });
1080
+ var questionId = uuid("The question ID (from ask_human or list_questions)");
1081
+ var BOARD_STATUSES = [
1082
+ "open",
1083
+ "in_progress",
1084
+ "blocked",
1085
+ "done",
1086
+ "failed"
1087
+ ];
1088
+ var QUESTION_WAIT_MAX_SECONDS = 25;
1089
+ var READ = {
1090
+ readOnlyHint: true,
1091
+ destructiveHint: false,
1092
+ idempotentHint: true,
1093
+ openWorldHint: false
1094
+ };
1095
+ var SEND = {
1096
+ readOnlyHint: false,
1097
+ destructiveHint: false,
1098
+ idempotentHint: false,
1099
+ openWorldHint: true
1100
+ };
1101
+ function actingAs(api, id2) {
1102
+ return id2 ?? api.agentId;
1103
+ }
1104
+ function requireAgent(api, id2) {
1105
+ const agent = actingAs(api, id2);
1106
+ if (!agent) {
1107
+ throw new ToolError(
1108
+ "Pass agentId (from list_agents), or set CHANNLIZE_AGENT_ID / --agent-id on the MCP server."
1109
+ );
1110
+ }
1111
+ return agent;
1112
+ }
1113
+ async function send(api, body) {
1114
+ const r = await api.request(
1115
+ "POST",
1116
+ "/v1/agents/messages",
1117
+ { body }
1118
+ );
1119
+ return { message: r.message, deliveries: r.deliveries ?? [] };
1120
+ }
1121
+ var enc = encodeURIComponent;
1122
+ function outcomeMessage(status, q) {
1123
+ const answer = q.answer ?? {};
1124
+ const choice = answer.option_label ?? answer.option_id;
1125
+ const comment = answer.comment ? `: ${String(answer.comment)}` : "";
1126
+ switch (status) {
1127
+ case "answered":
1128
+ if (q.kind === "approval") {
1129
+ return answer.approved ? `Approved${comment}. Go ahead.` : `Denied${comment}. Don't do it.`;
1130
+ }
1131
+ return `Answered: ${[choice, answer.text].filter(Boolean).join(" / ") || "(empty)"}.`;
1132
+ case "expired_default":
1133
+ return `Nobody answered by the deadline: the default option applies (${String(choice ?? "none")}).`;
1134
+ case "expired":
1135
+ 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.";
1136
+ case "canceled":
1137
+ return "The question was canceled.";
1138
+ default:
1139
+ return `Status: ${status}.`;
1140
+ }
1141
+ }
1142
+ var AGENT_MESSAGE_TYPES = [
1143
+ "message",
1144
+ "task",
1145
+ "question",
1146
+ "escalation",
1147
+ "status"
1148
+ ];
1149
+ var insightsDay = (what) => z2.string().regex(/^\d{4}-\d{2}-\d{2}$/, "expected a YYYY-MM-DD date").optional().describe(what);
1150
+ var insightsRange = {
1151
+ from: insightsDay(
1152
+ "First UTC day, YYYY-MM-DD (default: 30 days before to). Clamped to the plan history window."
1153
+ ),
1154
+ to: insightsDay("Last UTC day, inclusive, YYYY-MM-DD (default: today)"),
1155
+ channelId: channelId.optional().describe("Only this agent channel")
1156
+ };
1157
+ var insightsAgent = uuid(
1158
+ "Only this agent (from list_agents): pass your own id to see your own numbers"
1159
+ ).optional();
1160
+ var mine = z2.boolean().optional().describe(
1161
+ "true: only your own agent (the server's default agent, CHANNLIZE_AGENT_ID), when you don't know your id"
1162
+ );
1163
+ 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})`);
1164
+ function filterAgent(api, a) {
1165
+ if (a.agentId) return a.agentId;
1166
+ return a.mine ? requireAgent(api, void 0) : void 0;
1167
+ }
1168
+ var range = z2.looseObject({
1169
+ from: z2.string(),
1170
+ to: z2.string(),
1171
+ days: z2.number(),
1172
+ clamped: z2.boolean(),
1173
+ empty: z2.boolean()
1174
+ });
1175
+ var nullableNumber = z2.number().nullable();
1176
+ var AGENT_TOOLS = [
1177
+ defineTool({
1178
+ name: "send_agent_message",
1179
+ title: "Send agent message",
1180
+ 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.",
1181
+ scope: "agents:send",
1182
+ endpoint: "POST /v1/agents/messages",
1183
+ inputSchema: z2.object({
1184
+ agentId,
1185
+ channelId,
1186
+ text: z2.string().min(1).max(4e4).describe("Message text"),
1187
+ threadId,
1188
+ mentions,
1189
+ data,
1190
+ ...usage
1191
+ }),
1192
+ outputSchema: sendOutput,
1193
+ annotations: SEND,
1194
+ handler: (api, a) => send(api, {
1195
+ agent_id: actingAs(api, a.agentId),
1196
+ channel_id: a.channelId,
1197
+ type: "message",
1198
+ text: a.text,
1199
+ thread_id: a.threadId,
1200
+ mentions: a.mentions,
1201
+ data: a.data,
1202
+ tokens: a.tokens,
1203
+ cost: a.cost
1204
+ })
1205
+ }),
1206
+ defineTool({
1207
+ name: "create_task",
1208
+ title: "Create task",
1209
+ 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.",
1210
+ scope: "agents:send",
1211
+ endpoint: "POST /v1/agents/tasks",
1212
+ inputSchema: z2.object({
1213
+ agentId,
1214
+ channelId,
1215
+ text: z2.string().min(1).max(4e4).describe("What should be done, with enough context to do it"),
1216
+ assigneeAgentId: uuid(
1217
+ "The agent that should do it: a member of the channel (from list_agents)"
1218
+ ).optional(),
1219
+ dueAt,
1220
+ threadId,
1221
+ mentions,
1222
+ data
1223
+ }),
1224
+ // `message` is the task too (a task is its `task` message plus board fields).
1225
+ outputSchema: z2.object({ taskId: z2.string(), task, message, deliveries }),
1226
+ annotations: SEND,
1227
+ handler: async (api, a) => {
1228
+ const r = await api.request(
1229
+ "POST",
1230
+ "/v1/agents/tasks",
1231
+ {
1232
+ body: {
1233
+ agent_id: actingAs(api, a.agentId),
1234
+ channel_id: a.channelId,
1235
+ text: a.text,
1236
+ assignee_agent_id: a.assigneeAgentId,
1237
+ due_at: a.dueAt,
1238
+ thread_id: a.threadId,
1239
+ mentions: a.mentions,
1240
+ data: a.data
1241
+ }
1242
+ }
1243
+ );
1244
+ return {
1245
+ taskId: String(r.task.id),
1246
+ task: r.task,
1247
+ message: r.task,
1248
+ deliveries: r.deliveries ?? []
1249
+ };
1250
+ }
1251
+ }),
1252
+ defineTool({
1253
+ name: "update_task_status",
1254
+ title: "Update task status",
1255
+ 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.",
1256
+ scope: "agents:send",
1257
+ endpoint: "POST /v1/agents/messages",
1258
+ inputSchema: z2.object({
1259
+ agentId,
1260
+ channelId,
1261
+ taskId: uuid("The task message ID"),
1262
+ status: z2.enum(AGENT_TASK_STATUSES).describe("The new status of the task"),
1263
+ text: z2.string().max(4e4).optional().describe("What changed, e.g. the result or what input is needed"),
1264
+ data,
1265
+ ...usage
1266
+ }),
1267
+ outputSchema: sendOutput,
1268
+ annotations: SEND,
1269
+ handler: (api, a) => send(api, {
1270
+ agent_id: actingAs(api, a.agentId),
1271
+ channel_id: a.channelId,
1272
+ type: "status",
1273
+ text: a.text ?? "",
1274
+ task_id: a.taskId,
1275
+ task_status: a.status,
1276
+ data: a.data,
1277
+ tokens: a.tokens,
1278
+ cost: a.cost
1279
+ })
1280
+ }),
1281
+ defineTool({
1282
+ name: "update_task",
1283
+ title: "Update task",
1284
+ 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.",
1285
+ scope: "agents:send",
1286
+ endpoint: "PATCH /v1/agents/tasks/:taskId",
1287
+ inputSchema: z2.object({
1288
+ agentId,
1289
+ taskId: uuid("The task ID"),
1290
+ status: z2.enum(BOARD_STATUSES).optional().describe("The board column"),
1291
+ dueAt: z2.string().max(40).nullable().optional().describe("New due date (ISO date or date-time); null clears it"),
1292
+ note: z2.string().max(2e3).optional().describe("What changed, shown with the update")
1293
+ }),
1294
+ outputSchema: z2.object({ task, changed: z2.boolean() }),
1295
+ annotations: SEND,
1296
+ handler: async (api, a) => {
1297
+ if (a.status === void 0 && a.dueAt === void 0) {
1298
+ throw new ToolError("Pass status or dueAt.");
1299
+ }
1300
+ const r = await api.request(
1301
+ "PATCH",
1302
+ `/v1/agents/tasks/${enc(a.taskId)}`,
1303
+ {
1304
+ body: {
1305
+ agent_id: actingAs(api, a.agentId),
1306
+ status: a.status,
1307
+ due_at: a.dueAt,
1308
+ note: a.note
1309
+ }
1310
+ }
1311
+ );
1312
+ return { task: r.task, changed: Boolean(r.changed) };
1313
+ }
1314
+ }),
1315
+ defineTool({
1316
+ name: "handoff_task",
1317
+ title: "Hand off task",
1318
+ 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.",
1319
+ scope: "agents:send",
1320
+ endpoint: "POST /v1/agents/tasks/:taskId/handoff",
1321
+ inputSchema: z2.object({
1322
+ agentId,
1323
+ taskId: uuid("The task ID"),
1324
+ toAgentId: uuid("The new assignee (from list_agents or get_org_chart)"),
1325
+ reason: z2.string().max(2e3).optional().describe("Why, and what the new assignee needs to know")
1326
+ }),
1327
+ outputSchema: z2.object({ task, deliveries }),
1328
+ annotations: SEND,
1329
+ handler: async (api, a) => {
1330
+ const r = await api.request(
1331
+ "POST",
1332
+ `/v1/agents/tasks/${enc(a.taskId)}/handoff`,
1333
+ {
1334
+ body: {
1335
+ agent_id: actingAs(api, a.agentId),
1336
+ to_agent_id: a.toAgentId,
1337
+ reason: a.reason
1338
+ }
1339
+ }
1340
+ );
1341
+ return {
1342
+ task: r.task,
1343
+ deliveries: r.deliveries ?? []
1344
+ };
1345
+ }
1346
+ }),
1347
+ defineTool({
1348
+ name: "list_tasks",
1349
+ title: "List tasks",
1350
+ 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.",
1351
+ scope: "agents:read",
1352
+ endpoint: "GET /v1/agents/tasks",
1353
+ inputSchema: z2.object({
1354
+ agentId,
1355
+ channelId: channelId.optional(),
1356
+ assigneeAgentId: uuid("Only tasks assigned to this agent").optional(),
1357
+ status: z2.enum(BOARD_STATUSES).optional(),
1358
+ limit: z2.number().int().min(1).max(500).default(50).describe("How many to return (1-500, default 50)")
1359
+ }),
1360
+ outputSchema: z2.object({ tasks: z2.array(task) }),
1361
+ annotations: READ,
1362
+ handler: async (api, a) => {
1363
+ const r = await api.request(
1364
+ "GET",
1365
+ "/v1/agents/tasks",
1366
+ {
1367
+ query: {
1368
+ agent_id: actingAs(api, a.agentId),
1369
+ channel_id: a.channelId,
1370
+ assignee_agent_id: a.assigneeAgentId,
1371
+ status: a.status,
1372
+ limit: a.limit
1373
+ }
1374
+ }
1375
+ );
1376
+ return { tasks: r.tasks ?? [] };
1377
+ }
1378
+ }),
1379
+ defineTool({
1380
+ name: "get_task_board",
1381
+ title: "Get task board",
1382
+ 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.",
1383
+ scope: "agents:read",
1384
+ endpoint: "GET /v1/agents/tasks/board",
1385
+ inputSchema: z2.object({
1386
+ agentId,
1387
+ channelId,
1388
+ assigneeAgentId: uuid("Only tasks assigned to this agent").optional()
1389
+ }),
1390
+ outputSchema: z2.object({
1391
+ channel_id: z2.string(),
1392
+ columns: z2.record(z2.string(), z2.array(task)),
1393
+ counts: z2.record(z2.string(), z2.number()),
1394
+ agents: z2.array(z2.looseObject({ id: z2.string() })),
1395
+ truncated: z2.boolean()
1396
+ }),
1397
+ annotations: READ,
1398
+ handler: async (api, a) => await api.request("GET", "/v1/agents/tasks/board", {
1399
+ query: {
1400
+ agent_id: actingAs(api, a.agentId),
1401
+ channel_id: a.channelId,
1402
+ assignee_agent_id: a.assigneeAgentId
1403
+ }
1404
+ })
1405
+ }),
1406
+ defineTool({
1407
+ name: "ask_human",
1408
+ title: "Ask a human",
1409
+ 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.",
1410
+ scope: "agents:ask_human",
1411
+ endpoint: "POST /v1/agents/questions",
1412
+ inputSchema: z2.object({
1413
+ agentId,
1414
+ kind: z2.enum(["question", "approval"]).default("question").describe("question (default) or approval (answered Approve / Deny)"),
1415
+ question: z2.string().min(1).max(3e3).describe("The question, with what people need to answer it"),
1416
+ options: z2.array(
1417
+ z2.object({
1418
+ id: z2.string().min(1).max(100),
1419
+ label: z2.string().min(1).max(75)
1420
+ })
1421
+ ).max(10).optional().describe("Up to 10 answers to pick from (ignored for approvals)"),
1422
+ freeText: z2.boolean().optional().describe("Allow a typed answer (always on without options)"),
1423
+ urgency: z2.enum(["low", "normal", "high", "urgent"]).optional().describe("How fast it escalates (default normal)"),
1424
+ deadline: z2.string().max(40).optional().describe("ISO date-time, at most 30 days away"),
1425
+ defaultOption: z2.string().max(100).optional().describe("Option id applied at the deadline when nobody answered"),
1426
+ channelId: channelId.optional().describe("Post it in this agent channel (from list_agent_channels)"),
1427
+ threadId,
1428
+ context: z2.record(z2.string(), z2.unknown()).optional().describe("Facts shown with the question (JSON object)"),
1429
+ amount: z2.number().min(0).optional().describe("Approvals: the amount at stake"),
1430
+ currency: z2.string().regex(/^[A-Za-z]{3}$/).optional().describe("Approvals: ISO 4217 currency code"),
1431
+ resource: z2.record(z2.string(), z2.unknown()).optional().describe("Approvals: what is being approved (JSON object)"),
1432
+ requiredRoles: z2.array(z2.string().min(1).max(40)).max(10).optional().describe('Approvals: roles that may answer, e.g. ["admin"]')
1433
+ }),
1434
+ outputSchema: z2.object({ questionId: z2.string(), question }),
1435
+ annotations: SEND,
1436
+ handler: async (api, a) => {
1437
+ const r = await api.request(
1438
+ "POST",
1439
+ "/v1/agents/questions",
1440
+ {
1441
+ body: {
1442
+ agent_id: actingAs(api, a.agentId),
1443
+ kind: a.kind,
1444
+ question: a.question,
1445
+ options: a.options,
1446
+ free_text: a.freeText,
1447
+ urgency: a.urgency,
1448
+ deadline: a.deadline,
1449
+ default_option: a.defaultOption,
1450
+ channel_id: a.channelId,
1451
+ thread_id: a.threadId,
1452
+ context: a.context,
1453
+ amount: a.amount,
1454
+ currency: a.currency,
1455
+ resource: a.resource,
1456
+ required_roles: a.requiredRoles
1457
+ }
1458
+ }
1459
+ );
1460
+ return {
1461
+ questionId: String(r.question.id),
1462
+ question: r.question
1463
+ };
1464
+ }
1465
+ }),
1466
+ defineTool({
1467
+ name: "get_answer",
1468
+ title: "Get answer",
1469
+ 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).`,
1470
+ scope: "agents:ask_human",
1471
+ endpoint: "GET /v1/agents/questions/:id/wait",
1472
+ inputSchema: z2.object({
1473
+ agentId,
1474
+ questionId,
1475
+ waitSeconds: z2.number().int().min(0).max(QUESTION_WAIT_MAX_SECONDS).default(QUESTION_WAIT_MAX_SECONDS).describe(
1476
+ `Seconds to wait for an answer (0-${QUESTION_WAIT_MAX_SECONDS}, default ${QUESTION_WAIT_MAX_SECONDS}); 0 only checks`
1477
+ )
1478
+ }),
1479
+ outputSchema: z2.object({
1480
+ questionId: z2.string(),
1481
+ status: z2.string(),
1482
+ waiting: z2.boolean(),
1483
+ answer: z2.looseObject({}).nullable(),
1484
+ message: z2.string(),
1485
+ question
1486
+ }),
1487
+ annotations: READ,
1488
+ handler: async (api, a) => {
1489
+ const r = await api.request(
1490
+ "GET",
1491
+ `/v1/agents/questions/${enc(a.questionId)}/wait`,
1492
+ {
1493
+ query: {
1494
+ agent_id: actingAs(api, a.agentId),
1495
+ timeout: a.waitSeconds
1496
+ },
1497
+ // The API holds the request for up to waitSeconds.
1498
+ timeout: (a.waitSeconds + 10) * 1e3
1499
+ }
1500
+ );
1501
+ const status = String(r.question.status);
1502
+ const waiting = status === "open";
1503
+ return {
1504
+ questionId: a.questionId,
1505
+ status,
1506
+ waiting,
1507
+ answer: r.question.answer ?? null,
1508
+ 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),
1509
+ question: r.question
1510
+ };
1511
+ }
1512
+ }),
1513
+ defineTool({
1514
+ name: "list_questions",
1515
+ title: "List questions",
1516
+ 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).",
1517
+ scope: "agents:read",
1518
+ endpoint: "GET /v1/agents/questions",
1519
+ inputSchema: z2.object({
1520
+ agentId,
1521
+ status: z2.enum(["open", "answered", "expired_default", "expired", "canceled"]).optional(),
1522
+ kind: z2.enum(["question", "approval"]).optional(),
1523
+ channelId: channelId.optional(),
1524
+ cursor: z2.string().max(300).optional().describe("nextCursor of the previous call"),
1525
+ limit: z2.number().int().min(1).max(200).default(20).describe("How many to return (1-200, default 20)")
1526
+ }),
1527
+ outputSchema: z2.object({
1528
+ questions: z2.array(question),
1529
+ nextCursor: z2.string().nullable()
1530
+ }),
1531
+ annotations: READ,
1532
+ handler: async (api, a) => {
1533
+ const r = await api.request("GET", "/v1/agents/questions", {
1534
+ query: {
1535
+ agent_id: actingAs(api, a.agentId),
1536
+ status: a.status,
1537
+ kind: a.kind,
1538
+ channel_id: a.channelId,
1539
+ cursor: a.cursor,
1540
+ limit: a.limit
1541
+ }
1542
+ });
1543
+ return {
1544
+ questions: r.questions ?? [],
1545
+ nextCursor: r.next_cursor ?? null
1546
+ };
1547
+ }
1548
+ }),
1549
+ defineTool({
1550
+ name: "cancel_question",
1551
+ title: "Cancel question",
1552
+ 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.",
1553
+ scope: "agents:ask_human",
1554
+ endpoint: "DELETE /v1/agents/questions/:id",
1555
+ inputSchema: z2.object({ agentId, questionId }),
1556
+ outputSchema: z2.object({ question }),
1557
+ annotations: {
1558
+ readOnlyHint: false,
1559
+ destructiveHint: true,
1560
+ idempotentHint: false,
1561
+ openWorldHint: true
1562
+ },
1563
+ handler: async (api, a) => {
1564
+ const r = await api.request(
1565
+ "DELETE",
1566
+ `/v1/agents/questions/${enc(a.questionId)}`,
1567
+ { query: { agent_id: actingAs(api, a.agentId) } }
1568
+ );
1569
+ return { question: r.question };
1570
+ }
1571
+ }),
1572
+ defineTool({
1573
+ name: "answer_escalated_question",
1574
+ title: "Answer escalated question",
1575
+ 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.",
1576
+ scope: "agents:send",
1577
+ endpoint: "POST /v1/agents/questions/:id/answer",
1578
+ inputSchema: z2.object({
1579
+ agentId,
1580
+ questionId,
1581
+ optionId: z2.string().min(1).max(100).optional().describe("One of the question options (approve / deny for approvals)"),
1582
+ text: z2.string().max(3e3).optional().describe("A typed answer, when the question allows free text"),
1583
+ comment: z2.string().max(2e3).optional().describe("Why (shown with the answer; say why on a deny)")
1584
+ }),
1585
+ outputSchema: z2.object({ question }),
1586
+ annotations: SEND,
1587
+ handler: async (api, a) => {
1588
+ if (!a.optionId && !a.text) throw new ToolError("Pass optionId or text.");
1589
+ const r = await api.request(
1590
+ "POST",
1591
+ `/v1/agents/questions/${enc(a.questionId)}/answer`,
1592
+ {
1593
+ body: {
1594
+ agent_id: actingAs(api, a.agentId),
1595
+ option_id: a.optionId,
1596
+ text: a.text,
1597
+ comment: a.comment
1598
+ }
1599
+ }
1600
+ );
1601
+ return { question: r.question };
1602
+ }
1603
+ }),
1604
+ defineTool({
1605
+ name: "get_org_chart",
1606
+ title: "Get org chart",
1607
+ 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.",
1608
+ scope: "agents:read",
1609
+ endpoint: "GET /v1/agents/org-chart",
1610
+ inputSchema: z2.object({
1611
+ teamId: uuid("Only this team").optional(),
1612
+ channelId: uuid("Only the agents of this channel").optional(),
1613
+ includeRetired: z2.boolean().optional().describe("Include retired agents (default false)")
1614
+ }),
1615
+ outputSchema: z2.object({
1616
+ agents: z2.array(z2.looseObject({ id: z2.string() })),
1617
+ users: z2.array(z2.looseObject({ id: z2.string() })),
1618
+ teams: z2.array(z2.looseObject({ id: z2.string() })),
1619
+ tree: z2.array(z2.looseObject({}))
1620
+ }),
1621
+ annotations: READ,
1622
+ handler: async (api, a) => await api.request("GET", "/v1/agents/org-chart", {
1623
+ query: {
1624
+ team_id: a.teamId,
1625
+ channel_id: a.channelId,
1626
+ include_retired: a.includeRetired ? "true" : void 0
1627
+ }
1628
+ })
1629
+ }),
1630
+ defineTool({
1631
+ name: "get_effective_policy",
1632
+ title: "Get effective policy",
1633
+ 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.",
1634
+ scope: "agents:admin",
1635
+ endpoint: "GET /v1/agents/policies/preview",
1636
+ inputSchema: z2.object({
1637
+ agentId: uuid(
1638
+ "The agent (from list_agents). Default: the server agent (CHANNLIZE_AGENT_ID)"
1639
+ ).optional(),
1640
+ channelId: channelId.optional()
1641
+ }),
1642
+ outputSchema: z2.looseObject({
1643
+ agent_id: z2.string(),
1644
+ channel_id: z2.string().nullable(),
1645
+ rules: z2.looseObject({}),
1646
+ working_hours: z2.looseObject({}),
1647
+ usage: z2.looseObject({}),
1648
+ checks: z2.looseObject({}).nullable()
1649
+ }),
1650
+ annotations: READ,
1651
+ handler: async (api, a) => await api.request("GET", "/v1/agents/policies/preview", {
1652
+ query: {
1653
+ agent_id: requireAgent(api, a.agentId),
1654
+ channel_id: a.channelId
1655
+ }
1656
+ })
1657
+ }),
1658
+ defineTool({
1659
+ name: "read_agent_inbox",
1660
+ title: "Read agent inbox",
1661
+ 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.",
1662
+ scope: "agents:read",
1663
+ endpoint: "GET /v1/agents/:id/inbox",
1664
+ inputSchema: z2.object({
1665
+ agentId,
1666
+ cursor: z2.string().max(200).optional().describe("Read after this cursor (nextCursor of the previous call)"),
1667
+ limit: z2.number().int().min(1).max(200).default(20).describe("How many to return (1-200, default 20)")
1668
+ }),
1669
+ outputSchema: z2.object({
1670
+ agentId: z2.string(),
1671
+ messages: z2.array(
1672
+ z2.looseObject({
1673
+ delivery_id: z2.string(),
1674
+ cursor: z2.string(),
1675
+ message
1676
+ })
1677
+ ),
1678
+ nextCursor: z2.string().nullable(),
1679
+ hasMore: z2.boolean()
1680
+ }),
1681
+ annotations: READ,
1682
+ handler: async (api, a) => {
1683
+ const id2 = requireAgent(api, a.agentId);
1684
+ const r = await api.request("GET", `/v1/agents/${enc(id2)}/inbox`, {
1685
+ query: { cursor: a.cursor, limit: a.limit }
1686
+ });
1687
+ return {
1688
+ agentId: id2,
1689
+ messages: r.messages ?? [],
1690
+ nextCursor: r.next_cursor ?? null,
1691
+ hasMore: Boolean(r.has_more)
1692
+ };
1693
+ }
1694
+ }),
1695
+ defineTool({
1696
+ name: "ack_agent_messages",
1697
+ title: "Acknowledge agent messages",
1698
+ 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.",
1699
+ scope: "agents:read",
1700
+ endpoint: "POST /v1/agents/:id/inbox/ack",
1701
+ inputSchema: z2.object({
1702
+ agentId,
1703
+ upTo: z2.string().uuid().optional().describe("Ack everything up to and including this delivery_id"),
1704
+ ids: z2.array(z2.string().uuid()).min(1).max(500).optional().describe("Ack these delivery (or message) IDs")
1705
+ }),
1706
+ outputSchema: z2.object({ acked: z2.number() }),
1707
+ annotations: {
1708
+ readOnlyHint: false,
1709
+ destructiveHint: false,
1710
+ idempotentHint: true,
1711
+ openWorldHint: false
1712
+ },
1713
+ handler: async (api, a) => {
1714
+ if (!a.upTo === !a.ids) {
1715
+ throw new ToolError("Pass either upTo or ids.");
1716
+ }
1717
+ const id2 = requireAgent(api, a.agentId);
1718
+ const r = await api.request(
1719
+ "POST",
1720
+ `/v1/agents/${enc(id2)}/inbox/ack`,
1721
+ { body: a.upTo ? { up_to: a.upTo } : { ids: a.ids } }
1722
+ );
1723
+ return { acked: Number(r.acked ?? 0) };
1724
+ }
1725
+ }),
1726
+ defineTool({
1727
+ name: "search_agent_messages",
1728
+ title: "Search agent messages",
1729
+ 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.`,
1730
+ scope: "agents:read",
1731
+ endpoint: "GET /v1/agents/search",
1732
+ inputSchema: z2.object({
1733
+ q: z2.string().trim().min(2).max(200).describe("What to look for (2-200 characters)"),
1734
+ agentId: uuid(
1735
+ "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."
1736
+ ).optional(),
1737
+ channelId: channelId.optional().describe("Only this agent channel"),
1738
+ type: z2.enum(AGENT_MESSAGE_TYPES).optional().describe("Only this message type"),
1739
+ include: z2.enum(["messages", "questions", "both"]).default("both").describe("messages, questions, or both (default)"),
1740
+ from: z2.string().max(40).optional().describe("ISO date-time: the earliest to search"),
1741
+ to: z2.string().max(40).optional().describe("ISO date-time: the latest to search"),
1742
+ cursor: z2.string().max(300).optional().describe("nextCursor of the previous call"),
1743
+ limit: z2.number().int().min(1).max(50).default(10).describe("How many results (1-50, default 10)")
1744
+ }),
1745
+ outputSchema: z2.object({
1746
+ results: z2.array(
1747
+ z2.looseObject({
1748
+ kind: z2.string(),
1749
+ id: z2.string(),
1750
+ type: z2.string(),
1751
+ text: z2.string(),
1752
+ highlight: z2.string(),
1753
+ channel: z2.string().nullable(),
1754
+ threadId: z2.string().nullable()
1755
+ })
1756
+ ),
1757
+ nextCursor: z2.string().nullable(),
1758
+ window: z2.object({ from: z2.string(), days: z2.number() })
1759
+ }),
1760
+ annotations: READ,
1761
+ handler: async (api, a) => {
1762
+ const r = await api.request("GET", "/v1/agents/search", {
1763
+ query: {
1764
+ q: a.q,
1765
+ agent_id: a.agentId,
1766
+ channel_id: a.channelId,
1767
+ type: a.type,
1768
+ include: a.include === "both" ? void 0 : a.include,
1769
+ from: a.from,
1770
+ to: a.to,
1771
+ cursor: a.cursor,
1772
+ limit: a.limit
1773
+ }
1774
+ });
1775
+ return summarizeSearch(r);
1776
+ }
1777
+ }),
1778
+ defineTool({
1779
+ name: "get_agent_graph",
1780
+ title: "Get agent communication graph",
1781
+ 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.",
1782
+ scope: "agents:read",
1783
+ endpoint: "GET /v1/agents/insights/graph",
1784
+ inputSchema: z2.object({
1785
+ ...insightsRange,
1786
+ agentId: insightsAgent,
1787
+ mine,
1788
+ teamId: uuid("Only edges touching this team").optional(),
1789
+ top: top(10)
1790
+ }),
1791
+ outputSchema: z2.object({
1792
+ range,
1793
+ totals: z2.object({
1794
+ nodes: z2.number(),
1795
+ edges: z2.number(),
1796
+ messages: z2.number(),
1797
+ tokens: z2.number(),
1798
+ cost: z2.number()
1799
+ }),
1800
+ topNodes: z2.array(
1801
+ z2.looseObject({ id: z2.string(), label: z2.string(), sent: z2.number() })
1802
+ ),
1803
+ topEdges: z2.array(
1804
+ z2.looseObject({
1805
+ source: z2.string(),
1806
+ target: z2.string(),
1807
+ messages: z2.number(),
1808
+ replyAvgMs: nullableNumber
1809
+ })
1810
+ ),
1811
+ omitted: z2.looseObject({ nodes: z2.number(), edges: z2.number() }),
1812
+ summary: z2.string()
1813
+ }),
1814
+ annotations: READ,
1815
+ handler: async (api, a) => {
1816
+ const r = await api.request("GET", "/v1/agents/insights/graph", {
1817
+ query: {
1818
+ from: a.from,
1819
+ to: a.to,
1820
+ channel_id: a.channelId,
1821
+ agent_id: filterAgent(api, a),
1822
+ team_id: a.teamId
1823
+ }
1824
+ });
1825
+ return summarizeGraph(r, a.top);
1826
+ }
1827
+ }),
1828
+ defineTool({
1829
+ name: "get_agent_cost",
1830
+ title: "Get agent cost",
1831
+ 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.",
1832
+ scope: "agents:read",
1833
+ endpoint: "GET /v1/agents/insights/cost",
1834
+ inputSchema: z2.object({
1835
+ ...insightsRange,
1836
+ groupBy: z2.enum(["agent", "channel", "team", "task", "day"]).default("agent").describe("How to break the cost down (default agent)"),
1837
+ agentId: insightsAgent,
1838
+ mine,
1839
+ teamId: uuid("Only what this team's agents sent").optional(),
1840
+ top: top(10)
1841
+ }),
1842
+ outputSchema: z2.object({
1843
+ range,
1844
+ groupBy: z2.string(),
1845
+ totals: z2.object({
1846
+ messages: z2.number(),
1847
+ pricedMessages: z2.number(),
1848
+ tokens: z2.number(),
1849
+ cost: z2.number()
1850
+ }),
1851
+ groups: z2.array(
1852
+ z2.looseObject({
1853
+ key: z2.string(),
1854
+ label: z2.string(),
1855
+ cost: z2.number(),
1856
+ share: nullableNumber
1857
+ })
1858
+ ),
1859
+ omittedGroups: z2.number(),
1860
+ truncated: z2.boolean(),
1861
+ daily: z2.array(z2.looseObject({ day: z2.string(), cost: z2.number() })),
1862
+ peakDay: z2.object({ day: z2.string(), cost: z2.number() }).nullable(),
1863
+ summary: z2.string()
1864
+ }),
1865
+ annotations: READ,
1866
+ handler: async (api, a) => {
1867
+ const r = await api.request("GET", "/v1/agents/insights/cost", {
1868
+ query: {
1869
+ from: a.from,
1870
+ to: a.to,
1871
+ channel_id: a.channelId,
1872
+ agent_id: filterAgent(api, a),
1873
+ team_id: a.teamId,
1874
+ group_by: a.groupBy,
1875
+ // Day groups come back whole; the others only need the top ones.
1876
+ limit: a.groupBy === "day" ? void 0 : a.top
1877
+ }
1878
+ });
1879
+ return summarizeCost(r, a.top);
1880
+ }
1881
+ }),
1882
+ defineTool({
1883
+ name: "get_agent_metrics",
1884
+ title: "Get agent metrics",
1885
+ 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.",
1886
+ scope: "agents:read",
1887
+ endpoint: "GET /v1/agents/insights/metrics",
1888
+ inputSchema: z2.object({
1889
+ ...insightsRange,
1890
+ agentId: insightsAgent,
1891
+ mine,
1892
+ top: top(5)
1893
+ }),
1894
+ outputSchema: z2.object({
1895
+ range,
1896
+ replies: z2.looseObject({
1897
+ agentToAgent: z2.looseObject({ avgMs: nullableNumber }),
1898
+ humanToAgent: z2.looseObject({ avgMs: nullableNumber }),
1899
+ agentToHuman: z2.looseObject({ avgMs: nullableNumber }),
1900
+ byAgent: z2.array(z2.looseObject({ agentId: z2.string() }))
1901
+ }),
1902
+ questions: z2.looseObject({ asked: z2.number() }),
1903
+ deliveries: z2.looseObject({ deliveries: z2.number() }),
1904
+ backlog: z2.looseObject({ unacked: z2.number(), held: z2.number() }),
1905
+ summary: z2.string()
1906
+ }),
1907
+ annotations: READ,
1908
+ handler: async (api, a) => {
1909
+ const r = await api.request("GET", "/v1/agents/insights/metrics", {
1910
+ query: {
1911
+ from: a.from,
1912
+ to: a.to,
1913
+ channel_id: a.channelId,
1914
+ agent_id: filterAgent(api, a)
1915
+ }
1916
+ });
1917
+ return summarizeMetrics(r, a.top);
1918
+ }
1919
+ }),
1920
+ defineTool({
1921
+ name: "list_agents",
1922
+ title: "List agents",
1923
+ 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.",
1924
+ scope: "agents:read",
1925
+ endpoint: "GET /v1/agents",
1926
+ inputSchema: z2.object({
1927
+ includeRetired: z2.boolean().optional().describe("Include retired agents (default false)")
1928
+ }),
1929
+ outputSchema: z2.object({
1930
+ agents: z2.array(
1931
+ z2.looseObject({
1932
+ id: z2.string(),
1933
+ slug: z2.string(),
1934
+ name: z2.string(),
1935
+ status: z2.string()
1936
+ })
1937
+ )
1938
+ }),
1939
+ annotations: READ,
1940
+ handler: async (api, a) => {
1941
+ const r = await api.request("GET", "/v1/agents", {
1942
+ query: { include_retired: a.includeRetired || void 0 }
1943
+ });
1944
+ return { agents: r.agents ?? [] };
1945
+ }
1946
+ }),
1947
+ defineTool({
1948
+ name: "list_agent_channels",
1949
+ title: "List agent channels",
1950
+ 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.",
1951
+ scope: "agents:read",
1952
+ endpoint: "GET /v1/agents/channels",
1953
+ inputSchema: z2.object({
1954
+ includeArchived: z2.boolean().optional().describe("Include archived channels (default false)")
1955
+ }),
1956
+ outputSchema: z2.object({
1957
+ channels: z2.array(
1958
+ z2.looseObject({
1959
+ id: z2.string(),
1960
+ slug: z2.string(),
1961
+ name: z2.string(),
1962
+ archived: z2.boolean()
1963
+ })
1964
+ )
1965
+ }),
1966
+ annotations: READ,
1967
+ handler: async (api, a) => {
1968
+ const r = await api.request(
1969
+ "GET",
1970
+ "/v1/agents/channels",
1971
+ { query: { include_archived: a.includeArchived || void 0 } }
1972
+ );
1973
+ return { channels: r.channels ?? [] };
1974
+ }
1975
+ })
1976
+ ];
1977
+ var AGENT_TOOL_NAMES = AGENT_TOOLS.map((t) => t.name);
1978
+ function getAgentTool(name) {
1979
+ return AGENT_TOOLS.find((t) => t.name === name);
1980
+ }
1981
+ async function runAgentTool(api, name, args) {
1982
+ const tool = getAgentTool(name);
1983
+ if (!tool) throw new ToolError(`Unknown agent tool "${name}"`);
1984
+ const parsed = tool.inputSchema.safeParse(args ?? {});
1985
+ if (!parsed.success) {
1986
+ throw new ToolError(
1987
+ `Invalid arguments for ${name}: ${parsed.error.issues.map((i) => `${i.path.join(".") || "input"}: ${i.message}`).join("; ")}`
1988
+ );
1989
+ }
1990
+ return await tool.handler(api, parsed.data);
1991
+ }
1992
+ function agentToolsAsJsonSchema(filter = () => true) {
1993
+ return AGENT_TOOLS.filter(filter).map((t) => ({
1994
+ name: t.name,
1995
+ description: t.description,
1996
+ parameters: z2.toJSONSchema(t.inputSchema, { io: "input" })
1997
+ }));
1998
+ }
1999
+
2000
+ // src/inbox.ts
2001
+ import * as z3 from "zod/v4";
2002
+ function defineTool2(tool) {
2003
+ return tool;
2004
+ }
2005
+ var CONVERSATION_STATUSES = [
2006
+ "open",
2007
+ "pending",
2008
+ "resolved",
2009
+ "closed"
2010
+ ];
2011
+ var CONVERSATION_PRIORITIES = [
2012
+ "low",
2013
+ "normal",
2014
+ "high",
2015
+ "urgent"
2016
+ ];
2017
+ var CONVERSATION_SORTS = [
2018
+ "recent",
2019
+ "oldest",
2020
+ "newest",
2021
+ "priority"
2022
+ ];
2023
+ var loose = z3.looseObject({});
2024
+ var id = (what) => z3.string().uuid().describe(`${what} ID`);
2025
+ var conversationId = id(
2026
+ "Conversation (from list_conversations or search_conversations)"
2027
+ );
2028
+ var person = z3.looseObject({
2029
+ id: z3.string(),
2030
+ name: z3.string().nullable().optional(),
2031
+ email: z3.string().nullable().optional()
2032
+ }).nullable();
2033
+ var conversationSummary = z3.looseObject({
2034
+ id: z3.string(),
2035
+ subject: z3.string().nullable().optional(),
2036
+ status: z3.string(),
2037
+ priority: z3.string().optional(),
2038
+ source: z3.string().nullable().optional(),
2039
+ tags: z3.array(z3.string()).optional(),
2040
+ customer: person.optional(),
2041
+ assignee: person.optional(),
2042
+ triage: z3.record(z3.string(), z3.unknown()).nullable().optional(),
2043
+ needsReply: z3.boolean().optional(),
2044
+ lastActivityAt: z3.string().nullable().optional()
2045
+ });
2046
+ var page = {
2047
+ total: z3.number(),
2048
+ limit: z3.number(),
2049
+ offset: z3.number(),
2050
+ hasMore: z3.boolean()
2051
+ };
2052
+ var listOutput = z3.object({
2053
+ conversations: z3.array(conversationSummary),
2054
+ ...page
2055
+ });
2056
+ var changeOutput = z3.object({
2057
+ conversation: z3.looseObject({ id: z3.string(), status: z3.string() }),
2058
+ changes: z3.array(z3.string())
2059
+ });
2060
+ var slackOutcome = z3.string().describe(
2061
+ "Slack mirror: queued, posted, no_thread (not in Slack), not_connected or failed"
2062
+ );
2063
+ var tags = z3.array(z3.string().trim().min(1).max(50)).max(20);
2064
+ var paging = {
2065
+ limit: z3.number().int().min(1).max(100).default(20).describe("How many to return (1-100, default 20)"),
2066
+ offset: z3.number().int().min(0).default(0).describe("Skip this many")
2067
+ };
2068
+ function oneOrMany(values) {
2069
+ return z3.union([z3.enum(values), z3.array(z3.enum(values)).max(10)]).optional();
2070
+ }
2071
+ var asList = (v) => v === void 0 ? void 0 : Array.isArray(v) ? v.join(",") : v;
2072
+ var listFilters = {
2073
+ status: oneOrMany(CONVERSATION_STATUSES).describe(
2074
+ 'Only these statuses: "open" or a list like ["open", "pending"]'
2075
+ ),
2076
+ priority: oneOrMany(CONVERSATION_PRIORITIES).describe(
2077
+ 'Only these priorities: "urgent" or a list'
2078
+ ),
2079
+ assignee: z3.string().max(255).optional().describe('A teammate (user ID or email), "unassigned" or "assigned"'),
2080
+ projectId: id("Project").optional(),
2081
+ updatedSince: z3.iso.datetime({ offset: true }).optional().describe("Updated or with a new message since (ISO 8601)"),
2082
+ tag: z3.string().max(50).optional().describe("Carrying this tag"),
2083
+ source: z3.string().max(32).optional().describe("Entry point, e.g. live_chat, contact_form, api, email"),
2084
+ intent: z3.string().max(64).optional().describe("AI triage intent (triaged conversations only)"),
2085
+ urgency: z3.string().max(64).optional().describe("AI triage urgency (triaged conversations only)"),
2086
+ sort: z3.enum(CONVERSATION_SORTS).optional().describe(
2087
+ "recent (last activity, default), oldest, newest (created) or priority"
2088
+ )
2089
+ };
2090
+ async function list(api, a) {
2091
+ const r = await api.request("GET", "/v1/conversations", {
2092
+ query: {
2093
+ status: asList(a.status),
2094
+ priority: asList(a.priority),
2095
+ assignee: a.assignee,
2096
+ projectId: a.projectId,
2097
+ updatedSince: a.updatedSince,
2098
+ tag: a.tag,
2099
+ source: a.source,
2100
+ intent: a.intent,
2101
+ urgency: a.urgency,
2102
+ sort: a.sort,
2103
+ q: a.q,
2104
+ limit: a.limit,
2105
+ offset: a.offset
2106
+ }
2107
+ });
2108
+ return {
2109
+ conversations: r.conversations ?? [],
2110
+ total: Number(r.total ?? 0),
2111
+ limit: Number(r.limit ?? a.limit),
2112
+ offset: Number(r.offset ?? a.offset),
2113
+ hasMore: Boolean(r.hasMore)
2114
+ };
2115
+ }
2116
+ var path = (cid, rest = "") => `/v1/conversations/${encodeURIComponent(cid)}${rest}`;
2117
+ async function patch(api, cid, body) {
2118
+ const r = await api.request(
2119
+ "PATCH",
2120
+ path(cid),
2121
+ { body }
2122
+ );
575
2123
  return {
576
- content: [{ type: "text", text: JSON.stringify(data, null, 2) }],
577
- structuredContent: data
2124
+ conversation: r.conversation,
2125
+ changes: r.changes ?? []
2126
+ };
2127
+ }
2128
+ var READ2 = {
2129
+ readOnlyHint: true,
2130
+ destructiveHint: false,
2131
+ idempotentHint: true,
2132
+ openWorldHint: false
2133
+ };
2134
+ var CHANGE = {
2135
+ readOnlyHint: false,
2136
+ destructiveHint: false,
2137
+ idempotentHint: true,
2138
+ openWorldHint: true
2139
+ };
2140
+ var ROUTING_FIELDS = [
2141
+ "source",
2142
+ "project",
2143
+ "widget",
2144
+ "connection",
2145
+ "page_url",
2146
+ "page_domain",
2147
+ "customer_email",
2148
+ "customer_email_domain",
2149
+ "message",
2150
+ "subject",
2151
+ "tags",
2152
+ "priority",
2153
+ "language"
2154
+ ];
2155
+ var ROUTING_OPERATORS = [
2156
+ "equals",
2157
+ "not_equals",
2158
+ "contains",
2159
+ "not_contains",
2160
+ "starts_with",
2161
+ "ends_with",
2162
+ "matches"
2163
+ ];
2164
+ var routingConditions = z3.object({
2165
+ match: z3.enum(["all", "any"]).describe("all = every condition holds, any = one is enough"),
2166
+ conditions: z3.array(
2167
+ z3.object({
2168
+ field: z3.enum(ROUTING_FIELDS),
2169
+ operator: z3.enum(ROUTING_OPERATORS),
2170
+ value: z3.union([z3.string(), z3.array(z3.string())]).describe(
2171
+ "A value, or a list (positive operators: any matches; negative: none does). Case-insensitive; matches uses * and ? wildcards."
2172
+ )
2173
+ })
2174
+ ).max(50).describe("Empty = matches every new conversation (catch-all)")
2175
+ }).describe(
2176
+ 'Which new conversations the rule catches, tested on the first message, e.g. { "match": "any", "conditions": [{ "field": "message", "operator": "contains", "value": ["refund", "invoice"] }] }'
2177
+ );
2178
+ var ruleFields = {
2179
+ name: z3.string().trim().min(1).max(255).describe("Rule name"),
2180
+ targetChannelId: z3.string().regex(/^[A-Z0-9]{2,30}$/, "a Slack channel ID like C0123ABCD").describe("Slack channel ID to post matching conversations to"),
2181
+ conditions: routingConditions,
2182
+ projectId: id("Project (default: the oldest project)").optional(),
2183
+ widgetId: id("Widget").nullable().optional(),
2184
+ integrationId: id("Integration (default: the Slack workspace)").optional(),
2185
+ assignToUserId: id("Teammate to assign matching conversations to").nullable().optional(),
2186
+ isActive: z3.boolean().optional().describe("Default true"),
2187
+ priority: z3.number().int().min(-1e6).max(1e6).optional().describe("Higher runs first (default: after every rule)")
2188
+ };
2189
+ var rule = z3.looseObject({
2190
+ id: z3.string(),
2191
+ name: z3.string(),
2192
+ priority: z3.number(),
2193
+ is_active: z3.boolean(),
2194
+ target_channel_id: z3.string()
2195
+ });
2196
+ var INBOX_TOOLS = [
2197
+ defineTool2({
2198
+ name: "list_conversations",
2199
+ title: "List conversations",
2200
+ 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.",
2201
+ scope: "inbox:read",
2202
+ endpoint: "GET /v1/conversations",
2203
+ inputSchema: z3.object({ ...listFilters, ...paging }),
2204
+ outputSchema: listOutput,
2205
+ annotations: READ2,
2206
+ handler: (api, a) => list(api, a)
2207
+ }),
2208
+ defineTool2({
2209
+ name: "search_conversations",
2210
+ title: "Search conversations",
2211
+ 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.",
2212
+ scope: "inbox:read",
2213
+ endpoint: "GET /v1/conversations?q=",
2214
+ inputSchema: z3.object({
2215
+ query: z3.string().trim().min(1).max(200).describe("Text to look for"),
2216
+ ...listFilters,
2217
+ ...paging
2218
+ }),
2219
+ outputSchema: listOutput,
2220
+ annotations: READ2,
2221
+ handler: (api, { query, ...a }) => list(api, { ...a, q: query })
2222
+ }),
2223
+ defineTool2({
2224
+ name: "get_conversation",
2225
+ title: "Get conversation",
2226
+ 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.",
2227
+ scope: "inbox:read",
2228
+ endpoint: "GET /v1/conversations/:id",
2229
+ inputSchema: z3.object({ conversationId }),
2230
+ outputSchema: z3.object({
2231
+ conversation: z3.looseObject({
2232
+ id: z3.string(),
2233
+ status: z3.string(),
2234
+ messages: z3.array(loose)
2235
+ })
2236
+ }),
2237
+ annotations: READ2,
2238
+ handler: async (api, { conversationId: cid }) => {
2239
+ const r = await api.request("GET", path(cid));
2240
+ return { conversation: r.conversation };
2241
+ }
2242
+ }),
2243
+ defineTool2({
2244
+ name: "reply_to_conversation",
2245
+ title: "Reply to conversation",
2246
+ 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.',
2247
+ scope: "inbox:write",
2248
+ endpoint: "POST /v1/conversations/:id/reply",
2249
+ inputSchema: z3.object({
2250
+ conversationId,
2251
+ content: z3.string().trim().min(1).max(1e4).describe("Reply text, as the customer will read it")
2252
+ }),
2253
+ outputSchema: z3.object({
2254
+ message: z3.looseObject({ id: z3.string() }),
2255
+ conversationStatus: z3.string(),
2256
+ slack: slackOutcome
2257
+ }),
2258
+ annotations: {
2259
+ readOnlyHint: false,
2260
+ destructiveHint: false,
2261
+ idempotentHint: false,
2262
+ openWorldHint: true
2263
+ },
2264
+ handler: async (api, { conversationId: cid, content }) => {
2265
+ const r = await api.request("POST", path(cid, "/reply"), {
2266
+ body: { content }
2267
+ });
2268
+ return {
2269
+ message: r.message,
2270
+ conversationStatus: String(r.conversationStatus ?? ""),
2271
+ slack: String(r.slack ?? "")
2272
+ };
2273
+ }
2274
+ }),
2275
+ defineTool2({
2276
+ name: "add_internal_note",
2277
+ title: "Add internal note",
2278
+ 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.",
2279
+ scope: "inbox:write",
2280
+ endpoint: "POST /v1/conversations/:id/notes",
2281
+ inputSchema: z3.object({
2282
+ conversationId,
2283
+ content: z3.string().trim().min(1).max(1e4).describe("Note text")
2284
+ }),
2285
+ outputSchema: z3.object({
2286
+ note: z3.looseObject({ id: z3.string() }),
2287
+ slack: slackOutcome
2288
+ }),
2289
+ annotations: {
2290
+ readOnlyHint: false,
2291
+ destructiveHint: false,
2292
+ idempotentHint: false,
2293
+ openWorldHint: true
2294
+ },
2295
+ handler: async (api, { conversationId: cid, content }) => {
2296
+ const r = await api.request("POST", path(cid, "/notes"), {
2297
+ body: { content }
2298
+ });
2299
+ return { note: r.note, slack: String(r.slack ?? "") };
2300
+ }
2301
+ }),
2302
+ defineTool2({
2303
+ name: "assign_conversation",
2304
+ title: "Assign conversation",
2305
+ 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.",
2306
+ scope: "inbox:write",
2307
+ endpoint: "PATCH /v1/conversations/:id",
2308
+ inputSchema: z3.object({
2309
+ conversationId,
2310
+ assignee: z3.string().min(1).max(255).nullable().describe("User ID or email of the teammate, or null to unassign")
2311
+ }),
2312
+ outputSchema: changeOutput,
2313
+ annotations: CHANGE,
2314
+ handler: (api, { conversationId: cid, assignee }) => patch(
2315
+ api,
2316
+ cid,
2317
+ assignee === null ? { assigneeId: null } : assignee.includes("@") ? { assigneeEmail: assignee } : { assigneeId: assignee }
2318
+ )
2319
+ }),
2320
+ defineTool2({
2321
+ name: "tag_conversation",
2322
+ title: "Tag conversation",
2323
+ 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.",
2324
+ scope: "inbox:write",
2325
+ endpoint: "PATCH /v1/conversations/:id",
2326
+ inputSchema: z3.object({
2327
+ conversationId,
2328
+ add: tags.optional().describe("Tags to add"),
2329
+ remove: tags.optional().describe("Tags to remove"),
2330
+ set: tags.optional().describe("Replace every tag with these ([] clears them)")
2331
+ }),
2332
+ outputSchema: changeOutput,
2333
+ annotations: CHANGE,
2334
+ handler: (api, { conversationId: cid, add, remove, set }) => {
2335
+ if (!add?.length && !remove?.length && !set) {
2336
+ throw new ToolError("Pass tags to add, remove, or set.");
2337
+ }
2338
+ return patch(api, cid, {
2339
+ ...set ? { tags: set } : {},
2340
+ ...add?.length ? { addTags: add } : {},
2341
+ ...remove?.length ? { removeTags: remove } : {}
2342
+ });
2343
+ }
2344
+ }),
2345
+ defineTool2({
2346
+ name: "close_conversation",
2347
+ title: "Close conversation",
2348
+ 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.",
2349
+ scope: "inbox:write",
2350
+ endpoint: "PATCH /v1/conversations/:id",
2351
+ inputSchema: z3.object({
2352
+ conversationId,
2353
+ status: z3.enum(["closed", "resolved"]).default("closed").describe("closed (default) or resolved")
2354
+ }),
2355
+ outputSchema: changeOutput,
2356
+ annotations: CHANGE,
2357
+ handler: (api, { conversationId: cid, status }) => patch(api, cid, { status })
2358
+ }),
2359
+ defineTool2({
2360
+ name: "reopen_conversation",
2361
+ title: "Reopen conversation",
2362
+ description: "Reopen a closed or resolved conversation (status open). Needs the inbox:write scope.",
2363
+ scope: "inbox:write",
2364
+ endpoint: "PATCH /v1/conversations/:id",
2365
+ inputSchema: z3.object({ conversationId }),
2366
+ outputSchema: changeOutput,
2367
+ annotations: CHANGE,
2368
+ handler: (api, { conversationId: cid }) => patch(api, cid, { status: "open" })
2369
+ }),
2370
+ defineTool2({
2371
+ name: "get_analytics_summary",
2372
+ title: "Get analytics summary",
2373
+ 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.",
2374
+ scope: "analytics:read",
2375
+ endpoint: "GET /v1/analytics/summary",
2376
+ inputSchema: z3.object({
2377
+ days: z3.number().int().min(1).max(366).optional().describe("Period length in days, ending today (default 30)"),
2378
+ from: z3.iso.date().optional().describe("First day, YYYY-MM-DD"),
2379
+ to: z3.iso.date().optional().describe("Last day, YYYY-MM-DD"),
2380
+ tz: z3.string().max(64).optional().describe("IANA time zone for day boundaries (default UTC)"),
2381
+ projectId: id("Project").optional()
2382
+ }),
2383
+ outputSchema: z3.looseObject({ range: loose, kpis: loose, inbox: loose }),
2384
+ annotations: READ2,
2385
+ handler: async (api, args) => api.request(
2386
+ "GET",
2387
+ "/v1/analytics/summary",
2388
+ { query: args }
2389
+ )
2390
+ }),
2391
+ defineTool2({
2392
+ name: "list_routing_rules",
2393
+ title: "List routing rules",
2394
+ 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.",
2395
+ scope: "routing:read",
2396
+ endpoint: "GET /v1/routing-rules",
2397
+ inputSchema: z3.object({}),
2398
+ outputSchema: z3.object({ rules: z3.array(rule) }),
2399
+ annotations: READ2,
2400
+ handler: async (api) => {
2401
+ const r = await api.request(
2402
+ "GET",
2403
+ "/v1/routing-rules"
2404
+ );
2405
+ return { rules: r.routing_rules ?? [] };
2406
+ }
2407
+ }),
2408
+ defineTool2({
2409
+ name: "create_routing_rule",
2410
+ title: "Create routing rule",
2411
+ 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.",
2412
+ scope: "routing:write",
2413
+ endpoint: "POST /v1/routing-rules",
2414
+ inputSchema: z3.object(ruleFields),
2415
+ outputSchema: z3.object({ rule }),
2416
+ annotations: {
2417
+ readOnlyHint: false,
2418
+ destructiveHint: false,
2419
+ idempotentHint: false,
2420
+ openWorldHint: false
2421
+ },
2422
+ handler: async (api, body) => {
2423
+ const r = await api.request(
2424
+ "POST",
2425
+ "/v1/routing-rules",
2426
+ { body }
2427
+ );
2428
+ return { rule: r.routing_rule };
2429
+ }
2430
+ }),
2431
+ defineTool2({
2432
+ name: "update_routing_rule",
2433
+ title: "Update routing rule",
2434
+ 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.",
2435
+ scope: "routing:write",
2436
+ endpoint: "PATCH /v1/routing-rules/:id",
2437
+ inputSchema: z3.object({
2438
+ ruleId: id("Routing rule"),
2439
+ name: ruleFields.name.optional(),
2440
+ targetChannelId: ruleFields.targetChannelId.optional(),
2441
+ conditions: routingConditions.optional(),
2442
+ projectId: ruleFields.projectId,
2443
+ widgetId: ruleFields.widgetId,
2444
+ integrationId: ruleFields.integrationId,
2445
+ assignToUserId: ruleFields.assignToUserId,
2446
+ isActive: ruleFields.isActive,
2447
+ priority: ruleFields.priority
2448
+ }),
2449
+ outputSchema: z3.object({ rule }),
2450
+ annotations: {
2451
+ readOnlyHint: false,
2452
+ destructiveHint: false,
2453
+ idempotentHint: true,
2454
+ openWorldHint: false
2455
+ },
2456
+ handler: async (api, { ruleId, ...body }) => {
2457
+ if (Object.values(body).every((v) => v === void 0)) {
2458
+ throw new ToolError("Pass at least one field to change.");
2459
+ }
2460
+ const r = await api.request(
2461
+ "PATCH",
2462
+ `/v1/routing-rules/${encodeURIComponent(ruleId)}`,
2463
+ { body }
2464
+ );
2465
+ return { rule: r.routing_rule };
2466
+ }
2467
+ }),
2468
+ defineTool2({
2469
+ name: "delete_routing_rule",
2470
+ title: "Delete routing rule",
2471
+ 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.",
2472
+ scope: "routing:write",
2473
+ endpoint: "DELETE /v1/routing-rules/:id",
2474
+ inputSchema: z3.object({ ruleId: id("Routing rule") }),
2475
+ outputSchema: z3.object({ deleted: z3.boolean(), ruleId: z3.string() }),
2476
+ annotations: {
2477
+ readOnlyHint: false,
2478
+ destructiveHint: true,
2479
+ idempotentHint: true,
2480
+ openWorldHint: false
2481
+ },
2482
+ handler: async (api, { ruleId }) => {
2483
+ await api.request(
2484
+ "DELETE",
2485
+ `/v1/routing-rules/${encodeURIComponent(ruleId)}`
2486
+ );
2487
+ return { deleted: true, ruleId };
2488
+ }
2489
+ })
2490
+ ];
2491
+ var INBOX_TOOL_NAMES = INBOX_TOOLS.map((t) => t.name);
2492
+ function getInboxTool(name) {
2493
+ return INBOX_TOOLS.find((t) => t.name === name);
2494
+ }
2495
+ async function runInboxTool(api, name, args) {
2496
+ const tool = getInboxTool(name);
2497
+ if (!tool) throw new ToolError(`Unknown inbox tool "${name}"`);
2498
+ const parsed = tool.inputSchema.safeParse(args ?? {});
2499
+ if (!parsed.success) {
2500
+ throw new ToolError(
2501
+ `Invalid arguments for ${name}: ${parsed.error.issues.map((i) => `${i.path.join(".") || "input"}: ${i.message}`).join("; ")}`
2502
+ );
2503
+ }
2504
+ return await tool.handler(api, parsed.data);
2505
+ }
2506
+ function inboxToolsAsJsonSchema(filter = () => true) {
2507
+ return INBOX_TOOLS.filter(filter).map((t) => ({
2508
+ name: t.name,
2509
+ description: t.description,
2510
+ parameters: z3.toJSONSchema(t.inputSchema, { io: "input" })
2511
+ }));
2512
+ }
2513
+
2514
+ // src/tools.ts
2515
+ function ok(data2) {
2516
+ return {
2517
+ content: [{ type: "text", text: JSON.stringify(data2, null, 2) }],
2518
+ structuredContent: data2
578
2519
  };
579
2520
  }
580
2521
  async function run(fn) {
@@ -588,25 +2529,15 @@ async function run(fn) {
588
2529
  };
589
2530
  }
590
2531
  }
591
- var record2 = z2.record(z2.string(), z2.unknown());
592
- var loose = z2.looseObject({});
593
- var page = {
594
- total: z2.number(),
595
- limit: z2.number(),
596
- offset: z2.number(),
597
- hasMore: z2.boolean()
2532
+ var record4 = z4.record(z4.string(), z4.unknown());
2533
+ var loose2 = z4.looseObject({});
2534
+ var page2 = {
2535
+ total: z4.number(),
2536
+ limit: z4.number(),
2537
+ offset: z4.number(),
2538
+ hasMore: z4.boolean()
598
2539
  };
599
- var conversationSummary = z2.looseObject({
600
- id: z2.string(),
601
- subject: z2.string().nullable().optional(),
602
- status: z2.string(),
603
- priority: z2.string().nullable().optional(),
604
- customerEmail: z2.string().nullable().optional(),
605
- customerName: z2.string().nullable().optional(),
606
- tags: z2.array(z2.string()).nullable().optional(),
607
- createdAt: z2.string().optional()
608
- });
609
- var READ = {
2540
+ var READ3 = {
610
2541
  readOnlyHint: true,
611
2542
  destructiveHint: false,
612
2543
  idempotentHint: true,
@@ -618,9 +2549,9 @@ function registerServerTools(server, api) {
618
2549
  {
619
2550
  title: "Get project",
620
2551
  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.",
621
- inputSchema: z2.object({}),
622
- outputSchema: z2.object({ project: loose }),
623
- annotations: READ
2552
+ inputSchema: z4.object({}),
2553
+ outputSchema: z4.object({ project: loose2 }),
2554
+ annotations: READ3
624
2555
  },
625
2556
  () => run(async () => {
626
2557
  const r = await api.request("GET", "/projects/me");
@@ -632,9 +2563,9 @@ function registerServerTools(server, api) {
632
2563
  {
633
2564
  title: "Get analytics",
634
2565
  description: "Daily support activity for the last 30 days (UTC): conversations created and resolved, customer and agent messages.",
635
- inputSchema: z2.object({}),
636
- outputSchema: z2.object({ analytics: loose }),
637
- annotations: READ
2566
+ inputSchema: z4.object({}),
2567
+ outputSchema: z4.object({ analytics: loose2 }),
2568
+ annotations: READ3
638
2569
  },
639
2570
  () => run(async () => {
640
2571
  const r = await api.request(
@@ -644,75 +2575,20 @@ function registerServerTools(server, api) {
644
2575
  return { analytics: r.analytics };
645
2576
  })
646
2577
  );
647
- server.registerTool(
648
- "list_conversations",
649
- {
650
- title: "List conversations",
651
- 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.",
652
- inputSchema: z2.object({
653
- status: z2.enum(STATUSES).optional().describe("Only conversations with this status"),
654
- priority: z2.enum(PRIORITIES).optional().describe("Only conversations with this priority"),
655
- limit: z2.number().int().min(1).max(50).default(20).describe("How many to return (1-50, default 20)")
656
- }),
657
- outputSchema: z2.object({
658
- conversations: z2.array(conversationSummary),
659
- returned: z2.number(),
660
- matched: z2.number(),
661
- scanned: z2.number()
662
- }),
663
- annotations: READ
664
- },
665
- ({ status, priority, limit }) => run(async () => {
666
- const r = await api.request(
667
- "GET",
668
- "/conversations"
669
- );
670
- const all = r.conversations ?? [];
671
- const matched = all.filter(
672
- (c) => (!status || c.status === status) && (!priority || c.priority === priority)
673
- );
674
- const conversations = matched.slice(0, limit);
675
- return {
676
- conversations,
677
- returned: conversations.length,
678
- matched: matched.length,
679
- scanned: all.length
680
- };
681
- })
682
- );
683
- server.registerTool(
684
- "get_conversation",
685
- {
686
- title: "Get conversation",
687
- description: "Read one conversation with its full message thread (customer, agent and system messages), status, priority and tags.",
688
- inputSchema: z2.object({
689
- conversationId: z2.string().uuid().describe("Conversation ID (from list_conversations)")
690
- }),
691
- outputSchema: z2.object({ conversation: loose }),
692
- annotations: READ
693
- },
694
- ({ conversationId }) => run(async () => {
695
- const conversation = await api.request(
696
- "GET",
697
- `/conversations/${encodeURIComponent(conversationId)}`
698
- );
699
- return { conversation };
700
- })
701
- );
702
2578
  server.registerTool(
703
2579
  "create_conversation",
704
2580
  {
705
2581
  title: "Create conversation",
706
2582
  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.",
707
- inputSchema: z2.object({
708
- customerEmail: z2.email().describe("Customer's email address"),
709
- customerName: z2.string().max(255).optional().describe("Customer's name"),
710
- subject: z2.string().min(1).max(500).describe("Subject line"),
711
- message: z2.string().min(1).describe("First message, from the customer"),
712
- channel: z2.string().optional().describe("Slack channel ID to post to, overriding routing rules"),
713
- tags: z2.array(z2.string()).max(20).optional().describe("Tags")
2583
+ inputSchema: z4.object({
2584
+ customerEmail: z4.email().describe("Customer's email address"),
2585
+ customerName: z4.string().max(255).optional().describe("Customer's name"),
2586
+ subject: z4.string().min(1).max(500).describe("Subject line"),
2587
+ message: z4.string().min(1).describe("First message, from the customer"),
2588
+ channel: z4.string().optional().describe("Slack channel ID to post to, overriding routing rules"),
2589
+ tags: z4.array(z4.string()).max(20).optional().describe("Tags")
714
2590
  }),
715
- outputSchema: z2.object({ conversation: loose }),
2591
+ outputSchema: z4.object({ conversation: loose2 }),
716
2592
  annotations: {
717
2593
  readOnlyHint: false,
718
2594
  destructiveHint: false,
@@ -732,12 +2608,12 @@ function registerServerTools(server, api) {
732
2608
  {
733
2609
  title: "List contacts",
734
2610
  description: "List the customers who contacted the organization, with their conversation count. Paginate with limit/offset.",
735
- inputSchema: z2.object({
736
- limit: z2.number().int().min(1).max(100).default(50),
737
- offset: z2.number().int().min(0).default(0)
2611
+ inputSchema: z4.object({
2612
+ limit: z4.number().int().min(1).max(100).default(50),
2613
+ offset: z4.number().int().min(0).default(0)
738
2614
  }),
739
- outputSchema: z2.object({ contacts: z2.array(loose), ...page }),
740
- annotations: READ
2615
+ outputSchema: z4.object({ contacts: z4.array(loose2), ...page2 }),
2616
+ annotations: READ3
741
2617
  },
742
2618
  ({ limit, offset }) => run(async () => {
743
2619
  const r = await api.request("GET", "/contacts", {
@@ -757,11 +2633,11 @@ function registerServerTools(server, api) {
757
2633
  {
758
2634
  title: "Get contact",
759
2635
  description: "Read one contact (customer) by ID.",
760
- inputSchema: z2.object({
761
- contactId: z2.string().uuid().describe("Contact ID (from list_contacts)")
2636
+ inputSchema: z4.object({
2637
+ contactId: z4.string().uuid().describe("Contact ID (from list_contacts)")
762
2638
  }),
763
- outputSchema: z2.object({ contact: loose }),
764
- annotations: READ
2639
+ outputSchema: z4.object({ contact: loose2 }),
2640
+ annotations: READ3
765
2641
  },
766
2642
  ({ contactId }) => run(async () => {
767
2643
  const contact = await api.request(
@@ -776,14 +2652,14 @@ function registerServerTools(server, api) {
776
2652
  {
777
2653
  title: "Create contact",
778
2654
  description: "Add a customer by email, or return the existing one with that email. Needs the write scope.",
779
- inputSchema: z2.object({
780
- email: z2.email(),
781
- name: z2.string().max(255).optional(),
782
- company: z2.string().optional(),
783
- phone: z2.string().optional(),
784
- tags: z2.array(z2.string()).max(20).optional()
2655
+ inputSchema: z4.object({
2656
+ email: z4.email(),
2657
+ name: z4.string().max(255).optional(),
2658
+ company: z4.string().optional(),
2659
+ phone: z4.string().optional(),
2660
+ tags: z4.array(z4.string()).max(20).optional()
785
2661
  }),
786
- outputSchema: z2.object({ contact: loose }),
2662
+ outputSchema: z4.object({ contact: loose2 }),
787
2663
  annotations: {
788
2664
  readOnlyHint: false,
789
2665
  destructiveHint: false,
@@ -803,23 +2679,23 @@ function registerServerTools(server, api) {
803
2679
  {
804
2680
  title: "Send an Event to Slack",
805
2681
  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.',
806
- inputSchema: z2.object({
807
- event: z2.string().max(100).regex(
2682
+ inputSchema: z4.object({
2683
+ event: z4.string().max(100).regex(
808
2684
  EVENT_KEY_PATTERN,
809
2685
  "lowercase letters, digits, dots, underscores or dashes"
810
2686
  ).describe("Event key, e.g. user.subscribed"),
811
- data: record2.optional().describe(
2687
+ data: record4.optional().describe(
812
2688
  'Template fields, e.g. { "username": "ada", "plan": "Pro" }'
813
2689
  ),
814
- idempotencyKey: z2.string().min(1).max(255).optional().describe("Send at most once per key (retry-safe)"),
815
- channel: z2.string().optional().describe("Slack channel ID instead of the event's channel")
2690
+ idempotencyKey: z4.string().min(1).max(255).optional().describe("Send at most once per key (retry-safe)"),
2691
+ channel: z4.string().optional().describe("Slack channel ID instead of the event's channel")
816
2692
  }),
817
- outputSchema: z2.looseObject({
818
- id: z2.string(),
819
- event: z2.string(),
820
- status: z2.string(),
821
- reason: z2.string().optional(),
822
- duplicate: z2.boolean().optional()
2693
+ outputSchema: z4.looseObject({
2694
+ id: z4.string(),
2695
+ event: z4.string(),
2696
+ status: z4.string(),
2697
+ reason: z4.string().optional(),
2698
+ duplicate: z4.boolean().optional()
823
2699
  }),
824
2700
  annotations: {
825
2701
  readOnlyHint: false,
@@ -828,9 +2704,9 @@ function registerServerTools(server, api) {
828
2704
  openWorldHint: true
829
2705
  }
830
2706
  },
831
- ({ event, data, idempotencyKey, channel }) => run(async () => {
2707
+ ({ event, data: data2, idempotencyKey, channel }) => run(async () => {
832
2708
  const client = await api.notifier();
833
- const r = await client.notify(event, data, { idempotencyKey, channel });
2709
+ const r = await client.notify(event, data2, { idempotencyKey, channel });
834
2710
  return {
835
2711
  id: r.id,
836
2712
  event: r.event,
@@ -845,12 +2721,12 @@ function registerServerTools(server, api) {
845
2721
  {
846
2722
  title: "List Events",
847
2723
  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.",
848
- inputSchema: z2.object({}),
849
- outputSchema: z2.object({
850
- projectId: z2.string(),
851
- definitions: z2.array(loose)
2724
+ inputSchema: z4.object({}),
2725
+ outputSchema: z4.object({
2726
+ projectId: z4.string(),
2727
+ definitions: z4.array(loose2)
852
2728
  }),
853
- annotations: READ
2729
+ annotations: READ3
854
2730
  },
855
2731
  () => run(async () => {
856
2732
  const projectId = await api.projectId();
@@ -866,15 +2742,15 @@ function registerServerTools(server, api) {
866
2742
  {
867
2743
  title: "List Event deliveries",
868
2744
  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.",
869
- inputSchema: z2.object({
870
- definitionId: z2.string().uuid().optional().describe("Only this Event (ID from list_event_definitions)"),
871
- limit: z2.number().int().min(1).max(100).default(20)
2745
+ inputSchema: z4.object({
2746
+ definitionId: z4.string().uuid().optional().describe("Only this Event (ID from list_event_definitions)"),
2747
+ limit: z4.number().int().min(1).max(100).default(20)
872
2748
  }),
873
- outputSchema: z2.object({
874
- projectId: z2.string(),
875
- deliveries: z2.array(loose)
2749
+ outputSchema: z4.object({
2750
+ projectId: z4.string(),
2751
+ deliveries: z4.array(loose2)
876
2752
  }),
877
- annotations: READ
2753
+ annotations: READ3
878
2754
  },
879
2755
  ({ definitionId, limit }) => run(async () => {
880
2756
  const projectId = await api.projectId();
@@ -891,20 +2767,20 @@ function registerServerTools(server, api) {
891
2767
  {
892
2768
  title: "Query logs",
893
2769
  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.",
894
- inputSchema: z2.object({
895
- severity: z2.enum(EVENT_SEVERITIES).optional(),
896
- source: z2.enum(["client_sdk", "server_api", "system"]).optional().describe(
2770
+ inputSchema: z4.object({
2771
+ severity: z4.enum(EVENT_SEVERITIES).optional(),
2772
+ source: z4.enum(["client_sdk", "server_api", "system"]).optional().describe(
897
2773
  "client_sdk = browser (widget key), server_api = server key"
898
2774
  ),
899
- search: z2.string().max(200).optional().describe("Text to look for"),
900
- from: z2.iso.datetime({ offset: true }).optional().describe("ISO 8601 start"),
901
- to: z2.iso.datetime({ offset: true }).optional().describe("ISO 8601 end"),
902
- projectId: z2.string().uuid().optional(),
903
- limit: z2.number().int().min(1).max(100).default(50),
904
- offset: z2.number().int().min(0).default(0)
2775
+ search: z4.string().max(200).optional().describe("Text to look for"),
2776
+ from: z4.iso.datetime({ offset: true }).optional().describe("ISO 8601 start"),
2777
+ to: z4.iso.datetime({ offset: true }).optional().describe("ISO 8601 end"),
2778
+ projectId: z4.string().uuid().optional(),
2779
+ limit: z4.number().int().min(1).max(100).default(50),
2780
+ offset: z4.number().int().min(0).default(0)
905
2781
  }),
906
- outputSchema: z2.object({ events: z2.array(loose), ...page }),
907
- annotations: READ
2782
+ outputSchema: z4.object({ events: z4.array(loose2), ...page2 }),
2783
+ annotations: READ3
908
2784
  },
909
2785
  (args) => run(async () => {
910
2786
  const r = await api.request("GET", "/v1/events", { query: args });
@@ -922,12 +2798,12 @@ function registerServerTools(server, api) {
922
2798
  {
923
2799
  title: "Record a log",
924
2800
  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.",
925
- inputSchema: z2.object({
926
- name: z2.string().min(1).max(255).describe("Log name, e.g. payment.failed"),
927
- severity: z2.enum(EVENT_SEVERITIES).default("info"),
928
- properties: record2.optional().describe("Extra fields")
2801
+ inputSchema: z4.object({
2802
+ name: z4.string().min(1).max(255).describe("Log name, e.g. payment.failed"),
2803
+ severity: z4.enum(EVENT_SEVERITIES).default("info"),
2804
+ properties: record4.optional().describe("Extra fields")
929
2805
  }),
930
- outputSchema: z2.object({ id: z2.string(), projectId: z2.string() }),
2806
+ outputSchema: z4.object({ id: z4.string(), projectId: z4.string() }),
931
2807
  annotations: {
932
2808
  readOnlyHint: false,
933
2809
  destructiveHint: false,
@@ -956,16 +2832,16 @@ function registerWidgetTools(server, api) {
956
2832
  {
957
2833
  title: "Submit contact form",
958
2834
  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.",
959
- inputSchema: z2.object({
960
- name: z2.string().min(1).describe("Visitor's name"),
961
- email: z2.email().describe("Visitor's email"),
962
- subject: z2.string().optional(),
963
- message: z2.string().min(1),
964
- pageUrl: z2.url().optional().describe("Page the form was sent from")
2835
+ inputSchema: z4.object({
2836
+ name: z4.string().min(1).describe("Visitor's name"),
2837
+ email: z4.email().describe("Visitor's email"),
2838
+ subject: z4.string().optional(),
2839
+ message: z4.string().min(1),
2840
+ pageUrl: z4.url().optional().describe("Page the form was sent from")
965
2841
  }),
966
- outputSchema: z2.looseObject({
967
- conversationId: z2.string().optional(),
968
- message: z2.string().optional()
2842
+ outputSchema: z4.looseObject({
2843
+ conversationId: z4.string().optional(),
2844
+ message: z4.string().optional()
969
2845
  }),
970
2846
  annotations: VISITOR
971
2847
  },
@@ -979,12 +2855,12 @@ function registerWidgetTools(server, api) {
979
2855
  {
980
2856
  title: "Start chat session",
981
2857
  description: "Start a live chat session as a website visitor (widget key). Returns the session ID for send_message.",
982
- inputSchema: z2.object({
983
- metadata: record2.optional().describe("Metadata to attach (e.g. user info)")
2858
+ inputSchema: z4.object({
2859
+ metadata: record4.optional().describe("Metadata to attach (e.g. user info)")
984
2860
  }),
985
- outputSchema: z2.looseObject({
986
- sessionId: z2.string(),
987
- status: z2.string()
2861
+ outputSchema: z4.looseObject({
2862
+ sessionId: z4.string(),
2863
+ status: z4.string()
988
2864
  }),
989
2865
  annotations: VISITOR
990
2866
  },
@@ -1002,13 +2878,13 @@ function registerWidgetTools(server, api) {
1002
2878
  {
1003
2879
  title: "Send chat message",
1004
2880
  description: "Send a visitor message in a chat session (widget key); it is posted to the Slack thread.",
1005
- inputSchema: z2.object({
1006
- sessionId: z2.string().min(1).describe("From create_chat_session"),
1007
- content: z2.string().min(1).max(5e3)
2881
+ inputSchema: z4.object({
2882
+ sessionId: z4.string().min(1).describe("From create_chat_session"),
2883
+ content: z4.string().min(1).max(5e3)
1008
2884
  }),
1009
- outputSchema: z2.looseObject({
1010
- messageId: z2.string(),
1011
- sessionStatus: z2.string()
2885
+ outputSchema: z4.looseObject({
2886
+ messageId: z4.string(),
2887
+ sessionStatus: z4.string()
1012
2888
  }),
1013
2889
  annotations: VISITOR
1014
2890
  },
@@ -1022,16 +2898,16 @@ function registerWidgetTools(server, api) {
1022
2898
  {
1023
2899
  title: "Read chat messages",
1024
2900
  description: "Read a chat session's messages, including agent replies from Slack (widget key).",
1025
- inputSchema: z2.object({
1026
- sessionId: z2.string().min(1),
1027
- limit: z2.number().int().min(1).max(100).default(50),
1028
- offset: z2.number().int().min(0).default(0)
2901
+ inputSchema: z4.object({
2902
+ sessionId: z4.string().min(1),
2903
+ limit: z4.number().int().min(1).max(100).default(50),
2904
+ offset: z4.number().int().min(0).default(0)
1029
2905
  }),
1030
- outputSchema: z2.object({
1031
- sessionId: z2.string(),
1032
- messages: z2.array(loose)
2906
+ outputSchema: z4.object({
2907
+ sessionId: z4.string(),
2908
+ messages: z4.array(loose2)
1033
2909
  }),
1034
- annotations: { ...READ, openWorldHint: true }
2910
+ annotations: { ...READ3, openWorldHint: true }
1035
2911
  },
1036
2912
  ({ sessionId, limit, offset }) => run(async () => {
1037
2913
  const messages = await api.widget().getChatMessages(sessionId, limit, offset);
@@ -1053,10 +2929,10 @@ function registerWidgetTools(server, api) {
1053
2929
  {
1054
2930
  title: "End chat session",
1055
2931
  description: "End a chat session as the visitor (widget key).",
1056
- inputSchema: z2.object({ sessionId: z2.string().min(1) }),
1057
- outputSchema: z2.looseObject({
1058
- sessionId: z2.string(),
1059
- status: z2.string()
2932
+ inputSchema: z4.object({ sessionId: z4.string().min(1) }),
2933
+ outputSchema: z4.looseObject({
2934
+ sessionId: z4.string(),
2935
+ status: z4.string()
1060
2936
  }),
1061
2937
  annotations: { ...VISITOR, idempotentHint: true }
1062
2938
  },
@@ -1066,6 +2942,27 @@ function registerWidgetTools(server, api) {
1066
2942
  })
1067
2943
  );
1068
2944
  }
2945
+ function registerAll(server, api, tools) {
2946
+ for (const tool of tools) {
2947
+ server.registerTool(
2948
+ tool.name,
2949
+ {
2950
+ title: tool.title,
2951
+ description: tool.description,
2952
+ inputSchema: tool.inputSchema,
2953
+ outputSchema: tool.outputSchema,
2954
+ annotations: tool.annotations
2955
+ },
2956
+ (args) => run(async () => await tool.handler(api, args))
2957
+ );
2958
+ }
2959
+ }
2960
+ function registerInboxTools(server, api) {
2961
+ registerAll(server, api, INBOX_TOOLS);
2962
+ }
2963
+ function registerAgentTools(server, api) {
2964
+ registerAll(server, api, AGENT_TOOLS);
2965
+ }
1069
2966
 
1070
2967
  // src/http.ts
1071
2968
  import { createServer } from "http";
@@ -1103,7 +3000,7 @@ async function toRequest(req, origin) {
1103
3000
  async function startHttpServer(factory, options = {}) {
1104
3001
  const host = options.host ?? "127.0.0.1";
1105
3002
  const port = options.port ?? 3333;
1106
- const path = options.path ?? "/mcp";
3003
+ const path2 = options.path ?? "/mcp";
1107
3004
  const local = LOCAL_HOSTS.has(host);
1108
3005
  const handler = createMcpHandler(() => factory(), {
1109
3006
  onerror: (err) => console.error("[channlize-mcp]", err.message)
@@ -1115,8 +3012,8 @@ async function startHttpServer(factory, options = {}) {
1115
3012
  `http://${req.headers.host ?? `${host}:${port}`}`
1116
3013
  );
1117
3014
  const url2 = new URL(request.url);
1118
- if (url2.pathname !== path) {
1119
- res.writeHead(404, { "Content-Type": "text/plain" }).end(`Not found: use ${path}`);
3015
+ if (url2.pathname !== path2) {
3016
+ res.writeHead(404, { "Content-Type": "text/plain" }).end(`Not found: use ${path2}`);
1120
3017
  return;
1121
3018
  }
1122
3019
  const rejected = local ? hostHeaderValidationResponse(request, localhostAllowedHostnames()) ?? originValidationResponse(request, localhostAllowedOrigins()) : void 0;
@@ -1143,7 +3040,7 @@ async function startHttpServer(factory, options = {}) {
1143
3040
  const actualPort = typeof address === "object" && address ? address.port : port;
1144
3041
  const shownHost = host.includes(":") ? `[${host}]` : host;
1145
3042
  return {
1146
- url: `http://${shownHost}:${actualPort}${path}`,
3043
+ url: `http://${shownHost}:${actualPort}${path2}`,
1147
3044
  server,
1148
3045
  close: () => new Promise((r) => server.close(() => r()))
1149
3046
  };
@@ -1156,12 +3053,18 @@ import {
1156
3053
  AuthenticationError,
1157
3054
  RateLimitError
1158
3055
  } from "@channlize/core";
1159
- var VERSION = true ? "0.4.0" : "0.0.0";
3056
+ var VERSION = true ? "0.6.0" : "0.0.0";
1160
3057
  var INSTRUCTIONS = `Channlize routes website conversations and app events to the team's Slack.
1161
- - Inbox: list_conversations / get_conversation, then contacts. Replies and status changes happen in Slack or the dashboard.
3058
+ - 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.
3059
+ - get_analytics_summary gives KPIs and the inbox right now; list/create/update/delete_routing_rule manage which Slack channel new conversations go to.
1162
3060
  - Events (notify_event) post a Slack message per event key; list_event_definitions and list_event_deliveries explain what was sent or skipped.
1163
3061
  - Logs: query_logs searches log tracking; track_log records one.
1164
- - Write tools need a server API key with the write scope; a 403 means the key is read-only.`;
3062
+ - 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).
3063
+ - 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.
3064
+ - 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).
3065
+ - 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.
3066
+ - 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.
3067
+ - 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.`;
1165
3068
  function buildServer(config, info = {}) {
1166
3069
  const api = new ChannlizeApi(resolveConfig(config));
1167
3070
  const server = new McpServer(
@@ -1169,6 +3072,8 @@ function buildServer(config, info = {}) {
1169
3072
  { instructions: INSTRUCTIONS }
1170
3073
  );
1171
3074
  if (api.hasServerKey) {
3075
+ registerInboxTools(server, api);
3076
+ registerAgentTools(server, api);
1172
3077
  registerServerTools(server, api);
1173
3078
  registerServerPrompts(server);
1174
3079
  }
@@ -1210,19 +3115,40 @@ function createMCPServer(options) {
1210
3115
  }
1211
3116
  var index_default = ChannlizeMCPServer;
1212
3117
  export {
3118
+ AGENT_TASK_STATUSES,
3119
+ AGENT_TOOLS,
3120
+ AGENT_TOOL_NAMES,
1213
3121
  AuthenticationError,
3122
+ CONVERSATION_PRIORITIES,
3123
+ CONVERSATION_SORTS,
3124
+ CONVERSATION_STATUSES,
3125
+ ChannlizeApi,
1214
3126
  ChannlizeError2 as ChannlizeError,
1215
3127
  ChannlizeMCPServer,
1216
3128
  ConfigError,
3129
+ INBOX_TOOLS,
3130
+ INBOX_TOOL_NAMES,
3131
+ QUESTION_WAIT_MAX_SECONDS,
3132
+ ROUTING_FIELDS,
3133
+ ROUTING_OPERATORS,
1217
3134
  RateLimitError,
1218
3135
  ToolError,
1219
3136
  VERSION,
1220
3137
  ValidationError,
3138
+ agentToolsAsJsonSchema,
1221
3139
  buildServer,
1222
3140
  configFromEnv,
1223
3141
  createMCPServer,
1224
3142
  index_default as default,
3143
+ getAgentTool,
3144
+ getInboxTool,
3145
+ inboxToolsAsJsonSchema,
1225
3146
  keyKind,
1226
- resolveConfig
3147
+ registerAgentTools,
3148
+ registerInboxTools,
3149
+ resolveConfig,
3150
+ runAgentTool,
3151
+ runInboxTool,
3152
+ toToolError
1227
3153
  };
1228
3154
  //# sourceMappingURL=index.mjs.map