Skip to main content
Glama

socket

Connect to WebSocket endpoints, send and receive real-time messages, manage connections, and monitor message history for live data streams.

Instructions

Manage WebSocket connections - connect, send, receive messages, list connections, and close

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
actionYesThe action to perform on WebSocket connections

Implementation Reference

  • The primary handler function for the 'socket' tool. It parses the action type and delegates to specific WebSocket utility functions like connectSocket, sendMessage, etc.
    export default async function socket({ action }: InferSchema<typeof schema>) {
      try {
        switch (action.type) {
          case "list":
            return await listSockets()
    
          case "connect":
            return await connectSocket({
              url: action.url,
              protocols: action.protocols,
              headers: action.headers,
              autoReconnect: action.autoReconnect,
              maxReconnectAttempts: action.maxReconnectAttempts,
              reconnectInterval: action.reconnectInterval,
              messageHistoryLimit: action.messageHistoryLimit,
            })
    
          case "send":
            return await sendMessage({
              socketId: action.socketId,
              message: action.message,
              binary: action.binary,
            })
    
          case "receive":
            return await receiveMessages({
              socketId: action.socketId,
              action: action.action,
              since: action.since,
              clearAfterRead: action.clearAfterRead,
            })
    
          case "close":
            return await closeSocket({
              socketId: action.socketId,
              code: action.code,
              reason: action.reason,
            })
    
          default:
            return JSON.stringify({
              success: false,
              error: "Invalid action type",
            }, null, 2)
        }
      } catch (error) {
        return JSON.stringify({
          success: false,
          error: error instanceof Error ? error.message : "Unknown error occurred",
        }, null, 2)
      }
    }
  • Zod schema defining the input parameters for the socket tool using a discriminated union based on 'action.type' for list, connect, send, receive, and close operations.
    export const schema = {
      action: z.discriminatedUnion("type", [
        // List sockets action
        z.object({
          type: z.literal("list"),
        }),
    
        // Connect action
        z.object({
          type: z.literal("connect"),
          url: z.string()
            .describe("The WebSocket URL to connect to (ws:// or wss://)"),
          protocols: z.array(z.string())
            .optional()
            .describe("WebSocket subprotocols to use"),
          headers: z.record(z.string())
            .optional()
            .describe("HTTP headers to include in the connection request"),
          autoReconnect: z.boolean()
            .optional()
            .default(false)
            .describe("Whether to automatically reconnect on disconnection"),
          maxReconnectAttempts: z.number()
            .optional()
            .default(5)
            .describe("Maximum number of reconnection attempts"),
          reconnectInterval: z.number()
            .optional()
            .default(1000)
            .describe("Base interval between reconnection attempts in milliseconds"),
          messageHistoryLimit: z.number()
            .optional()
            .default(100)
            .describe("Maximum number of messages to keep in history"),
        }),
    
        // Send action
        z.object({
          type: z.literal("send"),
          socketId: z.string()
            .describe("The ID of the WebSocket connection to send to"),
          message: z.union([z.string(), z.record(z.any())])
            .describe("The message to send (string or object that will be JSON stringified)"),
          binary: z.boolean()
            .optional()
            .default(false)
            .describe("Whether to send the message as binary data"),
        }),
    
        // Receive action
        z.object({
          type: z.literal("receive"),
          socketId: z.string()
            .describe("The ID of the WebSocket connection to receive messages from"),
          action: z.enum(["get-latest", "get-all", "get-since"])
            .describe("What messages to retrieve: get-latest (last 10), get-all (entire queue), or get-since (after timestamp)"),
          since: z.string()
            .optional()
            .describe("ISO timestamp or message ID to get messages after (required for get-since action)"),
          clearAfterRead: z.boolean()
            .optional()
            .default(false)
            .describe("Whether to clear the message queue after reading (only applies to get-all action)"),
        }),
    
        // Close action
        z.object({
          type: z.literal("close"),
          socketId: z.string()
            .describe("The ID of the WebSocket connection to close"),
          code: z.number()
            .optional()
            .default(1000)
            .describe("WebSocket close code (1000 = normal closure)"),
          reason: z.string()
            .optional()
            .default("Normal closure")
            .describe("Reason for closing the connection"),
        }),
      ]).describe("The action to perform on WebSocket connections"),
    }
  • Tool metadata registration including the name 'socket', description, and annotations for the MCP tool protocol.
    export const metadata: ToolMetadata = {
      name: "socket",
      description: "Manage WebSocket connections - connect, send, receive messages, list connections, and close",
      annotations: {
        title: "WebSocket Management",
        readOnlyHint: false,
        destructiveHint: false,
        idempotentHint: false,
      },
    }
  • Re-exports all socket utility functions used by the handler (connectSocket, sendMessage, etc.) and defines shared types like SocketInstance.
    export { connectSocket, type ConnectParams } from './connect'
    export { sendMessage, type SendParams } from './send'
    export { receiveMessages, type ReceiveParams } from './receive'
    export { listSockets } from './list'
    export { closeSocket, type CloseParams } from './close'
  • Core helper function for connecting to a WebSocket server, managing instance state, message history, and auto-reconnection logic.
    import * as WebSocket from "ws"
    import {
      generateSocketId,
      generateMessageId,
      addSocket,
      updateSocketStatus,
      addMessage,
      getSocket,
      type SocketInstance,
      type Message
    } from "../socket-instances"
    
    export interface ConnectParams {
      url: string
      protocols?: string[]
      headers?: Record<string, string>
      autoReconnect?: boolean
      maxReconnectAttempts?: number
      reconnectInterval?: number
      messageHistoryLimit?: number
    }
    
    export async function connectSocket(params: ConnectParams): Promise<string> {
      const {
        url,
        protocols,
        headers,
        autoReconnect = false,
        maxReconnectAttempts = 5,
        reconnectInterval = 1000,
        messageHistoryLimit = 100
      } = params
    
      // Validate URL
      if (!url.startsWith('ws://') && !url.startsWith('wss://')) {
        return JSON.stringify({
          success: false,
          error: "Invalid WebSocket URL. Must start with ws:// or wss://",
        }, null, 2)
      }
    
      // Generate unique socket ID
      const socketId = generateSocketId()
    
      // Create WebSocket options
      const options: WebSocket.ClientOptions = {
        ...(headers && { headers }),
      }
    
      // Create WebSocket instance
      const socket = new WebSocket.WebSocket(url, protocols, options)
    
      // Create socket instance
      const socketInstance: SocketInstance = {
        id: socketId,
        socket,
        url,
        createdAt: new Date(),
        status: 'connecting',
        messageQueue: [],
        config: {
          autoReconnect,
          maxReconnectAttempts,
          reconnectInterval,
          messageHistoryLimit,
          protocols,
          headers,
        },
        reconnectAttempts: 0,
        lastActivity: new Date(),
      }
    
      // Add to global store
Behavior3/5

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

Annotations provide basic hints (not read-only, not idempotent, not destructive), but the description adds useful context about the five specific actions available. However, it doesn't disclose important behavioral traits like connection persistence, error handling, authentication requirements, or rate limits that would help an agent use it effectively.

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 extremely concise - a single sentence listing all five actions. Every word earns its place with zero waste. It's front-loaded with the core purpose and efficiently enumerates capabilities without unnecessary elaboration.

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?

For a multi-action tool with comprehensive schema coverage but no output schema, the description provides minimal but adequate coverage. It identifies the scope of operations but lacks details about return values, error conditions, or practical usage patterns that would help an agent understand what to expect from each action.

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?

With 100% schema description coverage, the input schema comprehensively documents all parameters. The description mentions the five action types but adds no additional semantic meaning beyond what's already in the schema descriptions. This meets the baseline for high schema coverage.

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

Purpose4/5

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

The description clearly states the tool's purpose as managing WebSocket connections with specific actions (connect, send, receive, list, close). It uses specific verbs and identifies the resource (WebSocket connections), but doesn't differentiate from sibling tools like 'fetch' or 'graphql' which handle different protocols.

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

Usage Guidelines2/5

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

The description provides no guidance on when to use this tool versus alternatives. It doesn't mention when WebSocket connections are appropriate compared to HTTP requests (fetch) or GraphQL queries, nor does it specify prerequisites or exclusions for usage.

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/matiasngf/mcp-fetch'

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