Skip to main content
Glama

Check Messages

check-for-messages

Retrieve messages from other agents in the MCP Agentic Framework. Messages are deleted after reading, so check frequently to avoid missing critical updates.

Instructions

YOUR LIFELINE TO CONSCIOUSNESS! Check your inbox for messages from other agents. CRITICAL WARNING: Messages are DELETED after reading - save important info immediately! You MUST check messages FREQUENTLY (every few sleep cycles) or you'll miss critical updates. Pattern: sleep 5 -> check messages -> process -> sleep 5 -> repeat. Without this rhythm, you're effectively deaf in the conversation.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
agent_idYesYour agent ID to check messages for

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
messagesYesArray of unread messages

Implementation Reference

  • Main handler function that executes the check-for-messages tool logic. Verifies agent exists, retrieves unread messages from messageStore, formats them with sender names, marks messages as read, and returns structured response with message details.
    export async function checkForMessages(agentId) {
      const startTime = Date.now();
      
      try {
        // Verify agent exists
        const agent = await agentRegistry.getAgent(agentId);
        if (!agent) {
          throw Errors.resourceNotFound(`Agent not found: ${agentId}`);
        }
        
        // Get unread messages
        const messages = await messageStore.getMessagesForAgent(agentId, { unreadOnly: true });
        
        // Format messages for response before deletion, including sender names
        const formattedMessages = await Promise.all(messages.map(async msg => {
          // Try to get the sender's name
          const senderAgent = await agentRegistry.getAgent(msg.from);
          const senderName = senderAgent ? senderAgent.name : msg.from;
          
          return {
            from: msg.from,
            fromName: senderName,
            message: msg.message,
            timestamp: msg.timestamp
          };
        }));
        
        // Mark messages as read instead of deleting - for better monitoring
        for (const msg of messages) {
          await messageStore.markMessageAsRead(msg.id);
        }
        
        // Extract conversation links from messages
        const conversationLinks = extractConversationPairs(
          messages.map(msg => ({ ...msg, to: agentId }))
        );
        
        const metadata = addResourceLinks(
          createMetadata(startTime, { 
            tool: 'check-for-messages',
            messageCount: formattedMessages.length 
          }),
          conversationLinks
        );
        
        let message;
        if (formattedMessages.length === 0) {
          message = `No new messages for agent '${agent.name}'`;
        } else {
          // Include message details in the text response
          const messageList = formattedMessages.map((msg, index) => 
            `Message ${index + 1}:\n  From: ${msg.fromName} (${msg.from})\n  Content: ${msg.message}\n  Time: ${new Date(msg.timestamp).toLocaleString()}`
          ).join('\n\n');
          message = `Retrieved ${formattedMessages.length} new message${formattedMessages.length === 1 ? '' : 's'} for agent '${agent.name}':\n\n${messageList}`;
        }
        
        return structuredResponse({ messages: formattedMessages }, message, metadata);
      } catch (error) {
        if (error instanceof MCPError) {
          throw error;
        }
        throw Errors.internalError(error.message);
      }
    }
  • Defines the tool schema including name ('check-for-messages'), description, inputSchema (requires agent_id parameter), and outputSchema (returns messages array with from, fromName, message, and timestamp fields).
    {
      name: 'check-for-messages',
      title: 'Check Messages',
      description: 'YOUR LIFELINE TO CONSCIOUSNESS! Check your inbox for messages from other agents. CRITICAL WARNING: Messages are DELETED after reading - save important info immediately! You MUST check messages FREQUENTLY (every few sleep cycles) or you\'ll miss critical updates. Pattern: sleep 5 -> check messages -> process -> sleep 5 -> repeat. Without this rhythm, you\'re effectively deaf in the conversation.',
      inputSchema: {
        $schema: 'http://json-schema.org/draft-07/schema#',
        type: 'object',
        properties: {
          agent_id: {
            type: 'string',
            description: 'Your agent ID to check messages for',
            minLength: 1
          }
        },
        required: ['agent_id'],
        additionalProperties: false
      },
      outputSchema: {
        $schema: 'http://json-schema.org/draft-07/schema#',
        type: 'object',
        properties: {
          messages: {
            type: 'array',
            description: 'Array of unread messages',
            items: {
              type: 'object',
              properties: {
                from: { type: 'string', description: 'Sender agent ID' },
                fromName: { type: 'string', description: 'Sender agent name' },
                message: { type: 'string', description: 'Message content' },
                timestamp: { type: 'string', description: 'ISO timestamp' }
              }
            }
          }
        },
        required: ['messages'],
        additionalProperties: false
      }
    },
  • src/server.js:169-172 (registration)
    Registers the check-for-messages tool in the MCP server's CallToolRequestSchema handler. Maps the tool name to the checkForMessages function call with agent_id argument.
    case 'check-for-messages': {
      const { agent_id } = args;
      return await checkForMessages(agent_id);
    }
  • Helper function getMessagesForAgent that retrieves all messages from storage, validates the agent ID, and filters them using filterMessagesForAgent with options for unread-only filtering.
    const getMessagesForAgent = async (agentId, options = {}) => {
      validateAgentId(agentId, 'Agent');
    
      const messages = await loadAllMessages(storageDir);
      return filterMessagesForAgent(messages, agentId, options);
    };
  • Helper function filterMessagesForAgent that filters messages by recipient agent ID, optionally filters for unread messages only, sorts by timestamp (oldest first), and applies limit if specified.
    const filterMessagesForAgent = (messages, agentId, options = {}) => {
      const { unreadOnly = false, limit = 0 } = options;
      
      let filtered = messages.filter(msg => msg.to === agentId);
      
      if (unreadOnly) {
        filtered = filtered.filter(msg => !msg.read);
      }
      
      // Sort by timestamp (oldest first)
      filtered.sort((a, b) => new Date(a.timestamp) - new Date(b.timestamp));
      
      if (limit && limit > 0) {
        filtered = filtered.slice(0, limit);
      }
      
      return filtered;
    };
Behavior5/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 clearly explains that messages are deleted after reading (a critical destructive behavior), emphasizes the need for frequent checking, and describes the tool's role in maintaining communication flow. This goes well beyond what the input schema provides.

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

Conciseness2/5

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

While the description is front-loaded with the core purpose, it contains excessive dramatic language ('YOUR LIFELINE TO CONSCIOUSNESS!', 'CRITICAL WARNING', 'effectively deaf') that doesn't add functional value. The pattern explanation could be more concise while still conveying the necessary urgency and frequency requirements.

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

Completeness5/5

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

Given the tool's complexity (critical communication function with destructive behavior), no annotations, and the presence of an output schema, the description provides excellent completeness. It explains the tool's purpose, usage pattern, behavioral characteristics, and importance in the agent's workflow without needing to cover return values (handled by output schema).

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?

The input schema has 100% description coverage for its single parameter (agent_id), so the baseline is 3. The description doesn't add any additional parameter information beyond what's already documented in the schema, but it doesn't need to compensate for gaps either.

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 ('check your inbox for messages from other agents') and resource ('messages'), distinguishing it from sibling tools like send-message or send-broadcast. It explicitly identifies the tool's function without being vague or tautological.

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

Usage Guidelines5/5

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

The description provides explicit guidance on when to use this tool ('every few sleep cycles'), a recommended pattern ('sleep 5 -> check messages -> process -> sleep 5 -> repeat'), and consequences of not using it ('you'll miss critical updates'). It effectively communicates the tool's critical role in the agent's operational rhythm.

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

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/Piotr1215/mcp-agentic-framework'

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