test-kontent-mcp
Version:
Experimental implementation of Model Context Protocol
51 lines (50 loc) • 1.45 kB
JavaScript
import http from 'node:http';
import { EventEmitter } from 'node:events';
export class SseServerTransport extends EventEmitter {
server;
clients = new Set();
constructor(port = 3000) {
super();
this.server = http.createServer((req, res) => {
if (req.url === '/sse') {
this.handleSseConnection(req, res);
}
else {
res.writeHead(404);
res.end();
}
});
this.server.listen(port, () => {
console.log(`SSE server running on port ${port}`);
});
}
handleSseConnection(req, res) {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
'Access-Control-Allow-Origin': '*',
});
this.clients.add(res);
req.on('close', () => {
this.clients.delete(res);
});
}
async start() {
// Server is already started in constructor
return Promise.resolve();
}
async send(message) {
const messageStr = JSON.stringify(message);
for (const client of this.clients) {
client.write(`data: ${messageStr}\n\n`);
}
}
async close() {
for (const client of this.clients) {
client.end();
}
this.clients.clear();
this.server.close();
}
}