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
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