MCP Apps
    Preparing search index...

    Class ProtocolWithEvents<SendRequestT, SendNotificationT, SendResultT, EventMap>Abstract

    Intermediate base class that adds DOM-style event support on top of the MCP SDK's Protocol.

    The base Protocol class stores one handler per method: setRequestHandler() and setNotificationHandler() replace any existing handler for the same method silently. This class introduces a two-channel event model inspired by the DOM:

    Subclasses expose get/set pairs that delegate to setEventHandler / getEventHandler. Assigning replaces the previous handler; assigning undefined clears it. addEventListener listeners are unaffected.

    Append to a per-event listener array. Listeners fire in insertion order after the singular on* handler.

    When a notification arrives for a mapped event:

    1. onEventDispatch (subclass side-effects)
    2. The singular on* handler (if set)
    3. All addEventListener listeners in insertion order

    Direct calls to setRequestHandler / setNotificationHandler throw if a handler for the same method has already been registered (through any path), so accidental overwrites surface as errors instead of silent bugs.

    Type Parameters

    • SendRequestT extends Request
    • SendNotificationT extends Notification
    • SendResultT extends Result
    • EventMap extends Record<string, unknown>

      Maps event names to the listener's params type.

    Hierarchy (View Summary)

    Index

    Accessors

    • get transport(): Transport | undefined

      Returns Transport | undefined

    Constructors

    • Type Parameters

      • SendRequestT extends {
            method: string;
            params?: {
                _meta?: {
                    "io.modelcontextprotocol/related-task"?: { taskId: string };
                    progressToken?: string | number;
                    [key: string]: unknown;
                };
                [key: string]: unknown;
            };
        }
      • SendNotificationT extends {
            method: string;
            params?: {
                _meta?: {
                    "io.modelcontextprotocol/related-task"?: { taskId: string };
                    progressToken?: string | number;
                    [key: string]: unknown;
                };
                [key: string]: unknown;
            };
        }
      • SendResultT extends {
            _meta?: {
                "io.modelcontextprotocol/related-task"?: { taskId: string };
                progressToken?: string | number;
                [key: string]: unknown;
            };
            [key: string]: unknown;
        }
      • EventMap extends Record<string, unknown>

        Maps event names to the listener's params type.

      Parameters

      • Optional_options: ProtocolOptions

      Returns ProtocolWithEvents<SendRequestT, SendNotificationT, SendResultT, EventMap>

    Methods

    • Add a listener for a notification event.

      Unlike the singular on* handler, calling this multiple times appends listeners rather than replacing them. All registered listeners fire in insertion order after the on* handler when the notification arrives.

      Registration is lazy: the first call (for a given event, from either this method or the on* setter) registers a dispatcher with the base Protocol.

      Type Parameters

      • K extends string | number | symbol

      Parameters

      • event: K

        Event name (a key of the EventMap type parameter).

      • handler: (params: EventMap[K]) => void

        Listener invoked with the notification params.

      Returns void

    • Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed.

      Parameters

      • method: string

      Returns void

    • A method to check if a capability is supported by the remote side, for the given method to be called.

      This should be implemented by subclasses.

      Parameters

      Returns void

    • A method to check if a notification is supported by the local side, for the given method to be sent.

      This should be implemented by subclasses.

      Parameters

      Returns void

    • A method to check if a request handler is supported by the local side, for the given method to be handled.

      This should be implemented by subclasses.

      Parameters

      • method: string

      Returns void

    • A method to check if task creation is supported for the given request method.

      This should be implemented by subclasses.

      Parameters

      • method: string

      Returns void

    • A method to check if task handler is supported by the local side, for the given method to be handled.

      This should be implemented by subclasses.

      Parameters

      • method: string

      Returns void

    • Experimental

      Cancels a specific task.

      Use client.experimental.tasks.cancelTask() to access this method.

      Parameters

      • params: { taskId: string }
      • Optionaloptions: RequestOptions

      Returns Promise<
          {
              _meta?: {
                  "io.modelcontextprotocol/related-task"?: { taskId: string };
                  progressToken?: string | number;
                  [key: string]: unknown;
              };
              createdAt: string;
              lastUpdatedAt: string;
              pollInterval?: number;
              status: | "working"
              | "input_required"
              | "completed"
              | "failed"
              | "cancelled";
              statusMessage?: string;
              taskId: string;
              ttl: number
              | null;
          },
      >

    • Closes the connection.

      Returns Promise<void>

    • Attaches to the given transport, starts it, and starts listening for messages.

      The Protocol object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward.

      Parameters

      • transport: Transport

      Returns Promise<void>

    • Get the singular on* handler for an event, or undefined if none is set. addEventListener listeners are not reflected here.

      Type Parameters

      • K extends string | number | symbol

      Parameters

      • event: K

      Returns ((params: EventMap[K]) => void) | undefined

    • Experimental

      Gets the current status of a task.

      Use client.experimental.tasks.getTask() to access this method.

      Parameters

      • params: {
            _meta?: {
                "io.modelcontextprotocol/related-task"?: { taskId: string };
                progressToken?: string | number;
                [key: string]: unknown;
            };
            taskId: string;
        }
      • Optionaloptions: RequestOptions

      Returns Promise<
          {
              _meta?: {
                  "io.modelcontextprotocol/related-task"?: { taskId: string };
                  progressToken?: string | number;
                  [key: string]: unknown;
              };
              createdAt: string;
              lastUpdatedAt: string;
              pollInterval?: number;
              status: | "working"
              | "input_required"
              | "completed"
              | "failed"
              | "cancelled";
              statusMessage?: string;
              taskId: string;
              ttl: number
              | null;
          },
      >

    • Experimental

      Retrieves the result of a completed task.

      Use client.experimental.tasks.getTaskResult() to access this method.

      Type Parameters

      • T extends AnySchema

      Parameters

      • params: {
            _meta?: {
                "io.modelcontextprotocol/related-task"?: { taskId: string };
                progressToken?: string | number;
                [key: string]: unknown;
            };
            taskId: string;
        }
      • resultSchema: T
      • Optionaloptions: RequestOptions

      Returns Promise<SchemaOutput<T>>

    • Experimental

      Lists tasks, optionally starting from a pagination cursor.

      Use client.experimental.tasks.listTasks() to access this method.

      Parameters

      • Optionalparams: { cursor?: string }
      • Optionaloptions: RequestOptions

      Returns Promise<
          {
              _meta?: {
                  "io.modelcontextprotocol/related-task"?: { taskId: string };
                  progressToken?: string | number;
                  [key: string]: unknown;
              };
              nextCursor?: string;
              tasks: {
                  createdAt: string;
                  lastUpdatedAt: string;
                  pollInterval?: number;
                  status: | "working"
                  | "input_required"
                  | "completed"
                  | "failed"
                  | "cancelled";
                  statusMessage?: string;
                  taskId: string;
                  ttl: number
                  | null;
              }[];
              [key: string]: unknown;
          },
      >

    • Emits a notification, which is a one-way message that does not expect a response.

      Parameters

      Returns Promise<void>

    • Called once per incoming notification, before any handlers or listeners fire. Subclasses may override to perform side effects such as merging notification params into cached state.

      Type Parameters

      • K extends string | number | symbol

      Parameters

      Returns void

    • Remove a previously registered event listener. The dispatcher stays registered even if the listener array becomes empty; future notifications simply have no listeners to call.

      Type Parameters

      • K extends string | number | symbol

      Parameters

      Returns void

    • Removes the notification handler for the given method.

      Parameters

      • method: string

      Returns void

    • Removes the request handler for the given method.

      Parameters

      • method: string

      Returns void

    • Sends a request and waits for a response.

      Do not use this method to emit notifications! Use notification() instead.

      Type Parameters

      • T extends AnySchema

      Parameters

      • request: SendRequestT
      • resultSchema: T
      • Optionaloptions: RequestOptions

      Returns Promise<SchemaOutput<T>>

    • Experimental

      Sends a request and returns an AsyncGenerator that yields response messages. The generator is guaranteed to end with either a 'result' or 'error' message.

      Type Parameters

      • T extends AnySchema

      Parameters

      • request: SendRequestT
      • resultSchema: T
      • Optionaloptions: RequestOptions

      Returns AsyncGenerator<ResponseMessage<SchemaOutput<T>>, void, void>

      const stream = protocol.requestStream(request, resultSchema, options);
      for await (const message of stream) {
      switch (message.type) {
      case 'taskCreated':
      console.log('Task created:', message.task.taskId);
      break;
      case 'taskStatus':
      console.log('Task status:', message.task.status);
      break;
      case 'result':
      console.log('Final result:', message.result);
      break;
      case 'error':
      console.error('Error:', message.error);
      break;
      }
      }

      Use client.experimental.tasks.requestStream() to access this method.

    • Set or clear the singular on* handler for an event.

      Replace semantics — like the DOM's el.onclick = fn. Assigning undefined clears the handler without affecting addEventListener listeners.

      Type Parameters

      • K extends string | number | symbol

      Parameters

      • event: K
      • handler: ((params: EventMap[K]) => void) | undefined

      Returns void

    • Warn if a request handler on* setter is replacing a previously-set handler. Call from each request setter before updating the backing field.

      Parameters

      • name: string
      • previous: unknown
      • next: unknown

      Returns void

    Properties

    eventSchemas: { [K in string | number | symbol]: MethodSchema }

    Event name → notification schema. Subclasses populate this so that the event system can lazily register a dispatcher with the correct schema on first use.

    fallbackNotificationHandler?: (
        notification: {
            method: string;
            params?: {
                _meta?: {
                    "io.modelcontextprotocol/related-task"?: { taskId: string };
                    progressToken?: string | number;
                    [key: string]: unknown;
                };
                [key: string]: unknown;
            };
        },
    ) => Promise<void>

    A handler to invoke for any notification types that do not have their own handler installed.

    fallbackRequestHandler?: (
        request: {
            id: string | number;
            jsonrpc: "2.0";
            method: string;
            params?: {
                _meta?: {
                    "io.modelcontextprotocol/related-task"?: { taskId: string };
                    progressToken?: string | number;
                    [key: string]: unknown;
                };
                [key: string]: unknown;
            };
        },
        extra: RequestHandlerExtra<SendRequestT, SendNotificationT>,
    ) => Promise<SendResultT>

    A handler to invoke for any request types that do not have their own handler installed.

    onclose?: () => void

    Callback for when the connection is closed for any reason.

    This is invoked when close() is called as well.

    onerror?: (error: Error) => void

    Callback for when an error occurs.

    Note that errors are not necessarily fatal; they are used for reporting any kind of exceptional condition out of band.

    replaceRequestHandler: <T extends AnyObjectSchema>(
        requestSchema: T,
        handler: (
            request: SchemaOutput<T>,
            extra: RequestHandlerExtra<SendRequestT, SendNotificationT>,
        ) => SendResultT | Promise<SendResultT>,
    ) => void = ...

    Replace a request handler, bypassing double-set protection. Used by on* request-handler setters that need replace semantics.

    Type Declaration

      • <T extends AnyObjectSchema>(
            requestSchema: T,
            handler: (
                request: SchemaOutput<T>,
                extra: RequestHandlerExtra<SendRequestT, SendNotificationT>,
            ) => SendResultT | Promise<SendResultT>,
        ): void
      • Registers a handler to invoke when this protocol object receives a request with the given method.

        Note that this will replace any previous request handler for the same method.

        Type Parameters

        • T extends AnyObjectSchema

        Parameters

        Returns void

    setNotificationHandler: <T extends AnyObjectSchema>(
        notificationSchema: T,
        handler: (notification: SchemaOutput<T>) => void | Promise<void>,
    ) => void = ...

    Registers a notification handler. Throws if a handler for the same method has already been registered — use the on* setter (replace semantics) or addEventListener (multi-listener) for mapped events.

    Type Declaration

      • <T extends AnyObjectSchema>(
            notificationSchema: T,
            handler: (notification: SchemaOutput<T>) => void | Promise<void>,
        ): void
      • Registers a handler to invoke when this protocol object receives a notification with the given method.

        Note that this will replace any previous notification handler for the same method.

        Type Parameters

        • T extends AnyObjectSchema

        Parameters

        • notificationSchema: T
        • handler: (notification: SchemaOutput<T>) => void | Promise<void>

        Returns void

    if a handler for this method is already registered.

    setRequestHandler: <T extends AnyObjectSchema>(
        requestSchema: T,
        handler: (
            request: SchemaOutput<T>,
            extra: RequestHandlerExtra<SendRequestT, SendNotificationT>,
        ) => SendResultT | Promise<SendResultT>,
    ) => void = ...

    Registers a request handler. Throws if a handler for the same method has already been registered — use the on* setter (replace semantics) or addEventListener (multi-listener) for notification events.

    Type Declaration

      • <T extends AnyObjectSchema>(
            requestSchema: T,
            handler: (
                request: SchemaOutput<T>,
                extra: RequestHandlerExtra<SendRequestT, SendNotificationT>,
            ) => SendResultT | Promise<SendResultT>,
        ): void
      • Registers a handler to invoke when this protocol object receives a request with the given method.

        Note that this will replace any previous request handler for the same method.

        Type Parameters

        • T extends AnyObjectSchema

        Parameters

        Returns void

    if a handler for this method is already registered.