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