MCP 服务器是 Model Context Protocol (MCP) 架构中的基础组件,为客户端提供工具、资源和功能。它实现了协议的服务器端,负责:
向客户端暴露可发现和执行的工具
使用基于 URI 的访问模式管理资源
提供提示模板并处理提示请求
支持与客户端的功能协商
实现服务器端协议操作
管理并发客户端连接
提供结构化日志和通知
服务器同时支持同步和异步 API,允许在不同应用场景中灵活集成。
// Create a server with custom configurationMcpSyncServer syncServer = McpServer.sync(transport) .serverInfo("my-server", "1.0.0") .capabilities(ServerCapabilities.builder() .resources(true) // Enable resource support .tools(true) // Enable tool support .prompts(true) // Enable prompt support .logging() // Enable logging support .build()) .build();// Initialize the serversyncServer.initialize();// Register tools, resources, and promptssyncServer.addTool(syncToolRegistration);syncServer.addResource(syncResourceRegistration);syncServer.addPrompt(syncPromptRegistration);// Send logging notificationssyncServer.loggingNotification(LoggingMessageNotification.builder() .level(LoggingLevel.INFO) .logger("custom-logger") .data("Server initialized") .build());// Close the server when donesyncServer.close();
// Create a server with custom configurationMcpSyncServer syncServer = McpServer.sync(transport) .serverInfo("my-server", "1.0.0") .capabilities(ServerCapabilities.builder() .resources(true) // Enable resource support .tools(true) // Enable tool support .prompts(true) // Enable prompt support .logging() // Enable logging support .build()) .build();// Initialize the serversyncServer.initialize();// Register tools, resources, and promptssyncServer.addTool(syncToolRegistration);syncServer.addResource(syncResourceRegistration);syncServer.addPrompt(syncPromptRegistration);// Send logging notificationssyncServer.loggingNotification(LoggingMessageNotification.builder() .level(LoggingLevel.INFO) .logger("custom-logger") .data("Server initialized") .build());// Close the server when donesyncServer.close();
// Create an async server with custom configurationMcpAsyncServer asyncServer = McpServer.async(transport) .serverInfo("my-server", "1.0.0") .capabilities(ServerCapabilities.builder() .resources(true) // Enable resource support .tools(true) // Enable tool support .prompts(true) // Enable prompt support .logging() // Enable logging support .build()) .build();// Initialize the serverasyncServer.initialize() .doOnSuccess(v -> logger.info("Server initialized")) .subscribe();// Register tools, resources, and promptsasyncServer.addTool(asyncToolRegistration) .doOnSuccess(v -> logger.info("Tool registered")) .subscribe();asyncServer.addResource(asyncResourceRegistration) .doOnSuccess(v -> logger.info("Resource registered")) .subscribe();asyncServer.addPrompt(asyncPromptRegistration) .doOnSuccess(v -> logger.info("Prompt registered")) .subscribe();// Send logging notificationsasyncServer.loggingNotification(LoggingMessageNotification.builder() .level(LoggingLevel.INFO) .logger("custom-logger") .data("Server initialized") .build());// Close the server when doneasyncServer.close() .doOnSuccess(v -> logger.info("Server closed")) .subscribe();