mcp-use
Version:
Opinionated MCP Framework for TypeScript (@modelcontextprotocol/sdk compatible) - Build MCP Agents, Clients and Servers with support for ChatGPT Apps, Code Mode, OAuth, Notifications, Sampling, Observability and more.
448 lines • 17.3 kB
TypeScript
import type { Client, ClientOptions } from "@modelcontextprotocol/sdk/client/index.js";
import type { RequestOptions } from "@modelcontextprotocol/sdk/shared/protocol.js";
import type { CallToolResult, CreateMessageRequest, CreateMessageResult, ElicitRequestFormParams, ElicitRequestURLParams, ElicitResult, Notification, Root, Tool } from "@modelcontextprotocol/sdk/types.js";
import type { ConnectionManager } from "../task_managers/base.js";
import type { ConnectorInitEventData } from "../telemetry/events.js";
/**
* Handler function for server notifications
*/
export type NotificationHandler = (notification: Notification) => void | Promise<void>;
export interface ConnectorInitOptions {
/**
* Options forwarded to the underlying MCP `Client` instance.
*/
clientOptions?: ClientOptions;
/**
* Arbitrary request options (timeouts, cancellation, etc.) used by helper
* methods when they issue SDK requests. Can be overridden per‑call.
*/
defaultRequestOptions?: RequestOptions;
/**
* OAuth client provider for automatic authentication
*/
authProvider?: any;
/**
* Optional callback to wrap the transport before passing it to the Client.
* Useful for logging, monitoring, or other transport-level interceptors.
*/
wrapTransport?: (transport: any, serverId: string) => any;
/**
* Initial roots to provide to the server.
* Roots allow the server to know which directories/files the client has access to.
*/
roots?: Root[];
/**
* Optional callback function to handle sampling requests from servers.
* When provided, the client will declare sampling capability and handle
* `sampling/createMessage` requests by calling this callback.
*/
onSampling?: (params: CreateMessageRequest["params"]) => Promise<CreateMessageResult>;
/**
* @deprecated Use `onSampling` instead. This option will be removed in a future version.
* Optional callback function to handle sampling requests from servers.
* When provided, the client will declare sampling capability and handle
* `sampling/createMessage` requests by calling this callback.
*/
samplingCallback?: (params: CreateMessageRequest["params"]) => Promise<CreateMessageResult>;
/**
* Optional callback function to handle elicitation requests from servers.
* When provided, the client will declare elicitation capability and handle
* `elicitation/create` requests by calling this callback.
*
* Elicitation allows servers to request additional information from users:
* - Form mode: Collect structured data with JSON schema validation
* - URL mode: Direct users to external URLs for sensitive interactions
*/
elicitationCallback?: (params: ElicitRequestFormParams | ElicitRequestURLParams) => Promise<ElicitResult>;
}
/**
* Base class for MCP connectors.
*/
export declare abstract class BaseConnector {
protected client: Client | null;
protected connectionManager: ConnectionManager<any> | null;
protected toolsCache: Tool[] | null;
protected capabilitiesCache: Record<string, unknown> | null;
protected serverInfoCache: {
name: string;
version?: string;
} | null;
protected connected: boolean;
protected readonly opts: ConnectorInitOptions;
protected notificationHandlers: NotificationHandler[];
protected rootsCache: Root[];
constructor(opts?: ConnectorInitOptions);
/**
* Track connector initialization event
* Should be called by subclasses after successful connection
*/
protected trackConnectorInit(data: Omit<ConnectorInitEventData, "connectorType">): void;
/**
* Register a handler for server notifications
*
* @param handler - Function to call when a notification is received
*
* @example
* ```typescript
* connector.onNotification((notification) => {
* console.log(`Received: ${notification.method}`, notification.params);
* });
* ```
*/
onNotification(handler: NotificationHandler): void;
/**
* Internal: wire notification handlers to the SDK client
* Includes automatic handling for list_changed notifications per MCP spec
*/
protected setupNotificationHandler(): void;
/**
* Auto-refresh tools cache when server sends tools/list_changed notification
*/
protected refreshToolsCache(): Promise<void>;
/**
* Called when server sends resources/list_changed notification
* Resources aren't cached by default, but we log for user awareness
*/
protected onResourcesListChanged(): Promise<void>;
/**
* Called when server sends prompts/list_changed notification
* Prompts aren't cached by default, but we log for user awareness
*/
protected onPromptsListChanged(): Promise<void>;
/**
* Set roots and notify the server.
* Roots represent directories or files that the client has access to.
*
* @param roots - Array of Root objects with `uri` (must start with "file://") and optional `name`
*
* @example
* ```typescript
* await connector.setRoots([
* { uri: "file:///home/user/project", name: "My Project" },
* { uri: "file:///home/user/data" }
* ]);
* ```
*/
setRoots(roots: Root[]): Promise<void>;
/**
* Get the current roots.
*/
getRoots(): Root[];
/**
* Internal: set up roots/list request handler.
* This is called after the client connects to register the handler for server requests.
*/
protected setupRootsHandler(): void;
/**
* Internal: set up sampling/createMessage request handler.
* This is called after the client connects to register the handler for sampling requests.
*/
protected setupSamplingHandler(): void;
/**
* Internal: set up elicitation/create request handler.
* This is called after the client connects to register the handler for elicitation requests.
*/
protected setupElicitationHandler(): void;
/** Establish the connection and create the SDK client. */
abstract connect(): Promise<void>;
/** Get the identifier for the connector. */
abstract get publicIdentifier(): Record<string, string>;
/** Disconnect and release resources. */
disconnect(): Promise<void>;
/** Check if the client is connected */
get isClientConnected(): boolean;
/**
* Initialise the MCP session **after** `connect()` has succeeded.
*
* In the SDK, `Client.connect(transport)` automatically performs the
* protocol‑level `initialize` handshake, so we only need to cache the list of
* tools and expose some server info.
*/
initialize(defaultRequestOptions?: RequestOptions): Promise<ReturnType<Client["getServerCapabilities"]>>;
/** Lazily expose the cached tools list. */
get tools(): Tool[];
/** Expose cached server capabilities. */
get serverCapabilities(): Record<string, unknown>;
/** Expose cached server info. */
get serverInfo(): {
name: string;
version?: string;
} | null;
/** Call a tool on the server. */
callTool(name: string, args: Record<string, any>, options?: RequestOptions): Promise<CallToolResult>;
/**
* List all available tools from the MCP server.
* This method fetches fresh tools from the server, unlike the `tools` getter which returns cached tools.
*
* @param options - Optional request options
* @returns Array of available tools
*/
listTools(options?: RequestOptions): Promise<Tool[]>;
/**
* List resources from the server with optional pagination
*
* @param cursor - Optional cursor for pagination
* @param options - Request options
* @returns Resource list with optional nextCursor for pagination
*/
listResources(cursor?: string, options?: RequestOptions): Promise<{
[]: unknown;
resources: {
uri: string;
name: string;
description?: string | undefined;
mimeType?: string | undefined;
annotations?: {
audience?: ("user" | "assistant")[] | undefined;
priority?: number | undefined;
lastModified?: string | undefined;
} | undefined;
_meta?: {
[]: unknown;
} | undefined;
icons?: {
src: string;
mimeType?: string | undefined;
sizes?: string[] | undefined;
theme?: "light" | "dark" | undefined;
}[] | undefined;
title?: string | undefined;
}[];
_meta?: {
[]: unknown;
progressToken?: string | number | undefined;
"io.modelcontextprotocol/related-task"?: {
taskId: string;
} | undefined;
} | undefined;
nextCursor?: string | undefined;
}>;
/**
* List all resources from the server, automatically handling pagination
*
* @param options - Request options
* @returns Complete list of all resources
*/
listAllResources(options?: RequestOptions): Promise<{
resources: any[];
}>;
/**
* List resource templates from the server
*
* @param options - Request options
* @returns List of available resource templates
*/
listResourceTemplates(options?: RequestOptions): Promise<{
[]: unknown;
resourceTemplates: {
uriTemplate: string;
name: string;
description?: string | undefined;
mimeType?: string | undefined;
annotations?: {
audience?: ("user" | "assistant")[] | undefined;
priority?: number | undefined;
lastModified?: string | undefined;
} | undefined;
_meta?: {
[]: unknown;
} | undefined;
icons?: {
src: string;
mimeType?: string | undefined;
sizes?: string[] | undefined;
theme?: "light" | "dark" | undefined;
}[] | undefined;
title?: string | undefined;
}[];
_meta?: {
[]: unknown;
progressToken?: string | number | undefined;
"io.modelcontextprotocol/related-task"?: {
taskId: string;
} | undefined;
} | undefined;
nextCursor?: string | undefined;
}>;
/** Read a resource by URI. */
readResource(uri: string, options?: RequestOptions): Promise<{
[]: unknown;
contents: ({
uri: string;
text: string;
mimeType
/**
* List resources from the server with optional pagination
*
* @param cursor - Optional cursor for pagination
* @param options - Request options
* @returns Resource list with optional nextCursor for pagination
*/
?: string | undefined;
_meta?: Record<string, unknown> | undefined;
} | {
uri: string;
blob: string;
mimeType?: string | undefined;
_meta?: Record<string, unknown> | undefined;
})[];
_meta?: {
[]: unknown;
progressToken?: string | number | undefined;
"io.modelcontextprotocol/related-task"?: {
taskId: string;
} | undefined;
} | undefined;
}>;
/**
* Subscribe to resource updates
*
* @param uri - URI of the resource to subscribe to
* @param options - Request options
*/
subscribeToResource(uri: string, options?: RequestOptions): Promise<{
_meta?: {
[]: unknown;
progressToken?: string | number | undefined;
"io.modelcontextprotocol/related-task"?: {
taskId: string;
} | undefined;
} | undefined;
}>;
/**
* Unsubscribe from resource updates
*
* @param uri - URI of the resource to unsubscribe from
* @param options - Request options
*/
unsubscribeFromResource(uri: string, options?: RequestOptions): Promise<{
_meta?: {
[]: unknown;
progressToken?: string | number | undefined;
"io.modelcontextprotocol/related-task"?: {
taskId: string;
} | undefined;
} | undefined;
}>;
listPrompts(): Promise<{
[]: unknown;
prompts: {
name: string;
description?: string | undefined;
arguments?: {
name: string;
description?: string | undefined;
required?: boolean | undefined;
}[] | undefined;
_meta?: {
[]: unknown;
} | undefined;
icons?: {
src: string;
mimeType?: string | undefined;
sizes?: string[] | undefined;
theme?: "light" | "dark" | undefined;
}[] | undefined;
title?: string | undefined;
}[];
_meta?: {
[]: unknown;
progressToken?: string | number | undefined;
"io.modelcontextprotocol/related-task"?: {
taskId: string;
} | undefined;
} | undefined;
nextCursor?: string | undefined;
}>;
getPrompt(name: string, args: Record<string, any>): Promise<{
[]: unknown;
messages: {
role: "user" | "assistant";
content: {
type: "text";
text: string;
annotations?: {
audience?: ("user" | "assistant")[] | undefined;
priority?: number | undefined;
lastModified?: string | undefined;
} | undefined;
_meta?: Record<string, unknown> | undefined;
} | {
type: "image";
data: string;
mimeType: string;
annotations?: {
audience?: ("user" | "assistant")[] | undefined;
priority?: number | undefined;
lastModified?: string | undefined;
} | undefined;
_meta?: Record<string, unknown> | undefined;
} | {
type: "audio";
data: string;
mimeType: string;
annotations?: {
audience?: ("user" | "assistant")[] | undefined;
priority?: number | undefined;
lastModified?: string | undefined;
} | undefined;
_meta?: Record<string, unknown> | undefined;
} | {
type: "resource";
resource: {
uri: string;
text: string;
mimeType?: string | undefined;
_meta?: Record<string, unknown> | undefined;
} | {
uri: string;
blob: string;
mimeType?: string | undefined;
_meta?: Record<string, unknown> | undefined;
};
annotations?: {
audience?: ("user" | "assistant")[] | undefined;
priority?: number | undefined;
lastModified?: string | undefined;
} | undefined;
_meta?: Record<string, unknown> | undefined;
} | {
uri: string;
name: string;
type: "resource_link";
description?: string | undefined;
mimeType?: string | undefined;
annotations?: {
audience?: ("user" | "assistant")[] | undefined;
priority?: number | undefined;
lastModified?: string | undefined;
} | undefined;
_meta?: {
[]: unknown;
} | undefined;
icons?: {
src: string;
mimeType?: string | undefined;
sizes?: string[] | undefined;
theme?: "light" | "dark" | undefined;
}[] | undefined;
title?: string | undefined;
};
}[];
_meta?: {
[]: unknown;
progressToken?: string | number | undefined;
"io.modelcontextprotocol/related-task"?: {
taskId: string;
} | undefined;
} | undefined;
description?: string | undefined;
}>;
/** Send a raw request through the client. */
request(method: string, params?: Record<string, any> | null, options?: RequestOptions): Promise<any>;
/**
* Helper to tear down the client & connection manager safely.
*/
protected cleanupResources(): Promise<void>;
}
//# sourceMappingURL=base.d.ts.map