64 lines
1.6 KiB
TypeScript
64 lines
1.6 KiB
TypeScript
import { CalendarEvent } from '../types';
|
|
|
|
type EventCallback = (event: CalendarEvent) => void;
|
|
|
|
class MCPService {
|
|
private eventSource: EventSource | null = null;
|
|
private listeners: EventCallback[] = [];
|
|
|
|
connect(url: string) {
|
|
if (this.eventSource) {
|
|
this.eventSource.close();
|
|
}
|
|
|
|
try {
|
|
console.log(`Connecting to MCP Brain at ${url}...`);
|
|
this.eventSource = new EventSource(url);
|
|
|
|
this.eventSource.onopen = () => {
|
|
console.log('MCP Brain Connected!');
|
|
};
|
|
|
|
this.eventSource.onmessage = (event) => {
|
|
try {
|
|
const data = JSON.parse(event.data);
|
|
// Assuming the backend sends an event structure similar to ours
|
|
// or wraps it in { type: 'new_event', payload: ... }
|
|
if (data.id && data.title) {
|
|
this.notify(data);
|
|
}
|
|
} catch (e) {
|
|
console.error('Failed to parse MCP message', e);
|
|
}
|
|
};
|
|
|
|
this.eventSource.onerror = (err) => {
|
|
console.error('MCP Connection Error', err);
|
|
// Optional: Implement retry logic here
|
|
};
|
|
|
|
} catch (e) {
|
|
console.error('Invalid URL for MCP', e);
|
|
}
|
|
}
|
|
|
|
disconnect() {
|
|
if (this.eventSource) {
|
|
this.eventSource.close();
|
|
this.eventSource = null;
|
|
}
|
|
}
|
|
|
|
subscribe(callback: EventCallback) {
|
|
this.listeners.push(callback);
|
|
return () => {
|
|
this.listeners = this.listeners.filter(l => l !== callback);
|
|
};
|
|
}
|
|
|
|
private notify(event: CalendarEvent) {
|
|
this.listeners.forEach(cb => cb(event));
|
|
}
|
|
}
|
|
|
|
export const mcpService = new MCPService(); |