@channel.io/channel-talk-integration-mcp
Version:
Channel Talk Integration MCP - Installation guides for Channel Talk SDK across multiple platforms
462 lines (390 loc) • 15.5 kB
JavaScript
import { z } from "zod";
export function registerGetWebGuideTool(server) {
server.tool("get_web_guide", `case1: 유저가 웹사이트에 채널톡을 설치하는 방법을 알고 싶다고 말하면 이 툴을 호출합니다.
case2: 이전 툴의 next_step에서 get_web_guide를 호출해야할 경우 이 툴을 호출합니다.`, {
language: z
.enum(["ko", "en"])
.optional()
.describe("Language for the guide. Use 'en' for English, defaults to Korean if not specified"),
}, (args) => {
try {
const language = args.language;
const result = language === "en" ? getEnglishWebGuide() : getKoreanWebGuide();
return {
content: [
{
type: "text",
text: JSON.stringify(result, null, 2),
},
],
};
}
catch (error) {
const message = error instanceof Error ? error.message : String(error);
throw new Error(`Failed to execute get_web_guide: ${message}`);
}
});
console.log("Registered tool: get_web_guide");
}
function getKoreanWebGuide() {
return {
result: `
채널톡 JavaScript SDK를 웹사이트에 설치하는 방법을 안내합니다. 아래 2가지 방법 중 프로젝트 상황에 맞는 방식을 선택하세요.
**다음 경우에 선택하세요:**
- 여러 페이지로 구성된 웹사이트 (MPA - Multi-Page Application)
- 각 페이지 요청 시 새로운 정적 리소스를 로드하는 구조
- HTML 파일에 직접 스크립트 삽입이 가능한 환경
- 빠른 프로토타이핑이나 테스트가 필요한 경우
- WordPress, Wix 등 CMS 기반 웹사이트
**다음 경우에 선택하세요:**
- React, Vue, Angular 등 모던 프론트엔드 프레임워크 사용
- TypeScript 프로젝트 (타입 안정성 필요)
- Webpack, Vite 등 번들러를 사용하는 프로젝트
- 컴포넌트 기반 개발 환경
- npm/yarn/pnpm 패키지 매니저 사용
---
${getScriptTagExample()}
${getSpaExample()}
---
${getNpmInstallExample()}
---
- **멤버 해시 사용 권장**: 예측 가능한 memberId 사용 시 보안 위험
- 실제 프로덕션에서는 서버에서 생성한 해시값 사용 필요
SPA에서 워크플로우와 마케팅 기능을 완전히 활용하려면:
${getSpaAdditionalSettings()}
${getMarketingEvents()}
---
1. **환경 분석**: MPA/SPA 구조 확인
2. **설치 방식 결정**: 직접 로드 vs NPM 모듈
3. **플러그인 키 준비**: "YOUR_PLUGIN_KEY"를 실제 키로 교체
4. **코드 구현**: 선택한 방식에 따라 구현
5. **유저 타입 설정**: 익명 vs 멤버 유저 결정
6. **유저 상태 관리**: 로그인/로그아웃/정보변경 시 부트 재시작 로직 구현 (SPA 필수)
7. **이벤트 설정**: 필요한 비즈니스 이벤트 추가
8. **보안 강화 검토**: 고객 정보 연동 시 멤버 해시 기능 사용할지 유저에게 물어보기
- memberId나 프로필 정보를 사용하는 경우 **보안 위험** 존재
- 예측 가능한 memberId 사용 시 제3자가 고객 정보 탈취 가능
- **멤버 해시 사용 시 장점**: HMAC-SHA256 암호화를 통한 안전한 인증, 무단 접근 차단
- 보안 강화를 하겠다고 유저가 대답하면 get_member_hash_guide 툴 호출하여 상세 설정 방법 확인
9. **테스트**: 채널톡 버튼 정상 작동 확인
**⚡ 플러그인 키 발급 위치**: 채널톡 데스크 > 채널 설정 > 일반 설정 > 버튼 설치 및 설정 > 채널톡 버튼 설치
**📚 참고 문서**: https://developers.channel.io/reference/web-quickstart-kr`,
};
}
function getEnglishWebGuide() {
return {
result: `
This guide explains how to install the Channel Talk JavaScript SDK on your website. Choose the appropriate method from the 2 options below based on your project requirements.
**Choose this method if:**
- Multi-page application (MPA) website
- Structure that loads new static resources on each page request
- Environment where you can directly insert scripts into HTML files
- Quick prototyping or testing needed
- CMS-based websites like WordPress, Wix, etc.
### Option 2. NPM Module Usage
**Choose this method if:**
- Using modern frontend frameworks like React, Vue, Angular
- TypeScript project (type safety required)
- Projects using bundlers like Webpack, Vite
- Component-based development environment
- Using npm/yarn/pnpm package managers
---
## 📋 Option 1. Direct Load Installation
### MPA (General Website)
${getScriptTagExample()}
${getSpaExample()}
---
${getNpmInstallExample()}
---
- **Use Member Hash Recommended**: Security risk when using predictable memberId
- Use hash values generated from server in actual production
To fully utilize workflows and marketing features in SPA:
${getSpaAdditionalSettingsEn()}
${getMarketingEvents()}
---
1. **Environment Analysis**: Check MPA/SPA structure
2. **Installation Method Decision**: Direct load vs NPM module
3. **Plugin Key Preparation**: Replace "YOUR_PLUGIN_KEY" with actual key
4. **Code Implementation**: Implement according to chosen method
5. **User Type Setting**: Decide anonymous vs member user
6. **User State Management**: Implement boot restart logic for login/logout/info changes (SPA Required)
7. **Event Setup**: Add necessary business events
8. **Security Enhancement Review**: Ask user if they want to use member hash feature when integrating customer information
- **Security risks exist** when using memberId or profile information
- Third parties can steal customer information when using predictable memberId
- **Benefits of member hash**: Secure authentication through HMAC-SHA256 encryption, blocking unauthorized access
- If user agrees to enhance security, call get_member_hash_guide tool to check detailed setup methods
9. **Testing**: Verify Channel Talk button works properly
**⚡ Plugin Key Location**: Channel Talk Desk > Channel Settings > General Settings > Button Installation & Settings > Install Channel Talk Button
**📚 Reference Documentation**: https://developers.channel.io/reference/web-quickstart`,
};
}
// 공통 코드 예제들을 별도 함수로 분리
function getScriptTagExample() {
return `\`\`\`html
<!-- 1단계: HTML <body> 태그 내에 스크립트 추가 -->
<script>
(function(){var w=window;if(w.ChannelIO){return w.console.error("ChannelIO script included twice.");}var ch=function(){ch.c(arguments);};ch.q=[];ch.c=function(args){ch.q.push(args);};w.ChannelIO=ch;function l(){if(w.ChannelIOInitialized){return;}w.ChannelIOInitialized=true;var s=document.createElement("script");s.type="text/javascript";s.async=true;s.src="https://cdn.channel.io/plugin/ch-plugin-web.js";var x=document.getElementsByTagName("script")[0];if(x.parentNode){x.parentNode.insertBefore(s,x);}}if(document.readyState==="complete"){l();}else{w.addEventListener("DOMContentLoaded",l);w.addEventListener("load",l);}})();
</script>
<!-- 2단계: SDK 초기화 (익명 유저) -->
<script>
ChannelIO('boot', {
"pluginKey": "YOUR_PLUGIN_KEY" // 실제 플러그인 키로 교체 필요
});
</script>
<!-- 또는 멤버 유저인 경우 -->
<script>
ChannelIO('boot', {
"pluginKey": "YOUR_PLUGIN_KEY", // 실제 플러그인 키로 교체 필요
"memberId": "USER_MEMBER_ID", // 유저 고유 ID
"profile": {
"name": "사용자명",
"mobileNumber": "010-1234-5678",
"customField1": "커스텀값1"
}
});
</script>
\`\`\``;
}
function getSpaExample() {
return `\`\`\`javascript
// 1단계: ChannelService 클래스 생성
class ChannelService {
loadScript() {
(function(){var w=window;if(w.ChannelIO){return w.console.error("ChannelIO script included twice.");}var ch=function(){ch.c(arguments);};ch.q=[];ch.c=function(args){ch.q.push(args);};w.ChannelIO=ch;function l(){if(w.ChannelIOInitialized){return;}w.ChannelIOInitialized=true;var s=document.createElement("script");s.type="text/javascript";s.async=true;s.src="https://cdn.channel.io/plugin/ch-plugin-web.js";var x=document.getElementsByTagName("script")[0];if(x.parentNode){x.parentNode.insertBefore(s,x);}}if(document.readyState==="complete"){l();}else{w.addEventListener("DOMContentLoaded",l);w.addEventListener("load",l);}})();
}
boot(option) {
window.ChannelIO?.('boot', option);
}
shutdown() {
window.ChannelIO?.('shutdown');
}
showChannelButton() {
window.ChannelIO?.('showChannelButton');
}
hideChannelButton() {
window.ChannelIO?.('hideChannelButton');
}
}
// 2단계: 서비스 사용
const channelService = new ChannelService();
channelService.loadScript();
// 3단계: 부트 실행
channelService.boot({
"pluginKey": "YOUR_PLUGIN_KEY" // 실제 플러그인 키로 교체 필요
});
\`\`\``;
}
function getNpmInstallExample() {
return `\`\`\`bash
npm install @channel.io/channel-web-sdk-loader
yarn add @channel.io/channel-web-sdk-loader
pnpm i @channel.io/channel-web-sdk-loader
\`\`\`
\`\`\`javascript
// 2단계: 모듈 import 및 SDK 로드
import * as ChannelService from '@channel.io/channel-web-sdk-loader';
ChannelService.loadScript();
// 3단계: 부트 실행 (익명 유저)
ChannelService.boot({
"pluginKey": "YOUR_PLUGIN_KEY" // 실제 플러그인 키로 교체 필요
});
// 또는 멤버 유저인 경우
ChannelService.boot({
"pluginKey": "YOUR_PLUGIN_KEY", // 실제 플러그인 키로 교체 필요
"memberId": "USER_MEMBER_ID",
"profile": {
"name": "사용자명",
"mobileNumber": "010-1234-5678",
"customField1": "커스텀값1"
}
});
\`\`\``;
}
function getSpaAdditionalSettings() {
return `\`\`\`javascript
// 페이지 변경 시 호출
ChannelIO('setPage', window.location.href);
// 사용자 이벤트 트래킹
ChannelIO('track', 'Purchase', {
price: 29.99,
currency: 'USD'
});
// ⚠️ 중요: 유저 상태 변화 시 부트 재시작 필요
// 로그인 시 - 익명 유저에서 멤버 유저로 전환
function handleUserLogin(userInfo) {
ChannelIO('shutdown'); // 기존 세션 종료
ChannelIO('boot', {
"pluginKey": "YOUR_PLUGIN_KEY",
"memberId": userInfo.memberId,
"profile": {
"name": userInfo.name,
"mobileNumber": userInfo.phone,
"email": userInfo.email
}
});
}
// 로그아웃 시 - 멤버 유저에서 익명 유저로 전환
function handleUserLogout() {
ChannelIO('shutdown'); // 기존 세션 종료
ChannelIO('boot', {
"pluginKey": "YOUR_PLUGIN_KEY"
// memberId 없이 익명 유저로 부트
});
}
// 유저 정보 변경 시 - 프로필 업데이트를 위한 재부트
function handleUserInfoUpdate(updatedUserInfo) {
ChannelIO('shutdown'); // 기존 세션 종료
ChannelIO('boot', {
"pluginKey": "YOUR_PLUGIN_KEY",
"memberId": updatedUserInfo.memberId,
"profile": {
"name": updatedUserInfo.name,
"mobileNumber": updatedUserInfo.phone,
"email": updatedUserInfo.email
// 변경된 정보로 업데이트
}
});
}
\`\`\`
**🔄 실제 구현 예시 (React 기준):**
\`\`\`javascript
// React에서 사용자 상태 변화 감지 예시
import { useEffect } from 'react';
import * as ChannelService from '@channel.io/channel-web-sdk-loader';
function useChannelTalk(user) {
useEffect(() => {
// 사용자 상태가 변경될 때마다 실행
if (user) {
// 로그인된 상태
ChannelService.shutdown();
ChannelService.boot({
pluginKey: "YOUR_PLUGIN_KEY",
memberId: user.id,
profile: {
name: user.name,
mobileNumber: user.phone,
email: user.email
}
});
} else {
// 로그아웃된 상태
ChannelService.shutdown();
ChannelService.boot({
pluginKey: "YOUR_PLUGIN_KEY"
});
}
}, [user]); // user 상태가 변경될 때마다 재실행
}
\`\`\``;
}
function getSpaAdditionalSettingsEn() {
return `\`\`\`javascript
// Call when page changes
ChannelIO('setPage', window.location.href);
// User event tracking
ChannelIO('track', 'Purchase', {
price: 29.99,
currency: 'USD'
});
// ⚠️ Important: Need to restart boot when user state changes
// On Login - Switch from anonymous user to member user
function handleUserLogin(userInfo) {
ChannelIO('shutdown'); // Terminate existing session
ChannelIO('boot', {
"pluginKey": "YOUR_PLUGIN_KEY",
"memberId": userInfo.memberId,
"profile": {
"name": userInfo.name,
"mobileNumber": userInfo.phone,
"email": userInfo.email
}
});
}
// On Logout - Switch from member user to anonymous user
function handleUserLogout() {
ChannelIO('shutdown'); // Terminate existing session
ChannelIO('boot', {
"pluginKey": "YOUR_PLUGIN_KEY"
// Boot as anonymous user without memberId
});
}
// On User Info Update - Reboot for profile update
function handleUserInfoUpdate(updatedUserInfo) {
ChannelIO('shutdown'); // Terminate existing session
ChannelIO('boot', {
"pluginKey": "YOUR_PLUGIN_KEY",
"memberId": updatedUserInfo.memberId,
"profile": {
"name": updatedUserInfo.name,
"mobileNumber": updatedUserInfo.phone,
"email": updatedUserInfo.email
// Update with changed information
}
});
}
\`\`\`
**🔄 Real Implementation Example (React):**
\`\`\`javascript
// Example of detecting user state changes in React
import { useEffect } from 'react';
import * as ChannelService from '@channel.io/channel-web-sdk-loader';
function useChannelTalk(user) {
useEffect(() => {
// Execute whenever user state changes
if (user) {
// Logged in state
ChannelService.shutdown();
ChannelService.boot({
pluginKey: "YOUR_PLUGIN_KEY",
memberId: user.id,
profile: {
name: user.name,
mobileNumber: user.phone,
email: user.email
}
});
} else {
// Logged out state
ChannelService.shutdown();
ChannelService.boot({
pluginKey: "YOUR_PLUGIN_KEY"
});
}
}, [user]); // Re-execute when user state changes
}
\`\`\``;
}
function getMarketingEvents() {
return `\`\`\`javascript
// 주요 비즈니스 이벤트 트래킹
ChannelIO('track', 'ViewProduct', { productId: '123' });
ChannelIO('track', 'AddToCart', { productId: '123', quantity: 1 });
ChannelIO('track', 'Purchase', { orderId: 'ORD123', amount: 50000 });
\`\`\``;
}
//# sourceMappingURL=get-web-guide.tool.js.map