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.
343 lines • 15.3 kB
TypeScript
import { McpServer as OfficialMcpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import type { CreateMessageRequest, CreateMessageResult } from "@modelcontextprotocol/sdk/types.js";
import type { Hono as HonoType } from "hono";
import { convertZodSchemaToParams, createParamsSchema } from "./tools/index.js";
import { uiResourceRegistration } from "./widgets/index.js";
import type { ElicitFormParams, ElicitOptions, ElicitUrlParams, SampleOptions, ToolContext } from "./types/tool-context.js";
export type { ElicitFormParams, ElicitOptions, ElicitUrlParams, SampleOptions, ToolContext, };
import { getActiveSessions, sendNotification, sendNotificationToSession, sendPromptsListChanged, sendResourcesListChanged, sendToolsListChanged } from "./notifications/index.js";
import type { OAuthProvider } from "./oauth/providers/types.js";
import { listRoots, onRootsChanged } from "./roots/index.js";
import type { SessionData } from "./sessions/index.js";
import type { ServerConfig } from "./types/index.js";
import type { PromptCallback, PromptDefinition } from "./types/prompt.js";
import type { ReadResourceCallback, ReadResourceTemplateCallback, ResourceDefinition, ResourceTemplateDefinition } from "./types/resource.js";
import type { InferToolInput, InferToolOutput, ToolCallback, ToolDefinition } from "./types/tool.js";
import { parseTemplateUri as parseTemplateUriHelper } from "./utils/index.js";
declare class MCPServerClass<HasOAuth extends boolean = false> {
/**
* Get the mcp-use package version.
* Works in all environments (Node.js, browser, Cloudflare Workers, Deno, etc.)
*/
static getPackageVersion(): string;
/**
* Native MCP server instance from @modelcontextprotocol/sdk
* Exposed publicly for advanced use cases
*/
readonly nativeServer: OfficialMcpServer;
/** @deprecated Use nativeServer instead - kept for backward compatibility */
get server(): OfficialMcpServer;
config: ServerConfig;
app: HonoType;
private mcpMounted;
private inspectorMounted;
serverPort?: number;
serverHost: string;
serverBaseUrl?: string;
favicon?: string;
registeredTools: string[];
registeredPrompts: string[];
registeredResources: string[];
buildId?: string;
sessions: Map<string, SessionData>;
private idleCleanupInterval?;
private oauthSetupState;
oauthProvider?: OAuthProvider;
private oauthMiddleware?;
/**
* Storage for registrations that can be replayed on new server instances
* Following the official SDK pattern where each session gets its own server instance
* @internal Exposed for telemetry purposes
*/
registrations: {
tools: Map<string, {
config: ToolDefinition;
handler: ToolCallback;
}>;
prompts: Map<string, {
config: PromptDefinition;
handler: PromptCallback;
}>;
resources: Map<string, {
config: ResourceDefinition;
handler: ReadResourceCallback;
}>;
resourceTemplates: Map<string, {
config: ResourceTemplateDefinition;
handler: ReadResourceTemplateCallback;
}>;
};
/**
* Storage for widget definitions, used to inject metadata into tool responses
* when using the widget() helper with returnsWidget option
*/
widgetDefinitions: Map<string, Record<string, unknown>>;
/**
* Resource subscription manager for tracking and notifying resource updates
*/
private subscriptionManager;
/**
* Clean up resource subscriptions for a closed session
*
* This method is called automatically when a session is closed to remove
* all resource subscriptions associated with that session.
*
* @param sessionId - The session ID to clean up
* @internal
*/
cleanupSessionSubscriptions(sessionId: string): void;
/**
* Creates a new MCP server instance with Hono integration
*
* Initializes the server with the provided configuration, sets up CORS headers,
* configures widget serving routes, and creates a proxy that allows direct
* access to Hono methods while preserving MCP server functionality.
*
* @param config - Server configuration including name, version, and description
* @returns A proxied MCPServer instance that supports both MCP and Hono methods
*/
constructor(config: ServerConfig);
/**
* Wrap registration methods to capture registrations following official SDK pattern.
* Each session will get a fresh server instance with all registrations replayed.
*/
private wrapRegistrationMethods;
/**
* Create a new server instance for a session following official SDK pattern.
* This is called for each initialize request to create an isolated server.
*/
getServerForSession(): OfficialMcpServer;
/**
* Gets the server base URL with fallback to host:port if not configured
* @returns The complete base URL for the server
*/
private getServerBaseUrl;
tool: <T extends ToolDefinition<any, any, HasOAuth>>(toolDefinition: T, callback?: ToolCallback<InferToolInput<T>, InferToolOutput<T>, HasOAuth>) => this;
convertZodSchemaToParams: typeof convertZodSchemaToParams;
createParamsSchema: typeof createParamsSchema;
parseTemplateUri: typeof parseTemplateUriHelper;
resource: (resourceDefinition: ResourceDefinition<HasOAuth> | import("./types/index.js").ResourceDefinitionWithoutCallback, callback?: ReadResourceCallback<HasOAuth>) => this;
resourceTemplate: (templateDefinition: ResourceTemplateDefinition<HasOAuth> | import("./types/index.js").ResourceTemplateDefinitionWithoutCallback | import("./types/index.js").FlatResourceTemplateDefinition<HasOAuth> | import("./types/index.js").FlatResourceTemplateDefinitionWithoutCallback, callback?: ReadResourceTemplateCallback<HasOAuth>) => this;
prompt: (promptDefinition: PromptDefinition<any, HasOAuth> | import("./types/index.js").PromptDefinitionWithoutCallback, callback?: PromptCallback<any, HasOAuth>) => this;
getActiveSessions: typeof getActiveSessions;
sendNotification: typeof sendNotification;
sendNotificationToSession: typeof sendNotificationToSession;
sendToolsListChanged: typeof sendToolsListChanged;
sendResourcesListChanged: typeof sendResourcesListChanged;
sendPromptsListChanged: typeof sendPromptsListChanged;
/**
* Notify subscribed clients that a resource has been updated
*
* This method sends a `notifications/resources/updated` notification to all
* sessions that have subscribed to the specified resource URI.
*
* @param uri - The URI of the resource that changed
* @returns Promise that resolves when all notifications have been sent
*
* @example
* ```typescript
* // After updating a resource, notify subscribers
* await server.notifyResourceUpdated("file:///path/to/resource.txt");
* ```
*/
notifyResourceUpdated(uri: string): Promise<void>;
uiResource: (definition: Parameters<typeof uiResourceRegistration>[1]) => any;
/**
* Mount MCP server endpoints at /mcp and /sse
*
* Sets up the HTTP transport layer for the MCP server, creating endpoints for
* Server-Sent Events (SSE) streaming, POST message handling, and DELETE session cleanup.
* The transport manages multiple sessions through a single server instance.
*
* This method is called automatically when the server starts listening and ensures
* that MCP clients can communicate with the server over HTTP.
*
* @private
* @returns Promise that resolves when MCP endpoints are successfully mounted
*
* @example
* Endpoints created:
* - GET /mcp, GET /sse - SSE streaming endpoint for real-time communication
* - POST /mcp, POST /sse - Message handling endpoint for MCP protocol messages
* - DELETE /mcp, DELETE /sse - Session cleanup endpoint
*/
private mountMcp;
/**
* Start the Hono server with MCP endpoints
*
* Initiates the server startup process by mounting MCP endpoints, configuring
* the inspector UI (if available), and starting the server to listen
* for incoming connections. This is the main entry point for running the server.
*
* The server will be accessible at the specified port with MCP endpoints at /mcp and /sse
* and inspector UI at /inspector (if the inspector package is installed).
*
* @param port - Port number to listen on (defaults to 3000 if not specified)
* @returns Promise that resolves when the server is successfully listening
*
* @example
* ```typescript
* await server.listen(8080)
* // Server now running at http://localhost:8080 (or configured host)
* // MCP endpoints: http://localhost:8080/mcp and http://localhost:8080/sse
* // Inspector UI: http://localhost:8080/inspector
* ```
*/
/**
* Log registered tools, prompts, and resources to console
*/
private logRegisteredItems;
getBuildId(): string | undefined;
getServerPort(): number;
/**
* Create a message for sampling (calling the LLM)
* Delegates to the native SDK server
*/
createMessage(params: CreateMessageRequest["params"], options?: any): Promise<CreateMessageResult>;
listen(port?: number): Promise<void>;
private _trackServerRun;
/**
* Get the fetch handler for the server after mounting all endpoints
*
* This method prepares the server by mounting MCP endpoints, widgets, and inspector
* (if available), then returns the fetch handler. This is useful for integrating
* with external server frameworks like Supabase Edge Functions, Cloudflare Workers,
* or other platforms that handle the server lifecycle themselves.
*
* Unlike `listen()`, this method does not start a server - it only prepares the
* routes and returns the handler function that can be used with external servers.
*
* @param options - Optional configuration for the handler
* @param options.provider - Platform provider (e.g., 'supabase') to handle platform-specific path rewriting
* @returns Promise that resolves to the fetch handler function
*
* @example
* ```typescript
* // For Supabase Edge Functions (handles path rewriting automatically)
* const server = new MCPServer({ name: 'my-server', version: '1.0.0' });
* server.tool({ ... });
* const handler = await server.getHandler({ provider: 'supabase' });
* Deno.serve(handler);
* ```
*
* @example
* ```typescript
* // For Cloudflare Workers
* const server = new MCPServer({ name: 'my-server', version: '1.0.0' });
* server.tool({ ... });
* const handler = await server.getHandler();
* export default { fetch: handler };
* ```
*/
getHandler(options?: {
provider?: "supabase" | "cloudflare" | "deno-deploy";
}): Promise<(req: Request) => Promise<Response>>;
onRootsChanged: typeof onRootsChanged;
listRoots: typeof listRoots;
/**
* Mount MCP Inspector UI at /inspector
*
* Dynamically loads and mounts the MCP Inspector UI package if available, providing
* a web-based interface for testing and debugging MCP servers. The inspector
* automatically connects to the local MCP server endpoints.
*
* This method gracefully handles cases where the inspector package is not installed,
* allowing the server to function without the inspector in production environments.
*
* @private
* @returns void
*
* @example
* If @mcp-use/inspector is installed:
* - Inspector UI available at http://localhost:PORT/inspector
* - Automatically connects to http://localhost:PORT/mcp (or /sse)
*
* If not installed:
* - Server continues to function normally
* - No inspector UI available
*/
private mountInspector;
}
export type McpServerInstance<HasOAuth extends boolean = false> = MCPServerClass<HasOAuth> & HonoType;
export type MCPServer<HasOAuth extends boolean = false> = MCPServerClass<HasOAuth>;
export interface MCPServerConstructor {
new (config: ServerConfig & {
oauth: NonNullable<ServerConfig["oauth"]>;
}): McpServerInstance<true>;
new (config: ServerConfig): McpServerInstance<false>;
prototype: MCPServerClass<boolean>;
}
export declare const MCPServer: MCPServerConstructor;
/**
* Create a new MCP server instance
*
* @param name - Server name
* @param config - Optional server configuration
* @param config.version - Server version (defaults to '1.0.0')
* @param config.description - Server description
* @param config.host - Hostname for widget URLs and server endpoints (defaults to 'localhost')
* @param config.baseUrl - Full base URL (e.g., 'https://myserver.com') - overrides host:port for widget URLs
* @param config.allowedOrigins - Allowed origins for DNS rebinding protection
* - **Development mode** (NODE_ENV !== "production"): If not set, all origins are allowed
* - **Production mode** (NODE_ENV === "production"): Only uses explicitly configured origins
* - See {@link ServerConfig.allowedOrigins} for detailed documentation
* @param config.sessionIdleTimeoutMs - Idle timeout for sessions in milliseconds (default: 300000 = 5 minutes)
* @returns McpServerInstance with both MCP and Hono methods
*
* @example
* ```typescript
* // Recommended: Use class constructor (matches MCPClient/MCPAgent pattern)
* const server = new MCPServer({
* name: 'my-server',
* version: '1.0.0',
* description: 'My MCP server'
* })
*
* // Legacy: Factory function (still supported for backward compatibility)
* const server = createMCPServer('my-server', {
* version: '1.0.0',
* description: 'My MCP server'
* })
*
* // Production mode with explicit allowed origins
* const server = new MCPServer({
* name: 'my-server',
* version: '1.0.0',
* allowedOrigins: [
* 'https://myapp.com',
* 'https://app.myapp.com'
* ]
* })
*
* // With custom host (e.g., for Docker or remote access)
* const server = new MCPServer({
* name: 'my-server',
* version: '1.0.0',
* host: '0.0.0.0' // or 'myserver.com'
* })
*
* // With full base URL (e.g., behind a proxy or custom domain)
* const server = new MCPServer({
* name: 'my-server',
* version: '1.0.0',
* baseUrl: 'https://myserver.com' // or process.env.MCP_URL
* })
* ```
*/
/**
* @deprecated Use `new MCPServer({ name, ... })` instead. This factory function is maintained for backward compatibility.
*
* @example
* ```typescript
* // Old (deprecated)
* const server = createMCPServer('my-server', { version: '1.0.0' })
*
* // New (recommended)
* const server = new MCPServer({ name: 'my-server', version: '1.0.0' })
* ```
*/
export declare function createMCPServer(name: string, config: Partial<ServerConfig> & {
oauth: NonNullable<ServerConfig["oauth"]>;
}): McpServerInstance<true>;
export declare function createMCPServer(name: string, config?: Partial<ServerConfig>): McpServerInstance<false>;
//# sourceMappingURL=mcp-server.d.ts.map