diff --git a/src/tools/builtin/messaging.ts b/src/tools/builtin/messaging.ts index 22a4b49..30a2906 100644 --- a/src/tools/builtin/messaging.ts +++ b/src/tools/builtin/messaging.ts @@ -65,6 +65,7 @@ export class SendMessageTool extends ToolHandler { export class ReceiveMessagesTool extends ToolHandler { private messages: any[] = []; + private subscribed = false; constructor(private natsClient: NatsClient) { super( @@ -74,20 +75,29 @@ export class ReceiveMessagesTool extends ToolHandler }, ReceiveMessagesSchema, ); - this.setupSubscription(); } private setupSubscription() { + if (this.subscribed) return; + const myRole = detectRole(); const channel = `dev.messages.${myRole}`; - // Subscribe to messages for this role - this.natsClient.subscribe(channel, (msg) => { - this.messages.push(msg); - }); + // Subscribe to messages for this role (only if NATS is connected) + try { + this.natsClient.subscribe(channel, (msg) => { + this.messages.push(msg); + }); + this.subscribed = true; + } catch (error) { + // NATS not connected yet, will be called later + } } protected async handle(input: ReceiveMessagesInput, _context: ToolContext): Promise { + // Setup subscription on first use (after NATS is connected) + this.setupSubscription(); + const limit = input.limit || 10; const recentMessages = this.messages.slice(-limit);