iwgt 2.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.
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ export {};
3
+ //# sourceMappingURL=index.d.ts.map
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env node
2
+ import { WidgetServer } from './server.js';
3
+ const server = new WidgetServer();
4
+ server.run().catch(console.error);
5
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * HTTP/SSE сервер для удаленного доступа к MCP серверу виджетов InSales
4
+ * Использует SSE (Server-Sent Events) транспорт для работы через HTTP
5
+ */
6
+ export {};
7
+ //# sourceMappingURL=server-http.d.ts.map
@@ -0,0 +1,165 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * HTTP/SSE сервер для удаленного доступа к MCP серверу виджетов InSales
4
+ * Использует SSE (Server-Sent Events) транспорт для работы через HTTP
5
+ */
6
+ import { SSEServerTransport } from '@modelcontextprotocol/sdk/server/sse.js';
7
+ import { createServer } from 'http';
8
+ import { fileURLToPath } from 'url';
9
+ import { dirname } from 'path';
10
+ const __filename = fileURLToPath(import.meta.url);
11
+ const __dirname = dirname(__filename);
12
+ // Импортируем класс WidgetServer
13
+ import { WidgetServer } from './server.js';
14
+ // Получаем порт из переменной окружения или используем 3000 по умолчанию
15
+ const PORT = process.env.PORT ? parseInt(process.env.PORT) : 3000;
16
+ const HOST = process.env.HOST || '0.0.0.0';
17
+ // API ключ для аутентификации (опционально)
18
+ const API_KEY = process.env.MCP_API_KEY;
19
+ /**
20
+ * Проверка API ключа
21
+ */
22
+ function checkAuth(req) {
23
+ if (!API_KEY) {
24
+ return true; // Если API ключ не установлен, пропускаем всех
25
+ }
26
+ const authHeader = req.headers['authorization'];
27
+ if (!authHeader) {
28
+ return false;
29
+ }
30
+ const token = authHeader.replace('Bearer ', '');
31
+ return token === API_KEY;
32
+ }
33
+ /**
34
+ * Создание HTTP сервера с поддержкой SSE
35
+ */
36
+ const httpServer = createServer(async (req, res) => {
37
+ // CORS headers
38
+ res.setHeader('Access-Control-Allow-Origin', '*');
39
+ res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
40
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
41
+ if (req.method === 'OPTIONS') {
42
+ res.writeHead(200);
43
+ res.end();
44
+ return;
45
+ }
46
+ // Проверка аутентификации
47
+ if (!checkAuth(req)) {
48
+ res.writeHead(401, { 'Content-Type': 'application/json' });
49
+ res.end(JSON.stringify({ error: 'Unauthorized' }));
50
+ return;
51
+ }
52
+ // Health check endpoint
53
+ if (req.url === '/health' || req.url === '/') {
54
+ res.writeHead(200, { 'Content-Type': 'application/json' });
55
+ res.end(JSON.stringify({
56
+ status: 'ok',
57
+ service: 'InSales Widgets MCP Server',
58
+ version: '2.3.0',
59
+ transport: 'SSE',
60
+ endpoints: {
61
+ sse: '/sse',
62
+ message: '/message',
63
+ health: '/health'
64
+ }
65
+ }));
66
+ return;
67
+ }
68
+ // SSE endpoint
69
+ if (req.url === '/sse' && req.method === 'GET') {
70
+ console.log('📡 New SSE connection established');
71
+ // Настройка SSE заголовков
72
+ res.writeHead(200, {
73
+ 'Content-Type': 'text/event-stream',
74
+ 'Cache-Control': 'no-cache',
75
+ 'Connection': 'keep-alive',
76
+ });
77
+ // Создаем новый MCP сервер для этого соединения
78
+ const widgetServer = new WidgetServer();
79
+ const transport = new SSEServerTransport('/message', res);
80
+ await widgetServer['server'].connect(transport);
81
+ // Обработка закрытия соединения
82
+ req.on('close', () => {
83
+ console.log('📡 SSE connection closed');
84
+ transport.close();
85
+ });
86
+ return;
87
+ }
88
+ // Message endpoint для отправки сообщений
89
+ if (req.url === '/message' && req.method === 'POST') {
90
+ let body = '';
91
+ req.on('data', (chunk) => {
92
+ body += chunk.toString();
93
+ });
94
+ req.on('end', () => {
95
+ try {
96
+ const message = JSON.parse(body);
97
+ // SSE транспорт обработает это сообщение
98
+ res.writeHead(200, { 'Content-Type': 'application/json' });
99
+ res.end(JSON.stringify({ status: 'ok' }));
100
+ }
101
+ catch (error) {
102
+ res.writeHead(400, { 'Content-Type': 'application/json' });
103
+ res.end(JSON.stringify({ error: 'Invalid JSON' }));
104
+ }
105
+ });
106
+ return;
107
+ }
108
+ // 404 для неизвестных путей
109
+ res.writeHead(404, { 'Content-Type': 'application/json' });
110
+ res.end(JSON.stringify({ error: 'Not found' }));
111
+ });
112
+ // Запуск сервера
113
+ httpServer.listen(PORT, HOST, () => {
114
+ console.log(`
115
+ ╔════════════════════════════════════════════════════════════════╗
116
+ ║ ║
117
+ ║ 🚀 InSales Widgets MCP Server (HTTP/SSE) ║
118
+ ║ ║
119
+ ╚════════════════════════════════════════════════════════════════╝
120
+
121
+ 📡 Server running at:
122
+ - Local: http://localhost:${PORT}
123
+ - Network: http://${HOST}:${PORT}
124
+
125
+ 🔌 Endpoints:
126
+ - SSE: http://localhost:${PORT}/sse
127
+ - Message: http://localhost:${PORT}/message
128
+ - Health: http://localhost:${PORT}/health
129
+
130
+ ${API_KEY ? '🔐 Authentication: ENABLED (API Key required)' : '⚠️ Authentication: DISABLED (set MCP_API_KEY to enable)'}
131
+
132
+ 📝 Environment variables:
133
+ - PORT=${PORT}
134
+ - HOST=${HOST}
135
+ - MCP_API_KEY=${API_KEY ? '***' : 'not set'}
136
+
137
+ 💡 To connect from Cursor:
138
+ Add to your MCP settings (settings.json):
139
+ {
140
+ "mcpServers": {
141
+ "insales-widgets-remote": {
142
+ "url": "http://your-vps-ip:${PORT}/sse"${API_KEY ? ',\n "headers": {\n "Authorization": "Bearer YOUR_API_KEY"\n }' : ''}
143
+ }
144
+ }
145
+ }
146
+
147
+ Press Ctrl+C to stop the server
148
+ `);
149
+ });
150
+ // Graceful shutdown
151
+ process.on('SIGTERM', () => {
152
+ console.log('\n🛑 Shutting down gracefully...');
153
+ httpServer.close(() => {
154
+ console.log('✅ Server closed');
155
+ process.exit(0);
156
+ });
157
+ });
158
+ process.on('SIGINT', () => {
159
+ console.log('\n🛑 Shutting down gracefully...');
160
+ httpServer.close(() => {
161
+ console.log('✅ Server closed');
162
+ process.exit(0);
163
+ });
164
+ });
165
+ //# sourceMappingURL=server-http.js.map
@@ -0,0 +1,8 @@
1
+ export declare class WidgetServer {
2
+ private server;
3
+ constructor();
4
+ private setupHandlers;
5
+ private createWidget;
6
+ run(): Promise<void>;
7
+ }
8
+ //# sourceMappingURL=server.d.ts.map