@channlize/mcp 0.4.0 → 0.5.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/server.js CHANGED
@@ -33,21 +33,108 @@ var import_stdio = require("@modelcontextprotocol/server/stdio");
33
33
  // src/api.ts
34
34
  var import_core = require("@channlize/core");
35
35
  var ToolError = class extends Error {
36
- constructor(message, statusCode, code) {
37
- super(message);
36
+ constructor(message2, statusCode, code, retryAt) {
37
+ super(message2);
38
38
  this.statusCode = statusCode;
39
39
  this.code = code;
40
+ this.retryAt = retryAt;
40
41
  this.name = "ToolError";
41
42
  }
42
43
  statusCode;
43
44
  code;
45
+ retryAt;
44
46
  };
45
- function hintFor(status, apiMessage) {
47
+ function scopeFor(apiMessage) {
48
+ const perm = /permission:\s*([\w:*-]+)/i.exec(apiMessage)?.[1] ?? "";
49
+ switch (perm) {
50
+ case "inbox:read":
51
+ return "inbox:read (or read)";
52
+ case "inbox:write":
53
+ return "inbox:write";
54
+ case "routing:read":
55
+ return "routing:write, inbox:read (or read)";
56
+ case "routing:write":
57
+ return "routing:write";
58
+ case "analytics:read":
59
+ return "analytics:read (or read)";
60
+ case "agents:send":
61
+ return "agents:send";
62
+ case "agents:read":
63
+ return "agents:read";
64
+ case "agents:ask_human":
65
+ return "agents:ask_human";
66
+ case "agents:admin":
67
+ return "agents:admin (an unbound key)";
68
+ default:
69
+ return /write|notify/.test(apiMessage) ? "write" : "read";
70
+ }
71
+ }
72
+ function retryText(retryAt) {
73
+ return retryAt ? ` Retry after ${retryAt}, not before.` : "";
74
+ }
75
+ function agentHint(code, body = {}) {
76
+ const retryAt = typeof body.retryAt === "string" ? body.retryAt : void 0;
77
+ switch (code) {
78
+ case "AGENT_KEY_REQUIRED":
79
+ return "Agent tools need an agent key or a multi-agent key: create one under SDK & Integration \u2192 API keys and pick the agents.";
80
+ case "AGENT_NOT_ALLOWED":
81
+ 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.";
82
+ case "NOT_A_CHANNEL_MEMBER":
83
+ return "Only channel members can post (observers only read): use list_agent_channels, or ask an admin to add the agent to the channel.";
84
+ case "AGENT_PAUSED":
85
+ case "AGENT_RETIRED":
86
+ return "Only active agents can act: ask an admin to reactivate it in the dashboard.";
87
+ case "AGENT_RATE_LIMITED":
88
+ return "The agent is sending too fast: wait a minute before sending again.";
89
+ case "AGENT_THREAD_PAUSED": {
90
+ const why = body.reason === "ping_pong" ? " (two agents were going back and forth)" : body.reason === "duplicate_content" ? " (the same message kept being posted)" : "";
91
+ return `The loop guard paused this thread${why}: stop sending in it until a person replies or resumes it. Don't rephrase and retry.`;
92
+ }
93
+ case "HUMAN_TAKEOVER":
94
+ return `A person took over this thread: don't post in it until the takeover ends or they hand it back.${retryText(retryAt)}`;
95
+ case "POLICY_RATE_LIMITED":
96
+ case "POLICY_BUDGET_EXHAUSTED":
97
+ case "POLICY_OUTSIDE_WORKING_HOURS":
98
+ return `The agent's policy refuses this for now: wait, don't retry in a loop.${retryText(retryAt)}`;
99
+ case "POLICY_CHANNEL_NOT_ALLOWED":
100
+ case "POLICY_DM_NOT_ALLOWED":
101
+ case "POLICY_ASK_HUMAN_NOT_ALLOWED":
102
+ case "POLICY_URGENCY_NOT_ALLOWED":
103
+ case "POLICY_MAX_DEPTH":
104
+ 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.";
105
+ case "TASK_CLOSED":
106
+ return "The task is closed (completed, failed, canceled or rejected) and cannot change: create a new task instead.";
107
+ case "ALREADY_ASSIGNED":
108
+ return "The task is already assigned to that agent.";
109
+ case "AGENT_NOT_IN_CHANNEL":
110
+ 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.";
111
+ case "NOT_TASK_PARTICIPANT":
112
+ return "Only the task's assignee or creator can change it or hand it off.";
113
+ case "QUESTION_CLOSED":
114
+ return "The question is already closed (answered, expired or canceled): the first answer wins. Read it with get_answer.";
115
+ case "APPROVAL_ROLE_REQUIRED":
116
+ return "This approval needs a person with the required role: an agent cannot answer it.";
117
+ case "AGENT_ADMIN_KEY_REQUIRED":
118
+ return "This needs an unbound agents:admin key (not a key bound to agents): create one under SDK & Integration \u2192 API keys.";
119
+ case "INVALID_ANSWER":
120
+ return "Answer with one of the question's option ids (approve / deny for approvals), or text when free text is allowed.";
121
+ default:
122
+ return void 0;
123
+ }
124
+ }
125
+ function hintFor(status, apiMessage, code, body) {
126
+ const agent = agentHint(code, body);
127
+ if (agent) return `${apiMessage}. ${agent}`;
128
+ if (status === 400 && /agent_id is required/i.test(apiMessage)) {
129
+ return `${apiMessage}. Pass agentId (from list_agents), or set CHANNLIZE_AGENT_ID / --agent-id on the MCP server.`;
130
+ }
46
131
  switch (status) {
47
132
  case 401:
48
133
  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.`;
49
134
  case 403:
50
- 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;
135
+ return /permission/i.test(apiMessage) ? `${apiMessage}. This needs a server API key with the ${scopeFor(
136
+ apiMessage
137
+ )} scope: create one under SDK & Integration \u2192 API keys.` : apiMessage;
51
138
  case 404:
52
139
  return `${apiMessage}. Check the ID (and CHANNLIZE_PROJECT_ID): it must belong to the key's organization.`;
53
140
  case 429:
@@ -60,9 +147,15 @@ function toToolError(err) {
60
147
  if (err instanceof ToolError) return err;
61
148
  if (err instanceof import_core.ChannlizeError) {
62
149
  return new ToolError(
63
- err.statusCode ? hintFor(err.statusCode, err.message.replace(/\.$/, "")) : err.message,
150
+ err.statusCode ? hintFor(
151
+ err.statusCode,
152
+ err.message.replace(/\.$/, ""),
153
+ err.code,
154
+ err.details
155
+ ) : err.message,
64
156
  err.statusCode,
65
- err.code
157
+ err.code,
158
+ err.retryAt
66
159
  );
67
160
  }
68
161
  return new ToolError(err instanceof Error ? err.message : String(err));
@@ -80,6 +173,10 @@ var ChannlizeApi = class {
80
173
  get hasWidgetKey() {
81
174
  return !!this.config.widgetKey;
82
175
  }
176
+ /** The default agent for the agent tools (`CHANNLIZE_AGENT_ID`). */
177
+ get agentId() {
178
+ return this.config.agentId;
179
+ }
83
180
  requireServerKey() {
84
181
  if (!this.config.serverApiKey) {
85
182
  throw new ToolError(
@@ -88,9 +185,10 @@ var ChannlizeApi = class {
88
185
  }
89
186
  return this.config.serverApiKey;
90
187
  }
91
- async request(method, path, options = {}) {
188
+ async request(method, path2, options = {}) {
92
189
  const key = this.requireServerKey();
93
- const url2 = new URL(`${this.config.baseUrl}${path}`);
190
+ const timeout = options.timeout ?? this.config.timeout;
191
+ const url2 = new URL(`${this.config.baseUrl}${path2}`);
94
192
  for (const [k, v] of Object.entries(options.query ?? {})) {
95
193
  if (v !== void 0 && v !== "") url2.searchParams.set(k, String(v));
96
194
  }
@@ -106,13 +204,13 @@ var ChannlizeApi = class {
106
204
  },
107
205
  // oxlint-disable-next-line unicorn/no-invalid-fetch-options -- `method` is dynamic; GET calls never pass a body.
108
206
  body: options.body !== void 0 ? JSON.stringify(options.body) : void 0,
109
- signal: AbortSignal.timeout(this.config.timeout)
207
+ signal: AbortSignal.timeout(timeout)
110
208
  });
111
209
  } catch (err) {
112
210
  const e = err;
113
211
  if (e.name === "TimeoutError" || e.name === "AbortError") {
114
212
  throw new ToolError(
115
- `Channlize API timed out after ${this.config.timeout} ms (${method} ${url2.pathname}). Retry, or raise CHANNLIZE_TIMEOUT.`,
213
+ `Channlize API timed out after ${timeout} ms (${method} ${url2.pathname}). Retry, or raise CHANNLIZE_TIMEOUT.`,
116
214
  408,
117
215
  "TIMEOUT"
118
216
  );
@@ -122,28 +220,34 @@ var ChannlizeApi = class {
122
220
  );
123
221
  }
124
222
  const text = await res.text();
125
- let data = void 0;
223
+ let data2 = void 0;
126
224
  if (text) {
127
225
  try {
128
- data = JSON.parse(text);
226
+ data2 = JSON.parse(text);
129
227
  } catch {
130
- data = void 0;
228
+ data2 = void 0;
131
229
  }
132
230
  }
133
231
  if (!res.ok) {
134
- const { message, code } = (0, import_core.parseApiError)(res.status, data, res.statusText);
232
+ const { message: message2, code, body } = (0, import_core.parseApiError)(
233
+ res.status,
234
+ data2,
235
+ res.statusText
236
+ );
237
+ const retryAt = typeof body.retryAt === "string" ? body.retryAt : void 0;
135
238
  throw new ToolError(
136
- hintFor(res.status, message.replace(/\.$/, "")),
239
+ hintFor(res.status, message2.replace(/\.$/, ""), code, body),
137
240
  res.status,
138
- code
241
+ code,
242
+ retryAt
139
243
  );
140
244
  }
141
- if (data === void 0) {
245
+ if (data2 === void 0) {
142
246
  throw new ToolError(
143
247
  `Unexpected non-JSON response from ${method} ${url2.pathname}`
144
248
  );
145
249
  }
146
- return data;
250
+ return data2;
147
251
  }
148
252
  /**
149
253
  * `CHANNLIZE_PROJECT_ID`, or the first project of the key's organization
@@ -199,11 +303,12 @@ var ChannlizeApi = class {
199
303
  // src/config.ts
200
304
  var import_core2 = require("@channlize/core");
201
305
  var ConfigError = class extends Error {
202
- constructor(message) {
203
- super(message);
306
+ constructor(message2) {
307
+ super(message2);
204
308
  this.name = "ConfigError";
205
309
  }
206
310
  };
311
+ var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
207
312
  function clean(value) {
208
313
  const v = value?.trim();
209
314
  return v ? v : void 0;
@@ -248,17 +353,33 @@ function resolveConfig(config) {
248
353
  `Invalid base URL "${config.baseUrl}": use e.g. ${import_core2.DEFAULT_BASE_URL}`
249
354
  );
250
355
  }
356
+ const agentId2 = clean(config.agentId);
357
+ if (agentId2 && !UUID.test(agentId2)) {
358
+ throw new ConfigError(
359
+ `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.`
360
+ );
361
+ }
251
362
  return {
252
363
  serverApiKey,
253
364
  widgetKey,
254
365
  projectId: clean(config.projectId),
366
+ agentId: agentId2,
255
367
  baseUrl,
256
368
  timeout
257
369
  };
258
370
  }
259
371
  function configFromEnv(env = process.env) {
260
- const { timeout, ...rest } = (0, import_core2.readChannlizeEnv)(env);
261
- return { ...rest, timeout: timeout ? Number(timeout) : void 0 };
372
+ const { timeout, serverApiKey, widgetKey, apiKey, projectId, baseUrl } = (0, import_core2.readChannlizeEnv)(env);
373
+ return {
374
+ serverApiKey,
375
+ widgetKey,
376
+ apiKey,
377
+ projectId,
378
+ baseUrl,
379
+ timeout: timeout ? Number(timeout) : void 0,
380
+ // Read here rather than from core, so older @channlize/core versions work.
381
+ agentId: clean(env.CHANNLIZE_AGENT_ID)
382
+ };
262
383
  }
263
384
 
264
385
  // src/prompts.ts
@@ -438,12 +559,12 @@ function registerServerPrompts(server) {
438
559
  },
439
560
  ({ status, limit }) => user(`Triage my Channlize support inbox.
440
561
 
441
- 1. Call list_conversations with status "${status || "open"}" and limit ${Number(limit) || 10}.
562
+ 1. Call list_conversations with status ["${status || "open"}"] and limit ${Number(limit) || 10}.
442
563
  2. For each conversation, call get_conversation to read the thread.
443
564
  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.
444
565
  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.
445
566
 
446
- 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.`)
567
+ 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.`)
447
568
  );
448
569
  server.registerPrompt(
449
570
  "summarize-conversation",
@@ -454,8 +575,8 @@ Replies and status or priority changes are made by the team in the Slack thread
454
575
  conversationId: z.string().describe("Conversation ID")
455
576
  })
456
577
  },
457
- ({ conversationId }) => user(
458
- `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.`
578
+ ({ conversationId: conversationId2 }) => user(
579
+ `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.`
459
580
  )
460
581
  );
461
582
  server.registerPrompt(
@@ -586,14 +707,1240 @@ function registerResources(server, api) {
586
707
  }
587
708
 
588
709
  // src/tools.ts
589
- var z2 = __toESM(require("zod/v4"));
710
+ var z4 = __toESM(require("zod/v4"));
590
711
  var import_core3 = require("@channlize/core");
591
- var STATUSES = ["open", "pending", "resolved", "closed"];
592
- var PRIORITIES = ["low", "normal", "high", "urgent"];
593
- function ok(data) {
712
+
713
+ // src/agents.ts
714
+ var z2 = __toESM(require("zod/v4"));
715
+ function defineTool(tool) {
716
+ return tool;
717
+ }
718
+ var AGENT_TASK_STATUSES = [
719
+ "open",
720
+ "working",
721
+ "input_required",
722
+ "completed",
723
+ "failed",
724
+ "canceled",
725
+ "rejected"
726
+ ];
727
+ var uuid = (what) => z2.string().uuid().describe(what);
728
+ var agentId = uuid(
729
+ "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."
730
+ ).optional();
731
+ var channelId = uuid("Agent channel ID (from list_agent_channels)");
732
+ var threadId = uuid(
733
+ "Reply in this thread: the id of any message in it (thread_id or id from read_agent_inbox)"
734
+ ).optional();
735
+ var mentions = z2.array(z2.string().uuid()).max(50).optional().describe("Agent IDs to mention (from list_agents)");
736
+ var data = z2.record(z2.string(), z2.unknown()).optional().describe("Structured data for the recipients (JSON object)");
737
+ var usage = {
738
+ tokens: z2.number().int().min(0).optional().describe("Tokens you used for this message (reporting)"),
739
+ cost: z2.number().min(0).optional().describe("What this message cost you, in USD (reporting)")
740
+ };
741
+ var message = z2.looseObject({
742
+ id: z2.string(),
743
+ channel_id: z2.string(),
744
+ thread_id: z2.string().nullable(),
745
+ type: z2.string(),
746
+ text: z2.string(),
747
+ sender: z2.looseObject({ kind: z2.string() }),
748
+ task_status: z2.string().nullable().optional()
749
+ });
750
+ var sendOutput = z2.object({
751
+ message,
752
+ deliveries: z2.array(
753
+ z2.looseObject({ id: z2.string(), agent_id: z2.string(), status: z2.string() })
754
+ )
755
+ });
756
+ var dueAt = z2.string().max(40).optional().describe("Due date: an ISO date (2026-11-30) or date-time");
757
+ var task = z2.looseObject({
758
+ id: z2.string(),
759
+ channel_id: z2.string(),
760
+ text: z2.string(),
761
+ board_status: z2.string(),
762
+ assignee_agent_id: z2.string().nullable(),
763
+ due_at: z2.string().nullable()
764
+ });
765
+ var deliveries = z2.array(
766
+ z2.looseObject({ id: z2.string(), agent_id: z2.string(), status: z2.string() })
767
+ );
768
+ var question = z2.looseObject({
769
+ id: z2.string(),
770
+ kind: z2.string(),
771
+ question: z2.string(),
772
+ status: z2.string(),
773
+ answer: z2.looseObject({}).nullable()
774
+ });
775
+ var questionId = uuid("The question ID (from ask_human or list_questions)");
776
+ var BOARD_STATUSES = [
777
+ "open",
778
+ "in_progress",
779
+ "blocked",
780
+ "done",
781
+ "failed"
782
+ ];
783
+ var QUESTION_WAIT_MAX_SECONDS = 25;
784
+ var READ = {
785
+ readOnlyHint: true,
786
+ destructiveHint: false,
787
+ idempotentHint: true,
788
+ openWorldHint: false
789
+ };
790
+ var SEND = {
791
+ readOnlyHint: false,
792
+ destructiveHint: false,
793
+ idempotentHint: false,
794
+ openWorldHint: true
795
+ };
796
+ function actingAs(api, id2) {
797
+ return id2 ?? api.agentId;
798
+ }
799
+ function requireAgent(api, id2) {
800
+ const agent = actingAs(api, id2);
801
+ if (!agent) {
802
+ throw new ToolError(
803
+ "Pass agentId (from list_agents), or set CHANNLIZE_AGENT_ID / --agent-id on the MCP server."
804
+ );
805
+ }
806
+ return agent;
807
+ }
808
+ async function send(api, body) {
809
+ const r = await api.request(
810
+ "POST",
811
+ "/v1/agents/messages",
812
+ { body }
813
+ );
814
+ return { message: r.message, deliveries: r.deliveries ?? [] };
815
+ }
816
+ var enc = encodeURIComponent;
817
+ function outcomeMessage(status, q) {
818
+ const answer = q.answer ?? {};
819
+ const choice = answer.option_label ?? answer.option_id;
820
+ const comment = answer.comment ? `: ${String(answer.comment)}` : "";
821
+ switch (status) {
822
+ case "answered":
823
+ if (q.kind === "approval") {
824
+ return answer.approved ? `Approved${comment}. Go ahead.` : `Denied${comment}. Don't do it.`;
825
+ }
826
+ return `Answered: ${[choice, answer.text].filter(Boolean).join(" / ") || "(empty)"}.`;
827
+ case "expired_default":
828
+ return `Nobody answered by the deadline: the default option applies (${String(choice ?? "none")}).`;
829
+ case "expired":
830
+ 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.";
831
+ case "canceled":
832
+ return "The question was canceled.";
833
+ default:
834
+ return `Status: ${status}.`;
835
+ }
836
+ }
837
+ var AGENT_TOOLS = [
838
+ defineTool({
839
+ name: "send_agent_message",
840
+ title: "Send agent message",
841
+ 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.",
842
+ scope: "agents:send",
843
+ endpoint: "POST /v1/agents/messages",
844
+ inputSchema: z2.object({
845
+ agentId,
846
+ channelId,
847
+ text: z2.string().min(1).max(4e4).describe("Message text"),
848
+ threadId,
849
+ mentions,
850
+ data,
851
+ ...usage
852
+ }),
853
+ outputSchema: sendOutput,
854
+ annotations: SEND,
855
+ handler: (api, a) => send(api, {
856
+ agent_id: actingAs(api, a.agentId),
857
+ channel_id: a.channelId,
858
+ type: "message",
859
+ text: a.text,
860
+ thread_id: a.threadId,
861
+ mentions: a.mentions,
862
+ data: a.data,
863
+ tokens: a.tokens,
864
+ cost: a.cost
865
+ })
866
+ }),
867
+ defineTool({
868
+ name: "create_task",
869
+ title: "Create task",
870
+ 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.",
871
+ scope: "agents:send",
872
+ endpoint: "POST /v1/agents/tasks",
873
+ inputSchema: z2.object({
874
+ agentId,
875
+ channelId,
876
+ text: z2.string().min(1).max(4e4).describe("What should be done, with enough context to do it"),
877
+ assigneeAgentId: uuid(
878
+ "The agent that should do it: a member of the channel (from list_agents)"
879
+ ).optional(),
880
+ dueAt,
881
+ threadId,
882
+ mentions,
883
+ data
884
+ }),
885
+ // `message` is the task too (a task is its `task` message plus board fields).
886
+ outputSchema: z2.object({ taskId: z2.string(), task, message, deliveries }),
887
+ annotations: SEND,
888
+ handler: async (api, a) => {
889
+ const r = await api.request(
890
+ "POST",
891
+ "/v1/agents/tasks",
892
+ {
893
+ body: {
894
+ agent_id: actingAs(api, a.agentId),
895
+ channel_id: a.channelId,
896
+ text: a.text,
897
+ assignee_agent_id: a.assigneeAgentId,
898
+ due_at: a.dueAt,
899
+ thread_id: a.threadId,
900
+ mentions: a.mentions,
901
+ data: a.data
902
+ }
903
+ }
904
+ );
905
+ return {
906
+ taskId: String(r.task.id),
907
+ task: r.task,
908
+ message: r.task,
909
+ deliveries: r.deliveries ?? []
910
+ };
911
+ }
912
+ }),
913
+ defineTool({
914
+ name: "update_task_status",
915
+ title: "Update task status",
916
+ 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.",
917
+ scope: "agents:send",
918
+ endpoint: "POST /v1/agents/messages",
919
+ inputSchema: z2.object({
920
+ agentId,
921
+ channelId,
922
+ taskId: uuid("The task message ID"),
923
+ status: z2.enum(AGENT_TASK_STATUSES).describe("The new status of the task"),
924
+ text: z2.string().max(4e4).optional().describe("What changed, e.g. the result or what input is needed"),
925
+ data,
926
+ ...usage
927
+ }),
928
+ outputSchema: sendOutput,
929
+ annotations: SEND,
930
+ handler: (api, a) => send(api, {
931
+ agent_id: actingAs(api, a.agentId),
932
+ channel_id: a.channelId,
933
+ type: "status",
934
+ text: a.text ?? "",
935
+ task_id: a.taskId,
936
+ task_status: a.status,
937
+ data: a.data,
938
+ tokens: a.tokens,
939
+ cost: a.cost
940
+ })
941
+ }),
942
+ defineTool({
943
+ name: "update_task",
944
+ title: "Update task",
945
+ 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.",
946
+ scope: "agents:send",
947
+ endpoint: "PATCH /v1/agents/tasks/:taskId",
948
+ inputSchema: z2.object({
949
+ agentId,
950
+ taskId: uuid("The task ID"),
951
+ status: z2.enum(BOARD_STATUSES).optional().describe("The board column"),
952
+ dueAt: z2.string().max(40).nullable().optional().describe("New due date (ISO date or date-time); null clears it"),
953
+ note: z2.string().max(2e3).optional().describe("What changed, shown with the update")
954
+ }),
955
+ outputSchema: z2.object({ task, changed: z2.boolean() }),
956
+ annotations: SEND,
957
+ handler: async (api, a) => {
958
+ if (a.status === void 0 && a.dueAt === void 0) {
959
+ throw new ToolError("Pass status or dueAt.");
960
+ }
961
+ const r = await api.request(
962
+ "PATCH",
963
+ `/v1/agents/tasks/${enc(a.taskId)}`,
964
+ {
965
+ body: {
966
+ agent_id: actingAs(api, a.agentId),
967
+ status: a.status,
968
+ due_at: a.dueAt,
969
+ note: a.note
970
+ }
971
+ }
972
+ );
973
+ return { task: r.task, changed: Boolean(r.changed) };
974
+ }
975
+ }),
976
+ defineTool({
977
+ name: "handoff_task",
978
+ title: "Hand off task",
979
+ 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.",
980
+ scope: "agents:send",
981
+ endpoint: "POST /v1/agents/tasks/:taskId/handoff",
982
+ inputSchema: z2.object({
983
+ agentId,
984
+ taskId: uuid("The task ID"),
985
+ toAgentId: uuid("The new assignee (from list_agents or get_org_chart)"),
986
+ reason: z2.string().max(2e3).optional().describe("Why, and what the new assignee needs to know")
987
+ }),
988
+ outputSchema: z2.object({ task, deliveries }),
989
+ annotations: SEND,
990
+ handler: async (api, a) => {
991
+ const r = await api.request(
992
+ "POST",
993
+ `/v1/agents/tasks/${enc(a.taskId)}/handoff`,
994
+ {
995
+ body: {
996
+ agent_id: actingAs(api, a.agentId),
997
+ to_agent_id: a.toAgentId,
998
+ reason: a.reason
999
+ }
1000
+ }
1001
+ );
1002
+ return {
1003
+ task: r.task,
1004
+ deliveries: r.deliveries ?? []
1005
+ };
1006
+ }
1007
+ }),
1008
+ defineTool({
1009
+ name: "list_tasks",
1010
+ title: "List tasks",
1011
+ 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.",
1012
+ scope: "agents:read",
1013
+ endpoint: "GET /v1/agents/tasks",
1014
+ inputSchema: z2.object({
1015
+ agentId,
1016
+ channelId: channelId.optional(),
1017
+ assigneeAgentId: uuid("Only tasks assigned to this agent").optional(),
1018
+ status: z2.enum(BOARD_STATUSES).optional(),
1019
+ limit: z2.number().int().min(1).max(500).default(50).describe("How many to return (1-500, default 50)")
1020
+ }),
1021
+ outputSchema: z2.object({ tasks: z2.array(task) }),
1022
+ annotations: READ,
1023
+ handler: async (api, a) => {
1024
+ const r = await api.request(
1025
+ "GET",
1026
+ "/v1/agents/tasks",
1027
+ {
1028
+ query: {
1029
+ agent_id: actingAs(api, a.agentId),
1030
+ channel_id: a.channelId,
1031
+ assignee_agent_id: a.assigneeAgentId,
1032
+ status: a.status,
1033
+ limit: a.limit
1034
+ }
1035
+ }
1036
+ );
1037
+ return { tasks: r.tasks ?? [] };
1038
+ }
1039
+ }),
1040
+ defineTool({
1041
+ name: "get_task_board",
1042
+ title: "Get task board",
1043
+ 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.",
1044
+ scope: "agents:read",
1045
+ endpoint: "GET /v1/agents/tasks/board",
1046
+ inputSchema: z2.object({
1047
+ agentId,
1048
+ channelId,
1049
+ assigneeAgentId: uuid("Only tasks assigned to this agent").optional()
1050
+ }),
1051
+ outputSchema: z2.object({
1052
+ channel_id: z2.string(),
1053
+ columns: z2.record(z2.string(), z2.array(task)),
1054
+ counts: z2.record(z2.string(), z2.number()),
1055
+ agents: z2.array(z2.looseObject({ id: z2.string() })),
1056
+ truncated: z2.boolean()
1057
+ }),
1058
+ annotations: READ,
1059
+ handler: async (api, a) => await api.request("GET", "/v1/agents/tasks/board", {
1060
+ query: {
1061
+ agent_id: actingAs(api, a.agentId),
1062
+ channel_id: a.channelId,
1063
+ assignee_agent_id: a.assigneeAgentId
1064
+ }
1065
+ })
1066
+ }),
1067
+ defineTool({
1068
+ name: "ask_human",
1069
+ title: "Ask a human",
1070
+ 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.",
1071
+ scope: "agents:ask_human",
1072
+ endpoint: "POST /v1/agents/questions",
1073
+ inputSchema: z2.object({
1074
+ agentId,
1075
+ kind: z2.enum(["question", "approval"]).default("question").describe("question (default) or approval (answered Approve / Deny)"),
1076
+ question: z2.string().min(1).max(3e3).describe("The question, with what people need to answer it"),
1077
+ options: z2.array(
1078
+ z2.object({
1079
+ id: z2.string().min(1).max(100),
1080
+ label: z2.string().min(1).max(75)
1081
+ })
1082
+ ).max(10).optional().describe("Up to 10 answers to pick from (ignored for approvals)"),
1083
+ freeText: z2.boolean().optional().describe("Allow a typed answer (always on without options)"),
1084
+ urgency: z2.enum(["low", "normal", "high", "urgent"]).optional().describe("How fast it escalates (default normal)"),
1085
+ deadline: z2.string().max(40).optional().describe("ISO date-time, at most 30 days away"),
1086
+ defaultOption: z2.string().max(100).optional().describe("Option id applied at the deadline when nobody answered"),
1087
+ channelId: channelId.optional().describe("Post it in this agent channel (from list_agent_channels)"),
1088
+ threadId,
1089
+ context: z2.record(z2.string(), z2.unknown()).optional().describe("Facts shown with the question (JSON object)"),
1090
+ amount: z2.number().min(0).optional().describe("Approvals: the amount at stake"),
1091
+ currency: z2.string().regex(/^[A-Za-z]{3}$/).optional().describe("Approvals: ISO 4217 currency code"),
1092
+ resource: z2.record(z2.string(), z2.unknown()).optional().describe("Approvals: what is being approved (JSON object)"),
1093
+ requiredRoles: z2.array(z2.string().min(1).max(40)).max(10).optional().describe('Approvals: roles that may answer, e.g. ["admin"]')
1094
+ }),
1095
+ outputSchema: z2.object({ questionId: z2.string(), question }),
1096
+ annotations: SEND,
1097
+ handler: async (api, a) => {
1098
+ const r = await api.request(
1099
+ "POST",
1100
+ "/v1/agents/questions",
1101
+ {
1102
+ body: {
1103
+ agent_id: actingAs(api, a.agentId),
1104
+ kind: a.kind,
1105
+ question: a.question,
1106
+ options: a.options,
1107
+ free_text: a.freeText,
1108
+ urgency: a.urgency,
1109
+ deadline: a.deadline,
1110
+ default_option: a.defaultOption,
1111
+ channel_id: a.channelId,
1112
+ thread_id: a.threadId,
1113
+ context: a.context,
1114
+ amount: a.amount,
1115
+ currency: a.currency,
1116
+ resource: a.resource,
1117
+ required_roles: a.requiredRoles
1118
+ }
1119
+ }
1120
+ );
1121
+ return {
1122
+ questionId: String(r.question.id),
1123
+ question: r.question
1124
+ };
1125
+ }
1126
+ }),
1127
+ defineTool({
1128
+ name: "get_answer",
1129
+ title: "Get answer",
1130
+ 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).`,
1131
+ scope: "agents:ask_human",
1132
+ endpoint: "GET /v1/agents/questions/:id/wait",
1133
+ inputSchema: z2.object({
1134
+ agentId,
1135
+ questionId,
1136
+ waitSeconds: z2.number().int().min(0).max(QUESTION_WAIT_MAX_SECONDS).default(QUESTION_WAIT_MAX_SECONDS).describe(
1137
+ `Seconds to wait for an answer (0-${QUESTION_WAIT_MAX_SECONDS}, default ${QUESTION_WAIT_MAX_SECONDS}); 0 only checks`
1138
+ )
1139
+ }),
1140
+ outputSchema: z2.object({
1141
+ questionId: z2.string(),
1142
+ status: z2.string(),
1143
+ waiting: z2.boolean(),
1144
+ answer: z2.looseObject({}).nullable(),
1145
+ message: z2.string(),
1146
+ question
1147
+ }),
1148
+ annotations: READ,
1149
+ handler: async (api, a) => {
1150
+ const r = await api.request(
1151
+ "GET",
1152
+ `/v1/agents/questions/${enc(a.questionId)}/wait`,
1153
+ {
1154
+ query: {
1155
+ agent_id: actingAs(api, a.agentId),
1156
+ timeout: a.waitSeconds
1157
+ },
1158
+ // The API holds the request for up to waitSeconds.
1159
+ timeout: (a.waitSeconds + 10) * 1e3
1160
+ }
1161
+ );
1162
+ const status = String(r.question.status);
1163
+ const waiting = status === "open";
1164
+ return {
1165
+ questionId: a.questionId,
1166
+ status,
1167
+ waiting,
1168
+ answer: r.question.answer ?? null,
1169
+ 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),
1170
+ question: r.question
1171
+ };
1172
+ }
1173
+ }),
1174
+ defineTool({
1175
+ name: "list_questions",
1176
+ title: "List questions",
1177
+ 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).",
1178
+ scope: "agents:read",
1179
+ endpoint: "GET /v1/agents/questions",
1180
+ inputSchema: z2.object({
1181
+ agentId,
1182
+ status: z2.enum(["open", "answered", "expired_default", "expired", "canceled"]).optional(),
1183
+ kind: z2.enum(["question", "approval"]).optional(),
1184
+ channelId: channelId.optional(),
1185
+ cursor: z2.string().max(300).optional().describe("nextCursor of the previous call"),
1186
+ limit: z2.number().int().min(1).max(200).default(20).describe("How many to return (1-200, default 20)")
1187
+ }),
1188
+ outputSchema: z2.object({
1189
+ questions: z2.array(question),
1190
+ nextCursor: z2.string().nullable()
1191
+ }),
1192
+ annotations: READ,
1193
+ handler: async (api, a) => {
1194
+ const r = await api.request("GET", "/v1/agents/questions", {
1195
+ query: {
1196
+ agent_id: actingAs(api, a.agentId),
1197
+ status: a.status,
1198
+ kind: a.kind,
1199
+ channel_id: a.channelId,
1200
+ cursor: a.cursor,
1201
+ limit: a.limit
1202
+ }
1203
+ });
1204
+ return {
1205
+ questions: r.questions ?? [],
1206
+ nextCursor: r.next_cursor ?? null
1207
+ };
1208
+ }
1209
+ }),
1210
+ defineTool({
1211
+ name: "cancel_question",
1212
+ title: "Cancel question",
1213
+ 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.",
1214
+ scope: "agents:ask_human",
1215
+ endpoint: "DELETE /v1/agents/questions/:id",
1216
+ inputSchema: z2.object({ agentId, questionId }),
1217
+ outputSchema: z2.object({ question }),
1218
+ annotations: {
1219
+ readOnlyHint: false,
1220
+ destructiveHint: true,
1221
+ idempotentHint: false,
1222
+ openWorldHint: true
1223
+ },
1224
+ handler: async (api, a) => {
1225
+ const r = await api.request(
1226
+ "DELETE",
1227
+ `/v1/agents/questions/${enc(a.questionId)}`,
1228
+ { query: { agent_id: actingAs(api, a.agentId) } }
1229
+ );
1230
+ return { question: r.question };
1231
+ }
1232
+ }),
1233
+ defineTool({
1234
+ name: "answer_escalated_question",
1235
+ title: "Answer escalated question",
1236
+ 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.",
1237
+ scope: "agents:send",
1238
+ endpoint: "POST /v1/agents/questions/:id/answer",
1239
+ inputSchema: z2.object({
1240
+ agentId,
1241
+ questionId,
1242
+ optionId: z2.string().min(1).max(100).optional().describe("One of the question options (approve / deny for approvals)"),
1243
+ text: z2.string().max(3e3).optional().describe("A typed answer, when the question allows free text"),
1244
+ comment: z2.string().max(2e3).optional().describe("Why (shown with the answer; say why on a deny)")
1245
+ }),
1246
+ outputSchema: z2.object({ question }),
1247
+ annotations: SEND,
1248
+ handler: async (api, a) => {
1249
+ if (!a.optionId && !a.text) throw new ToolError("Pass optionId or text.");
1250
+ const r = await api.request(
1251
+ "POST",
1252
+ `/v1/agents/questions/${enc(a.questionId)}/answer`,
1253
+ {
1254
+ body: {
1255
+ agent_id: actingAs(api, a.agentId),
1256
+ option_id: a.optionId,
1257
+ text: a.text,
1258
+ comment: a.comment
1259
+ }
1260
+ }
1261
+ );
1262
+ return { question: r.question };
1263
+ }
1264
+ }),
1265
+ defineTool({
1266
+ name: "get_org_chart",
1267
+ title: "Get org chart",
1268
+ 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.",
1269
+ scope: "agents:read",
1270
+ endpoint: "GET /v1/agents/org-chart",
1271
+ inputSchema: z2.object({
1272
+ teamId: uuid("Only this team").optional(),
1273
+ channelId: uuid("Only the agents of this channel").optional(),
1274
+ includeRetired: z2.boolean().optional().describe("Include retired agents (default false)")
1275
+ }),
1276
+ outputSchema: z2.object({
1277
+ agents: z2.array(z2.looseObject({ id: z2.string() })),
1278
+ users: z2.array(z2.looseObject({ id: z2.string() })),
1279
+ teams: z2.array(z2.looseObject({ id: z2.string() })),
1280
+ tree: z2.array(z2.looseObject({}))
1281
+ }),
1282
+ annotations: READ,
1283
+ handler: async (api, a) => await api.request("GET", "/v1/agents/org-chart", {
1284
+ query: {
1285
+ team_id: a.teamId,
1286
+ channel_id: a.channelId,
1287
+ include_retired: a.includeRetired ? "true" : void 0
1288
+ }
1289
+ })
1290
+ }),
1291
+ defineTool({
1292
+ name: "get_effective_policy",
1293
+ title: "Get effective policy",
1294
+ 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.",
1295
+ scope: "agents:admin",
1296
+ endpoint: "GET /v1/agents/policies/preview",
1297
+ inputSchema: z2.object({
1298
+ agentId: uuid(
1299
+ "The agent (from list_agents). Default: the server agent (CHANNLIZE_AGENT_ID)"
1300
+ ).optional(),
1301
+ channelId: channelId.optional()
1302
+ }),
1303
+ outputSchema: z2.looseObject({
1304
+ agent_id: z2.string(),
1305
+ channel_id: z2.string().nullable(),
1306
+ rules: z2.looseObject({}),
1307
+ working_hours: z2.looseObject({}),
1308
+ usage: z2.looseObject({}),
1309
+ checks: z2.looseObject({}).nullable()
1310
+ }),
1311
+ annotations: READ,
1312
+ handler: async (api, a) => await api.request("GET", "/v1/agents/policies/preview", {
1313
+ query: {
1314
+ agent_id: requireAgent(api, a.agentId),
1315
+ channel_id: a.channelId
1316
+ }
1317
+ })
1318
+ }),
1319
+ defineTool({
1320
+ name: "read_agent_inbox",
1321
+ title: "Read agent inbox",
1322
+ 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.",
1323
+ scope: "agents:read",
1324
+ endpoint: "GET /v1/agents/:id/inbox",
1325
+ inputSchema: z2.object({
1326
+ agentId,
1327
+ cursor: z2.string().max(200).optional().describe("Read after this cursor (nextCursor of the previous call)"),
1328
+ limit: z2.number().int().min(1).max(200).default(20).describe("How many to return (1-200, default 20)")
1329
+ }),
1330
+ outputSchema: z2.object({
1331
+ agentId: z2.string(),
1332
+ messages: z2.array(
1333
+ z2.looseObject({
1334
+ delivery_id: z2.string(),
1335
+ cursor: z2.string(),
1336
+ message
1337
+ })
1338
+ ),
1339
+ nextCursor: z2.string().nullable(),
1340
+ hasMore: z2.boolean()
1341
+ }),
1342
+ annotations: READ,
1343
+ handler: async (api, a) => {
1344
+ const id2 = requireAgent(api, a.agentId);
1345
+ const r = await api.request("GET", `/v1/agents/${enc(id2)}/inbox`, {
1346
+ query: { cursor: a.cursor, limit: a.limit }
1347
+ });
1348
+ return {
1349
+ agentId: id2,
1350
+ messages: r.messages ?? [],
1351
+ nextCursor: r.next_cursor ?? null,
1352
+ hasMore: Boolean(r.has_more)
1353
+ };
1354
+ }
1355
+ }),
1356
+ defineTool({
1357
+ name: "ack_agent_messages",
1358
+ title: "Acknowledge agent messages",
1359
+ 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.",
1360
+ scope: "agents:read",
1361
+ endpoint: "POST /v1/agents/:id/inbox/ack",
1362
+ inputSchema: z2.object({
1363
+ agentId,
1364
+ upTo: z2.string().uuid().optional().describe("Ack everything up to and including this delivery_id"),
1365
+ ids: z2.array(z2.string().uuid()).min(1).max(500).optional().describe("Ack these delivery (or message) IDs")
1366
+ }),
1367
+ outputSchema: z2.object({ acked: z2.number() }),
1368
+ annotations: {
1369
+ readOnlyHint: false,
1370
+ destructiveHint: false,
1371
+ idempotentHint: true,
1372
+ openWorldHint: false
1373
+ },
1374
+ handler: async (api, a) => {
1375
+ if (!a.upTo === !a.ids) {
1376
+ throw new ToolError("Pass either upTo or ids.");
1377
+ }
1378
+ const id2 = requireAgent(api, a.agentId);
1379
+ const r = await api.request(
1380
+ "POST",
1381
+ `/v1/agents/${enc(id2)}/inbox/ack`,
1382
+ { body: a.upTo ? { up_to: a.upTo } : { ids: a.ids } }
1383
+ );
1384
+ return { acked: Number(r.acked ?? 0) };
1385
+ }
1386
+ }),
1387
+ defineTool({
1388
+ name: "list_agents",
1389
+ title: "List agents",
1390
+ 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.",
1391
+ scope: "agents:read",
1392
+ endpoint: "GET /v1/agents",
1393
+ inputSchema: z2.object({
1394
+ includeRetired: z2.boolean().optional().describe("Include retired agents (default false)")
1395
+ }),
1396
+ outputSchema: z2.object({
1397
+ agents: z2.array(
1398
+ z2.looseObject({
1399
+ id: z2.string(),
1400
+ slug: z2.string(),
1401
+ name: z2.string(),
1402
+ status: z2.string()
1403
+ })
1404
+ )
1405
+ }),
1406
+ annotations: READ,
1407
+ handler: async (api, a) => {
1408
+ const r = await api.request("GET", "/v1/agents", {
1409
+ query: { include_retired: a.includeRetired || void 0 }
1410
+ });
1411
+ return { agents: r.agents ?? [] };
1412
+ }
1413
+ }),
1414
+ defineTool({
1415
+ name: "list_agent_channels",
1416
+ title: "List agent channels",
1417
+ 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.",
1418
+ scope: "agents:read",
1419
+ endpoint: "GET /v1/agents/channels",
1420
+ inputSchema: z2.object({
1421
+ includeArchived: z2.boolean().optional().describe("Include archived channels (default false)")
1422
+ }),
1423
+ outputSchema: z2.object({
1424
+ channels: z2.array(
1425
+ z2.looseObject({
1426
+ id: z2.string(),
1427
+ slug: z2.string(),
1428
+ name: z2.string(),
1429
+ archived: z2.boolean()
1430
+ })
1431
+ )
1432
+ }),
1433
+ annotations: READ,
1434
+ handler: async (api, a) => {
1435
+ const r = await api.request(
1436
+ "GET",
1437
+ "/v1/agents/channels",
1438
+ { query: { include_archived: a.includeArchived || void 0 } }
1439
+ );
1440
+ return { channels: r.channels ?? [] };
1441
+ }
1442
+ })
1443
+ ];
1444
+ var AGENT_TOOL_NAMES = AGENT_TOOLS.map((t) => t.name);
1445
+
1446
+ // src/inbox.ts
1447
+ var z3 = __toESM(require("zod/v4"));
1448
+ function defineTool2(tool) {
1449
+ return tool;
1450
+ }
1451
+ var CONVERSATION_STATUSES = [
1452
+ "open",
1453
+ "pending",
1454
+ "resolved",
1455
+ "closed"
1456
+ ];
1457
+ var CONVERSATION_PRIORITIES = [
1458
+ "low",
1459
+ "normal",
1460
+ "high",
1461
+ "urgent"
1462
+ ];
1463
+ var CONVERSATION_SORTS = [
1464
+ "recent",
1465
+ "oldest",
1466
+ "newest",
1467
+ "priority"
1468
+ ];
1469
+ var loose = z3.looseObject({});
1470
+ var id = (what) => z3.string().uuid().describe(`${what} ID`);
1471
+ var conversationId = id(
1472
+ "Conversation (from list_conversations or search_conversations)"
1473
+ );
1474
+ var person = z3.looseObject({
1475
+ id: z3.string(),
1476
+ name: z3.string().nullable().optional(),
1477
+ email: z3.string().nullable().optional()
1478
+ }).nullable();
1479
+ var conversationSummary = z3.looseObject({
1480
+ id: z3.string(),
1481
+ subject: z3.string().nullable().optional(),
1482
+ status: z3.string(),
1483
+ priority: z3.string().optional(),
1484
+ source: z3.string().nullable().optional(),
1485
+ tags: z3.array(z3.string()).optional(),
1486
+ customer: person.optional(),
1487
+ assignee: person.optional(),
1488
+ triage: z3.record(z3.string(), z3.unknown()).nullable().optional(),
1489
+ needsReply: z3.boolean().optional(),
1490
+ lastActivityAt: z3.string().nullable().optional()
1491
+ });
1492
+ var page = {
1493
+ total: z3.number(),
1494
+ limit: z3.number(),
1495
+ offset: z3.number(),
1496
+ hasMore: z3.boolean()
1497
+ };
1498
+ var listOutput = z3.object({
1499
+ conversations: z3.array(conversationSummary),
1500
+ ...page
1501
+ });
1502
+ var changeOutput = z3.object({
1503
+ conversation: z3.looseObject({ id: z3.string(), status: z3.string() }),
1504
+ changes: z3.array(z3.string())
1505
+ });
1506
+ var slackOutcome = z3.string().describe(
1507
+ "Slack mirror: queued, posted, no_thread (not in Slack), not_connected or failed"
1508
+ );
1509
+ var tags = z3.array(z3.string().trim().min(1).max(50)).max(20);
1510
+ var paging = {
1511
+ limit: z3.number().int().min(1).max(100).default(20).describe("How many to return (1-100, default 20)"),
1512
+ offset: z3.number().int().min(0).default(0).describe("Skip this many")
1513
+ };
1514
+ function oneOrMany(values) {
1515
+ return z3.union([z3.enum(values), z3.array(z3.enum(values)).max(10)]).optional();
1516
+ }
1517
+ var asList = (v) => v === void 0 ? void 0 : Array.isArray(v) ? v.join(",") : v;
1518
+ var listFilters = {
1519
+ status: oneOrMany(CONVERSATION_STATUSES).describe(
1520
+ 'Only these statuses: "open" or a list like ["open", "pending"]'
1521
+ ),
1522
+ priority: oneOrMany(CONVERSATION_PRIORITIES).describe(
1523
+ 'Only these priorities: "urgent" or a list'
1524
+ ),
1525
+ assignee: z3.string().max(255).optional().describe('A teammate (user ID or email), "unassigned" or "assigned"'),
1526
+ projectId: id("Project").optional(),
1527
+ updatedSince: z3.iso.datetime({ offset: true }).optional().describe("Updated or with a new message since (ISO 8601)"),
1528
+ tag: z3.string().max(50).optional().describe("Carrying this tag"),
1529
+ source: z3.string().max(32).optional().describe("Entry point, e.g. live_chat, contact_form, api, email"),
1530
+ intent: z3.string().max(64).optional().describe("AI triage intent (triaged conversations only)"),
1531
+ urgency: z3.string().max(64).optional().describe("AI triage urgency (triaged conversations only)"),
1532
+ sort: z3.enum(CONVERSATION_SORTS).optional().describe(
1533
+ "recent (last activity, default), oldest, newest (created) or priority"
1534
+ )
1535
+ };
1536
+ async function list(api, a) {
1537
+ const r = await api.request("GET", "/v1/conversations", {
1538
+ query: {
1539
+ status: asList(a.status),
1540
+ priority: asList(a.priority),
1541
+ assignee: a.assignee,
1542
+ projectId: a.projectId,
1543
+ updatedSince: a.updatedSince,
1544
+ tag: a.tag,
1545
+ source: a.source,
1546
+ intent: a.intent,
1547
+ urgency: a.urgency,
1548
+ sort: a.sort,
1549
+ q: a.q,
1550
+ limit: a.limit,
1551
+ offset: a.offset
1552
+ }
1553
+ });
1554
+ return {
1555
+ conversations: r.conversations ?? [],
1556
+ total: Number(r.total ?? 0),
1557
+ limit: Number(r.limit ?? a.limit),
1558
+ offset: Number(r.offset ?? a.offset),
1559
+ hasMore: Boolean(r.hasMore)
1560
+ };
1561
+ }
1562
+ var path = (cid, rest = "") => `/v1/conversations/${encodeURIComponent(cid)}${rest}`;
1563
+ async function patch(api, cid, body) {
1564
+ const r = await api.request(
1565
+ "PATCH",
1566
+ path(cid),
1567
+ { body }
1568
+ );
594
1569
  return {
595
- content: [{ type: "text", text: JSON.stringify(data, null, 2) }],
596
- structuredContent: data
1570
+ conversation: r.conversation,
1571
+ changes: r.changes ?? []
1572
+ };
1573
+ }
1574
+ var READ2 = {
1575
+ readOnlyHint: true,
1576
+ destructiveHint: false,
1577
+ idempotentHint: true,
1578
+ openWorldHint: false
1579
+ };
1580
+ var CHANGE = {
1581
+ readOnlyHint: false,
1582
+ destructiveHint: false,
1583
+ idempotentHint: true,
1584
+ openWorldHint: true
1585
+ };
1586
+ var ROUTING_FIELDS = [
1587
+ "source",
1588
+ "project",
1589
+ "widget",
1590
+ "connection",
1591
+ "page_url",
1592
+ "page_domain",
1593
+ "customer_email",
1594
+ "customer_email_domain",
1595
+ "message",
1596
+ "subject",
1597
+ "tags",
1598
+ "priority",
1599
+ "language"
1600
+ ];
1601
+ var ROUTING_OPERATORS = [
1602
+ "equals",
1603
+ "not_equals",
1604
+ "contains",
1605
+ "not_contains",
1606
+ "starts_with",
1607
+ "ends_with",
1608
+ "matches"
1609
+ ];
1610
+ var routingConditions = z3.object({
1611
+ match: z3.enum(["all", "any"]).describe("all = every condition holds, any = one is enough"),
1612
+ conditions: z3.array(
1613
+ z3.object({
1614
+ field: z3.enum(ROUTING_FIELDS),
1615
+ operator: z3.enum(ROUTING_OPERATORS),
1616
+ value: z3.union([z3.string(), z3.array(z3.string())]).describe(
1617
+ "A value, or a list (positive operators: any matches; negative: none does). Case-insensitive; matches uses * and ? wildcards."
1618
+ )
1619
+ })
1620
+ ).max(50).describe("Empty = matches every new conversation (catch-all)")
1621
+ }).describe(
1622
+ 'Which new conversations the rule catches, tested on the first message, e.g. { "match": "any", "conditions": [{ "field": "message", "operator": "contains", "value": ["refund", "invoice"] }] }'
1623
+ );
1624
+ var ruleFields = {
1625
+ name: z3.string().trim().min(1).max(255).describe("Rule name"),
1626
+ targetChannelId: z3.string().regex(/^[A-Z0-9]{2,30}$/, "a Slack channel ID like C0123ABCD").describe("Slack channel ID to post matching conversations to"),
1627
+ conditions: routingConditions,
1628
+ projectId: id("Project (default: the oldest project)").optional(),
1629
+ widgetId: id("Widget").nullable().optional(),
1630
+ integrationId: id("Integration (default: the Slack workspace)").optional(),
1631
+ assignToUserId: id("Teammate to assign matching conversations to").nullable().optional(),
1632
+ isActive: z3.boolean().optional().describe("Default true"),
1633
+ priority: z3.number().int().min(-1e6).max(1e6).optional().describe("Higher runs first (default: after every rule)")
1634
+ };
1635
+ var rule = z3.looseObject({
1636
+ id: z3.string(),
1637
+ name: z3.string(),
1638
+ priority: z3.number(),
1639
+ is_active: z3.boolean(),
1640
+ target_channel_id: z3.string()
1641
+ });
1642
+ var INBOX_TOOLS = [
1643
+ defineTool2({
1644
+ name: "list_conversations",
1645
+ title: "List conversations",
1646
+ 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.",
1647
+ scope: "inbox:read",
1648
+ endpoint: "GET /v1/conversations",
1649
+ inputSchema: z3.object({ ...listFilters, ...paging }),
1650
+ outputSchema: listOutput,
1651
+ annotations: READ2,
1652
+ handler: (api, a) => list(api, a)
1653
+ }),
1654
+ defineTool2({
1655
+ name: "search_conversations",
1656
+ title: "Search conversations",
1657
+ 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.",
1658
+ scope: "inbox:read",
1659
+ endpoint: "GET /v1/conversations?q=",
1660
+ inputSchema: z3.object({
1661
+ query: z3.string().trim().min(1).max(200).describe("Text to look for"),
1662
+ ...listFilters,
1663
+ ...paging
1664
+ }),
1665
+ outputSchema: listOutput,
1666
+ annotations: READ2,
1667
+ handler: (api, { query, ...a }) => list(api, { ...a, q: query })
1668
+ }),
1669
+ defineTool2({
1670
+ name: "get_conversation",
1671
+ title: "Get conversation",
1672
+ 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.",
1673
+ scope: "inbox:read",
1674
+ endpoint: "GET /v1/conversations/:id",
1675
+ inputSchema: z3.object({ conversationId }),
1676
+ outputSchema: z3.object({
1677
+ conversation: z3.looseObject({
1678
+ id: z3.string(),
1679
+ status: z3.string(),
1680
+ messages: z3.array(loose)
1681
+ })
1682
+ }),
1683
+ annotations: READ2,
1684
+ handler: async (api, { conversationId: cid }) => {
1685
+ const r = await api.request("GET", path(cid));
1686
+ return { conversation: r.conversation };
1687
+ }
1688
+ }),
1689
+ defineTool2({
1690
+ name: "reply_to_conversation",
1691
+ title: "Reply to conversation",
1692
+ 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.',
1693
+ scope: "inbox:write",
1694
+ endpoint: "POST /v1/conversations/:id/reply",
1695
+ inputSchema: z3.object({
1696
+ conversationId,
1697
+ content: z3.string().trim().min(1).max(1e4).describe("Reply text, as the customer will read it")
1698
+ }),
1699
+ outputSchema: z3.object({
1700
+ message: z3.looseObject({ id: z3.string() }),
1701
+ conversationStatus: z3.string(),
1702
+ slack: slackOutcome
1703
+ }),
1704
+ annotations: {
1705
+ readOnlyHint: false,
1706
+ destructiveHint: false,
1707
+ idempotentHint: false,
1708
+ openWorldHint: true
1709
+ },
1710
+ handler: async (api, { conversationId: cid, content }) => {
1711
+ const r = await api.request("POST", path(cid, "/reply"), {
1712
+ body: { content }
1713
+ });
1714
+ return {
1715
+ message: r.message,
1716
+ conversationStatus: String(r.conversationStatus ?? ""),
1717
+ slack: String(r.slack ?? "")
1718
+ };
1719
+ }
1720
+ }),
1721
+ defineTool2({
1722
+ name: "add_internal_note",
1723
+ title: "Add internal note",
1724
+ 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.",
1725
+ scope: "inbox:write",
1726
+ endpoint: "POST /v1/conversations/:id/notes",
1727
+ inputSchema: z3.object({
1728
+ conversationId,
1729
+ content: z3.string().trim().min(1).max(1e4).describe("Note text")
1730
+ }),
1731
+ outputSchema: z3.object({
1732
+ note: z3.looseObject({ id: z3.string() }),
1733
+ slack: slackOutcome
1734
+ }),
1735
+ annotations: {
1736
+ readOnlyHint: false,
1737
+ destructiveHint: false,
1738
+ idempotentHint: false,
1739
+ openWorldHint: true
1740
+ },
1741
+ handler: async (api, { conversationId: cid, content }) => {
1742
+ const r = await api.request("POST", path(cid, "/notes"), {
1743
+ body: { content }
1744
+ });
1745
+ return { note: r.note, slack: String(r.slack ?? "") };
1746
+ }
1747
+ }),
1748
+ defineTool2({
1749
+ name: "assign_conversation",
1750
+ title: "Assign conversation",
1751
+ 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.",
1752
+ scope: "inbox:write",
1753
+ endpoint: "PATCH /v1/conversations/:id",
1754
+ inputSchema: z3.object({
1755
+ conversationId,
1756
+ assignee: z3.string().min(1).max(255).nullable().describe("User ID or email of the teammate, or null to unassign")
1757
+ }),
1758
+ outputSchema: changeOutput,
1759
+ annotations: CHANGE,
1760
+ handler: (api, { conversationId: cid, assignee }) => patch(
1761
+ api,
1762
+ cid,
1763
+ assignee === null ? { assigneeId: null } : assignee.includes("@") ? { assigneeEmail: assignee } : { assigneeId: assignee }
1764
+ )
1765
+ }),
1766
+ defineTool2({
1767
+ name: "tag_conversation",
1768
+ title: "Tag conversation",
1769
+ 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.",
1770
+ scope: "inbox:write",
1771
+ endpoint: "PATCH /v1/conversations/:id",
1772
+ inputSchema: z3.object({
1773
+ conversationId,
1774
+ add: tags.optional().describe("Tags to add"),
1775
+ remove: tags.optional().describe("Tags to remove"),
1776
+ set: tags.optional().describe("Replace every tag with these ([] clears them)")
1777
+ }),
1778
+ outputSchema: changeOutput,
1779
+ annotations: CHANGE,
1780
+ handler: (api, { conversationId: cid, add, remove, set }) => {
1781
+ if (!add?.length && !remove?.length && !set) {
1782
+ throw new ToolError("Pass tags to add, remove, or set.");
1783
+ }
1784
+ return patch(api, cid, {
1785
+ ...set ? { tags: set } : {},
1786
+ ...add?.length ? { addTags: add } : {},
1787
+ ...remove?.length ? { removeTags: remove } : {}
1788
+ });
1789
+ }
1790
+ }),
1791
+ defineTool2({
1792
+ name: "close_conversation",
1793
+ title: "Close conversation",
1794
+ 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.",
1795
+ scope: "inbox:write",
1796
+ endpoint: "PATCH /v1/conversations/:id",
1797
+ inputSchema: z3.object({
1798
+ conversationId,
1799
+ status: z3.enum(["closed", "resolved"]).default("closed").describe("closed (default) or resolved")
1800
+ }),
1801
+ outputSchema: changeOutput,
1802
+ annotations: CHANGE,
1803
+ handler: (api, { conversationId: cid, status }) => patch(api, cid, { status })
1804
+ }),
1805
+ defineTool2({
1806
+ name: "reopen_conversation",
1807
+ title: "Reopen conversation",
1808
+ description: "Reopen a closed or resolved conversation (status open). Needs the inbox:write scope.",
1809
+ scope: "inbox:write",
1810
+ endpoint: "PATCH /v1/conversations/:id",
1811
+ inputSchema: z3.object({ conversationId }),
1812
+ outputSchema: changeOutput,
1813
+ annotations: CHANGE,
1814
+ handler: (api, { conversationId: cid }) => patch(api, cid, { status: "open" })
1815
+ }),
1816
+ defineTool2({
1817
+ name: "get_analytics_summary",
1818
+ title: "Get analytics summary",
1819
+ 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.",
1820
+ scope: "analytics:read",
1821
+ endpoint: "GET /v1/analytics/summary",
1822
+ inputSchema: z3.object({
1823
+ days: z3.number().int().min(1).max(366).optional().describe("Period length in days, ending today (default 30)"),
1824
+ from: z3.iso.date().optional().describe("First day, YYYY-MM-DD"),
1825
+ to: z3.iso.date().optional().describe("Last day, YYYY-MM-DD"),
1826
+ tz: z3.string().max(64).optional().describe("IANA time zone for day boundaries (default UTC)"),
1827
+ projectId: id("Project").optional()
1828
+ }),
1829
+ outputSchema: z3.looseObject({ range: loose, kpis: loose, inbox: loose }),
1830
+ annotations: READ2,
1831
+ handler: async (api, args) => api.request(
1832
+ "GET",
1833
+ "/v1/analytics/summary",
1834
+ { query: args }
1835
+ )
1836
+ }),
1837
+ defineTool2({
1838
+ name: "list_routing_rules",
1839
+ title: "List routing rules",
1840
+ 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.",
1841
+ scope: "routing:read",
1842
+ endpoint: "GET /v1/routing-rules",
1843
+ inputSchema: z3.object({}),
1844
+ outputSchema: z3.object({ rules: z3.array(rule) }),
1845
+ annotations: READ2,
1846
+ handler: async (api) => {
1847
+ const r = await api.request(
1848
+ "GET",
1849
+ "/v1/routing-rules"
1850
+ );
1851
+ return { rules: r.routing_rules ?? [] };
1852
+ }
1853
+ }),
1854
+ defineTool2({
1855
+ name: "create_routing_rule",
1856
+ title: "Create routing rule",
1857
+ 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.",
1858
+ scope: "routing:write",
1859
+ endpoint: "POST /v1/routing-rules",
1860
+ inputSchema: z3.object(ruleFields),
1861
+ outputSchema: z3.object({ rule }),
1862
+ annotations: {
1863
+ readOnlyHint: false,
1864
+ destructiveHint: false,
1865
+ idempotentHint: false,
1866
+ openWorldHint: false
1867
+ },
1868
+ handler: async (api, body) => {
1869
+ const r = await api.request(
1870
+ "POST",
1871
+ "/v1/routing-rules",
1872
+ { body }
1873
+ );
1874
+ return { rule: r.routing_rule };
1875
+ }
1876
+ }),
1877
+ defineTool2({
1878
+ name: "update_routing_rule",
1879
+ title: "Update routing rule",
1880
+ 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.",
1881
+ scope: "routing:write",
1882
+ endpoint: "PATCH /v1/routing-rules/:id",
1883
+ inputSchema: z3.object({
1884
+ ruleId: id("Routing rule"),
1885
+ name: ruleFields.name.optional(),
1886
+ targetChannelId: ruleFields.targetChannelId.optional(),
1887
+ conditions: routingConditions.optional(),
1888
+ projectId: ruleFields.projectId,
1889
+ widgetId: ruleFields.widgetId,
1890
+ integrationId: ruleFields.integrationId,
1891
+ assignToUserId: ruleFields.assignToUserId,
1892
+ isActive: ruleFields.isActive,
1893
+ priority: ruleFields.priority
1894
+ }),
1895
+ outputSchema: z3.object({ rule }),
1896
+ annotations: {
1897
+ readOnlyHint: false,
1898
+ destructiveHint: false,
1899
+ idempotentHint: true,
1900
+ openWorldHint: false
1901
+ },
1902
+ handler: async (api, { ruleId, ...body }) => {
1903
+ if (Object.values(body).every((v) => v === void 0)) {
1904
+ throw new ToolError("Pass at least one field to change.");
1905
+ }
1906
+ const r = await api.request(
1907
+ "PATCH",
1908
+ `/v1/routing-rules/${encodeURIComponent(ruleId)}`,
1909
+ { body }
1910
+ );
1911
+ return { rule: r.routing_rule };
1912
+ }
1913
+ }),
1914
+ defineTool2({
1915
+ name: "delete_routing_rule",
1916
+ title: "Delete routing rule",
1917
+ 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.",
1918
+ scope: "routing:write",
1919
+ endpoint: "DELETE /v1/routing-rules/:id",
1920
+ inputSchema: z3.object({ ruleId: id("Routing rule") }),
1921
+ outputSchema: z3.object({ deleted: z3.boolean(), ruleId: z3.string() }),
1922
+ annotations: {
1923
+ readOnlyHint: false,
1924
+ destructiveHint: true,
1925
+ idempotentHint: true,
1926
+ openWorldHint: false
1927
+ },
1928
+ handler: async (api, { ruleId }) => {
1929
+ await api.request(
1930
+ "DELETE",
1931
+ `/v1/routing-rules/${encodeURIComponent(ruleId)}`
1932
+ );
1933
+ return { deleted: true, ruleId };
1934
+ }
1935
+ })
1936
+ ];
1937
+ var INBOX_TOOL_NAMES = INBOX_TOOLS.map((t) => t.name);
1938
+
1939
+ // src/tools.ts
1940
+ function ok(data2) {
1941
+ return {
1942
+ content: [{ type: "text", text: JSON.stringify(data2, null, 2) }],
1943
+ structuredContent: data2
597
1944
  };
598
1945
  }
599
1946
  async function run(fn) {
@@ -607,25 +1954,15 @@ async function run(fn) {
607
1954
  };
608
1955
  }
609
1956
  }
610
- var record2 = z2.record(z2.string(), z2.unknown());
611
- var loose = z2.looseObject({});
612
- var page = {
613
- total: z2.number(),
614
- limit: z2.number(),
615
- offset: z2.number(),
616
- hasMore: z2.boolean()
1957
+ var record4 = z4.record(z4.string(), z4.unknown());
1958
+ var loose2 = z4.looseObject({});
1959
+ var page2 = {
1960
+ total: z4.number(),
1961
+ limit: z4.number(),
1962
+ offset: z4.number(),
1963
+ hasMore: z4.boolean()
617
1964
  };
618
- var conversationSummary = z2.looseObject({
619
- id: z2.string(),
620
- subject: z2.string().nullable().optional(),
621
- status: z2.string(),
622
- priority: z2.string().nullable().optional(),
623
- customerEmail: z2.string().nullable().optional(),
624
- customerName: z2.string().nullable().optional(),
625
- tags: z2.array(z2.string()).nullable().optional(),
626
- createdAt: z2.string().optional()
627
- });
628
- var READ = {
1965
+ var READ3 = {
629
1966
  readOnlyHint: true,
630
1967
  destructiveHint: false,
631
1968
  idempotentHint: true,
@@ -637,9 +1974,9 @@ function registerServerTools(server, api) {
637
1974
  {
638
1975
  title: "Get project",
639
1976
  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.",
640
- inputSchema: z2.object({}),
641
- outputSchema: z2.object({ project: loose }),
642
- annotations: READ
1977
+ inputSchema: z4.object({}),
1978
+ outputSchema: z4.object({ project: loose2 }),
1979
+ annotations: READ3
643
1980
  },
644
1981
  () => run(async () => {
645
1982
  const r = await api.request("GET", "/projects/me");
@@ -651,9 +1988,9 @@ function registerServerTools(server, api) {
651
1988
  {
652
1989
  title: "Get analytics",
653
1990
  description: "Daily support activity for the last 30 days (UTC): conversations created and resolved, customer and agent messages.",
654
- inputSchema: z2.object({}),
655
- outputSchema: z2.object({ analytics: loose }),
656
- annotations: READ
1991
+ inputSchema: z4.object({}),
1992
+ outputSchema: z4.object({ analytics: loose2 }),
1993
+ annotations: READ3
657
1994
  },
658
1995
  () => run(async () => {
659
1996
  const r = await api.request(
@@ -663,75 +2000,20 @@ function registerServerTools(server, api) {
663
2000
  return { analytics: r.analytics };
664
2001
  })
665
2002
  );
666
- server.registerTool(
667
- "list_conversations",
668
- {
669
- title: "List conversations",
670
- 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.",
671
- inputSchema: z2.object({
672
- status: z2.enum(STATUSES).optional().describe("Only conversations with this status"),
673
- priority: z2.enum(PRIORITIES).optional().describe("Only conversations with this priority"),
674
- limit: z2.number().int().min(1).max(50).default(20).describe("How many to return (1-50, default 20)")
675
- }),
676
- outputSchema: z2.object({
677
- conversations: z2.array(conversationSummary),
678
- returned: z2.number(),
679
- matched: z2.number(),
680
- scanned: z2.number()
681
- }),
682
- annotations: READ
683
- },
684
- ({ status, priority, limit }) => run(async () => {
685
- const r = await api.request(
686
- "GET",
687
- "/conversations"
688
- );
689
- const all = r.conversations ?? [];
690
- const matched = all.filter(
691
- (c) => (!status || c.status === status) && (!priority || c.priority === priority)
692
- );
693
- const conversations = matched.slice(0, limit);
694
- return {
695
- conversations,
696
- returned: conversations.length,
697
- matched: matched.length,
698
- scanned: all.length
699
- };
700
- })
701
- );
702
- server.registerTool(
703
- "get_conversation",
704
- {
705
- title: "Get conversation",
706
- description: "Read one conversation with its full message thread (customer, agent and system messages), status, priority and tags.",
707
- inputSchema: z2.object({
708
- conversationId: z2.string().uuid().describe("Conversation ID (from list_conversations)")
709
- }),
710
- outputSchema: z2.object({ conversation: loose }),
711
- annotations: READ
712
- },
713
- ({ conversationId }) => run(async () => {
714
- const conversation = await api.request(
715
- "GET",
716
- `/conversations/${encodeURIComponent(conversationId)}`
717
- );
718
- return { conversation };
719
- })
720
- );
721
2003
  server.registerTool(
722
2004
  "create_conversation",
723
2005
  {
724
2006
  title: "Create conversation",
725
2007
  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.",
726
- inputSchema: z2.object({
727
- customerEmail: z2.email().describe("Customer's email address"),
728
- customerName: z2.string().max(255).optional().describe("Customer's name"),
729
- subject: z2.string().min(1).max(500).describe("Subject line"),
730
- message: z2.string().min(1).describe("First message, from the customer"),
731
- channel: z2.string().optional().describe("Slack channel ID to post to, overriding routing rules"),
732
- tags: z2.array(z2.string()).max(20).optional().describe("Tags")
2008
+ inputSchema: z4.object({
2009
+ customerEmail: z4.email().describe("Customer's email address"),
2010
+ customerName: z4.string().max(255).optional().describe("Customer's name"),
2011
+ subject: z4.string().min(1).max(500).describe("Subject line"),
2012
+ message: z4.string().min(1).describe("First message, from the customer"),
2013
+ channel: z4.string().optional().describe("Slack channel ID to post to, overriding routing rules"),
2014
+ tags: z4.array(z4.string()).max(20).optional().describe("Tags")
733
2015
  }),
734
- outputSchema: z2.object({ conversation: loose }),
2016
+ outputSchema: z4.object({ conversation: loose2 }),
735
2017
  annotations: {
736
2018
  readOnlyHint: false,
737
2019
  destructiveHint: false,
@@ -751,12 +2033,12 @@ function registerServerTools(server, api) {
751
2033
  {
752
2034
  title: "List contacts",
753
2035
  description: "List the customers who contacted the organization, with their conversation count. Paginate with limit/offset.",
754
- inputSchema: z2.object({
755
- limit: z2.number().int().min(1).max(100).default(50),
756
- offset: z2.number().int().min(0).default(0)
2036
+ inputSchema: z4.object({
2037
+ limit: z4.number().int().min(1).max(100).default(50),
2038
+ offset: z4.number().int().min(0).default(0)
757
2039
  }),
758
- outputSchema: z2.object({ contacts: z2.array(loose), ...page }),
759
- annotations: READ
2040
+ outputSchema: z4.object({ contacts: z4.array(loose2), ...page2 }),
2041
+ annotations: READ3
760
2042
  },
761
2043
  ({ limit, offset }) => run(async () => {
762
2044
  const r = await api.request("GET", "/contacts", {
@@ -776,11 +2058,11 @@ function registerServerTools(server, api) {
776
2058
  {
777
2059
  title: "Get contact",
778
2060
  description: "Read one contact (customer) by ID.",
779
- inputSchema: z2.object({
780
- contactId: z2.string().uuid().describe("Contact ID (from list_contacts)")
2061
+ inputSchema: z4.object({
2062
+ contactId: z4.string().uuid().describe("Contact ID (from list_contacts)")
781
2063
  }),
782
- outputSchema: z2.object({ contact: loose }),
783
- annotations: READ
2064
+ outputSchema: z4.object({ contact: loose2 }),
2065
+ annotations: READ3
784
2066
  },
785
2067
  ({ contactId }) => run(async () => {
786
2068
  const contact = await api.request(
@@ -795,14 +2077,14 @@ function registerServerTools(server, api) {
795
2077
  {
796
2078
  title: "Create contact",
797
2079
  description: "Add a customer by email, or return the existing one with that email. Needs the write scope.",
798
- inputSchema: z2.object({
799
- email: z2.email(),
800
- name: z2.string().max(255).optional(),
801
- company: z2.string().optional(),
802
- phone: z2.string().optional(),
803
- tags: z2.array(z2.string()).max(20).optional()
2080
+ inputSchema: z4.object({
2081
+ email: z4.email(),
2082
+ name: z4.string().max(255).optional(),
2083
+ company: z4.string().optional(),
2084
+ phone: z4.string().optional(),
2085
+ tags: z4.array(z4.string()).max(20).optional()
804
2086
  }),
805
- outputSchema: z2.object({ contact: loose }),
2087
+ outputSchema: z4.object({ contact: loose2 }),
806
2088
  annotations: {
807
2089
  readOnlyHint: false,
808
2090
  destructiveHint: false,
@@ -822,23 +2104,23 @@ function registerServerTools(server, api) {
822
2104
  {
823
2105
  title: "Send an Event to Slack",
824
2106
  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.',
825
- inputSchema: z2.object({
826
- event: z2.string().max(100).regex(
2107
+ inputSchema: z4.object({
2108
+ event: z4.string().max(100).regex(
827
2109
  import_core3.EVENT_KEY_PATTERN,
828
2110
  "lowercase letters, digits, dots, underscores or dashes"
829
2111
  ).describe("Event key, e.g. user.subscribed"),
830
- data: record2.optional().describe(
2112
+ data: record4.optional().describe(
831
2113
  'Template fields, e.g. { "username": "ada", "plan": "Pro" }'
832
2114
  ),
833
- idempotencyKey: z2.string().min(1).max(255).optional().describe("Send at most once per key (retry-safe)"),
834
- channel: z2.string().optional().describe("Slack channel ID instead of the event's channel")
2115
+ idempotencyKey: z4.string().min(1).max(255).optional().describe("Send at most once per key (retry-safe)"),
2116
+ channel: z4.string().optional().describe("Slack channel ID instead of the event's channel")
835
2117
  }),
836
- outputSchema: z2.looseObject({
837
- id: z2.string(),
838
- event: z2.string(),
839
- status: z2.string(),
840
- reason: z2.string().optional(),
841
- duplicate: z2.boolean().optional()
2118
+ outputSchema: z4.looseObject({
2119
+ id: z4.string(),
2120
+ event: z4.string(),
2121
+ status: z4.string(),
2122
+ reason: z4.string().optional(),
2123
+ duplicate: z4.boolean().optional()
842
2124
  }),
843
2125
  annotations: {
844
2126
  readOnlyHint: false,
@@ -847,9 +2129,9 @@ function registerServerTools(server, api) {
847
2129
  openWorldHint: true
848
2130
  }
849
2131
  },
850
- ({ event, data, idempotencyKey, channel }) => run(async () => {
2132
+ ({ event, data: data2, idempotencyKey, channel }) => run(async () => {
851
2133
  const client = await api.notifier();
852
- const r = await client.notify(event, data, { idempotencyKey, channel });
2134
+ const r = await client.notify(event, data2, { idempotencyKey, channel });
853
2135
  return {
854
2136
  id: r.id,
855
2137
  event: r.event,
@@ -864,12 +2146,12 @@ function registerServerTools(server, api) {
864
2146
  {
865
2147
  title: "List Events",
866
2148
  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.",
867
- inputSchema: z2.object({}),
868
- outputSchema: z2.object({
869
- projectId: z2.string(),
870
- definitions: z2.array(loose)
2149
+ inputSchema: z4.object({}),
2150
+ outputSchema: z4.object({
2151
+ projectId: z4.string(),
2152
+ definitions: z4.array(loose2)
871
2153
  }),
872
- annotations: READ
2154
+ annotations: READ3
873
2155
  },
874
2156
  () => run(async () => {
875
2157
  const projectId = await api.projectId();
@@ -885,15 +2167,15 @@ function registerServerTools(server, api) {
885
2167
  {
886
2168
  title: "List Event deliveries",
887
2169
  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.",
888
- inputSchema: z2.object({
889
- definitionId: z2.string().uuid().optional().describe("Only this Event (ID from list_event_definitions)"),
890
- limit: z2.number().int().min(1).max(100).default(20)
2170
+ inputSchema: z4.object({
2171
+ definitionId: z4.string().uuid().optional().describe("Only this Event (ID from list_event_definitions)"),
2172
+ limit: z4.number().int().min(1).max(100).default(20)
891
2173
  }),
892
- outputSchema: z2.object({
893
- projectId: z2.string(),
894
- deliveries: z2.array(loose)
2174
+ outputSchema: z4.object({
2175
+ projectId: z4.string(),
2176
+ deliveries: z4.array(loose2)
895
2177
  }),
896
- annotations: READ
2178
+ annotations: READ3
897
2179
  },
898
2180
  ({ definitionId, limit }) => run(async () => {
899
2181
  const projectId = await api.projectId();
@@ -910,20 +2192,20 @@ function registerServerTools(server, api) {
910
2192
  {
911
2193
  title: "Query logs",
912
2194
  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.",
913
- inputSchema: z2.object({
914
- severity: z2.enum(import_core3.EVENT_SEVERITIES).optional(),
915
- source: z2.enum(["client_sdk", "server_api", "system"]).optional().describe(
2195
+ inputSchema: z4.object({
2196
+ severity: z4.enum(import_core3.EVENT_SEVERITIES).optional(),
2197
+ source: z4.enum(["client_sdk", "server_api", "system"]).optional().describe(
916
2198
  "client_sdk = browser (widget key), server_api = server key"
917
2199
  ),
918
- search: z2.string().max(200).optional().describe("Text to look for"),
919
- from: z2.iso.datetime({ offset: true }).optional().describe("ISO 8601 start"),
920
- to: z2.iso.datetime({ offset: true }).optional().describe("ISO 8601 end"),
921
- projectId: z2.string().uuid().optional(),
922
- limit: z2.number().int().min(1).max(100).default(50),
923
- offset: z2.number().int().min(0).default(0)
2200
+ search: z4.string().max(200).optional().describe("Text to look for"),
2201
+ from: z4.iso.datetime({ offset: true }).optional().describe("ISO 8601 start"),
2202
+ to: z4.iso.datetime({ offset: true }).optional().describe("ISO 8601 end"),
2203
+ projectId: z4.string().uuid().optional(),
2204
+ limit: z4.number().int().min(1).max(100).default(50),
2205
+ offset: z4.number().int().min(0).default(0)
924
2206
  }),
925
- outputSchema: z2.object({ events: z2.array(loose), ...page }),
926
- annotations: READ
2207
+ outputSchema: z4.object({ events: z4.array(loose2), ...page2 }),
2208
+ annotations: READ3
927
2209
  },
928
2210
  (args) => run(async () => {
929
2211
  const r = await api.request("GET", "/v1/events", { query: args });
@@ -941,12 +2223,12 @@ function registerServerTools(server, api) {
941
2223
  {
942
2224
  title: "Record a log",
943
2225
  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.",
944
- inputSchema: z2.object({
945
- name: z2.string().min(1).max(255).describe("Log name, e.g. payment.failed"),
946
- severity: z2.enum(import_core3.EVENT_SEVERITIES).default("info"),
947
- properties: record2.optional().describe("Extra fields")
2226
+ inputSchema: z4.object({
2227
+ name: z4.string().min(1).max(255).describe("Log name, e.g. payment.failed"),
2228
+ severity: z4.enum(import_core3.EVENT_SEVERITIES).default("info"),
2229
+ properties: record4.optional().describe("Extra fields")
948
2230
  }),
949
- outputSchema: z2.object({ id: z2.string(), projectId: z2.string() }),
2231
+ outputSchema: z4.object({ id: z4.string(), projectId: z4.string() }),
950
2232
  annotations: {
951
2233
  readOnlyHint: false,
952
2234
  destructiveHint: false,
@@ -975,16 +2257,16 @@ function registerWidgetTools(server, api) {
975
2257
  {
976
2258
  title: "Submit contact form",
977
2259
  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.",
978
- inputSchema: z2.object({
979
- name: z2.string().min(1).describe("Visitor's name"),
980
- email: z2.email().describe("Visitor's email"),
981
- subject: z2.string().optional(),
982
- message: z2.string().min(1),
983
- pageUrl: z2.url().optional().describe("Page the form was sent from")
2260
+ inputSchema: z4.object({
2261
+ name: z4.string().min(1).describe("Visitor's name"),
2262
+ email: z4.email().describe("Visitor's email"),
2263
+ subject: z4.string().optional(),
2264
+ message: z4.string().min(1),
2265
+ pageUrl: z4.url().optional().describe("Page the form was sent from")
984
2266
  }),
985
- outputSchema: z2.looseObject({
986
- conversationId: z2.string().optional(),
987
- message: z2.string().optional()
2267
+ outputSchema: z4.looseObject({
2268
+ conversationId: z4.string().optional(),
2269
+ message: z4.string().optional()
988
2270
  }),
989
2271
  annotations: VISITOR
990
2272
  },
@@ -998,12 +2280,12 @@ function registerWidgetTools(server, api) {
998
2280
  {
999
2281
  title: "Start chat session",
1000
2282
  description: "Start a live chat session as a website visitor (widget key). Returns the session ID for send_message.",
1001
- inputSchema: z2.object({
1002
- metadata: record2.optional().describe("Metadata to attach (e.g. user info)")
2283
+ inputSchema: z4.object({
2284
+ metadata: record4.optional().describe("Metadata to attach (e.g. user info)")
1003
2285
  }),
1004
- outputSchema: z2.looseObject({
1005
- sessionId: z2.string(),
1006
- status: z2.string()
2286
+ outputSchema: z4.looseObject({
2287
+ sessionId: z4.string(),
2288
+ status: z4.string()
1007
2289
  }),
1008
2290
  annotations: VISITOR
1009
2291
  },
@@ -1021,13 +2303,13 @@ function registerWidgetTools(server, api) {
1021
2303
  {
1022
2304
  title: "Send chat message",
1023
2305
  description: "Send a visitor message in a chat session (widget key); it is posted to the Slack thread.",
1024
- inputSchema: z2.object({
1025
- sessionId: z2.string().min(1).describe("From create_chat_session"),
1026
- content: z2.string().min(1).max(5e3)
2306
+ inputSchema: z4.object({
2307
+ sessionId: z4.string().min(1).describe("From create_chat_session"),
2308
+ content: z4.string().min(1).max(5e3)
1027
2309
  }),
1028
- outputSchema: z2.looseObject({
1029
- messageId: z2.string(),
1030
- sessionStatus: z2.string()
2310
+ outputSchema: z4.looseObject({
2311
+ messageId: z4.string(),
2312
+ sessionStatus: z4.string()
1031
2313
  }),
1032
2314
  annotations: VISITOR
1033
2315
  },
@@ -1041,16 +2323,16 @@ function registerWidgetTools(server, api) {
1041
2323
  {
1042
2324
  title: "Read chat messages",
1043
2325
  description: "Read a chat session's messages, including agent replies from Slack (widget key).",
1044
- inputSchema: z2.object({
1045
- sessionId: z2.string().min(1),
1046
- limit: z2.number().int().min(1).max(100).default(50),
1047
- offset: z2.number().int().min(0).default(0)
2326
+ inputSchema: z4.object({
2327
+ sessionId: z4.string().min(1),
2328
+ limit: z4.number().int().min(1).max(100).default(50),
2329
+ offset: z4.number().int().min(0).default(0)
1048
2330
  }),
1049
- outputSchema: z2.object({
1050
- sessionId: z2.string(),
1051
- messages: z2.array(loose)
2331
+ outputSchema: z4.object({
2332
+ sessionId: z4.string(),
2333
+ messages: z4.array(loose2)
1052
2334
  }),
1053
- annotations: { ...READ, openWorldHint: true }
2335
+ annotations: { ...READ3, openWorldHint: true }
1054
2336
  },
1055
2337
  ({ sessionId, limit, offset }) => run(async () => {
1056
2338
  const messages = await api.widget().getChatMessages(sessionId, limit, offset);
@@ -1072,10 +2354,10 @@ function registerWidgetTools(server, api) {
1072
2354
  {
1073
2355
  title: "End chat session",
1074
2356
  description: "End a chat session as the visitor (widget key).",
1075
- inputSchema: z2.object({ sessionId: z2.string().min(1) }),
1076
- outputSchema: z2.looseObject({
1077
- sessionId: z2.string(),
1078
- status: z2.string()
2357
+ inputSchema: z4.object({ sessionId: z4.string().min(1) }),
2358
+ outputSchema: z4.looseObject({
2359
+ sessionId: z4.string(),
2360
+ status: z4.string()
1079
2361
  }),
1080
2362
  annotations: { ...VISITOR, idempotentHint: true }
1081
2363
  },
@@ -1085,6 +2367,27 @@ function registerWidgetTools(server, api) {
1085
2367
  })
1086
2368
  );
1087
2369
  }
2370
+ function registerAll(server, api, tools) {
2371
+ for (const tool of tools) {
2372
+ server.registerTool(
2373
+ tool.name,
2374
+ {
2375
+ title: tool.title,
2376
+ description: tool.description,
2377
+ inputSchema: tool.inputSchema,
2378
+ outputSchema: tool.outputSchema,
2379
+ annotations: tool.annotations
2380
+ },
2381
+ (args) => run(async () => await tool.handler(api, args))
2382
+ );
2383
+ }
2384
+ }
2385
+ function registerInboxTools(server, api) {
2386
+ registerAll(server, api, INBOX_TOOLS);
2387
+ }
2388
+ function registerAgentTools(server, api) {
2389
+ registerAll(server, api, AGENT_TOOLS);
2390
+ }
1088
2391
 
1089
2392
  // src/http.ts
1090
2393
  var import_node_http = require("http");
@@ -1116,7 +2419,7 @@ async function toRequest(req, origin) {
1116
2419
  async function startHttpServer(factory, options = {}) {
1117
2420
  const host = options.host ?? "127.0.0.1";
1118
2421
  const port = options.port ?? 3333;
1119
- const path = options.path ?? "/mcp";
2422
+ const path2 = options.path ?? "/mcp";
1120
2423
  const local = LOCAL_HOSTS.has(host);
1121
2424
  const handler = (0, import_server.createMcpHandler)(() => factory(), {
1122
2425
  onerror: (err) => console.error("[channlize-mcp]", err.message)
@@ -1128,8 +2431,8 @@ async function startHttpServer(factory, options = {}) {
1128
2431
  `http://${req.headers.host ?? `${host}:${port}`}`
1129
2432
  );
1130
2433
  const url2 = new URL(request.url);
1131
- if (url2.pathname !== path) {
1132
- res.writeHead(404, { "Content-Type": "text/plain" }).end(`Not found: use ${path}`);
2434
+ if (url2.pathname !== path2) {
2435
+ res.writeHead(404, { "Content-Type": "text/plain" }).end(`Not found: use ${path2}`);
1133
2436
  return;
1134
2437
  }
1135
2438
  const rejected = local ? (0, import_server.hostHeaderValidationResponse)(request, (0, import_server.localhostAllowedHostnames)()) ?? (0, import_server.originValidationResponse)(request, (0, import_server.localhostAllowedOrigins)()) : void 0;
@@ -1156,7 +2459,7 @@ async function startHttpServer(factory, options = {}) {
1156
2459
  const actualPort = typeof address === "object" && address ? address.port : port;
1157
2460
  const shownHost = host.includes(":") ? `[${host}]` : host;
1158
2461
  return {
1159
- url: `http://${shownHost}:${actualPort}${path}`,
2462
+ url: `http://${shownHost}:${actualPort}${path2}`,
1160
2463
  server,
1161
2464
  close: () => new Promise((r) => server.close(() => r()))
1162
2465
  };
@@ -1164,12 +2467,17 @@ async function startHttpServer(factory, options = {}) {
1164
2467
 
1165
2468
  // src/index.ts
1166
2469
  var import_core4 = require("@channlize/core");
1167
- var VERSION = true ? "0.4.0" : "0.0.0";
2470
+ var VERSION = true ? "0.5.0" : "0.0.0";
1168
2471
  var INSTRUCTIONS = `Channlize routes website conversations and app events to the team's Slack.
1169
- - Inbox: list_conversations / get_conversation, then contacts. Replies and status changes happen in Slack or the dashboard.
2472
+ - 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.
2473
+ - get_analytics_summary gives KPIs and the inbox right now; list/create/update/delete_routing_rule manage which Slack channel new conversations go to.
1170
2474
  - Events (notify_event) post a Slack message per event key; list_event_definitions and list_event_deliveries explain what was sent or skipped.
1171
2475
  - Logs: query_logs searches log tracking; track_log records one.
1172
- - Write tools need a server API key with the write scope; a 403 means the key is read-only.`;
2476
+ - 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).
2477
+ - 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.
2478
+ - 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).
2479
+ - 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.
2480
+ - 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.`;
1173
2481
  function buildServer(config, info = {}) {
1174
2482
  const api = new ChannlizeApi(resolveConfig(config));
1175
2483
  const server = new import_server2.McpServer(
@@ -1177,6 +2485,8 @@ function buildServer(config, info = {}) {
1177
2485
  { instructions: INSTRUCTIONS }
1178
2486
  );
1179
2487
  if (api.hasServerKey) {
2488
+ registerInboxTools(server, api);
2489
+ registerAgentTools(server, api);
1180
2490
  registerServerTools(server, api);
1181
2491
  registerServerPrompts(server);
1182
2492
  }
@@ -1225,6 +2535,8 @@ Keys (flags override environment variables):
1225
2535
  --api-key <key> Either kind, by prefix CHANNLIZE_API_KEY
1226
2536
  --project-id <id> Project (default: the key's first project)
1227
2537
  CHANNLIZE_PROJECT_ID
2538
+ --agent-id <id> Agent the agent tools act as (multi-agent keys)
2539
+ CHANNLIZE_AGENT_ID
1228
2540
  Options:
1229
2541
  --base-url <url> API URL (default https://api.channlize.com)
1230
2542
  CHANNLIZE_BASE_URL
@@ -1238,17 +2550,18 @@ Options:
1238
2550
 
1239
2551
  The server API key enables the inbox, contact, Events and log tools (read
1240
2552
  scope for reads, write scope to send). The widget key adds visitor tools
1241
- (contact form, chat). Create keys in the Channlize dashboard under
1242
- SDK & Integration \u2192 API keys.
2553
+ (contact form, chat). An agent key or a multi-agent key (agents:send,
2554
+ agents:read, agents:ask_human) enables the agent tools. Create keys in the
2555
+ Channlize dashboard under SDK & Integration \u2192 API keys.
1243
2556
 
1244
2557
  Claude Code:
1245
2558
  claude mcp add channlize --env CHANNLIZE_SERVER_API_KEY=ch_live_\u2026 -- npx -y @channlize/mcp
1246
2559
 
1247
2560
  Docs: https://github.com/channlize/sdk/tree/main/packages/mcp
1248
2561
  `;
1249
- function fail(message) {
2562
+ function fail(message2) {
1250
2563
  console.error(
1251
- `channlize-mcp: ${message}
2564
+ `channlize-mcp: ${message2}
1252
2565
 
1253
2566
  Run 'channlize-mcp --help' for usage.`
1254
2567
  );
@@ -1263,6 +2576,7 @@ async function main() {
1263
2576
  "widget-key": { type: "string" },
1264
2577
  "api-key": { type: "string" },
1265
2578
  "project-id": { type: "string" },
2579
+ "agent-id": { type: "string" },
1266
2580
  "base-url": { type: "string" },
1267
2581
  timeout: { type: "string" },
1268
2582
  transport: { type: "string" },
@@ -1292,6 +2606,7 @@ async function main() {
1292
2606
  widgetKey: str("widget-key") ?? env.widgetKey,
1293
2607
  apiKey: str("api-key") ?? env.apiKey,
1294
2608
  projectId: str("project-id") ?? env.projectId,
2609
+ agentId: str("agent-id") ?? env.agentId,
1295
2610
  baseUrl: str("base-url") ?? env.baseUrl,
1296
2611
  timeout: timeout !== void 0 ? Number(timeout) : env.timeout
1297
2612
  };