Skip to main content
Glama

pubnub_subscribe_and_receive_messages

Subscribe to a PubNub channel, receive a specified number of messages, and automatically unsubscribe. Use to listen for messages on a channel, with an optional timeout to control the waiting period.

Instructions

Subscribes to a PubNub channel and waits to receive a specified number of messages, then automatically unsubscribes. Call this tool when you need to listen for messages on a channel. Optionally specify a timeout in milliseconds to avoid waiting indefinitely.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
channelYesName of the PubNub channel to subscribe to and receive messages from
messageCountNoNumber of messages to wait for before unsubscribing (default: 1)
timeoutNoOptional timeout in milliseconds. If not all messages are received within this time, the subscription will end (default: no timeout)

Implementation Reference

  • The handler function that subscribes to the specified PubNub channel, sets up a message listener, collects the requested number of messages or times out, then unsubscribes and returns the received messages.
    toolHandlers['pubnub_subscribe_and_receive_messages'] = async ({ channel, messageCount = 1, timeout }) => {
      try {
        return new Promise((resolve, reject) => {
          let messagesReceived = [];
          let completed = false;
          let timeoutId;
    
          // Create subscription for the channel
          const channelEntity = pubnub.channel(channel);
          const subscription = channelEntity.subscription();
    
          // Set up message listener
          const messageListener = (messageEvent) => {
            if (!completed) {
              messagesReceived.push({
                channel: messageEvent.channel,
                message: messageEvent.message,
                publisher: messageEvent.publisher,
                timetoken: messageEvent.timetoken,
                subscription: messageEvent.subscription
              });
    
              // Check if we've received the desired number of messages
              if (messagesReceived.length >= messageCount) {
                completed = true;
                
                // Clean up
                if (timeoutId) {
                  clearTimeout(timeoutId);
                }
                subscription.unsubscribe();
                subscription.removeListener(messageListener);
    
                // Return all received messages
                resolve({
                  content: [
                    {
                      type: 'text',
                      text: JSON.stringify({
                        channel: channel,
                        messageCount: messagesReceived.length,
                        messages: messagesReceived
                      }, null, 2)
                    }
                  ]
                });
              }
            }
          };
    
          // Add listener and subscribe
          subscription.addListener({ message: messageListener });
          subscription.subscribe();
    
          // Set timeout if specified
          if (timeout && timeout > 0) {
            timeoutId = setTimeout(() => {
              if (!completed) {
                completed = true;
                subscription.unsubscribe();
                subscription.removeListener(messageListener);
                
                if (messagesReceived.length > 0) {
                  // Return partial results if some messages were received
                  resolve({
                    content: [
                      {
                        type: 'text',
                        text: JSON.stringify({
                          channel: channel,
                          messageCount: messagesReceived.length,
                          messages: messagesReceived,
                          note: `Timeout: Only ${messagesReceived.length} of ${messageCount} requested messages received within ${timeout}ms`
                        }, null, 2)
                      }
                    ]
                  });
                } else {
                  // No messages received at all
                  resolve({
                    content: [
                      {
                        type: 'text',
                        text: `Timeout: No messages received on channel '${channel}' within ${timeout}ms`
                      }
                    ]
                  });
                }
              }
            }, timeout);
          }
        });
      } catch (err) {
        return {
          content: [
            {
              type: 'text',
              text: `Error subscribing to channel and receiving messages: ${err.message || err}`
            }
          ],
          isError: true
        };
      }
    };
  • Tool metadata including name, description, and Zod parameter schema for input validation.
    toolDefinitions['pubnub_subscribe_and_receive_messages'] = {
      name: 'pubnub_subscribe_and_receive_messages',
      description: 'Subscribes to a PubNub channel and waits to receive a specified number of messages, then automatically unsubscribes. Call this tool when you need to listen for messages on a channel. Optionally specify a timeout in milliseconds to avoid waiting indefinitely.',
      parameters: {
        channel: z.string().describe('Name of the PubNub channel to subscribe to and receive messages from'),
        messageCount: z.number().optional().default(1).describe('Number of messages to wait for before unsubscribing (default: 1)'),
        timeout: z.number().optional().describe('Optional timeout in milliseconds. If not all messages are received within this time, the subscription will end (default: no timeout)')
      }
    };
  • index.js:1363-1394 (registration)
    The registerAllTools function iterates over all tool definitions and registers each tool (including pubnub_subscribe_and_receive_messages) with the MCP server using server.tool(). Called for the main server and HTTP sessions.
    function registerAllTools(serverInstance, chatSdkMode = false) {
      // Tools to exclude when in chat SDK mode
      const chatSdkExcludedTools = [
        'read_pubnub_sdk_docs',
        'write_pubnub_app', 
        'read_pubnub_resources',
        'manage_pubnub_account'
      ];
    
      for (const toolName in toolDefinitions) {
        if (toolHandlers[toolName]) {
          // Skip excluded tools when in chat SDK mode
          if (chatSdkMode && chatSdkExcludedTools.includes(toolName)) {
            continue;
          }
    
          // Special handling for chat SDK docs tool
          if (toolName === 'read_pubnub_chat_sdk_docs' && 
              (chatSdkLanguages.length === 0 || chatSdkTopics.length === 0)) {
            continue; // Skip this tool if chat SDK data isn't loaded
          }
          
          const toolDef = toolDefinitions[toolName];
          serverInstance.tool(
            toolDef.name,
            toolDef.description,
            toolDef.parameters,
            wrapToolHandler(toolHandlers[toolName], toolName)
          );
        }
      }
    }
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden of behavioral disclosure. It effectively describes the core behavior (subscribe, wait for messages, auto-unsubscribe) and adds useful context about the timeout option. However, it lacks details on error handling, message format, or whether this is a blocking operation, which are important for a tool with no annotation coverage.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is front-loaded with the core purpose in the first sentence, followed by usage guidance and optional details. It uses two efficient sentences with no redundant information, making it highly concise and well-structured.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's moderate complexity (real-time messaging with timeout) and no annotations or output schema, the description is adequate but incomplete. It covers the basic operation and parameters but lacks details on return values, error conditions, or performance implications, which are needed for full contextual understanding.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the schema already documents all parameters thoroughly. The description adds minimal value by mentioning the timeout option but does not provide additional semantics beyond what the schema specifies, such as typical values or edge cases, warranting the baseline score.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the specific action ('subscribes to a PubNub channel and waits to receive a specified number of messages, then automatically unsubscribes'), identifies the resource (PubNub channel), and distinguishes it from siblings like 'publish_pubnub_message' (which sends messages) and 'get_pubnub_messages' (which likely retrieves stored messages).

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides explicit usage context ('Call this tool when you need to listen for messages on a channel') and mentions an alternative approach for timeout handling, but it does not specify when not to use it or compare it directly to sibling tools like 'get_pubnub_messages' for different listening scenarios.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Related Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/pubnub/pubnub-mcp-server'

If you have feedback or need assistance with the MCP directory API, please join our Discord server