Add code reference links and backticks to JSDoc comments (#1484)
Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com> Co-authored-by: Felix Weinberger <3823880+felixweinberger@users.noreply.github.com>
This commit is contained in:
parent
91f6a277c4
commit
42b335953a
38 changed files with 400 additions and 400 deletions
|
|
@ -44,8 +44,8 @@ export type AddClientAuthentication = (
|
|||
export interface OAuthClientProvider {
|
||||
/**
|
||||
* The URL to redirect the user agent to after authorization.
|
||||
* Return undefined for non-interactive flows that don't require user interaction
|
||||
* (e.g., client_credentials, jwt-bearer).
|
||||
* Return `undefined` for non-interactive flows that don't require user interaction
|
||||
* (e.g., `client_credentials`, `jwt-bearer`).
|
||||
*/
|
||||
get redirectUrl(): string | URL | undefined;
|
||||
|
||||
|
|
@ -74,7 +74,7 @@ export interface OAuthClientProvider {
|
|||
/**
|
||||
* If implemented, this permits the OAuth client to dynamically register with
|
||||
* the server. Client information saved this way should later be read via
|
||||
* `clientInformation()`.
|
||||
* {@linkcode OAuthClientProvider.clientInformation | clientInformation()}.
|
||||
*
|
||||
* This method is not required to be implemented if client information is
|
||||
* statically known (e.g., pre-registered).
|
||||
|
|
@ -154,11 +154,11 @@ export interface OAuthClientProvider {
|
|||
* any grant-specific parameters needed for the token exchange.
|
||||
*
|
||||
* If not implemented, the default behavior depends on the flow:
|
||||
* - For authorization code flow: uses code, code_verifier, and redirect_uri
|
||||
* - For client_credentials: detected via grant_types in clientMetadata
|
||||
* - For authorization code flow: uses `code`, `code_verifier`, and `redirect_uri`
|
||||
* - For `client_credentials`: detected via `grant_types` in {@linkcode OAuthClientProvider.clientMetadata | clientMetadata}
|
||||
*
|
||||
* @param scope - Optional scope to request
|
||||
* @returns Grant type and parameters, or undefined to use default behavior
|
||||
* @returns Grant type and parameters, or `undefined` to use default behavior
|
||||
*
|
||||
* @example
|
||||
* // For client_credentials grant:
|
||||
|
|
@ -206,9 +206,9 @@ const AUTHORIZATION_CODE_CHALLENGE_METHOD = 'S256';
|
|||
* Determines the best client authentication method to use based on server support and client configuration.
|
||||
*
|
||||
* Priority order (highest to lowest):
|
||||
* 1. client_secret_basic (if client secret is available)
|
||||
* 2. client_secret_post (if client secret is available)
|
||||
* 3. none (for public clients)
|
||||
* 1. `client_secret_basic` (if client secret is available)
|
||||
* 2. `client_secret_post` (if client secret is available)
|
||||
* 3. `none` (for public clients)
|
||||
*
|
||||
* @param clientInformation - OAuth client information containing credentials
|
||||
* @param supportedMethods - Authentication methods supported by the authorization server
|
||||
|
|
@ -253,9 +253,9 @@ export function selectClientAuthMethod(clientInformation: OAuthClientInformation
|
|||
* Applies client authentication to the request based on the specified method.
|
||||
*
|
||||
* Implements OAuth 2.1 client authentication methods:
|
||||
* - client_secret_basic: HTTP Basic authentication (RFC 6749 Section 2.3.1)
|
||||
* - client_secret_post: Credentials in request body (RFC 6749 Section 2.3.1)
|
||||
* - none: Public client authentication (RFC 6749 Section 2.1)
|
||||
* - `client_secret_basic`: HTTP Basic authentication (RFC 6749 Section 2.3.1)
|
||||
* - `client_secret_post`: Credentials in request body (RFC 6749 Section 2.3.1)
|
||||
* - `none`: Public client authentication (RFC 6749 Section 2.1)
|
||||
*
|
||||
* @param method - The authentication method to use
|
||||
* @param clientInformation - OAuth client information containing credentials
|
||||
|
|
@ -323,12 +323,12 @@ function applyPublicAuth(clientId: string, params: URLSearchParams): void {
|
|||
* Parses an OAuth error response from a string or Response object.
|
||||
*
|
||||
* If the input is a standard OAuth2.0 error response, it will be parsed according to the spec
|
||||
* and an OAuthError will be returned with the appropriate error code.
|
||||
* If parsing fails, it falls back to a generic ServerError that includes
|
||||
* and an {@linkcode OAuthError} will be returned with the appropriate error code.
|
||||
* If parsing fails, it falls back to a generic {@linkcode OAuthErrorCode.ServerError | ServerError} that includes
|
||||
* the response status (if available) and original content.
|
||||
*
|
||||
* @param input - A Response object or string containing the error response
|
||||
* @returns A Promise that resolves to an OAuthError instance
|
||||
* @returns A Promise that resolves to an {@linkcode OAuthError} instance
|
||||
*/
|
||||
export async function parseErrorResponse(input: Response | string): Promise<OAuthError> {
|
||||
const statusCode = input instanceof Response ? input.status : undefined;
|
||||
|
|
@ -526,7 +526,7 @@ async function authInternal(
|
|||
|
||||
/**
|
||||
* SEP-991: URL-based Client IDs
|
||||
* Validate that the client_id is a valid URL with https scheme
|
||||
* Validate that the `client_id` is a valid URL with `https` scheme
|
||||
*/
|
||||
export function isHttpsUrl(value?: string): boolean {
|
||||
if (!value) return false;
|
||||
|
|
@ -564,7 +564,7 @@ export async function selectResourceURL(
|
|||
}
|
||||
|
||||
/**
|
||||
* Extract resource_metadata, scope, and error from WWW-Authenticate header.
|
||||
* Extract `resource_metadata`, `scope`, and `error` from `WWW-Authenticate` header.
|
||||
*/
|
||||
export function extractWWWAuthenticateParams(res: Response): { resourceMetadataUrl?: URL; scope?: string; error?: string } {
|
||||
const authenticateHeader = res.headers.get('WWW-Authenticate');
|
||||
|
|
@ -599,10 +599,10 @@ export function extractWWWAuthenticateParams(res: Response): { resourceMetadataU
|
|||
}
|
||||
|
||||
/**
|
||||
* Extracts a specific field's value from the WWW-Authenticate header string.
|
||||
* Extracts a specific field's value from the `WWW-Authenticate` header string.
|
||||
*
|
||||
* @param response The HTTP response object containing the headers.
|
||||
* @param fieldName The name of the field to extract (e.g., "realm", "nonce").
|
||||
* @param fieldName The name of the field to extract (e.g., `"realm"`, `"nonce"`).
|
||||
* @returns The field value
|
||||
*/
|
||||
function extractFieldFromWwwAuth(response: Response, fieldName: string): string | null {
|
||||
|
|
@ -626,8 +626,8 @@ function extractFieldFromWwwAuth(response: Response, fieldName: string): string
|
|||
}
|
||||
|
||||
/**
|
||||
* Extract resource_metadata from response header.
|
||||
* @deprecated Use `extractWWWAuthenticateParams` instead.
|
||||
* Extract `resource_metadata` from response header.
|
||||
* @deprecated Use {@linkcode extractWWWAuthenticateParams} instead.
|
||||
*/
|
||||
export function extractResourceMetadataUrl(res: Response): URL | undefined {
|
||||
const authenticateHeader = res.headers.get('WWW-Authenticate');
|
||||
|
|
@ -770,7 +770,7 @@ async function discoverMetadataWithFallback(
|
|||
* If the server returns a 404 for the well-known endpoint, this function will
|
||||
* return `undefined`. Any other errors will be thrown as exceptions.
|
||||
*
|
||||
* @deprecated This function is deprecated in favor of `discoverAuthorizationServerMetadata`.
|
||||
* @deprecated This function is deprecated in favor of {@linkcode discoverAuthorizationServerMetadata}.
|
||||
*/
|
||||
export async function discoverOAuthMetadata(
|
||||
issuer: string | URL,
|
||||
|
|
@ -888,7 +888,7 @@ export function buildDiscoveryUrls(authorizationServerUrl: string | URL): { url:
|
|||
* metadata was not found.
|
||||
* @param options - Configuration options
|
||||
* @param options.fetchFn - Optional fetch function for making HTTP requests, defaults to global fetch
|
||||
* @param options.protocolVersion - MCP protocol version to use, defaults to LATEST_PROTOCOL_VERSION
|
||||
* @param options.protocolVersion - MCP protocol version to use, defaults to {@linkcode LATEST_PROTOCOL_VERSION}
|
||||
* @returns Promise resolving to authorization server metadata, or undefined if discovery fails
|
||||
*/
|
||||
export async function discoverAuthorizationServerMetadata(
|
||||
|
|
@ -1016,13 +1016,13 @@ export async function startAuthorization(
|
|||
/**
|
||||
* Prepares token request parameters for an authorization code exchange.
|
||||
*
|
||||
* This is the default implementation used by fetchToken when the provider
|
||||
* doesn't implement prepareTokenRequest.
|
||||
* This is the default implementation used by {@linkcode fetchToken} when the provider
|
||||
* doesn't implement {@linkcode OAuthClientProvider.prepareTokenRequest | prepareTokenRequest}.
|
||||
*
|
||||
* @param authorizationCode - The authorization code received from the authorization endpoint
|
||||
* @param codeVerifier - The PKCE code verifier
|
||||
* @param redirectUri - The redirect URI used in the authorization request
|
||||
* @returns URLSearchParams for the authorization_code grant
|
||||
* @returns URLSearchParams for the `authorization_code` grant
|
||||
*/
|
||||
export function prepareAuthorizationCodeRequest(
|
||||
authorizationCode: string,
|
||||
|
|
@ -1039,7 +1039,7 @@ export function prepareAuthorizationCodeRequest(
|
|||
|
||||
/**
|
||||
* Internal helper to execute a token request with the given parameters.
|
||||
* Used by exchangeAuthorization, refreshAuthorization, and fetchToken.
|
||||
* Used by {@linkcode exchangeAuthorization}, {@linkcode refreshAuthorization}, and {@linkcode fetchToken}.
|
||||
*/
|
||||
async function executeTokenRequest(
|
||||
authorizationServerUrl: string | URL,
|
||||
|
|
@ -1157,7 +1157,7 @@ export async function exchangeAuthorization(
|
|||
*
|
||||
* @param authorizationServerUrl - The authorization server's base URL
|
||||
* @param options - Configuration object containing client info, refresh token, etc.
|
||||
* @returns Promise resolving to OAuth tokens (preserves original refresh_token if not replaced)
|
||||
* @returns Promise resolving to OAuth tokens (preserves original `refresh_token` if not replaced)
|
||||
* @throws {Error} When token refresh fails or authentication is invalid
|
||||
*/
|
||||
export async function refreshAuthorization(
|
||||
|
|
@ -1197,17 +1197,17 @@ export async function refreshAuthorization(
|
|||
}
|
||||
|
||||
/**
|
||||
* Unified token fetching that works with any grant type via provider.prepareTokenRequest().
|
||||
* Unified token fetching that works with any grant type via {@linkcode OAuthClientProvider.prepareTokenRequest | prepareTokenRequest()}.
|
||||
*
|
||||
* This function provides a single entry point for obtaining tokens regardless of the
|
||||
* OAuth grant type. The provider's prepareTokenRequest() method determines which grant
|
||||
* OAuth grant type. The provider's `prepareTokenRequest()` method determines which grant
|
||||
* to use and supplies the grant-specific parameters.
|
||||
*
|
||||
* @param provider - OAuth client provider that implements prepareTokenRequest()
|
||||
* @param provider - OAuth client provider that implements `prepareTokenRequest()`
|
||||
* @param authorizationServerUrl - The authorization server's base URL
|
||||
* @param options - Configuration for the token request
|
||||
* @returns Promise resolving to OAuth tokens
|
||||
* @throws {Error} When provider doesn't implement prepareTokenRequest or token fetch fails
|
||||
* @throws {Error} When provider doesn't implement `prepareTokenRequest` or token fetch fails
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
|
|
@ -1235,7 +1235,7 @@ export async function fetchToken(
|
|||
}: {
|
||||
metadata?: AuthorizationServerMetadata;
|
||||
resource?: URL;
|
||||
/** Authorization code for the default authorization_code grant flow */
|
||||
/** Authorization code for the default `authorization_code` grant flow */
|
||||
authorizationCode?: string;
|
||||
fetchFn?: FetchLike;
|
||||
} = {}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
/**
|
||||
* OAuth provider extensions for specialized authentication flows.
|
||||
*
|
||||
* This module provides ready-to-use OAuthClientProvider implementations
|
||||
* This module provides ready-to-use {@linkcode OAuthClientProvider} implementations
|
||||
* for common machine-to-machine authentication scenarios.
|
||||
*/
|
||||
|
||||
|
|
@ -11,7 +11,7 @@ import type { CryptoKey, JWK } from 'jose';
|
|||
import type { AddClientAuthentication, OAuthClientProvider } from './auth.js';
|
||||
|
||||
/**
|
||||
* Helper to produce a private_key_jwt client authentication function.
|
||||
* Helper to produce a `private_key_jwt` client authentication function.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
|
|
@ -90,16 +90,16 @@ export function createPrivateKeyJwtAuth(options: {
|
|||
}
|
||||
|
||||
/**
|
||||
* Options for creating a ClientCredentialsProvider.
|
||||
* Options for creating a {@linkcode ClientCredentialsProvider}.
|
||||
*/
|
||||
export interface ClientCredentialsProviderOptions {
|
||||
/**
|
||||
* The client_id for this OAuth client.
|
||||
* The `client_id` for this OAuth client.
|
||||
*/
|
||||
clientId: string;
|
||||
|
||||
/**
|
||||
* The client_secret for client_secret_basic authentication.
|
||||
* The `client_secret` for `client_secret_basic` authentication.
|
||||
*/
|
||||
clientSecret: string;
|
||||
|
||||
|
|
@ -110,10 +110,10 @@ export interface ClientCredentialsProviderOptions {
|
|||
}
|
||||
|
||||
/**
|
||||
* OAuth provider for client_credentials grant with client_secret_basic authentication.
|
||||
* OAuth provider for `client_credentials` grant with `client_secret_basic` authentication.
|
||||
*
|
||||
* This provider is designed for machine-to-machine authentication where
|
||||
* the client authenticates using a client_id and client_secret.
|
||||
* the client authenticates using a `client_id` and `client_secret`.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
|
|
@ -189,11 +189,11 @@ export class ClientCredentialsProvider implements OAuthClientProvider {
|
|||
}
|
||||
|
||||
/**
|
||||
* Options for creating a PrivateKeyJwtProvider.
|
||||
* Options for creating a {@linkcode PrivateKeyJwtProvider}.
|
||||
*/
|
||||
export interface PrivateKeyJwtProviderOptions {
|
||||
/**
|
||||
* The client_id for this OAuth client.
|
||||
* The `client_id` for this OAuth client.
|
||||
*/
|
||||
clientId: string;
|
||||
|
||||
|
|
@ -220,7 +220,7 @@ export interface PrivateKeyJwtProviderOptions {
|
|||
}
|
||||
|
||||
/**
|
||||
* OAuth provider for client_credentials grant with private_key_jwt authentication.
|
||||
* OAuth provider for `client_credentials` grant with `private_key_jwt` authentication.
|
||||
*
|
||||
* This provider is designed for machine-to-machine authentication where
|
||||
* the client authenticates using a signed JWT assertion
|
||||
|
|
@ -308,11 +308,11 @@ export class PrivateKeyJwtProvider implements OAuthClientProvider {
|
|||
}
|
||||
|
||||
/**
|
||||
* Options for creating a StaticPrivateKeyJwtProvider.
|
||||
* Options for creating a {@linkcode StaticPrivateKeyJwtProvider}.
|
||||
*/
|
||||
export interface StaticPrivateKeyJwtProviderOptions {
|
||||
/**
|
||||
* The client_id for this OAuth client.
|
||||
* The `client_id` for this OAuth client.
|
||||
*/
|
||||
clientId: string;
|
||||
|
||||
|
|
@ -320,7 +320,7 @@ export interface StaticPrivateKeyJwtProviderOptions {
|
|||
* A pre-built JWT client assertion to use for authentication.
|
||||
*
|
||||
* This token should already contain the appropriate claims
|
||||
* (iss, sub, aud, exp, etc.) and be signed by the client's key.
|
||||
* (`iss`, `sub`, `aud`, `exp`, etc.) and be signed by the client's key.
|
||||
*/
|
||||
jwtBearerAssertion: string;
|
||||
|
||||
|
|
@ -331,9 +331,9 @@ export interface StaticPrivateKeyJwtProviderOptions {
|
|||
}
|
||||
|
||||
/**
|
||||
* OAuth provider for client_credentials grant with a static private_key_jwt assertion.
|
||||
* OAuth provider for `client_credentials` grant with a static `private_key_jwt` assertion.
|
||||
*
|
||||
* This provider mirrors {@link PrivateKeyJwtProvider} but instead of constructing and
|
||||
* This provider mirrors {@linkcode PrivateKeyJwtProvider} but instead of constructing and
|
||||
* signing a JWT on each request, it accepts a pre-built JWT assertion string and
|
||||
* uses it directly for authentication.
|
||||
*/
|
||||
|
|
|
|||
|
|
@ -68,7 +68,7 @@ import {
|
|||
import { ExperimentalClientTasks } from '../experimental/tasks/client.js';
|
||||
|
||||
/**
|
||||
* Elicitation default application helper. Applies defaults to the data based on the schema.
|
||||
* Elicitation default application helper. Applies defaults to the `data` based on the `schema`.
|
||||
*
|
||||
* @param schema - The schema to apply defaults to.
|
||||
* @param data - The data to apply defaults to.
|
||||
|
|
@ -153,7 +153,7 @@ export type ClientOptions = ProtocolOptions & {
|
|||
* The validator is used to validate structured content returned by tools
|
||||
* against their declared output schemas.
|
||||
*
|
||||
* @default DefaultJsonSchemaValidator (AjvJsonSchemaValidator on Node.js, CfWorkerJsonSchemaValidator on Cloudflare Workers)
|
||||
* @default {@linkcode DefaultJsonSchemaValidator} ({@linkcode index.AjvJsonSchemaValidator | AjvJsonSchemaValidator} on Node.js, {@linkcode index.CfWorkerJsonSchemaValidator | CfWorkerJsonSchemaValidator} on Cloudflare Workers)
|
||||
*/
|
||||
jsonSchemaValidator?: jsonSchemaValidator;
|
||||
|
||||
|
|
@ -189,7 +189,7 @@ export type ClientOptions = ProtocolOptions & {
|
|||
/**
|
||||
* An MCP client on top of a pluggable transport.
|
||||
*
|
||||
* The client will automatically begin the initialization flow with the server when connect() is called.
|
||||
* The client will automatically begin the initialization flow with the server when {@linkcode connect} is called.
|
||||
*
|
||||
*/
|
||||
export class Client extends Protocol<ClientContext> {
|
||||
|
|
@ -713,9 +713,9 @@ export class Client extends Protocol<ClientContext> {
|
|||
}
|
||||
|
||||
/**
|
||||
* Calls a tool and waits for the result. Automatically validates structured output if the tool has an outputSchema.
|
||||
* Calls a tool and waits for the result. Automatically validates structured output if the tool has an `outputSchema`.
|
||||
*
|
||||
* For task-based execution with streaming behavior, use client.experimental.tasks.callToolStream() instead.
|
||||
* For task-based execution with streaming behavior, use {@linkcode ExperimentalClientTasks.callToolStream | client.experimental.tasks.callToolStream()} instead.
|
||||
*/
|
||||
async callTool(
|
||||
params: CallToolRequest['params'],
|
||||
|
|
@ -780,7 +780,7 @@ export class Client extends Protocol<ClientContext> {
|
|||
|
||||
/**
|
||||
* Check if a tool requires task-based execution.
|
||||
* Unlike isToolTask which includes 'optional' tools, this only checks for 'required'.
|
||||
* Unlike {@linkcode isToolTask} which includes `'optional'` tools, this only checks for `'required'`.
|
||||
*/
|
||||
private isToolTaskRequired(toolName: string): boolean {
|
||||
return this._cachedRequiredTaskTools.has(toolName);
|
||||
|
|
@ -788,7 +788,7 @@ export class Client extends Protocol<ClientContext> {
|
|||
|
||||
/**
|
||||
* Cache validators for tool output schemas.
|
||||
* Called after listTools() to pre-compile validators for better performance.
|
||||
* Called after {@linkcode listTools | listTools()} to pre-compile validators for better performance.
|
||||
*/
|
||||
private cacheToolMetadata(tools: Tool[]): void {
|
||||
this._cachedToolOutputValidators.clear();
|
||||
|
|
|
|||
|
|
@ -13,19 +13,19 @@ export type Middleware = (next: FetchLike) => FetchLike;
|
|||
* Creates a fetch wrapper that handles OAuth authentication automatically.
|
||||
*
|
||||
* This wrapper will:
|
||||
* - Add Authorization headers with access tokens
|
||||
* - Add `Authorization` headers with access tokens
|
||||
* - Handle 401 responses by attempting re-authentication
|
||||
* - Retry the original request after successful auth
|
||||
* - Handle OAuth errors appropriately (OAuthErrorCode.InvalidClient, etc.)
|
||||
* - Handle OAuth errors appropriately ({@linkcode index.OAuthErrorCode.InvalidClient | OAuthErrorCode.InvalidClient}, etc.)
|
||||
*
|
||||
* The baseUrl parameter is optional and defaults to using the domain from the request URL.
|
||||
* However, you should explicitly provide baseUrl when:
|
||||
* The `baseUrl` parameter is optional and defaults to using the domain from the request URL.
|
||||
* However, you should explicitly provide `baseUrl` when:
|
||||
* - Making requests to multiple subdomains (e.g., api.example.com, cdn.example.com)
|
||||
* - Using API paths that differ from OAuth discovery paths (e.g., requesting /api/v1/data but OAuth is at /)
|
||||
* - The OAuth server is on a different domain than your API requests
|
||||
* - You want to ensure consistent OAuth behavior regardless of request URLs
|
||||
*
|
||||
* For MCP transports, set baseUrl to the same URL you pass to the transport constructor.
|
||||
* For MCP transports, set `baseUrl` to the same URL you pass to the transport constructor.
|
||||
*
|
||||
* Note: This wrapper is designed for general-purpose fetch operations.
|
||||
* MCP transports (SSE and StreamableHTTP) already have built-in OAuth handling
|
||||
|
|
@ -133,7 +133,7 @@ export type LoggingOptions = {
|
|||
|
||||
/**
|
||||
* Status level filter - only log requests with status >= this value
|
||||
* Set to 0 to log all requests, 400 to log only errors
|
||||
* Set to `0` to log all requests, `400` to log only errors
|
||||
* @default 0
|
||||
*/
|
||||
statusLevel?: number;
|
||||
|
|
@ -145,7 +145,7 @@ export type LoggingOptions = {
|
|||
* When called without arguments `withLogging()`, it uses the default logger that:
|
||||
* - Logs successful requests (2xx) to `console.log`
|
||||
* - Logs error responses (4xx/5xx) and network errors to `console.error`
|
||||
* - Logs all requests regardless of status (statusLevel: 0)
|
||||
* - Logs all requests regardless of status (`statusLevel: 0`)
|
||||
* - Does not include request or response headers in logs
|
||||
* - Measures and displays request duration in milliseconds
|
||||
*
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@ export class SseError extends Error {
|
|||
}
|
||||
|
||||
/**
|
||||
* Configuration options for the `SSEClientTransport`.
|
||||
* Configuration options for the {@linkcode SSEClientTransport}.
|
||||
*/
|
||||
export type SSEClientTransportOptions = {
|
||||
/**
|
||||
|
|
@ -26,13 +26,13 @@ export type SSEClientTransportOptions = {
|
|||
* When an `authProvider` is specified and the SSE connection is started:
|
||||
* 1. The connection is attempted with any existing access token from the `authProvider`.
|
||||
* 2. If the access token has expired, the `authProvider` is used to refresh the token.
|
||||
* 3. If token refresh fails or no access token exists, and auth is required, `OAuthClientProvider.redirectToAuthorization` is called, and an `UnauthorizedError` will be thrown from `connect`/`start`.
|
||||
* 3. If token refresh fails or no access token exists, and auth is required, {@linkcode OAuthClientProvider.redirectToAuthorization} is called, and an {@linkcode UnauthorizedError} will be thrown from {@linkcode index.Protocol.connect | connect}/{@linkcode SSEClientTransport.start | start}.
|
||||
*
|
||||
* After the user has finished authorizing via their user agent, and is redirected back to the MCP client application, call `SSEClientTransport.finishAuth` with the authorization code before retrying the connection.
|
||||
* After the user has finished authorizing via their user agent, and is redirected back to the MCP client application, call {@linkcode SSEClientTransport.finishAuth} with the authorization code before retrying the connection.
|
||||
*
|
||||
* If an `authProvider` is not provided, and auth is required, an `UnauthorizedError` will be thrown.
|
||||
* If an `authProvider` is not provided, and auth is required, an {@linkcode UnauthorizedError} will be thrown.
|
||||
*
|
||||
* `UnauthorizedError` might also be thrown when sending any message over the SSE transport, indicating that the session has expired, and needs to be re-authed and reconnected.
|
||||
* {@linkcode UnauthorizedError} might also be thrown when sending any message over the SSE transport, indicating that the session has expired, and needs to be re-authed and reconnected.
|
||||
*/
|
||||
authProvider?: OAuthClientProvider;
|
||||
|
||||
|
|
@ -40,14 +40,14 @@ export type SSEClientTransportOptions = {
|
|||
* Customizes the initial SSE request to the server (the request that begins the stream).
|
||||
*
|
||||
* NOTE: Setting this property will prevent an `Authorization` header from
|
||||
* being automatically attached to the SSE request, if an `authProvider` is
|
||||
* being automatically attached to the SSE request, if an {@linkcode SSEClientTransportOptions.authProvider | authProvider} is
|
||||
* also given. This can be worked around by setting the `Authorization` header
|
||||
* manually.
|
||||
*/
|
||||
eventSourceInit?: EventSourceInit;
|
||||
|
||||
/**
|
||||
* Customizes recurring POST requests to the server.
|
||||
* Customizes recurring `POST` requests to the server.
|
||||
*/
|
||||
requestInit?: RequestInit;
|
||||
|
||||
|
|
@ -59,8 +59,8 @@ export type SSEClientTransportOptions = {
|
|||
|
||||
/**
|
||||
* Client transport for SSE: this will connect to a server using Server-Sent Events for receiving
|
||||
* messages and make separate POST requests for sending messages.
|
||||
* @deprecated SSEClientTransport is deprecated. Prefer to use StreamableHTTPClientTransport where possible instead. Note that because some servers are still using SSE, clients may need to support both transports during the migration period.
|
||||
* messages and make separate `POST` requests for sending messages.
|
||||
* @deprecated SSEClientTransport is deprecated. Prefer to use {@linkcode index.StreamableHTTPClientTransport | StreamableHTTPClientTransport} where possible instead. Note that because some servers are still using SSE, clients may need to support both transports during the migration period.
|
||||
*/
|
||||
export class SSEClientTransport implements Transport {
|
||||
private _eventSource?: EventSource;
|
||||
|
|
|
|||
|
|
@ -21,14 +21,14 @@ export type StdioServerParameters = {
|
|||
/**
|
||||
* The environment to use when spawning the process.
|
||||
*
|
||||
* If not specified, the result of getDefaultEnvironment() will be used.
|
||||
* If not specified, the result of {@linkcode getDefaultEnvironment} will be used.
|
||||
*/
|
||||
env?: Record<string, string>;
|
||||
|
||||
/**
|
||||
* How to handle stderr of the child process. This matches the semantics of Node's `child_process.spawn`.
|
||||
*
|
||||
* The default is "inherit", meaning messages to stderr will be printed to the parent process's stderr.
|
||||
* The default is `"inherit"`, meaning messages to stderr will be printed to the parent process's stderr.
|
||||
*/
|
||||
stderr?: IOType | Stream | number;
|
||||
|
||||
|
|
@ -164,10 +164,10 @@ export class StdioClientTransport implements Transport {
|
|||
}
|
||||
|
||||
/**
|
||||
* The stderr stream of the child process, if `StdioServerParameters.stderr` was set to "pipe" or "overlapped".
|
||||
* The `stderr` stream of the child process, if {@linkcode StdioServerParameters.stderr} was set to `"pipe"` or `"overlapped"`.
|
||||
*
|
||||
* If stderr piping was requested, a PassThrough stream is returned _immediately_, allowing callers to
|
||||
* attach listeners before the start method is invoked. This prevents loss of any early
|
||||
* If `stderr` piping was requested, a `PassThrough` stream is returned _immediately_, allowing callers to
|
||||
* attach listeners before the `start` method is invoked. This prevents loss of any early
|
||||
* error output emitted by the child process.
|
||||
*/
|
||||
get stderr(): Stream | null {
|
||||
|
|
|
|||
|
|
@ -50,7 +50,7 @@ export interface StartSSEOptions {
|
|||
}
|
||||
|
||||
/**
|
||||
* Configuration options for reconnection behavior of the StreamableHTTPClientTransport.
|
||||
* Configuration options for reconnection behavior of the {@linkcode StreamableHTTPClientTransport}.
|
||||
*/
|
||||
export interface StreamableHTTPReconnectionOptions {
|
||||
/**
|
||||
|
|
@ -79,7 +79,7 @@ export interface StreamableHTTPReconnectionOptions {
|
|||
}
|
||||
|
||||
/**
|
||||
* Configuration options for the `StreamableHTTPClientTransport`.
|
||||
* Configuration options for the {@linkcode StreamableHTTPClientTransport}.
|
||||
*/
|
||||
export type StreamableHTTPClientTransportOptions = {
|
||||
/**
|
||||
|
|
@ -88,13 +88,13 @@ export type StreamableHTTPClientTransportOptions = {
|
|||
* When an `authProvider` is specified and the connection is started:
|
||||
* 1. The connection is attempted with any existing access token from the `authProvider`.
|
||||
* 2. If the access token has expired, the `authProvider` is used to refresh the token.
|
||||
* 3. If token refresh fails or no access token exists, and auth is required, `OAuthClientProvider.redirectToAuthorization` is called, and an `UnauthorizedError` will be thrown from `connect`/`start`.
|
||||
* 3. If token refresh fails or no access token exists, and auth is required, {@linkcode OAuthClientProvider.redirectToAuthorization} is called, and an {@linkcode UnauthorizedError} will be thrown from {@linkcode index.Protocol.connect | connect}/{@linkcode StreamableHTTPClientTransport.start | start}.
|
||||
*
|
||||
* After the user has finished authorizing via their user agent, and is redirected back to the MCP client application, call `StreamableHTTPClientTransport.finishAuth` with the authorization code before retrying the connection.
|
||||
* After the user has finished authorizing via their user agent, and is redirected back to the MCP client application, call {@linkcode StreamableHTTPClientTransport.finishAuth} with the authorization code before retrying the connection.
|
||||
*
|
||||
* If an `authProvider` is not provided, and auth is required, an `UnauthorizedError` will be thrown.
|
||||
* If an `authProvider` is not provided, and auth is required, an {@linkcode UnauthorizedError} will be thrown.
|
||||
*
|
||||
* `UnauthorizedError` might also be thrown when sending any message over the transport, indicating that the session has expired, and needs to be re-authed and reconnected.
|
||||
* {@linkcode UnauthorizedError} might also be thrown when sending any message over the transport, indicating that the session has expired, and needs to be re-authed and reconnected.
|
||||
*/
|
||||
authProvider?: OAuthClientProvider;
|
||||
|
||||
|
|
@ -122,7 +122,7 @@ export type StreamableHTTPClientTransportOptions = {
|
|||
|
||||
/**
|
||||
* Client transport for Streamable HTTP: this implements the MCP Streamable HTTP transport specification.
|
||||
* It will connect to a server using HTTP POST for sending messages and HTTP GET with Server-Sent Events
|
||||
* It will connect to a server using HTTP `POST` for sending messages and HTTP `GET` with Server-Sent Events
|
||||
* for receiving messages.
|
||||
*/
|
||||
export class StreamableHTTPClientTransport implements Transport {
|
||||
|
|
@ -628,14 +628,14 @@ export class StreamableHTTPClientTransport implements Transport {
|
|||
}
|
||||
|
||||
/**
|
||||
* Terminates the current session by sending a DELETE request to the server.
|
||||
* Terminates the current session by sending a `DELETE` request to the server.
|
||||
*
|
||||
* Clients that no longer need a particular session
|
||||
* (e.g., because the user is leaving the client application) SHOULD send an
|
||||
* HTTP DELETE to the MCP endpoint with the Mcp-Session-Id header to explicitly
|
||||
* HTTP `DELETE` to the MCP endpoint with the `Mcp-Session-Id` header to explicitly
|
||||
* terminate the session.
|
||||
*
|
||||
* The server MAY respond with HTTP 405 Method Not Allowed, indicating that
|
||||
* The server MAY respond with HTTP `405 Method Not Allowed`, indicating that
|
||||
* the server does not allow clients to terminate sessions.
|
||||
*/
|
||||
async terminateSession(): Promise<void> {
|
||||
|
|
@ -681,7 +681,7 @@ export class StreamableHTTPClientTransport implements Transport {
|
|||
|
||||
/**
|
||||
* Resume an SSE stream from a previous event ID.
|
||||
* Opens a GET SSE connection with Last-Event-ID header to replay missed events.
|
||||
* Opens a `GET` SSE connection with `Last-Event-ID` header to replay missed events.
|
||||
*
|
||||
* @param lastEventId The event ID to resume from
|
||||
* @param options Optional callback to receive new resumption tokens
|
||||
|
|
|
|||
|
|
@ -21,7 +21,7 @@ import { CallToolResultSchema, ProtocolError, ProtocolErrorCode } from '@modelco
|
|||
import type { Client } from '../../client/client.js';
|
||||
|
||||
/**
|
||||
* Internal interface for accessing Client's private methods.
|
||||
* Internal interface for accessing {@linkcode Client}'s private methods.
|
||||
* @internal
|
||||
*/
|
||||
interface ClientInternal {
|
||||
|
|
@ -50,11 +50,11 @@ export class ExperimentalClientTasks {
|
|||
|
||||
/**
|
||||
* Calls a tool and returns an AsyncGenerator that yields response messages.
|
||||
* The generator is guaranteed to end with either a 'result' or 'error' message.
|
||||
* The generator is guaranteed to end with either a `'result'` or `'error'` message.
|
||||
*
|
||||
* This method provides streaming access to tool execution, allowing you to
|
||||
* observe intermediate task status updates for long-running tool calls.
|
||||
* Automatically validates structured output if the tool has an outputSchema.
|
||||
* Automatically validates structured output if the tool has an `outputSchema`.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
|
|
@ -78,9 +78,9 @@ export class ExperimentalClientTasks {
|
|||
* ```
|
||||
*
|
||||
* @param params - Tool call parameters (name and arguments)
|
||||
* @param resultSchema - Zod schema for validating the result (defaults to CallToolResultSchema)
|
||||
* @param resultSchema - Zod schema for validating the result (defaults to {@linkcode CallToolResultSchema})
|
||||
* @param options - Optional request options (timeout, signal, task creation params, etc.)
|
||||
* @returns AsyncGenerator that yields ResponseMessage objects
|
||||
* @returns AsyncGenerator that yields {@linkcode ResponseMessage} objects
|
||||
*
|
||||
* @experimental
|
||||
*/
|
||||
|
|
@ -235,7 +235,7 @@ export class ExperimentalClientTasks {
|
|||
|
||||
/**
|
||||
* Sends a request and returns an AsyncGenerator that yields response messages.
|
||||
* The generator is guaranteed to end with either a 'result' or 'error' message.
|
||||
* The generator is guaranteed to end with either a `'result'` or `'error'` message.
|
||||
*
|
||||
* This method provides streaming access to request processing, allowing you to
|
||||
* observe intermediate task status updates for task-augmented requests.
|
||||
|
|
@ -243,7 +243,7 @@ export class ExperimentalClientTasks {
|
|||
* @param request - The request to send
|
||||
* @param resultSchema - Zod schema for validating the result
|
||||
* @param options - Optional request options (timeout, signal, task creation params, etc.)
|
||||
* @returns AsyncGenerator that yields ResponseMessage objects
|
||||
* @returns AsyncGenerator that yields {@linkcode ResponseMessage} objects
|
||||
*
|
||||
* @experimental
|
||||
*/
|
||||
|
|
|
|||
|
|
@ -124,7 +124,7 @@ export class OAuthError extends Error {
|
|||
}
|
||||
|
||||
/**
|
||||
* Creates an OAuthError from an OAuth error response.
|
||||
* Creates an {@linkcode OAuthError} from an OAuth error response.
|
||||
*/
|
||||
static fromResponse(response: OAuthErrorResponse): OAuthError {
|
||||
return new OAuthError(response.error as OAuthErrorCode, response.error_description ?? response.error, response.error_uri);
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
/**
|
||||
* Error codes for SDK errors (local errors that never cross the wire).
|
||||
* Unlike ProtocolErrorCode which uses numeric JSON-RPC codes, SdkErrorCode uses
|
||||
* Unlike {@linkcode ProtocolErrorCode} which uses numeric JSON-RPC codes, `SdkErrorCode` uses
|
||||
* descriptive string values for better developer experience.
|
||||
*
|
||||
* These errors are thrown locally by the SDK and are never serialized as
|
||||
|
|
@ -38,7 +38,7 @@ export enum SdkErrorCode {
|
|||
|
||||
/**
|
||||
* SDK errors are local errors that never cross the wire.
|
||||
* They are distinct from ProtocolError which represents JSON-RPC protocol errors
|
||||
* They are distinct from {@linkcode ProtocolError} which represents JSON-RPC protocol errors
|
||||
* that are serialized and sent as error responses.
|
||||
*
|
||||
* @example
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@
|
|||
|
||||
/**
|
||||
* Type representing the task requests capability structure.
|
||||
* This is derived from ClientTasksCapability.requests and ServerTasksCapability.requests.
|
||||
* This is derived from `ClientTasksCapability.requests` and `ServerTasksCapability.requests`.
|
||||
*/
|
||||
interface TaskRequestsCapability {
|
||||
tools?: { call?: object };
|
||||
|
|
@ -16,12 +16,12 @@ interface TaskRequestsCapability {
|
|||
}
|
||||
|
||||
/**
|
||||
* Asserts that task creation is supported for tools/call.
|
||||
* Used by Client.assertTaskCapability and Server.assertTaskHandlerCapability.
|
||||
* Asserts that task creation is supported for `tools/call`.
|
||||
* Used by {@linkcode @modelcontextprotocol/client!client/client.Client.assertTaskCapability | Client.assertTaskCapability} and {@linkcode @modelcontextprotocol/server!server/server.Server.assertTaskHandlerCapability | Server.assertTaskHandlerCapability}.
|
||||
*
|
||||
* @param requests - The task requests capability object
|
||||
* @param method - The method being checked
|
||||
* @param entityName - 'Server' or 'Client' for error messages
|
||||
* @param entityName - `'Server'` or `'Client'` for error messages
|
||||
* @throws Error if the capability is not supported
|
||||
*
|
||||
* @experimental
|
||||
|
|
@ -51,12 +51,12 @@ export function assertToolsCallTaskCapability(
|
|||
}
|
||||
|
||||
/**
|
||||
* Asserts that task creation is supported for sampling/createMessage or elicitation/create.
|
||||
* Used by Server.assertTaskCapability and Client.assertTaskHandlerCapability.
|
||||
* Asserts that task creation is supported for `sampling/createMessage` or `elicitation/create`.
|
||||
* Used by {@linkcode @modelcontextprotocol/server!server/server.Server.assertTaskCapability | Server.assertTaskCapability} and {@linkcode @modelcontextprotocol/client!client/client.Client.assertTaskHandlerCapability | Client.assertTaskHandlerCapability}.
|
||||
*
|
||||
* @param requests - The task requests capability object
|
||||
* @param method - The method being checked
|
||||
* @param entityName - 'Server' or 'Client' for error messages
|
||||
* @param entityName - `'Server'` or `'Client'` for error messages
|
||||
* @throws Error if the capability is not supported
|
||||
*
|
||||
* @experimental
|
||||
|
|
|
|||
|
|
@ -38,7 +38,7 @@ export type TaskServerContext = ServerContext & {
|
|||
|
||||
/**
|
||||
* Task-specific execution configuration.
|
||||
* taskSupport cannot be 'forbidden' for task-based tools.
|
||||
* `taskSupport` cannot be `'forbidden'` for task-based tools.
|
||||
* @experimental
|
||||
*/
|
||||
export type TaskToolExecution<TaskSupport = ToolExecution['taskSupport']> = Omit<ToolExecution, 'taskSupport'> & {
|
||||
|
|
@ -87,7 +87,7 @@ export interface QueuedError extends BaseQueuedMessage {
|
|||
/**
|
||||
* Interface for managing per-task FIFO message queues.
|
||||
*
|
||||
* Similar to TaskStore, this allows pluggable queue implementations
|
||||
* Similar to {@linkcode TaskStore}, this allows pluggable queue implementations
|
||||
* (in-memory, Redis, other distributed queues, etc.).
|
||||
*
|
||||
* Each method accepts taskId and optional sessionId parameters to enable
|
||||
|
|
@ -95,7 +95,7 @@ export interface QueuedError extends BaseQueuedMessage {
|
|||
* isolation based on task ID and session ID.
|
||||
*
|
||||
* All methods are async to support external storage implementations.
|
||||
* All data in QueuedMessage must be JSON-serializable.
|
||||
* All data in {@linkcode QueuedMessage} must be JSON-serializable.
|
||||
*
|
||||
* @see {@linkcode InMemoryTaskMessageQueue} for a reference implementation
|
||||
* @experimental
|
||||
|
|
@ -116,7 +116,7 @@ export interface TaskMessageQueue {
|
|||
* Removes and returns the first message from the queue for a specific task.
|
||||
* @param taskId The task identifier
|
||||
* @param sessionId Optional session ID for binding the query to a specific session
|
||||
* @returns The first message, or undefined if the queue is empty
|
||||
* @returns The first message, or `undefined` if the queue is empty
|
||||
*/
|
||||
dequeue(taskId: string, sessionId?: string): Promise<QueuedMessage | undefined>;
|
||||
|
||||
|
|
@ -137,7 +137,7 @@ export interface TaskMessageQueue {
|
|||
export interface CreateTaskOptions {
|
||||
/**
|
||||
* Time in milliseconds to keep task results available after completion.
|
||||
* If null, the task has unlimited lifetime until manually cleaned up.
|
||||
* If `null`, the task has unlimited lifetime until manually cleaned up.
|
||||
*/
|
||||
ttl?: number | null;
|
||||
|
||||
|
|
@ -155,7 +155,7 @@ export interface CreateTaskOptions {
|
|||
/**
|
||||
* Interface for storing and retrieving task state and results.
|
||||
*
|
||||
* Similar to Transport, this allows pluggable task storage implementations
|
||||
* Similar to {@linkcode Transport}, this allows pluggable task storage implementations
|
||||
* (in-memory, database, distributed cache, etc.).
|
||||
*
|
||||
* @see {@linkcode InMemoryTaskStore} for a reference implementation
|
||||
|
|
@ -167,17 +167,17 @@ export interface TaskStore {
|
|||
* The implementation must generate a unique taskId and createdAt timestamp.
|
||||
*
|
||||
* TTL Management:
|
||||
* - The implementation receives the TTL suggested by the requestor via taskParams.ttl
|
||||
* - The implementation receives the TTL suggested by the requestor via `taskParams.ttl`
|
||||
* - The implementation MAY override the requested TTL (e.g., to enforce limits)
|
||||
* - The actual TTL used MUST be returned in the Task object
|
||||
* - Null TTL indicates unlimited task lifetime (no automatic cleanup)
|
||||
* - The actual TTL used MUST be returned in the {@linkcode Task} object
|
||||
* - `null` TTL indicates unlimited task lifetime (no automatic cleanup)
|
||||
* - Cleanup SHOULD occur automatically after TTL expires, regardless of task status
|
||||
*
|
||||
* @param taskParams - The task creation parameters from the request (ttl, pollInterval)
|
||||
* @param requestId - The JSON-RPC request ID
|
||||
* @param request - The original request that triggered task creation
|
||||
* @param sessionId - Optional session ID for binding the task to a specific session
|
||||
* @returns The created task object
|
||||
* @returns The created {@linkcode Task} object
|
||||
*/
|
||||
createTask(taskParams: CreateTaskOptions, requestId: RequestId, request: Request, sessionId?: string): Promise<Task>;
|
||||
|
||||
|
|
@ -186,7 +186,7 @@ export interface TaskStore {
|
|||
*
|
||||
* @param taskId - The task identifier
|
||||
* @param sessionId - Optional session ID for binding the query to a specific session
|
||||
* @returns The task object, or null if it does not exist
|
||||
* @returns The {@linkcode Task} object, or `null` if it does not exist
|
||||
*/
|
||||
getTask(taskId: string, sessionId?: string): Promise<Task | null>;
|
||||
|
||||
|
|
@ -194,7 +194,7 @@ export interface TaskStore {
|
|||
* Stores the result of a task and sets its final status.
|
||||
*
|
||||
* @param taskId - The task identifier
|
||||
* @param status - The final status: 'completed' for success, 'failed' for errors
|
||||
* @param status - The final status: `'completed'` for success, `'failed'` for errors
|
||||
* @param result - The result to store
|
||||
* @param sessionId - Optional session ID for binding the operation to a specific session
|
||||
*/
|
||||
|
|
@ -210,7 +210,7 @@ export interface TaskStore {
|
|||
getTaskResult(taskId: string, sessionId?: string): Promise<Result>;
|
||||
|
||||
/**
|
||||
* Updates a task's status (e.g., to 'cancelled', 'failed', 'completed').
|
||||
* Updates a task's status (e.g., to `'cancelled'`, `'failed'`, `'completed'`).
|
||||
*
|
||||
* @param taskId - The task identifier
|
||||
* @param status - The new status
|
||||
|
|
@ -234,7 +234,7 @@ export interface TaskStore {
|
|||
* Terminal states are those where the task has finished and will not change.
|
||||
*
|
||||
* @param status - The task status to check
|
||||
* @returns True if the status is terminal (completed, failed, or cancelled)
|
||||
* @returns `true` if the status is terminal (`completed`, `failed`, or `cancelled`)
|
||||
* @experimental
|
||||
*/
|
||||
export function isTerminal(status: Task['status']): boolean {
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
/**
|
||||
* In-memory implementations of TaskStore and TaskMessageQueue.
|
||||
* In-memory implementations of {@linkcode TaskStore} and {@linkcode TaskMessageQueue}.
|
||||
* @experimental
|
||||
*/
|
||||
|
||||
|
|
@ -16,7 +16,7 @@ interface StoredTask {
|
|||
}
|
||||
|
||||
/**
|
||||
* In-memory TaskStore implementation for development and testing.
|
||||
* In-memory {@linkcode TaskStore} implementation for development and testing.
|
||||
* For production, use a database or distributed cache.
|
||||
* @experimental
|
||||
*/
|
||||
|
|
@ -233,7 +233,7 @@ export class InMemoryTaskStore implements TaskStore {
|
|||
}
|
||||
|
||||
/**
|
||||
* In-memory TaskMessageQueue implementation for development and testing.
|
||||
* In-memory {@linkcode TaskMessageQueue} implementation for development and testing.
|
||||
* For production, use Redis or another distributed queue.
|
||||
* @experimental
|
||||
*/
|
||||
|
|
@ -286,7 +286,7 @@ export class InMemoryTaskMessageQueue implements TaskMessageQueue {
|
|||
* Removes and returns the first message from the queue for a specific task.
|
||||
* @param taskId The task identifier
|
||||
* @param sessionId Optional session ID for binding the query to a specific session
|
||||
* @returns The first message, or undefined if the queue is empty
|
||||
* @returns The first message, or `undefined` if the queue is empty
|
||||
*/
|
||||
async dequeue(taskId: string, sessionId?: string): Promise<QueuedMessage | undefined> {
|
||||
const queue = this.getQueue(taskId, sessionId);
|
||||
|
|
|
|||
|
|
@ -23,11 +23,11 @@ export * from './validation/cfWorkerProvider.js';
|
|||
* This module provides configurable JSON Schema validation for the MCP SDK.
|
||||
* Choose a validator based on your runtime environment:
|
||||
*
|
||||
* - AjvJsonSchemaValidator: Best for Node.js (default, fastest)
|
||||
* - {@linkcode AjvJsonSchemaValidator}: Best for Node.js (default, fastest)
|
||||
* Import from: @modelcontextprotocol/sdk/validation/ajv
|
||||
* Requires peer dependencies: ajv, ajv-formats
|
||||
*
|
||||
* - CfWorkerJsonSchemaValidator: Best for edge runtimes
|
||||
* - {@linkcode CfWorkerJsonSchemaValidator}: Best for edge runtimes
|
||||
* Import from: @modelcontextprotocol/sdk/validation/cfworker
|
||||
* Requires peer dependency: @cfworker/json-schema
|
||||
*
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import * as z from 'zod/v4';
|
||||
|
||||
/**
|
||||
* Reusable URL validation that disallows javascript: scheme
|
||||
* Reusable URL validation that disallows `javascript:` scheme
|
||||
*/
|
||||
export const SafeUrlSchema = z
|
||||
.url()
|
||||
|
|
@ -149,7 +149,7 @@ export const OAuthErrorResponseSchema = z.object({
|
|||
});
|
||||
|
||||
/**
|
||||
* Optional version of SafeUrlSchema that allows empty string for backward compatibility on tos_uri and logo_uri
|
||||
* Optional version of {@linkcode SafeUrlSchema} that allows empty string for backward compatibility on `tos_uri` and `logo_uri`
|
||||
*/
|
||||
// eslint-disable-next-line unicorn/no-useless-undefined
|
||||
export const OptionalSafeUrlSchema = SafeUrlSchema.optional().or(z.literal('').transform(() => undefined));
|
||||
|
|
|
|||
|
|
@ -1,13 +1,13 @@
|
|||
import type { BaseMetadata } from '../types/types.js';
|
||||
|
||||
/**
|
||||
* Utilities for working with BaseMetadata objects.
|
||||
* Utilities for working with {@linkcode BaseMetadata} objects.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Gets the display name for an object with BaseMetadata.
|
||||
* For tools, the precedence is: title → annotations.title → name
|
||||
* For other objects: title → name
|
||||
* Gets the display name for an object with {@linkcode BaseMetadata}.
|
||||
* For tools, the precedence is: `title` → {@linkcode index.ToolAnnotations | annotations}.`title` → `name`
|
||||
* For other objects: `title` → `name`
|
||||
* This implements the spec requirement: "if no title is provided, name should be used for display purposes"
|
||||
*/
|
||||
export function getDisplayName(metadata: BaseMetadata | (BaseMetadata & { annotations?: { title?: string } })): string {
|
||||
|
|
|
|||
|
|
@ -73,9 +73,9 @@ export type ProgressCallback = (progress: Progress) => void;
|
|||
export type ProtocolOptions = {
|
||||
/**
|
||||
* Protocol versions supported. First version is preferred (sent by client,
|
||||
* used as fallback by server). Passed to transport during connect().
|
||||
* used as fallback by server). Passed to transport during {@linkcode Protocol.connect | connect()}.
|
||||
*
|
||||
* @default SUPPORTED_PROTOCOL_VERSIONS
|
||||
* @default {@linkcode SUPPORTED_PROTOCOL_VERSIONS}
|
||||
*/
|
||||
supportedProtocolVersions?: string[];
|
||||
|
||||
|
|
@ -84,14 +84,14 @@ export type ProtocolOptions = {
|
|||
*
|
||||
* Note that this DOES NOT affect checking of _local_ side capabilities, as it is considered a logic error to mis-specify those.
|
||||
*
|
||||
* Currently this defaults to false, for backwards compatibility with SDK versions that did not advertise capabilities correctly. In future, this will default to true.
|
||||
* Currently this defaults to `false`, for backwards compatibility with SDK versions that did not advertise capabilities correctly. In future, this will default to `true`.
|
||||
*/
|
||||
enforceStrictCapabilities?: boolean;
|
||||
/**
|
||||
* An array of notification method names that should be automatically debounced.
|
||||
* Any notifications with a method in this list will be coalesced if they
|
||||
* occur in the same tick of the event loop.
|
||||
* e.g., ['notifications/tools/list_changed']
|
||||
* e.g., `['notifications/tools/list_changed']`
|
||||
*/
|
||||
debouncedNotificationMethods?: string[];
|
||||
/**
|
||||
|
|
@ -105,14 +105,14 @@ export type ProtocolOptions = {
|
|||
*/
|
||||
taskMessageQueue?: TaskMessageQueue;
|
||||
/**
|
||||
* Default polling interval (in milliseconds) for task status checks when no pollInterval
|
||||
* Default polling interval (in milliseconds) for task status checks when no `pollInterval`
|
||||
* is provided by the server. Defaults to 5000ms if not specified.
|
||||
*/
|
||||
defaultTaskPollInterval?: number;
|
||||
/**
|
||||
* Maximum number of messages that can be queued per task for side-channel delivery.
|
||||
* If undefined, the queue size is unbounded.
|
||||
* When the limit is exceeded, the TaskMessageQueue implementation's enqueue() method
|
||||
* When the limit is exceeded, the {@linkcode TaskMessageQueue} implementation's {@linkcode TaskMessageQueue.enqueue | enqueue()} method
|
||||
* will throw an error. It's the implementation's responsibility to handle overflow
|
||||
* appropriately (e.g., by failing the task, dropping messages, etc.).
|
||||
*/
|
||||
|
|
@ -131,32 +131,32 @@ export type RequestOptions = {
|
|||
/**
|
||||
* If set, requests progress notifications from the remote end (if supported). When progress notifications are received, this callback will be invoked.
|
||||
*
|
||||
* For task-augmented requests: progress notifications continue after CreateTaskResult is returned and stop automatically when the task reaches a terminal status.
|
||||
* For task-augmented requests: progress notifications continue after {@linkcode CreateTaskResult} is returned and stop automatically when the task reaches a terminal status.
|
||||
*/
|
||||
onprogress?: ProgressCallback;
|
||||
|
||||
/**
|
||||
* Can be used to cancel an in-flight request. This will cause an AbortError to be raised from request().
|
||||
* Can be used to cancel an in-flight request. This will cause an `AbortError` to be raised from {@linkcode Protocol.request | request()}.
|
||||
*/
|
||||
signal?: AbortSignal;
|
||||
|
||||
/**
|
||||
* A timeout (in milliseconds) for this request. If exceeded, an SdkError with code `SdkErrorCode.RequestTimeout` will be raised from request().
|
||||
* A timeout (in milliseconds) for this request. If exceeded, an {@linkcode SdkError} with code {@linkcode SdkErrorCode.RequestTimeout} will be raised from {@linkcode Protocol.request | request()}.
|
||||
*
|
||||
* If not specified, `DEFAULT_REQUEST_TIMEOUT_MSEC` will be used as the timeout.
|
||||
* If not specified, {@linkcode DEFAULT_REQUEST_TIMEOUT_MSEC} will be used as the timeout.
|
||||
*/
|
||||
timeout?: number;
|
||||
|
||||
/**
|
||||
* If true, receiving a progress notification will reset the request timeout.
|
||||
* If `true`, receiving a progress notification will reset the request timeout.
|
||||
* This is useful for long-running operations that send periodic progress updates.
|
||||
* Default: false
|
||||
* Default: `false`
|
||||
*/
|
||||
resetTimeoutOnProgress?: boolean;
|
||||
|
||||
/**
|
||||
* Maximum total time (in milliseconds) to wait for a response.
|
||||
* If exceeded, an SdkError with code `SdkErrorCode.RequestTimeout` will be raised, regardless of progress notifications.
|
||||
* If exceeded, an {@linkcode SdkError} with code {@linkcode SdkErrorCode.RequestTimeout} will be raised, regardless of progress notifications.
|
||||
* If not specified, there is no maximum total timeout.
|
||||
*/
|
||||
maxTotalTimeout?: number;
|
||||
|
|
@ -194,15 +194,15 @@ export type NotificationOptions = {
|
|||
export type TaskRequestOptions = Omit<RequestOptions, 'relatedTask'>;
|
||||
|
||||
/**
|
||||
* Request-scoped TaskStore interface.
|
||||
* Request-scoped {@linkcode TaskStore} interface.
|
||||
*/
|
||||
export interface RequestTaskStore {
|
||||
/**
|
||||
* Creates a new task with the given creation parameters.
|
||||
* The implementation generates a unique taskId and createdAt timestamp.
|
||||
* The implementation generates a unique `taskId` and `createdAt` timestamp.
|
||||
*
|
||||
* @param taskParams - The task creation parameters from the request
|
||||
* @returns The created task object
|
||||
* @returns The created {@linkcode Task} object
|
||||
*/
|
||||
createTask(taskParams: CreateTaskOptions): Promise<Task>;
|
||||
|
||||
|
|
@ -210,7 +210,7 @@ export interface RequestTaskStore {
|
|||
* Gets the current status of a task.
|
||||
*
|
||||
* @param taskId - The task identifier
|
||||
* @returns The task object
|
||||
* @returns The {@linkcode Task} object
|
||||
* @throws If the task does not exist
|
||||
*/
|
||||
getTask(taskId: string): Promise<Task>;
|
||||
|
|
@ -219,7 +219,7 @@ export interface RequestTaskStore {
|
|||
* Stores the result of a task and sets its final status.
|
||||
*
|
||||
* @param taskId - The task identifier
|
||||
* @param status - The final status: 'completed' for success, 'failed' for errors
|
||||
* @param status - The final status: `'completed'` for success, `'failed'` for errors
|
||||
* @param result - The result to store
|
||||
*/
|
||||
storeTaskResult(taskId: string, status: 'completed' | 'failed', result: Result): Promise<void>;
|
||||
|
|
@ -233,7 +233,7 @@ export interface RequestTaskStore {
|
|||
getTaskResult(taskId: string): Promise<Result>;
|
||||
|
||||
/**
|
||||
* Updates a task's status (e.g., to 'cancelled', 'failed', 'completed').
|
||||
* Updates a task's status (e.g., to `'cancelled'`, `'failed'`, `'completed'`).
|
||||
*
|
||||
* @param taskId - The task identifier
|
||||
* @param status - The new status
|
||||
|
|
@ -245,7 +245,7 @@ export interface RequestTaskStore {
|
|||
* Lists tasks, optionally starting from a pagination cursor.
|
||||
*
|
||||
* @param cursor - Optional cursor for pagination
|
||||
* @returns An object containing the tasks array and an optional nextCursor
|
||||
* @returns An object containing the `tasks` array and an optional `nextCursor`
|
||||
*/
|
||||
listTasks(cursor?: string): Promise<{ tasks: Task[]; nextCursor?: string }>;
|
||||
}
|
||||
|
|
@ -324,7 +324,7 @@ export type BaseContext = {
|
|||
};
|
||||
|
||||
/**
|
||||
* Context provided to server-side request handlers, extending BaseContext with server-specific fields.
|
||||
* Context provided to server-side request handlers, extending {@linkcode BaseContext} with server-specific fields.
|
||||
*/
|
||||
export type ServerContext = BaseContext & {
|
||||
mcpReq: {
|
||||
|
|
@ -413,7 +413,7 @@ export abstract class Protocol<ContextT extends BaseContext> {
|
|||
/**
|
||||
* Callback for when the connection is closed for any reason.
|
||||
*
|
||||
* This is invoked when close() is called as well.
|
||||
* This is invoked when {@linkcode Protocol.close | close()} is called as well.
|
||||
*/
|
||||
onclose?: () => void;
|
||||
|
||||
|
|
@ -682,7 +682,7 @@ export abstract class Protocol<ContextT extends BaseContext> {
|
|||
/**
|
||||
* 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.
|
||||
* The {@linkcode Protocol} object assumes ownership of the {@linkcode Transport}, replacing any callbacks that have already been set, and expects that it is the only user of the {@linkcode Transport} instance going forward.
|
||||
*/
|
||||
async connect(transport: Transport): Promise<void> {
|
||||
this._transport = transport;
|
||||
|
|
@ -1031,7 +1031,7 @@ export abstract class Protocol<ContextT extends BaseContext> {
|
|||
|
||||
/**
|
||||
* Sends a request and returns an AsyncGenerator that yields response messages.
|
||||
* The generator is guaranteed to end with either a 'result' or 'error' message.
|
||||
* The generator is guaranteed to end with either a `'result'` or `'error'` message.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
|
|
@ -1155,7 +1155,7 @@ export abstract class Protocol<ContextT extends BaseContext> {
|
|||
/**
|
||||
* Sends a request and waits for a response.
|
||||
*
|
||||
* Do not use this method to emit notifications! Use notification() instead.
|
||||
* Do not use this method to emit notifications! Use {@linkcode Protocol.notification | notification()} instead.
|
||||
*/
|
||||
request<T extends AnySchema>(request: Request, resultSchema: T, options?: RequestOptions): Promise<SchemaOutput<T>> {
|
||||
const { relatedRequestId, resumptionToken, onresumptiontoken, task, relatedTask } = options ?? {};
|
||||
|
|
@ -1538,13 +1538,13 @@ export abstract class Protocol<ContextT extends BaseContext> {
|
|||
}
|
||||
|
||||
/**
|
||||
* Enqueues a task-related message for side-channel delivery via tasks/result.
|
||||
* Enqueues a task-related message for side-channel delivery via `tasks/result`.
|
||||
* @param taskId The task ID to associate the message with
|
||||
* @param message The message to enqueue
|
||||
* @param sessionId Optional session ID for binding the operation to a specific session
|
||||
* @throws Error if taskStore is not configured or if enqueue fails (e.g., queue overflow)
|
||||
* @throws Error if `taskStore` is not configured or if enqueue fails (e.g., queue overflow)
|
||||
*
|
||||
* Note: If enqueue fails, it's the TaskMessageQueue implementation's responsibility to handle
|
||||
* Note: If enqueue fails, it's the {@linkcode TaskMessageQueue} implementation's responsibility to handle
|
||||
* the error appropriately (e.g., by failing the task, logging, etc.). The Protocol layer
|
||||
* simply propagates the error.
|
||||
*/
|
||||
|
|
|
|||
|
|
@ -41,7 +41,7 @@ export interface ErrorMessage extends BaseResponseMessage {
|
|||
|
||||
/**
|
||||
* Union type representing all possible messages that can be yielded during request processing.
|
||||
* Note: Progress notifications are handled through the existing onprogress callback mechanism.
|
||||
* Note: Progress notifications are handled through the existing {@linkcode index.RequestOptions | onprogress} callback mechanism.
|
||||
* Side-channeled messages (server requests/notifications) are handled through registered handlers.
|
||||
*/
|
||||
export type ResponseMessage<T extends Result> = TaskStatusMessage | TaskCreatedMessage | ResultMessage<T> | ErrorMessage;
|
||||
|
|
|
|||
|
|
@ -3,8 +3,8 @@
|
|||
*
|
||||
* Tool names SHOULD be between 1 and 128 characters in length (inclusive).
|
||||
* Tool names are case-sensitive.
|
||||
* Allowed characters: uppercase and lowercase ASCII letters (A-Z, a-z), digits
|
||||
* (0-9), underscore (_), dash (-), and dot (.).
|
||||
* Allowed characters: uppercase and lowercase ASCII letters (`A-Z`, `a-z`), digits
|
||||
* (`0-9`), underscore (`_`), dash (`-`), and dot (`.`).
|
||||
* Tool names SHOULD NOT contain spaces, commas, or other special characters.
|
||||
*
|
||||
* @see {@link https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986 | SEP-986: Specify Format for Tool Names}
|
||||
|
|
@ -104,7 +104,7 @@ export function issueToolNameWarning(name: string, warnings: string[]): void {
|
|||
/**
|
||||
* Validates a tool name and issues warnings for non-conforming names
|
||||
* @param name - The tool name to validate
|
||||
* @returns true if the name is valid, false otherwise
|
||||
* @returns `true` if the name is valid, `false` otherwise
|
||||
*/
|
||||
export function validateAndWarnToolName(name: string): boolean {
|
||||
const result = validateToolName(name);
|
||||
|
|
|
|||
|
|
@ -3,8 +3,8 @@ import type { JSONRPCMessage, MessageExtraInfo, RequestId } from '../types/types
|
|||
export type FetchLike = (url: string | URL, init?: RequestInit) => Promise<Response>;
|
||||
|
||||
/**
|
||||
* Normalizes HeadersInit to a plain Record<string, string> for manipulation.
|
||||
* Handles Headers objects, arrays of tuples, and plain objects.
|
||||
* Normalizes `HeadersInit` to a plain `Record<string, string>` for manipulation.
|
||||
* Handles `Headers` objects, arrays of tuples, and plain objects.
|
||||
*/
|
||||
export function normalizeHeaders(headers: RequestInit['headers'] | undefined): Record<string, string> {
|
||||
if (!headers) return {};
|
||||
|
|
@ -21,11 +21,11 @@ export function normalizeHeaders(headers: RequestInit['headers'] | undefined): R
|
|||
}
|
||||
|
||||
/**
|
||||
* Creates a fetch function that includes base RequestInit options.
|
||||
* Creates a fetch function that includes base `RequestInit` options.
|
||||
* This ensures requests inherit settings like credentials, mode, headers, etc. from the base init.
|
||||
*
|
||||
* @param baseFetch - The base fetch function to wrap (defaults to global fetch)
|
||||
* @param baseInit - The base RequestInit to merge with each request
|
||||
* @param baseFetch - The base fetch function to wrap (defaults to global `fetch`)
|
||||
* @param baseInit - The base `RequestInit` to merge with each request
|
||||
* @returns A wrapped fetch function that merges base options with call-specific options
|
||||
*/
|
||||
export function createFetchWithInit(baseFetch: FetchLike = fetch, baseInit?: RequestInit): FetchLike {
|
||||
|
|
@ -77,7 +77,7 @@ export interface Transport {
|
|||
*
|
||||
* This method should only be called after callbacks are installed, or else messages may be lost.
|
||||
*
|
||||
* NOTE: This method should not be called explicitly when using Client, Server, or Protocol classes, as they will implicitly call start().
|
||||
* NOTE: This method should not be called explicitly when using {@linkcode @modelcontextprotocol/client!client/client.Client | Client}, {@linkcode @modelcontextprotocol/server!server/server.Server | Server}, or {@linkcode @modelcontextprotocol/server!index.Protocol | Protocol} classes, as they will implicitly call {@linkcode Transport.start | start()}.
|
||||
*/
|
||||
start(): Promise<void>;
|
||||
|
||||
|
|
@ -96,7 +96,7 @@ export interface Transport {
|
|||
/**
|
||||
* Callback for when the connection is closed for any reason.
|
||||
*
|
||||
* This should be invoked when close() is called as well.
|
||||
* This should be invoked when {@linkcode Transport.close | close()} is called as well.
|
||||
*/
|
||||
onclose?: () => void;
|
||||
|
||||
|
|
@ -110,9 +110,9 @@ export interface Transport {
|
|||
/**
|
||||
* Callback for when a message (request or response) is received over the connection.
|
||||
*
|
||||
* Includes the requestInfo and authInfo if the transport is authenticated.
|
||||
* Includes the {@linkcode MessageExtraInfo.requestInfo | requestInfo} and {@linkcode MessageExtraInfo.authInfo | authInfo} if the transport is authenticated.
|
||||
*
|
||||
* The requestInfo can be used to get the original request information (headers, etc.)
|
||||
* The {@linkcode MessageExtraInfo.requestInfo | requestInfo} can be used to get the original request information (headers, etc.)
|
||||
*/
|
||||
onmessage?: <T extends JSONRPCMessage>(message: T, extra?: MessageExtraInfo) => void;
|
||||
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue