MCP TypeScript SDK (V2)
    Preparing search index...

    An MCP client on top of a pluggable transport.

    The client will automatically begin the initialization flow with the server when connect is called.

    Hierarchy (View Summary)

    Index

    Constructors

    • Initializes this client with the given name and version information.

      Parameters

      • _clientInfo: {
            description?: string;
            icons?: {
                mimeType?: string;
                sizes?: string[];
                src: string;
                theme?: "light" | "dark";
            }[];
            name: string;
            title?: string;
            version: string;
            websiteUrl?: string;
        }
        • Optionaldescription?: string

          An optional human-readable description of what this implementation does.

          This can be used by clients or servers to provide context about their purpose and capabilities. For example, a server might describe the types of resources or tools it provides, while a client might describe its intended use case.

        • Optionalicons?: { mimeType?: string; sizes?: string[]; src: string; theme?: "light" | "dark" }[]

          Optional set of sized icons that the client can display in a user interface.

          Clients that support rendering icons MUST support at least the following MIME types:

          • image/png - PNG images (safe, universal compatibility)
          • image/jpeg (and image/jpg) - JPEG images (safe, universal compatibility)

          Clients that support rendering icons SHOULD also support:

          • image/svg+xml - SVG images (scalable but requires security precautions)
          • image/webp - WebP images (modern, efficient format)
        • name: string

          Intended for programmatic or logical use, but used as a display name in past specs or fallback

        • Optionaltitle?: string

          Intended for UI and end-user contexts — optimized to be human-readable and easily understood, even by those unfamiliar with domain-specific terminology.

          If not provided, the name should be used for display (except for Tool, where annotations.title should be given precedence over using name, if present).

        • version: string
        • OptionalwebsiteUrl?: string

          An optional URL of the website for this implementation.

      • Optionaloptions: ClientOptions

      Returns Client

    Properties

    _supportedProtocolVersions: string[]
    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;
            };
        },
        ctx: BaseContext,
    ) => Promise<
        {
            _meta?: {
                "io.modelcontextprotocol/related-task"?: { taskId: string };
                progressToken?: string | number;
                [key: string]: unknown;
            };
            [key: string]: unknown;
        },
    >

    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.

    Accessors

    Methods

    • Parameters

      • capability:
            | "tools"
            | "experimental"
            | "tasks"
            | "logging"
            | "completions"
            | "prompts"
            | "resources"
      • method: string

      Returns void

    • Calls a tool on the connected server and returns the result. Automatically validates structured output if the tool has an outputSchema.

      Tool results have two error surfaces: result.isError for tool-level failures (the tool ran but reported a problem), and thrown ProtocolError for protocol-level failures or SdkError for SDK-level issues (timeouts, missing capabilities).

      For task-based execution with streaming behavior, use client.experimental.tasks.callToolStream() instead.

      Parameters

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

          See General fields: _meta for notes on _meta usage.

          • Optionalio.modelcontextprotocol/related-task?: { taskId: string }

            If specified, this request is related to the provided task.

          • OptionalprogressToken?: string | number

            If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications.

        • Optionalarguments?: { [key: string]: unknown }

          Arguments to pass to the tool.

        • name: string

          The name of the tool to call.

        • Optionaltask?: { ttl?: number }

          If specified, the caller is requesting task-augmented execution for this request. The request will return a CreateTaskResult immediately, and the actual result can be retrieved later via tasks/result.

          Task augmentation is subject to capability negotiation - receivers MUST declare support for task augmentation of specific request types in their capabilities.

      • resultSchema:
            | ZodObject<
                {
                    _meta: ZodOptional<
                        ZodObject<
                            {
                                "io.modelcontextprotocol/related-task": ZodOptional<
                                    ZodObject<{ taskId: ZodString }, $strip>,
                                >;
                                progressToken: ZodOptional<ZodUnion<readonly [ZodString, ZodNumber]>>;
                            },
                            $loose,
                        >,
                    >;
                    content: ZodDefault<
                        ZodArray<
                            ZodUnion<
                                readonly [
                                    ZodObject<
                                        {
                                            _meta: ZodOptional<ZodRecord<(...), (...)>>;
                                            annotations: ZodOptional<ZodObject<(...), (...)>>;
                                            text: ZodString;
                                            type: ZodLiteral<"text">;
                                        },
                                        $strip,
                                    >,
                                    ZodObject<
                                        {
                                            _meta: ZodOptional<ZodRecord<(...), (...)>>;
                                            annotations: ZodOptional<ZodObject<(...), (...)>>;
                                            data: ZodString;
                                            mimeType: ZodString;
                                            type: ZodLiteral<"image">;
                                        },
                                        $strip,
                                    >,
                                    ZodObject<
                                        {
                                            _meta: ZodOptional<ZodRecord<(...), (...)>>;
                                            annotations: ZodOptional<ZodObject<(...), (...)>>;
                                            data: ZodString;
                                            mimeType: ZodString;
                                            type: ZodLiteral<"audio">;
                                        },
                                        $strip,
                                    >,
                                    ZodObject<
                                        {
                                            _meta: ZodOptional<ZodObject<(...), (...)>>;
                                            annotations: ZodOptional<ZodObject<(...), (...)>>;
                                            description: ZodOptional<ZodString>;
                                            icons: ZodOptional<ZodArray<(...)>>;
                                            mimeType: ZodOptional<ZodString>;
                                            name: ZodString;
                                            title: ZodOptional<ZodString>;
                                            type: ZodLiteral<"resource_link">;
                                            uri: ZodString;
                                        },
                                        $strip,
                                    >,
                                    ZodObject<
                                        {
                                            _meta: ZodOptional<ZodRecord<(...), (...)>>;
                                            annotations: ZodOptional<ZodObject<(...), (...)>>;
                                            resource: ZodUnion<readonly [(...), (...)]>;
                                            type: ZodLiteral<"resource">;
                                        },
                                        $strip,
                                    >,
                                ],
                            >,
                        >,
                    >;
                    isError: ZodOptional<ZodBoolean>;
                    structuredContent: ZodOptional<ZodRecord<ZodString, ZodUnknown>>;
                },
                $loose,
            >
            | ZodUnion<
                [
                    ZodObject<
                        {
                            _meta: ZodOptional<
                                ZodObject<
                                    {
                                        "io.modelcontextprotocol/related-task": ZodOptional<
                                            ZodObject<{ taskId: ... }, $strip>,
                                        >;
                                        progressToken: ZodOptional<ZodUnion<readonly [(...), (...)]>>;
                                    },
                                    $loose,
                                >,
                            >;
                            content: ZodDefault<
                                ZodArray<
                                    ZodUnion<
                                        readonly [
                                            ZodObject<
                                                { _meta: ...; annotations: ...; text: ...; type: ... },
                                                $strip,
                                            >,
                                            ZodObject<
                                                {
                                                    _meta: ...;
                                                    annotations: ...;
                                                    data: ...;
                                                    mimeType: ...;
                                                    type: ...;
                                                },
                                                $strip,
                                            >,
                                            ZodObject<
                                                {
                                                    _meta: ...;
                                                    annotations: ...;
                                                    data: ...;
                                                    mimeType: ...;
                                                    type: ...;
                                                },
                                                $strip,
                                            >,
                                            ZodObject<
                                                {
                                                    _meta: ...;
                                                    annotations: ...;
                                                    description: ...;
                                                    icons: ...;
                                                    mimeType: ...;
                                                    name: ...;
                                                    title: ...;
                                                    type: ...;
                                                    uri: ...;
                                                },
                                                $strip,
                                            >,
                                            ZodObject<
                                                { _meta: ...; annotations: ...; resource: ...; type: ... },
                                                $strip,
                                            >,
                                        ],
                                    >,
                                >,
                            >;
                            isError: ZodOptional<ZodBoolean>;
                            structuredContent: ZodOptional<ZodRecord<ZodString, ZodUnknown>>;
                        },
                        $loose,
                    >,
                    ZodObject<
                        {
                            _meta: ZodOptional<
                                ZodObject<
                                    {
                                        "io.modelcontextprotocol/related-task": ZodOptional<
                                            ZodObject<{ taskId: ... }, $strip>,
                                        >;
                                        progressToken: ZodOptional<ZodUnion<readonly [(...), (...)]>>;
                                    },
                                    $loose,
                                >,
                            >;
                            toolResult: ZodUnknown;
                        },
                        $loose,
                    >,
                ],
            > = CallToolResultSchema
      • Optionaloptions: RequestOptions

      Returns Promise<
          | {
              _meta?: {
                  "io.modelcontextprotocol/related-task"?: { taskId: string };
                  progressToken?: string | number;
                  [key: string]: unknown;
              };
              content: (
                  | {
                      _meta?: Record<string, unknown>;
                      annotations?: {
                          audience?: ((...) | (...))[];
                          lastModified?: string;
                          priority?: number;
                      };
                      text: string;
                      type: "text";
                  }
                  | {
                      _meta?: Record<string, unknown>;
                      annotations?: {
                          audience?: ((...) | (...))[];
                          lastModified?: string;
                          priority?: number;
                      };
                      data: string;
                      mimeType: string;
                      type: "image";
                  }
                  | {
                      _meta?: Record<string, unknown>;
                      annotations?: {
                          audience?: ((...) | (...))[];
                          lastModified?: string;
                          priority?: number;
                      };
                      data: string;
                      mimeType: string;
                      type: "audio";
                  }
                  | {
                      _meta?: Record<string, unknown>;
                      annotations?: {
                          audience?: ((...) | (...))[];
                          lastModified?: string;
                          priority?: number;
                      };
                      resource: | {
                          _meta?: Record<string, unknown>;
                          mimeType?: string;
                          text: string;
                          uri: string;
                      }
                      | {
                          _meta?: Record<string, unknown>;
                          blob: string;
                          mimeType?: string;
                          uri: string;
                      };
                      type: "resource";
                  }
                  | {
                      _meta?: { [key: string]: unknown };
                      annotations?: {
                          audience?: ((...) | (...))[];
                          lastModified?: string;
                          priority?: number;
                      };
                      description?: string;
                      icons?: {
                          mimeType?: string;
                          sizes?: (...)[];
                          src: string;
                          theme?: "light" | "dark";
                      }[];
                      mimeType?: string;
                      name: string;
                      title?: string;
                      type: "resource_link";
                      uri: string;
                  }
              )[];
              isError?: boolean;
              structuredContent?: Record<string, unknown>;
              [key: string]: unknown;
          }
          | {
              _meta?: {
                  "io.modelcontextprotocol/related-task"?: { taskId: string };
                  progressToken?: string | number;
                  [key: string]: unknown;
              };
              toolResult: unknown;
              [key: string]: unknown;
          },
      >

      const result = await client.callTool({
      name: 'calculate-bmi',
      arguments: { weightKg: 70, heightM: 1.75 }
      });

      // Tool-level errors are returned in the result, not thrown
      if (result.isError) {
      console.error('Tool error:', result.content);
      return;
      }

      console.log(result.content);
      const result = await client.callTool({
      name: 'calculate-bmi',
      arguments: { weightKg: 70, heightM: 1.75 }
      });

      // Machine-readable output for the client application
      if (result.structuredContent) {
      console.log(result.structuredContent); // e.g. { bmi: 22.86 }
      }
    • Experimental

      Cancels a specific task.

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

      Parameters

      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;
          },
      >

    • Requests argument autocompletion suggestions from the server for a prompt or resource.

      Parameters

      • params: {
            _meta?: {
                "io.modelcontextprotocol/related-task"?: { taskId: string };
                progressToken?: string | number;
                [key: string]: unknown;
            };
            argument: { name: string; value: string };
            context?: { arguments?: { [key: string]: string } };
            ref:
                | { type: "ref/resource"; uri: string }
                | { name: string; type: "ref/prompt" };
        }
        • Optional_meta?: {
              "io.modelcontextprotocol/related-task"?: { taskId: string };
              progressToken?: string | number;
              [key: string]: unknown;
          }

          See General fields: _meta for notes on _meta usage.

          • Optionalio.modelcontextprotocol/related-task?: { taskId: string }

            If specified, this request is related to the provided task.

          • OptionalprogressToken?: string | number

            If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications.

        • argument: { name: string; value: string }

          The argument's information

          • name: string

            The name of the argument

          • value: string

            The value of the argument to use for completion matching.

        • Optionalcontext?: { arguments?: { [key: string]: string } }
          • Optionalarguments?: { [key: string]: string }

            Previously-resolved variables in a URI template or prompt.

        • ref: { type: "ref/resource"; uri: string } | { name: string; type: "ref/prompt" }
      • Optionaloptions: RequestOptions

      Returns Promise<
          {
              _meta?: {
                  "io.modelcontextprotocol/related-task"?: { taskId: string };
                  progressToken?: string | number;
                  [key: string]: unknown;
              };
              completion: {
                  hasMore?: boolean;
                  total?: number;
                  values: string[];
                  [key: string]: unknown;
              };
              [key: string]: unknown;
          },
      >

    • Connects to a server via the given transport and performs the MCP initialization handshake.

      Parameters

      Returns Promise<void>

      const client = new Client({ name: 'my-client', version: '1.0.0' });
      const transport = new StdioClientTransport({ command: 'my-mcp-server' });
      await client.connect(transport);
      const baseUrl = new URL(url);

      try {
      // Try modern Streamable HTTP transport first
      const client = new Client({ name: 'my-client', version: '1.0.0' });
      const transport = new StreamableHTTPClientTransport(baseUrl);
      await client.connect(transport);
      return { client, transport };
      } catch {
      // Fall back to legacy SSE transport
      const client = new Client({ name: 'my-client', version: '1.0.0' });
      const transport = new SSEClientTransport(baseUrl);
      await client.connect(transport);
      return { client, transport };
      }
    • After initialization has completed, this may be populated with information about the server's instructions.

      Returns string | undefined

    • Retrieves a prompt by name from the server, passing the given arguments for template substitution.

      Parameters

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

          See General fields: _meta for notes on _meta usage.

          • Optionalio.modelcontextprotocol/related-task?: { taskId: string }

            If specified, this request is related to the provided task.

          • OptionalprogressToken?: string | number

            If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications.

        • Optionalarguments?: { [key: string]: string }

          Arguments to use for templating the prompt.

        • name: string

          The name of the prompt or prompt template.

      • Optionaloptions: RequestOptions

      Returns Promise<
          {
              _meta?: {
                  "io.modelcontextprotocol/related-task"?: { taskId: string };
                  progressToken?: string | number;
                  [key: string]: unknown;
              };
              description?: string;
              messages: {
                  content: | {
                      _meta?: Record<string, unknown>;
                      annotations?: {
                          audience?: ((...) | (...))[];
                          lastModified?: string;
                          priority?: number;
                      };
                      text: string;
                      type: "text";
                  }
                  | {
                      _meta?: Record<string, unknown>;
                      annotations?: {
                          audience?: ((...) | (...))[];
                          lastModified?: string;
                          priority?: number;
                      };
                      data: string;
                      mimeType: string;
                      type: "image";
                  }
                  | {
                      _meta?: Record<string, unknown>;
                      annotations?: {
                          audience?: ((...) | (...))[];
                          lastModified?: string;
                          priority?: number;
                      };
                      data: string;
                      mimeType: string;
                      type: "audio";
                  }
                  | {
                      _meta?: Record<string, unknown>;
                      annotations?: {
                          audience?: ((...) | (...))[];
                          lastModified?: string;
                          priority?: number;
                      };
                      resource: | {
                          _meta?: Record<string, unknown>;
                          mimeType?: string;
                          text: string;
                          uri: string;
                      }
                      | {
                          _meta?: Record<string, unknown>;
                          blob: string;
                          mimeType?: string;
                          uri: string;
                      };
                      type: "resource";
                  }
                  | {
                      _meta?: { [key: string]: unknown };
                      annotations?: {
                          audience?: ((...) | (...))[];
                          lastModified?: string;
                          priority?: number;
                      };
                      description?: string;
                      icons?: {
                          mimeType?: string;
                          sizes?: (...)[];
                          src: string;
                          theme?: "light" | "dark";
                      }[];
                      mimeType?: string;
                      name: string;
                      title?: string;
                      type: "resource_link";
                      uri: string;
                  };
                  role: "user"
                  | "assistant";
              }[];
              [key: string]: unknown;
          },
      >

    • After initialization has completed, this will be populated with the server's reported capabilities.

      Returns
          | {
              completions?: object;
              experimental?: { [key: string]: object };
              logging?: object;
              prompts?: { listChanged?: boolean };
              resources?: { listChanged?: boolean; subscribe?: boolean };
              tasks?: {
                  cancel?: object;
                  list?: object;
                  requests?: {
                      tools?: { call?: object; [key: string]: unknown };
                      [key: string]: unknown;
                  };
                  [key: string]: unknown;
              };
              tools?: { listChanged?: boolean };
          }
          | undefined

      • {
            completions?: object;
            experimental?: { [key: string]: object };
            logging?: object;
            prompts?: { listChanged?: boolean };
            resources?: { listChanged?: boolean; subscribe?: boolean };
            tasks?: {
                cancel?: object;
                list?: object;
                requests?: {
                    tools?: { call?: object; [key: string]: unknown };
                    [key: string]: unknown;
                };
                [key: string]: unknown;
            };
            tools?: { listChanged?: boolean };
        }
        • Optionalcompletions?: object

          Present if the server supports sending completions to the client.

        • Optionalexperimental?: { [key: string]: object }

          Experimental, non-standard capabilities that the server supports.

        • Optionallogging?: object

          Present if the server supports sending log messages to the client.

        • Optionalprompts?: { listChanged?: boolean }

          Present if the server offers any prompt templates.

          • OptionallistChanged?: boolean

            Whether this server supports issuing notifications for changes to the prompt list.

        • Optionalresources?: { listChanged?: boolean; subscribe?: boolean }

          Present if the server offers any resources to read.

          • OptionallistChanged?: boolean

            Whether this server supports issuing notifications for changes to the resource list.

          • Optionalsubscribe?: boolean

            Whether this server supports clients subscribing to resource updates.

        • Optionaltasks?: {
              cancel?: object;
              list?: object;
              requests?: {
                  tools?: { call?: object; [key: string]: unknown };
                  [key: string]: unknown;
              };
              [key: string]: unknown;
          }

          Present if the server supports task creation.

          • Optionalcancel?: object

            Present if the server supports cancelling tasks.

          • Optionallist?: object

            Present if the server supports listing tasks.

          • Optionalrequests?: { tools?: { call?: object; [key: string]: unknown }; [key: string]: unknown }

            Capabilities for task creation on specific request types.

            • Optionaltools?: { call?: object; [key: string]: unknown }

              Task support for tool requests.

        • Optionaltools?: { listChanged?: boolean }

          Present if the server offers any tools to call.

          • OptionallistChanged?: boolean

            Whether this server supports issuing notifications for changes to the tool list.

      • undefined
    • After initialization has completed, this will be populated with information about the server's name and version.

      Returns
          | {
              description?: string;
              icons?: {
                  mimeType?: string;
                  sizes?: string[];
                  src: string;
                  theme?: "light"
                  | "dark";
              }[];
              name: string;
              title?: string;
              version: string;
              websiteUrl?: string;
          }
          | undefined

      • {
            description?: string;
            icons?: {
                mimeType?: string;
                sizes?: string[];
                src: string;
                theme?: "light" | "dark";
            }[];
            name: string;
            title?: string;
            version: string;
            websiteUrl?: string;
        }
        • Optionaldescription?: string

          An optional human-readable description of what this implementation does.

          This can be used by clients or servers to provide context about their purpose and capabilities. For example, a server might describe the types of resources or tools it provides, while a client might describe its intended use case.

        • Optionalicons?: { mimeType?: string; sizes?: string[]; src: string; theme?: "light" | "dark" }[]

          Optional set of sized icons that the client can display in a user interface.

          Clients that support rendering icons MUST support at least the following MIME types:

          • image/png - PNG images (safe, universal compatibility)
          • image/jpeg (and image/jpg) - JPEG images (safe, universal compatibility)

          Clients that support rendering icons SHOULD also support:

          • image/svg+xml - SVG images (scalable but requires security precautions)
          • image/webp - WebP images (modern, efficient format)
        • name: string

          Intended for programmatic or logical use, but used as a display name in past specs or fallback

        • Optionaltitle?: string

          Intended for UI and end-user contexts — optimized to be human-readable and easily understood, even by those unfamiliar with domain-specific terminology.

          If not provided, the name should be used for display (except for Tool, where annotations.title should be given precedence over using name, if present).

        • version: string
        • OptionalwebsiteUrl?: string

          An optional URL of the website for this implementation.

      • 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;
        }
        • Optional_meta?: {
              "io.modelcontextprotocol/related-task"?: { taskId: string };
              progressToken?: string | number;
              [key: string]: unknown;
          }

          See General fields: _meta for notes on _meta usage.

          • Optionalio.modelcontextprotocol/related-task?: { taskId: string }

            If specified, this request is related to the provided task.

          • OptionalprogressToken?: string | number

            If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications.

        • 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

      Parameters

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

          See General fields: _meta for notes on _meta usage.

          • Optionalio.modelcontextprotocol/related-task?: { taskId: string }

            If specified, this request is related to the provided task.

          • OptionalprogressToken?: string | number

            If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications.

        • taskId: string
      • resultSchema: T
      • Optionaloptions: RequestOptions

      Returns Promise<SchemaOutput<T>>

    • Lists available prompts. Results may be paginated — loop on nextCursor to collect all pages.

      Returns an empty list if the server does not advertise prompts capability (or throws if ClientOptions.enforceStrictCapabilities is enabled).

      Parameters

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

          See General fields: _meta for notes on _meta usage.

          • Optionalio.modelcontextprotocol/related-task?: { taskId: string }

            If specified, this request is related to the provided task.

          • OptionalprogressToken?: string | number

            If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications.

        • Optionalcursor?: string

          An opaque token representing the current pagination position. If provided, the server should return results starting after this cursor.

      • Optionaloptions: RequestOptions

      Returns Promise<
          {
              _meta?: {
                  "io.modelcontextprotocol/related-task"?: { taskId: string };
                  progressToken?: string | number;
                  [key: string]: unknown;
              };
              nextCursor?: string;
              prompts: {
                  _meta?: { [key: string]: unknown };
                  arguments?: { description?: string; name: string; required?: boolean }[];
                  description?: string;
                  icons?: {
                      mimeType?: string;
                      sizes?: string[];
                      src: string;
                      theme?: "light" | "dark";
                  }[];
                  name: string;
                  title?: string;
              }[];
              [key: string]: unknown;
          },
      >

      const allPrompts: Prompt[] = [];
      let cursor: string | undefined;
      do {
      const { prompts, nextCursor } = await client.listPrompts({ cursor });
      allPrompts.push(...prompts);
      cursor = nextCursor;
      } while (cursor);
      console.log(
      'Available prompts:',
      allPrompts.map(p => p.name)
      );
    • Lists available resources. Results may be paginated — loop on nextCursor to collect all pages.

      Returns an empty list if the server does not advertise resources capability (or throws if ClientOptions.enforceStrictCapabilities is enabled).

      Parameters

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

          See General fields: _meta for notes on _meta usage.

          • Optionalio.modelcontextprotocol/related-task?: { taskId: string }

            If specified, this request is related to the provided task.

          • OptionalprogressToken?: string | number

            If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications.

        • Optionalcursor?: string

          An opaque token representing the current pagination position. If provided, the server should return results starting after this cursor.

      • Optionaloptions: RequestOptions

      Returns Promise<
          {
              _meta?: {
                  "io.modelcontextprotocol/related-task"?: { taskId: string };
                  progressToken?: string | number;
                  [key: string]: unknown;
              };
              nextCursor?: string;
              resources: {
                  _meta?: { [key: string]: unknown };
                  annotations?: {
                      audience?: ("user" | "assistant")[];
                      lastModified?: string;
                      priority?: number;
                  };
                  description?: string;
                  icons?: {
                      mimeType?: string;
                      sizes?: string[];
                      src: string;
                      theme?: "light"
                      | "dark";
                  }[];
                  mimeType?: string;
                  name: string;
                  title?: string;
                  uri: string;
              }[];
              [key: string]: unknown;
          },
      >

      const allResources: Resource[] = [];
      let cursor: string | undefined;
      do {
      const { resources, nextCursor } = await client.listResources({ cursor });
      allResources.push(...resources);
      cursor = nextCursor;
      } while (cursor);
      console.log(
      'Available resources:',
      allResources.map(r => r.name)
      );
    • Lists available resource URI templates for dynamic resources. Results may be paginated — see listResources() for the cursor pattern.

      Returns an empty list if the server does not advertise resources capability (or throws if ClientOptions.enforceStrictCapabilities is enabled).

      Parameters

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

          See General fields: _meta for notes on _meta usage.

          • Optionalio.modelcontextprotocol/related-task?: { taskId: string }

            If specified, this request is related to the provided task.

          • OptionalprogressToken?: string | number

            If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications.

        • Optionalcursor?: string

          An opaque token representing the current pagination position. If provided, the server should return results starting after this cursor.

      • Optionaloptions: RequestOptions

      Returns Promise<
          {
              _meta?: {
                  "io.modelcontextprotocol/related-task"?: { taskId: string };
                  progressToken?: string | number;
                  [key: string]: unknown;
              };
              nextCursor?: string;
              resourceTemplates: {
                  _meta?: { [key: string]: unknown };
                  annotations?: {
                      audience?: ("user" | "assistant")[];
                      lastModified?: string;
                      priority?: number;
                  };
                  description?: string;
                  icons?: {
                      mimeType?: string;
                      sizes?: string[];
                      src: string;
                      theme?: "light"
                      | "dark";
                  }[];
                  mimeType?: string;
                  name: string;
                  title?: string;
                  uriTemplate: string;
              }[];
              [key: string]: unknown;
          },
      >

    • Experimental

      Lists tasks, optionally starting from a pagination cursor.

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

      Parameters

      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;
          },
      >

    • Lists available tools. Results may be paginated — loop on nextCursor to collect all pages.

      Returns an empty list if the server does not advertise tools capability (or throws if ClientOptions.enforceStrictCapabilities is enabled).

      Parameters

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

          See General fields: _meta for notes on _meta usage.

          • Optionalio.modelcontextprotocol/related-task?: { taskId: string }

            If specified, this request is related to the provided task.

          • OptionalprogressToken?: string | number

            If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications.

        • Optionalcursor?: string

          An opaque token representing the current pagination position. If provided, the server should return results starting after this cursor.

      • Optionaloptions: RequestOptions

      Returns Promise<
          {
              _meta?: {
                  "io.modelcontextprotocol/related-task"?: { taskId: string };
                  progressToken?: string | number;
                  [key: string]: unknown;
              };
              nextCursor?: string;
              tools: {
                  _meta?: Record<string, unknown>;
                  annotations?: {
                      destructiveHint?: boolean;
                      idempotentHint?: boolean;
                      openWorldHint?: boolean;
                      readOnlyHint?: boolean;
                      title?: string;
                  };
                  description?: string;
                  execution?: { taskSupport?: "optional"
                  | "required"
                  | "forbidden" };
                  icons?: {
                      mimeType?: string;
                      sizes?: string[];
                      src: string;
                      theme?: "light" | "dark";
                  }[];
                  inputSchema: {
                      properties?: Record<string, object>;
                      required?: string[];
                      type: "object";
                      [key: string]: unknown;
                  };
                  name: string;
                  outputSchema?: {
                      properties?: Record<string, object>;
                      required?: string[];
                      type: "object";
                      [key: string]: unknown;
                  };
                  title?: string;
              }[];
              [key: string]: unknown;
          },
      >

      const allTools: Tool[] = [];
      let cursor: string | undefined;
      do {
      const { tools, nextCursor } = await client.listTools({ cursor });
      allTools.push(...tools);
      cursor = nextCursor;
      } while (cursor);
      console.log(
      'Available tools:',
      allTools.map(t => t.name)
      );
    • Emits a notification, which is a one-way message that does not expect a response.

      Parameters

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

      Returns Promise<void>

    • Sends a ping to the server to check connectivity.

      Parameters

      Returns Promise<
          {
              _meta?: {
                  "io.modelcontextprotocol/related-task"?: { taskId: string };
                  progressToken?: string | number;
                  [key: string]: unknown;
              };
          },
      >

    • Reads the contents of a resource by URI.

      Parameters

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

          See General fields: _meta for notes on _meta usage.

          • Optionalio.modelcontextprotocol/related-task?: { taskId: string }

            If specified, this request is related to the provided task.

          • OptionalprogressToken?: string | number

            If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications.

        • uri: string

          The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it.

          uri

      • Optionaloptions: RequestOptions

      Returns Promise<
          {
              _meta?: {
                  "io.modelcontextprotocol/related-task"?: { taskId: string };
                  progressToken?: string | number;
                  [key: string]: unknown;
              };
              contents: (
                  | {
                      _meta?: Record<string, unknown>;
                      mimeType?: string;
                      text: string;
                      uri: string;
                  }
                  | {
                      _meta?: Record<string, unknown>;
                      blob: string;
                      mimeType?: string;
                      uri: string;
                  }
              )[];
              [key: string]: unknown;
          },
      >

    • Registers new capabilities. This can only be called before connecting to a transport.

      The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization).

      Parameters

      • capabilities: {
            elicitation?: {
                form?: { applyDefaults?: boolean; [key: string]: unknown };
                url?: object;
                [key: string]: unknown;
            };
            experimental?: { [key: string]: object };
            roots?: { listChanged?: boolean };
            sampling?: { context?: object; tools?: object };
            tasks?: {
                cancel?: object;
                list?: object;
                requests?: {
                    elicitation?: { create?: object; [key: string]: unknown };
                    sampling?: { createMessage?: object; [key: string]: unknown };
                    [key: string]: unknown;
                };
                [key: string]: unknown;
            };
        }
        • Optionalelicitation?: {
              form?: { applyDefaults?: boolean; [key: string]: unknown };
              url?: object;
              [key: string]: unknown;
          }

          Present if the client supports eliciting user input.

        • Optionalexperimental?: { [key: string]: object }

          Experimental, non-standard capabilities that the client supports.

        • Optionalroots?: { listChanged?: boolean }

          Present if the client supports listing roots.

          • OptionallistChanged?: boolean

            Whether the client supports issuing notifications for changes to the roots list.

        • Optionalsampling?: { context?: object; tools?: object }

          Present if the client supports sampling from an LLM.

          • Optionalcontext?: object

            Present if the client supports context inclusion via includeContext parameter. If not declared, servers SHOULD only use includeContext: "none" (or omit it).

          • Optionaltools?: object

            Present if the client supports tool use via tools and toolChoice parameters.

        • Optionaltasks?: {
              cancel?: object;
              list?: object;
              requests?: {
                  elicitation?: { create?: object; [key: string]: unknown };
                  sampling?: { createMessage?: object; [key: string]: unknown };
                  [key: string]: unknown;
              };
              [key: string]: unknown;
          }

          Present if the client supports task creation.

          • Optionalcancel?: object

            Present if the client supports cancelling tasks.

          • Optionallist?: object

            Present if the client supports listing tasks.

          • Optionalrequests?: {
                elicitation?: { create?: object; [key: string]: unknown };
                sampling?: { createMessage?: object; [key: string]: unknown };
                [key: string]: unknown;
            }

            Capabilities for task creation on specific request types.

            • Optionalelicitation?: { create?: object; [key: string]: unknown }

              Task support for elicitation requests.

            • Optionalsampling?: { createMessage?: object; [key: string]: unknown }

              Task support for sampling requests.

      Returns void

    • Sends a request and waits for a response.

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

      Type Parameters

      Parameters

      • request: {
            method: string;
            params?: {
                _meta?: {
                    "io.modelcontextprotocol/related-task"?: { taskId: string };
                    progressToken?: string | number;
                    [key: string]: unknown;
                };
                [key: string]: unknown;
            };
        }
      • 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.

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

      Type Parameters

      Parameters

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

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

    • Notifies the server that the client's root list has changed. Requires the roots.listChanged capability.

      Returns Promise<void>

    • Sets the minimum severity level for log messages sent by the server.

      Parameters

      Returns Promise<
          {
              _meta?: {
                  "io.modelcontextprotocol/related-task"?: { taskId: string };
                  progressToken?: string | number;
                  [key: string]: unknown;
              };
          },
      >

    • Registers a handler for server-initiated requests (sampling, elicitation, roots). The client must declare the corresponding capability for the handler to be accepted. Replaces any previously registered handler for the same method.

      For sampling/createMessage and elicitation/create, the handler is automatically wrapped with schema validation for both the incoming request and the returned result.

      Type Parameters

      Parameters

      Returns void

      client.setRequestHandler('sampling/createMessage', async request => {
      const lastMessage = request.params.messages.at(-1);
      console.log('Sampling request:', lastMessage);

      // In production, send messages to your LLM here
      return {
      model: 'my-model',
      role: 'assistant' as const,
      content: {
      type: 'text' as const,
      text: 'Response from the model'
      }
      };
      });
    • Subscribes to change notifications for a resource. The server must support resource subscriptions.

      Parameters

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

          See General fields: _meta for notes on _meta usage.

          • Optionalio.modelcontextprotocol/related-task?: { taskId: string }

            If specified, this request is related to the provided task.

          • OptionalprogressToken?: string | number

            If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications.

        • uri: string

          The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it.

          uri

      • Optionaloptions: RequestOptions

      Returns Promise<
          {
              _meta?: {
                  "io.modelcontextprotocol/related-task"?: { taskId: string };
                  progressToken?: string | number;
                  [key: string]: unknown;
              };
          },
      >

    • Unsubscribes from change notifications for a resource.

      Parameters

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

          See General fields: _meta for notes on _meta usage.

          • Optionalio.modelcontextprotocol/related-task?: { taskId: string }

            If specified, this request is related to the provided task.

          • OptionalprogressToken?: string | number

            If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications.

        • uri: string

          The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it.

          uri

      • Optionaloptions: RequestOptions

      Returns Promise<
          {
              _meta?: {
                  "io.modelcontextprotocol/related-task"?: { taskId: string };
                  progressToken?: string | number;
                  [key: string]: unknown;
              };
          },
      >