@channlize/mcp 0.5.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +17 -0
- package/README.md +15 -2
- package/dist/agents.d.mts +12 -2
- package/dist/agents.d.ts +12 -2
- package/dist/agents.js +548 -0
- package/dist/agents.js.map +1 -1
- package/dist/agents.mjs +548 -0
- package/dist/agents.mjs.map +1 -1
- package/dist/inbox.js.map +1 -1
- package/dist/inbox.mjs.map +1 -1
- package/dist/index.js +554 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +554 -1
- package/dist/index.mjs.map +1 -1
- package/dist/server.js +566 -13
- package/dist/server.js.map +1 -1
- package/package.json +2 -2
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/api.ts","../src/config.ts","../src/prompts.ts","../src/docs.ts","../src/resources.ts","../src/tools.ts","../src/agents.ts","../src/inbox.ts","../src/http.ts"],"sourcesContent":["/**\n * @channlize/mcp\n * Model Context Protocol (MCP) server for Channlize: lets AI assistants\n * work the support inbox (list, search, reply, assign, tag, close, notes),\n * manage routing rules, read analytics, contacts, logs and Events, send\n * Events to Slack, and talk to other agents (Channlize for Agents).\n */\n\nimport { McpServer } from '@modelcontextprotocol/server';\nimport { StdioServerTransport } from '@modelcontextprotocol/server/stdio';\nimport { ChannlizeApi } from './api';\nimport { resolveConfig, type ResolvedConfig } from './config';\nimport { registerGuidePrompts, registerServerPrompts } from './prompts';\nimport { registerResources } from './resources';\nimport {\n registerAgentTools,\n registerInboxTools,\n registerServerTools,\n registerWidgetTools,\n} from './tools';\nimport type { ChannlizeMCPConfig, MCPServerOptions } from './types';\nimport { startHttpServer, type HttpServerOptions } from './http';\n\ndeclare const __PACKAGE_VERSION__: string;\nexport const VERSION: string =\n typeof __PACKAGE_VERSION__ !== 'undefined' ? __PACKAGE_VERSION__ : '0.0.0';\n\nexport * from './types';\nexport { ConfigError, configFromEnv, resolveConfig, keyKind } from './config';\nexport type { ResolvedConfig, KeyKind } from './config';\nexport { ChannlizeApi, ToolError, toToolError } from './api';\nexport type { HttpMethod } from './api';\nexport * from './inbox';\nexport * from './agents';\nexport { registerAgentTools, registerInboxTools } from './tools';\nexport type { HttpServerOptions } from './http';\n\n// Re-export core types for convenience\nexport type {\n ChannlizeConfig,\n ContactFormData,\n ChatMessage,\n ChatSession,\n FileAttachment,\n CreateContactResponse,\n CreateChatSessionResponse,\n SendMessageResponse,\n NotifyResponse,\n} from '@channlize/core';\n\nconst INSTRUCTIONS = `Channlize routes website conversations and app events to the team's Slack.\n- 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.\n- get_analytics_summary gives KPIs and the inbox right now; list/create/update/delete_routing_rule manage which Slack channel new conversations go to.\n- Events (notify_event) post a Slack message per event key; list_event_definitions and list_event_deliveries explain what was sent or skipped.\n- Logs: query_logs searches log tracking; track_log records one.\n- 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).\n- 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.\n- 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).\n- 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.\n- 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.`;\n\n/**\n * Builds a configured `McpServer` (tools, resources and prompts) without\n * connecting it. Tools are registered for the keys you pass: server-key\n * tools for `serverApiKey`, visitor tools for `widgetKey`.\n */\nexport function buildServer(\n config: ChannlizeMCPConfig,\n info: { name?: string; version?: string } = {}\n): McpServer {\n const api = new ChannlizeApi(resolveConfig(config));\n const server = new McpServer(\n { name: info.name ?? 'channlize', version: info.version ?? VERSION },\n { instructions: INSTRUCTIONS }\n );\n if (api.hasServerKey) {\n registerInboxTools(server, api);\n registerAgentTools(server, api);\n registerServerTools(server, api);\n registerServerPrompts(server);\n }\n if (api.hasWidgetKey) registerWidgetTools(server, api);\n registerResources(server, api);\n registerGuidePrompts(server);\n return server;\n}\n\n/**\n * Channlize MCP server. Validates the configuration on construction (a\n * missing key or a widget key passed as the server key throws\n * `ConfigError`).\n */\nexport class ChannlizeMCPServer {\n private server: McpServer;\n private readonly config: ResolvedConfig;\n private readonly info: { name?: string; version?: string };\n\n constructor(options: MCPServerOptions = {}) {\n this.config = resolveConfig(options.config ?? {});\n this.info = { name: options.name, version: options.version };\n this.server = buildServer(this.config, this.info);\n }\n\n /** The underlying `McpServer`. */\n getServer(): McpServer {\n return this.server;\n }\n\n /** Serve over stdio (what desktop and IDE clients launch). */\n async runStdio(): Promise<void> {\n await this.server.connect(new StdioServerTransport());\n }\n\n /**\n * Serve Streamable HTTP at `http://<host>:<port>/mcp` (default\n * 127.0.0.1:3333). Each request gets a fresh server; nothing is shared.\n */\n async runHttp(options: HttpServerOptions = {}) {\n return startHttpServer(() => buildServer(this.config, this.info), options);\n }\n\n async close(): Promise<void> {\n await this.server.close();\n }\n}\n\n/** Create a new Channlize MCP server. */\nexport function createMCPServer(\n options?: MCPServerOptions\n): ChannlizeMCPServer {\n return new ChannlizeMCPServer(options);\n}\n\nexport default ChannlizeMCPServer;\n\n// Error classes as values, so `instanceof` works without importing core.\nexport {\n ChannlizeError,\n ValidationError,\n AuthenticationError,\n RateLimitError,\n} from '@channlize/core';\n","import {\n ChannlizeClient,\n ChannlizeError,\n parseApiError,\n} from '@channlize/core';\nimport type { ResolvedConfig } from './config';\n\nexport type HttpMethod = 'GET' | 'POST' | 'PATCH' | 'DELETE';\n\n/**\n * A failed Channlize call, worded for the model: what went wrong and how\n * to fix it (wrong key, missing scope, unknown id). Tool handlers throw it\n * and the MCP server returns it as a tool error (`isError: true`).\n */\nexport class ToolError extends Error {\n constructor(\n message: string,\n public statusCode?: number,\n public code?: string,\n /** ISO time the call may succeed again (agent policies, takeovers). */\n public retryAt?: string\n ) {\n super(message);\n this.name = 'ToolError';\n }\n}\n\ntype Query = Record<string, string | number | boolean | undefined>;\n\n/** The scope to add for an \"API key lacks required permission: <perm>\" 403. */\nfunction scopeFor(apiMessage: string): string {\n const perm = /permission:\\s*([\\w:*-]+)/i.exec(apiMessage)?.[1] ?? '';\n switch (perm) {\n case 'inbox:read':\n return 'inbox:read (or read)';\n case 'inbox:write':\n return 'inbox:write';\n case 'routing:read':\n return 'routing:write, inbox:read (or read)';\n case 'routing:write':\n return 'routing:write';\n case 'analytics:read':\n return 'analytics:read (or read)';\n case 'agents:send':\n return 'agents:send';\n case 'agents:read':\n return 'agents:read';\n case 'agents:ask_human':\n return 'agents:ask_human';\n case 'agents:admin':\n return 'agents:admin (an unbound key)';\n default:\n return /write|notify/.test(apiMessage) ? 'write' : 'read';\n }\n}\n\n/** \" Retry after <time>.\" for a refusal that names one. */\nfunction retryText(retryAt: string | undefined): string {\n return retryAt ? ` Retry after ${retryAt}, not before.` : '';\n}\n\n/** Hints for the Channlize for Agents error codes. */\nfunction agentHint(\n code: string | undefined,\n body: Record<string, unknown> = {}\n): string | undefined {\n const retryAt = typeof body.retryAt === 'string' ? body.retryAt : undefined;\n switch (code) {\n case 'AGENT_KEY_REQUIRED':\n return 'Agent tools need an agent key or a multi-agent key: create one under SDK & Integration → API keys and pick the agents.';\n case 'AGENT_NOT_ALLOWED':\n 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.\";\n case 'NOT_A_CHANNEL_MEMBER':\n return 'Only channel members can post (observers only read): use list_agent_channels, or ask an admin to add the agent to the channel.';\n case 'AGENT_PAUSED':\n case 'AGENT_RETIRED':\n return 'Only active agents can act: ask an admin to reactivate it in the dashboard.';\n case 'AGENT_RATE_LIMITED':\n return 'The agent is sending too fast: wait a minute before sending again.';\n case 'AGENT_THREAD_PAUSED': {\n const why =\n body.reason === 'ping_pong'\n ? ' (two agents were going back and forth)'\n : body.reason === 'duplicate_content'\n ? ' (the same message kept being posted)'\n : '';\n return `The loop guard paused this thread${why}: stop sending in it until a person replies or resumes it. Don't rephrase and retry.`;\n }\n case 'HUMAN_TAKEOVER':\n return `A person took over this thread: don't post in it until the takeover ends or they hand it back.${retryText(retryAt)}`;\n case 'POLICY_RATE_LIMITED':\n case 'POLICY_BUDGET_EXHAUSTED':\n case 'POLICY_OUTSIDE_WORKING_HOURS':\n return `The agent's policy refuses this for now: wait, don't retry in a loop.${retryText(retryAt)}`;\n case 'POLICY_CHANNEL_NOT_ALLOWED':\n case 'POLICY_DM_NOT_ALLOWED':\n case 'POLICY_ASK_HUMAN_NOT_ALLOWED':\n case 'POLICY_URGENCY_NOT_ALLOWED':\n case 'POLICY_MAX_DEPTH':\n 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.\";\n case 'TASK_CLOSED':\n return 'The task is closed (completed, failed, canceled or rejected) and cannot change: create a new task instead.';\n case 'ALREADY_ASSIGNED':\n return 'The task is already assigned to that agent.';\n case 'AGENT_NOT_IN_CHANNEL':\n 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.\";\n case 'NOT_TASK_PARTICIPANT':\n return \"Only the task's assignee or creator can change it or hand it off.\";\n case 'QUESTION_CLOSED':\n return 'The question is already closed (answered, expired or canceled): the first answer wins. Read it with get_answer.';\n case 'APPROVAL_ROLE_REQUIRED':\n return 'This approval needs a person with the required role: an agent cannot answer it.';\n case 'AGENT_ADMIN_KEY_REQUIRED':\n return 'This needs an unbound agents:admin key (not a key bound to agents): create one under SDK & Integration → API keys.';\n case 'INVALID_ANSWER':\n return \"Answer with one of the question's option ids (approve / deny for approvals), or text when free text is allowed.\";\n default:\n return undefined;\n }\n}\n\nfunction hintFor(\n status: number,\n apiMessage: string,\n code?: string,\n body?: Record<string, unknown>\n): string {\n const agent = agentHint(code, body);\n if (agent) return `${apiMessage}. ${agent}`;\n if (status === 400 && /agent_id is required/i.test(apiMessage)) {\n return `${apiMessage}. Pass agentId (from list_agents), or set CHANNLIZE_AGENT_ID / --agent-id on the MCP server.`;\n }\n switch (status) {\n case 401:\n return `${apiMessage}. The server API key is invalid, revoked or expired: create a new one under SDK & Integration → API keys and update CHANNLIZE_SERVER_API_KEY.`;\n case 403:\n return /permission/i.test(apiMessage)\n ? `${apiMessage}. This needs a server API key with the ${scopeFor(\n apiMessage\n )} scope: create one under SDK & Integration → API keys.`\n : apiMessage;\n case 404:\n return `${apiMessage}. Check the ID (and CHANNLIZE_PROJECT_ID): it must belong to the key's organization.`;\n case 429:\n return `${apiMessage}. Rate limited: wait a little before retrying.`;\n default:\n return apiMessage;\n }\n}\n\n/** Maps a `@channlize/core` error to a `ToolError` with the same hints. */\nexport function toToolError(err: unknown): ToolError {\n if (err instanceof ToolError) return err;\n if (err instanceof ChannlizeError) {\n return new ToolError(\n err.statusCode\n ? hintFor(\n err.statusCode,\n err.message.replace(/\\.$/, ''),\n err.code,\n err.details\n )\n : err.message,\n err.statusCode,\n err.code,\n err.retryAt\n );\n }\n return new ToolError(err instanceof Error ? err.message : String(err));\n}\n\n/**\n * Thin client for the API-key endpoints `@channlize/core` doesn't wrap\n * (projects, the inbox, routing rules, contacts, Events and log reads,\n * agents). Widget-key\n * calls and `notify` go through `@channlize/core`.\n */\nexport class ChannlizeApi {\n private projectIdPromise?: Promise<string>;\n private widgetClient?: ChannlizeClient;\n\n constructor(readonly config: ResolvedConfig) {}\n\n get hasServerKey(): boolean {\n return !!this.config.serverApiKey;\n }\n\n get hasWidgetKey(): boolean {\n return !!this.config.widgetKey;\n }\n\n /** The default agent for the agent tools (`CHANNLIZE_AGENT_ID`). */\n get agentId(): string | undefined {\n return this.config.agentId;\n }\n\n private requireServerKey(): string {\n if (!this.config.serverApiKey) {\n throw new ToolError(\n 'This tool needs a server API key (ch_live_…): set CHANNLIZE_SERVER_API_KEY or pass --server-api-key.'\n );\n }\n return this.config.serverApiKey;\n }\n\n async request<T>(\n method: HttpMethod,\n path: string,\n options: {\n query?: Query;\n body?: unknown;\n headers?: Record<string, string>;\n /** Overrides the configured timeout, in ms (long-polls). */\n timeout?: number;\n } = {}\n ): Promise<T> {\n const key = this.requireServerKey();\n const timeout = options.timeout ?? this.config.timeout;\n const url = new URL(`${this.config.baseUrl}${path}`);\n for (const [k, v] of Object.entries(options.query ?? {})) {\n if (v !== undefined && v !== '') url.searchParams.set(k, String(v));\n }\n\n let res: Response;\n try {\n res = await fetch(url, {\n method,\n headers: {\n Authorization: `Bearer ${key}`,\n Accept: 'application/json',\n ...(options.body !== undefined\n ? { 'Content-Type': 'application/json' }\n : {}),\n ...options.headers,\n },\n // oxlint-disable-next-line unicorn/no-invalid-fetch-options -- `method` is dynamic; GET calls never pass a body.\n body:\n options.body !== undefined ? JSON.stringify(options.body) : undefined,\n signal: AbortSignal.timeout(timeout),\n });\n } catch (err) {\n const e = err as Error;\n if (e.name === 'TimeoutError' || e.name === 'AbortError') {\n throw new ToolError(\n `Channlize API timed out after ${timeout} ms (${method} ${url.pathname}). Retry, or raise CHANNLIZE_TIMEOUT.`,\n 408,\n 'TIMEOUT'\n );\n }\n throw new ToolError(\n `Could not reach the Channlize API at ${this.config.baseUrl}: ${e.message}`\n );\n }\n\n const text = await res.text();\n let data: unknown = undefined;\n if (text) {\n try {\n data = JSON.parse(text);\n } catch {\n data = undefined;\n }\n }\n\n if (!res.ok) {\n const { message, code, body } = parseApiError(\n res.status,\n data,\n res.statusText\n );\n const retryAt =\n typeof body.retryAt === 'string' ? body.retryAt : undefined;\n throw new ToolError(\n hintFor(res.status, message.replace(/\\.$/, ''), code, body),\n res.status,\n code,\n retryAt\n );\n }\n if (data === undefined) {\n throw new ToolError(\n `Unexpected non-JSON response from ${method} ${url.pathname}`\n );\n }\n return data as T;\n }\n\n /**\n * `CHANNLIZE_PROJECT_ID`, or the first project of the key's organization\n * (`GET /projects/me`), looked up once.\n */\n projectId(): Promise<string> {\n if (this.config.projectId) return Promise.resolve(this.config.projectId);\n this.projectIdPromise ??= this.request<{ project: { id: string } }>(\n 'GET',\n '/projects/me'\n )\n .then(r => {\n if (!r.project?.id) {\n throw new ToolError(\n 'Could not find a project for this key: set CHANNLIZE_PROJECT_ID.'\n );\n }\n return r.project.id;\n })\n .catch(err => {\n this.projectIdPromise = undefined;\n throw err;\n });\n return this.projectIdPromise;\n }\n\n /** `@channlize/core` client bound to the widget key (visitor tools). */\n widget(): ChannlizeClient {\n if (!this.config.widgetKey) {\n throw new ToolError(\n 'This tool needs the public widget key (wk_…): set CHANNLIZE_WIDGET_KEY or pass --widget-key.'\n );\n }\n this.widgetClient ??= new ChannlizeClient({\n apiKey: this.config.widgetKey,\n projectId: this.config.projectId ?? '',\n baseUrl: this.config.baseUrl,\n timeout: this.config.timeout,\n });\n return this.widgetClient;\n }\n\n /** `@channlize/core` client for `notify` (server key + project). */\n async notifier(): Promise<ChannlizeClient> {\n const serverApiKey = this.requireServerKey();\n return new ChannlizeClient({\n // core requires a widget key; notify only uses serverApiKey.\n apiKey: this.config.widgetKey ?? 'unused',\n serverApiKey,\n projectId: await this.projectId(),\n baseUrl: this.config.baseUrl,\n timeout: this.config.timeout,\n });\n }\n}\n","import {\n DEFAULT_BASE_URL,\n DEFAULT_TIMEOUT,\n keyKind,\n readChannlizeEnv,\n} from '@channlize/core';\nimport type { ChannlizeMCPConfig } from './types';\n\n// Key detection lives in @channlize/core; re-exported for compatibility.\nexport { keyKind };\nexport type { KeyKind } from '@channlize/core';\n\n/** A configuration problem the user must fix; the CLI prints it and exits 1. */\nexport class ConfigError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ConfigError';\n }\n}\n\nexport interface ResolvedConfig {\n serverApiKey?: string;\n widgetKey?: string;\n projectId?: string;\n /** Default agent for the agent tools (multi-agent keys). */\n agentId?: string;\n baseUrl: string;\n timeout: number;\n}\n\nconst UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\nfunction clean(value: string | undefined): string | undefined {\n const v = value?.trim();\n return v ? v : undefined;\n}\n\n/**\n * Normalizes the config: `apiKey` (either kind, detected by prefix) fills\n * whichever of `serverApiKey` / `widgetKey` is missing, and a key passed in\n * the wrong slot fails with a message that says which one to use.\n */\nexport function resolveConfig(config: ChannlizeMCPConfig): ResolvedConfig {\n let serverApiKey = clean(config.serverApiKey);\n let widgetKey = clean(config.widgetKey);\n const apiKey = clean(config.apiKey);\n\n if (serverApiKey && keyKind(serverApiKey) === 'widget') {\n throw new ConfigError(\n 'CHANNLIZE_SERVER_API_KEY / --server-api-key holds a widget key (wk_…). ' +\n 'Widget keys are public and only work for the visitor tools: pass it as ' +\n 'CHANNLIZE_WIDGET_KEY / --widget-key, and create a server API key (ch_live_…) ' +\n 'under SDK & Integration → API keys in the Channlize dashboard.'\n );\n }\n if (widgetKey && keyKind(widgetKey) === 'server') {\n throw new ConfigError(\n 'CHANNLIZE_WIDGET_KEY / --widget-key holds a server API key. Pass server keys ' +\n '(ch_live_…) as CHANNLIZE_SERVER_API_KEY / --server-api-key; widget keys start with wk_.'\n );\n }\n if (apiKey) {\n if (keyKind(apiKey) === 'widget') widgetKey ??= apiKey;\n else serverApiKey ??= apiKey;\n }\n\n if (!serverApiKey && !widgetKey) {\n throw new ConfigError(\n 'A Channlize key is required. Set CHANNLIZE_SERVER_API_KEY (or --server-api-key) ' +\n 'to a server API key (ch_live_…) from SDK & Integration → API keys in the ' +\n 'Channlize dashboard. Use a read-scoped key for read-only access, or add the ' +\n 'write scope to send events, logs and conversations.'\n );\n }\n\n const timeout = config.timeout ?? DEFAULT_TIMEOUT;\n if (!Number.isFinite(timeout) || timeout <= 0) {\n throw new ConfigError(\n `Invalid timeout \"${config.timeout}\": use milliseconds, e.g. 10000`\n );\n }\n\n const baseUrl = (clean(config.baseUrl) ?? DEFAULT_BASE_URL).replace(\n /\\/+$/,\n ''\n );\n try {\n new URL(baseUrl);\n } catch {\n throw new ConfigError(\n `Invalid base URL \"${config.baseUrl}\": use e.g. ${DEFAULT_BASE_URL}`\n );\n }\n\n const agentId = clean(config.agentId);\n if (agentId && !UUID.test(agentId)) {\n throw new ConfigError(\n `Invalid agent ID \"${agentId}\": CHANNLIZE_AGENT_ID / --agent-id takes the agent's ID (a UUID, shown in the dashboard under Agents), not its slug.`\n );\n }\n\n return {\n serverApiKey,\n widgetKey,\n projectId: clean(config.projectId),\n agentId,\n baseUrl,\n timeout,\n };\n}\n\n/** Reads `ChannlizeMCPConfig` from the environment (CLI flags override it). */\nexport function configFromEnv(\n env: NodeJS.ProcessEnv = process.env\n): ChannlizeMCPConfig {\n const { timeout, serverApiKey, widgetKey, apiKey, projectId, baseUrl } =\n readChannlizeEnv(env);\n return {\n serverApiKey,\n widgetKey,\n apiKey,\n projectId,\n baseUrl,\n timeout: timeout ? Number(timeout) : undefined,\n // Read here rather than from core, so older @channlize/core versions work.\n agentId: clean(env.CHANNLIZE_AGENT_ID),\n };\n}\n","import type { McpServer } from '@modelcontextprotocol/server';\nimport * as z from 'zod/v4';\nimport { EVENTS, REACT_COMPONENTS } from './docs';\n\nfunction user(text: string) {\n return {\n messages: [\n { role: 'user' as const, content: { type: 'text' as const, text } },\n ],\n };\n}\n\n/** Prompts that use the live tools (need a server API key). */\nexport function registerServerPrompts(server: McpServer) {\n server.registerPrompt(\n 'triage-conversations',\n {\n title: 'Triage open conversations',\n description:\n 'Review open support conversations, rank them by urgency and draft a reply for each.',\n argsSchema: z.object({\n status: z\n .string()\n .optional()\n .describe(\n 'Status to triage: open (default), pending, resolved or closed'\n ),\n limit: z\n .string()\n .optional()\n .describe('How many conversations (default 10)'),\n }),\n },\n ({ status, limit }) =>\n user(`Triage my Channlize support inbox.\n\n1. Call list_conversations with status [\"${status || 'open'}\"] and limit ${Number(limit) || 10}.\n2. For each conversation, call get_conversation to read the thread.\n3. 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.\n4. 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.\n\nPresent 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.`)\n );\n\n server.registerPrompt(\n 'summarize-conversation',\n {\n title: 'Summarize a conversation',\n description: 'Summarize one conversation and suggest the next step.',\n argsSchema: z.object({\n conversationId: z.string().describe('Conversation ID'),\n }),\n },\n ({ conversationId }) =>\n user(\n `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.`\n )\n );\n\n server.registerPrompt(\n 'check-events',\n {\n title: 'Check Events delivery',\n description:\n 'Check that Events reach Slack: list them and explain failed or skipped deliveries.',\n argsSchema: z.object({}),\n },\n () =>\n user(`Check my Channlize Events setup.\n\n1. Call list_event_definitions and list the Events, flagging disabled drafts and Events without a Slack channel.\n2. Call list_event_deliveries (limit 50) and group the deliveries by status.\n3. For each failed or skipped delivery, explain the reason and how to fix it (enable the Event, pick a channel under Events in the dashboard, invite the Slack app to the channel, or connect Slack).`)\n );\n}\n\n/** Integration guides (no key needed beyond startup). */\nexport function registerGuidePrompts(server: McpServer) {\n server.registerPrompt(\n 'setup-events',\n {\n title: 'Add Events to my app',\n description:\n 'Add Channlize Events (notify Slack from server code) to the current codebase.',\n argsSchema: z.object({\n events: z\n .string()\n .optional()\n .describe('Events to add, e.g. \"signup, subscription upgrade\"'),\n }),\n },\n ({ events }) =>\n user(`Add Channlize Events to this codebase${events ? ` for: ${events}` : ''}.\n\nFind where these things happen on the server, then call notify there with a typed event map and an idempotency key derived from the record ID. Never call it from browser code. Read the server key from CHANNLIZE_SERVER_API_KEY and the project from CHANNLIZE_PROJECT_ID, and add both to the env example file. Don't let a notify failure break the request: catch and log it.\n\nReference:\n\n${EVENTS}`)\n );\n\n server.registerPrompt(\n 'setup-live-chat',\n {\n title: 'Add the chat widget',\n description:\n 'Add the Channlize live chat widget to a React or Next.js app.',\n argsSchema: z.object({\n framework: z\n .string()\n .optional()\n .describe('e.g. Next.js App Router, Vite, Remix'),\n }),\n },\n ({ framework }) =>\n user(`Add the Channlize chat widget to this ${framework || 'React'} app: install @channlize/react, render ChannlizeChat once in the root layout (from a 'use client' component on Next.js), read the widget key and project ID from public env variables, and match primaryColor to the app's brand color.\n\nReference:\n\n${REACT_COMPONENTS}`)\n );\n\n server.registerPrompt(\n 'integrate-contact-form',\n {\n title: 'Add a contact form',\n description: 'Add a Channlize contact form page to a React app.',\n argsSchema: z.object({\n styling: z\n .string()\n .optional()\n .describe('Styling approach, e.g. Tailwind or CSS modules'),\n }),\n },\n ({ styling }) =>\n user(`Add a contact page to this app using Channlize. Use the ContactForm component (or useContactForm with a custom form${styling ? ` styled with ${styling}` : ''}) inside ChannlizeProvider, show a clear success state, and surface errors from onError.\n\nReference:\n\n${REACT_COMPONENTS}`)\n );\n}\n","/**\n * Integration docs served as MCP resources and reused by the prompts.\n * Keep in sync with the public API of `@channlize/core` and\n * `@channlize/react` (their `src/index.ts`).\n */\n\nexport const QUICK_START = `# Channlize quick start\n\nChannlize routes website conversations and app events to Slack.\n\n## Keys\n- **Widget key** (\\`wk_…\\`): public, safe in browser code. Used by the chat widget,\n contact form and browser log tracking (\\`apiKey\\` in the SDK config).\n- **Server API key** (\\`ch_live_…\\`): secret, server only (\\`serverApiKey\\`). Scopes:\n \\`read\\` (conversations, contacts, logs, Events) and \\`write\\` (notify, server logs,\n create conversations/contacts). Create both under SDK & Integration → API keys.\n- **Project ID**: shown next to each widget key.\n\n## Install\n\\`\\`\\`bash\nnpm install @channlize/core # any JS runtime\nnpm install @channlize/react # React components and hooks\n\\`\\`\\`\n\n## Browser\n\\`\\`\\`ts\nimport { ChannlizeClient } from '@channlize/core';\n\nconst client = new ChannlizeClient({ apiKey: 'wk_…', projectId: '<project-id>' });\nawait client.submitContactForm({ name: 'Ada', email: 'ada@example.com', message: 'Hi!' });\nawait client.trackEvent('checkout.started', { properties: { cartId: 'c_1' } });\n\\`\\`\\`\n\n## Server\n\\`\\`\\`ts\nimport { createNotifier } from '@channlize/core';\n\n// Reads CHANNLIZE_SERVER_API_KEY (or CHANNLIZE_API_KEY) and CHANNLIZE_PROJECT_ID.\nconst notify = createNotifier();\nawait notify('user.subscribed', { username: 'ada', plan: 'Pro' });\n\\`\\`\\`\n\nErrors are \\`ChannlizeError\\` (\\`statusCode\\`, \\`code\\`), with subclasses\n\\`ValidationError\\` (400), \\`AuthenticationError\\` (401) and \\`RateLimitError\\` (429).\n`;\n\nexport const REACT_COMPONENTS = `# @channlize/react\n\n\\`\\`\\`bash\nnpm install @channlize/react\n\\`\\`\\`\n\n## Floating chat widget (all-in-one)\n\\`ChannlizeChat\\` includes the provider, launcher button and chat window.\n\n\\`\\`\\`tsx\n'use client';\nimport { ChannlizeChat } from '@channlize/react';\n\nexport function SupportWidget() {\n return (\n <ChannlizeChat\n config={{\n apiKey: process.env.NEXT_PUBLIC_CHANNLIZE_WIDGET_KEY!, // wk_…, public\n projectId: process.env.NEXT_PUBLIC_CHANNLIZE_PROJECT_ID!,\n }}\n position=\"bottom-right\"\n primaryColor=\"#2563eb\"\n theme=\"auto\"\n chatProps={{ title: 'Acme Support', greeting: 'Hi there!', welcomeMessage: 'Ask us anything.' }}\n />\n );\n}\n\\`\\`\\`\n\nKey props: \\`position\\` ('bottom-right' | 'bottom-left' | 'top-right' | 'top-left'),\n\\`primaryColor\\`, \\`theme\\` ('auto' | 'light' | 'dark'), \\`defaultOpen\\`, \\`showOnMobile\\`,\n\\`offset\\`, \\`zIndex\\`, \\`onOpen\\`, \\`onClose\\`, and \\`chatProps\\` (SupportChat props).\n\n## Provider + inline components\n\\`\\`\\`tsx\nimport { ChannlizeProvider, SupportChat, ContactForm } from '@channlize/react';\n\n<ChannlizeProvider config={{ apiKey: 'wk_…', projectId: '<project-id>' }}>\n <SupportChat title=\"Need help?\" greeting=\"Hi!\" suggestions={['Pricing', 'Billing']} />\n <ContactForm submitText=\"Send\" successMessage=\"Thanks! We'll reply by email.\" />\n</ChannlizeProvider>\n\\`\\`\\`\n\nSupportChat props include \\`title\\`, \\`greeting\\`, \\`welcomeMessage\\`, \\`suggestions\\`,\n\\`placeholder\\`, \\`allowAttachments\\`, \\`allowEndChat\\`, \\`theme\\`, \\`primaryColor\\`,\n\\`locale\\`, \\`maxLength\\`, \\`labels\\` and the \\`useChatSession\\` options\n(\\`autoConnect\\`, \\`metadata\\`, \\`persistSession\\`, \\`onMessage\\`, \\`onError\\`).\n\nContactForm props: \\`customFields\\`, \\`onSuccess\\`, \\`onError\\`, \\`className\\`, \\`styles\\`,\n\\`submitText\\`, \\`successMessage\\`.\n\n## Hooks (inside ChannlizeProvider)\n- \\`useChatSession(options)\\` → \\`{ session, messages, isConnecting, isConnected, error,\n sendMessage, startSession, endSession, reconnect }\\`\n- \\`useContactForm({ onSuccess, onError })\\` → \\`{ submit, isSubmitting, isSuccess, error, reset }\\`\n- \\`useChannlizeAnalytics()\\` → \\`{ track(name, { properties, severity }) }\\` (log tracking)\n- \\`useChannlize()\\` → \\`{ client, config }\\`\n\n## Next.js App Router\nComponents use state and effects: render them from a \\`'use client'\\` file. The widget\nkey is public (\\`NEXT_PUBLIC_…\\` is fine); never put the server API key in a\n\\`NEXT_PUBLIC_\\` variable.\n`;\n\nexport const EVENTS = `# Events: notify Slack from code\n\nEach event key (e.g. \\`user.subscribed\\`) has a Slack channel and a message template\nwith \\`{{field}}\\` placeholders, set under Events in the dashboard. A key that isn't set\nup yet is saved as a disabled draft the first time it is sent (\\`status: 'skipped'\\`),\nso you can ship code first and configure it after. Server only: needs a server API key\nwith the \\`write\\` scope.\n\n\\`\\`\\`ts\nimport { createNotifier } from '@channlize/core';\n\ntype AppEvents = {\n 'user.subscribed': { username: string; plan: string };\n 'invoice.paid': { amount: string; customer: string };\n};\n\n// Env: CHANNLIZE_SERVER_API_KEY (or CHANNLIZE_API_KEY), CHANNLIZE_PROJECT_ID.\nconst notify = createNotifier<AppEvents>();\n\nconst res = await notify('user.subscribed', { username: 'ada', plan: 'Pro' });\n// res.status: 'queued' | 'skipped' (see res.reason); res.duplicate on a repeated key\n\n// Retry-safe: an idempotency key already used posts nothing.\nawait notify('invoice.paid', { amount: '$49', customer: 'ada@example.com' }, { idempotencyKey: 'inv_123' });\n\\`\\`\\`\n\nTo type keys app-wide instead, augment the interface:\n\\`\\`\\`ts\ndeclare module '@channlize/core' {\n interface ChannlizeEvents {\n 'user.subscribed': { username: string; plan: string };\n }\n}\n\\`\\`\\`\n\nOver HTTP:\n\\`\\`\\`bash\ncurl -X POST https://api.channlize.com/v1/notify \\\\\n -H \"Authorization: Bearer $CHANNLIZE_SERVER_API_KEY\" \\\\\n -H \"Content-Type: application/json\" \\\\\n -H \"Idempotency-Key: signup-42\" \\\\\n -d '{\"projectId\":\"<project-id>\",\"event\":\"user.subscribed\",\"data\":{\"username\":\"ada\"}}'\n\\`\\`\\`\n\nLog tracking is separate: \\`client.trackEvent\\` (browser) / \\`trackServerEvent\\` (server)\nrecord log lines shown under Log tracking.\n`;\n","import type { McpServer } from '@modelcontextprotocol/server';\nimport type { ChannlizeApi } from './api';\nimport { EVENTS, QUICK_START, REACT_COMPONENTS } from './docs';\n\nconst markdown = (uri: string, text: string) => ({\n contents: [{ uri, mimeType: 'text/markdown', text }],\n});\n\nexport function registerResources(server: McpServer, api: ChannlizeApi) {\n server.registerResource(\n 'quick-start',\n 'channlize://docs/quick-start',\n {\n title: 'Channlize quick start',\n description:\n 'Keys, install, and first calls from the browser and the server.',\n mimeType: 'text/markdown',\n },\n uri => markdown(uri.href, QUICK_START)\n );\n server.registerResource(\n 'react-components',\n 'channlize://docs/react-components',\n {\n title: '@channlize/react components and hooks',\n description:\n 'ChannlizeChat, SupportChat, ContactForm, hooks and Next.js notes.',\n mimeType: 'text/markdown',\n },\n uri => markdown(uri.href, REACT_COMPONENTS)\n );\n server.registerResource(\n 'events',\n 'channlize://docs/events',\n {\n title: 'Events: notify Slack from code',\n description:\n 'createNotifier / notify with typed events, idempotency and curl.',\n mimeType: 'text/markdown',\n },\n uri => markdown(uri.href, EVENTS)\n );\n\n if (api.hasServerKey) {\n server.registerResource(\n 'project',\n 'channlize://project',\n {\n title: 'Current Channlize project',\n description:\n \"The key's project: ID, name, totals, permissions and Slack connection.\",\n mimeType: 'application/json',\n },\n async uri => {\n const r = await api.request<{ project: unknown }>(\n 'GET',\n '/projects/me'\n );\n return {\n contents: [\n {\n uri: uri.href,\n mimeType: 'application/json',\n text: JSON.stringify(r.project, null, 2),\n },\n ],\n };\n }\n );\n }\n}\n","/**\n * MCP tools for Channlize.\n *\n * Server-key tools (`ch_live_…`) are registered when a server API key is\n * configured; visitor tools (contact form, chat) when a widget key is. The\n * inbox tools (list, search, reply, assign, tag, close, notes, analytics,\n * routing rules) are defined in `inbox.ts`, and the agent tools (Channlize\n * for Agents) in `agents.ts`; neither depends on the MCP server. They are\n * registered here with `registerInboxTools` and `registerAgentTools`.\n * Every tool returns its result as `structuredContent` (matching its\n * `outputSchema`) plus the same JSON as text for clients that ignore it.\n * Failures are tool errors (`isError: true`) with a message that says how\n * to fix them.\n */\nimport type { McpServer } from '@modelcontextprotocol/server';\nimport * as z from 'zod/v4';\nimport { EVENT_KEY_PATTERN, EVENT_SEVERITIES } from '@channlize/core';\nimport { ChannlizeApi, toToolError } from './api';\nimport { AGENT_TOOLS } from './agents';\nimport { INBOX_TOOLS } from './inbox';\n\ntype Json = Record<string, unknown>;\n\nfunction ok(data: Json) {\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(data, null, 2) }],\n structuredContent: data,\n };\n}\n\n/** Runs a handler, turning any failure into a readable tool error. */\nasync function run(fn: () => Promise<Json>) {\n try {\n return ok(await fn());\n } catch (err) {\n const e = toToolError(err);\n return {\n content: [{ type: 'text' as const, text: e.message }],\n isError: true,\n };\n }\n}\n\nconst record = z.record(z.string(), z.unknown());\nconst loose = z.looseObject({});\nconst page = {\n total: z.number(),\n limit: z.number(),\n offset: z.number(),\n hasMore: z.boolean(),\n};\n\nconst READ = {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n} as const;\n\nexport function registerServerTools(server: McpServer, api: ChannlizeApi) {\n server.registerTool(\n 'get_project',\n {\n title: 'Get project',\n description:\n \"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.\",\n inputSchema: z.object({}),\n outputSchema: z.object({ project: loose }),\n annotations: READ,\n },\n () =>\n run(async () => {\n const r = await api.request<{ project: Json }>('GET', '/projects/me');\n return { project: r.project };\n })\n );\n\n server.registerTool(\n 'get_analytics',\n {\n title: 'Get analytics',\n description:\n 'Daily support activity for the last 30 days (UTC): conversations created and resolved, customer and agent messages.',\n inputSchema: z.object({}),\n outputSchema: z.object({ analytics: loose }),\n annotations: READ,\n },\n () =>\n run(async () => {\n const r = await api.request<{ analytics: Json }>(\n 'GET',\n '/projects/analytics'\n );\n return { analytics: r.analytics };\n })\n );\n\n server.registerTool(\n 'create_conversation',\n {\n title: 'Create conversation',\n description:\n '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.',\n inputSchema: z.object({\n customerEmail: z.email().describe(\"Customer's email address\"),\n customerName: z\n .string()\n .max(255)\n .optional()\n .describe(\"Customer's name\"),\n subject: z.string().min(1).max(500).describe('Subject line'),\n message: z.string().min(1).describe('First message, from the customer'),\n channel: z\n .string()\n .optional()\n .describe('Slack channel ID to post to, overriding routing rules'),\n tags: z.array(z.string()).max(20).optional().describe('Tags'),\n }),\n outputSchema: z.object({ conversation: loose }),\n annotations: {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: true,\n },\n },\n args =>\n run(async () => {\n const conversation = await api.request<Json>('POST', '/conversations', {\n body: args,\n });\n return { conversation };\n })\n );\n\n server.registerTool(\n 'list_contacts',\n {\n title: 'List contacts',\n description:\n 'List the customers who contacted the organization, with their conversation count. Paginate with limit/offset.',\n inputSchema: z.object({\n limit: z.number().int().min(1).max(100).default(50),\n offset: z.number().int().min(0).default(0),\n }),\n outputSchema: z.object({ contacts: z.array(loose), ...page }),\n annotations: READ,\n },\n ({ limit, offset }) =>\n run(async () => {\n const r = await api.request<Json>('GET', '/contacts', {\n query: { limit, offset },\n });\n return {\n contacts: (r.contacts as Json[]) ?? [],\n total: Number(r.total ?? 0),\n limit: Number(r.limit ?? limit),\n offset: Number(r.offset ?? offset),\n hasMore: Boolean(r.hasMore),\n };\n })\n );\n\n server.registerTool(\n 'get_contact',\n {\n title: 'Get contact',\n description: 'Read one contact (customer) by ID.',\n inputSchema: z.object({\n contactId: z\n .string()\n .uuid()\n .describe('Contact ID (from list_contacts)'),\n }),\n outputSchema: z.object({ contact: loose }),\n annotations: READ,\n },\n ({ contactId }) =>\n run(async () => {\n const contact = await api.request<Json>(\n 'GET',\n `/contacts/${encodeURIComponent(contactId)}`\n );\n return { contact };\n })\n );\n\n server.registerTool(\n 'create_contact',\n {\n title: 'Create contact',\n description:\n 'Add a customer by email, or return the existing one with that email. Needs the write scope.',\n inputSchema: z.object({\n email: z.email(),\n name: z.string().max(255).optional(),\n company: z.string().optional(),\n phone: z.string().optional(),\n tags: z.array(z.string()).max(20).optional(),\n }),\n outputSchema: z.object({ contact: loose }),\n annotations: {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n },\n args =>\n run(async () => {\n const contact = await api.request<Json>('POST', '/contacts', {\n body: args,\n });\n return { contact };\n })\n );\n\n server.registerTool(\n 'notify_event',\n {\n title: 'Send an Event to Slack',\n description:\n '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.',\n inputSchema: z.object({\n event: z\n .string()\n .max(100)\n .regex(\n EVENT_KEY_PATTERN,\n 'lowercase letters, digits, dots, underscores or dashes'\n )\n .describe('Event key, e.g. user.subscribed'),\n data: record\n .optional()\n .describe(\n 'Template fields, e.g. { \"username\": \"ada\", \"plan\": \"Pro\" }'\n ),\n idempotencyKey: z\n .string()\n .min(1)\n .max(255)\n .optional()\n .describe('Send at most once per key (retry-safe)'),\n channel: z\n .string()\n .optional()\n .describe(\"Slack channel ID instead of the event's channel\"),\n }),\n outputSchema: z.looseObject({\n id: z.string(),\n event: z.string(),\n status: z.string(),\n reason: z.string().optional(),\n duplicate: z.boolean().optional(),\n }),\n annotations: {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: true,\n },\n },\n ({ event, data, idempotencyKey, channel }) =>\n run(async () => {\n const client = await api.notifier();\n const r = await client.notify(event, data, { idempotencyKey, channel });\n return {\n id: r.id,\n event: r.event,\n status: r.status,\n ...(r.reason ? { reason: r.reason } : {}),\n ...(r.duplicate ? { duplicate: true } : {}),\n };\n })\n );\n\n server.registerTool(\n 'list_event_definitions',\n {\n title: 'List Events',\n description:\n '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.',\n inputSchema: z.object({}),\n outputSchema: z.object({\n projectId: z.string(),\n definitions: z.array(loose),\n }),\n annotations: READ,\n },\n () =>\n run(async () => {\n const projectId = await api.projectId();\n const r = await api.request<{ definitions: Json[] }>(\n 'GET',\n `/v1/projects/${encodeURIComponent(projectId)}/event-definitions`\n );\n return { projectId, definitions: r.definitions ?? [] };\n })\n );\n\n server.registerTool(\n 'list_event_deliveries',\n {\n title: 'List Event deliveries',\n description:\n '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.',\n inputSchema: z.object({\n definitionId: z\n .string()\n .uuid()\n .optional()\n .describe('Only this Event (ID from list_event_definitions)'),\n limit: z.number().int().min(1).max(100).default(20),\n }),\n outputSchema: z.object({\n projectId: z.string(),\n deliveries: z.array(loose),\n }),\n annotations: READ,\n },\n ({ definitionId, limit }) =>\n run(async () => {\n const projectId = await api.projectId();\n const r = await api.request<{ deliveries: Json[] }>(\n 'GET',\n `/v1/projects/${encodeURIComponent(projectId)}/event-deliveries`,\n { query: { definitionId, limit } }\n );\n return { projectId, deliveries: r.deliveries ?? [] };\n })\n );\n\n server.registerTool(\n 'query_logs',\n {\n title: 'Query logs',\n description:\n '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.',\n inputSchema: z.object({\n severity: z.enum(EVENT_SEVERITIES).optional(),\n source: z\n .enum(['client_sdk', 'server_api', 'system'])\n .optional()\n .describe(\n 'client_sdk = browser (widget key), server_api = server key'\n ),\n search: z.string().max(200).optional().describe('Text to look for'),\n from: z.iso\n .datetime({ offset: true })\n .optional()\n .describe('ISO 8601 start'),\n to: z.iso\n .datetime({ offset: true })\n .optional()\n .describe('ISO 8601 end'),\n projectId: z.string().uuid().optional(),\n limit: z.number().int().min(1).max(100).default(50),\n offset: z.number().int().min(0).default(0),\n }),\n outputSchema: z.object({ events: z.array(loose), ...page }),\n annotations: READ,\n },\n args =>\n run(async () => {\n const r = await api.request<Json>('GET', '/v1/events', { query: args });\n return {\n events: (r.events as Json[]) ?? [],\n total: Number(r.total ?? 0),\n limit: Number(r.limit ?? args.limit),\n offset: Number(r.offset ?? args.offset),\n hasMore: Boolean(r.hasMore),\n };\n })\n );\n\n server.registerTool(\n 'track_log',\n {\n title: 'Record a log',\n description:\n '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.',\n inputSchema: z.object({\n name: z\n .string()\n .min(1)\n .max(255)\n .describe('Log name, e.g. payment.failed'),\n severity: z.enum(EVENT_SEVERITIES).default('info'),\n properties: record.optional().describe('Extra fields'),\n }),\n outputSchema: z.object({ id: z.string(), projectId: z.string() }),\n annotations: {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: false,\n },\n },\n ({ name, severity, properties }) =>\n run(async () => {\n const projectId = await api.projectId();\n const r = await api.request<{ id: string }>('POST', '/v1/events', {\n body: { projectId, name, severity, properties },\n });\n return { id: r.id, projectId };\n })\n );\n}\n\nconst VISITOR = {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: true,\n} as const;\n\n/** Tools that act as a website visitor, with the public widget key. */\nexport function registerWidgetTools(server: McpServer, api: ChannlizeApi) {\n server.registerTool(\n 'submit_contact_form',\n {\n title: 'Submit contact form',\n description:\n '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.',\n inputSchema: z.object({\n name: z.string().min(1).describe(\"Visitor's name\"),\n email: z.email().describe(\"Visitor's email\"),\n subject: z.string().optional(),\n message: z.string().min(1),\n pageUrl: z.url().optional().describe('Page the form was sent from'),\n }),\n outputSchema: z.looseObject({\n conversationId: z.string().optional(),\n message: z.string().optional(),\n }),\n annotations: VISITOR,\n },\n args =>\n run(async () => {\n const r = await api.widget().submitContactForm(args);\n return { conversationId: r.conversationId, message: r.message };\n })\n );\n\n server.registerTool(\n 'create_chat_session',\n {\n title: 'Start chat session',\n description:\n 'Start a live chat session as a website visitor (widget key). Returns the session ID for send_message.',\n inputSchema: z.object({\n metadata: record\n .optional()\n .describe('Metadata to attach (e.g. user info)'),\n }),\n outputSchema: z.looseObject({\n sessionId: z.string(),\n status: z.string(),\n }),\n annotations: VISITOR,\n },\n ({ metadata }) =>\n run(async () => {\n const r = await api.widget().createChatSession(metadata);\n return {\n sessionId: r.session.id,\n status: r.session.status,\n createdAt: String(r.session.createdAt),\n };\n })\n );\n\n server.registerTool(\n 'send_message',\n {\n title: 'Send chat message',\n description:\n 'Send a visitor message in a chat session (widget key); it is posted to the Slack thread.',\n inputSchema: z.object({\n sessionId: z.string().min(1).describe('From create_chat_session'),\n content: z.string().min(1).max(5000),\n }),\n outputSchema: z.looseObject({\n messageId: z.string(),\n sessionStatus: z.string(),\n }),\n annotations: VISITOR,\n },\n ({ sessionId, content }) =>\n run(async () => {\n const r = await api.widget().sendMessage(sessionId, content);\n return { messageId: r.message.id, sessionStatus: r.session.status };\n })\n );\n\n server.registerTool(\n 'get_chat_messages',\n {\n title: 'Read chat messages',\n description:\n \"Read a chat session's messages, including agent replies from Slack (widget key).\",\n inputSchema: z.object({\n sessionId: z.string().min(1),\n limit: z.number().int().min(1).max(100).default(50),\n offset: z.number().int().min(0).default(0),\n }),\n outputSchema: z.object({\n sessionId: z.string(),\n messages: z.array(loose),\n }),\n annotations: { ...READ, openWorldHint: true },\n },\n ({ sessionId, limit, offset }) =>\n run(async () => {\n const messages = await api\n .widget()\n .getChatMessages(sessionId, limit, offset);\n return {\n sessionId,\n messages: messages.map(m => ({\n id: m.id,\n author: m.author,\n authorName: m.authorData?.name,\n content: m.content,\n timestamp: String(m.timestamp),\n attachments: m.attachments?.length ?? 0,\n })),\n };\n })\n );\n\n server.registerTool(\n 'close_chat_session',\n {\n title: 'End chat session',\n description: 'End a chat session as the visitor (widget key).',\n inputSchema: z.object({ sessionId: z.string().min(1) }),\n outputSchema: z.looseObject({\n sessionId: z.string(),\n status: z.string(),\n }),\n annotations: { ...VISITOR, idempotentHint: true },\n },\n ({ sessionId }) =>\n run(async () => {\n const s = await api.widget().closeChatSession(sessionId);\n return { sessionId: s.id ?? sessionId, status: s.status };\n })\n );\n}\n\n/**\n * Register the inbox tools (`INBOX_TOOLS` from `inbox.ts`). They are listed\n * for every server key; a call the key's scopes don't allow returns a tool\n * error naming the scope to add.\n */\ntype ToolDefinition = Pick<\n (typeof INBOX_TOOLS)[number],\n | 'name'\n | 'title'\n | 'description'\n | 'inputSchema'\n | 'outputSchema'\n | 'annotations'\n> & { handler: (api: ChannlizeApi, args: never) => Promise<unknown> };\n\nfunction registerAll(\n server: McpServer,\n api: ChannlizeApi,\n tools: readonly ToolDefinition[]\n) {\n for (const tool of tools) {\n server.registerTool(\n tool.name,\n {\n title: tool.title,\n description: tool.description,\n inputSchema: tool.inputSchema,\n outputSchema: tool.outputSchema,\n annotations: tool.annotations,\n },\n (args: unknown) =>\n run(async () => (await tool.handler(api, args as never)) as Json)\n );\n }\n}\n\nexport function registerInboxTools(server: McpServer, api: ChannlizeApi) {\n registerAll(server, api, INBOX_TOOLS);\n}\n\n/** Channlize for Agents: messages, tasks, inbox, directory and channels. */\nexport function registerAgentTools(server: McpServer, api: ChannlizeApi) {\n registerAll(server, api, AGENT_TOOLS);\n}\n","/**\n * The Channlize for Agents toolset: names, zod input/output schemas and\n * handlers for talking to other agents and to people in agent channels,\n * through `/v1/agents`.\n *\n * Like `inbox.ts`, it has no dependency on the MCP server or its\n * transports, so any agent can import it (`@channlize/mcp/agents`): the\n * stdio/HTTP server registers these tools (`registerAgentTools` in\n * `tools.ts`), and an LLM loop can run the same handlers with its own client\n * (anything with a `request(method, path, { query, body })`).\n *\n * Identity: the key decides who the tools act as. An agent key acts as its\n * agent; a multi-agent key acts as one of its agents, picked by `agentId`\n * on the call or the requester's default `agentId` (`CHANNLIZE_AGENT_ID` /\n * `--agent-id` on the server).\n *\n * Scopes: `agents:send` (post messages, create, update and hand off\n * tasks, answer escalated questions), `agents:read` (directory, channels,\n * inbox and ack, tasks, the org chart), `agents:ask_human` (ask people and\n * read the answer) and `agents:admin` (`get_effective_policy` only).\n *\n * No admin-write tools: changing policies, teams, the org chart or an\n * agent's status stays in the dashboard or `@channlize/core` with an\n * `agents:admin` key. Policies are the guardrails on what an agent may do,\n * so the agent that runs these tools shouldn't be able to rewrite them.\n */\nimport * as z from 'zod/v4';\nimport { ToolError, type HttpMethod } from './api';\nimport type { ToolAnnotations } from './inbox';\n\ntype Json = Record<string, unknown>;\ntype Query = Record<string, string | number | boolean | undefined>;\n\n/** What a handler needs: `ChannlizeApi` from this package, or your own. */\nexport interface AgentsRequester {\n request<T>(\n method: HttpMethod,\n path: string,\n /** `timeout` (ms) overrides the default, for the `get_answer` long-poll. */\n options?: { query?: Query; body?: unknown; timeout?: number }\n ): Promise<T>;\n /** The agent to act as when a call doesn't pass `agentId`. */\n readonly agentId?: string;\n}\n\n/** The API key scope a tool needs. */\nexport type AgentScope =\n 'agents:send' | 'agents:read' | 'agents:ask_human' | 'agents:admin';\n\nexport interface AgentTool<\n I extends z.ZodObject = z.ZodObject,\n O extends z.ZodObject = z.ZodObject,\n> {\n name: string;\n title: string;\n description: string;\n scope: AgentScope;\n /** The HTTP endpoint it calls, for docs and logs. */\n endpoint: string;\n inputSchema: I;\n outputSchema: O;\n annotations: ToolAnnotations;\n handler: (api: AgentsRequester, args: z.output<I>) => Promise<z.output<O>>;\n}\n\nfunction defineTool<I extends z.ZodObject, O extends z.ZodObject>(\n tool: AgentTool<I, O>\n): AgentTool {\n return tool as unknown as AgentTool;\n}\n\n/** Task lifecycle (same values as the API). */\nexport const AGENT_TASK_STATUSES = [\n 'open',\n 'working',\n 'input_required',\n 'completed',\n 'failed',\n 'canceled',\n 'rejected',\n] as const;\n\n// ----- shared schemas -----\n\nconst uuid = (what: string) => z.string().uuid().describe(what);\n\nconst agentId = uuid(\n '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.'\n).optional();\n\nconst channelId = uuid('Agent channel ID (from list_agent_channels)');\n\nconst threadId = uuid(\n 'Reply in this thread: the id of any message in it (thread_id or id from read_agent_inbox)'\n).optional();\n\nconst mentions = z\n .array(z.string().uuid())\n .max(50)\n .optional()\n .describe('Agent IDs to mention (from list_agents)');\n\nconst data = z\n .record(z.string(), z.unknown())\n .optional()\n .describe('Structured data for the recipients (JSON object)');\n\nconst usage = {\n tokens: z\n .number()\n .int()\n .min(0)\n .optional()\n .describe('Tokens you used for this message (reporting)'),\n cost: z\n .number()\n .min(0)\n .optional()\n .describe('What this message cost you, in USD (reporting)'),\n};\n\nconst message = z.looseObject({\n id: z.string(),\n channel_id: z.string(),\n thread_id: z.string().nullable(),\n type: z.string(),\n text: z.string(),\n sender: z.looseObject({ kind: z.string() }),\n task_status: z.string().nullable().optional(),\n});\n\nconst sendOutput = z.object({\n message,\n deliveries: z.array(\n z.looseObject({ id: z.string(), agent_id: z.string(), status: z.string() })\n ),\n});\n\nconst dueAt = z\n .string()\n .max(40)\n .optional()\n .describe('Due date: an ISO date (2026-11-30) or date-time');\n\nconst task = z.looseObject({\n id: z.string(),\n channel_id: z.string(),\n text: z.string(),\n board_status: z.string(),\n assignee_agent_id: z.string().nullable(),\n due_at: z.string().nullable(),\n});\n\nconst deliveries = z.array(\n z.looseObject({ id: z.string(), agent_id: z.string(), status: z.string() })\n);\n\nconst question = z.looseObject({\n id: z.string(),\n kind: z.string(),\n question: z.string(),\n status: z.string(),\n answer: z.looseObject({}).nullable(),\n});\n\nconst questionId = uuid('The question ID (from ask_human or list_questions)');\n\nconst BOARD_STATUSES = [\n 'open',\n 'in_progress',\n 'blocked',\n 'done',\n 'failed',\n] as const;\n\n/** The longest single long-poll the API holds (`/questions/:id/wait`). */\nexport const QUESTION_WAIT_MAX_SECONDS = 25;\n\nconst READ: ToolAnnotations = {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n};\nconst SEND: ToolAnnotations = {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: true,\n};\n\n/** The call's agent, else the requester's default. */\nfunction actingAs(api: AgentsRequester, id: string | undefined) {\n return id ?? api.agentId;\n}\n\n/** Inbox and ack need the agent in the path. */\nfunction requireAgent(api: AgentsRequester, id: string | undefined): string {\n const agent = actingAs(api, id);\n if (!agent) {\n throw new ToolError(\n 'Pass agentId (from list_agents), or set CHANNLIZE_AGENT_ID / --agent-id on the MCP server.'\n );\n }\n return agent;\n}\n\nasync function send(\n api: AgentsRequester,\n body: Json\n): Promise<z.output<typeof sendOutput>> {\n const r = await api.request<z.output<typeof sendOutput>>(\n 'POST',\n '/v1/agents/messages',\n { body }\n );\n return { message: r.message, deliveries: r.deliveries ?? [] };\n}\n\nconst enc = encodeURIComponent;\n\n/** One line about a closed question, for the model. */\nfunction outcomeMessage(status: string, q: Json): string {\n const answer = (q.answer ?? {}) as Json;\n const choice = answer.option_label ?? answer.option_id;\n const comment = answer.comment ? `: ${String(answer.comment)}` : '';\n switch (status) {\n case 'answered':\n if (q.kind === 'approval') {\n return answer.approved\n ? `Approved${comment}. Go ahead.`\n : `Denied${comment}. Don't do it.`;\n }\n return `Answered: ${[choice, answer.text].filter(Boolean).join(' / ') || '(empty)'}.`;\n case 'expired_default':\n return `Nobody answered by the deadline: the default option applies (${String(choice ?? 'none')}).`;\n case 'expired':\n 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.';\n case 'canceled':\n return 'The question was canceled.';\n default:\n return `Status: ${status}.`;\n }\n}\n\n// ----- the tools -----\n\nexport const AGENT_TOOLS: readonly AgentTool[] = [\n defineTool({\n name: 'send_agent_message',\n title: 'Send agent message',\n description:\n '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.',\n scope: 'agents:send',\n endpoint: 'POST /v1/agents/messages',\n inputSchema: z.object({\n agentId,\n channelId,\n text: z.string().min(1).max(40_000).describe('Message text'),\n threadId,\n mentions,\n data,\n ...usage,\n }),\n outputSchema: sendOutput,\n annotations: SEND,\n handler: (api, a) =>\n send(api, {\n agent_id: actingAs(api, a.agentId),\n channel_id: a.channelId,\n type: 'message',\n text: a.text,\n thread_id: a.threadId,\n mentions: a.mentions,\n data: a.data,\n tokens: a.tokens,\n cost: a.cost,\n }),\n }),\n\n defineTool({\n name: 'create_task',\n title: 'Create task',\n description:\n '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.',\n scope: 'agents:send',\n endpoint: 'POST /v1/agents/tasks',\n inputSchema: z.object({\n agentId,\n channelId,\n text: z\n .string()\n .min(1)\n .max(40_000)\n .describe('What should be done, with enough context to do it'),\n assigneeAgentId: uuid(\n 'The agent that should do it: a member of the channel (from list_agents)'\n ).optional(),\n dueAt,\n threadId,\n mentions,\n data,\n }),\n // `message` is the task too (a task is its `task` message plus board fields).\n outputSchema: z.object({ taskId: z.string(), task, message, deliveries }),\n annotations: SEND,\n handler: async (api, a) => {\n const r = await api.request<{ task: Json; deliveries?: Json[] }>(\n 'POST',\n '/v1/agents/tasks',\n {\n body: {\n agent_id: actingAs(api, a.agentId),\n channel_id: a.channelId,\n text: a.text,\n assignee_agent_id: a.assigneeAgentId,\n due_at: a.dueAt,\n thread_id: a.threadId,\n mentions: a.mentions,\n data: a.data,\n },\n }\n );\n return {\n taskId: String(r.task.id),\n task: r.task as never,\n message: r.task as never,\n deliveries: (r.deliveries ?? []) as never,\n };\n },\n }),\n\n defineTool({\n name: 'update_task_status',\n title: 'Update task status',\n description:\n '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 → in_progress, input_required → blocked, completed → 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.',\n scope: 'agents:send',\n endpoint: 'POST /v1/agents/messages',\n inputSchema: z.object({\n agentId,\n channelId,\n taskId: uuid('The task message ID'),\n status: z\n .enum(AGENT_TASK_STATUSES)\n .describe('The new status of the task'),\n text: z\n .string()\n .max(40_000)\n .optional()\n .describe('What changed, e.g. the result or what input is needed'),\n data,\n ...usage,\n }),\n outputSchema: sendOutput,\n annotations: SEND,\n handler: (api, a) =>\n send(api, {\n agent_id: actingAs(api, a.agentId),\n channel_id: a.channelId,\n type: 'status',\n text: a.text ?? '',\n task_id: a.taskId,\n task_status: a.status,\n data: a.data,\n tokens: a.tokens,\n cost: a.cost,\n }),\n }),\n\n defineTool({\n name: 'update_task',\n title: 'Update task',\n description:\n \"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.\",\n scope: 'agents:send',\n endpoint: 'PATCH /v1/agents/tasks/:taskId',\n inputSchema: z.object({\n agentId,\n taskId: uuid('The task ID'),\n status: z.enum(BOARD_STATUSES).optional().describe('The board column'),\n dueAt: z\n .string()\n .max(40)\n .nullable()\n .optional()\n .describe('New due date (ISO date or date-time); null clears it'),\n note: z\n .string()\n .max(2000)\n .optional()\n .describe('What changed, shown with the update'),\n }),\n outputSchema: z.object({ task, changed: z.boolean() }),\n annotations: SEND,\n handler: async (api, a) => {\n if (a.status === undefined && a.dueAt === undefined) {\n throw new ToolError('Pass status or dueAt.');\n }\n const r = await api.request<{ task: Json; changed?: boolean }>(\n 'PATCH',\n `/v1/agents/tasks/${enc(a.taskId)}`,\n {\n body: {\n agent_id: actingAs(api, a.agentId),\n status: a.status,\n due_at: a.dueAt,\n note: a.note,\n },\n }\n );\n return { task: r.task as never, changed: Boolean(r.changed) };\n },\n }),\n\n defineTool({\n name: 'handoff_task',\n title: 'Hand off task',\n description:\n \"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.\",\n scope: 'agents:send',\n endpoint: 'POST /v1/agents/tasks/:taskId/handoff',\n inputSchema: z.object({\n agentId,\n taskId: uuid('The task ID'),\n toAgentId: uuid('The new assignee (from list_agents or get_org_chart)'),\n reason: z\n .string()\n .max(2000)\n .optional()\n .describe('Why, and what the new assignee needs to know'),\n }),\n outputSchema: z.object({ task, deliveries }),\n annotations: SEND,\n handler: async (api, a) => {\n const r = await api.request<{ task: Json; deliveries?: Json[] }>(\n 'POST',\n `/v1/agents/tasks/${enc(a.taskId)}/handoff`,\n {\n body: {\n agent_id: actingAs(api, a.agentId),\n to_agent_id: a.toAgentId,\n reason: a.reason,\n },\n }\n );\n return {\n task: r.task as never,\n deliveries: (r.deliveries ?? []) as never,\n };\n },\n }),\n\n defineTool({\n name: 'list_tasks',\n title: 'List tasks',\n description:\n \"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.\",\n scope: 'agents:read',\n endpoint: 'GET /v1/agents/tasks',\n inputSchema: z.object({\n agentId,\n channelId: channelId.optional(),\n assigneeAgentId: uuid('Only tasks assigned to this agent').optional(),\n status: z.enum(BOARD_STATUSES).optional(),\n limit: z\n .number()\n .int()\n .min(1)\n .max(500)\n .default(50)\n .describe('How many to return (1-500, default 50)'),\n }),\n outputSchema: z.object({ tasks: z.array(task) }),\n annotations: READ,\n handler: async (api, a) => {\n const r = await api.request<{ tasks?: Json[] }>(\n 'GET',\n '/v1/agents/tasks',\n {\n query: {\n agent_id: actingAs(api, a.agentId),\n channel_id: a.channelId,\n assignee_agent_id: a.assigneeAgentId,\n status: a.status,\n limit: a.limit,\n },\n }\n );\n return { tasks: (r.tasks ?? []) as never };\n },\n }),\n\n defineTool({\n name: 'get_task_board',\n title: 'Get task board',\n description:\n \"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.\",\n scope: 'agents:read',\n endpoint: 'GET /v1/agents/tasks/board',\n inputSchema: z.object({\n agentId,\n channelId,\n assigneeAgentId: uuid('Only tasks assigned to this agent').optional(),\n }),\n outputSchema: z.object({\n channel_id: z.string(),\n columns: z.record(z.string(), z.array(task)),\n counts: z.record(z.string(), z.number()),\n agents: z.array(z.looseObject({ id: z.string() })),\n truncated: z.boolean(),\n }),\n annotations: READ,\n handler: async (api, a) =>\n (await api.request<Json>('GET', '/v1/agents/tasks/board', {\n query: {\n agent_id: actingAs(api, a.agentId),\n channel_id: a.channelId,\n assignee_agent_id: a.assigneeAgentId,\n },\n })) as never,\n }),\n\n defineTool({\n name: 'ask_human',\n title: 'Ask a human',\n description:\n \"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.\",\n scope: 'agents:ask_human',\n endpoint: 'POST /v1/agents/questions',\n inputSchema: z.object({\n agentId,\n kind: z\n .enum(['question', 'approval'])\n .default('question')\n .describe('question (default) or approval (answered Approve / Deny)'),\n question: z\n .string()\n .min(1)\n .max(3000)\n .describe('The question, with what people need to answer it'),\n options: z\n .array(\n z.object({\n id: z.string().min(1).max(100),\n label: z.string().min(1).max(75),\n })\n )\n .max(10)\n .optional()\n .describe('Up to 10 answers to pick from (ignored for approvals)'),\n freeText: z\n .boolean()\n .optional()\n .describe('Allow a typed answer (always on without options)'),\n urgency: z\n .enum(['low', 'normal', 'high', 'urgent'])\n .optional()\n .describe('How fast it escalates (default normal)'),\n deadline: z\n .string()\n .max(40)\n .optional()\n .describe('ISO date-time, at most 30 days away'),\n defaultOption: z\n .string()\n .max(100)\n .optional()\n .describe('Option id applied at the deadline when nobody answered'),\n channelId: channelId\n .optional()\n .describe('Post it in this agent channel (from list_agent_channels)'),\n threadId,\n context: z\n .record(z.string(), z.unknown())\n .optional()\n .describe('Facts shown with the question (JSON object)'),\n amount: z\n .number()\n .min(0)\n .optional()\n .describe('Approvals: the amount at stake'),\n currency: z\n .string()\n .regex(/^[A-Za-z]{3}$/)\n .optional()\n .describe('Approvals: ISO 4217 currency code'),\n resource: z\n .record(z.string(), z.unknown())\n .optional()\n .describe('Approvals: what is being approved (JSON object)'),\n requiredRoles: z\n .array(z.string().min(1).max(40))\n .max(10)\n .optional()\n .describe('Approvals: roles that may answer, e.g. [\"admin\"]'),\n }),\n outputSchema: z.object({ questionId: z.string(), question }),\n annotations: SEND,\n handler: async (api, a) => {\n const r = await api.request<{ question: Json }>(\n 'POST',\n '/v1/agents/questions',\n {\n body: {\n agent_id: actingAs(api, a.agentId),\n kind: a.kind,\n question: a.question,\n options: a.options,\n free_text: a.freeText,\n urgency: a.urgency,\n deadline: a.deadline,\n default_option: a.defaultOption,\n channel_id: a.channelId,\n thread_id: a.threadId,\n context: a.context,\n amount: a.amount,\n currency: a.currency,\n resource: a.resource,\n required_roles: a.requiredRoles,\n },\n }\n );\n return {\n questionId: String(r.question.id),\n question: r.question as never,\n };\n },\n }),\n\n defineTool({\n name: 'get_answer',\n title: 'Get answer',\n 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).`,\n scope: 'agents:ask_human',\n endpoint: 'GET /v1/agents/questions/:id/wait',\n inputSchema: z.object({\n agentId,\n questionId,\n waitSeconds: z\n .number()\n .int()\n .min(0)\n .max(QUESTION_WAIT_MAX_SECONDS)\n .default(QUESTION_WAIT_MAX_SECONDS)\n .describe(\n `Seconds to wait for an answer (0-${QUESTION_WAIT_MAX_SECONDS}, default ${QUESTION_WAIT_MAX_SECONDS}); 0 only checks`\n ),\n }),\n outputSchema: z.object({\n questionId: z.string(),\n status: z.string(),\n waiting: z.boolean(),\n answer: z.looseObject({}).nullable(),\n message: z.string(),\n question,\n }),\n annotations: READ,\n handler: async (api, a) => {\n const r = await api.request<{ question: Json; timed_out?: boolean }>(\n 'GET',\n `/v1/agents/questions/${enc(a.questionId)}/wait`,\n {\n query: {\n agent_id: actingAs(api, a.agentId),\n timeout: a.waitSeconds,\n },\n // The API holds the request for up to waitSeconds.\n timeout: (a.waitSeconds + 10) * 1000,\n }\n );\n const status = String(r.question.status);\n const waiting = status === 'open';\n return {\n questionId: a.questionId,\n status,\n waiting,\n answer: (r.question.answer ?? null) as never,\n message: waiting\n ? `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.`\n : outcomeMessage(status, r.question),\n question: r.question as never,\n };\n },\n }),\n\n defineTool({\n name: 'list_questions',\n title: 'List questions',\n description:\n '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).',\n scope: 'agents:read',\n endpoint: 'GET /v1/agents/questions',\n inputSchema: z.object({\n agentId,\n status: z\n .enum(['open', 'answered', 'expired_default', 'expired', 'canceled'])\n .optional(),\n kind: z.enum(['question', 'approval']).optional(),\n channelId: channelId.optional(),\n cursor: z\n .string()\n .max(300)\n .optional()\n .describe('nextCursor of the previous call'),\n limit: z\n .number()\n .int()\n .min(1)\n .max(200)\n .default(20)\n .describe('How many to return (1-200, default 20)'),\n }),\n outputSchema: z.object({\n questions: z.array(question),\n nextCursor: z.string().nullable(),\n }),\n annotations: READ,\n handler: async (api, a) => {\n const r = await api.request<{\n questions?: Json[];\n next_cursor?: string | null;\n }>('GET', '/v1/agents/questions', {\n query: {\n agent_id: actingAs(api, a.agentId),\n status: a.status,\n kind: a.kind,\n channel_id: a.channelId,\n cursor: a.cursor,\n limit: a.limit,\n },\n });\n return {\n questions: (r.questions ?? []) as never,\n nextCursor: r.next_cursor ?? null,\n };\n },\n }),\n\n defineTool({\n name: 'cancel_question',\n title: 'Cancel question',\n description:\n \"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.\",\n scope: 'agents:ask_human',\n endpoint: 'DELETE /v1/agents/questions/:id',\n inputSchema: z.object({ agentId, questionId }),\n outputSchema: z.object({ question }),\n annotations: {\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: false,\n openWorldHint: true,\n },\n handler: async (api, a) => {\n const r = await api.request<{ question: Json }>(\n 'DELETE',\n `/v1/agents/questions/${enc(a.questionId)}`,\n { query: { agent_id: actingAs(api, a.agentId) } }\n );\n return { question: r.question as never };\n },\n }),\n\n defineTool({\n name: 'answer_escalated_question',\n title: 'Answer escalated question',\n description:\n \"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.\",\n scope: 'agents:send',\n endpoint: 'POST /v1/agents/questions/:id/answer',\n inputSchema: z.object({\n agentId,\n questionId,\n optionId: z\n .string()\n .min(1)\n .max(100)\n .optional()\n .describe('One of the question options (approve / deny for approvals)'),\n text: z\n .string()\n .max(3000)\n .optional()\n .describe('A typed answer, when the question allows free text'),\n comment: z\n .string()\n .max(2000)\n .optional()\n .describe('Why (shown with the answer; say why on a deny)'),\n }),\n outputSchema: z.object({ question }),\n annotations: SEND,\n handler: async (api, a) => {\n if (!a.optionId && !a.text) throw new ToolError('Pass optionId or text.');\n const r = await api.request<{ question: Json }>(\n 'POST',\n `/v1/agents/questions/${enc(a.questionId)}/answer`,\n {\n body: {\n agent_id: actingAs(api, a.agentId),\n option_id: a.optionId,\n text: a.text,\n comment: a.comment,\n },\n }\n );\n return { question: r.question as never };\n },\n }),\n\n defineTool({\n name: 'get_org_chart',\n title: 'Get org chart',\n description:\n \"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.\",\n scope: 'agents:read',\n endpoint: 'GET /v1/agents/org-chart',\n inputSchema: z.object({\n teamId: uuid('Only this team').optional(),\n channelId: uuid('Only the agents of this channel').optional(),\n includeRetired: z\n .boolean()\n .optional()\n .describe('Include retired agents (default false)'),\n }),\n outputSchema: z.object({\n agents: z.array(z.looseObject({ id: z.string() })),\n users: z.array(z.looseObject({ id: z.string() })),\n teams: z.array(z.looseObject({ id: z.string() })),\n tree: z.array(z.looseObject({})),\n }),\n annotations: READ,\n handler: async (api, a) =>\n (await api.request<Json>('GET', '/v1/agents/org-chart', {\n query: {\n team_id: a.teamId,\n channel_id: a.channelId,\n include_retired: a.includeRetired ? 'true' : undefined,\n },\n })) as never,\n }),\n\n defineTool({\n name: 'get_effective_policy',\n title: 'Get effective policy',\n description:\n '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.',\n scope: 'agents:admin',\n endpoint: 'GET /v1/agents/policies/preview',\n inputSchema: z.object({\n agentId: uuid(\n 'The agent (from list_agents). Default: the server agent (CHANNLIZE_AGENT_ID)'\n ).optional(),\n channelId: channelId.optional(),\n }),\n outputSchema: z.looseObject({\n agent_id: z.string(),\n channel_id: z.string().nullable(),\n rules: z.looseObject({}),\n working_hours: z.looseObject({}),\n usage: z.looseObject({}),\n checks: z.looseObject({}).nullable(),\n }),\n annotations: READ,\n handler: async (api, a) =>\n (await api.request<Json>('GET', '/v1/agents/policies/preview', {\n query: {\n agent_id: requireAgent(api, a.agentId),\n channel_id: a.channelId,\n },\n })) as never,\n }),\n\n defineTool({\n name: 'read_agent_inbox',\n title: 'Read agent inbox',\n description:\n \"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.\",\n scope: 'agents:read',\n endpoint: 'GET /v1/agents/:id/inbox',\n inputSchema: z.object({\n agentId,\n cursor: z\n .string()\n .max(200)\n .optional()\n .describe('Read after this cursor (nextCursor of the previous call)'),\n limit: z\n .number()\n .int()\n .min(1)\n .max(200)\n .default(20)\n .describe('How many to return (1-200, default 20)'),\n }),\n outputSchema: z.object({\n agentId: z.string(),\n messages: z.array(\n z.looseObject({\n delivery_id: z.string(),\n cursor: z.string(),\n message,\n })\n ),\n nextCursor: z.string().nullable(),\n hasMore: z.boolean(),\n }),\n annotations: READ,\n handler: async (api, a) => {\n const id = requireAgent(api, a.agentId);\n const r = await api.request<Json>('GET', `/v1/agents/${enc(id)}/inbox`, {\n query: { cursor: a.cursor, limit: a.limit },\n });\n return {\n agentId: id,\n messages: (r.messages ?? []) as never,\n nextCursor: (r.next_cursor as string | null | undefined) ?? null,\n hasMore: Boolean(r.has_more),\n };\n },\n }),\n\n defineTool({\n name: 'ack_agent_messages',\n title: 'Acknowledge agent messages',\n description:\n '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.',\n scope: 'agents:read',\n endpoint: 'POST /v1/agents/:id/inbox/ack',\n inputSchema: z.object({\n agentId,\n upTo: z\n .string()\n .uuid()\n .optional()\n .describe('Ack everything up to and including this delivery_id'),\n ids: z\n .array(z.string().uuid())\n .min(1)\n .max(500)\n .optional()\n .describe('Ack these delivery (or message) IDs'),\n }),\n outputSchema: z.object({ acked: z.number() }),\n annotations: {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n handler: async (api, a) => {\n if (!a.upTo === !a.ids) {\n throw new ToolError('Pass either upTo or ids.');\n }\n const id = requireAgent(api, a.agentId);\n const r = await api.request<{ acked?: number }>(\n 'POST',\n `/v1/agents/${enc(id)}/inbox/ack`,\n { body: a.upTo ? { up_to: a.upTo } : { ids: a.ids } }\n );\n return { acked: Number(r.acked ?? 0) };\n },\n }),\n\n defineTool({\n name: 'list_agents',\n title: 'List agents',\n description:\n \"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.\",\n scope: 'agents:read',\n endpoint: 'GET /v1/agents',\n inputSchema: z.object({\n includeRetired: z\n .boolean()\n .optional()\n .describe('Include retired agents (default false)'),\n }),\n outputSchema: z.object({\n agents: z.array(\n z.looseObject({\n id: z.string(),\n slug: z.string(),\n name: z.string(),\n status: z.string(),\n })\n ),\n }),\n annotations: READ,\n handler: async (api, a) => {\n const r = await api.request<{ agents?: Json[] }>('GET', '/v1/agents', {\n query: { include_retired: a.includeRetired || undefined },\n });\n return { agents: (r.agents ?? []) as never };\n },\n }),\n\n defineTool({\n name: 'list_agent_channels',\n title: 'List agent channels',\n description:\n \"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.\",\n scope: 'agents:read',\n endpoint: 'GET /v1/agents/channels',\n inputSchema: z.object({\n includeArchived: z\n .boolean()\n .optional()\n .describe('Include archived channels (default false)'),\n }),\n outputSchema: z.object({\n channels: z.array(\n z.looseObject({\n id: z.string(),\n slug: z.string(),\n name: z.string(),\n archived: z.boolean(),\n })\n ),\n }),\n annotations: READ,\n handler: async (api, a) => {\n const r = await api.request<{ channels?: Json[] }>(\n 'GET',\n '/v1/agents/channels',\n { query: { include_archived: a.includeArchived || undefined } }\n );\n return { channels: (r.channels ?? []) as never };\n },\n }),\n];\n\nexport const AGENT_TOOL_NAMES = AGENT_TOOLS.map(t => t.name);\n\nexport function getAgentTool(name: string): AgentTool | undefined {\n return AGENT_TOOLS.find(t => t.name === name);\n}\n\n/**\n * Validate `args` against the tool's input schema and run it. Throws\n * `ToolError` for an unknown tool or invalid arguments, and for API\n * failures (`toToolError` in `api.ts` words them for the model).\n */\nexport async function runAgentTool(\n api: AgentsRequester,\n name: string,\n args: unknown\n): Promise<Json> {\n const tool = getAgentTool(name);\n if (!tool) throw new ToolError(`Unknown agent tool \"${name}\"`);\n const parsed = tool.inputSchema.safeParse(args ?? {});\n if (!parsed.success) {\n throw new ToolError(\n `Invalid arguments for ${name}: ${parsed.error.issues\n .map(i => `${i.path.join('.') || 'input'}: ${i.message}`)\n .join('; ')}`\n );\n }\n return (await tool.handler(api, parsed.data)) as Json;\n}\n\n/**\n * The tools as JSON Schema function definitions, for LLM APIs that take\n * `{ name, description, parameters }` (OpenAI / OpenRouter style).\n */\nexport function agentToolsAsJsonSchema(\n filter: (tool: AgentTool) => boolean = () => true\n): Array<{ name: string; description: string; parameters: Json }> {\n return AGENT_TOOLS.filter(filter).map(t => ({\n name: t.name,\n description: t.description,\n parameters: z.toJSONSchema(t.inputSchema, { io: 'input' }) as Json,\n }));\n}\n","/**\n * The Channlize inbox toolset: names, zod input/output schemas and handlers\n * for working the inbox through the API-key endpoints under `/v1`.\n *\n * This module has no dependency on the MCP server or its transports, so any\n * agent can import it (`@channlize/mcp/inbox`): the stdio/HTTP server\n * registers these tools (`registerInboxTools` in `tools.ts`), and the\n * dashboard copilot or an internal bot can run the same handlers with its own\n * client (anything with a `request(method, path, { query, body })`).\n *\n * Writes act as a named agent: the API key's name. Replies show in Slack as\n * \"Replied by <key name> (agent)\", and changes as \"… by <key name> (agent)\".\n *\n * Scopes (pick them when creating the key): `inbox:read`, `inbox:write`,\n * `routing:write`, `analytics:read`. A `read` key can use the read tools.\n */\nimport * as z from 'zod/v4';\nimport { ToolError, type HttpMethod } from './api';\n\nexport type { HttpMethod };\n\ntype Json = Record<string, unknown>;\ntype Query = Record<string, string | number | boolean | undefined>;\n\n/** What a handler needs: `ChannlizeApi` from this package, or your own. */\nexport interface InboxRequester {\n request<T>(\n method: HttpMethod,\n path: string,\n options?: { query?: Query; body?: unknown }\n ): Promise<T>;\n}\n\n/** The API key scope a tool needs. `routing:read` is granted by `routing:write`, `inbox:read` or `read`. */\nexport type InboxScope =\n | 'inbox:read'\n | 'inbox:write'\n | 'routing:read'\n | 'routing:write'\n | 'analytics:read';\n\nexport interface ToolAnnotations {\n readOnlyHint: boolean;\n destructiveHint: boolean;\n idempotentHint: boolean;\n openWorldHint: boolean;\n}\n\nexport interface InboxTool<\n I extends z.ZodObject = z.ZodObject,\n O extends z.ZodObject = z.ZodObject,\n> {\n name: string;\n title: string;\n description: string;\n scope: InboxScope;\n /** The HTTP endpoint it calls, for docs and logs. */\n endpoint: string;\n inputSchema: I;\n outputSchema: O;\n annotations: ToolAnnotations;\n handler: (api: InboxRequester, args: z.output<I>) => Promise<z.output<O>>;\n}\n\nfunction defineTool<I extends z.ZodObject, O extends z.ZodObject>(\n tool: InboxTool<I, O>\n): InboxTool {\n return tool as unknown as InboxTool;\n}\n\n// ----- shared schemas -----\n\nexport const CONVERSATION_STATUSES = [\n 'open',\n 'pending',\n 'resolved',\n 'closed',\n] as const;\nexport const CONVERSATION_PRIORITIES = [\n 'low',\n 'normal',\n 'high',\n 'urgent',\n] as const;\nexport const CONVERSATION_SORTS = [\n 'recent',\n 'oldest',\n 'newest',\n 'priority',\n] as const;\n\nconst loose = z.looseObject({});\nconst id = (what: string) => z.string().uuid().describe(`${what} ID`);\nconst conversationId = id(\n 'Conversation (from list_conversations or search_conversations)'\n);\n\nconst person = z\n .looseObject({\n id: z.string(),\n name: z.string().nullable().optional(),\n email: z.string().nullable().optional(),\n })\n .nullable();\n\nconst conversationSummary = z.looseObject({\n id: z.string(),\n subject: z.string().nullable().optional(),\n status: z.string(),\n priority: z.string().optional(),\n source: z.string().nullable().optional(),\n tags: z.array(z.string()).optional(),\n customer: person.optional(),\n assignee: person.optional(),\n triage: z.record(z.string(), z.unknown()).nullable().optional(),\n needsReply: z.boolean().optional(),\n lastActivityAt: z.string().nullable().optional(),\n});\n\nconst page = {\n total: z.number(),\n limit: z.number(),\n offset: z.number(),\n hasMore: z.boolean(),\n};\n\nconst listOutput = z.object({\n conversations: z.array(conversationSummary),\n ...page,\n});\n\nconst changeOutput = z.object({\n conversation: z.looseObject({ id: z.string(), status: z.string() }),\n changes: z.array(z.string()),\n});\n\nconst slackOutcome = z\n .string()\n .describe(\n 'Slack mirror: queued, posted, no_thread (not in Slack), not_connected or failed'\n );\n\nconst tags = z.array(z.string().trim().min(1).max(50)).max(20);\n\nconst paging = {\n limit: z\n .number()\n .int()\n .min(1)\n .max(100)\n .default(20)\n .describe('How many to return (1-100, default 20)'),\n offset: z.number().int().min(0).default(0).describe('Skip this many'),\n};\n\n/** One value or a list of them (sent as a comma list). */\nfunction oneOrMany<T extends readonly [string, ...string[]]>(values: T) {\n return z.union([z.enum(values), z.array(z.enum(values)).max(10)]).optional();\n}\n\nconst asList = (v: string | string[] | undefined) =>\n v === undefined ? undefined : Array.isArray(v) ? v.join(',') : v;\n\nconst listFilters = {\n status: oneOrMany(CONVERSATION_STATUSES).describe(\n 'Only these statuses: \"open\" or a list like [\"open\", \"pending\"]'\n ),\n priority: oneOrMany(CONVERSATION_PRIORITIES).describe(\n 'Only these priorities: \"urgent\" or a list'\n ),\n assignee: z\n .string()\n .max(255)\n .optional()\n .describe('A teammate (user ID or email), \"unassigned\" or \"assigned\"'),\n projectId: id('Project').optional(),\n updatedSince: z.iso\n .datetime({ offset: true })\n .optional()\n .describe('Updated or with a new message since (ISO 8601)'),\n tag: z.string().max(50).optional().describe('Carrying this tag'),\n source: z\n .string()\n .max(32)\n .optional()\n .describe('Entry point, e.g. live_chat, contact_form, api, email'),\n intent: z\n .string()\n .max(64)\n .optional()\n .describe('AI triage intent (triaged conversations only)'),\n urgency: z\n .string()\n .max(64)\n .optional()\n .describe('AI triage urgency (triaged conversations only)'),\n sort: z\n .enum(CONVERSATION_SORTS)\n .optional()\n .describe(\n 'recent (last activity, default), oldest, newest (created) or priority'\n ),\n};\n\ntype ListArgs = {\n status?: string | string[];\n priority?: string | string[];\n assignee?: string;\n projectId?: string;\n updatedSince?: string;\n tag?: string;\n source?: string;\n intent?: string;\n urgency?: string;\n sort?: string;\n limit: number;\n offset: number;\n q?: string;\n};\n\nasync function list(api: InboxRequester, a: ListArgs) {\n const r = await api.request<Json>('GET', '/v1/conversations', {\n query: {\n status: asList(a.status),\n priority: asList(a.priority),\n assignee: a.assignee,\n projectId: a.projectId,\n updatedSince: a.updatedSince,\n tag: a.tag,\n source: a.source,\n intent: a.intent,\n urgency: a.urgency,\n sort: a.sort,\n q: a.q,\n limit: a.limit,\n offset: a.offset,\n },\n });\n return {\n conversations:\n (r.conversations as z.output<typeof conversationSummary>[]) ?? [],\n total: Number(r.total ?? 0),\n limit: Number(r.limit ?? a.limit),\n offset: Number(r.offset ?? a.offset),\n hasMore: Boolean(r.hasMore),\n };\n}\n\nconst path = (cid: string, rest = '') =>\n `/v1/conversations/${encodeURIComponent(cid)}${rest}`;\n\nasync function patch(api: InboxRequester, cid: string, body: Json) {\n const r = await api.request<{ conversation: Json; changes?: string[] }>(\n 'PATCH',\n path(cid),\n { body }\n );\n return {\n conversation: r.conversation as { id: string; status: string },\n changes: r.changes ?? [],\n };\n}\n\nconst READ: ToolAnnotations = {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n};\nconst CHANGE: ToolAnnotations = {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: true,\n};\n\n// ----- routing rules -----\n\nexport const ROUTING_FIELDS = [\n 'source',\n 'project',\n 'widget',\n 'connection',\n 'page_url',\n 'page_domain',\n 'customer_email',\n 'customer_email_domain',\n 'message',\n 'subject',\n 'tags',\n 'priority',\n 'language',\n] as const;\nexport const ROUTING_OPERATORS = [\n 'equals',\n 'not_equals',\n 'contains',\n 'not_contains',\n 'starts_with',\n 'ends_with',\n 'matches',\n] as const;\n\nconst routingConditions = z\n .object({\n match: z\n .enum(['all', 'any'])\n .describe('all = every condition holds, any = one is enough'),\n conditions: z\n .array(\n z.object({\n field: z.enum(ROUTING_FIELDS),\n operator: z.enum(ROUTING_OPERATORS),\n value: z\n .union([z.string(), z.array(z.string())])\n .describe(\n 'A value, or a list (positive operators: any matches; negative: none does). Case-insensitive; matches uses * and ? wildcards.'\n ),\n })\n )\n .max(50)\n .describe('Empty = matches every new conversation (catch-all)'),\n })\n .describe(\n 'Which new conversations the rule catches, tested on the first message, e.g. { \"match\": \"any\", \"conditions\": [{ \"field\": \"message\", \"operator\": \"contains\", \"value\": [\"refund\", \"invoice\"] }] }'\n );\n\nconst ruleFields = {\n name: z.string().trim().min(1).max(255).describe('Rule name'),\n targetChannelId: z\n .string()\n .regex(/^[A-Z0-9]{2,30}$/, 'a Slack channel ID like C0123ABCD')\n .describe('Slack channel ID to post matching conversations to'),\n conditions: routingConditions,\n projectId: id('Project (default: the oldest project)').optional(),\n widgetId: id('Widget').nullable().optional(),\n integrationId: id('Integration (default: the Slack workspace)').optional(),\n assignToUserId: id('Teammate to assign matching conversations to')\n .nullable()\n .optional(),\n isActive: z.boolean().optional().describe('Default true'),\n priority: z\n .number()\n .int()\n .min(-1_000_000)\n .max(1_000_000)\n .optional()\n .describe('Higher runs first (default: after every rule)'),\n};\n\nconst rule = z.looseObject({\n id: z.string(),\n name: z.string(),\n priority: z.number(),\n is_active: z.boolean(),\n target_channel_id: z.string(),\n});\n\n// ----- the tools -----\n\nexport const INBOX_TOOLS: readonly InboxTool[] = [\n defineTool({\n name: 'list_conversations',\n title: 'List conversations',\n description:\n '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.',\n scope: 'inbox:read',\n endpoint: 'GET /v1/conversations',\n inputSchema: z.object({ ...listFilters, ...paging }),\n outputSchema: listOutput,\n annotations: READ,\n handler: (api, a) => list(api, a),\n }),\n\n defineTool({\n name: 'search_conversations',\n title: 'Search conversations',\n description:\n '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.',\n scope: 'inbox:read',\n endpoint: 'GET /v1/conversations?q=',\n inputSchema: z.object({\n query: z.string().trim().min(1).max(200).describe('Text to look for'),\n ...listFilters,\n ...paging,\n }),\n outputSchema: listOutput,\n annotations: READ,\n handler: (api, { query, ...a }) => list(api, { ...a, q: query }),\n }),\n\n defineTool({\n name: 'get_conversation',\n title: 'Get conversation',\n description:\n '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.',\n scope: 'inbox:read',\n endpoint: 'GET /v1/conversations/:id',\n inputSchema: z.object({ conversationId }),\n outputSchema: z.object({\n conversation: z.looseObject({\n id: z.string(),\n status: z.string(),\n messages: z.array(loose),\n }),\n }),\n annotations: READ,\n handler: async (api, { conversationId: cid }) => {\n const r = await api.request<{ conversation: Json }>('GET', path(cid));\n return { conversation: r.conversation as never };\n },\n }),\n\n defineTool({\n name: 'reply_to_conversation',\n title: 'Reply to conversation',\n description:\n '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.',\n scope: 'inbox:write',\n endpoint: 'POST /v1/conversations/:id/reply',\n inputSchema: z.object({\n conversationId,\n content: z\n .string()\n .trim()\n .min(1)\n .max(10_000)\n .describe('Reply text, as the customer will read it'),\n }),\n outputSchema: z.object({\n message: z.looseObject({ id: z.string() }),\n conversationStatus: z.string(),\n slack: slackOutcome,\n }),\n annotations: {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: true,\n },\n handler: async (api, { conversationId: cid, content }) => {\n const r = await api.request<Json>('POST', path(cid, '/reply'), {\n body: { content },\n });\n return {\n message: r.message as { id: string },\n conversationStatus: String(r.conversationStatus ?? ''),\n slack: String(r.slack ?? ''),\n };\n },\n }),\n\n defineTool({\n name: 'add_internal_note',\n title: 'Add internal note',\n description:\n '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.',\n scope: 'inbox:write',\n endpoint: 'POST /v1/conversations/:id/notes',\n inputSchema: z.object({\n conversationId,\n content: z.string().trim().min(1).max(10_000).describe('Note text'),\n }),\n outputSchema: z.object({\n note: z.looseObject({ id: z.string() }),\n slack: slackOutcome,\n }),\n annotations: {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: true,\n },\n handler: async (api, { conversationId: cid, content }) => {\n const r = await api.request<Json>('POST', path(cid, '/notes'), {\n body: { content },\n });\n return { note: r.note as { id: string }, slack: String(r.slack ?? '') };\n },\n }),\n\n defineTool({\n name: 'assign_conversation',\n title: 'Assign conversation',\n description:\n '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.',\n scope: 'inbox:write',\n endpoint: 'PATCH /v1/conversations/:id',\n inputSchema: z.object({\n conversationId,\n assignee: z\n .string()\n .min(1)\n .max(255)\n .nullable()\n .describe('User ID or email of the teammate, or null to unassign'),\n }),\n outputSchema: changeOutput,\n annotations: CHANGE,\n handler: (api, { conversationId: cid, assignee }) =>\n patch(\n api,\n cid,\n assignee === null\n ? { assigneeId: null }\n : assignee.includes('@')\n ? { assigneeEmail: assignee }\n : { assigneeId: assignee }\n ),\n }),\n\n defineTool({\n name: 'tag_conversation',\n title: 'Tag conversation',\n description:\n 'Add or remove tags on a conversation, or replace them all with `set`. Tags are lowercased; at most 20. Needs the inbox:write scope.',\n scope: 'inbox:write',\n endpoint: 'PATCH /v1/conversations/:id',\n inputSchema: z.object({\n conversationId,\n add: tags.optional().describe('Tags to add'),\n remove: tags.optional().describe('Tags to remove'),\n set: tags\n .optional()\n .describe('Replace every tag with these ([] clears them)'),\n }),\n outputSchema: changeOutput,\n annotations: CHANGE,\n handler: (api, { conversationId: cid, add, remove, set }) => {\n if (!add?.length && !remove?.length && !set) {\n throw new ToolError('Pass tags to add, remove, or set.');\n }\n return patch(api, cid, {\n ...(set ? { tags: set } : {}),\n ...(add?.length ? { addTags: add } : {}),\n ...(remove?.length ? { removeTags: remove } : {}),\n });\n },\n }),\n\n defineTool({\n name: 'close_conversation',\n title: 'Close conversation',\n description:\n '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.',\n scope: 'inbox:write',\n endpoint: 'PATCH /v1/conversations/:id',\n inputSchema: z.object({\n conversationId,\n status: z\n .enum(['closed', 'resolved'])\n .default('closed')\n .describe('closed (default) or resolved'),\n }),\n outputSchema: changeOutput,\n annotations: CHANGE,\n handler: (api, { conversationId: cid, status }) =>\n patch(api, cid, { status }),\n }),\n\n defineTool({\n name: 'reopen_conversation',\n title: 'Reopen conversation',\n description:\n 'Reopen a closed or resolved conversation (status open). Needs the inbox:write scope.',\n scope: 'inbox:write',\n endpoint: 'PATCH /v1/conversations/:id',\n inputSchema: z.object({ conversationId }),\n outputSchema: changeOutput,\n annotations: CHANGE,\n handler: (api, { conversationId: cid }) =>\n patch(api, cid, { status: 'open' }),\n }),\n\n defineTool({\n name: 'get_analytics_summary',\n title: 'Get analytics summary',\n description:\n '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.',\n scope: 'analytics:read',\n endpoint: 'GET /v1/analytics/summary',\n inputSchema: z.object({\n days: z\n .number()\n .int()\n .min(1)\n .max(366)\n .optional()\n .describe('Period length in days, ending today (default 30)'),\n from: z.iso.date().optional().describe('First day, YYYY-MM-DD'),\n to: z.iso.date().optional().describe('Last day, YYYY-MM-DD'),\n tz: z\n .string()\n .max(64)\n .optional()\n .describe('IANA time zone for day boundaries (default UTC)'),\n projectId: id('Project').optional(),\n }),\n outputSchema: z.looseObject({ range: loose, kpis: loose, inbox: loose }),\n annotations: READ,\n handler: async (api, args) =>\n api.request<{ range: Json; kpis: Json; inbox: Json }>(\n 'GET',\n '/v1/analytics/summary',\n { query: args }\n ),\n }),\n\n defineTool({\n name: 'list_routing_rules',\n title: 'List routing rules',\n description:\n '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.',\n scope: 'routing:read',\n endpoint: 'GET /v1/routing-rules',\n inputSchema: z.object({}),\n outputSchema: z.object({ rules: z.array(rule) }),\n annotations: READ,\n handler: async api => {\n const r = await api.request<{ routing_rules: Json[] }>(\n 'GET',\n '/v1/routing-rules'\n );\n return { rules: (r.routing_rules ?? []) as never };\n },\n }),\n\n defineTool({\n name: 'create_routing_rule',\n title: 'Create routing rule',\n description:\n '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.',\n scope: 'routing:write',\n endpoint: 'POST /v1/routing-rules',\n inputSchema: z.object(ruleFields),\n outputSchema: z.object({ rule }),\n annotations: {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: false,\n },\n handler: async (api, body) => {\n const r = await api.request<{ routing_rule: Json }>(\n 'POST',\n '/v1/routing-rules',\n { body }\n );\n return { rule: r.routing_rule as never };\n },\n }),\n\n defineTool({\n name: 'update_routing_rule',\n title: 'Update routing rule',\n description:\n '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.',\n scope: 'routing:write',\n endpoint: 'PATCH /v1/routing-rules/:id',\n inputSchema: z.object({\n ruleId: id('Routing rule'),\n name: ruleFields.name.optional(),\n targetChannelId: ruleFields.targetChannelId.optional(),\n conditions: routingConditions.optional(),\n projectId: ruleFields.projectId,\n widgetId: ruleFields.widgetId,\n integrationId: ruleFields.integrationId,\n assignToUserId: ruleFields.assignToUserId,\n isActive: ruleFields.isActive,\n priority: ruleFields.priority,\n }),\n outputSchema: z.object({ rule }),\n annotations: {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n handler: async (api, { ruleId, ...body }) => {\n if (Object.values(body).every(v => v === undefined)) {\n throw new ToolError('Pass at least one field to change.');\n }\n const r = await api.request<{ routing_rule: Json }>(\n 'PATCH',\n `/v1/routing-rules/${encodeURIComponent(ruleId)}`,\n { body }\n );\n return { rule: r.routing_rule as never };\n },\n }),\n\n defineTool({\n name: 'delete_routing_rule',\n title: 'Delete routing rule',\n description:\n '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.',\n scope: 'routing:write',\n endpoint: 'DELETE /v1/routing-rules/:id',\n inputSchema: z.object({ ruleId: id('Routing rule') }),\n outputSchema: z.object({ deleted: z.boolean(), ruleId: z.string() }),\n annotations: {\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: true,\n openWorldHint: false,\n },\n handler: async (api, { ruleId }) => {\n await api.request(\n 'DELETE',\n `/v1/routing-rules/${encodeURIComponent(ruleId)}`\n );\n return { deleted: true, ruleId };\n },\n }),\n];\n\nexport const INBOX_TOOL_NAMES = INBOX_TOOLS.map(t => t.name);\n\nexport function getInboxTool(name: string): InboxTool | undefined {\n return INBOX_TOOLS.find(t => t.name === name);\n}\n\n/**\n * Validate `args` against the tool's input schema and run it. Throws\n * `ToolError` for an unknown tool or invalid arguments, and for API\n * failures (`toToolError` in `api.ts` words them for the model).\n */\nexport async function runInboxTool(\n api: InboxRequester,\n name: string,\n args: unknown\n): Promise<Json> {\n const tool = getInboxTool(name);\n if (!tool) throw new ToolError(`Unknown inbox tool \"${name}\"`);\n const parsed = tool.inputSchema.safeParse(args ?? {});\n if (!parsed.success) {\n throw new ToolError(\n `Invalid arguments for ${name}: ${parsed.error.issues\n .map(i => `${i.path.join('.') || 'input'}: ${i.message}`)\n .join('; ')}`\n );\n }\n return (await tool.handler(api, parsed.data)) as Json;\n}\n\n/**\n * The tools as JSON Schema function definitions, for LLM APIs that take\n * `{ name, description, parameters }` (OpenAI / OpenRouter style).\n */\nexport function inboxToolsAsJsonSchema(\n filter: (tool: InboxTool) => boolean = () => true\n): Array<{ name: string; description: string; parameters: Json }> {\n return INBOX_TOOLS.filter(filter).map(t => ({\n name: t.name,\n description: t.description,\n parameters: z.toJSONSchema(t.inputSchema, { io: 'input' }) as Json,\n }));\n}\n","import { createServer, type IncomingMessage, type Server } from 'node:http';\nimport {\n createMcpHandler,\n hostHeaderValidationResponse,\n localhostAllowedHostnames,\n localhostAllowedOrigins,\n originValidationResponse,\n type McpServer,\n} from '@modelcontextprotocol/server';\n\nexport interface HttpServerOptions {\n /** Interface to bind (default 127.0.0.1). */\n host?: string;\n /** Port (default 3333). */\n port?: number;\n /** Endpoint path (default /mcp). */\n path?: string;\n}\n\nconst LOCAL_HOSTS = new Set(['127.0.0.1', 'localhost', '::1']);\n\nasync function toRequest(\n req: IncomingMessage,\n origin: string\n): Promise<Request> {\n const headers = new Headers();\n for (const [k, v] of Object.entries(req.headers)) {\n if (Array.isArray(v)) v.forEach(x => headers.append(k, x));\n else if (v !== undefined) headers.set(k, v);\n }\n let body: Uint8Array<ArrayBuffer> | undefined;\n if (req.method !== 'GET' && req.method !== 'HEAD') {\n const chunks: Buffer[] = [];\n for await (const chunk of req) chunks.push(chunk as Buffer);\n body = new Uint8Array(Buffer.concat(chunks));\n }\n const controller = new AbortController();\n req.on('close', () => {\n if (!req.complete) controller.abort();\n });\n return new Request(new URL(req.url ?? '/', origin), {\n method: req.method,\n headers,\n body,\n signal: controller.signal,\n });\n}\n\n/**\n * Streamable HTTP transport on `node:http`. Stateless: every request is\n * served by a fresh server from `factory`. Bound to localhost by default,\n * with Host and Origin checks against DNS rebinding.\n */\nexport async function startHttpServer(\n factory: () => McpServer,\n options: HttpServerOptions = {}\n): Promise<{ url: string; server: Server; close: () => Promise<void> }> {\n const host = options.host ?? '127.0.0.1';\n const port = options.port ?? 3333;\n const path = options.path ?? '/mcp';\n const local = LOCAL_HOSTS.has(host);\n const handler = createMcpHandler(() => factory(), {\n onerror: err => console.error('[channlize-mcp]', err.message),\n });\n\n const server = createServer(async (req, res) => {\n try {\n const request = await toRequest(\n req,\n `http://${req.headers.host ?? `${host}:${port}`}`\n );\n const url = new URL(request.url);\n if (url.pathname !== path) {\n res\n .writeHead(404, { 'Content-Type': 'text/plain' })\n .end(`Not found: use ${path}`);\n return;\n }\n const rejected = local\n ? (hostHeaderValidationResponse(request, localhostAllowedHostnames()) ??\n originValidationResponse(request, localhostAllowedOrigins()))\n : undefined;\n const response = rejected ?? (await handler.fetch(request));\n res.writeHead(response.status, Object.fromEntries(response.headers));\n if (response.body) {\n for await (const chunk of response.body as unknown as AsyncIterable<Uint8Array>) {\n res.write(chunk);\n }\n }\n res.end();\n } catch (err) {\n console.error('[channlize-mcp]', (err as Error).message);\n if (!res.headersSent)\n res.writeHead(500, { 'Content-Type': 'text/plain' });\n res.end('Internal server error');\n }\n });\n\n await new Promise<void>((resolve, reject) => {\n server.once('error', reject);\n server.listen(port, host, () => resolve());\n });\n const address = server.address();\n const actualPort =\n typeof address === 'object' && address ? address.port : port;\n const shownHost = host.includes(':') ? `[${host}]` : host;\n return {\n url: `http://${shownHost}:${actualPort}${path}`,\n server,\n close: () => new Promise<void>(r => server.close(() => r())),\n };\n}\n"],"mappings":";AAQA,SAAS,iBAAiB;AAC1B,SAAS,4BAA4B;;;ACTrC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAUA,IAAM,YAAN,cAAwB,MAAM;AAAA,EACnC,YACEA,UACO,YACA,MAEA,SACP;AACA,UAAMA,QAAO;AALN;AACA;AAEA;AAGP,SAAK,OAAO;AAAA,EACd;AAAA,EAPS;AAAA,EACA;AAAA,EAEA;AAKX;AAKA,SAAS,SAAS,YAA4B;AAC5C,QAAM,OAAO,4BAA4B,KAAK,UAAU,IAAI,CAAC,KAAK;AAClE,UAAQ,MAAM;AAAA,IACZ,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT;AACE,aAAO,eAAe,KAAK,UAAU,IAAI,UAAU;AAAA,EACvD;AACF;AAGA,SAAS,UAAU,SAAqC;AACtD,SAAO,UAAU,gBAAgB,OAAO,kBAAkB;AAC5D;AAGA,SAAS,UACP,MACA,OAAgC,CAAC,GACb;AACpB,QAAM,UAAU,OAAO,KAAK,YAAY,WAAW,KAAK,UAAU;AAClE,UAAQ,MAAM;AAAA,IACZ,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT,K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,SAAO,IAAI,mBAAmB,OAAO;AACvC;AAEA,IAAO,gBAAQ;","names":["message","path","url","data","message","agentId","conversationId","z","z","id","z","defineTool","READ","data","record","loose","page","READ","path","url","ChannlizeError"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/api.ts","../src/config.ts","../src/prompts.ts","../src/docs.ts","../src/resources.ts","../src/tools.ts","../src/agents.ts","../src/agents-summary.ts","../src/inbox.ts","../src/http.ts"],"sourcesContent":["/**\n * @channlize/mcp\n * Model Context Protocol (MCP) server for Channlize: lets AI assistants\n * work the support inbox (list, search, reply, assign, tag, close, notes),\n * manage routing rules, read analytics, contacts, logs and Events, send\n * Events to Slack, and talk to other agents (Channlize for Agents).\n */\n\nimport { McpServer } from '@modelcontextprotocol/server';\nimport { StdioServerTransport } from '@modelcontextprotocol/server/stdio';\nimport { ChannlizeApi } from './api';\nimport { resolveConfig, type ResolvedConfig } from './config';\nimport { registerGuidePrompts, registerServerPrompts } from './prompts';\nimport { registerResources } from './resources';\nimport {\n registerAgentTools,\n registerInboxTools,\n registerServerTools,\n registerWidgetTools,\n} from './tools';\nimport type { ChannlizeMCPConfig, MCPServerOptions } from './types';\nimport { startHttpServer, type HttpServerOptions } from './http';\n\ndeclare const __PACKAGE_VERSION__: string;\nexport const VERSION: string =\n typeof __PACKAGE_VERSION__ !== 'undefined' ? __PACKAGE_VERSION__ : '0.0.0';\n\nexport * from './types';\nexport { ConfigError, configFromEnv, resolveConfig, keyKind } from './config';\nexport type { ResolvedConfig, KeyKind } from './config';\nexport { ChannlizeApi, ToolError, toToolError } from './api';\nexport type { HttpMethod } from './api';\nexport * from './inbox';\nexport * from './agents';\nexport { registerAgentTools, registerInboxTools } from './tools';\nexport type { HttpServerOptions } from './http';\n\n// Re-export core types for convenience\nexport type {\n ChannlizeConfig,\n ContactFormData,\n ChatMessage,\n ChatSession,\n FileAttachment,\n CreateContactResponse,\n CreateChatSessionResponse,\n SendMessageResponse,\n NotifyResponse,\n} from '@channlize/core';\n\nconst INSTRUCTIONS = `Channlize routes website conversations and app events to the team's Slack.\n- 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.\n- get_analytics_summary gives KPIs and the inbox right now; list/create/update/delete_routing_rule manage which Slack channel new conversations go to.\n- Events (notify_event) post a Slack message per event key; list_event_definitions and list_event_deliveries explain what was sent or skipped.\n- Logs: query_logs searches log tracking; track_log records one.\n- 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).\n- 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.\n- 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).\n- History and numbers: search_agent_messages finds past messages, tasks and answered questions (search before asking a person again). get_agent_cost, get_agent_metrics and get_agent_graph report spend, reply latency, backlog and who talks to whom over a range of UTC days; pass mine: true for your own agent. They return the top rows plus totals and a summary line.\n- 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.\n- 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.`;\n\n/**\n * Builds a configured `McpServer` (tools, resources and prompts) without\n * connecting it. Tools are registered for the keys you pass: server-key\n * tools for `serverApiKey`, visitor tools for `widgetKey`.\n */\nexport function buildServer(\n config: ChannlizeMCPConfig,\n info: { name?: string; version?: string } = {}\n): McpServer {\n const api = new ChannlizeApi(resolveConfig(config));\n const server = new McpServer(\n { name: info.name ?? 'channlize', version: info.version ?? VERSION },\n { instructions: INSTRUCTIONS }\n );\n if (api.hasServerKey) {\n registerInboxTools(server, api);\n registerAgentTools(server, api);\n registerServerTools(server, api);\n registerServerPrompts(server);\n }\n if (api.hasWidgetKey) registerWidgetTools(server, api);\n registerResources(server, api);\n registerGuidePrompts(server);\n return server;\n}\n\n/**\n * Channlize MCP server. Validates the configuration on construction (a\n * missing key or a widget key passed as the server key throws\n * `ConfigError`).\n */\nexport class ChannlizeMCPServer {\n private server: McpServer;\n private readonly config: ResolvedConfig;\n private readonly info: { name?: string; version?: string };\n\n constructor(options: MCPServerOptions = {}) {\n this.config = resolveConfig(options.config ?? {});\n this.info = { name: options.name, version: options.version };\n this.server = buildServer(this.config, this.info);\n }\n\n /** The underlying `McpServer`. */\n getServer(): McpServer {\n return this.server;\n }\n\n /** Serve over stdio (what desktop and IDE clients launch). */\n async runStdio(): Promise<void> {\n await this.server.connect(new StdioServerTransport());\n }\n\n /**\n * Serve Streamable HTTP at `http://<host>:<port>/mcp` (default\n * 127.0.0.1:3333). Each request gets a fresh server; nothing is shared.\n */\n async runHttp(options: HttpServerOptions = {}) {\n return startHttpServer(() => buildServer(this.config, this.info), options);\n }\n\n async close(): Promise<void> {\n await this.server.close();\n }\n}\n\n/** Create a new Channlize MCP server. */\nexport function createMCPServer(\n options?: MCPServerOptions\n): ChannlizeMCPServer {\n return new ChannlizeMCPServer(options);\n}\n\nexport default ChannlizeMCPServer;\n\n// Error classes as values, so `instanceof` works without importing core.\nexport {\n ChannlizeError,\n ValidationError,\n AuthenticationError,\n RateLimitError,\n} from '@channlize/core';\n","import {\n ChannlizeClient,\n ChannlizeError,\n parseApiError,\n} from '@channlize/core';\nimport type { ResolvedConfig } from './config';\n\nexport type HttpMethod = 'GET' | 'POST' | 'PATCH' | 'DELETE';\n\n/**\n * A failed Channlize call, worded for the model: what went wrong and how\n * to fix it (wrong key, missing scope, unknown id). Tool handlers throw it\n * and the MCP server returns it as a tool error (`isError: true`).\n */\nexport class ToolError extends Error {\n constructor(\n message: string,\n public statusCode?: number,\n public code?: string,\n /** ISO time the call may succeed again (agent policies, takeovers). */\n public retryAt?: string\n ) {\n super(message);\n this.name = 'ToolError';\n }\n}\n\ntype Query = Record<string, string | number | boolean | undefined>;\n\n/** The scope to add for an \"API key lacks required permission: <perm>\" 403. */\nfunction scopeFor(apiMessage: string): string {\n const perm = /permission:\\s*([\\w:*-]+)/i.exec(apiMessage)?.[1] ?? '';\n switch (perm) {\n case 'inbox:read':\n return 'inbox:read (or read)';\n case 'inbox:write':\n return 'inbox:write';\n case 'routing:read':\n return 'routing:write, inbox:read (or read)';\n case 'routing:write':\n return 'routing:write';\n case 'analytics:read':\n return 'analytics:read (or read)';\n case 'agents:send':\n return 'agents:send';\n case 'agents:read':\n return 'agents:read';\n case 'agents:ask_human':\n return 'agents:ask_human';\n case 'agents:admin':\n return 'agents:admin (an unbound key)';\n default:\n return /write|notify/.test(apiMessage) ? 'write' : 'read';\n }\n}\n\n/** \" Retry after <time>.\" for a refusal that names one. */\nfunction retryText(retryAt: string | undefined): string {\n return retryAt ? ` Retry after ${retryAt}, not before.` : '';\n}\n\n/** Hints for the Channlize for Agents error codes. */\nfunction agentHint(\n code: string | undefined,\n body: Record<string, unknown> = {}\n): string | undefined {\n const retryAt = typeof body.retryAt === 'string' ? body.retryAt : undefined;\n switch (code) {\n case 'AGENT_KEY_REQUIRED':\n return 'Agent tools need an agent key or a multi-agent key: create one under SDK & Integration → API keys and pick the agents.';\n case 'AGENT_NOT_ALLOWED':\n 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.\";\n case 'NOT_A_CHANNEL_MEMBER':\n return 'Only channel members can post (observers only read): use list_agent_channels, or ask an admin to add the agent to the channel.';\n case 'AGENT_PAUSED':\n case 'AGENT_RETIRED':\n return 'Only active agents can act: ask an admin to reactivate it in the dashboard.';\n case 'AGENT_RATE_LIMITED':\n return 'The agent is sending too fast: wait a minute before sending again.';\n case 'AGENT_THREAD_PAUSED': {\n const why =\n body.reason === 'ping_pong'\n ? ' (two agents were going back and forth)'\n : body.reason === 'duplicate_content'\n ? ' (the same message kept being posted)'\n : '';\n return `The loop guard paused this thread${why}: stop sending in it until a person replies or resumes it. Don't rephrase and retry.`;\n }\n case 'HUMAN_TAKEOVER':\n return `A person took over this thread: don't post in it until the takeover ends or they hand it back.${retryText(retryAt)}`;\n case 'POLICY_RATE_LIMITED':\n case 'POLICY_BUDGET_EXHAUSTED':\n case 'POLICY_OUTSIDE_WORKING_HOURS':\n return `The agent's policy refuses this for now: wait, don't retry in a loop.${retryText(retryAt)}`;\n case 'POLICY_CHANNEL_NOT_ALLOWED':\n case 'POLICY_DM_NOT_ALLOWED':\n case 'POLICY_ASK_HUMAN_NOT_ALLOWED':\n case 'POLICY_URGENCY_NOT_ALLOWED':\n case 'POLICY_MAX_DEPTH':\n 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.\";\n case 'TASK_CLOSED':\n return 'The task is closed (completed, failed, canceled or rejected) and cannot change: create a new task instead.';\n case 'ALREADY_ASSIGNED':\n return 'The task is already assigned to that agent.';\n case 'AGENT_NOT_IN_CHANNEL':\n 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.\";\n case 'NOT_TASK_PARTICIPANT':\n return \"Only the task's assignee or creator can change it or hand it off.\";\n case 'QUESTION_CLOSED':\n return 'The question is already closed (answered, expired or canceled): the first answer wins. Read it with get_answer.';\n case 'APPROVAL_ROLE_REQUIRED':\n return 'This approval needs a person with the required role: an agent cannot answer it.';\n case 'AGENT_ADMIN_KEY_REQUIRED':\n return 'This needs an unbound agents:admin key (not a key bound to agents): create one under SDK & Integration → API keys.';\n case 'CHANNEL_NOT_VISIBLE':\n return \"Your key's agents can't read that channel: leave channelId out, or pick one from list_agent_channels.\";\n case 'INVALID_ANSWER':\n return \"Answer with one of the question's option ids (approve / deny for approvals), or text when free text is allowed.\";\n default:\n return undefined;\n }\n}\n\nfunction hintFor(\n status: number,\n apiMessage: string,\n code?: string,\n body?: Record<string, unknown>\n): string {\n const agent = agentHint(code, body);\n if (agent) return `${apiMessage}. ${agent}`;\n if (status === 400 && /agent_id is required/i.test(apiMessage)) {\n return `${apiMessage}. Pass agentId (from list_agents), or set CHANNLIZE_AGENT_ID / --agent-id on the MCP server.`;\n }\n switch (status) {\n case 401:\n return `${apiMessage}. The server API key is invalid, revoked or expired: create a new one under SDK & Integration → API keys and update CHANNLIZE_SERVER_API_KEY.`;\n case 403:\n return /permission/i.test(apiMessage)\n ? `${apiMessage}. This needs a server API key with the ${scopeFor(\n apiMessage\n )} scope: create one under SDK & Integration → API keys.`\n : apiMessage;\n case 404:\n return `${apiMessage}. Check the ID (and CHANNLIZE_PROJECT_ID): it must belong to the key's organization.`;\n case 429:\n return `${apiMessage}. Rate limited: wait a little before retrying.`;\n default:\n return apiMessage;\n }\n}\n\n/** Maps a `@channlize/core` error to a `ToolError` with the same hints. */\nexport function toToolError(err: unknown): ToolError {\n if (err instanceof ToolError) return err;\n if (err instanceof ChannlizeError) {\n return new ToolError(\n err.statusCode\n ? hintFor(\n err.statusCode,\n err.message.replace(/\\.$/, ''),\n err.code,\n err.details\n )\n : err.message,\n err.statusCode,\n err.code,\n err.retryAt\n );\n }\n return new ToolError(err instanceof Error ? err.message : String(err));\n}\n\n/**\n * Thin client for the API-key endpoints `@channlize/core` doesn't wrap\n * (projects, the inbox, routing rules, contacts, Events and log reads,\n * agents). Widget-key\n * calls and `notify` go through `@channlize/core`.\n */\nexport class ChannlizeApi {\n private projectIdPromise?: Promise<string>;\n private widgetClient?: ChannlizeClient;\n\n constructor(readonly config: ResolvedConfig) {}\n\n get hasServerKey(): boolean {\n return !!this.config.serverApiKey;\n }\n\n get hasWidgetKey(): boolean {\n return !!this.config.widgetKey;\n }\n\n /** The default agent for the agent tools (`CHANNLIZE_AGENT_ID`). */\n get agentId(): string | undefined {\n return this.config.agentId;\n }\n\n private requireServerKey(): string {\n if (!this.config.serverApiKey) {\n throw new ToolError(\n 'This tool needs a server API key (ch_live_…): set CHANNLIZE_SERVER_API_KEY or pass --server-api-key.'\n );\n }\n return this.config.serverApiKey;\n }\n\n async request<T>(\n method: HttpMethod,\n path: string,\n options: {\n query?: Query;\n body?: unknown;\n headers?: Record<string, string>;\n /** Overrides the configured timeout, in ms (long-polls). */\n timeout?: number;\n } = {}\n ): Promise<T> {\n const key = this.requireServerKey();\n const timeout = options.timeout ?? this.config.timeout;\n const url = new URL(`${this.config.baseUrl}${path}`);\n for (const [k, v] of Object.entries(options.query ?? {})) {\n if (v !== undefined && v !== '') url.searchParams.set(k, String(v));\n }\n\n let res: Response;\n try {\n res = await fetch(url, {\n method,\n headers: {\n Authorization: `Bearer ${key}`,\n Accept: 'application/json',\n ...(options.body !== undefined\n ? { 'Content-Type': 'application/json' }\n : {}),\n ...options.headers,\n },\n // oxlint-disable-next-line unicorn/no-invalid-fetch-options -- `method` is dynamic; GET calls never pass a body.\n body:\n options.body !== undefined ? JSON.stringify(options.body) : undefined,\n signal: AbortSignal.timeout(timeout),\n });\n } catch (err) {\n const e = err as Error;\n if (e.name === 'TimeoutError' || e.name === 'AbortError') {\n throw new ToolError(\n `Channlize API timed out after ${timeout} ms (${method} ${url.pathname}). Retry, or raise CHANNLIZE_TIMEOUT.`,\n 408,\n 'TIMEOUT'\n );\n }\n throw new ToolError(\n `Could not reach the Channlize API at ${this.config.baseUrl}: ${e.message}`\n );\n }\n\n const text = await res.text();\n let data: unknown = undefined;\n if (text) {\n try {\n data = JSON.parse(text);\n } catch {\n data = undefined;\n }\n }\n\n if (!res.ok) {\n const { message, code, body } = parseApiError(\n res.status,\n data,\n res.statusText\n );\n const retryAt =\n typeof body.retryAt === 'string' ? body.retryAt : undefined;\n throw new ToolError(\n hintFor(res.status, message.replace(/\\.$/, ''), code, body),\n res.status,\n code,\n retryAt\n );\n }\n if (data === undefined) {\n throw new ToolError(\n `Unexpected non-JSON response from ${method} ${url.pathname}`\n );\n }\n return data as T;\n }\n\n /**\n * `CHANNLIZE_PROJECT_ID`, or the first project of the key's organization\n * (`GET /projects/me`), looked up once.\n */\n projectId(): Promise<string> {\n if (this.config.projectId) return Promise.resolve(this.config.projectId);\n this.projectIdPromise ??= this.request<{ project: { id: string } }>(\n 'GET',\n '/projects/me'\n )\n .then(r => {\n if (!r.project?.id) {\n throw new ToolError(\n 'Could not find a project for this key: set CHANNLIZE_PROJECT_ID.'\n );\n }\n return r.project.id;\n })\n .catch(err => {\n this.projectIdPromise = undefined;\n throw err;\n });\n return this.projectIdPromise;\n }\n\n /** `@channlize/core` client bound to the widget key (visitor tools). */\n widget(): ChannlizeClient {\n if (!this.config.widgetKey) {\n throw new ToolError(\n 'This tool needs the public widget key (wk_…): set CHANNLIZE_WIDGET_KEY or pass --widget-key.'\n );\n }\n this.widgetClient ??= new ChannlizeClient({\n apiKey: this.config.widgetKey,\n projectId: this.config.projectId ?? '',\n baseUrl: this.config.baseUrl,\n timeout: this.config.timeout,\n });\n return this.widgetClient;\n }\n\n /** `@channlize/core` client for `notify` (server key + project). */\n async notifier(): Promise<ChannlizeClient> {\n const serverApiKey = this.requireServerKey();\n return new ChannlizeClient({\n // core requires a widget key; notify only uses serverApiKey.\n apiKey: this.config.widgetKey ?? 'unused',\n serverApiKey,\n projectId: await this.projectId(),\n baseUrl: this.config.baseUrl,\n timeout: this.config.timeout,\n });\n }\n}\n","import {\n DEFAULT_BASE_URL,\n DEFAULT_TIMEOUT,\n keyKind,\n readChannlizeEnv,\n} from '@channlize/core';\nimport type { ChannlizeMCPConfig } from './types';\n\n// Key detection lives in @channlize/core; re-exported for compatibility.\nexport { keyKind };\nexport type { KeyKind } from '@channlize/core';\n\n/** A configuration problem the user must fix; the CLI prints it and exits 1. */\nexport class ConfigError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ConfigError';\n }\n}\n\nexport interface ResolvedConfig {\n serverApiKey?: string;\n widgetKey?: string;\n projectId?: string;\n /** Default agent for the agent tools (multi-agent keys). */\n agentId?: string;\n baseUrl: string;\n timeout: number;\n}\n\nconst UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\nfunction clean(value: string | undefined): string | undefined {\n const v = value?.trim();\n return v ? v : undefined;\n}\n\n/**\n * Normalizes the config: `apiKey` (either kind, detected by prefix) fills\n * whichever of `serverApiKey` / `widgetKey` is missing, and a key passed in\n * the wrong slot fails with a message that says which one to use.\n */\nexport function resolveConfig(config: ChannlizeMCPConfig): ResolvedConfig {\n let serverApiKey = clean(config.serverApiKey);\n let widgetKey = clean(config.widgetKey);\n const apiKey = clean(config.apiKey);\n\n if (serverApiKey && keyKind(serverApiKey) === 'widget') {\n throw new ConfigError(\n 'CHANNLIZE_SERVER_API_KEY / --server-api-key holds a widget key (wk_…). ' +\n 'Widget keys are public and only work for the visitor tools: pass it as ' +\n 'CHANNLIZE_WIDGET_KEY / --widget-key, and create a server API key (ch_live_…) ' +\n 'under SDK & Integration → API keys in the Channlize dashboard.'\n );\n }\n if (widgetKey && keyKind(widgetKey) === 'server') {\n throw new ConfigError(\n 'CHANNLIZE_WIDGET_KEY / --widget-key holds a server API key. Pass server keys ' +\n '(ch_live_…) as CHANNLIZE_SERVER_API_KEY / --server-api-key; widget keys start with wk_.'\n );\n }\n if (apiKey) {\n if (keyKind(apiKey) === 'widget') widgetKey ??= apiKey;\n else serverApiKey ??= apiKey;\n }\n\n if (!serverApiKey && !widgetKey) {\n throw new ConfigError(\n 'A Channlize key is required. Set CHANNLIZE_SERVER_API_KEY (or --server-api-key) ' +\n 'to a server API key (ch_live_…) from SDK & Integration → API keys in the ' +\n 'Channlize dashboard. Use a read-scoped key for read-only access, or add the ' +\n 'write scope to send events, logs and conversations.'\n );\n }\n\n const timeout = config.timeout ?? DEFAULT_TIMEOUT;\n if (!Number.isFinite(timeout) || timeout <= 0) {\n throw new ConfigError(\n `Invalid timeout \"${config.timeout}\": use milliseconds, e.g. 10000`\n );\n }\n\n const baseUrl = (clean(config.baseUrl) ?? DEFAULT_BASE_URL).replace(\n /\\/+$/,\n ''\n );\n try {\n new URL(baseUrl);\n } catch {\n throw new ConfigError(\n `Invalid base URL \"${config.baseUrl}\": use e.g. ${DEFAULT_BASE_URL}`\n );\n }\n\n const agentId = clean(config.agentId);\n if (agentId && !UUID.test(agentId)) {\n throw new ConfigError(\n `Invalid agent ID \"${agentId}\": CHANNLIZE_AGENT_ID / --agent-id takes the agent's ID (a UUID, shown in the dashboard under Agents), not its slug.`\n );\n }\n\n return {\n serverApiKey,\n widgetKey,\n projectId: clean(config.projectId),\n agentId,\n baseUrl,\n timeout,\n };\n}\n\n/** Reads `ChannlizeMCPConfig` from the environment (CLI flags override it). */\nexport function configFromEnv(\n env: NodeJS.ProcessEnv = process.env\n): ChannlizeMCPConfig {\n const { timeout, serverApiKey, widgetKey, apiKey, projectId, baseUrl } =\n readChannlizeEnv(env);\n return {\n serverApiKey,\n widgetKey,\n apiKey,\n projectId,\n baseUrl,\n timeout: timeout ? Number(timeout) : undefined,\n // Read here rather than from core, so older @channlize/core versions work.\n agentId: clean(env.CHANNLIZE_AGENT_ID),\n };\n}\n","import type { McpServer } from '@modelcontextprotocol/server';\nimport * as z from 'zod/v4';\nimport { EVENTS, REACT_COMPONENTS } from './docs';\n\nfunction user(text: string) {\n return {\n messages: [\n { role: 'user' as const, content: { type: 'text' as const, text } },\n ],\n };\n}\n\n/** Prompts that use the live tools (need a server API key). */\nexport function registerServerPrompts(server: McpServer) {\n server.registerPrompt(\n 'triage-conversations',\n {\n title: 'Triage open conversations',\n description:\n 'Review open support conversations, rank them by urgency and draft a reply for each.',\n argsSchema: z.object({\n status: z\n .string()\n .optional()\n .describe(\n 'Status to triage: open (default), pending, resolved or closed'\n ),\n limit: z\n .string()\n .optional()\n .describe('How many conversations (default 10)'),\n }),\n },\n ({ status, limit }) =>\n user(`Triage my Channlize support inbox.\n\n1. Call list_conversations with status [\"${status || 'open'}\"] and limit ${Number(limit) || 10}.\n2. For each conversation, call get_conversation to read the thread.\n3. 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.\n4. 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.\n\nPresent 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.`)\n );\n\n server.registerPrompt(\n 'summarize-conversation',\n {\n title: 'Summarize a conversation',\n description: 'Summarize one conversation and suggest the next step.',\n argsSchema: z.object({\n conversationId: z.string().describe('Conversation ID'),\n }),\n },\n ({ conversationId }) =>\n user(\n `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.`\n )\n );\n\n server.registerPrompt(\n 'check-events',\n {\n title: 'Check Events delivery',\n description:\n 'Check that Events reach Slack: list them and explain failed or skipped deliveries.',\n argsSchema: z.object({}),\n },\n () =>\n user(`Check my Channlize Events setup.\n\n1. Call list_event_definitions and list the Events, flagging disabled drafts and Events without a Slack channel.\n2. Call list_event_deliveries (limit 50) and group the deliveries by status.\n3. For each failed or skipped delivery, explain the reason and how to fix it (enable the Event, pick a channel under Events in the dashboard, invite the Slack app to the channel, or connect Slack).`)\n );\n}\n\n/** Integration guides (no key needed beyond startup). */\nexport function registerGuidePrompts(server: McpServer) {\n server.registerPrompt(\n 'setup-events',\n {\n title: 'Add Events to my app',\n description:\n 'Add Channlize Events (notify Slack from server code) to the current codebase.',\n argsSchema: z.object({\n events: z\n .string()\n .optional()\n .describe('Events to add, e.g. \"signup, subscription upgrade\"'),\n }),\n },\n ({ events }) =>\n user(`Add Channlize Events to this codebase${events ? ` for: ${events}` : ''}.\n\nFind where these things happen on the server, then call notify there with a typed event map and an idempotency key derived from the record ID. Never call it from browser code. Read the server key from CHANNLIZE_SERVER_API_KEY and the project from CHANNLIZE_PROJECT_ID, and add both to the env example file. Don't let a notify failure break the request: catch and log it.\n\nReference:\n\n${EVENTS}`)\n );\n\n server.registerPrompt(\n 'setup-live-chat',\n {\n title: 'Add the chat widget',\n description:\n 'Add the Channlize live chat widget to a React or Next.js app.',\n argsSchema: z.object({\n framework: z\n .string()\n .optional()\n .describe('e.g. Next.js App Router, Vite, Remix'),\n }),\n },\n ({ framework }) =>\n user(`Add the Channlize chat widget to this ${framework || 'React'} app: install @channlize/react, render ChannlizeChat once in the root layout (from a 'use client' component on Next.js), read the widget key and project ID from public env variables, and match primaryColor to the app's brand color.\n\nReference:\n\n${REACT_COMPONENTS}`)\n );\n\n server.registerPrompt(\n 'integrate-contact-form',\n {\n title: 'Add a contact form',\n description: 'Add a Channlize contact form page to a React app.',\n argsSchema: z.object({\n styling: z\n .string()\n .optional()\n .describe('Styling approach, e.g. Tailwind or CSS modules'),\n }),\n },\n ({ styling }) =>\n user(`Add a contact page to this app using Channlize. Use the ContactForm component (or useContactForm with a custom form${styling ? ` styled with ${styling}` : ''}) inside ChannlizeProvider, show a clear success state, and surface errors from onError.\n\nReference:\n\n${REACT_COMPONENTS}`)\n );\n}\n","/**\n * Integration docs served as MCP resources and reused by the prompts.\n * Keep in sync with the public API of `@channlize/core` and\n * `@channlize/react` (their `src/index.ts`).\n */\n\nexport const QUICK_START = `# Channlize quick start\n\nChannlize routes website conversations and app events to Slack.\n\n## Keys\n- **Widget key** (\\`wk_…\\`): public, safe in browser code. Used by the chat widget,\n contact form and browser log tracking (\\`apiKey\\` in the SDK config).\n- **Server API key** (\\`ch_live_…\\`): secret, server only (\\`serverApiKey\\`). Scopes:\n \\`read\\` (conversations, contacts, logs, Events) and \\`write\\` (notify, server logs,\n create conversations/contacts). Create both under SDK & Integration → API keys.\n- **Project ID**: shown next to each widget key.\n\n## Install\n\\`\\`\\`bash\nnpm install @channlize/core # any JS runtime\nnpm install @channlize/react # React components and hooks\n\\`\\`\\`\n\n## Browser\n\\`\\`\\`ts\nimport { ChannlizeClient } from '@channlize/core';\n\nconst client = new ChannlizeClient({ apiKey: 'wk_…', projectId: '<project-id>' });\nawait client.submitContactForm({ name: 'Ada', email: 'ada@example.com', message: 'Hi!' });\nawait client.trackEvent('checkout.started', { properties: { cartId: 'c_1' } });\n\\`\\`\\`\n\n## Server\n\\`\\`\\`ts\nimport { createNotifier } from '@channlize/core';\n\n// Reads CHANNLIZE_SERVER_API_KEY (or CHANNLIZE_API_KEY) and CHANNLIZE_PROJECT_ID.\nconst notify = createNotifier();\nawait notify('user.subscribed', { username: 'ada', plan: 'Pro' });\n\\`\\`\\`\n\nErrors are \\`ChannlizeError\\` (\\`statusCode\\`, \\`code\\`), with subclasses\n\\`ValidationError\\` (400), \\`AuthenticationError\\` (401) and \\`RateLimitError\\` (429).\n`;\n\nexport const REACT_COMPONENTS = `# @channlize/react\n\n\\`\\`\\`bash\nnpm install @channlize/react\n\\`\\`\\`\n\n## Floating chat widget (all-in-one)\n\\`ChannlizeChat\\` includes the provider, launcher button and chat window.\n\n\\`\\`\\`tsx\n'use client';\nimport { ChannlizeChat } from '@channlize/react';\n\nexport function SupportWidget() {\n return (\n <ChannlizeChat\n config={{\n apiKey: process.env.NEXT_PUBLIC_CHANNLIZE_WIDGET_KEY!, // wk_…, public\n projectId: process.env.NEXT_PUBLIC_CHANNLIZE_PROJECT_ID!,\n }}\n position=\"bottom-right\"\n primaryColor=\"#2563eb\"\n theme=\"auto\"\n chatProps={{ title: 'Acme Support', greeting: 'Hi there!', welcomeMessage: 'Ask us anything.' }}\n />\n );\n}\n\\`\\`\\`\n\nKey props: \\`position\\` ('bottom-right' | 'bottom-left' | 'top-right' | 'top-left'),\n\\`primaryColor\\`, \\`theme\\` ('auto' | 'light' | 'dark'), \\`defaultOpen\\`, \\`showOnMobile\\`,\n\\`offset\\`, \\`zIndex\\`, \\`onOpen\\`, \\`onClose\\`, and \\`chatProps\\` (SupportChat props).\n\n## Provider + inline components\n\\`\\`\\`tsx\nimport { ChannlizeProvider, SupportChat, ContactForm } from '@channlize/react';\n\n<ChannlizeProvider config={{ apiKey: 'wk_…', projectId: '<project-id>' }}>\n <SupportChat title=\"Need help?\" greeting=\"Hi!\" suggestions={['Pricing', 'Billing']} />\n <ContactForm submitText=\"Send\" successMessage=\"Thanks! We'll reply by email.\" />\n</ChannlizeProvider>\n\\`\\`\\`\n\nSupportChat props include \\`title\\`, \\`greeting\\`, \\`welcomeMessage\\`, \\`suggestions\\`,\n\\`placeholder\\`, \\`allowAttachments\\`, \\`allowEndChat\\`, \\`theme\\`, \\`primaryColor\\`,\n\\`locale\\`, \\`maxLength\\`, \\`labels\\` and the \\`useChatSession\\` options\n(\\`autoConnect\\`, \\`metadata\\`, \\`persistSession\\`, \\`onMessage\\`, \\`onError\\`).\n\nContactForm props: \\`customFields\\`, \\`onSuccess\\`, \\`onError\\`, \\`className\\`, \\`styles\\`,\n\\`submitText\\`, \\`successMessage\\`.\n\n## Hooks (inside ChannlizeProvider)\n- \\`useChatSession(options)\\` → \\`{ session, messages, isConnecting, isConnected, error,\n sendMessage, startSession, endSession, reconnect }\\`\n- \\`useContactForm({ onSuccess, onError })\\` → \\`{ submit, isSubmitting, isSuccess, error, reset }\\`\n- \\`useChannlizeAnalytics()\\` → \\`{ track(name, { properties, severity }) }\\` (log tracking)\n- \\`useChannlize()\\` → \\`{ client, config }\\`\n\n## Next.js App Router\nComponents use state and effects: render them from a \\`'use client'\\` file. The widget\nkey is public (\\`NEXT_PUBLIC_…\\` is fine); never put the server API key in a\n\\`NEXT_PUBLIC_\\` variable.\n`;\n\nexport const EVENTS = `# Events: notify Slack from code\n\nEach event key (e.g. \\`user.subscribed\\`) has a Slack channel and a message template\nwith \\`{{field}}\\` placeholders, set under Events in the dashboard. A key that isn't set\nup yet is saved as a disabled draft the first time it is sent (\\`status: 'skipped'\\`),\nso you can ship code first and configure it after. Server only: needs a server API key\nwith the \\`write\\` scope.\n\n\\`\\`\\`ts\nimport { createNotifier } from '@channlize/core';\n\ntype AppEvents = {\n 'user.subscribed': { username: string; plan: string };\n 'invoice.paid': { amount: string; customer: string };\n};\n\n// Env: CHANNLIZE_SERVER_API_KEY (or CHANNLIZE_API_KEY), CHANNLIZE_PROJECT_ID.\nconst notify = createNotifier<AppEvents>();\n\nconst res = await notify('user.subscribed', { username: 'ada', plan: 'Pro' });\n// res.status: 'queued' | 'skipped' (see res.reason); res.duplicate on a repeated key\n\n// Retry-safe: an idempotency key already used posts nothing.\nawait notify('invoice.paid', { amount: '$49', customer: 'ada@example.com' }, { idempotencyKey: 'inv_123' });\n\\`\\`\\`\n\nTo type keys app-wide instead, augment the interface:\n\\`\\`\\`ts\ndeclare module '@channlize/core' {\n interface ChannlizeEvents {\n 'user.subscribed': { username: string; plan: string };\n }\n}\n\\`\\`\\`\n\nOver HTTP:\n\\`\\`\\`bash\ncurl -X POST https://api.channlize.com/v1/notify \\\\\n -H \"Authorization: Bearer $CHANNLIZE_SERVER_API_KEY\" \\\\\n -H \"Content-Type: application/json\" \\\\\n -H \"Idempotency-Key: signup-42\" \\\\\n -d '{\"projectId\":\"<project-id>\",\"event\":\"user.subscribed\",\"data\":{\"username\":\"ada\"}}'\n\\`\\`\\`\n\nLog tracking is separate: \\`client.trackEvent\\` (browser) / \\`trackServerEvent\\` (server)\nrecord log lines shown under Log tracking.\n`;\n","import type { McpServer } from '@modelcontextprotocol/server';\nimport type { ChannlizeApi } from './api';\nimport { EVENTS, QUICK_START, REACT_COMPONENTS } from './docs';\n\nconst markdown = (uri: string, text: string) => ({\n contents: [{ uri, mimeType: 'text/markdown', text }],\n});\n\nexport function registerResources(server: McpServer, api: ChannlizeApi) {\n server.registerResource(\n 'quick-start',\n 'channlize://docs/quick-start',\n {\n title: 'Channlize quick start',\n description:\n 'Keys, install, and first calls from the browser and the server.',\n mimeType: 'text/markdown',\n },\n uri => markdown(uri.href, QUICK_START)\n );\n server.registerResource(\n 'react-components',\n 'channlize://docs/react-components',\n {\n title: '@channlize/react components and hooks',\n description:\n 'ChannlizeChat, SupportChat, ContactForm, hooks and Next.js notes.',\n mimeType: 'text/markdown',\n },\n uri => markdown(uri.href, REACT_COMPONENTS)\n );\n server.registerResource(\n 'events',\n 'channlize://docs/events',\n {\n title: 'Events: notify Slack from code',\n description:\n 'createNotifier / notify with typed events, idempotency and curl.',\n mimeType: 'text/markdown',\n },\n uri => markdown(uri.href, EVENTS)\n );\n\n if (api.hasServerKey) {\n server.registerResource(\n 'project',\n 'channlize://project',\n {\n title: 'Current Channlize project',\n description:\n \"The key's project: ID, name, totals, permissions and Slack connection.\",\n mimeType: 'application/json',\n },\n async uri => {\n const r = await api.request<{ project: unknown }>(\n 'GET',\n '/projects/me'\n );\n return {\n contents: [\n {\n uri: uri.href,\n mimeType: 'application/json',\n text: JSON.stringify(r.project, null, 2),\n },\n ],\n };\n }\n );\n }\n}\n","/**\n * MCP tools for Channlize.\n *\n * Server-key tools (`ch_live_…`) are registered when a server API key is\n * configured; visitor tools (contact form, chat) when a widget key is. The\n * inbox tools (list, search, reply, assign, tag, close, notes, analytics,\n * routing rules) are defined in `inbox.ts`, and the agent tools (Channlize\n * for Agents) in `agents.ts`; neither depends on the MCP server. They are\n * registered here with `registerInboxTools` and `registerAgentTools`.\n * Every tool returns its result as `structuredContent` (matching its\n * `outputSchema`) plus the same JSON as text for clients that ignore it.\n * Failures are tool errors (`isError: true`) with a message that says how\n * to fix them.\n */\nimport type { McpServer } from '@modelcontextprotocol/server';\nimport * as z from 'zod/v4';\nimport { EVENT_KEY_PATTERN, EVENT_SEVERITIES } from '@channlize/core';\nimport { ChannlizeApi, toToolError } from './api';\nimport { AGENT_TOOLS } from './agents';\nimport { INBOX_TOOLS } from './inbox';\n\ntype Json = Record<string, unknown>;\n\nfunction ok(data: Json) {\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(data, null, 2) }],\n structuredContent: data,\n };\n}\n\n/** Runs a handler, turning any failure into a readable tool error. */\nasync function run(fn: () => Promise<Json>) {\n try {\n return ok(await fn());\n } catch (err) {\n const e = toToolError(err);\n return {\n content: [{ type: 'text' as const, text: e.message }],\n isError: true,\n };\n }\n}\n\nconst record = z.record(z.string(), z.unknown());\nconst loose = z.looseObject({});\nconst page = {\n total: z.number(),\n limit: z.number(),\n offset: z.number(),\n hasMore: z.boolean(),\n};\n\nconst READ = {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n} as const;\n\nexport function registerServerTools(server: McpServer, api: ChannlizeApi) {\n server.registerTool(\n 'get_project',\n {\n title: 'Get project',\n description:\n \"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.\",\n inputSchema: z.object({}),\n outputSchema: z.object({ project: loose }),\n annotations: READ,\n },\n () =>\n run(async () => {\n const r = await api.request<{ project: Json }>('GET', '/projects/me');\n return { project: r.project };\n })\n );\n\n server.registerTool(\n 'get_analytics',\n {\n title: 'Get analytics',\n description:\n 'Daily support activity for the last 30 days (UTC): conversations created and resolved, customer and agent messages.',\n inputSchema: z.object({}),\n outputSchema: z.object({ analytics: loose }),\n annotations: READ,\n },\n () =>\n run(async () => {\n const r = await api.request<{ analytics: Json }>(\n 'GET',\n '/projects/analytics'\n );\n return { analytics: r.analytics };\n })\n );\n\n server.registerTool(\n 'create_conversation',\n {\n title: 'Create conversation',\n description:\n '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.',\n inputSchema: z.object({\n customerEmail: z.email().describe(\"Customer's email address\"),\n customerName: z\n .string()\n .max(255)\n .optional()\n .describe(\"Customer's name\"),\n subject: z.string().min(1).max(500).describe('Subject line'),\n message: z.string().min(1).describe('First message, from the customer'),\n channel: z\n .string()\n .optional()\n .describe('Slack channel ID to post to, overriding routing rules'),\n tags: z.array(z.string()).max(20).optional().describe('Tags'),\n }),\n outputSchema: z.object({ conversation: loose }),\n annotations: {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: true,\n },\n },\n args =>\n run(async () => {\n const conversation = await api.request<Json>('POST', '/conversations', {\n body: args,\n });\n return { conversation };\n })\n );\n\n server.registerTool(\n 'list_contacts',\n {\n title: 'List contacts',\n description:\n 'List the customers who contacted the organization, with their conversation count. Paginate with limit/offset.',\n inputSchema: z.object({\n limit: z.number().int().min(1).max(100).default(50),\n offset: z.number().int().min(0).default(0),\n }),\n outputSchema: z.object({ contacts: z.array(loose), ...page }),\n annotations: READ,\n },\n ({ limit, offset }) =>\n run(async () => {\n const r = await api.request<Json>('GET', '/contacts', {\n query: { limit, offset },\n });\n return {\n contacts: (r.contacts as Json[]) ?? [],\n total: Number(r.total ?? 0),\n limit: Number(r.limit ?? limit),\n offset: Number(r.offset ?? offset),\n hasMore: Boolean(r.hasMore),\n };\n })\n );\n\n server.registerTool(\n 'get_contact',\n {\n title: 'Get contact',\n description: 'Read one contact (customer) by ID.',\n inputSchema: z.object({\n contactId: z\n .string()\n .uuid()\n .describe('Contact ID (from list_contacts)'),\n }),\n outputSchema: z.object({ contact: loose }),\n annotations: READ,\n },\n ({ contactId }) =>\n run(async () => {\n const contact = await api.request<Json>(\n 'GET',\n `/contacts/${encodeURIComponent(contactId)}`\n );\n return { contact };\n })\n );\n\n server.registerTool(\n 'create_contact',\n {\n title: 'Create contact',\n description:\n 'Add a customer by email, or return the existing one with that email. Needs the write scope.',\n inputSchema: z.object({\n email: z.email(),\n name: z.string().max(255).optional(),\n company: z.string().optional(),\n phone: z.string().optional(),\n tags: z.array(z.string()).max(20).optional(),\n }),\n outputSchema: z.object({ contact: loose }),\n annotations: {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n },\n args =>\n run(async () => {\n const contact = await api.request<Json>('POST', '/contacts', {\n body: args,\n });\n return { contact };\n })\n );\n\n server.registerTool(\n 'notify_event',\n {\n title: 'Send an Event to Slack',\n description:\n '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.',\n inputSchema: z.object({\n event: z\n .string()\n .max(100)\n .regex(\n EVENT_KEY_PATTERN,\n 'lowercase letters, digits, dots, underscores or dashes'\n )\n .describe('Event key, e.g. user.subscribed'),\n data: record\n .optional()\n .describe(\n 'Template fields, e.g. { \"username\": \"ada\", \"plan\": \"Pro\" }'\n ),\n idempotencyKey: z\n .string()\n .min(1)\n .max(255)\n .optional()\n .describe('Send at most once per key (retry-safe)'),\n channel: z\n .string()\n .optional()\n .describe(\"Slack channel ID instead of the event's channel\"),\n }),\n outputSchema: z.looseObject({\n id: z.string(),\n event: z.string(),\n status: z.string(),\n reason: z.string().optional(),\n duplicate: z.boolean().optional(),\n }),\n annotations: {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: true,\n },\n },\n ({ event, data, idempotencyKey, channel }) =>\n run(async () => {\n const client = await api.notifier();\n const r = await client.notify(event, data, { idempotencyKey, channel });\n return {\n id: r.id,\n event: r.event,\n status: r.status,\n ...(r.reason ? { reason: r.reason } : {}),\n ...(r.duplicate ? { duplicate: true } : {}),\n };\n })\n );\n\n server.registerTool(\n 'list_event_definitions',\n {\n title: 'List Events',\n description:\n '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.',\n inputSchema: z.object({}),\n outputSchema: z.object({\n projectId: z.string(),\n definitions: z.array(loose),\n }),\n annotations: READ,\n },\n () =>\n run(async () => {\n const projectId = await api.projectId();\n const r = await api.request<{ definitions: Json[] }>(\n 'GET',\n `/v1/projects/${encodeURIComponent(projectId)}/event-definitions`\n );\n return { projectId, definitions: r.definitions ?? [] };\n })\n );\n\n server.registerTool(\n 'list_event_deliveries',\n {\n title: 'List Event deliveries',\n description:\n '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.',\n inputSchema: z.object({\n definitionId: z\n .string()\n .uuid()\n .optional()\n .describe('Only this Event (ID from list_event_definitions)'),\n limit: z.number().int().min(1).max(100).default(20),\n }),\n outputSchema: z.object({\n projectId: z.string(),\n deliveries: z.array(loose),\n }),\n annotations: READ,\n },\n ({ definitionId, limit }) =>\n run(async () => {\n const projectId = await api.projectId();\n const r = await api.request<{ deliveries: Json[] }>(\n 'GET',\n `/v1/projects/${encodeURIComponent(projectId)}/event-deliveries`,\n { query: { definitionId, limit } }\n );\n return { projectId, deliveries: r.deliveries ?? [] };\n })\n );\n\n server.registerTool(\n 'query_logs',\n {\n title: 'Query logs',\n description:\n '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.',\n inputSchema: z.object({\n severity: z.enum(EVENT_SEVERITIES).optional(),\n source: z\n .enum(['client_sdk', 'server_api', 'system'])\n .optional()\n .describe(\n 'client_sdk = browser (widget key), server_api = server key'\n ),\n search: z.string().max(200).optional().describe('Text to look for'),\n from: z.iso\n .datetime({ offset: true })\n .optional()\n .describe('ISO 8601 start'),\n to: z.iso\n .datetime({ offset: true })\n .optional()\n .describe('ISO 8601 end'),\n projectId: z.string().uuid().optional(),\n limit: z.number().int().min(1).max(100).default(50),\n offset: z.number().int().min(0).default(0),\n }),\n outputSchema: z.object({ events: z.array(loose), ...page }),\n annotations: READ,\n },\n args =>\n run(async () => {\n const r = await api.request<Json>('GET', '/v1/events', { query: args });\n return {\n events: (r.events as Json[]) ?? [],\n total: Number(r.total ?? 0),\n limit: Number(r.limit ?? args.limit),\n offset: Number(r.offset ?? args.offset),\n hasMore: Boolean(r.hasMore),\n };\n })\n );\n\n server.registerTool(\n 'track_log',\n {\n title: 'Record a log',\n description:\n '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.',\n inputSchema: z.object({\n name: z\n .string()\n .min(1)\n .max(255)\n .describe('Log name, e.g. payment.failed'),\n severity: z.enum(EVENT_SEVERITIES).default('info'),\n properties: record.optional().describe('Extra fields'),\n }),\n outputSchema: z.object({ id: z.string(), projectId: z.string() }),\n annotations: {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: false,\n },\n },\n ({ name, severity, properties }) =>\n run(async () => {\n const projectId = await api.projectId();\n const r = await api.request<{ id: string }>('POST', '/v1/events', {\n body: { projectId, name, severity, properties },\n });\n return { id: r.id, projectId };\n })\n );\n}\n\nconst VISITOR = {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: true,\n} as const;\n\n/** Tools that act as a website visitor, with the public widget key. */\nexport function registerWidgetTools(server: McpServer, api: ChannlizeApi) {\n server.registerTool(\n 'submit_contact_form',\n {\n title: 'Submit contact form',\n description:\n '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.',\n inputSchema: z.object({\n name: z.string().min(1).describe(\"Visitor's name\"),\n email: z.email().describe(\"Visitor's email\"),\n subject: z.string().optional(),\n message: z.string().min(1),\n pageUrl: z.url().optional().describe('Page the form was sent from'),\n }),\n outputSchema: z.looseObject({\n conversationId: z.string().optional(),\n message: z.string().optional(),\n }),\n annotations: VISITOR,\n },\n args =>\n run(async () => {\n const r = await api.widget().submitContactForm(args);\n return { conversationId: r.conversationId, message: r.message };\n })\n );\n\n server.registerTool(\n 'create_chat_session',\n {\n title: 'Start chat session',\n description:\n 'Start a live chat session as a website visitor (widget key). Returns the session ID for send_message.',\n inputSchema: z.object({\n metadata: record\n .optional()\n .describe('Metadata to attach (e.g. user info)'),\n }),\n outputSchema: z.looseObject({\n sessionId: z.string(),\n status: z.string(),\n }),\n annotations: VISITOR,\n },\n ({ metadata }) =>\n run(async () => {\n const r = await api.widget().createChatSession(metadata);\n return {\n sessionId: r.session.id,\n status: r.session.status,\n createdAt: String(r.session.createdAt),\n };\n })\n );\n\n server.registerTool(\n 'send_message',\n {\n title: 'Send chat message',\n description:\n 'Send a visitor message in a chat session (widget key); it is posted to the Slack thread.',\n inputSchema: z.object({\n sessionId: z.string().min(1).describe('From create_chat_session'),\n content: z.string().min(1).max(5000),\n }),\n outputSchema: z.looseObject({\n messageId: z.string(),\n sessionStatus: z.string(),\n }),\n annotations: VISITOR,\n },\n ({ sessionId, content }) =>\n run(async () => {\n const r = await api.widget().sendMessage(sessionId, content);\n return { messageId: r.message.id, sessionStatus: r.session.status };\n })\n );\n\n server.registerTool(\n 'get_chat_messages',\n {\n title: 'Read chat messages',\n description:\n \"Read a chat session's messages, including agent replies from Slack (widget key).\",\n inputSchema: z.object({\n sessionId: z.string().min(1),\n limit: z.number().int().min(1).max(100).default(50),\n offset: z.number().int().min(0).default(0),\n }),\n outputSchema: z.object({\n sessionId: z.string(),\n messages: z.array(loose),\n }),\n annotations: { ...READ, openWorldHint: true },\n },\n ({ sessionId, limit, offset }) =>\n run(async () => {\n const messages = await api\n .widget()\n .getChatMessages(sessionId, limit, offset);\n return {\n sessionId,\n messages: messages.map(m => ({\n id: m.id,\n author: m.author,\n authorName: m.authorData?.name,\n content: m.content,\n timestamp: String(m.timestamp),\n attachments: m.attachments?.length ?? 0,\n })),\n };\n })\n );\n\n server.registerTool(\n 'close_chat_session',\n {\n title: 'End chat session',\n description: 'End a chat session as the visitor (widget key).',\n inputSchema: z.object({ sessionId: z.string().min(1) }),\n outputSchema: z.looseObject({\n sessionId: z.string(),\n status: z.string(),\n }),\n annotations: { ...VISITOR, idempotentHint: true },\n },\n ({ sessionId }) =>\n run(async () => {\n const s = await api.widget().closeChatSession(sessionId);\n return { sessionId: s.id ?? sessionId, status: s.status };\n })\n );\n}\n\n/**\n * Register the inbox tools (`INBOX_TOOLS` from `inbox.ts`). They are listed\n * for every server key; a call the key's scopes don't allow returns a tool\n * error naming the scope to add.\n */\ntype ToolDefinition = Pick<\n (typeof INBOX_TOOLS)[number],\n | 'name'\n | 'title'\n | 'description'\n | 'inputSchema'\n | 'outputSchema'\n | 'annotations'\n> & { handler: (api: ChannlizeApi, args: never) => Promise<unknown> };\n\nfunction registerAll(\n server: McpServer,\n api: ChannlizeApi,\n tools: readonly ToolDefinition[]\n) {\n for (const tool of tools) {\n server.registerTool(\n tool.name,\n {\n title: tool.title,\n description: tool.description,\n inputSchema: tool.inputSchema,\n outputSchema: tool.outputSchema,\n annotations: tool.annotations,\n },\n (args: unknown) =>\n run(async () => (await tool.handler(api, args as never)) as Json)\n );\n }\n}\n\nexport function registerInboxTools(server: McpServer, api: ChannlizeApi) {\n registerAll(server, api, INBOX_TOOLS);\n}\n\n/** Channlize for Agents: messages, tasks, inbox, directory and channels. */\nexport function registerAgentTools(server: McpServer, api: ChannlizeApi) {\n registerAll(server, api, AGENT_TOOLS);\n}\n","/**\n * The Channlize for Agents toolset: names, zod input/output schemas and\n * handlers for talking to other agents and to people in agent channels,\n * through `/v1/agents`.\n *\n * Like `inbox.ts`, it has no dependency on the MCP server or its\n * transports, so any agent can import it (`@channlize/mcp/agents`): the\n * stdio/HTTP server registers these tools (`registerAgentTools` in\n * `tools.ts`), and an LLM loop can run the same handlers with its own client\n * (anything with a `request(method, path, { query, body })`).\n *\n * Identity: the key decides who the tools act as. An agent key acts as its\n * agent; a multi-agent key acts as one of its agents, picked by `agentId`\n * on the call or the requester's default `agentId` (`CHANNLIZE_AGENT_ID` /\n * `--agent-id` on the server).\n *\n * Scopes: `agents:send` (post messages, create, update and hand off\n * tasks, answer escalated questions), `agents:read` (directory, channels,\n * inbox and ack, tasks, the org chart, search, and the graph, cost and\n * metrics insights), `agents:ask_human` (ask people and read the answer)\n * and `agents:admin` (`get_effective_policy` only).\n *\n * No admin-write tools: changing policies, teams, the org chart or an\n * agent's status stays in the dashboard or `@channlize/core` with an\n * `agents:admin` key. Policies are the guardrails on what an agent may do,\n * so the agent that runs these tools shouldn't be able to rewrite them.\n *\n * No export or telemetry tools either (Phase 4): exports dump the org's\n * whole history (messages, tasks, questions, the audit log), and the\n * telemetry settings choose where every agent's traces go, with\n * credentials. Both need an unbound `agents:admin` key and belong to the\n * people who run Channlize: the dashboard, or `@channlize/core`\n * (`agents.exports`, `agents.telemetry`). An agent reads its own history\n * with `search_agent_messages` and its numbers with the insights tools,\n * which only see what its key may read.\n */\nimport * as z from 'zod/v4';\nimport { ToolError, type HttpMethod } from './api';\nimport {\n summarizeCost,\n summarizeGraph,\n summarizeMetrics,\n summarizeSearch,\n} from './agents-summary';\nimport type { ToolAnnotations } from './inbox';\n\ntype Json = Record<string, unknown>;\ntype Query = Record<string, string | number | boolean | undefined>;\n\n/** What a handler needs: `ChannlizeApi` from this package, or your own. */\nexport interface AgentsRequester {\n request<T>(\n method: HttpMethod,\n path: string,\n /** `timeout` (ms) overrides the default, for the `get_answer` long-poll. */\n options?: { query?: Query; body?: unknown; timeout?: number }\n ): Promise<T>;\n /** The agent to act as when a call doesn't pass `agentId`. */\n readonly agentId?: string;\n}\n\n/** The API key scope a tool needs. */\nexport type AgentScope =\n 'agents:send' | 'agents:read' | 'agents:ask_human' | 'agents:admin';\n\nexport interface AgentTool<\n I extends z.ZodObject = z.ZodObject,\n O extends z.ZodObject = z.ZodObject,\n> {\n name: string;\n title: string;\n description: string;\n scope: AgentScope;\n /** The HTTP endpoint it calls, for docs and logs. */\n endpoint: string;\n inputSchema: I;\n outputSchema: O;\n annotations: ToolAnnotations;\n handler: (api: AgentsRequester, args: z.output<I>) => Promise<z.output<O>>;\n}\n\nfunction defineTool<I extends z.ZodObject, O extends z.ZodObject>(\n tool: AgentTool<I, O>\n): AgentTool {\n return tool as unknown as AgentTool;\n}\n\n/** Task lifecycle (same values as the API). */\nexport const AGENT_TASK_STATUSES = [\n 'open',\n 'working',\n 'input_required',\n 'completed',\n 'failed',\n 'canceled',\n 'rejected',\n] as const;\n\n// ----- shared schemas -----\n\nconst uuid = (what: string) => z.string().uuid().describe(what);\n\nconst agentId = uuid(\n '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.'\n).optional();\n\nconst channelId = uuid('Agent channel ID (from list_agent_channels)');\n\nconst threadId = uuid(\n 'Reply in this thread: the id of any message in it (thread_id or id from read_agent_inbox)'\n).optional();\n\nconst mentions = z\n .array(z.string().uuid())\n .max(50)\n .optional()\n .describe('Agent IDs to mention (from list_agents)');\n\nconst data = z\n .record(z.string(), z.unknown())\n .optional()\n .describe('Structured data for the recipients (JSON object)');\n\nconst usage = {\n tokens: z\n .number()\n .int()\n .min(0)\n .optional()\n .describe('Tokens you used for this message (reporting)'),\n cost: z\n .number()\n .min(0)\n .optional()\n .describe('What this message cost you, in USD (reporting)'),\n};\n\nconst message = z.looseObject({\n id: z.string(),\n channel_id: z.string(),\n thread_id: z.string().nullable(),\n type: z.string(),\n text: z.string(),\n sender: z.looseObject({ kind: z.string() }),\n task_status: z.string().nullable().optional(),\n});\n\nconst sendOutput = z.object({\n message,\n deliveries: z.array(\n z.looseObject({ id: z.string(), agent_id: z.string(), status: z.string() })\n ),\n});\n\nconst dueAt = z\n .string()\n .max(40)\n .optional()\n .describe('Due date: an ISO date (2026-11-30) or date-time');\n\nconst task = z.looseObject({\n id: z.string(),\n channel_id: z.string(),\n text: z.string(),\n board_status: z.string(),\n assignee_agent_id: z.string().nullable(),\n due_at: z.string().nullable(),\n});\n\nconst deliveries = z.array(\n z.looseObject({ id: z.string(), agent_id: z.string(), status: z.string() })\n);\n\nconst question = z.looseObject({\n id: z.string(),\n kind: z.string(),\n question: z.string(),\n status: z.string(),\n answer: z.looseObject({}).nullable(),\n});\n\nconst questionId = uuid('The question ID (from ask_human or list_questions)');\n\nconst BOARD_STATUSES = [\n 'open',\n 'in_progress',\n 'blocked',\n 'done',\n 'failed',\n] as const;\n\n/** The longest single long-poll the API holds (`/questions/:id/wait`). */\nexport const QUESTION_WAIT_MAX_SECONDS = 25;\n\nconst READ: ToolAnnotations = {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n};\nconst SEND: ToolAnnotations = {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: true,\n};\n\n/** The call's agent, else the requester's default. */\nfunction actingAs(api: AgentsRequester, id: string | undefined) {\n return id ?? api.agentId;\n}\n\n/** Inbox and ack need the agent in the path. */\nfunction requireAgent(api: AgentsRequester, id: string | undefined): string {\n const agent = actingAs(api, id);\n if (!agent) {\n throw new ToolError(\n 'Pass agentId (from list_agents), or set CHANNLIZE_AGENT_ID / --agent-id on the MCP server.'\n );\n }\n return agent;\n}\n\nasync function send(\n api: AgentsRequester,\n body: Json\n): Promise<z.output<typeof sendOutput>> {\n const r = await api.request<z.output<typeof sendOutput>>(\n 'POST',\n '/v1/agents/messages',\n { body }\n );\n return { message: r.message, deliveries: r.deliveries ?? [] };\n}\n\nconst enc = encodeURIComponent;\n\n/** One line about a closed question, for the model. */\nfunction outcomeMessage(status: string, q: Json): string {\n const answer = (q.answer ?? {}) as Json;\n const choice = answer.option_label ?? answer.option_id;\n const comment = answer.comment ? `: ${String(answer.comment)}` : '';\n switch (status) {\n case 'answered':\n if (q.kind === 'approval') {\n return answer.approved\n ? `Approved${comment}. Go ahead.`\n : `Denied${comment}. Don't do it.`;\n }\n return `Answered: ${[choice, answer.text].filter(Boolean).join(' / ') || '(empty)'}.`;\n case 'expired_default':\n return `Nobody answered by the deadline: the default option applies (${String(choice ?? 'none')}).`;\n case 'expired':\n 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.';\n case 'canceled':\n return 'The question was canceled.';\n default:\n return `Status: ${status}.`;\n }\n}\n\n// ----- Phase 4: search and insights -----\n\nconst AGENT_MESSAGE_TYPES = [\n 'message',\n 'task',\n 'question',\n 'escalation',\n 'status',\n] as const;\n\nconst insightsDay = (what: string) =>\n z\n .string()\n .regex(/^\\d{4}-\\d{2}-\\d{2}$/, 'expected a YYYY-MM-DD date')\n .optional()\n .describe(what);\n\nconst insightsRange = {\n from: insightsDay(\n 'First UTC day, YYYY-MM-DD (default: 30 days before to). Clamped to the plan history window.'\n ),\n to: insightsDay('Last UTC day, inclusive, YYYY-MM-DD (default: today)'),\n channelId: channelId.optional().describe('Only this agent channel'),\n};\n\nconst insightsAgent = uuid(\n 'Only this agent (from list_agents): pass your own id to see your own numbers'\n).optional();\n\nconst mine = z\n .boolean()\n .optional()\n .describe(\n \"true: only your own agent (the server's default agent, CHANNLIZE_AGENT_ID), when you don't know your id\"\n );\n\nconst top = (dflt: number) =>\n z\n .number()\n .int()\n .min(1)\n .max(50)\n .default(dflt)\n .describe(`How many rows to return in each list (1-50, default ${dflt})`);\n\n/** `agentId`, else the default agent with `mine`, else no filter. */\nfunction filterAgent(\n api: AgentsRequester,\n a: { agentId?: string; mine?: boolean }\n): string | undefined {\n if (a.agentId) return a.agentId;\n return a.mine ? requireAgent(api, undefined) : undefined;\n}\n\nconst range = z.looseObject({\n from: z.string(),\n to: z.string(),\n days: z.number(),\n clamped: z.boolean(),\n empty: z.boolean(),\n});\n\nconst nullableNumber = z.number().nullable();\n\n// ----- the tools -----\n\nexport const AGENT_TOOLS: readonly AgentTool[] = [\n defineTool({\n name: 'send_agent_message',\n title: 'Send agent message',\n description:\n '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.',\n scope: 'agents:send',\n endpoint: 'POST /v1/agents/messages',\n inputSchema: z.object({\n agentId,\n channelId,\n text: z.string().min(1).max(40_000).describe('Message text'),\n threadId,\n mentions,\n data,\n ...usage,\n }),\n outputSchema: sendOutput,\n annotations: SEND,\n handler: (api, a) =>\n send(api, {\n agent_id: actingAs(api, a.agentId),\n channel_id: a.channelId,\n type: 'message',\n text: a.text,\n thread_id: a.threadId,\n mentions: a.mentions,\n data: a.data,\n tokens: a.tokens,\n cost: a.cost,\n }),\n }),\n\n defineTool({\n name: 'create_task',\n title: 'Create task',\n description:\n '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.',\n scope: 'agents:send',\n endpoint: 'POST /v1/agents/tasks',\n inputSchema: z.object({\n agentId,\n channelId,\n text: z\n .string()\n .min(1)\n .max(40_000)\n .describe('What should be done, with enough context to do it'),\n assigneeAgentId: uuid(\n 'The agent that should do it: a member of the channel (from list_agents)'\n ).optional(),\n dueAt,\n threadId,\n mentions,\n data,\n }),\n // `message` is the task too (a task is its `task` message plus board fields).\n outputSchema: z.object({ taskId: z.string(), task, message, deliveries }),\n annotations: SEND,\n handler: async (api, a) => {\n const r = await api.request<{ task: Json; deliveries?: Json[] }>(\n 'POST',\n '/v1/agents/tasks',\n {\n body: {\n agent_id: actingAs(api, a.agentId),\n channel_id: a.channelId,\n text: a.text,\n assignee_agent_id: a.assigneeAgentId,\n due_at: a.dueAt,\n thread_id: a.threadId,\n mentions: a.mentions,\n data: a.data,\n },\n }\n );\n return {\n taskId: String(r.task.id),\n task: r.task as never,\n message: r.task as never,\n deliveries: (r.deliveries ?? []) as never,\n };\n },\n }),\n\n defineTool({\n name: 'update_task_status',\n title: 'Update task status',\n description:\n '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 → in_progress, input_required → blocked, completed → 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.',\n scope: 'agents:send',\n endpoint: 'POST /v1/agents/messages',\n inputSchema: z.object({\n agentId,\n channelId,\n taskId: uuid('The task message ID'),\n status: z\n .enum(AGENT_TASK_STATUSES)\n .describe('The new status of the task'),\n text: z\n .string()\n .max(40_000)\n .optional()\n .describe('What changed, e.g. the result or what input is needed'),\n data,\n ...usage,\n }),\n outputSchema: sendOutput,\n annotations: SEND,\n handler: (api, a) =>\n send(api, {\n agent_id: actingAs(api, a.agentId),\n channel_id: a.channelId,\n type: 'status',\n text: a.text ?? '',\n task_id: a.taskId,\n task_status: a.status,\n data: a.data,\n tokens: a.tokens,\n cost: a.cost,\n }),\n }),\n\n defineTool({\n name: 'update_task',\n title: 'Update task',\n description:\n \"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.\",\n scope: 'agents:send',\n endpoint: 'PATCH /v1/agents/tasks/:taskId',\n inputSchema: z.object({\n agentId,\n taskId: uuid('The task ID'),\n status: z.enum(BOARD_STATUSES).optional().describe('The board column'),\n dueAt: z\n .string()\n .max(40)\n .nullable()\n .optional()\n .describe('New due date (ISO date or date-time); null clears it'),\n note: z\n .string()\n .max(2000)\n .optional()\n .describe('What changed, shown with the update'),\n }),\n outputSchema: z.object({ task, changed: z.boolean() }),\n annotations: SEND,\n handler: async (api, a) => {\n if (a.status === undefined && a.dueAt === undefined) {\n throw new ToolError('Pass status or dueAt.');\n }\n const r = await api.request<{ task: Json; changed?: boolean }>(\n 'PATCH',\n `/v1/agents/tasks/${enc(a.taskId)}`,\n {\n body: {\n agent_id: actingAs(api, a.agentId),\n status: a.status,\n due_at: a.dueAt,\n note: a.note,\n },\n }\n );\n return { task: r.task as never, changed: Boolean(r.changed) };\n },\n }),\n\n defineTool({\n name: 'handoff_task',\n title: 'Hand off task',\n description:\n \"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.\",\n scope: 'agents:send',\n endpoint: 'POST /v1/agents/tasks/:taskId/handoff',\n inputSchema: z.object({\n agentId,\n taskId: uuid('The task ID'),\n toAgentId: uuid('The new assignee (from list_agents or get_org_chart)'),\n reason: z\n .string()\n .max(2000)\n .optional()\n .describe('Why, and what the new assignee needs to know'),\n }),\n outputSchema: z.object({ task, deliveries }),\n annotations: SEND,\n handler: async (api, a) => {\n const r = await api.request<{ task: Json; deliveries?: Json[] }>(\n 'POST',\n `/v1/agents/tasks/${enc(a.taskId)}/handoff`,\n {\n body: {\n agent_id: actingAs(api, a.agentId),\n to_agent_id: a.toAgentId,\n reason: a.reason,\n },\n }\n );\n return {\n task: r.task as never,\n deliveries: (r.deliveries ?? []) as never,\n };\n },\n }),\n\n defineTool({\n name: 'list_tasks',\n title: 'List tasks',\n description:\n \"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.\",\n scope: 'agents:read',\n endpoint: 'GET /v1/agents/tasks',\n inputSchema: z.object({\n agentId,\n channelId: channelId.optional(),\n assigneeAgentId: uuid('Only tasks assigned to this agent').optional(),\n status: z.enum(BOARD_STATUSES).optional(),\n limit: z\n .number()\n .int()\n .min(1)\n .max(500)\n .default(50)\n .describe('How many to return (1-500, default 50)'),\n }),\n outputSchema: z.object({ tasks: z.array(task) }),\n annotations: READ,\n handler: async (api, a) => {\n const r = await api.request<{ tasks?: Json[] }>(\n 'GET',\n '/v1/agents/tasks',\n {\n query: {\n agent_id: actingAs(api, a.agentId),\n channel_id: a.channelId,\n assignee_agent_id: a.assigneeAgentId,\n status: a.status,\n limit: a.limit,\n },\n }\n );\n return { tasks: (r.tasks ?? []) as never };\n },\n }),\n\n defineTool({\n name: 'get_task_board',\n title: 'Get task board',\n description:\n \"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.\",\n scope: 'agents:read',\n endpoint: 'GET /v1/agents/tasks/board',\n inputSchema: z.object({\n agentId,\n channelId,\n assigneeAgentId: uuid('Only tasks assigned to this agent').optional(),\n }),\n outputSchema: z.object({\n channel_id: z.string(),\n columns: z.record(z.string(), z.array(task)),\n counts: z.record(z.string(), z.number()),\n agents: z.array(z.looseObject({ id: z.string() })),\n truncated: z.boolean(),\n }),\n annotations: READ,\n handler: async (api, a) =>\n (await api.request<Json>('GET', '/v1/agents/tasks/board', {\n query: {\n agent_id: actingAs(api, a.agentId),\n channel_id: a.channelId,\n assignee_agent_id: a.assigneeAgentId,\n },\n })) as never,\n }),\n\n defineTool({\n name: 'ask_human',\n title: 'Ask a human',\n description:\n \"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.\",\n scope: 'agents:ask_human',\n endpoint: 'POST /v1/agents/questions',\n inputSchema: z.object({\n agentId,\n kind: z\n .enum(['question', 'approval'])\n .default('question')\n .describe('question (default) or approval (answered Approve / Deny)'),\n question: z\n .string()\n .min(1)\n .max(3000)\n .describe('The question, with what people need to answer it'),\n options: z\n .array(\n z.object({\n id: z.string().min(1).max(100),\n label: z.string().min(1).max(75),\n })\n )\n .max(10)\n .optional()\n .describe('Up to 10 answers to pick from (ignored for approvals)'),\n freeText: z\n .boolean()\n .optional()\n .describe('Allow a typed answer (always on without options)'),\n urgency: z\n .enum(['low', 'normal', 'high', 'urgent'])\n .optional()\n .describe('How fast it escalates (default normal)'),\n deadline: z\n .string()\n .max(40)\n .optional()\n .describe('ISO date-time, at most 30 days away'),\n defaultOption: z\n .string()\n .max(100)\n .optional()\n .describe('Option id applied at the deadline when nobody answered'),\n channelId: channelId\n .optional()\n .describe('Post it in this agent channel (from list_agent_channels)'),\n threadId,\n context: z\n .record(z.string(), z.unknown())\n .optional()\n .describe('Facts shown with the question (JSON object)'),\n amount: z\n .number()\n .min(0)\n .optional()\n .describe('Approvals: the amount at stake'),\n currency: z\n .string()\n .regex(/^[A-Za-z]{3}$/)\n .optional()\n .describe('Approvals: ISO 4217 currency code'),\n resource: z\n .record(z.string(), z.unknown())\n .optional()\n .describe('Approvals: what is being approved (JSON object)'),\n requiredRoles: z\n .array(z.string().min(1).max(40))\n .max(10)\n .optional()\n .describe('Approvals: roles that may answer, e.g. [\"admin\"]'),\n }),\n outputSchema: z.object({ questionId: z.string(), question }),\n annotations: SEND,\n handler: async (api, a) => {\n const r = await api.request<{ question: Json }>(\n 'POST',\n '/v1/agents/questions',\n {\n body: {\n agent_id: actingAs(api, a.agentId),\n kind: a.kind,\n question: a.question,\n options: a.options,\n free_text: a.freeText,\n urgency: a.urgency,\n deadline: a.deadline,\n default_option: a.defaultOption,\n channel_id: a.channelId,\n thread_id: a.threadId,\n context: a.context,\n amount: a.amount,\n currency: a.currency,\n resource: a.resource,\n required_roles: a.requiredRoles,\n },\n }\n );\n return {\n questionId: String(r.question.id),\n question: r.question as never,\n };\n },\n }),\n\n defineTool({\n name: 'get_answer',\n title: 'Get answer',\n 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).`,\n scope: 'agents:ask_human',\n endpoint: 'GET /v1/agents/questions/:id/wait',\n inputSchema: z.object({\n agentId,\n questionId,\n waitSeconds: z\n .number()\n .int()\n .min(0)\n .max(QUESTION_WAIT_MAX_SECONDS)\n .default(QUESTION_WAIT_MAX_SECONDS)\n .describe(\n `Seconds to wait for an answer (0-${QUESTION_WAIT_MAX_SECONDS}, default ${QUESTION_WAIT_MAX_SECONDS}); 0 only checks`\n ),\n }),\n outputSchema: z.object({\n questionId: z.string(),\n status: z.string(),\n waiting: z.boolean(),\n answer: z.looseObject({}).nullable(),\n message: z.string(),\n question,\n }),\n annotations: READ,\n handler: async (api, a) => {\n const r = await api.request<{ question: Json; timed_out?: boolean }>(\n 'GET',\n `/v1/agents/questions/${enc(a.questionId)}/wait`,\n {\n query: {\n agent_id: actingAs(api, a.agentId),\n timeout: a.waitSeconds,\n },\n // The API holds the request for up to waitSeconds.\n timeout: (a.waitSeconds + 10) * 1000,\n }\n );\n const status = String(r.question.status);\n const waiting = status === 'open';\n return {\n questionId: a.questionId,\n status,\n waiting,\n answer: (r.question.answer ?? null) as never,\n message: waiting\n ? `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.`\n : outcomeMessage(status, r.question),\n question: r.question as never,\n };\n },\n }),\n\n defineTool({\n name: 'list_questions',\n title: 'List questions',\n description:\n '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).',\n scope: 'agents:read',\n endpoint: 'GET /v1/agents/questions',\n inputSchema: z.object({\n agentId,\n status: z\n .enum(['open', 'answered', 'expired_default', 'expired', 'canceled'])\n .optional(),\n kind: z.enum(['question', 'approval']).optional(),\n channelId: channelId.optional(),\n cursor: z\n .string()\n .max(300)\n .optional()\n .describe('nextCursor of the previous call'),\n limit: z\n .number()\n .int()\n .min(1)\n .max(200)\n .default(20)\n .describe('How many to return (1-200, default 20)'),\n }),\n outputSchema: z.object({\n questions: z.array(question),\n nextCursor: z.string().nullable(),\n }),\n annotations: READ,\n handler: async (api, a) => {\n const r = await api.request<{\n questions?: Json[];\n next_cursor?: string | null;\n }>('GET', '/v1/agents/questions', {\n query: {\n agent_id: actingAs(api, a.agentId),\n status: a.status,\n kind: a.kind,\n channel_id: a.channelId,\n cursor: a.cursor,\n limit: a.limit,\n },\n });\n return {\n questions: (r.questions ?? []) as never,\n nextCursor: r.next_cursor ?? null,\n };\n },\n }),\n\n defineTool({\n name: 'cancel_question',\n title: 'Cancel question',\n description:\n \"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.\",\n scope: 'agents:ask_human',\n endpoint: 'DELETE /v1/agents/questions/:id',\n inputSchema: z.object({ agentId, questionId }),\n outputSchema: z.object({ question }),\n annotations: {\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: false,\n openWorldHint: true,\n },\n handler: async (api, a) => {\n const r = await api.request<{ question: Json }>(\n 'DELETE',\n `/v1/agents/questions/${enc(a.questionId)}`,\n { query: { agent_id: actingAs(api, a.agentId) } }\n );\n return { question: r.question as never };\n },\n }),\n\n defineTool({\n name: 'answer_escalated_question',\n title: 'Answer escalated question',\n description:\n \"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.\",\n scope: 'agents:send',\n endpoint: 'POST /v1/agents/questions/:id/answer',\n inputSchema: z.object({\n agentId,\n questionId,\n optionId: z\n .string()\n .min(1)\n .max(100)\n .optional()\n .describe('One of the question options (approve / deny for approvals)'),\n text: z\n .string()\n .max(3000)\n .optional()\n .describe('A typed answer, when the question allows free text'),\n comment: z\n .string()\n .max(2000)\n .optional()\n .describe('Why (shown with the answer; say why on a deny)'),\n }),\n outputSchema: z.object({ question }),\n annotations: SEND,\n handler: async (api, a) => {\n if (!a.optionId && !a.text) throw new ToolError('Pass optionId or text.');\n const r = await api.request<{ question: Json }>(\n 'POST',\n `/v1/agents/questions/${enc(a.questionId)}/answer`,\n {\n body: {\n agent_id: actingAs(api, a.agentId),\n option_id: a.optionId,\n text: a.text,\n comment: a.comment,\n },\n }\n );\n return { question: r.question as never };\n },\n }),\n\n defineTool({\n name: 'get_org_chart',\n title: 'Get org chart',\n description:\n \"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.\",\n scope: 'agents:read',\n endpoint: 'GET /v1/agents/org-chart',\n inputSchema: z.object({\n teamId: uuid('Only this team').optional(),\n channelId: uuid('Only the agents of this channel').optional(),\n includeRetired: z\n .boolean()\n .optional()\n .describe('Include retired agents (default false)'),\n }),\n outputSchema: z.object({\n agents: z.array(z.looseObject({ id: z.string() })),\n users: z.array(z.looseObject({ id: z.string() })),\n teams: z.array(z.looseObject({ id: z.string() })),\n tree: z.array(z.looseObject({})),\n }),\n annotations: READ,\n handler: async (api, a) =>\n (await api.request<Json>('GET', '/v1/agents/org-chart', {\n query: {\n team_id: a.teamId,\n channel_id: a.channelId,\n include_retired: a.includeRetired ? 'true' : undefined,\n },\n })) as never,\n }),\n\n defineTool({\n name: 'get_effective_policy',\n title: 'Get effective policy',\n description:\n '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.',\n scope: 'agents:admin',\n endpoint: 'GET /v1/agents/policies/preview',\n inputSchema: z.object({\n agentId: uuid(\n 'The agent (from list_agents). Default: the server agent (CHANNLIZE_AGENT_ID)'\n ).optional(),\n channelId: channelId.optional(),\n }),\n outputSchema: z.looseObject({\n agent_id: z.string(),\n channel_id: z.string().nullable(),\n rules: z.looseObject({}),\n working_hours: z.looseObject({}),\n usage: z.looseObject({}),\n checks: z.looseObject({}).nullable(),\n }),\n annotations: READ,\n handler: async (api, a) =>\n (await api.request<Json>('GET', '/v1/agents/policies/preview', {\n query: {\n agent_id: requireAgent(api, a.agentId),\n channel_id: a.channelId,\n },\n })) as never,\n }),\n\n defineTool({\n name: 'read_agent_inbox',\n title: 'Read agent inbox',\n description:\n \"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.\",\n scope: 'agents:read',\n endpoint: 'GET /v1/agents/:id/inbox',\n inputSchema: z.object({\n agentId,\n cursor: z\n .string()\n .max(200)\n .optional()\n .describe('Read after this cursor (nextCursor of the previous call)'),\n limit: z\n .number()\n .int()\n .min(1)\n .max(200)\n .default(20)\n .describe('How many to return (1-200, default 20)'),\n }),\n outputSchema: z.object({\n agentId: z.string(),\n messages: z.array(\n z.looseObject({\n delivery_id: z.string(),\n cursor: z.string(),\n message,\n })\n ),\n nextCursor: z.string().nullable(),\n hasMore: z.boolean(),\n }),\n annotations: READ,\n handler: async (api, a) => {\n const id = requireAgent(api, a.agentId);\n const r = await api.request<Json>('GET', `/v1/agents/${enc(id)}/inbox`, {\n query: { cursor: a.cursor, limit: a.limit },\n });\n return {\n agentId: id,\n messages: (r.messages ?? []) as never,\n nextCursor: (r.next_cursor as string | null | undefined) ?? null,\n hasMore: Boolean(r.has_more),\n };\n },\n }),\n\n defineTool({\n name: 'ack_agent_messages',\n title: 'Acknowledge agent messages',\n description:\n '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.',\n scope: 'agents:read',\n endpoint: 'POST /v1/agents/:id/inbox/ack',\n inputSchema: z.object({\n agentId,\n upTo: z\n .string()\n .uuid()\n .optional()\n .describe('Ack everything up to and including this delivery_id'),\n ids: z\n .array(z.string().uuid())\n .min(1)\n .max(500)\n .optional()\n .describe('Ack these delivery (or message) IDs'),\n }),\n outputSchema: z.object({ acked: z.number() }),\n annotations: {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n handler: async (api, a) => {\n if (!a.upTo === !a.ids) {\n throw new ToolError('Pass either upTo or ids.');\n }\n const id = requireAgent(api, a.agentId);\n const r = await api.request<{ acked?: number }>(\n 'POST',\n `/v1/agents/${enc(id)}/inbox/ack`,\n { body: a.upTo ? { up_to: a.upTo } : { ids: a.ids } }\n );\n return { acked: Number(r.acked ?? 0) };\n },\n }),\n\n defineTool({\n name: 'search_agent_messages',\n title: 'Search agent messages',\n description:\n 'Full-text search over agent channel history: messages, tasks, status updates and questions to people (with their answers), best match first. Use it to find what was said or decided before, a past task, or an answer a human already gave, instead of asking again. q takes websearch syntax: \"exact phrase\", or, -word; codes and ids match as substrings (INV-20 finds INV-2041). Each result has a highlight (hits in **bold**), the channel, threadId and a Slack link when mirrored. Searches the channels your key\\'s agents can read and their own questions (the whole org for an agents:admin key), within the plan\\'s history window. Page with cursor. Needs the agents:read scope.',\n scope: 'agents:read',\n endpoint: 'GET /v1/agents/search',\n inputSchema: z.object({\n q: z\n .string()\n .trim()\n .min(2)\n .max(200)\n .describe('What to look for (2-200 characters)'),\n agentId: uuid(\n 'Only messages sent by or mentioning this agent, and questions it asked (from list_agents). With a multi-agent key it also picks whose channels are searched.'\n ).optional(),\n channelId: channelId.optional().describe('Only this agent channel'),\n type: z\n .enum(AGENT_MESSAGE_TYPES)\n .optional()\n .describe('Only this message type'),\n include: z\n .enum(['messages', 'questions', 'both'])\n .default('both')\n .describe('messages, questions, or both (default)'),\n from: z\n .string()\n .max(40)\n .optional()\n .describe('ISO date-time: the earliest to search'),\n to: z\n .string()\n .max(40)\n .optional()\n .describe('ISO date-time: the latest to search'),\n cursor: z\n .string()\n .max(300)\n .optional()\n .describe('nextCursor of the previous call'),\n limit: z\n .number()\n .int()\n .min(1)\n .max(50)\n .default(10)\n .describe('How many results (1-50, default 10)'),\n }),\n outputSchema: z.object({\n results: z.array(\n z.looseObject({\n kind: z.string(),\n id: z.string(),\n type: z.string(),\n text: z.string(),\n highlight: z.string(),\n channel: z.string().nullable(),\n threadId: z.string().nullable(),\n })\n ),\n nextCursor: z.string().nullable(),\n window: z.object({ from: z.string(), days: z.number() }),\n }),\n annotations: READ,\n handler: async (api, a) => {\n const r = await api.request<Json>('GET', '/v1/agents/search', {\n query: {\n q: a.q,\n agent_id: a.agentId,\n channel_id: a.channelId,\n type: a.type,\n include: a.include === 'both' ? undefined : a.include,\n from: a.from,\n to: a.to,\n cursor: a.cursor,\n limit: a.limit,\n },\n });\n return summarizeSearch(r) as never;\n },\n }),\n\n defineTool({\n name: 'get_agent_graph',\n title: 'Get agent communication graph',\n description:\n \"Who talks to whom among agents and people over a range of days: the busiest participants (messages sent and received, tokens, cost) and the busiest sender → recipient edges (messages, replies, reply latency), with totals and a one-line summary. Rows beyond top are counted in omitted. Filter to one agent (agentId, or mine for your own), a team or a channel. Sees the channels your key's agents can read (the whole org for an agents:admin key). Needs the agents:read scope.\",\n scope: 'agents:read',\n endpoint: 'GET /v1/agents/insights/graph',\n inputSchema: z.object({\n ...insightsRange,\n agentId: insightsAgent,\n mine,\n teamId: uuid('Only edges touching this team').optional(),\n top: top(10),\n }),\n outputSchema: z.object({\n range,\n totals: z.object({\n nodes: z.number(),\n edges: z.number(),\n messages: z.number(),\n tokens: z.number(),\n cost: z.number(),\n }),\n topNodes: z.array(\n z.looseObject({ id: z.string(), label: z.string(), sent: z.number() })\n ),\n topEdges: z.array(\n z.looseObject({\n source: z.string(),\n target: z.string(),\n messages: z.number(),\n replyAvgMs: nullableNumber,\n })\n ),\n omitted: z.looseObject({ nodes: z.number(), edges: z.number() }),\n summary: z.string(),\n }),\n annotations: READ,\n handler: async (api, a) => {\n const r = await api.request<Json>('GET', '/v1/agents/insights/graph', {\n query: {\n from: a.from,\n to: a.to,\n channel_id: a.channelId,\n agent_id: filterAgent(api, a),\n team_id: a.teamId,\n },\n });\n return summarizeGraph(r, a.top) as never;\n },\n }),\n\n defineTool({\n name: 'get_agent_cost',\n title: 'Get agent cost',\n description:\n \"What agents spent, from the tokens and cost they reported on their messages: the range's totals, the top groups by cost (groupBy agent, channel, team, task or day) with their share, the active days and the peak day, and a one-line summary. Check your own spend with mine (or agentId), e.g. before starting expensive work or to report it. Cost is in whatever currency agents report (usually USD). Sees the channels your key's agents can read (the whole org for an agents:admin key). Needs the agents:read scope.\",\n scope: 'agents:read',\n endpoint: 'GET /v1/agents/insights/cost',\n inputSchema: z.object({\n ...insightsRange,\n groupBy: z\n .enum(['agent', 'channel', 'team', 'task', 'day'])\n .default('agent')\n .describe('How to break the cost down (default agent)'),\n agentId: insightsAgent,\n mine,\n teamId: uuid(\"Only what this team's agents sent\").optional(),\n top: top(10),\n }),\n outputSchema: z.object({\n range,\n groupBy: z.string(),\n totals: z.object({\n messages: z.number(),\n pricedMessages: z.number(),\n tokens: z.number(),\n cost: z.number(),\n }),\n groups: z.array(\n z.looseObject({\n key: z.string(),\n label: z.string(),\n cost: z.number(),\n share: nullableNumber,\n })\n ),\n omittedGroups: z.number(),\n truncated: z.boolean(),\n daily: z.array(z.looseObject({ day: z.string(), cost: z.number() })),\n peakDay: z.object({ day: z.string(), cost: z.number() }).nullable(),\n summary: z.string(),\n }),\n annotations: READ,\n handler: async (api, a) => {\n const r = await api.request<Json>('GET', '/v1/agents/insights/cost', {\n query: {\n from: a.from,\n to: a.to,\n channel_id: a.channelId,\n agent_id: filterAgent(api, a),\n team_id: a.teamId,\n group_by: a.groupBy,\n // Day groups come back whole; the others only need the top ones.\n limit: a.groupBy === 'day' ? undefined : a.top,\n },\n });\n return summarizeCost(r, a.top) as never;\n },\n }),\n\n defineTool({\n name: 'get_agent_metrics',\n title: 'Get agent metrics',\n description:\n 'Response metrics over a range of days: reply latency (agent → agent, human → agent, agent → human: avg, p50, p90 and reply rate) and per responding agent, questions to people (answer rate, time to a human answer, by urgency), delivery failure and retry rates per mode, and the inbox backlog right now, with a one-line summary. Use mine (or agentId) to check how fast you answer and whether your inbox is backing up. Needs the agents:read scope.',\n scope: 'agents:read',\n endpoint: 'GET /v1/agents/insights/metrics',\n inputSchema: z.object({\n ...insightsRange,\n agentId: insightsAgent,\n mine,\n top: top(5),\n }),\n outputSchema: z.object({\n range,\n replies: z.looseObject({\n agentToAgent: z.looseObject({ avgMs: nullableNumber }),\n humanToAgent: z.looseObject({ avgMs: nullableNumber }),\n agentToHuman: z.looseObject({ avgMs: nullableNumber }),\n byAgent: z.array(z.looseObject({ agentId: z.string() })),\n }),\n questions: z.looseObject({ asked: z.number() }),\n deliveries: z.looseObject({ deliveries: z.number() }),\n backlog: z.looseObject({ unacked: z.number(), held: z.number() }),\n summary: z.string(),\n }),\n annotations: READ,\n handler: async (api, a) => {\n const r = await api.request<Json>('GET', '/v1/agents/insights/metrics', {\n query: {\n from: a.from,\n to: a.to,\n channel_id: a.channelId,\n agent_id: filterAgent(api, a),\n },\n });\n return summarizeMetrics(r, a.top) as never;\n },\n }),\n\n defineTool({\n name: 'list_agents',\n title: 'List agents',\n description:\n \"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.\",\n scope: 'agents:read',\n endpoint: 'GET /v1/agents',\n inputSchema: z.object({\n includeRetired: z\n .boolean()\n .optional()\n .describe('Include retired agents (default false)'),\n }),\n outputSchema: z.object({\n agents: z.array(\n z.looseObject({\n id: z.string(),\n slug: z.string(),\n name: z.string(),\n status: z.string(),\n })\n ),\n }),\n annotations: READ,\n handler: async (api, a) => {\n const r = await api.request<{ agents?: Json[] }>('GET', '/v1/agents', {\n query: { include_retired: a.includeRetired || undefined },\n });\n return { agents: (r.agents ?? []) as never };\n },\n }),\n\n defineTool({\n name: 'list_agent_channels',\n title: 'List agent channels',\n description:\n \"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.\",\n scope: 'agents:read',\n endpoint: 'GET /v1/agents/channels',\n inputSchema: z.object({\n includeArchived: z\n .boolean()\n .optional()\n .describe('Include archived channels (default false)'),\n }),\n outputSchema: z.object({\n channels: z.array(\n z.looseObject({\n id: z.string(),\n slug: z.string(),\n name: z.string(),\n archived: z.boolean(),\n })\n ),\n }),\n annotations: READ,\n handler: async (api, a) => {\n const r = await api.request<{ channels?: Json[] }>(\n 'GET',\n '/v1/agents/channels',\n { query: { include_archived: a.includeArchived || undefined } }\n );\n return { channels: (r.channels ?? []) as never };\n },\n }),\n];\n\nexport const AGENT_TOOL_NAMES = AGENT_TOOLS.map(t => t.name);\n\nexport function getAgentTool(name: string): AgentTool | undefined {\n return AGENT_TOOLS.find(t => t.name === name);\n}\n\n/**\n * Validate `args` against the tool's input schema and run it. Throws\n * `ToolError` for an unknown tool or invalid arguments, and for API\n * failures (`toToolError` in `api.ts` words them for the model).\n */\nexport async function runAgentTool(\n api: AgentsRequester,\n name: string,\n args: unknown\n): Promise<Json> {\n const tool = getAgentTool(name);\n if (!tool) throw new ToolError(`Unknown agent tool \"${name}\"`);\n const parsed = tool.inputSchema.safeParse(args ?? {});\n if (!parsed.success) {\n throw new ToolError(\n `Invalid arguments for ${name}: ${parsed.error.issues\n .map(i => `${i.path.join('.') || 'input'}: ${i.message}`)\n .join('; ')}`\n );\n }\n return (await tool.handler(api, parsed.data)) as Json;\n}\n\n/**\n * The tools as JSON Schema function definitions, for LLM APIs that take\n * `{ name, description, parameters }` (OpenAI / OpenRouter style).\n */\nexport function agentToolsAsJsonSchema(\n filter: (tool: AgentTool) => boolean = () => true\n): Array<{ name: string; description: string; parameters: Json }> {\n return AGENT_TOOLS.filter(filter).map(t => ({\n name: t.name,\n description: t.description,\n parameters: z.toJSONSchema(t.inputSchema, { io: 'input' }) as Json,\n }));\n}\n","/**\n * Compact views of the Phase 4 insights and search responses for the agent\n * tools: the top N rows plus totals, short strings, and a one-line summary,\n * so a model gets the answer without thousands of tokens of graph or\n * series. Pure functions over the API's JSON (see `/v1/agents/insights/*`\n * and `/v1/agents/search` in the api README).\n */\n\ntype Json = Record<string, unknown>;\n\nconst num = (v: unknown): number =>\n typeof v === 'number' ? v : Number(v) || 0;\nconst arr = (v: unknown): Json[] => (Array.isArray(v) ? (v as Json[]) : []);\nconst obj = (v: unknown): Json =>\n v && typeof v === 'object' ? (v as Json) : {};\nconst str = (v: unknown): string | null => (typeof v === 'string' ? v : null);\n\n/** Money as reported, rounded to 4 decimals for reading. */\nfunction money(v: unknown): number {\n return Math.round(num(v) * 10_000) / 10_000;\n}\n\nfunction fmtMoney(v: unknown): string {\n return (\n money(v)\n .toFixed(4)\n .replace(/\\.?0+$/, '') || '0'\n );\n}\n\nfunction pct(v: unknown): string {\n return v === null || v === undefined\n ? 'n/a'\n : `${Math.round(num(v) * 1000) / 10}%`;\n}\n\nfunction fmtMs(v: unknown): string {\n if (v === null || v === undefined) return 'n/a';\n const ms = num(v);\n if (ms < 1000) return `${Math.round(ms)}ms`;\n if (ms < 60_000) return `${Math.round(ms / 100) / 10}s`;\n if (ms < 3_600_000) return `${Math.round(ms / 6000) / 10}m`;\n return `${Math.round(ms / 360_000) / 10}h`;\n}\n\n/** Plain text from the API's safe-HTML highlight: hits as **bold**. */\nexport function highlightText(html: string): string {\n return html\n .replace(/<mark>/g, '**')\n .replace(/<\\/mark>/g, '**')\n .replace(/<[^>]*>/g, '')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/"/g, '\"')\n .replace(/'/g, \"'\")\n .replace(/&/g, '&');\n}\n\nfunction clip(text: unknown, max: number): string {\n const s = typeof text === 'string' ? text : '';\n return s.length > max ? `${s.slice(0, max - 1)}…` : s;\n}\n\nexport interface RangeSummary {\n from: string;\n to: string;\n days: number;\n historyStart: string | null;\n retentionDays: number | null;\n /** `from` was moved forward to the plan's history start. */\n clamped: boolean;\n /** Nothing visible in the range. */\n empty: boolean;\n}\n\nexport function rangeSummary(range: unknown): RangeSummary {\n const r = obj(range);\n return {\n from: String(r.from ?? ''),\n to: String(r.to ?? ''),\n days: num(r.days),\n historyStart: str(r.history_start),\n retentionDays:\n r.retention_days === undefined ? null : num(r.retention_days),\n clamped: Boolean(r.clamped),\n empty: Boolean(r.empty),\n };\n}\n\nfunction rangeNote(r: RangeSummary): string {\n const base = `${r.from}..${r.to} (${r.days} day${r.days === 1 ? '' : 's'}, UTC)`;\n return r.clamped\n ? `${base}; clamped to the plan's history start ${r.historyStart}`\n : base;\n}\n\nfunction latency(v: unknown) {\n const l = obj(v);\n return {\n count: num(l.count),\n avgMs: l.avg_ms === null || l.avg_ms === undefined ? null : num(l.avg_ms),\n p50Ms: l.p50_ms === null || l.p50_ms === undefined ? null : num(l.p50_ms),\n p90Ms: l.p90_ms === null || l.p90_ms === undefined ? null : num(l.p90_ms),\n };\n}\n\n// ----- search -----\n\nexport function summarizeSearch(r: Json) {\n const results = arr(r.results).map(x => {\n const channel = x.channel ? obj(x.channel) : null;\n const base = {\n kind: String(x.kind),\n highlight: clip(highlightText(String(x.highlight ?? '')), 400),\n rank: Math.round(num(x.rank) * 1000) / 1000,\n channel: channel ? (str(channel.slug) ?? str(channel.id)) : null,\n channelId: channel ? str(channel.id) : null,\n threadId: str(x.thread_id),\n slackPermalink: str(x.slack_permalink),\n };\n if (x.kind === 'question') {\n const q = obj(x.question);\n const answer = q.answer ? obj(q.answer) : null;\n return {\n ...base,\n id: String(q.id ?? ''),\n type: 'question',\n text: clip(q.question, 500),\n status: str(q.status),\n answer: answer\n ? clip(\n [answer.option_label ?? answer.option_id, answer.text]\n .filter(Boolean)\n .join(' / '),\n 200\n ) || null\n : null,\n sender: str(q.agent_id) ? `agent:${String(q.agent_id)}` : null,\n createdAt: str(q.created_at),\n };\n }\n const m = obj(x.message);\n const sender = obj(m.sender);\n const senderId = sender.agent_id ?? sender.user_id ?? sender.slack_user_id;\n return {\n ...base,\n id: String(m.id ?? ''),\n type: String(m.type ?? 'message'),\n text: clip(m.text, 500),\n status: str(m.task_status),\n answer: null,\n sender: sender.kind\n ? `${String(sender.kind)}${senderId ? `:${String(senderId)}` : ''}`\n : null,\n createdAt: str(m.created_at),\n };\n });\n const window = obj(r.window);\n return {\n results,\n nextCursor: str(r.next_cursor),\n window: { from: String(window.from ?? ''), days: num(window.days) },\n };\n}\n\n// ----- graph -----\n\nexport function summarizeGraph(r: Json, top: number) {\n const range = rangeSummary(r.range);\n const nodes = arr(r.nodes);\n const labels = new Map(nodes.map(n => [String(n.id), String(n.label)]));\n const topNodes = [...nodes]\n .sort(\n (a, b) => num(b.sent) + num(b.received) - (num(a.sent) + num(a.received))\n )\n .slice(0, top)\n .map(n => ({\n id: String(n.id),\n kind: String(n.kind),\n label: String(n.label),\n slug: str(n.slug),\n sent: num(n.sent),\n received: num(n.received),\n tokens: num(n.tokens),\n cost: money(n.cost),\n }));\n const edges = arr(r.edges);\n const topEdges = [...edges]\n .sort((a, b) => num(b.messages) - num(a.messages))\n .slice(0, top)\n .map(e => {\n const l = latency(e.reply_latency);\n return {\n source: String(e.source),\n target: String(e.target),\n from: labels.get(String(e.source)) ?? String(e.source),\n to: labels.get(String(e.target)) ?? String(e.target),\n messages: num(e.messages),\n replies: num(e.replies),\n cost: money(e.cost),\n replyAvgMs: l.avgMs,\n replyP90Ms: l.p90Ms,\n lastAt: str(e.last_at),\n };\n });\n const totals = obj(r.totals);\n const truncated = obj(r.truncated);\n const t = {\n nodes: num(totals.nodes),\n edges: num(totals.edges),\n messages: num(totals.messages),\n tokens: num(totals.tokens),\n cost: money(totals.cost),\n };\n const busiest = topEdges[0];\n return {\n range,\n totals: t,\n topNodes,\n topEdges,\n /** Not shown here: beyond `top`, or folded / dropped by the API's cap. */\n omitted: {\n nodes: Math.max(0, nodes.length - topNodes.length),\n edges: Math.max(0, edges.length - topEdges.length),\n cappedNodes: num(truncated.nodes),\n cappedEdges: num(truncated.edges),\n },\n summary: range.empty\n ? `No visible activity in ${rangeNote(range)}.`\n : `${t.nodes} participants, ${t.edges} edges, ${t.messages} messages, cost ${fmtMoney(t.cost)} over ${rangeNote(range)}.` +\n (busiest\n ? ` Busiest edge: ${busiest.from} → ${busiest.to} (${busiest.messages} messages, reply avg ${fmtMs(busiest.replyAvgMs)}).`\n : ''),\n };\n}\n\n// ----- cost -----\n\nexport function summarizeCost(r: Json, top: number) {\n const range = rangeSummary(r.range);\n const totals = obj(r.totals);\n const t = {\n messages: num(totals.messages),\n pricedMessages: num(totals.priced_messages),\n tokens: num(totals.tokens),\n cost: money(totals.cost),\n };\n const all = arr(r.groups);\n const groups = all.slice(0, top).map(g => ({\n key: String(g.key),\n label: clip(g.label, 120),\n messages: num(g.messages),\n tokens: num(g.tokens),\n cost: money(g.cost),\n share: g.share === null || g.share === undefined ? null : num(g.share),\n }));\n // Days with activity, most recent last (at most 31).\n const active = arr(r.series).filter(\n d => num(d.messages) > 0 || num(d.cost) > 0\n );\n const daily = active.slice(-31).map(d => ({\n day: String(d.day),\n messages: num(d.messages),\n tokens: num(d.tokens),\n cost: money(d.cost),\n }));\n const peak = active.reduce<Json | null>(\n (best, d) => (!best || num(d.cost) > num(best.cost) ? d : best),\n null\n );\n const groupBy = String(r.group_by ?? 'agent');\n const head = groups\n .slice(0, 3)\n .map(g => `${g.label} ${fmtMoney(g.cost)} (${pct(g.share)})`)\n .join(', ');\n return {\n range,\n groupBy,\n totals: t,\n groups,\n omittedGroups: Math.max(0, all.length - groups.length),\n /** The API had more groups than it returned. */\n truncated: Boolean(r.truncated),\n daily,\n peakDay: peak ? { day: String(peak.day), cost: money(peak.cost) } : null,\n summary: range.empty\n ? `No visible activity in ${rangeNote(range)}.`\n : `Total cost ${fmtMoney(t.cost)} (as reported by agents), ${t.tokens} tokens, ${t.messages} messages (${t.pricedMessages} priced) over ${rangeNote(range)}.` +\n (head ? ` Top by ${groupBy}: ${head}.` : ''),\n };\n}\n\n// ----- metrics -----\n\nfunction pair(v: unknown) {\n const p = obj(v);\n const l = latency(p.latency);\n return {\n messages: num(p.messages),\n replied: num(p.replied),\n replyRate:\n p.reply_rate === null || p.reply_rate === undefined\n ? null\n : num(p.reply_rate),\n avgMs: l.avgMs,\n p50Ms: l.p50Ms,\n p90Ms: l.p90Ms,\n };\n}\n\nexport function summarizeMetrics(r: Json, top: number) {\n const range = rangeSummary(r.range);\n const replies = obj(r.replies);\n const q = obj(r.questions);\n const qLatency = latency(q.time_to_human_answer);\n const byUrgency = obj(q.by_urgency);\n const d = obj(r.deliveries);\n const byMode = obj(d.by_mode);\n const backlog = obj(r.backlog);\n const rate = (v: unknown) => (v === null || v === undefined ? null : num(v));\n\n const out = {\n range,\n replies: {\n agentToAgent: pair(replies.agent_to_agent),\n humanToAgent: pair(replies.human_to_agent),\n agentToHuman: pair(replies.agent_to_human),\n byAgent: arr(replies.by_agent)\n .slice(0, top)\n .map(a => {\n const l = latency(a.latency);\n return {\n agentId: String(a.agent_id),\n name: str(a.name),\n messages: num(a.messages),\n replied: num(a.replied),\n avgMs: l.avgMs,\n p90Ms: l.p90Ms,\n };\n }),\n },\n questions: {\n asked: num(q.asked),\n answered: num(q.answered),\n answeredByUser: num(q.answered_by_user),\n answeredByAgent: num(q.answered_by_agent),\n expired: num(q.expired),\n expiredDefault: num(q.expired_default),\n canceled: num(q.canceled),\n answerRate: rate(q.answer_rate),\n timeToHumanAnswer: {\n count: qLatency.count,\n avgMs: qLatency.avgMs,\n p50Ms: qLatency.p50Ms,\n p90Ms: qLatency.p90Ms,\n },\n byUrgency: Object.fromEntries(\n ['low', 'normal', 'high', 'urgent'].map(u => {\n const b = obj(byUrgency[u]);\n return [\n u,\n {\n asked: num(b.asked),\n answerRate: rate(b.answer_rate),\n p50Ms: latency(b.time_to_human_answer).p50Ms,\n },\n ];\n })\n ),\n },\n deliveries: {\n deliveries: num(d.deliveries),\n failed: num(d.failed),\n retried: num(d.retried),\n failureRate: rate(d.failure_rate),\n retryRate: rate(d.retry_rate),\n byMode: Object.fromEntries(\n ['webhook', 'inbox', 'a2a'].map(m => {\n const b = obj(byMode[m]);\n return [\n m,\n {\n deliveries: num(b.deliveries),\n failed: num(b.failed),\n held: num(b.held),\n failureRate: rate(b.failure_rate),\n retryRate: rate(b.retry_rate),\n },\n ];\n })\n ),\n },\n backlog: {\n asOf: String(backlog.as_of ?? ''),\n unacked: num(backlog.unacked),\n held: num(backlog.held),\n agentsWithBacklog: num(backlog.agents_with_backlog),\n agents: arr(backlog.agents)\n .slice(0, top)\n .map(a => ({\n agentId: String(a.agent_id),\n name: str(a.name),\n delivery: str(a.delivery),\n unacked: num(a.unacked),\n held: num(a.held),\n oldestAgeSeconds:\n a.oldest_age_seconds === null || a.oldest_age_seconds === undefined\n ? null\n : num(a.oldest_age_seconds),\n })),\n },\n summary: '',\n };\n const h2a = out.replies.humanToAgent;\n const a2a = out.replies.agentToAgent;\n out.summary =\n `Over ${rangeNote(range)}: agents answered people in avg ${fmtMs(h2a.avgMs)} (p90 ${fmtMs(h2a.p90Ms)}, ${pct(h2a.replyRate)} replied) and other agents in avg ${fmtMs(a2a.avgMs)} (p90 ${fmtMs(a2a.p90Ms)}).` +\n ` Questions: ${out.questions.asked} asked, ${pct(out.questions.answerRate)} answered, human answer p50 ${fmtMs(out.questions.timeToHumanAnswer.p50Ms)}.` +\n ` Deliveries: ${out.deliveries.deliveries}, ${pct(out.deliveries.failureRate)} failed, ${pct(out.deliveries.retryRate)} retried.` +\n ` Backlog now: ${out.backlog.unacked} unacked, ${out.backlog.held} held.`;\n return out;\n}\n","/**\n * The Channlize inbox toolset: names, zod input/output schemas and handlers\n * for working the inbox through the API-key endpoints under `/v1`.\n *\n * This module has no dependency on the MCP server or its transports, so any\n * agent can import it (`@channlize/mcp/inbox`): the stdio/HTTP server\n * registers these tools (`registerInboxTools` in `tools.ts`), and the\n * dashboard copilot or an internal bot can run the same handlers with its own\n * client (anything with a `request(method, path, { query, body })`).\n *\n * Writes act as a named agent: the API key's name. Replies show in Slack as\n * \"Replied by <key name> (agent)\", and changes as \"… by <key name> (agent)\".\n *\n * Scopes (pick them when creating the key): `inbox:read`, `inbox:write`,\n * `routing:write`, `analytics:read`. A `read` key can use the read tools.\n */\nimport * as z from 'zod/v4';\nimport { ToolError, type HttpMethod } from './api';\n\nexport type { HttpMethod };\n\ntype Json = Record<string, unknown>;\ntype Query = Record<string, string | number | boolean | undefined>;\n\n/** What a handler needs: `ChannlizeApi` from this package, or your own. */\nexport interface InboxRequester {\n request<T>(\n method: HttpMethod,\n path: string,\n options?: { query?: Query; body?: unknown }\n ): Promise<T>;\n}\n\n/** The API key scope a tool needs. `routing:read` is granted by `routing:write`, `inbox:read` or `read`. */\nexport type InboxScope =\n | 'inbox:read'\n | 'inbox:write'\n | 'routing:read'\n | 'routing:write'\n | 'analytics:read';\n\nexport interface ToolAnnotations {\n readOnlyHint: boolean;\n destructiveHint: boolean;\n idempotentHint: boolean;\n openWorldHint: boolean;\n}\n\nexport interface InboxTool<\n I extends z.ZodObject = z.ZodObject,\n O extends z.ZodObject = z.ZodObject,\n> {\n name: string;\n title: string;\n description: string;\n scope: InboxScope;\n /** The HTTP endpoint it calls, for docs and logs. */\n endpoint: string;\n inputSchema: I;\n outputSchema: O;\n annotations: ToolAnnotations;\n handler: (api: InboxRequester, args: z.output<I>) => Promise<z.output<O>>;\n}\n\nfunction defineTool<I extends z.ZodObject, O extends z.ZodObject>(\n tool: InboxTool<I, O>\n): InboxTool {\n return tool as unknown as InboxTool;\n}\n\n// ----- shared schemas -----\n\nexport const CONVERSATION_STATUSES = [\n 'open',\n 'pending',\n 'resolved',\n 'closed',\n] as const;\nexport const CONVERSATION_PRIORITIES = [\n 'low',\n 'normal',\n 'high',\n 'urgent',\n] as const;\nexport const CONVERSATION_SORTS = [\n 'recent',\n 'oldest',\n 'newest',\n 'priority',\n] as const;\n\nconst loose = z.looseObject({});\nconst id = (what: string) => z.string().uuid().describe(`${what} ID`);\nconst conversationId = id(\n 'Conversation (from list_conversations or search_conversations)'\n);\n\nconst person = z\n .looseObject({\n id: z.string(),\n name: z.string().nullable().optional(),\n email: z.string().nullable().optional(),\n })\n .nullable();\n\nconst conversationSummary = z.looseObject({\n id: z.string(),\n subject: z.string().nullable().optional(),\n status: z.string(),\n priority: z.string().optional(),\n source: z.string().nullable().optional(),\n tags: z.array(z.string()).optional(),\n customer: person.optional(),\n assignee: person.optional(),\n triage: z.record(z.string(), z.unknown()).nullable().optional(),\n needsReply: z.boolean().optional(),\n lastActivityAt: z.string().nullable().optional(),\n});\n\nconst page = {\n total: z.number(),\n limit: z.number(),\n offset: z.number(),\n hasMore: z.boolean(),\n};\n\nconst listOutput = z.object({\n conversations: z.array(conversationSummary),\n ...page,\n});\n\nconst changeOutput = z.object({\n conversation: z.looseObject({ id: z.string(), status: z.string() }),\n changes: z.array(z.string()),\n});\n\nconst slackOutcome = z\n .string()\n .describe(\n 'Slack mirror: queued, posted, no_thread (not in Slack), not_connected or failed'\n );\n\nconst tags = z.array(z.string().trim().min(1).max(50)).max(20);\n\nconst paging = {\n limit: z\n .number()\n .int()\n .min(1)\n .max(100)\n .default(20)\n .describe('How many to return (1-100, default 20)'),\n offset: z.number().int().min(0).default(0).describe('Skip this many'),\n};\n\n/** One value or a list of them (sent as a comma list). */\nfunction oneOrMany<T extends readonly [string, ...string[]]>(values: T) {\n return z.union([z.enum(values), z.array(z.enum(values)).max(10)]).optional();\n}\n\nconst asList = (v: string | string[] | undefined) =>\n v === undefined ? undefined : Array.isArray(v) ? v.join(',') : v;\n\nconst listFilters = {\n status: oneOrMany(CONVERSATION_STATUSES).describe(\n 'Only these statuses: \"open\" or a list like [\"open\", \"pending\"]'\n ),\n priority: oneOrMany(CONVERSATION_PRIORITIES).describe(\n 'Only these priorities: \"urgent\" or a list'\n ),\n assignee: z\n .string()\n .max(255)\n .optional()\n .describe('A teammate (user ID or email), \"unassigned\" or \"assigned\"'),\n projectId: id('Project').optional(),\n updatedSince: z.iso\n .datetime({ offset: true })\n .optional()\n .describe('Updated or with a new message since (ISO 8601)'),\n tag: z.string().max(50).optional().describe('Carrying this tag'),\n source: z\n .string()\n .max(32)\n .optional()\n .describe('Entry point, e.g. live_chat, contact_form, api, email'),\n intent: z\n .string()\n .max(64)\n .optional()\n .describe('AI triage intent (triaged conversations only)'),\n urgency: z\n .string()\n .max(64)\n .optional()\n .describe('AI triage urgency (triaged conversations only)'),\n sort: z\n .enum(CONVERSATION_SORTS)\n .optional()\n .describe(\n 'recent (last activity, default), oldest, newest (created) or priority'\n ),\n};\n\ntype ListArgs = {\n status?: string | string[];\n priority?: string | string[];\n assignee?: string;\n projectId?: string;\n updatedSince?: string;\n tag?: string;\n source?: string;\n intent?: string;\n urgency?: string;\n sort?: string;\n limit: number;\n offset: number;\n q?: string;\n};\n\nasync function list(api: InboxRequester, a: ListArgs) {\n const r = await api.request<Json>('GET', '/v1/conversations', {\n query: {\n status: asList(a.status),\n priority: asList(a.priority),\n assignee: a.assignee,\n projectId: a.projectId,\n updatedSince: a.updatedSince,\n tag: a.tag,\n source: a.source,\n intent: a.intent,\n urgency: a.urgency,\n sort: a.sort,\n q: a.q,\n limit: a.limit,\n offset: a.offset,\n },\n });\n return {\n conversations:\n (r.conversations as z.output<typeof conversationSummary>[]) ?? [],\n total: Number(r.total ?? 0),\n limit: Number(r.limit ?? a.limit),\n offset: Number(r.offset ?? a.offset),\n hasMore: Boolean(r.hasMore),\n };\n}\n\nconst path = (cid: string, rest = '') =>\n `/v1/conversations/${encodeURIComponent(cid)}${rest}`;\n\nasync function patch(api: InboxRequester, cid: string, body: Json) {\n const r = await api.request<{ conversation: Json; changes?: string[] }>(\n 'PATCH',\n path(cid),\n { body }\n );\n return {\n conversation: r.conversation as { id: string; status: string },\n changes: r.changes ?? [],\n };\n}\n\nconst READ: ToolAnnotations = {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n};\nconst CHANGE: ToolAnnotations = {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: true,\n};\n\n// ----- routing rules -----\n\nexport const ROUTING_FIELDS = [\n 'source',\n 'project',\n 'widget',\n 'connection',\n 'page_url',\n 'page_domain',\n 'customer_email',\n 'customer_email_domain',\n 'message',\n 'subject',\n 'tags',\n 'priority',\n 'language',\n] as const;\nexport const ROUTING_OPERATORS = [\n 'equals',\n 'not_equals',\n 'contains',\n 'not_contains',\n 'starts_with',\n 'ends_with',\n 'matches',\n] as const;\n\nconst routingConditions = z\n .object({\n match: z\n .enum(['all', 'any'])\n .describe('all = every condition holds, any = one is enough'),\n conditions: z\n .array(\n z.object({\n field: z.enum(ROUTING_FIELDS),\n operator: z.enum(ROUTING_OPERATORS),\n value: z\n .union([z.string(), z.array(z.string())])\n .describe(\n 'A value, or a list (positive operators: any matches; negative: none does). Case-insensitive; matches uses * and ? wildcards.'\n ),\n })\n )\n .max(50)\n .describe('Empty = matches every new conversation (catch-all)'),\n })\n .describe(\n 'Which new conversations the rule catches, tested on the first message, e.g. { \"match\": \"any\", \"conditions\": [{ \"field\": \"message\", \"operator\": \"contains\", \"value\": [\"refund\", \"invoice\"] }] }'\n );\n\nconst ruleFields = {\n name: z.string().trim().min(1).max(255).describe('Rule name'),\n targetChannelId: z\n .string()\n .regex(/^[A-Z0-9]{2,30}$/, 'a Slack channel ID like C0123ABCD')\n .describe('Slack channel ID to post matching conversations to'),\n conditions: routingConditions,\n projectId: id('Project (default: the oldest project)').optional(),\n widgetId: id('Widget').nullable().optional(),\n integrationId: id('Integration (default: the Slack workspace)').optional(),\n assignToUserId: id('Teammate to assign matching conversations to')\n .nullable()\n .optional(),\n isActive: z.boolean().optional().describe('Default true'),\n priority: z\n .number()\n .int()\n .min(-1_000_000)\n .max(1_000_000)\n .optional()\n .describe('Higher runs first (default: after every rule)'),\n};\n\nconst rule = z.looseObject({\n id: z.string(),\n name: z.string(),\n priority: z.number(),\n is_active: z.boolean(),\n target_channel_id: z.string(),\n});\n\n// ----- the tools -----\n\nexport const INBOX_TOOLS: readonly InboxTool[] = [\n defineTool({\n name: 'list_conversations',\n title: 'List conversations',\n description:\n '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.',\n scope: 'inbox:read',\n endpoint: 'GET /v1/conversations',\n inputSchema: z.object({ ...listFilters, ...paging }),\n outputSchema: listOutput,\n annotations: READ,\n handler: (api, a) => list(api, a),\n }),\n\n defineTool({\n name: 'search_conversations',\n title: 'Search conversations',\n description:\n '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.',\n scope: 'inbox:read',\n endpoint: 'GET /v1/conversations?q=',\n inputSchema: z.object({\n query: z.string().trim().min(1).max(200).describe('Text to look for'),\n ...listFilters,\n ...paging,\n }),\n outputSchema: listOutput,\n annotations: READ,\n handler: (api, { query, ...a }) => list(api, { ...a, q: query }),\n }),\n\n defineTool({\n name: 'get_conversation',\n title: 'Get conversation',\n description:\n '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.',\n scope: 'inbox:read',\n endpoint: 'GET /v1/conversations/:id',\n inputSchema: z.object({ conversationId }),\n outputSchema: z.object({\n conversation: z.looseObject({\n id: z.string(),\n status: z.string(),\n messages: z.array(loose),\n }),\n }),\n annotations: READ,\n handler: async (api, { conversationId: cid }) => {\n const r = await api.request<{ conversation: Json }>('GET', path(cid));\n return { conversation: r.conversation as never };\n },\n }),\n\n defineTool({\n name: 'reply_to_conversation',\n title: 'Reply to conversation',\n description:\n '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.',\n scope: 'inbox:write',\n endpoint: 'POST /v1/conversations/:id/reply',\n inputSchema: z.object({\n conversationId,\n content: z\n .string()\n .trim()\n .min(1)\n .max(10_000)\n .describe('Reply text, as the customer will read it'),\n }),\n outputSchema: z.object({\n message: z.looseObject({ id: z.string() }),\n conversationStatus: z.string(),\n slack: slackOutcome,\n }),\n annotations: {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: true,\n },\n handler: async (api, { conversationId: cid, content }) => {\n const r = await api.request<Json>('POST', path(cid, '/reply'), {\n body: { content },\n });\n return {\n message: r.message as { id: string },\n conversationStatus: String(r.conversationStatus ?? ''),\n slack: String(r.slack ?? ''),\n };\n },\n }),\n\n defineTool({\n name: 'add_internal_note',\n title: 'Add internal note',\n description:\n '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.',\n scope: 'inbox:write',\n endpoint: 'POST /v1/conversations/:id/notes',\n inputSchema: z.object({\n conversationId,\n content: z.string().trim().min(1).max(10_000).describe('Note text'),\n }),\n outputSchema: z.object({\n note: z.looseObject({ id: z.string() }),\n slack: slackOutcome,\n }),\n annotations: {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: true,\n },\n handler: async (api, { conversationId: cid, content }) => {\n const r = await api.request<Json>('POST', path(cid, '/notes'), {\n body: { content },\n });\n return { note: r.note as { id: string }, slack: String(r.slack ?? '') };\n },\n }),\n\n defineTool({\n name: 'assign_conversation',\n title: 'Assign conversation',\n description:\n '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.',\n scope: 'inbox:write',\n endpoint: 'PATCH /v1/conversations/:id',\n inputSchema: z.object({\n conversationId,\n assignee: z\n .string()\n .min(1)\n .max(255)\n .nullable()\n .describe('User ID or email of the teammate, or null to unassign'),\n }),\n outputSchema: changeOutput,\n annotations: CHANGE,\n handler: (api, { conversationId: cid, assignee }) =>\n patch(\n api,\n cid,\n assignee === null\n ? { assigneeId: null }\n : assignee.includes('@')\n ? { assigneeEmail: assignee }\n : { assigneeId: assignee }\n ),\n }),\n\n defineTool({\n name: 'tag_conversation',\n title: 'Tag conversation',\n description:\n 'Add or remove tags on a conversation, or replace them all with `set`. Tags are lowercased; at most 20. Needs the inbox:write scope.',\n scope: 'inbox:write',\n endpoint: 'PATCH /v1/conversations/:id',\n inputSchema: z.object({\n conversationId,\n add: tags.optional().describe('Tags to add'),\n remove: tags.optional().describe('Tags to remove'),\n set: tags\n .optional()\n .describe('Replace every tag with these ([] clears them)'),\n }),\n outputSchema: changeOutput,\n annotations: CHANGE,\n handler: (api, { conversationId: cid, add, remove, set }) => {\n if (!add?.length && !remove?.length && !set) {\n throw new ToolError('Pass tags to add, remove, or set.');\n }\n return patch(api, cid, {\n ...(set ? { tags: set } : {}),\n ...(add?.length ? { addTags: add } : {}),\n ...(remove?.length ? { removeTags: remove } : {}),\n });\n },\n }),\n\n defineTool({\n name: 'close_conversation',\n title: 'Close conversation',\n description:\n '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.',\n scope: 'inbox:write',\n endpoint: 'PATCH /v1/conversations/:id',\n inputSchema: z.object({\n conversationId,\n status: z\n .enum(['closed', 'resolved'])\n .default('closed')\n .describe('closed (default) or resolved'),\n }),\n outputSchema: changeOutput,\n annotations: CHANGE,\n handler: (api, { conversationId: cid, status }) =>\n patch(api, cid, { status }),\n }),\n\n defineTool({\n name: 'reopen_conversation',\n title: 'Reopen conversation',\n description:\n 'Reopen a closed or resolved conversation (status open). Needs the inbox:write scope.',\n scope: 'inbox:write',\n endpoint: 'PATCH /v1/conversations/:id',\n inputSchema: z.object({ conversationId }),\n outputSchema: changeOutput,\n annotations: CHANGE,\n handler: (api, { conversationId: cid }) =>\n patch(api, cid, { status: 'open' }),\n }),\n\n defineTool({\n name: 'get_analytics_summary',\n title: 'Get analytics summary',\n description:\n '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.',\n scope: 'analytics:read',\n endpoint: 'GET /v1/analytics/summary',\n inputSchema: z.object({\n days: z\n .number()\n .int()\n .min(1)\n .max(366)\n .optional()\n .describe('Period length in days, ending today (default 30)'),\n from: z.iso.date().optional().describe('First day, YYYY-MM-DD'),\n to: z.iso.date().optional().describe('Last day, YYYY-MM-DD'),\n tz: z\n .string()\n .max(64)\n .optional()\n .describe('IANA time zone for day boundaries (default UTC)'),\n projectId: id('Project').optional(),\n }),\n outputSchema: z.looseObject({ range: loose, kpis: loose, inbox: loose }),\n annotations: READ,\n handler: async (api, args) =>\n api.request<{ range: Json; kpis: Json; inbox: Json }>(\n 'GET',\n '/v1/analytics/summary',\n { query: args }\n ),\n }),\n\n defineTool({\n name: 'list_routing_rules',\n title: 'List routing rules',\n description:\n '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.',\n scope: 'routing:read',\n endpoint: 'GET /v1/routing-rules',\n inputSchema: z.object({}),\n outputSchema: z.object({ rules: z.array(rule) }),\n annotations: READ,\n handler: async api => {\n const r = await api.request<{ routing_rules: Json[] }>(\n 'GET',\n '/v1/routing-rules'\n );\n return { rules: (r.routing_rules ?? []) as never };\n },\n }),\n\n defineTool({\n name: 'create_routing_rule',\n title: 'Create routing rule',\n description:\n '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.',\n scope: 'routing:write',\n endpoint: 'POST /v1/routing-rules',\n inputSchema: z.object(ruleFields),\n outputSchema: z.object({ rule }),\n annotations: {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: false,\n },\n handler: async (api, body) => {\n const r = await api.request<{ routing_rule: Json }>(\n 'POST',\n '/v1/routing-rules',\n { body }\n );\n return { rule: r.routing_rule as never };\n },\n }),\n\n defineTool({\n name: 'update_routing_rule',\n title: 'Update routing rule',\n description:\n '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.',\n scope: 'routing:write',\n endpoint: 'PATCH /v1/routing-rules/:id',\n inputSchema: z.object({\n ruleId: id('Routing rule'),\n name: ruleFields.name.optional(),\n targetChannelId: ruleFields.targetChannelId.optional(),\n conditions: routingConditions.optional(),\n projectId: ruleFields.projectId,\n widgetId: ruleFields.widgetId,\n integrationId: ruleFields.integrationId,\n assignToUserId: ruleFields.assignToUserId,\n isActive: ruleFields.isActive,\n priority: ruleFields.priority,\n }),\n outputSchema: z.object({ rule }),\n annotations: {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n handler: async (api, { ruleId, ...body }) => {\n if (Object.values(body).every(v => v === undefined)) {\n throw new ToolError('Pass at least one field to change.');\n }\n const r = await api.request<{ routing_rule: Json }>(\n 'PATCH',\n `/v1/routing-rules/${encodeURIComponent(ruleId)}`,\n { body }\n );\n return { rule: r.routing_rule as never };\n },\n }),\n\n defineTool({\n name: 'delete_routing_rule',\n title: 'Delete routing rule',\n description:\n '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.',\n scope: 'routing:write',\n endpoint: 'DELETE /v1/routing-rules/:id',\n inputSchema: z.object({ ruleId: id('Routing rule') }),\n outputSchema: z.object({ deleted: z.boolean(), ruleId: z.string() }),\n annotations: {\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: true,\n openWorldHint: false,\n },\n handler: async (api, { ruleId }) => {\n await api.request(\n 'DELETE',\n `/v1/routing-rules/${encodeURIComponent(ruleId)}`\n );\n return { deleted: true, ruleId };\n },\n }),\n];\n\nexport const INBOX_TOOL_NAMES = INBOX_TOOLS.map(t => t.name);\n\nexport function getInboxTool(name: string): InboxTool | undefined {\n return INBOX_TOOLS.find(t => t.name === name);\n}\n\n/**\n * Validate `args` against the tool's input schema and run it. Throws\n * `ToolError` for an unknown tool or invalid arguments, and for API\n * failures (`toToolError` in `api.ts` words them for the model).\n */\nexport async function runInboxTool(\n api: InboxRequester,\n name: string,\n args: unknown\n): Promise<Json> {\n const tool = getInboxTool(name);\n if (!tool) throw new ToolError(`Unknown inbox tool \"${name}\"`);\n const parsed = tool.inputSchema.safeParse(args ?? {});\n if (!parsed.success) {\n throw new ToolError(\n `Invalid arguments for ${name}: ${parsed.error.issues\n .map(i => `${i.path.join('.') || 'input'}: ${i.message}`)\n .join('; ')}`\n );\n }\n return (await tool.handler(api, parsed.data)) as Json;\n}\n\n/**\n * The tools as JSON Schema function definitions, for LLM APIs that take\n * `{ name, description, parameters }` (OpenAI / OpenRouter style).\n */\nexport function inboxToolsAsJsonSchema(\n filter: (tool: InboxTool) => boolean = () => true\n): Array<{ name: string; description: string; parameters: Json }> {\n return INBOX_TOOLS.filter(filter).map(t => ({\n name: t.name,\n description: t.description,\n parameters: z.toJSONSchema(t.inputSchema, { io: 'input' }) as Json,\n }));\n}\n","import { createServer, type IncomingMessage, type Server } from 'node:http';\nimport {\n createMcpHandler,\n hostHeaderValidationResponse,\n localhostAllowedHostnames,\n localhostAllowedOrigins,\n originValidationResponse,\n type McpServer,\n} from '@modelcontextprotocol/server';\n\nexport interface HttpServerOptions {\n /** Interface to bind (default 127.0.0.1). */\n host?: string;\n /** Port (default 3333). */\n port?: number;\n /** Endpoint path (default /mcp). */\n path?: string;\n}\n\nconst LOCAL_HOSTS = new Set(['127.0.0.1', 'localhost', '::1']);\n\nasync function toRequest(\n req: IncomingMessage,\n origin: string\n): Promise<Request> {\n const headers = new Headers();\n for (const [k, v] of Object.entries(req.headers)) {\n if (Array.isArray(v)) v.forEach(x => headers.append(k, x));\n else if (v !== undefined) headers.set(k, v);\n }\n let body: Uint8Array<ArrayBuffer> | undefined;\n if (req.method !== 'GET' && req.method !== 'HEAD') {\n const chunks: Buffer[] = [];\n for await (const chunk of req) chunks.push(chunk as Buffer);\n body = new Uint8Array(Buffer.concat(chunks));\n }\n const controller = new AbortController();\n req.on('close', () => {\n if (!req.complete) controller.abort();\n });\n return new Request(new URL(req.url ?? '/', origin), {\n method: req.method,\n headers,\n body,\n signal: controller.signal,\n });\n}\n\n/**\n * Streamable HTTP transport on `node:http`. Stateless: every request is\n * served by a fresh server from `factory`. Bound to localhost by default,\n * with Host and Origin checks against DNS rebinding.\n */\nexport async function startHttpServer(\n factory: () => McpServer,\n options: HttpServerOptions = {}\n): Promise<{ url: string; server: Server; close: () => Promise<void> }> {\n const host = options.host ?? '127.0.0.1';\n const port = options.port ?? 3333;\n const path = options.path ?? '/mcp';\n const local = LOCAL_HOSTS.has(host);\n const handler = createMcpHandler(() => factory(), {\n onerror: err => console.error('[channlize-mcp]', err.message),\n });\n\n const server = createServer(async (req, res) => {\n try {\n const request = await toRequest(\n req,\n `http://${req.headers.host ?? `${host}:${port}`}`\n );\n const url = new URL(request.url);\n if (url.pathname !== path) {\n res\n .writeHead(404, { 'Content-Type': 'text/plain' })\n .end(`Not found: use ${path}`);\n return;\n }\n const rejected = local\n ? (hostHeaderValidationResponse(request, localhostAllowedHostnames()) ??\n originValidationResponse(request, localhostAllowedOrigins()))\n : undefined;\n const response = rejected ?? (await handler.fetch(request));\n res.writeHead(response.status, Object.fromEntries(response.headers));\n if (response.body) {\n for await (const chunk of response.body as unknown as AsyncIterable<Uint8Array>) {\n res.write(chunk);\n }\n }\n res.end();\n } catch (err) {\n console.error('[channlize-mcp]', (err as Error).message);\n if (!res.headersSent)\n res.writeHead(500, { 'Content-Type': 'text/plain' });\n res.end('Internal server error');\n }\n });\n\n await new Promise<void>((resolve, reject) => {\n server.once('error', reject);\n server.listen(port, host, () => resolve());\n });\n const address = server.address();\n const actualPort =\n typeof address === 'object' && address ? address.port : port;\n const shownHost = host.includes(':') ? `[${host}]` : host;\n return {\n url: `http://${shownHost}:${actualPort}${path}`,\n server,\n close: () => new Promise<void>(r => server.close(() => r())),\n };\n}\n"],"mappings":";AAQA,SAAS,iBAAiB;AAC1B,SAAS,4BAA4B;;;ACTrC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAUA,IAAM,YAAN,cAAwB,MAAM;AAAA,EACnC,YACEA,UACO,YACA,MAEA,SACP;AACA,UAAMA,QAAO;AALN;AACA;AAEA;AAGP,SAAK,OAAO;AAAA,EACd;AAAA,EAPS;AAAA,EACA;AAAA,EAEA;AAKX;AAKA,SAAS,SAAS,YAA4B;AAC5C,QAAM,OAAO,4BAA4B,KAAK,UAAU,IAAI,CAAC,KAAK;AAClE,UAAQ,MAAM;AAAA,IACZ,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT;AACE,aAAO,eAAe,KAAK,UAAU,IAAI,UAAU;AAAA,EACvD;AACF;AAGA,SAAS,UAAU,SAAqC;AACtD,SAAO,UAAU,gBAAgB,OAAO,kBAAkB;AAC5D;AAGA,SAAS,UACP,MACA,OAAgC,CAAC,GACb;AACpB,QAAM,UAAU,OAAO,KAAK,YAAY,WAAW,KAAK,UAAU;AAClE,UAAQ,MAAM;AAAA,IACZ,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AAAA,IACL,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT,KAAK,uBAAuB;AAC1B,YAAM,M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AAQ,aAAa,SAAS,KAAK,WAAW,QAAQ;AAAA,IACnE,EAAE,cAAc,aAAa;AAAA,EAC/B;AACA,MAAI,IAAI,cAAc;AACpB,uBAAmB,QAAQ,GAAG;AAC9B,uBAAmB,QAAQ,GAAG;AAC9B,wBAAoB,QAAQ,GAAG;AAC/B,0BAAsB,MAAM;AAAA,EAC9B;AACA,MAAI,IAAI,aAAc,qBAAoB,QAAQ,GAAG;AACrD,oBAAkB,QAAQ,GAAG;AAC7B,uBAAqB,MAAM;AAC3B,SAAO;AACT;AAOO,IAAM,qBAAN,MAAyB;AAAA,EACtB;AAAA,EACS;AAAA,EACA;AAAA,EAEjB,YAAY,UAA4B,CAAC,GAAG;AAC1C,SAAK,SAAS,cAAc,QAAQ,UAAU,CAAC,CAAC;AAChD,SAAK,OAAO,EAAE,MAAM,QAAQ,MAAM,SAAS,QAAQ,QAAQ;AAC3D,SAAK,SAAS,YAAY,KAAK,QAAQ,KAAK,IAAI;AAAA,EAClD;AAAA;AAAA,EAGA,YAAuB;AACrB,WAAO,KAAK;AAAA,EACd;AAAA;AAAA,EAGA,MAAM,WAA0B;AAC9B,UAAM,KAAK,OAAO,QAAQ,IAAI,qBAAqB,CAAC;AAAA,EACtD;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAM,QAAQ,UAA6B,CAAC,GAAG;AAC7C,WAAO,gBAAgB,MAAM,YAAY,KAAK,QAAQ,KAAK,IAAI,GAAG,OAAO;AAAA,EAC3E;AAAA,EAEA,MAAM,QAAuB;AAC3B,UAAM,KAAK,OAAO,MAAM;AAAA,EAC1B;AACF;AAGO,SAAS,gBACd,SACoB;AACpB,SAAO,IAAI,mBAAmB,OAAO;AACvC;AAEA,IAAO,gBAAQ;","names":["message","path","url","data","message","agentId","conversationId","z","z","range","top","id","z","defineTool","READ","data","record","loose","page","READ","path","url","ChannlizeError"]}
|