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