@channlize/mcp 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.js CHANGED
@@ -1,1850 +1,1348 @@
1
1
  #!/usr/bin/env node
2
- #!/usr/bin/env node
3
2
  "use strict";
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
18
+ // If the importer is in node compatibility mode or this is not an ESM
19
+ // file that has been converted to a CommonJS file using a Babel-
20
+ // compatible transform (i.e. "__esModule" has not been set), then set
21
+ // "default" to the CommonJS "module.exports" for node compatibility.
22
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
23
+ mod
24
+ ));
25
+
26
+ // src/server.ts
27
+ var import_node_util = require("util");
4
28
 
5
29
  // src/index.ts
6
- var import_server = require("@modelcontextprotocol/sdk/server/index.js");
7
- var import_stdio = require("@modelcontextprotocol/sdk/server/stdio.js");
8
- var import_types = require("@modelcontextprotocol/sdk/types.js");
30
+ var import_server2 = require("@modelcontextprotocol/server");
31
+ var import_stdio = require("@modelcontextprotocol/server/stdio");
9
32
 
10
- // src/resources/index.ts
11
- var CONTACT_FORM_SCHEMA = `{
12
- "name": "ContactFormData",
13
- "description": "Data structure for submitting a contact form inquiry",
14
- "type": "object",
15
- "properties": {
16
- "name": {
17
- "type": "string",
18
- "description": "Contact's full name",
19
- "required": true
20
- },
21
- "email": {
22
- "type": "string",
23
- "format": "email",
24
- "description": "Contact's email address",
25
- "required": true
26
- },
27
- "subject": {
28
- "type": "string",
29
- "description": "Subject line for the inquiry"
30
- },
31
- "message": {
32
- "type": "string",
33
- "description": "Message content",
34
- "required": true
35
- },
36
- "customFields": {
37
- "type": "object",
38
- "description": "Additional custom fields as key-value pairs",
39
- "additionalProperties": true
40
- },
41
- "pageUrl": {
42
- "type": "string",
43
- "description": "URL of the page where form was submitted"
44
- },
45
- "userAgent": {
46
- "type": "string",
47
- "description": "User agent string of the submitter"
33
+ // src/api.ts
34
+ var import_core = require("@channlize/core");
35
+ var ToolError = class extends Error {
36
+ constructor(message, statusCode, code) {
37
+ super(message);
38
+ this.statusCode = statusCode;
39
+ this.code = code;
40
+ this.name = "ToolError";
41
+ }
42
+ statusCode;
43
+ code;
44
+ };
45
+ function hintFor(status, apiMessage) {
46
+ switch (status) {
47
+ case 401:
48
+ return `${apiMessage}. The server API key is invalid, revoked or expired: create a new one under SDK & Integration \u2192 API keys and update CHANNLIZE_SERVER_API_KEY.`;
49
+ case 403:
50
+ return /permission/i.test(apiMessage) ? `${apiMessage}. This needs a server API key with the ${/write|notify/.test(apiMessage) ? "write" : "read"} scope: create one under SDK & Integration \u2192 API keys.` : apiMessage;
51
+ case 404:
52
+ return `${apiMessage}. Check the ID (and CHANNLIZE_PROJECT_ID): it must belong to the key's organization.`;
53
+ case 429:
54
+ return `${apiMessage}. Rate limited: wait a little before retrying.`;
55
+ default:
56
+ return apiMessage;
57
+ }
58
+ }
59
+ function toToolError(err) {
60
+ if (err instanceof ToolError) return err;
61
+ if (err instanceof import_core.ChannlizeError) {
62
+ return new ToolError(
63
+ err.statusCode ? hintFor(err.statusCode, err.message) : err.message,
64
+ err.statusCode,
65
+ err.code
66
+ );
67
+ }
68
+ return new ToolError(err instanceof Error ? err.message : String(err));
69
+ }
70
+ var ChannlizeApi = class {
71
+ constructor(config) {
72
+ this.config = config;
73
+ }
74
+ config;
75
+ projectIdPromise;
76
+ widgetClient;
77
+ get hasServerKey() {
78
+ return !!this.config.serverApiKey;
79
+ }
80
+ get hasWidgetKey() {
81
+ return !!this.config.widgetKey;
82
+ }
83
+ requireServerKey() {
84
+ if (!this.config.serverApiKey) {
85
+ throw new ToolError(
86
+ "This tool needs a server API key (ch_live_\u2026): set CHANNLIZE_SERVER_API_KEY or pass --server-api-key."
87
+ );
48
88
  }
89
+ return this.config.serverApiKey;
49
90
  }
50
- }`;
51
- var CHAT_SESSION_SCHEMA = `{
52
- "name": "ChatSession",
53
- "description": "Real-time chat session structure",
54
- "type": "object",
55
- "properties": {
56
- "id": {
57
- "type": "string",
58
- "description": "Unique session identifier"
59
- },
60
- "status": {
61
- "type": "string",
62
- "enum": ["active", "closed", "waiting"],
63
- "description": "Current session status"
64
- },
65
- "messages": {
66
- "type": "array",
67
- "items": {
68
- "$ref": "#/definitions/ChatMessage"
69
- },
70
- "description": "Array of messages in this session"
71
- },
72
- "metadata": {
73
- "type": "object",
74
- "description": "Custom metadata for the session"
75
- },
76
- "createdAt": {
77
- "type": "string",
78
- "format": "date-time",
79
- "description": "Session creation timestamp"
80
- },
81
- "updatedAt": {
82
- "type": "string",
83
- "format": "date-time",
84
- "description": "Last update timestamp"
91
+ async request(method, path, options = {}) {
92
+ const key = this.requireServerKey();
93
+ const url2 = new URL(`${this.config.baseUrl}${path}`);
94
+ for (const [k, v] of Object.entries(options.query ?? {})) {
95
+ if (v !== void 0 && v !== "") url2.searchParams.set(k, String(v));
85
96
  }
86
- },
87
- "definitions": {
88
- "ChatMessage": {
89
- "type": "object",
90
- "properties": {
91
- "id": { "type": "string" },
92
- "content": { "type": "string" },
93
- "timestamp": { "type": "string", "format": "date-time" },
94
- "author": { "type": "string", "enum": ["user", "agent"] },
95
- "authorData": {
96
- "type": "object",
97
- "properties": {
98
- "name": { "type": "string" },
99
- "email": { "type": "string" },
100
- "avatarUrl": { "type": "string" }
101
- }
97
+ let res;
98
+ try {
99
+ res = await fetch(url2, {
100
+ method,
101
+ headers: {
102
+ Authorization: `Bearer ${key}`,
103
+ Accept: "application/json",
104
+ ...options.body !== void 0 ? { "Content-Type": "application/json" } : {},
105
+ ...options.headers
102
106
  },
103
- "attachments": {
104
- "type": "array",
105
- "items": { "$ref": "#/definitions/FileAttachment" }
106
- }
107
+ body: options.body !== void 0 ? JSON.stringify(options.body) : void 0,
108
+ signal: AbortSignal.timeout(this.config.timeout)
109
+ });
110
+ } catch (err) {
111
+ const e = err;
112
+ if (e.name === "TimeoutError" || e.name === "AbortError") {
113
+ throw new ToolError(
114
+ `Channlize API timed out after ${this.config.timeout} ms (${method} ${url2.pathname}). Retry, or raise CHANNLIZE_TIMEOUT.`,
115
+ 408,
116
+ "TIMEOUT"
117
+ );
107
118
  }
108
- },
109
- "FileAttachment": {
110
- "type": "object",
111
- "properties": {
112
- "id": { "type": "string" },
113
- "name": { "type": "string" },
114
- "size": { "type": "number" },
115
- "type": { "type": "string" },
116
- "url": { "type": "string" }
119
+ throw new ToolError(
120
+ `Could not reach the Channlize API at ${this.config.baseUrl}: ${e.message}`
121
+ );
122
+ }
123
+ const text = await res.text();
124
+ let data = void 0;
125
+ if (text) {
126
+ try {
127
+ data = JSON.parse(text);
128
+ } catch {
129
+ data = void 0;
117
130
  }
118
131
  }
132
+ if (!res.ok) {
133
+ const body = data ?? {};
134
+ const raw = Array.isArray(body.message) ? body.message.join(", ") : body.message;
135
+ const apiMessage = raw || (typeof body.error === "string" && /\s/.test(body.error) ? body.error : "") || `HTTP ${res.status} ${res.statusText}`.trim();
136
+ throw new ToolError(
137
+ hintFor(res.status, apiMessage.replace(/\.$/, "")),
138
+ res.status,
139
+ body.code ?? (typeof body.error === "string" ? body.error : void 0)
140
+ );
141
+ }
142
+ if (data === void 0) {
143
+ throw new ToolError(
144
+ `Unexpected non-JSON response from ${method} ${url2.pathname}`
145
+ );
146
+ }
147
+ return data;
119
148
  }
120
- }`;
121
- var API_REFERENCE = `# Channlize API Reference
122
-
123
- ## Overview
124
- Channlize is a developer-first support platform that routes customer conversations directly into Slack.
125
-
126
- Base URL: \`http://api.channlize.com\` (default) or your configured API endpoint
127
-
128
- ## Authentication
129
- All API requests require a Widget Key (API key) in the request body or as a header.
130
-
131
- ## Endpoints
132
-
133
- ### Contact Forms
134
-
135
- **POST /public/contact**
136
- Submit a contact form inquiry.
137
-
138
- Request Body:
139
- \`\`\`json
140
- {
141
- "widgetKey": "your-widget-key",
142
- "name": "John Doe",
143
- "email": "john@example.com",
144
- "subject": "Support Request",
145
- "message": "I need help with...",
146
- "pageUrl": "https://example.com/contact",
147
- "userAgent": "Mozilla/5.0..."
148
- }
149
- \`\`\`
150
-
151
- Response:
152
- \`\`\`json
153
- {
154
- "data": {
155
- "id": "contact_123",
156
- "status": "received",
157
- "slackThreadUrl": "https://slack.com/..."
149
+ /**
150
+ * `CHANNLIZE_PROJECT_ID`, or the first project of the key's organization
151
+ * (`GET /projects/me`), looked up once.
152
+ */
153
+ projectId() {
154
+ if (this.config.projectId) return Promise.resolve(this.config.projectId);
155
+ this.projectIdPromise ??= this.request(
156
+ "GET",
157
+ "/projects/me"
158
+ ).then((r) => {
159
+ if (!r.project?.id) {
160
+ throw new ToolError(
161
+ "Could not find a project for this key: set CHANNLIZE_PROJECT_ID."
162
+ );
163
+ }
164
+ return r.project.id;
165
+ }).catch((err) => {
166
+ this.projectIdPromise = void 0;
167
+ throw err;
168
+ });
169
+ return this.projectIdPromise;
158
170
  }
159
- }
160
- \`\`\`
161
-
162
- ### Chat Sessions
163
-
164
- **POST /v1/chat/sessions**
165
- Create a new chat session.
171
+ /** `@channlize/core` client bound to the widget key (visitor tools). */
172
+ widget() {
173
+ if (!this.config.widgetKey) {
174
+ throw new ToolError(
175
+ "This tool needs the public widget key (wk_\u2026): set CHANNLIZE_WIDGET_KEY or pass --widget-key."
176
+ );
177
+ }
178
+ this.widgetClient ??= new import_core.ChannlizeClient({
179
+ apiKey: this.config.widgetKey,
180
+ projectId: this.config.projectId ?? "",
181
+ baseUrl: this.config.baseUrl,
182
+ timeout: this.config.timeout
183
+ });
184
+ return this.widgetClient;
185
+ }
186
+ /** `@channlize/core` client for `notify` (server key + project). */
187
+ async notifier() {
188
+ const serverApiKey = this.requireServerKey();
189
+ return new import_core.ChannlizeClient({
190
+ // core requires a widget key; notify only uses serverApiKey.
191
+ apiKey: this.config.widgetKey ?? "unused",
192
+ serverApiKey,
193
+ projectId: await this.projectId(),
194
+ baseUrl: this.config.baseUrl,
195
+ timeout: this.config.timeout
196
+ });
197
+ }
198
+ };
166
199
 
167
- Request Body:
168
- \`\`\`json
169
- {
170
- "metadata": {
171
- "pageUrl": "https://example.com",
172
- "userAgent": "Mozilla/5.0...",
173
- "customField": "value"
200
+ // src/config.ts
201
+ var DEFAULT_BASE_URL = "https://api.channlize.com";
202
+ var DEFAULT_TIMEOUT = 1e4;
203
+ var ConfigError = class extends Error {
204
+ constructor(message) {
205
+ super(message);
206
+ this.name = "ConfigError";
174
207
  }
208
+ };
209
+ function keyKind(key) {
210
+ return key.startsWith("wk_") ? "widget" : "server";
175
211
  }
176
- \`\`\`
177
-
178
- Response:
179
- \`\`\`json
180
- {
181
- "data": {
182
- "session": {
183
- "id": "session_123",
184
- "status": "active",
185
- "messages": [],
186
- "createdAt": "2025-01-15T10:00:00Z"
187
- },
188
- "sseEndpoint": "/v1/chat/sessions/session_123/events"
212
+ function clean(value) {
213
+ const v = value?.trim();
214
+ return v ? v : void 0;
215
+ }
216
+ function resolveConfig(config) {
217
+ let serverApiKey = clean(config.serverApiKey);
218
+ let widgetKey = clean(config.widgetKey);
219
+ const apiKey = clean(config.apiKey);
220
+ if (serverApiKey && keyKind(serverApiKey) === "widget") {
221
+ throw new ConfigError(
222
+ "CHANNLIZE_SERVER_API_KEY / --server-api-key holds a widget key (wk_\u2026). Widget keys are public and only work for the visitor tools: pass it as CHANNLIZE_WIDGET_KEY / --widget-key, and create a server API key (ch_live_\u2026) under SDK & Integration \u2192 API keys in the Channlize dashboard."
223
+ );
224
+ }
225
+ if (widgetKey && keyKind(widgetKey) === "server") {
226
+ throw new ConfigError(
227
+ "CHANNLIZE_WIDGET_KEY / --widget-key holds a server API key. Pass server keys (ch_live_\u2026) as CHANNLIZE_SERVER_API_KEY / --server-api-key; widget keys start with wk_."
228
+ );
229
+ }
230
+ if (apiKey) {
231
+ if (keyKind(apiKey) === "widget") widgetKey ??= apiKey;
232
+ else serverApiKey ??= apiKey;
233
+ }
234
+ if (!serverApiKey && !widgetKey) {
235
+ throw new ConfigError(
236
+ "A Channlize key is required. Set CHANNLIZE_SERVER_API_KEY (or --server-api-key) to a server API key (ch_live_\u2026) from SDK & Integration \u2192 API keys in the Channlize dashboard. Use a read-scoped key for read-only access, or add the write scope to send events, logs and conversations."
237
+ );
238
+ }
239
+ const timeout = config.timeout ?? DEFAULT_TIMEOUT;
240
+ if (!Number.isFinite(timeout) || timeout <= 0) {
241
+ throw new ConfigError(
242
+ `Invalid timeout "${config.timeout}": use milliseconds, e.g. 10000`
243
+ );
244
+ }
245
+ const baseUrl = (clean(config.baseUrl) ?? DEFAULT_BASE_URL).replace(
246
+ /\/+$/,
247
+ ""
248
+ );
249
+ try {
250
+ new URL(baseUrl);
251
+ } catch {
252
+ throw new ConfigError(
253
+ `Invalid base URL "${config.baseUrl}": use e.g. ${DEFAULT_BASE_URL}`
254
+ );
189
255
  }
256
+ return {
257
+ serverApiKey,
258
+ widgetKey,
259
+ projectId: clean(config.projectId),
260
+ baseUrl,
261
+ timeout
262
+ };
190
263
  }
191
- \`\`\`
264
+ function configFromEnv(env = process.env) {
265
+ const timeout = clean(env.CHANNLIZE_TIMEOUT);
266
+ return {
267
+ serverApiKey: clean(env.CHANNLIZE_SERVER_API_KEY),
268
+ widgetKey: clean(env.CHANNLIZE_WIDGET_KEY),
269
+ apiKey: clean(env.CHANNLIZE_API_KEY),
270
+ projectId: clean(env.CHANNLIZE_PROJECT_ID),
271
+ baseUrl: clean(env.CHANNLIZE_BASE_URL),
272
+ timeout: timeout ? Number(timeout) : void 0
273
+ };
274
+ }
275
+
276
+ // src/prompts.ts
277
+ var z = __toESM(require("zod/v4"));
278
+
279
+ // src/docs.ts
280
+ var QUICK_START = `# Channlize quick start
192
281
 
193
- **POST /v1/chat/sessions/:sessionId/messages**
194
- Send a message in a chat session.
282
+ Channlize routes website conversations and app events to Slack.
195
283
 
196
- Request: FormData with 'content' field and optional file attachments
284
+ ## Keys
285
+ - **Widget key** (\`wk_\u2026\`): public, safe in browser code. Used by the chat widget,
286
+ contact form and browser log tracking (\`apiKey\` in the SDK config).
287
+ - **Server API key** (\`ch_live_\u2026\`): secret, server only (\`serverApiKey\`). Scopes:
288
+ \`read\` (conversations, contacts, logs, Events) and \`write\` (notify, server logs,
289
+ create conversations/contacts). Create both under SDK & Integration \u2192 API keys.
290
+ - **Project ID**: shown next to each widget key.
197
291
 
198
- **GET /v1/chat/sessions/:sessionId/messages**
199
- Get messages for a session. Query params: limit, offset
292
+ ## Install
293
+ \`\`\`bash
294
+ npm install @channlize/core # any JS runtime
295
+ npm install @channlize/react # React components and hooks
296
+ \`\`\`
200
297
 
201
- **POST /v1/chat/sessions/:sessionId/close**
202
- Close a chat session.
298
+ ## Browser
299
+ \`\`\`ts
300
+ import { ChannlizeClient } from '@channlize/core';
203
301
 
204
- ## Error Responses
302
+ const client = new ChannlizeClient({ apiKey: 'wk_\u2026', projectId: '<project-id>' });
303
+ await client.submitContactForm({ name: 'Ada', email: 'ada@example.com', message: 'Hi!' });
304
+ await client.trackEvent('checkout.started', { properties: { cartId: 'c_1' } });
305
+ \`\`\`
205
306
 
206
- Status codes:
207
- - 400: Validation error
208
- - 401: Authentication failed
209
- - 429: Rate limit exceeded
210
- - 500: Server error
307
+ ## Server
308
+ \`\`\`ts
309
+ import { createNotifier } from '@channlize/core';
211
310
 
212
- Error format:
213
- \`\`\`json
214
- {
215
- "error": "Error message",
216
- "code": "ERROR_CODE",
217
- "field": "fieldName" // for validation errors
218
- }
311
+ // Reads CHANNLIZE_SERVER_API_KEY (or CHANNLIZE_API_KEY) and CHANNLIZE_PROJECT_ID.
312
+ const notify = createNotifier();
313
+ await notify('user.subscribed', { username: 'ada', plan: 'Pro' });
219
314
  \`\`\`
220
- `;
221
- var QUICK_START = `# Channlize Quick Start
222
315
 
223
- ## Installation
316
+ Errors are \`ChannlizeError\` (\`statusCode\`, \`code\`), with subclasses
317
+ \`ValidationError\` (400), \`AuthenticationError\` (401) and \`RateLimitError\` (429).
318
+ `;
319
+ var REACT_COMPONENTS = `# @channlize/react
224
320
 
225
321
  \`\`\`bash
226
- # For React applications
227
322
  npm install @channlize/react
228
-
229
- # For non-React applications
230
- npm install @channlize/core
231
323
  \`\`\`
232
324
 
233
- ## React Setup
234
-
235
- 1. Wrap your app with ChannlizeProvider:
325
+ ## Floating chat widget (all-in-one)
326
+ \`ChannlizeChat\` includes the provider, launcher button and chat window.
236
327
 
237
328
  \`\`\`tsx
238
- import { ChannlizeProvider } from '@channlize/react';
329
+ 'use client';
330
+ import { ChannlizeChat } from '@channlize/react';
239
331
 
240
- function App() {
332
+ export function SupportWidget() {
241
333
  return (
242
- <ChannlizeProvider
334
+ <ChannlizeChat
243
335
  config={{
244
- apiKey: 'your-widget-key',
245
- projectId: 'your-project-id',
336
+ apiKey: process.env.NEXT_PUBLIC_CHANNLIZE_WIDGET_KEY!, // wk_\u2026, public
337
+ projectId: process.env.NEXT_PUBLIC_CHANNLIZE_PROJECT_ID!,
246
338
  }}
247
- >
248
- <YourApp />
249
- </ChannlizeProvider>
250
- );
251
- }
252
- \`\`\`
253
-
254
- 2. Use the Form component:
255
-
256
- \`\`\`tsx
257
- import { Form } from '@channlize/react';
258
-
259
- function ContactPage() {
260
- return (
261
- <Form
262
- onSuccess={() => console.log('Form submitted!')}
263
- submitText="Send Message"
339
+ position="bottom-right"
340
+ primaryColor="#2563eb"
341
+ theme="auto"
342
+ chatProps={{ title: 'Acme Support', greeting: 'Hi there!', welcomeMessage: 'Ask us anything.' }}
264
343
  />
265
344
  );
266
345
  }
267
346
  \`\`\`
268
347
 
269
- 3. Add live chat:
348
+ Key props: \`position\` ('bottom-right' | 'bottom-left' | 'top-right' | 'top-left'),
349
+ \`primaryColor\`, \`theme\` ('auto' | 'light' | 'dark'), \`defaultOpen\`, \`showOnMobile\`,
350
+ \`offset\`, \`zIndex\`, \`onOpen\`, \`onClose\`, and \`chatProps\` (SupportChat props).
270
351
 
352
+ ## Provider + inline components
271
353
  \`\`\`tsx
272
- import { Chat } from '@channlize/react';
354
+ import { ChannlizeProvider, SupportChat, ContactForm } from '@channlize/react';
273
355
 
274
- function SupportPage() {
275
- return (
276
- <Chat
277
- autoStart={true}
278
- title="Customer Support"
279
- placeholder="How can we help?"
280
- />
281
- );
282
- }
356
+ <ChannlizeProvider config={{ apiKey: 'wk_\u2026', projectId: '<project-id>' }}>
357
+ <SupportChat title="Need help?" greeting="Hi!" suggestions={['Pricing', 'Billing']} />
358
+ <ContactForm submitText="Send" successMessage="Thanks! We'll reply by email." />
359
+ </ChannlizeProvider>
283
360
  \`\`\`
284
361
 
285
- ## Core SDK Usage
362
+ SupportChat props include \`title\`, \`greeting\`, \`welcomeMessage\`, \`suggestions\`,
363
+ \`placeholder\`, \`allowAttachments\`, \`allowEndChat\`, \`theme\`, \`primaryColor\`,
364
+ \`locale\`, \`maxLength\`, \`labels\` and the \`useChatSession\` options
365
+ (\`autoConnect\`, \`metadata\`, \`persistSession\`, \`onMessage\`, \`onError\`).
366
+
367
+ ContactForm props: \`customFields\`, \`onSuccess\`, \`onError\`, \`className\`, \`styles\`,
368
+ \`submitText\`, \`successMessage\`.
369
+
370
+ ## Hooks (inside ChannlizeProvider)
371
+ - \`useChatSession(options)\` \u2192 \`{ session, messages, isConnecting, isConnected, error,
372
+ sendMessage, startSession, endSession, reconnect }\`
373
+ - \`useContactForm({ onSuccess, onError })\` \u2192 \`{ submit, isSubmitting, isSuccess, error, reset }\`
374
+ - \`useChannlizeAnalytics()\` \u2192 \`{ track(name, { properties, severity }) }\` (log tracking)
375
+ - \`useChannlize()\` \u2192 \`{ client, config }\`
376
+
377
+ ## Next.js App Router
378
+ Components use state and effects: render them from a \`'use client'\` file. The widget
379
+ key is public (\`NEXT_PUBLIC_\u2026\` is fine); never put the server API key in a
380
+ \`NEXT_PUBLIC_\` variable.
381
+ `;
382
+ var EVENTS = `# Events: notify Slack from code
286
383
 
287
- For non-React applications:
384
+ Each event key (e.g. \`user.subscribed\`) has a Slack channel and a message template
385
+ with \`{{field}}\` placeholders, set under Events in the dashboard. A key that isn't set
386
+ up yet is saved as a disabled draft the first time it is sent (\`status: 'skipped'\`),
387
+ so you can ship code first and configure it after. Server only: needs a server API key
388
+ with the \`write\` scope.
288
389
 
289
- \`\`\`typescript
290
- import { ChannlizeClient } from '@channlize/core';
390
+ \`\`\`ts
391
+ import { createNotifier } from '@channlize/core';
291
392
 
292
- const client = new ChannlizeClient({
293
- apiKey: 'your-widget-key',
294
- projectId: 'your-project-id',
295
- });
393
+ type AppEvents = {
394
+ 'user.subscribed': { username: string; plan: string };
395
+ 'invoice.paid': { amount: string; customer: string };
396
+ };
296
397
 
297
- // Submit contact form
298
- await client.submitContactForm({
299
- name: 'John Doe',
300
- email: 'john@example.com',
301
- message: 'I need help!',
302
- });
398
+ // Env: CHANNLIZE_SERVER_API_KEY (or CHANNLIZE_API_KEY), CHANNLIZE_PROJECT_ID.
399
+ const notify = createNotifier<AppEvents>();
303
400
 
304
- // Create chat session
305
- const { session } = await client.createChatSession();
401
+ const res = await notify('user.subscribed', { username: 'ada', plan: 'Pro' });
402
+ // res.status: 'queued' | 'skipped' (see res.reason); res.duplicate on a repeated key
306
403
 
307
- // Send message
308
- await client.sendMessage(session.id, 'Hello!');
404
+ // Retry-safe: an idempotency key already used posts nothing.
405
+ await notify('invoice.paid', { amount: '$49', customer: 'ada@example.com' }, { idempotencyKey: 'inv_123' });
309
406
  \`\`\`
310
407
 
311
- ## Configuration
312
-
313
- - \`apiKey\`: Your Channlize widget key (required)
314
- - \`projectId\`: Your project ID (required)
315
- - \`baseUrl\`: API base URL (optional, defaults to api.channlize.com)
316
- - \`timeout\`: Request timeout in ms (optional, defaults to 10000)
317
- `;
318
- var REACT_COMPONENTS = `# Channlize React Components
319
-
320
- ## ChannlizeProvider
321
-
322
- Wrap your app to provide Channlize configuration to all components.
408
+ To type keys app-wide instead, augment the interface:
409
+ \`\`\`ts
410
+ declare module '@channlize/core' {
411
+ interface ChannlizeEvents {
412
+ 'user.subscribed': { username: string; plan: string };
413
+ }
414
+ }
415
+ \`\`\`
323
416
 
324
- \`\`\`tsx
325
- <ChannlizeProvider config={{ apiKey, projectId }}>
326
- {children}
327
- </ChannlizeProvider>
417
+ Over HTTP:
418
+ \`\`\`bash
419
+ curl -X POST https://api.channlize.com/v1/notify \\
420
+ -H "Authorization: Bearer $CHANNLIZE_SERVER_API_KEY" \\
421
+ -H "Content-Type: application/json" \\
422
+ -H "Idempotency-Key: signup-42" \\
423
+ -d '{"projectId":"<project-id>","event":"user.subscribed","data":{"username":"ada"}}'
328
424
  \`\`\`
329
425
 
330
- ## Form
426
+ Log tracking is separate: \`client.trackEvent\` (browser) / \`trackServerEvent\` (server)
427
+ record log lines shown under Log tracking.
428
+ `;
331
429
 
332
- A complete contact form with validation and submission handling.
430
+ // src/prompts.ts
431
+ function user(text) {
432
+ return {
433
+ messages: [
434
+ { role: "user", content: { type: "text", text } }
435
+ ]
436
+ };
437
+ }
438
+ function registerServerPrompts(server) {
439
+ server.registerPrompt(
440
+ "triage-conversations",
441
+ {
442
+ title: "Triage open conversations",
443
+ description: "Review open support conversations, rank them by urgency and draft a reply for each.",
444
+ argsSchema: z.object({
445
+ status: z.string().optional().describe(
446
+ "Status to triage: open (default), pending, resolved or closed"
447
+ ),
448
+ limit: z.string().optional().describe("How many conversations (default 10)")
449
+ })
450
+ },
451
+ ({ status, limit }) => user(`Triage my Channlize support inbox.
333
452
 
334
- ### Props
335
- - \`customFields?: Array<CustomField>\` - Additional form fields
336
- - \`onSuccess?: () => void\` - Success callback
337
- - \`onError?: (error: Error) => void\` - Error callback
338
- - \`className?: string\` - CSS class name
339
- - \`styles?: FormStyles\` - Custom styles object
340
- - \`submitText?: string\` - Submit button text
341
- - \`successMessage?: string\` - Success message text
453
+ 1. Call list_conversations with status "${status || "open"}" and limit ${Number(limit) || 10}.
454
+ 2. For each conversation, call get_conversation to read the thread.
455
+ 3. Return a table sorted by urgency: subject, customer, how long it has waited, current priority, a suggested priority (low / normal / high / urgent) and a one-line reason.
456
+ 4. Under the table, draft a short, friendly reply for each conversation that needs one, and flag anything that looks like a bug, an outage or a billing problem.
342
457
 
343
- ### Example
344
- \`\`\`tsx
345
- <Form
346
- customFields={[
458
+ Replies and status or priority changes are made by the team in the Slack thread or the Channlize dashboard, so present the drafts for me to send; don't invent facts about my product.`)
459
+ );
460
+ server.registerPrompt(
461
+ "summarize-conversation",
347
462
  {
348
- name: 'department',
349
- label: 'Department',
350
- type: 'select',
351
- options: ['Sales', 'Support'],
352
- required: true,
463
+ title: "Summarize a conversation",
464
+ description: "Summarize one conversation and suggest the next step.",
465
+ argsSchema: z.object({
466
+ conversationId: z.string().describe("Conversation ID")
467
+ })
353
468
  },
354
- ]}
355
- onSuccess={() => alert('Sent!')}
356
- styles={{
357
- button: { background: '#007bff', color: 'white' },
358
- }}
359
- />
360
- \`\`\`
469
+ ({ conversationId }) => user(
470
+ `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.`
471
+ )
472
+ );
473
+ server.registerPrompt(
474
+ "check-events",
475
+ {
476
+ title: "Check Events delivery",
477
+ description: "Check that Events reach Slack: list them and explain failed or skipped deliveries.",
478
+ argsSchema: z.object({})
479
+ },
480
+ () => user(`Check my Channlize Events setup.
361
481
 
362
- ## Chat
482
+ 1. Call list_event_definitions and list the Events, flagging disabled drafts and Events without a Slack channel.
483
+ 2. Call list_event_deliveries (limit 50) and group the deliveries by status.
484
+ 3. 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).`)
485
+ );
486
+ }
487
+ function registerGuidePrompts(server) {
488
+ server.registerPrompt(
489
+ "setup-events",
490
+ {
491
+ title: "Add Events to my app",
492
+ description: "Add Channlize Events (notify Slack from server code) to the current codebase.",
493
+ argsSchema: z.object({
494
+ events: z.string().optional().describe('Events to add, e.g. "signup, subscription upgrade"')
495
+ })
496
+ },
497
+ ({ events }) => user(`Add Channlize Events to this codebase${events ? ` for: ${events}` : ""}.
363
498
 
364
- Real-time chat widget with message history and file attachments.
499
+ Find 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.
365
500
 
366
- ### Props
367
- - \`autoStart?: boolean\` - Auto-start chat session
368
- - \`metadata?: Record<string, unknown>\` - Session metadata
369
- - \`onMessage?: (message: ChatMessage) => void\` - New message callback
370
- - \`onError?: (error: Error) => void\` - Error callback
371
- - \`className?: string\` - CSS class name
372
- - \`styles?: ChatStyles\` - Custom styles object
373
- - \`title?: string\` - Chat header title
374
- - \`placeholder?: string\` - Input placeholder text
375
- - \`maxHeight?: string\` - Maximum container height
501
+ Reference:
376
502
 
377
- ### Example
378
- \`\`\`tsx
379
- <Chat
380
- autoStart={true}
381
- title="Need Help?"
382
- placeholder="Type your message..."
383
- onMessage={(msg) => console.log('New:', msg)}
384
- styles={{
385
- container: { width: '400px', height: '500px' },
386
- header: { background: '#007bff', color: 'white' },
387
- }}
388
- />
389
- \`\`\`
503
+ ${EVENTS}`)
504
+ );
505
+ server.registerPrompt(
506
+ "setup-live-chat",
507
+ {
508
+ title: "Add the chat widget",
509
+ description: "Add the Channlize live chat widget to a React or Next.js app.",
510
+ argsSchema: z.object({
511
+ framework: z.string().optional().describe("e.g. Next.js App Router, Vite, Remix")
512
+ })
513
+ },
514
+ ({ framework }) => 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.
390
515
 
391
- ## Hooks
516
+ Reference:
392
517
 
393
- ### useContactForm()
394
- Hook for managing contact form state.
518
+ ${REACT_COMPONENTS}`)
519
+ );
520
+ server.registerPrompt(
521
+ "integrate-contact-form",
522
+ {
523
+ title: "Add a contact form",
524
+ description: "Add a Channlize contact form page to a React app.",
525
+ argsSchema: z.object({
526
+ styling: z.string().optional().describe("Styling approach, e.g. Tailwind or CSS modules")
527
+ })
528
+ },
529
+ ({ styling }) => 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.
395
530
 
396
- \`\`\`tsx
397
- const { submit, isSubmitting, isSuccess, error, reset } = useContactForm({
398
- onSuccess: (response) => console.log('Submitted:', response),
399
- onError: (error) => console.error('Failed:', error),
400
- });
401
- \`\`\`
531
+ Reference:
402
532
 
403
- ### useChatSession()
404
- Hook for managing chat sessions.
533
+ ${REACT_COMPONENTS}`)
534
+ );
535
+ }
405
536
 
406
- \`\`\`tsx
407
- const {
408
- session,
409
- messages,
410
- isConnecting,
411
- isConnected,
412
- error,
413
- sendMessage,
414
- startSession,
415
- endSession,
416
- } = useChatSession({
417
- autoConnect: false,
418
- metadata: { page: 'support' },
419
- onMessage: (message) => console.log('New message:', message),
537
+ // src/resources.ts
538
+ var markdown = (uri, text) => ({
539
+ contents: [{ uri, mimeType: "text/markdown", text }]
420
540
  });
421
- \`\`\`
422
-
423
- ## Styling
424
-
425
- All components accept \`styles\` prop for custom styling or \`className\` for CSS classes.
426
-
427
- CSS class names:
428
- - \`.channlize-form\`
429
- - \`.channlize-field\`
430
- - \`.channlize-error\`
431
- - \`.channlize-chat-container\`
432
- - \`.channlize-chat-header\`
433
- - \`.channlize-chat-messages\`
434
- - \`.channlize-message\`
435
- - \`.channlize-message-user\`
436
- - \`.channlize-message-agent\`
437
- `;
438
- var resources = [
439
- {
440
- uri: "channlize://schema/contact-form",
441
- name: "Contact Form Schema",
442
- description: "JSON schema for contact form data structure",
443
- mimeType: "application/json",
444
- getText: () => CONTACT_FORM_SCHEMA
445
- },
446
- {
447
- uri: "channlize://schema/chat-session",
448
- name: "Chat Session Schema",
449
- description: "JSON schema for chat session data structure",
450
- mimeType: "application/json",
451
- getText: () => CHAT_SESSION_SCHEMA
452
- },
453
- {
454
- uri: "channlize://docs/api-reference",
455
- name: "API Reference",
456
- description: "Complete Channlize API reference documentation",
457
- mimeType: "text/markdown",
458
- getText: () => API_REFERENCE
459
- },
460
- {
461
- uri: "channlize://docs/quick-start",
462
- name: "Quick Start Guide",
463
- description: "Quick start guide for using Channlize SDK",
464
- mimeType: "text/markdown",
465
- getText: () => QUICK_START
466
- },
467
- {
468
- uri: "channlize://docs/react-components",
469
- name: "React Components Documentation",
470
- description: "Documentation for Channlize React components and hooks",
471
- mimeType: "text/markdown",
472
- getText: () => REACT_COMPONENTS
541
+ function registerResources(server, api) {
542
+ server.registerResource(
543
+ "quick-start",
544
+ "channlize://docs/quick-start",
545
+ {
546
+ title: "Channlize quick start",
547
+ description: "Keys, install, and first calls from the browser and the server.",
548
+ mimeType: "text/markdown"
549
+ },
550
+ (uri) => markdown(uri.href, QUICK_START)
551
+ );
552
+ server.registerResource(
553
+ "react-components",
554
+ "channlize://docs/react-components",
555
+ {
556
+ title: "@channlize/react components and hooks",
557
+ description: "ChannlizeChat, SupportChat, ContactForm, hooks and Next.js notes.",
558
+ mimeType: "text/markdown"
559
+ },
560
+ (uri) => markdown(uri.href, REACT_COMPONENTS)
561
+ );
562
+ server.registerResource(
563
+ "events",
564
+ "channlize://docs/events",
565
+ {
566
+ title: "Events: notify Slack from code",
567
+ description: "createNotifier / notify with typed events, idempotency and curl.",
568
+ mimeType: "text/markdown"
569
+ },
570
+ (uri) => markdown(uri.href, EVENTS)
571
+ );
572
+ if (api.hasServerKey) {
573
+ server.registerResource(
574
+ "project",
575
+ "channlize://project",
576
+ {
577
+ title: "Current Channlize project",
578
+ description: "The key's project: ID, name, totals, permissions and Slack connection.",
579
+ mimeType: "application/json"
580
+ },
581
+ async (uri) => {
582
+ const r = await api.request(
583
+ "GET",
584
+ "/projects/me"
585
+ );
586
+ return {
587
+ contents: [
588
+ {
589
+ uri: uri.href,
590
+ mimeType: "application/json",
591
+ text: JSON.stringify(r.project, null, 2)
592
+ }
593
+ ]
594
+ };
595
+ }
596
+ );
473
597
  }
474
- ];
475
- function getResource(uri) {
476
- return resources.find((r) => r.uri === uri);
477
- }
478
- function listResources() {
479
- return resources;
480
598
  }
481
599
 
482
- // src/tools/index.ts
483
- var import_core = require("@channlize/core");
484
- function createClient(context) {
485
- return new import_core.ChannlizeClient({
486
- apiKey: context.config.apiKey,
487
- projectId: context.config.projectId || "",
488
- baseUrl: context.config.baseUrl,
489
- timeout: context.config.timeout
490
- });
600
+ // src/tools.ts
601
+ var z2 = __toESM(require("zod/v4"));
602
+ var STATUSES = ["open", "pending", "resolved", "closed"];
603
+ var PRIORITIES = ["low", "normal", "high", "urgent"];
604
+ var SEVERITIES = ["info", "warning", "error"];
605
+ var EVENT_KEY = /^[a-z0-9][a-z0-9._-]*$/;
606
+ function ok(data) {
607
+ return {
608
+ content: [{ type: "text", text: JSON.stringify(data, null, 2) }],
609
+ structuredContent: data
610
+ };
491
611
  }
492
- var tools = [
493
- {
494
- name: "submit_contact_form",
495
- description: "Submit a contact form inquiry to Channlize. This creates a new conversation thread in Slack where the team can respond.",
496
- inputSchema: {
497
- type: "object",
498
- properties: {
499
- name: {
500
- type: "string",
501
- description: "Contact's full name"
502
- },
503
- email: {
504
- type: "string",
505
- description: "Contact's email address"
506
- },
507
- subject: {
508
- type: "string",
509
- description: "Subject line for the inquiry (optional)"
510
- },
511
- message: {
512
- type: "string",
513
- description: "The message content"
514
- },
515
- customFields: {
516
- type: "object",
517
- description: "Additional custom fields as key-value pairs (optional)",
518
- additionalProperties: true
519
- },
520
- pageUrl: {
521
- type: "string",
522
- description: "URL of the page where form was submitted (optional)"
523
- },
524
- userAgent: {
525
- type: "string",
526
- description: "User agent string of the submitter (optional)"
527
- }
528
- },
529
- required: ["name", "email", "message"]
612
+ async function run(fn) {
613
+ try {
614
+ return ok(await fn());
615
+ } catch (err) {
616
+ const e = toToolError(err);
617
+ return {
618
+ content: [{ type: "text", text: e.message }],
619
+ isError: true
620
+ };
621
+ }
622
+ }
623
+ var record2 = z2.record(z2.string(), z2.unknown());
624
+ var loose = z2.looseObject({});
625
+ var page = {
626
+ total: z2.number(),
627
+ limit: z2.number(),
628
+ offset: z2.number(),
629
+ hasMore: z2.boolean()
630
+ };
631
+ var conversationSummary = z2.looseObject({
632
+ id: z2.string(),
633
+ subject: z2.string().nullable().optional(),
634
+ status: z2.string(),
635
+ priority: z2.string().nullable().optional(),
636
+ customerEmail: z2.string().nullable().optional(),
637
+ customerName: z2.string().nullable().optional(),
638
+ tags: z2.array(z2.string()).nullable().optional(),
639
+ createdAt: z2.string().optional()
640
+ });
641
+ var READ = {
642
+ readOnlyHint: true,
643
+ destructiveHint: false,
644
+ idempotentHint: true,
645
+ openWorldHint: false
646
+ };
647
+ function registerServerTools(server, api) {
648
+ server.registerTool(
649
+ "get_project",
650
+ {
651
+ title: "Get project",
652
+ description: "Show the Channlize project behind the server API key: name, ID, totals, the key's permissions and whether Slack is connected. Start here to check the setup.",
653
+ inputSchema: z2.object({}),
654
+ outputSchema: z2.object({ project: loose }),
655
+ annotations: READ
530
656
  },
531
- handler: async (args2, context) => {
532
- const client = createClient(context);
533
- const response = await client.submitContactForm({
534
- name: args2.name,
535
- email: args2.email,
536
- subject: args2.subject,
537
- message: args2.message,
538
- customFields: args2.customFields,
539
- pageUrl: args2.pageUrl,
540
- userAgent: args2.userAgent
541
- });
657
+ () => run(async () => {
658
+ const r = await api.request("GET", "/projects/me");
659
+ return { project: r.project };
660
+ })
661
+ );
662
+ server.registerTool(
663
+ "get_analytics",
664
+ {
665
+ title: "Get analytics",
666
+ description: "Daily support activity for the last 30 days (UTC): conversations created and resolved, customer and agent messages.",
667
+ inputSchema: z2.object({}),
668
+ outputSchema: z2.object({ analytics: loose }),
669
+ annotations: READ
670
+ },
671
+ () => run(async () => {
672
+ const r = await api.request(
673
+ "GET",
674
+ "/projects/analytics"
675
+ );
676
+ return { analytics: r.analytics };
677
+ })
678
+ );
679
+ server.registerTool(
680
+ "list_conversations",
681
+ {
682
+ title: "List conversations",
683
+ description: "List the organization's most recent support conversations (newest first, from the latest 50), optionally filtered by status or priority. Use get_conversation for the messages.",
684
+ inputSchema: z2.object({
685
+ status: z2.enum(STATUSES).optional().describe("Only conversations with this status"),
686
+ priority: z2.enum(PRIORITIES).optional().describe("Only conversations with this priority"),
687
+ limit: z2.number().int().min(1).max(50).default(20).describe("How many to return (1-50, default 20)")
688
+ }),
689
+ outputSchema: z2.object({
690
+ conversations: z2.array(conversationSummary),
691
+ returned: z2.number(),
692
+ matched: z2.number(),
693
+ scanned: z2.number()
694
+ }),
695
+ annotations: READ
696
+ },
697
+ ({ status, priority, limit }) => run(async () => {
698
+ const r = await api.request(
699
+ "GET",
700
+ "/conversations"
701
+ );
702
+ const all = r.conversations ?? [];
703
+ const matched = all.filter(
704
+ (c) => (!status || c.status === status) && (!priority || c.priority === priority)
705
+ );
706
+ const conversations = matched.slice(0, limit);
542
707
  return {
543
- success: true,
544
- contactId: response.id,
545
- status: response.status,
546
- slackThreadUrl: response.slackThreadUrl,
547
- message: "Contact form submitted successfully"
708
+ conversations,
709
+ returned: conversations.length,
710
+ matched: matched.length,
711
+ scanned: all.length
548
712
  };
549
- }
550
- },
551
- {
552
- name: "create_chat_session",
553
- description: "Create a new chat session for real-time messaging. Returns a session ID that can be used to send and receive messages.",
554
- inputSchema: {
555
- type: "object",
556
- properties: {
557
- metadata: {
558
- type: "object",
559
- description: "Custom metadata to attach to the session (e.g., page URL, user info)",
560
- additionalProperties: true
561
- }
713
+ })
714
+ );
715
+ server.registerTool(
716
+ "get_conversation",
717
+ {
718
+ title: "Get conversation",
719
+ description: "Read one conversation with its full message thread (customer, agent and system messages), status, priority and tags.",
720
+ inputSchema: z2.object({
721
+ conversationId: z2.string().uuid().describe("Conversation ID (from list_conversations)")
722
+ }),
723
+ outputSchema: z2.object({ conversation: loose }),
724
+ annotations: READ
725
+ },
726
+ ({ conversationId }) => run(async () => {
727
+ const conversation = await api.request(
728
+ "GET",
729
+ `/conversations/${encodeURIComponent(conversationId)}`
730
+ );
731
+ return { conversation };
732
+ })
733
+ );
734
+ server.registerTool(
735
+ "create_conversation",
736
+ {
737
+ title: "Create conversation",
738
+ description: "Open a new support conversation on behalf of a customer. It is posted to Slack (the given channel, else routing rules, else the default channel). Needs the write scope. Repeating the same customer, subject and message within 30 seconds returns the existing conversation.",
739
+ inputSchema: z2.object({
740
+ customerEmail: z2.email().describe("Customer's email address"),
741
+ customerName: z2.string().max(255).optional().describe("Customer's name"),
742
+ subject: z2.string().min(1).max(500).describe("Subject line"),
743
+ message: z2.string().min(1).describe("First message, from the customer"),
744
+ channel: z2.string().optional().describe("Slack channel ID to post to, overriding routing rules"),
745
+ tags: z2.array(z2.string()).max(20).optional().describe("Tags")
746
+ }),
747
+ outputSchema: z2.object({ conversation: loose }),
748
+ annotations: {
749
+ readOnlyHint: false,
750
+ destructiveHint: false,
751
+ idempotentHint: false,
752
+ openWorldHint: true
562
753
  }
563
754
  },
564
- handler: async (args2, context) => {
565
- const client = createClient(context);
566
- const response = await client.createChatSession(args2.metadata);
567
- return {
568
- success: true,
569
- session: {
570
- id: response.session.id,
571
- status: response.session.status,
572
- createdAt: response.session.createdAt,
573
- messageCount: response.session.messages?.length || 0
574
- },
575
- sseEndpoint: response.sseEndpoint,
576
- message: "Chat session created successfully"
577
- };
578
- }
579
- },
580
- {
581
- name: "send_message",
582
- description: "Send a message in an existing chat session. The message will be delivered to the Slack thread and the user can see agent replies in real-time.",
583
- inputSchema: {
584
- type: "object",
585
- properties: {
586
- sessionId: {
587
- type: "string",
588
- description: "The chat session ID"
589
- },
590
- content: {
591
- type: "string",
592
- description: "The message content to send"
593
- }
594
- },
595
- required: ["sessionId", "content"]
755
+ (args) => run(async () => {
756
+ const conversation = await api.request("POST", "/conversations", {
757
+ body: args
758
+ });
759
+ return { conversation };
760
+ })
761
+ );
762
+ server.registerTool(
763
+ "list_contacts",
764
+ {
765
+ title: "List contacts",
766
+ description: "List the customers who contacted the organization, with their conversation count. Paginate with limit/offset.",
767
+ inputSchema: z2.object({
768
+ limit: z2.number().int().min(1).max(100).default(50),
769
+ offset: z2.number().int().min(0).default(0)
770
+ }),
771
+ outputSchema: z2.object({ contacts: z2.array(loose), ...page }),
772
+ annotations: READ
596
773
  },
597
- handler: async (args2, context) => {
598
- const client = createClient(context);
599
- const response = await client.sendMessage(args2.sessionId, args2.content);
774
+ ({ limit, offset }) => run(async () => {
775
+ const r = await api.request("GET", "/contacts", {
776
+ query: { limit, offset }
777
+ });
600
778
  return {
601
- success: true,
602
- message: {
603
- id: response.message.id,
604
- content: response.message.content,
605
- timestamp: response.message.timestamp,
606
- author: response.message.author
607
- },
608
- sessionStatus: response.session.status,
609
- deliveryMessage: "Message sent successfully"
779
+ contacts: r.contacts ?? [],
780
+ total: Number(r.total ?? 0),
781
+ limit: Number(r.limit ?? limit),
782
+ offset: Number(r.offset ?? offset),
783
+ hasMore: Boolean(r.hasMore)
610
784
  };
611
- }
612
- },
613
- {
614
- name: "get_chat_messages",
615
- description: "Retrieve messages from a chat session. Useful for viewing conversation history.",
616
- inputSchema: {
617
- type: "object",
618
- properties: {
619
- sessionId: {
620
- type: "string",
621
- description: "The chat session ID"
622
- },
623
- limit: {
624
- type: "number",
625
- description: "Maximum number of messages to retrieve (default: 50)",
626
- default: 50
627
- },
628
- offset: {
629
- type: "number",
630
- description: "Number of messages to skip (default: 0)",
631
- default: 0
632
- }
633
- },
634
- required: ["sessionId"]
785
+ })
786
+ );
787
+ server.registerTool(
788
+ "get_contact",
789
+ {
790
+ title: "Get contact",
791
+ description: "Read one contact (customer) by ID.",
792
+ inputSchema: z2.object({
793
+ contactId: z2.string().uuid().describe("Contact ID (from list_contacts)")
794
+ }),
795
+ outputSchema: z2.object({ contact: loose }),
796
+ annotations: READ
635
797
  },
636
- handler: async (args2, context) => {
637
- const client = createClient(context);
638
- const messages = await client.getChatMessages(
639
- args2.sessionId,
640
- args2.limit || 50,
641
- args2.offset || 0
798
+ ({ contactId }) => run(async () => {
799
+ const contact = await api.request(
800
+ "GET",
801
+ `/contacts/${encodeURIComponent(contactId)}`
642
802
  );
803
+ return { contact };
804
+ })
805
+ );
806
+ server.registerTool(
807
+ "create_contact",
808
+ {
809
+ title: "Create contact",
810
+ description: "Add a customer by email, or return the existing one with that email. Needs the write scope.",
811
+ inputSchema: z2.object({
812
+ email: z2.email(),
813
+ name: z2.string().max(255).optional(),
814
+ company: z2.string().optional(),
815
+ phone: z2.string().optional(),
816
+ tags: z2.array(z2.string()).max(20).optional()
817
+ }),
818
+ outputSchema: z2.object({ contact: loose }),
819
+ annotations: {
820
+ readOnlyHint: false,
821
+ destructiveHint: false,
822
+ idempotentHint: true,
823
+ openWorldHint: false
824
+ }
825
+ },
826
+ (args) => run(async () => {
827
+ const contact = await api.request("POST", "/contacts", {
828
+ body: args
829
+ });
830
+ return { contact };
831
+ })
832
+ );
833
+ server.registerTool(
834
+ "notify_event",
835
+ {
836
+ title: "Send an Event to Slack",
837
+ description: 'Post an Event to Slack: the event key (e.g. "user.subscribed") picks the channel and message template set under Events in the dashboard, and `data` fills its {{placeholders}}. An unknown key is saved as a disabled draft and answered with status "skipped". Needs the write scope. Pass an idempotencyKey so a retry never posts twice.',
838
+ inputSchema: z2.object({
839
+ event: z2.string().max(100).regex(
840
+ EVENT_KEY,
841
+ "lowercase letters, digits, dots, underscores or dashes"
842
+ ).describe("Event key, e.g. user.subscribed"),
843
+ data: record2.optional().describe(
844
+ 'Template fields, e.g. { "username": "ada", "plan": "Pro" }'
845
+ ),
846
+ idempotencyKey: z2.string().min(1).max(255).optional().describe("Send at most once per key (retry-safe)"),
847
+ channel: z2.string().optional().describe("Slack channel ID instead of the event's channel")
848
+ }),
849
+ outputSchema: z2.looseObject({
850
+ id: z2.string(),
851
+ event: z2.string(),
852
+ status: z2.string(),
853
+ reason: z2.string().optional(),
854
+ duplicate: z2.boolean().optional()
855
+ }),
856
+ annotations: {
857
+ readOnlyHint: false,
858
+ destructiveHint: false,
859
+ idempotentHint: false,
860
+ openWorldHint: true
861
+ }
862
+ },
863
+ ({ event, data, idempotencyKey, channel }) => run(async () => {
864
+ const client = await api.notifier();
865
+ const r = await client.notify(event, data, { idempotencyKey, channel });
643
866
  return {
644
- success: true,
645
- sessionId: args2.sessionId,
646
- messageCount: messages.length,
647
- messages: messages.map((msg) => ({
648
- id: msg.id,
649
- content: msg.content,
650
- timestamp: msg.timestamp,
651
- author: msg.author,
652
- authorData: msg.authorData,
653
- hasAttachments: (msg.attachments?.length || 0) > 0
654
- }))
867
+ id: r.id,
868
+ event: r.event,
869
+ status: r.status,
870
+ ...r.reason ? { reason: r.reason } : {},
871
+ ...r.duplicate ? { duplicate: true } : {}
655
872
  };
656
- }
657
- },
658
- {
659
- name: "close_chat_session",
660
- description: "Close an active chat session. This marks the conversation as complete and stops real-time updates.",
661
- inputSchema: {
662
- type: "object",
663
- properties: {
664
- sessionId: {
665
- type: "string",
666
- description: "The chat session ID to close"
667
- }
668
- },
669
- required: ["sessionId"]
873
+ })
874
+ );
875
+ server.registerTool(
876
+ "list_event_definitions",
877
+ {
878
+ title: "List Events",
879
+ description: "List the Events configured on the project (key, name, Slack channel, message template, enabled), including disabled drafts created by unknown keys sent with notify_event.",
880
+ inputSchema: z2.object({}),
881
+ outputSchema: z2.object({
882
+ projectId: z2.string(),
883
+ definitions: z2.array(loose)
884
+ }),
885
+ annotations: READ
886
+ },
887
+ () => run(async () => {
888
+ const projectId = await api.projectId();
889
+ const r = await api.request(
890
+ "GET",
891
+ `/v1/projects/${encodeURIComponent(projectId)}/event-definitions`
892
+ );
893
+ return { projectId, definitions: r.definitions ?? [] };
894
+ })
895
+ );
896
+ server.registerTool(
897
+ "list_event_deliveries",
898
+ {
899
+ title: "List Event deliveries",
900
+ description: "Recent notify_event deliveries on the project, newest first, with their status (queued, sent, failed, skipped) and the reason when not sent. Use it to check why an Event did not reach Slack.",
901
+ inputSchema: z2.object({
902
+ definitionId: z2.string().uuid().optional().describe("Only this Event (ID from list_event_definitions)"),
903
+ limit: z2.number().int().min(1).max(100).default(20)
904
+ }),
905
+ outputSchema: z2.object({
906
+ projectId: z2.string(),
907
+ deliveries: z2.array(loose)
908
+ }),
909
+ annotations: READ
910
+ },
911
+ ({ definitionId, limit }) => run(async () => {
912
+ const projectId = await api.projectId();
913
+ const r = await api.request(
914
+ "GET",
915
+ `/v1/projects/${encodeURIComponent(projectId)}/event-deliveries`,
916
+ { query: { definitionId, limit } }
917
+ );
918
+ return { projectId, deliveries: r.deliveries ?? [] };
919
+ })
920
+ );
921
+ server.registerTool(
922
+ "query_logs",
923
+ {
924
+ title: "Query logs",
925
+ description: "Search log tracking (trackEvent / trackServerEvent / track_log), newest first. Filter by severity, source, text (matches the name and properties) and time range; paginate with limit/offset. Covers all projects unless projectId is given.",
926
+ inputSchema: z2.object({
927
+ severity: z2.enum(SEVERITIES).optional(),
928
+ source: z2.enum(["client_sdk", "server_api", "system"]).optional().describe(
929
+ "client_sdk = browser (widget key), server_api = server key"
930
+ ),
931
+ search: z2.string().max(200).optional().describe("Text to look for"),
932
+ from: z2.iso.datetime({ offset: true }).optional().describe("ISO 8601 start"),
933
+ to: z2.iso.datetime({ offset: true }).optional().describe("ISO 8601 end"),
934
+ projectId: z2.string().uuid().optional(),
935
+ limit: z2.number().int().min(1).max(100).default(50),
936
+ offset: z2.number().int().min(0).default(0)
937
+ }),
938
+ outputSchema: z2.object({ events: z2.array(loose), ...page }),
939
+ annotations: READ
670
940
  },
671
- handler: async (args2, context) => {
672
- const client = createClient(context);
673
- const session = await client.closeChatSession(args2.sessionId);
941
+ (args) => run(async () => {
942
+ const r = await api.request("GET", "/v1/events", { query: args });
674
943
  return {
675
- success: true,
676
- sessionId: session.id,
677
- status: session.status,
678
- closedAt: session.updatedAt,
679
- message: "Chat session closed successfully"
944
+ events: r.events ?? [],
945
+ total: Number(r.total ?? 0),
946
+ limit: Number(r.limit ?? args.limit),
947
+ offset: Number(r.offset ?? args.offset),
948
+ hasMore: Boolean(r.hasMore)
680
949
  };
681
- }
682
- }
683
- ];
684
- function getTool(name) {
685
- return tools.find((t) => t.name === name);
686
- }
687
- function listTools() {
688
- return tools;
689
- }
690
-
691
- // src/prompts/index.ts
692
- var prompts = [
693
- {
694
- name: "integrate-contact-form",
695
- description: "Guide for adding a Channlize contact form to a React application",
696
- arguments: [
697
- {
698
- name: "framework",
699
- description: "The React framework being used (e.g., Next.js, Vite, CRA)",
700
- required: false
701
- },
702
- {
703
- name: "styling",
704
- description: "The styling approach (e.g., Tailwind, CSS Modules, styled-components)",
705
- required: false
706
- }
707
- ],
708
- getPrompt: (args2) => {
709
- const framework = args2?.framework || "React";
710
- const styling = args2?.styling || "CSS";
711
- return `# Integrating Channlize Contact Form in ${framework}
712
-
713
- ## Step 1: Install Dependencies
714
-
715
- \`\`\`bash
716
- npm install @channlize/react
717
- \`\`\`
718
-
719
- ## Step 2: Configure Provider
720
-
721
- Wrap your application with the ChannlizeProvider at the root level:
722
-
723
- \`\`\`tsx
724
- import { ChannlizeProvider } from '@channlize/react';
725
-
726
- function App() {
727
- return (
728
- <ChannlizeProvider
729
- config={{
730
- apiKey: process.env.NEXT_PUBLIC_CHANNLIZE_API_KEY, // Your widget key
731
- projectId: process.env.NEXT_PUBLIC_CHANNLIZE_PROJECT_ID,
732
- baseUrl: process.env.NEXT_PUBLIC_CHANNLIZE_API_URL, // Optional
733
- }}
734
- >
735
- <YourAppContent />
736
- </ChannlizeProvider>
737
- );
738
- }
739
- \`\`\`
740
-
741
- ## Step 3: Add Form Component
742
-
743
- Create a contact page or component:
744
-
745
- \`\`\`tsx
746
- import { Form } from '@channlize/react';
747
-
748
- export default function ContactPage() {
749
- return (
750
- <div className="container mx-auto py-8">
751
- <h1>Contact Us</h1>
752
- <Form
753
- onSuccess={() => {
754
- alert('Thank you! We will get back to you soon.');
755
- }}
756
- onError={(error) => {
757
- console.error('Failed to submit:', error);
758
- }}
759
- customFields={[
760
- {
761
- name: 'department',
762
- label: 'Department',
763
- type: 'select',
764
- options: ['Sales', 'Support', 'Billing'],
765
- required: true,
766
- },
767
- ]}
768
- ${styling === "Tailwind" ? `className="max-w-2xl"` : ""}
769
- styles={{
770
- form: { maxWidth: '600px', margin: '0 auto' },
771
- button: {
772
- background: '#007bff',
773
- color: 'white',
774
- padding: '0.75rem 1.5rem',
775
- borderRadius: '0.5rem',
776
- },
777
- }}
778
- submitText="Send Message"
779
- successMessage="Thank you! We'll respond shortly."
780
- />
781
- </div>
950
+ })
782
951
  );
783
- }
784
- \`\`\`
785
-
786
- ## Step 4: Environment Variables
787
-
788
- Add to your \`.env.local\` or \`.env\`:
789
-
790
- \`\`\`
791
- NEXT_PUBLIC_CHANNLIZE_API_KEY=your_widget_key_here
792
- NEXT_PUBLIC_CHANNLIZE_PROJECT_ID=your_project_id_here
793
- NEXT_PUBLIC_CHANNLIZE_API_URL=http://api.channlize.com # Optional
794
- \`\`\`
795
-
796
- ## Step 5: Customize (Optional)
797
-
798
- ### Custom Fields
799
- Add custom fields to gather specific information:
800
-
801
- \`\`\`tsx
802
- customFields={[
803
- {
804
- name: 'company',
805
- label: 'Company Name',
806
- type: 'text',
807
- required: false,
808
- },
809
- {
810
- name: 'priority',
811
- label: 'Priority',
812
- type: 'select',
813
- options: ['Low', 'Medium', 'High'],
814
- required: true,
815
- },
816
- ]}
817
- \`\`\`
818
-
819
- ### Custom Styling with ${styling}
820
- ${styling === "Tailwind" ? "Use Tailwind classes with the className prop or override styles." : "Apply custom styles using the styles prop or external CSS."}
821
-
822
- ## Tips
823
-
824
- - Messages are sent to your configured Slack channel instantly
825
- - Email fallback is automatic if Slack delivery fails
826
- - Form includes built-in validation and error handling
827
- - All fields support accessibility features (ARIA labels, keyboard navigation)
828
-
829
- ## Next Steps
830
-
831
- - Set up Slack workspace integration in your Channlize dashboard
832
- - Configure channel routing rules
833
- - Add webhooks for custom workflows
834
- `;
835
- }
836
- },
837
- {
838
- name: "setup-live-chat",
839
- description: "Guide for implementing the Channlize live chat widget in a React application",
840
- arguments: [
841
- {
842
- name: "placement",
843
- description: 'Where to place the chat widget (e.g., "page", "popup", "sidebar")',
844
- required: false
952
+ server.registerTool(
953
+ "track_log",
954
+ {
955
+ title: "Record a log",
956
+ description: "Record a log line under Log tracking from a trusted server context (source server_api). Needs the write scope. For Slack messages about product events use notify_event instead.",
957
+ inputSchema: z2.object({
958
+ name: z2.string().min(1).max(255).describe("Log name, e.g. payment.failed"),
959
+ severity: z2.enum(SEVERITIES).default("info"),
960
+ properties: record2.optional().describe("Extra fields")
961
+ }),
962
+ outputSchema: z2.object({ id: z2.string(), projectId: z2.string() }),
963
+ annotations: {
964
+ readOnlyHint: false,
965
+ destructiveHint: false,
966
+ idempotentHint: false,
967
+ openWorldHint: false
845
968
  }
846
- ],
847
- getPrompt: (args2) => {
848
- const placement = args2?.placement || "page";
849
- return `# Setting Up Channlize Live Chat Widget
850
-
851
- ## Step 1: Install Dependencies
852
-
853
- \`\`\`bash
854
- npm install @channlize/react
855
- \`\`\`
856
-
857
- ## Step 2: Configure Provider
858
-
859
- Ensure your app is wrapped with ChannlizeProvider:
860
-
861
- \`\`\`tsx
862
- import { ChannlizeProvider } from '@channlize/react';
863
-
864
- function App() {
865
- return (
866
- <ChannlizeProvider
867
- config={{
868
- apiKey: process.env.NEXT_PUBLIC_CHANNLIZE_API_KEY,
869
- projectId: process.env.NEXT_PUBLIC_CHANNLIZE_PROJECT_ID,
870
- }}
871
- >
872
- <YourAppContent />
873
- </ChannlizeProvider>
874
- );
875
- }
876
- \`\`\`
877
-
878
- ## Step 3: Add Chat Component
879
-
880
- ${placement === "popup" ? `
881
- ### Popup Widget (Bottom-Right Corner)
882
-
883
- \`\`\`tsx
884
- import { useState } from 'react';
885
- import { Chat } from '@channlize/react';
886
-
887
- export function ChatWidget() {
888
- const [isOpen, setIsOpen] = useState(false);
889
-
890
- return (
891
- <>
892
- {/* Floating Button */}
893
- {!isOpen && (
894
- <button
895
- onClick={() => setIsOpen(true)}
896
- style={{
897
- position: 'fixed',
898
- bottom: '20px',
899
- right: '20px',
900
- width: '60px',
901
- height: '60px',
902
- borderRadius: '50%',
903
- background: '#007bff',
904
- color: 'white',
905
- border: 'none',
906
- fontSize: '24px',
907
- cursor: 'pointer',
908
- boxShadow: '0 4px 12px rgba(0,0,0,0.15)',
909
- zIndex: 1000,
910
- }}
911
- >
912
- \u{1F4AC}
913
- </button>
914
- )}
915
-
916
- {/* Chat Window */}
917
- {isOpen && (
918
- <div
919
- style={{
920
- position: 'fixed',
921
- bottom: '20px',
922
- right: '20px',
923
- zIndex: 1000,
924
- boxShadow: '0 4px 24px rgba(0,0,0,0.15)',
925
- borderRadius: '12px',
926
- overflow: 'hidden',
927
- }}
928
- >
929
- <Chat
930
- autoStart={true}
931
- title="Customer Support"
932
- placeholder="Type your message..."
933
- onMessage={(message) => {
934
- console.log('New message:', message);
935
- }}
936
- styles={{
937
- container: {
938
- width: '380px',
939
- height: '600px',
940
- display: 'flex',
941
- flexDirection: 'column',
942
- background: 'white',
943
- },
944
- header: {
945
- background: '#007bff',
946
- color: 'white',
947
- padding: '1rem',
948
- display: 'flex',
949
- alignItems: 'center',
950
- },
951
- }}
952
- />
953
- <button
954
- onClick={() => setIsOpen(false)}
955
- style={{
956
- position: 'absolute',
957
- top: '10px',
958
- right: '10px',
959
- background: 'rgba(255,255,255,0.2)',
960
- border: 'none',
961
- color: 'white',
962
- cursor: 'pointer',
963
- fontSize: '20px',
964
- width: '30px',
965
- height: '30px',
966
- borderRadius: '50%',
967
- }}
968
- >
969
- \xD7
970
- </button>
971
- </div>
972
- )}
973
- </>
974
- );
975
- }
976
- \`\`\`
977
- ` : `
978
- ### Embedded Chat
979
-
980
- \`\`\`tsx
981
- import { Chat } from '@channlize/react';
982
-
983
- export default function SupportPage() {
984
- return (
985
- <div className="container mx-auto py-8">
986
- <h1>Customer Support</h1>
987
- <Chat
988
- autoStart={true}
989
- title="Live Chat Support"
990
- placeholder="How can we help you today?"
991
- onMessage={(message) => {
992
- // Handle incoming messages
993
- console.log('New message:', message);
994
- }}
995
- onError={(error) => {
996
- console.error('Chat error:', error);
997
- }}
998
- styles={{
999
- container: {
1000
- width: '100%',
1001
- maxWidth: '800px',
1002
- height: '600px',
1003
- margin: '0 auto',
1004
- border: '1px solid #e0e0e0',
1005
- borderRadius: '12px',
1006
- },
1007
- header: {
1008
- background: '#007bff',
1009
- color: 'white',
1010
- },
1011
- }}
1012
- maxHeight="600px"
1013
- />
1014
- </div>
1015
- );
1016
- }
1017
- \`\`\`
1018
- `}
1019
-
1020
- ## Step 4: Advanced Features
1021
-
1022
- ### Custom Metadata
1023
- Pass context about the user or page:
1024
-
1025
- \`\`\`tsx
1026
- <Chat
1027
- metadata={{
1028
- userId: user?.id,
1029
- userName: user?.name,
1030
- currentPage: window.location.pathname,
1031
- plan: 'pro',
1032
- }}
1033
- />
1034
- \`\`\`
1035
-
1036
- ### Event Handlers
1037
- React to chat events:
1038
-
1039
- \`\`\`tsx
1040
- <Chat
1041
- onMessage={(message) => {
1042
- // Track analytics
1043
- analytics.track('chat_message_received', {
1044
- author: message.author,
1045
- timestamp: message.timestamp,
1046
- });
1047
- }}
1048
- onError={(error) => {
1049
- // Report errors
1050
- errorReporting.log(error);
1051
- }}
1052
- />
1053
- \`\`\`
1054
-
1055
- ## Real-Time Features
1056
-
1057
- - Messages are delivered instantly via Server-Sent Events (SSE)
1058
- - Agent presence indicators show when team is active
1059
- - File attachments supported (images, documents)
1060
- - Automatic reconnection on connection loss
1061
- - Message history persisted across sessions
1062
-
1063
- ## Tips
1064
-
1065
- - Chat sessions are automatically created on first message
1066
- - Sessions remain active until explicitly closed
1067
- - Messages are threaded in Slack for team collaboration
1068
- - Supports multiple concurrent chat sessions per project
1069
-
1070
- ## Next Steps
1071
-
1072
- - Configure Slack notifications for new chats
1073
- - Set up auto-responses for common questions
1074
- - Integrate with your analytics platform
1075
- - Add custom routing based on user context
1076
- `;
1077
- }
1078
- },
1079
- {
1080
- name: "customize-styling",
1081
- description: "Guide for theming and customizing Channlize components",
1082
- getPrompt: () => `# Customizing Channlize Component Styling
1083
-
1084
- Channlize components are designed to be highly customizable to match your brand.
1085
-
1086
- ## Styling Approaches
1087
-
1088
- ### 1. Inline Styles with \`styles\` Prop
1089
-
1090
- The most direct way to customize appearance:
1091
-
1092
- \`\`\`tsx
1093
- <Form
1094
- styles={{
1095
- form: {
1096
- maxWidth: '600px',
1097
- margin: '0 auto',
1098
- padding: '2rem',
1099
- background: '#f9fafb',
1100
- borderRadius: '8px',
1101
- },
1102
- field: {
1103
- marginBottom: '1.5rem',
1104
- },
1105
- label: {
1106
- display: 'block',
1107
- marginBottom: '0.5rem',
1108
- fontWeight: '600',
1109
- color: '#374151',
1110
- },
1111
- input: {
1112
- width: '100%',
1113
- padding: '0.75rem',
1114
- border: '1px solid #d1d5db',
1115
- borderRadius: '6px',
1116
- fontSize: '1rem',
1117
- },
1118
- textarea: {
1119
- width: '100%',
1120
- padding: '0.75rem',
1121
- border: '1px solid #d1d5db',
1122
- borderRadius: '6px',
1123
- fontSize: '1rem',
1124
- minHeight: '120px',
1125
- },
1126
- button: {
1127
- background: '#3b82f6',
1128
- color: 'white',
1129
- padding: '0.75rem 2rem',
1130
- border: 'none',
1131
- borderRadius: '6px',
1132
- fontSize: '1rem',
1133
- fontWeight: '600',
1134
- cursor: 'pointer',
1135
- transition: 'background 0.2s',
1136
- },
1137
- error: {
1138
- color: '#ef4444',
1139
- fontSize: '0.875rem',
1140
- marginTop: '0.5rem',
1141
- },
1142
- success: {
1143
- background: '#ecfdf5',
1144
- border: '1px solid #10b981',
1145
- padding: '1.5rem',
1146
- borderRadius: '6px',
1147
- color: '#065f46',
1148
- },
1149
- }}
1150
- />
1151
- \`\`\`
1152
-
1153
- ### 2. CSS Classes with \`className\` Prop
1154
-
1155
- Use your existing CSS or CSS-in-JS solution:
1156
-
1157
- \`\`\`tsx
1158
- <Form className="custom-form" />
1159
- \`\`\`
1160
-
1161
- \`\`\`css
1162
- /* styles.css */
1163
- .channlize-form {
1164
- max-width: 600px;
1165
- margin: 0 auto;
1166
- }
1167
-
1168
- .channlize-field {
1169
- margin-bottom: 1.5rem;
1170
- }
1171
-
1172
- .channlize-field label {
1173
- font-weight: 600;
1174
- color: var(--primary-text);
1175
- }
1176
-
1177
- .channlize-field input,
1178
- .channlize-field textarea,
1179
- .channlize-field select {
1180
- border: 1px solid var(--border-color);
1181
- border-radius: 6px;
1182
- padding: 0.75rem;
1183
- }
1184
-
1185
- .channlize-form button[type="submit"] {
1186
- background: var(--primary-color);
1187
- color: white;
1188
- }
1189
- \`\`\`
1190
-
1191
- ### 3. Tailwind CSS
1192
-
1193
- Combine with Tailwind utility classes:
1194
-
1195
- \`\`\`tsx
1196
- <Form
1197
- className="max-w-2xl mx-auto p-8"
1198
- styles={{
1199
- input: {
1200
- // Tailwind styles as objects don't work well
1201
- // Use className on wrapper or global CSS
1202
969
  },
1203
- }}
1204
- />
1205
- \`\`\`
1206
-
1207
- \`\`\`css
1208
- /* globals.css with @layer */
1209
- @layer components {
1210
- .channlize-field input {
1211
- @apply w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500;
1212
- }
1213
-
1214
- .channlize-field textarea {
1215
- @apply w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500;
1216
- }
1217
-
1218
- .channlize-form button[type="submit"] {
1219
- @apply bg-blue-600 hover:bg-blue-700 text-white font-semibold py-3 px-6 rounded-lg transition;
1220
- }
970
+ ({ name, severity, properties }) => run(async () => {
971
+ const projectId = await api.projectId();
972
+ const r = await api.request("POST", "/v1/events", {
973
+ body: { projectId, name, severity, properties }
974
+ });
975
+ return { id: r.id, projectId };
976
+ })
977
+ );
1221
978
  }
1222
- \`\`\`
1223
-
1224
- ## Styling Chat
1225
-
1226
- \`\`\`tsx
1227
- <Chat
1228
- styles={{
1229
- container: {
1230
- border: '1px solid #e5e7eb',
1231
- borderRadius: '12px',
1232
- overflow: 'hidden',
1233
- boxShadow: '0 4px 12px rgba(0,0,0,0.1)',
1234
- },
1235
- header: {
1236
- background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
1237
- color: 'white',
1238
- padding: '1rem',
1239
- },
1240
- messages: {
1241
- background: '#f9fafb',
1242
- padding: '1rem',
979
+ var VISITOR = {
980
+ readOnlyHint: false,
981
+ destructiveHint: false,
982
+ idempotentHint: false,
983
+ openWorldHint: true
984
+ };
985
+ function registerWidgetTools(server, api) {
986
+ server.registerTool(
987
+ "submit_contact_form",
988
+ {
989
+ title: "Submit contact form",
990
+ description: "Submit the website contact form as a visitor (widget key). Creates a conversation that is posted to Slack. Useful to test the setup end to end.",
991
+ inputSchema: z2.object({
992
+ name: z2.string().min(1).describe("Visitor's name"),
993
+ email: z2.email().describe("Visitor's email"),
994
+ subject: z2.string().optional(),
995
+ message: z2.string().min(1),
996
+ pageUrl: z2.url().optional().describe("Page the form was sent from")
997
+ }),
998
+ outputSchema: z2.looseObject({
999
+ conversationId: z2.string().optional(),
1000
+ message: z2.string().optional()
1001
+ }),
1002
+ annotations: VISITOR
1243
1003
  },
1244
- messageUser: {
1245
- background: '#3b82f6',
1246
- color: 'white',
1247
- padding: '0.75rem',
1248
- borderRadius: '12px 12px 4px 12px',
1249
- maxWidth: '70%',
1250
- marginLeft: 'auto',
1004
+ (args) => run(async () => {
1005
+ const r = await api.widget().submitContactForm(args);
1006
+ return { conversationId: r.conversationId, message: r.message };
1007
+ })
1008
+ );
1009
+ server.registerTool(
1010
+ "create_chat_session",
1011
+ {
1012
+ title: "Start chat session",
1013
+ description: "Start a live chat session as a website visitor (widget key). Returns the session ID for send_message.",
1014
+ inputSchema: z2.object({
1015
+ metadata: record2.optional().describe("Metadata to attach (e.g. user info)")
1016
+ }),
1017
+ outputSchema: z2.looseObject({
1018
+ sessionId: z2.string(),
1019
+ status: z2.string()
1020
+ }),
1021
+ annotations: VISITOR
1251
1022
  },
1252
- messageAgent: {
1253
- background: 'white',
1254
- color: '#1f2937',
1255
- padding: '0.75rem',
1256
- borderRadius: '12px 12px 12px 4px',
1257
- maxWidth: '70%',
1258
- border: '1px solid #e5e7eb',
1023
+ ({ metadata }) => run(async () => {
1024
+ const r = await api.widget().createChatSession(metadata);
1025
+ return {
1026
+ sessionId: r.session.id,
1027
+ status: r.session.status,
1028
+ createdAt: String(r.session.createdAt)
1029
+ };
1030
+ })
1031
+ );
1032
+ server.registerTool(
1033
+ "send_message",
1034
+ {
1035
+ title: "Send chat message",
1036
+ description: "Send a visitor message in a chat session (widget key); it is posted to the Slack thread.",
1037
+ inputSchema: z2.object({
1038
+ sessionId: z2.string().min(1).describe("From create_chat_session"),
1039
+ content: z2.string().min(1).max(5e3)
1040
+ }),
1041
+ outputSchema: z2.looseObject({
1042
+ messageId: z2.string(),
1043
+ sessionStatus: z2.string()
1044
+ }),
1045
+ annotations: VISITOR
1259
1046
  },
1260
- input: {
1261
- border: '1px solid #d1d5db',
1262
- borderRadius: '6px',
1263
- padding: '0.75rem',
1264
- fontSize: '1rem',
1047
+ ({ sessionId, content }) => run(async () => {
1048
+ const r = await api.widget().sendMessage(sessionId, content);
1049
+ return { messageId: r.message.id, sessionStatus: r.session.status };
1050
+ })
1051
+ );
1052
+ server.registerTool(
1053
+ "get_chat_messages",
1054
+ {
1055
+ title: "Read chat messages",
1056
+ description: "Read a chat session's messages, including agent replies from Slack (widget key).",
1057
+ inputSchema: z2.object({
1058
+ sessionId: z2.string().min(1),
1059
+ limit: z2.number().int().min(1).max(100).default(50),
1060
+ offset: z2.number().int().min(0).default(0)
1061
+ }),
1062
+ outputSchema: z2.object({
1063
+ sessionId: z2.string(),
1064
+ messages: z2.array(loose)
1065
+ }),
1066
+ annotations: { ...READ, openWorldHint: true }
1265
1067
  },
1266
- button: {
1267
- background: '#3b82f6',
1268
- color: 'white',
1269
- padding: '0.75rem 1.5rem',
1270
- borderRadius: '6px',
1271
- border: 'none',
1272
- cursor: 'pointer',
1068
+ ({ sessionId, limit, offset }) => run(async () => {
1069
+ const messages = await api.widget().getChatMessages(sessionId, limit, offset);
1070
+ return {
1071
+ sessionId,
1072
+ messages: messages.map((m) => ({
1073
+ id: m.id,
1074
+ author: m.author,
1075
+ authorName: m.authorData?.name,
1076
+ content: m.content,
1077
+ timestamp: String(m.timestamp),
1078
+ attachments: m.attachments?.length ?? 0
1079
+ }))
1080
+ };
1081
+ })
1082
+ );
1083
+ server.registerTool(
1084
+ "close_chat_session",
1085
+ {
1086
+ title: "End chat session",
1087
+ description: "End a chat session as the visitor (widget key).",
1088
+ inputSchema: z2.object({ sessionId: z2.string().min(1) }),
1089
+ outputSchema: z2.looseObject({
1090
+ sessionId: z2.string(),
1091
+ status: z2.string()
1092
+ }),
1093
+ annotations: { ...VISITOR, idempotentHint: true }
1273
1094
  },
1274
- }}
1275
- />
1276
- \`\`\`
1277
-
1278
- ## CSS Class Reference
1279
-
1280
- All Channlize components use semantic CSS classes:
1281
-
1282
- **Form:**
1283
- - \`.channlize-form\` - Form container
1284
- - \`.channlize-form-success\` - Success message container
1285
- - \`.channlize-field\` - Field wrapper
1286
- - \`.channlize-error\` - Error message
1287
-
1288
- **Chat:**
1289
- - \`.channlize-chat-container\` - Main container
1290
- - \`.channlize-chat-header\` - Header section
1291
- - \`.channlize-chat-messages\` - Messages container
1292
- - \`.channlize-message\` - Individual message
1293
- - \`.channlize-message-user\` - User message
1294
- - \`.channlize-message-agent\` - Agent message
1295
- - \`.channlize-chat-input-container\` - Input area
1296
-
1297
- ## Dark Mode Example
1298
-
1299
- \`\`\`tsx
1300
- const darkStyles = {
1301
- form: {
1302
- background: '#1f2937',
1303
- color: '#f9fafb',
1304
- },
1305
- input: {
1306
- background: '#374151',
1307
- color: '#f9fafb',
1308
- border: '1px solid #4b5563',
1309
- },
1310
- button: {
1311
- background: '#3b82f6',
1312
- color: 'white',
1313
- },
1314
- };
1315
-
1316
- <Form styles={darkStyles} />
1317
- \`\`\`
1318
- `
1319
- },
1320
- {
1321
- name: "handle-webhooks",
1322
- description: "Guide for integrating Channlize webhooks into custom workflows",
1323
- getPrompt: () => `# Integrating Channlize Webhooks
1324
-
1325
- Channlize can send webhook events to your backend for custom workflows and integrations.
1326
-
1327
- ## Available Webhook Events
1328
-
1329
- - \`conversation.created\` - New contact form or chat session started
1330
- - \`message.created\` - New message in a conversation
1331
- - \`conversation.closed\` - Conversation marked as closed
1332
- - \`agent.assigned\` - Agent assigned to conversation
1333
-
1334
- ## Setting Up Webhooks
1335
-
1336
- ### 1. Configure Webhook URL
1337
-
1338
- In your Channlize dashboard:
1339
- 1. Navigate to Project Settings \u2192 Webhooks
1340
- 2. Add your webhook endpoint URL
1341
- 3. Select which events to receive
1342
- 4. Save your secret key for verification
1343
-
1344
- ### 2. Create Webhook Handler (Next.js API Route)
1345
-
1346
- \`\`\`typescript
1347
- // app/api/webhooks/channlize/route.ts
1348
- import { NextRequest, NextResponse } from 'next/server';
1349
- import crypto from 'crypto';
1350
-
1351
- const WEBHOOK_SECRET = process.env.CHANNLIZE_WEBHOOK_SECRET!;
1352
-
1353
- function verifySignature(payload: string, signature: string): boolean {
1354
- const hmac = crypto.createHmac('sha256', WEBHOOK_SECRET);
1355
- const digest = hmac.update(payload).digest('hex');
1356
- return crypto.timingSafeEqual(
1357
- Buffer.from(signature),
1358
- Buffer.from(digest)
1095
+ ({ sessionId }) => run(async () => {
1096
+ const s = await api.widget().closeChatSession(sessionId);
1097
+ return { sessionId: s.id ?? sessionId, status: s.status };
1098
+ })
1359
1099
  );
1360
1100
  }
1361
1101
 
1362
- export async function POST(req: NextRequest) {
1363
- const signature = req.headers.get('x-channlize-signature');
1364
- const payload = await req.text();
1365
-
1366
- if (!signature || !verifySignature(payload, signature)) {
1367
- return NextResponse.json(
1368
- { error: 'Invalid signature' },
1369
- { status: 401 }
1370
- );
1371
- }
1372
-
1373
- const event = JSON.parse(payload);
1374
-
1375
- // Handle different event types
1376
- switch (event.type) {
1377
- case 'conversation.created':
1378
- await handleNewConversation(event.data);
1379
- break;
1380
-
1381
- case 'message.created':
1382
- await handleNewMessage(event.data);
1383
- break;
1384
-
1385
- case 'conversation.closed':
1386
- await handleConversationClosed(event.data);
1387
- break;
1388
-
1389
- default:
1390
- console.log('Unhandled event type:', event.type);
1391
- }
1392
-
1393
- return NextResponse.json({ received: true });
1394
- }
1395
-
1396
- async function handleNewConversation(data: any) {
1397
- // Example: Log to analytics
1398
- await analytics.track('support_conversation_started', {
1399
- conversationId: data.conversation.id,
1400
- type: data.conversation.type, // 'contact_form' or 'chat'
1401
- customerEmail: data.conversation.email,
1402
- });
1403
-
1404
- // Example: Notify sales team for high-value customers
1405
- if (data.conversation.metadata?.customerTier === 'enterprise') {
1406
- await notifySalesTeam({
1407
- conversationId: data.conversation.id,
1408
- customerEmail: data.conversation.email,
1409
- message: data.conversation.initialMessage,
1410
- });
1411
- }
1412
- }
1413
-
1414
- async function handleNewMessage(data: any) {
1415
- // Example: Auto-tag based on content
1416
- const message = data.message.content.toLowerCase();
1417
-
1418
- if (message.includes('bug') || message.includes('error')) {
1419
- await tagConversation(data.conversation.id, 'bug');
1102
+ // src/http.ts
1103
+ var import_node_http = require("http");
1104
+ var import_server = require("@modelcontextprotocol/server");
1105
+ var LOCAL_HOSTS = /* @__PURE__ */ new Set(["127.0.0.1", "localhost", "::1"]);
1106
+ async function toRequest(req, origin) {
1107
+ const headers = new Headers();
1108
+ for (const [k, v] of Object.entries(req.headers)) {
1109
+ if (Array.isArray(v)) v.forEach((x) => headers.append(k, x));
1110
+ else if (v !== void 0) headers.set(k, v);
1420
1111
  }
1421
-
1422
- if (message.includes('billing') || message.includes('payment')) {
1423
- await tagConversation(data.conversation.id, 'billing');
1424
- await assignToDepartment(data.conversation.id, 'billing');
1112
+ let body;
1113
+ if (req.method !== "GET" && req.method !== "HEAD") {
1114
+ const chunks = [];
1115
+ for await (const chunk of req) chunks.push(chunk);
1116
+ body = new Uint8Array(Buffer.concat(chunks));
1425
1117
  }
1426
-
1427
- // Example: Sentiment analysis
1428
- const sentiment = await analyzeSentiment(message);
1429
- if (sentiment === 'negative') {
1430
- await escalateConversation(data.conversation.id, 'high');
1431
- }
1432
- }
1433
-
1434
- async function handleConversationClosed(data: any) {
1435
- // Example: Send satisfaction survey
1436
- await sendSurveyEmail({
1437
- to: data.conversation.email,
1438
- conversationId: data.conversation.id,
1439
- resolutionTime: data.metrics.resolutionTime,
1118
+ const controller = new AbortController();
1119
+ req.on("close", () => {
1120
+ if (!req.complete) controller.abort();
1440
1121
  });
1441
-
1442
- // Example: Update CRM
1443
- await updateCRM({
1444
- email: data.conversation.email,
1445
- lastInteraction: new Date(),
1446
- supportTicketId: data.conversation.id,
1447
- resolved: true,
1122
+ return new Request(new URL(req.url ?? "/", origin), {
1123
+ method: req.method,
1124
+ headers,
1125
+ body,
1126
+ signal: controller.signal
1448
1127
  });
1449
1128
  }
1450
- \`\`\`
1451
-
1452
- ### 3. Express.js Example
1453
-
1454
- \`\`\`typescript
1455
- import express from 'express';
1456
- import crypto from 'crypto';
1457
-
1458
- const app = express();
1459
-
1460
- // Raw body needed for signature verification
1461
- app.use('/webhooks/channlize', express.raw({ type: 'application/json' }));
1462
-
1463
- app.post('/webhooks/channlize', (req, res) => {
1464
- const signature = req.headers['x-channlize-signature'];
1465
- const payload = req.body.toString();
1466
-
1467
- // Verify signature
1468
- const hmac = crypto.createHmac('sha256', process.env.CHANNLIZE_WEBHOOK_SECRET);
1469
- const digest = hmac.update(payload).digest('hex');
1470
-
1471
- if (signature !== digest) {
1472
- return res.status(401).json({ error: 'Invalid signature' });
1473
- }
1474
-
1475
- const event = JSON.parse(payload);
1476
-
1477
- // Handle event
1478
- handleEvent(event);
1479
-
1480
- res.json({ received: true });
1481
- });
1482
- \`\`\`
1483
-
1484
- ## Webhook Event Payload Examples
1485
-
1486
- ### conversation.created
1487
-
1488
- \`\`\`json
1489
- {
1490
- "type": "conversation.created",
1491
- "timestamp": "2025-01-15T10:00:00Z",
1492
- "data": {
1493
- "conversation": {
1494
- "id": "conv_123",
1495
- "type": "contact_form",
1496
- "status": "open",
1497
- "email": "customer@example.com",
1498
- "name": "John Doe",
1499
- "initialMessage": "I need help with...",
1500
- "metadata": {
1501
- "pageUrl": "https://example.com/contact",
1502
- "userAgent": "Mozilla/5.0..."
1503
- },
1504
- "createdAt": "2025-01-15T10:00:00Z"
1505
- }
1506
- }
1507
- }
1508
- \`\`\`
1509
-
1510
- ### message.created
1511
-
1512
- \`\`\`json
1513
- {
1514
- "type": "message.created",
1515
- "timestamp": "2025-01-15T10:05:00Z",
1516
- "data": {
1517
- "message": {
1518
- "id": "msg_456",
1519
- "conversationId": "conv_123",
1520
- "content": "Thanks for reaching out!",
1521
- "author": "agent",
1522
- "authorData": {
1523
- "name": "Sarah",
1524
- "email": "sarah@example.com"
1525
- },
1526
- "timestamp": "2025-01-15T10:05:00Z"
1527
- },
1528
- "conversation": {
1529
- "id": "conv_123",
1530
- "status": "open"
1129
+ async function startHttpServer(factory, options = {}) {
1130
+ const host = options.host ?? "127.0.0.1";
1131
+ const port = options.port ?? 3333;
1132
+ const path = options.path ?? "/mcp";
1133
+ const local = LOCAL_HOSTS.has(host);
1134
+ const handler = (0, import_server.createMcpHandler)(() => factory(), {
1135
+ onerror: (err) => console.error("[channlize-mcp]", err.message)
1136
+ });
1137
+ const server = (0, import_node_http.createServer)(async (req, res) => {
1138
+ try {
1139
+ const request = await toRequest(
1140
+ req,
1141
+ `http://${req.headers.host ?? `${host}:${port}`}`
1142
+ );
1143
+ const url2 = new URL(request.url);
1144
+ if (url2.pathname !== path) {
1145
+ res.writeHead(404, { "Content-Type": "text/plain" }).end(`Not found: use ${path}`);
1146
+ return;
1147
+ }
1148
+ const rejected = local ? (0, import_server.hostHeaderValidationResponse)(request, (0, import_server.localhostAllowedHostnames)()) ?? (0, import_server.originValidationResponse)(request, (0, import_server.localhostAllowedOrigins)()) : void 0;
1149
+ const response = rejected ?? await handler.fetch(request);
1150
+ res.writeHead(response.status, Object.fromEntries(response.headers));
1151
+ if (response.body) {
1152
+ for await (const chunk of response.body) {
1153
+ res.write(chunk);
1154
+ }
1155
+ }
1156
+ res.end();
1157
+ } catch (err) {
1158
+ console.error("[channlize-mcp]", err.message);
1159
+ if (!res.headersSent)
1160
+ res.writeHead(500, { "Content-Type": "text/plain" });
1161
+ res.end("Internal server error");
1531
1162
  }
1532
- }
1163
+ });
1164
+ await new Promise((resolve, reject) => {
1165
+ server.once("error", reject);
1166
+ server.listen(port, host, () => resolve());
1167
+ });
1168
+ const address = server.address();
1169
+ const actualPort = typeof address === "object" && address ? address.port : port;
1170
+ const shownHost = host.includes(":") ? `[${host}]` : host;
1171
+ return {
1172
+ url: `http://${shownHost}:${actualPort}${path}`,
1173
+ server,
1174
+ close: () => new Promise((r) => server.close(() => r()))
1175
+ };
1533
1176
  }
1534
- \`\`\`
1535
-
1536
- ## Use Cases
1537
-
1538
- 1. **CRM Integration**: Sync conversations to Salesforce, HubSpot, etc.
1539
- 2. **Analytics**: Track support metrics in your data warehouse
1540
- 3. **Auto-routing**: Assign conversations based on content analysis
1541
- 4. **Notifications**: Alert teams via SMS, PagerDuty for urgent issues
1542
- 5. **AI Enhancement**: Feed messages to AI for sentiment/intent analysis
1543
- 6. **Billing**: Track support usage for metered billing
1544
1177
 
1545
- ## Security Best Practices
1546
-
1547
- - Always verify webhook signatures
1548
- - Use HTTPS endpoints only
1549
- - Rotate webhook secrets periodically
1550
- - Implement rate limiting on webhook endpoints
1551
- - Log all webhook events for audit trail
1552
- `
1178
+ // src/index.ts
1179
+ var VERSION = true ? "0.3.0" : "0.0.0";
1180
+ var INSTRUCTIONS = `Channlize routes website conversations and app events to the team's Slack.
1181
+ - Inbox: list_conversations / get_conversation, then contacts. Replies and status changes happen in Slack or the dashboard.
1182
+ - Events (notify_event) post a Slack message per event key; list_event_definitions and list_event_deliveries explain what was sent or skipped.
1183
+ - Logs: query_logs searches log tracking; track_log records one.
1184
+ - Write tools need a server API key with the write scope; a 403 means the key is read-only.`;
1185
+ function buildServer(config, info = {}) {
1186
+ const api = new ChannlizeApi(resolveConfig(config));
1187
+ const server = new import_server2.McpServer(
1188
+ { name: info.name ?? "channlize", version: info.version ?? VERSION },
1189
+ { instructions: INSTRUCTIONS }
1190
+ );
1191
+ if (api.hasServerKey) {
1192
+ registerServerTools(server, api);
1193
+ registerServerPrompts(server);
1553
1194
  }
1554
- ];
1555
- function getPrompt(name) {
1556
- return prompts.find((p) => p.name === name);
1195
+ if (api.hasWidgetKey) registerWidgetTools(server, api);
1196
+ registerResources(server, api);
1197
+ registerGuidePrompts(server);
1198
+ return server;
1557
1199
  }
1558
- function listPrompts() {
1559
- return prompts;
1560
- }
1561
-
1562
- // src/index.ts
1563
1200
  var ChannlizeMCPServer = class {
1564
1201
  server;
1565
1202
  config;
1203
+ info;
1566
1204
  constructor(options = {}) {
1567
- this.config = options.config;
1568
- this.server = new import_server.Server(
1569
- {
1570
- name: options.name || "channlize-mcp",
1571
- version: options.version || "0.1.0"
1572
- },
1573
- {
1574
- capabilities: {
1575
- resources: {},
1576
- tools: {},
1577
- prompts: {}
1578
- }
1579
- }
1580
- );
1581
- this.setupHandlers();
1582
- }
1583
- setupHandlers() {
1584
- this.server.setRequestHandler(import_types.ListResourcesRequestSchema, async () => {
1585
- const resources2 = listResources();
1586
- return {
1587
- resources: resources2.map((r) => ({
1588
- uri: r.uri,
1589
- name: r.name,
1590
- description: r.description,
1591
- mimeType: r.mimeType
1592
- }))
1593
- };
1594
- });
1595
- this.server.setRequestHandler(import_types.ReadResourceRequestSchema, async (request) => {
1596
- const resource = getResource(request.params.uri);
1597
- if (!resource) {
1598
- throw new Error(`Resource not found: ${request.params.uri}`);
1599
- }
1600
- return {
1601
- contents: [
1602
- {
1603
- uri: resource.uri,
1604
- mimeType: resource.mimeType,
1605
- text: resource.getText()
1606
- }
1607
- ]
1608
- };
1609
- });
1610
- this.server.setRequestHandler(import_types.ListToolsRequestSchema, async () => {
1611
- const tools2 = listTools();
1612
- return {
1613
- tools: tools2.map((t) => ({
1614
- name: t.name,
1615
- description: t.description,
1616
- inputSchema: t.inputSchema
1617
- }))
1618
- };
1619
- });
1620
- this.server.setRequestHandler(import_types.CallToolRequestSchema, async (request) => {
1621
- const tool = getTool(request.params.name);
1622
- if (!tool) {
1623
- throw new Error(`Tool not found: ${request.params.name}`);
1624
- }
1625
- if (!this.config?.apiKey) {
1626
- throw new Error(
1627
- "Channlize API key required. Please configure the MCP server with your API credentials."
1628
- );
1629
- }
1630
- const context = {
1631
- config: this.config
1632
- };
1633
- try {
1634
- const result = await tool.handler(request.params.arguments || {}, context);
1635
- return {
1636
- content: [
1637
- {
1638
- type: "text",
1639
- text: JSON.stringify(result, null, 2)
1640
- }
1641
- ]
1642
- };
1643
- } catch (error) {
1644
- return {
1645
- content: [
1646
- {
1647
- type: "text",
1648
- text: JSON.stringify(
1649
- {
1650
- success: false,
1651
- error: error.message || "Unknown error",
1652
- code: error.code,
1653
- statusCode: error.statusCode
1654
- },
1655
- null,
1656
- 2
1657
- )
1658
- }
1659
- ],
1660
- isError: true
1661
- };
1662
- }
1663
- });
1664
- this.server.setRequestHandler(import_types.ListPromptsRequestSchema, async () => {
1665
- const prompts2 = listPrompts();
1666
- return {
1667
- prompts: prompts2.map((p) => ({
1668
- name: p.name,
1669
- description: p.description,
1670
- arguments: p.arguments
1671
- }))
1672
- };
1673
- });
1674
- this.server.setRequestHandler(import_types.GetPromptRequestSchema, async (request) => {
1675
- const prompt = getPrompt(request.params.name);
1676
- if (!prompt) {
1677
- throw new Error(`Prompt not found: ${request.params.name}`);
1678
- }
1679
- const args2 = request.params.arguments;
1680
- const text = prompt.getPrompt(args2);
1681
- return {
1682
- description: prompt.description,
1683
- messages: [
1684
- {
1685
- role: "user",
1686
- content: {
1687
- type: "text",
1688
- text
1689
- }
1690
- }
1691
- ]
1692
- };
1693
- });
1694
- }
1695
- /**
1696
- * Set or update the Channlize configuration
1697
- */
1698
- setConfig(config2) {
1699
- this.config = config2;
1205
+ this.config = resolveConfig(options.config ?? {});
1206
+ this.info = { name: options.name, version: options.version };
1207
+ this.server = buildServer(this.config, this.info);
1700
1208
  }
1701
- /**
1702
- * Get the underlying MCP server instance
1703
- */
1209
+ /** The underlying `McpServer`. */
1704
1210
  getServer() {
1705
1211
  return this.server;
1706
1212
  }
1707
- /**
1708
- * Start the server with stdio transport
1709
- */
1213
+ /** Serve over stdio (what desktop and IDE clients launch). */
1710
1214
  async runStdio() {
1711
- const transport = new import_stdio.StdioServerTransport();
1712
- await this.server.connect(transport);
1215
+ await this.server.connect(new import_stdio.StdioServerTransport());
1713
1216
  }
1714
1217
  /**
1715
- * Close the server
1218
+ * Serve Streamable HTTP at `http://<host>:<port>/mcp` (default
1219
+ * 127.0.0.1:3333). Each request gets a fresh server; nothing is shared.
1716
1220
  */
1221
+ async runHttp(options = {}) {
1222
+ return startHttpServer(() => buildServer(this.config, this.info), options);
1223
+ }
1717
1224
  async close() {
1718
1225
  await this.server.close();
1719
1226
  }
1720
1227
  };
1721
1228
 
1722
1229
  // src/server.ts
1723
- var args = process.argv.slice(2);
1724
- var getArg = (name) => {
1725
- const index = args.findIndex((arg) => arg === `--${name}` || arg === `-${name[0]}`);
1726
- return index >= 0 && index + 1 < args.length ? args[index + 1] : void 0;
1727
- };
1728
- if (args.includes("--help") || args.includes("-h")) {
1729
- console.log(`
1730
- Channlize MCP Server
1230
+ var HELP = `Channlize MCP server ${VERSION}
1731
1231
 
1732
1232
  Usage: channlize-mcp [options]
1733
1233
 
1234
+ Keys (flags override environment variables):
1235
+ --server-api-key <key> Server API key, ch_live_\u2026 CHANNLIZE_SERVER_API_KEY
1236
+ --widget-key <key> Public widget key, wk_\u2026 CHANNLIZE_WIDGET_KEY
1237
+ --api-key <key> Either kind, by prefix CHANNLIZE_API_KEY
1238
+ --project-id <id> Project (default: the key's first project)
1239
+ CHANNLIZE_PROJECT_ID
1734
1240
  Options:
1735
- --api-key <key> Channlize API key (widget key) [required]
1736
- --project-id <id> Channlize project ID
1737
- --base-url <url> Channlize API base URL (default: https://api.channlize.com)
1738
- --timeout <ms> Request timeout in milliseconds (default: 10000)
1739
- -h, --help Show this help message
1740
-
1741
- Environment Variables:
1742
- CHANNLIZE_API_KEY Alternative to --api-key
1743
- CHANNLIZE_PROJECT_ID Alternative to --project-id
1744
- CHANNLIZE_BASE_URL Alternative to --base-url
1745
- CHANNLIZE_TIMEOUT Alternative to --timeout
1746
-
1747
- Examples:
1748
- # Using command line arguments
1749
- channlize-mcp --api-key wk_123abc --project-id proj_456def
1750
-
1751
- # Using environment variables
1752
- export CHANNLIZE_API_KEY=wk_123abc
1753
- export CHANNLIZE_PROJECT_ID=proj_456def
1754
- channlize-mcp
1241
+ --base-url <url> API URL (default https://api.channlize.com)
1242
+ CHANNLIZE_BASE_URL
1243
+ --timeout <ms> Request timeout (default 10000)
1244
+ CHANNLIZE_TIMEOUT
1245
+ --transport <t> stdio (default) or http CHANNLIZE_MCP_TRANSPORT
1246
+ --host <host> HTTP bind address (default 127.0.0.1)
1247
+ --port <port> HTTP port (default 3333) CHANNLIZE_MCP_PORT
1248
+ -v, --version Print the version
1249
+ -h, --help Show this help
1250
+
1251
+ The server API key enables the inbox, contact, Events and log tools (read
1252
+ scope for reads, write scope to send). The widget key adds visitor tools
1253
+ (contact form, chat). Create keys in the Channlize dashboard under
1254
+ SDK & Integration \u2192 API keys.
1255
+
1256
+ Claude Code:
1257
+ claude mcp add channlize --env CHANNLIZE_SERVER_API_KEY=ch_live_\u2026 -- npx -y @channlize/mcp
1258
+
1259
+ Docs: https://github.com/channlize/sdk/tree/main/packages/mcp
1260
+ `;
1261
+ function fail(message) {
1262
+ console.error(
1263
+ `channlize-mcp: ${message}
1755
1264
 
1756
- Configuration in MCP Clients (e.g., Claude Desktop):
1757
- {
1758
- "mcpServers": {
1759
- "channlize": {
1760
- "command": "npx",
1761
- "args": [
1762
- "@channlize/mcp",
1763
- "--api-key",
1764
- "your-api-key",
1765
- "--project-id",
1766
- "your-project-id"
1767
- ]
1768
- }
1769
- }
1265
+ Run 'channlize-mcp --help' for usage.`
1266
+ );
1267
+ process.exit(1);
1268
+ }
1269
+ async function main() {
1270
+ let values;
1271
+ try {
1272
+ ({ values } = (0, import_node_util.parseArgs)({
1273
+ options: {
1274
+ "server-api-key": { type: "string" },
1275
+ "widget-key": { type: "string" },
1276
+ "api-key": { type: "string" },
1277
+ "project-id": { type: "string" },
1278
+ "base-url": { type: "string" },
1279
+ timeout: { type: "string" },
1280
+ transport: { type: "string" },
1281
+ host: { type: "string" },
1282
+ port: { type: "string" },
1283
+ help: { type: "boolean", short: "h" },
1284
+ version: { type: "boolean", short: "v" }
1285
+ },
1286
+ strict: true
1287
+ }));
1288
+ } catch (err) {
1289
+ fail(err.message);
1770
1290
  }
1771
-
1772
- Or with environment variables:
1773
- {
1774
- "mcpServers": {
1775
- "channlize": {
1776
- "command": "npx",
1777
- "args": ["@channlize/mcp"],
1778
- "env": {
1779
- "CHANNLIZE_API_KEY": "your-api-key",
1780
- "CHANNLIZE_PROJECT_ID": "your-project-id"
1781
- }
1782
- }
1291
+ if (values.help) {
1292
+ console.log(HELP);
1293
+ return;
1294
+ }
1295
+ if (values.version) {
1296
+ console.log(VERSION);
1297
+ return;
1298
+ }
1299
+ const str = (k) => values[k];
1300
+ const env = configFromEnv();
1301
+ const timeout = str("timeout");
1302
+ const config = {
1303
+ serverApiKey: str("server-api-key") ?? env.serverApiKey,
1304
+ widgetKey: str("widget-key") ?? env.widgetKey,
1305
+ apiKey: str("api-key") ?? env.apiKey,
1306
+ projectId: str("project-id") ?? env.projectId,
1307
+ baseUrl: str("base-url") ?? env.baseUrl,
1308
+ timeout: timeout !== void 0 ? Number(timeout) : env.timeout
1309
+ };
1310
+ const transport = str("transport") ?? process.env.CHANNLIZE_MCP_TRANSPORT ?? "stdio";
1311
+ if (transport !== "stdio" && transport !== "http") {
1312
+ fail(`unknown transport "${transport}": use stdio or http`);
1313
+ }
1314
+ let server;
1315
+ try {
1316
+ server = new ChannlizeMCPServer({ config });
1317
+ } catch (err) {
1318
+ if (err instanceof ConfigError) fail(err.message);
1319
+ throw err;
1320
+ }
1321
+ if (transport === "http") {
1322
+ const port = Number(str("port") ?? process.env.CHANNLIZE_MCP_PORT ?? 3333);
1323
+ if (!Number.isInteger(port) || port < 0 || port > 65535) {
1324
+ fail(`invalid port "${str("port") ?? process.env.CHANNLIZE_MCP_PORT}"`);
1783
1325
  }
1326
+ const { url: url2, close } = await server.runHttp({ host: str("host"), port });
1327
+ console.error(`Channlize MCP server listening on ${url2}`);
1328
+ const stop2 = async () => {
1329
+ await close();
1330
+ process.exit(0);
1331
+ };
1332
+ process.on("SIGINT", stop2);
1333
+ process.on("SIGTERM", stop2);
1334
+ return;
1784
1335
  }
1785
-
1786
- Resources:
1787
- channlize://schema/contact-form - Contact form JSON schema
1788
- channlize://schema/chat-session - Chat session JSON schema
1789
- channlize://docs/api-reference - Full API documentation
1790
- channlize://docs/quick-start - Quick start guide
1791
- channlize://docs/react-components - React components guide
1792
-
1793
- Tools:
1794
- submit_contact_form - Submit a contact form inquiry
1795
- create_chat_session - Create a new chat session
1796
- send_message - Send a message in a chat session
1797
- get_chat_messages - Retrieve chat message history
1798
- close_chat_session - Close an active chat session
1799
-
1800
- Prompts:
1801
- integrate-contact-form - Guide for adding contact form to React app
1802
- setup-live-chat - Guide for implementing live chat widget
1803
- customize-styling - Guide for theming components
1804
- handle-webhooks - Guide for webhook integration
1805
-
1806
- For more information, visit: https://github.com/channlize/sdk
1807
- `);
1808
- process.exit(0);
1809
- }
1810
- var config = {
1811
- apiKey: getArg("api-key") || process.env.CHANNLIZE_API_KEY || "",
1812
- projectId: getArg("project-id") || process.env.CHANNLIZE_PROJECT_ID,
1813
- baseUrl: getArg("base-url") || process.env.CHANNLIZE_BASE_URL,
1814
- timeout: parseInt(
1815
- getArg("timeout") || process.env.CHANNLIZE_TIMEOUT || "10000",
1816
- 10
1817
- )
1818
- };
1819
- if (!config.apiKey) {
1820
- console.error(`
1821
- Error: Channlize API key is required
1822
-
1823
- Please provide your API key using either:
1824
- --api-key <key>
1825
- or set CHANNLIZE_API_KEY environment variable
1826
-
1827
- Get your API key from your Channlize dashboard.
1828
-
1829
- Run 'channlize-mcp --help' for more information.
1830
- `);
1831
- process.exit(1);
1336
+ const stop = async () => {
1337
+ await server.close();
1338
+ process.exit(0);
1339
+ };
1340
+ process.on("SIGINT", stop);
1341
+ process.on("SIGTERM", stop);
1342
+ await server.runStdio();
1832
1343
  }
1833
- var server = new ChannlizeMCPServer({
1834
- name: "channlize-mcp",
1835
- version: "0.1.0",
1836
- config
1837
- });
1838
- process.on("SIGINT", async () => {
1839
- await server.close();
1840
- process.exit(0);
1841
- });
1842
- process.on("SIGTERM", async () => {
1843
- await server.close();
1844
- process.exit(0);
1845
- });
1846
- server.runStdio().catch((error) => {
1847
- console.error("Failed to start Channlize MCP server:", error);
1344
+ main().catch((err) => {
1345
+ console.error("Failed to start the Channlize MCP server:", err.message);
1848
1346
  process.exit(1);
1849
1347
  });
1850
1348
  //# sourceMappingURL=server.js.map