-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathdev-server.js
More file actions
230 lines (195 loc) · 6.98 KB
/
Copy pathdev-server.js
File metadata and controls
230 lines (195 loc) · 6.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
#!/usr/bin/env node
/**
* Development server for MCP resources
*
* Serves the generated ZIP file over HTTP and watches markdown files
* for changes, automatically rebuilding when needed.
*
* Usage: npm run dev
*
* To use a different port:
* PORT=3000 npm run dev
*
* Then update the MCP server command to match:
* pnpm run dev:local-resources (and update wrangler --var flag)
*/
import http from 'http';
import fs from 'fs';
import path from 'path';
import { spawn } from 'child_process';
const PORT = process.env.PORT || 8765;
const DIST_DIR = path.join(import.meta.dirname, '..', 'dist');
const SKILLS_ZIP_PATH = path.join(DIST_DIR, 'skills-mcp-resources.zip');
const SKILLS_DIR = path.join(DIST_DIR, 'skills');
// Directories to watch for changes
const WATCH_DIRS = [
path.join(import.meta.dirname, '..', 'llm-prompts'),
path.join(import.meta.dirname, '..', 'transformation-config'),
path.join(import.meta.dirname, '..', 'mcp-commands'),
path.join(import.meta.dirname, '..', 'basics'),
];
let isRebuilding = false;
let rebuildQueued = false;
/**
* Run the build script with local URLs
*/
function rebuild() {
if (isRebuilding) {
rebuildQueued = true;
return;
}
console.log('\n🔨 Rebuilding skills with local URLs...');
isRebuilding = true;
// Use local URL for skill downloads during development
const localSkillsUrl = `http://localhost:${PORT}/skills`;
const buildProcess = spawn('npm', ['run', 'build'], {
stdio: 'inherit',
cwd: path.join(import.meta.dirname, '..'),
env: { ...process.env, SKILLS_BASE_URL: localSkillsUrl },
shell: true
});
buildProcess.on('close', (code) => {
isRebuilding = false;
if (code === 0) {
console.log('✅ Rebuild complete!\n');
} else {
console.error(`❌ Build failed with code ${code}\n`);
}
// If another rebuild was queued, run it now
if (rebuildQueued) {
rebuildQueued = false;
rebuild();
}
});
}
/**
* Watch directories for file changes
*/
function setupWatchers() {
console.log('\n👀 Watching for changes in:');
WATCH_DIRS.forEach(dir => {
if (!fs.existsSync(dir)) {
console.log(` ⚠️ ${path.relative(path.join(import.meta.dirname, '..'), dir)} (not found, skipping)`);
return;
}
console.log(` 📁 ${path.relative(path.join(import.meta.dirname, '..'), dir)}`);
// Watch recursively
fs.watch(dir, { recursive: true }, (eventType, filename) => {
if (!filename) return;
// Trigger on markdown, JSON, or YAML files
if (filename.endsWith('.md') || filename.endsWith('.json') || filename.endsWith('.yaml') || filename.endsWith('.yml')) {
console.log(`\n📝 Changed: ${filename}`);
rebuild();
}
});
});
}
/**
* Helper to serve a ZIP file
*/
function serveZip(res, zipPath, filename) {
if (!fs.existsSync(zipPath)) {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end(`ZIP file not found: ${filename}. Run build first.`);
return;
}
const stat = fs.statSync(zipPath);
const fileSize = stat.size;
const fileStream = fs.createReadStream(zipPath);
res.writeHead(200, {
'Content-Type': 'application/zip',
'Content-Length': fileSize,
'Content-Disposition': `attachment; filename="${filename}"`,
'Cache-Control': 'no-cache, no-store, must-revalidate',
'Pragma': 'no-cache',
'Expires': '0'
});
fileStream.pipe(res);
console.log(`📦 Served ${filename} (${(fileSize / 1024).toFixed(1)} KB)`);
}
/**
* Create HTTP server to serve the ZIP files
*/
function createServer() {
const server = http.createServer((req, res) => {
// Serve individual skill ZIPs at /skills/{id}.zip
const skillMatch = req.url?.match(/^\/skills\/(.+\.zip)$/);
if (skillMatch) {
const skillFile = skillMatch[1];
const skillPath = path.join(SKILLS_DIR, skillFile);
serveZip(res, skillPath, skillFile);
return;
}
// Serve skill menu
if (req.url === '/skill-menu.json') {
const menuPath = path.join(SKILLS_DIR, 'skill-menu.json');
if (!fs.existsSync(menuPath)) {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('skill-menu.json not found. Run build first.');
return;
}
const content = fs.readFileSync(menuPath, 'utf8');
res.writeHead(200, {
'Content-Type': 'application/json',
'Cache-Control': 'no-cache',
});
res.end(content);
console.log(`📋 Served skill-menu.json`);
return;
}
// Serve skills bundle
if (req.url === '/skills-mcp-resources.zip' || req.url === '/') {
serveZip(res, SKILLS_ZIP_PATH, 'skills-mcp-resources.zip');
return;
}
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not found. Available endpoints:\n /skill-menu.json\n /skills-mcp-resources.zip\n /skills/{id}.zip');
});
server.listen(PORT, () => {
console.log('\n🚀 Development server started!');
console.log(`\n📍 Skills bundle: http://localhost:${PORT}/skills-mcp-resources.zip`);
console.log(`📍 Individual skill: http://localhost:${PORT}/skills/{id}.zip`);
console.log('\n💡 To use with MCP server, set environment variable:');
console.log(` POSTHOG_MCP_LOCAL_SKILLS_URL=http://localhost:${PORT}/skills-mcp-resources.zip`);
console.log(`\n📋 Skills menu: http://localhost:${PORT}/skill-menu.json`);
});
}
/**
* Main entry point
*/
async function main() {
console.log('🎯 PostHog MCP Skills Development Server');
console.log('=========================================');
// Initial build with local URLs
const localSkillsUrl = `http://localhost:${PORT}/skills`;
if (!fs.existsSync(SKILLS_ZIP_PATH)) {
console.log('\n⚠️ ZIP file not found. Running initial build...');
} else {
console.log('\n🔄 Rebuilding with local URLs...');
}
await new Promise((resolve) => {
const buildProcess = spawn('npm', ['run', 'build'], {
stdio: 'inherit',
cwd: path.join(import.meta.dirname, '..'),
env: { ...process.env, SKILLS_BASE_URL: localSkillsUrl },
shell: true
});
buildProcess.on('close', resolve);
});
// Start server
createServer();
// Setup file watchers
setupWatchers();
console.log('\n✨ Ready for development!');
console.log(' Press Ctrl+C to stop\n');
}
// Handle graceful shutdown
process.on('SIGINT', () => {
console.log('\n\n👋 Shutting down dev server...');
process.exit(0);
});
// Run
main().catch(err => {
console.error('Fatal error:', err);
process.exit(1);
});