跳转到主要内容

标签(标签)

资源精选(342) Go开发(108) Go语言(103) Go(99) LLM(84) angular(83) 大语言模型(67) 人工智能(56) 前端开发(50) LangChain(43) golang(43) 机器学习(40) Go工程师(38) Go程序员(38) Go开发者(36) React(34) Go基础(29) Python(24) Vue(23) Web开发(20) 深度学习(20) Web技术(19) 精选资源(19) Java(19) ChatGTP(17) Cookie(16) android(16) 前端框架(13) JavaScript(13) Next.js(12) ChatGPT(11) LLMOps(11) 聊天机器人(11) 安卓(11) typescript(10) 资料精选(10) mlops(10) NLP(10) 第三方Cookie(9) Redwoodjs(9) RAG(9) Go语言中级开发(9) 自然语言处理(9) PostgreSQL(9) 区块链(9) 安全(9) 智能体(8) 全栈开发(8) OpenAI(8) Linux(8) AI(8) GraphQL(8) iOS(8) 数据科学(8) 软件架构(7) Go语言高级开发(7) AWS(7) C++(7) whisper(6) Prisma(6) 隐私保护(6) 提示工程(6) Agent(6) JSON(6) DevOps(6) 数据可视化(6) wasm(6) 计算机视觉(6) 算法(6) Rust(6) 微服务(6) 隐私沙盒(5) FedCM(5) 语音识别(5) Angular开发(5) 快速应用开发(5) 生成式AI(5) LLaMA(5) 低代码开发(5) Go测试(5) gorm(5) REST API(5) kafka(5) 推荐系统(5) WebAssembly(5) GameDev(5) 数据分析(5) CMS(5) CSS(5) machine-learning(5) 机器人(5) 游戏开发(5) Blockchain(5) Web安全(5) nextjs(5) Kotlin(5) 低代码平台(5) 机器学习资源(5) Go资源(5) Nodejs(5) PHP(5) Swift(5) RAG架构(4) devin(4) LLM Agent(4) Blitz(4) javascript框架(4) Redwood(4) GDPR(4) 生成式人工智能(4) Angular16(4) Alpaca(4) 编程语言(4) SAML(4) JWT(4) JSON处理(4) Go并发(4) 移动开发(4) 移动应用(4) security(4) 隐私(4) spring-boot(4) 物联网(4) 网络安全(4) API(4) Ruby(4) 信息安全(4) flutter(4) 专家智能体(3) Chrome(3) CHIPS(3) 3PC(3) SSE(3) 人工智能软件工程师(3) Remix(3) Ubuntu(3) GPT4All(3) 模型评估(3) 软件开发(3) 问答系统(3) 开发工具(3) 最佳实践(3) RxJS(3) SSR(3) Node.js(3) Dolly(3) 移动应用开发(3) 低代码(3) IAM(3) Web框架(3) CORS(3) 基准测试(3) Go语言数据库开发(3) Oauth2(3) 并发(3) 主题(3) Theme(3) earth(3) nginx(3) 软件工程(3) azure(3) keycloak(3) 生产力工具(3) gpt3(3) 工作流(3) C(3) jupyter(3) 认证(3) prometheus(3) GAN(3) Spring(3) 逆向工程(3) 应用安全(3) Docker(3) Django(3) Machine Learning(3) R(3) .NET(3) 大数据(3) Hacking(3) 渗透测试(3) C++资源(3) Mac(3) 微信小程序(3) Python资源(3) JHipster(3) JDK(2) SQL(2) Apache(2) Hashicorp Vault(2) Spring Cloud Vault(2) Go语言Web开发(2) Go测试工程师(2) WebSocket(2) 容器化(2) AES(2) 加密(2) 输入验证(2) ORM(2) Fiber(2) Postgres(2) Gorilla Mux(2) Go数据库开发(2) 模块(2) 泛型(2) 指针(2) HTTP(2) PostgreSQL开发(2) Vault(2) K8s(2) Spring boot(2) R语言(2) 深度学习资源(2) 半监督学习(2) semi-supervised-learning(2) architecture(2) 普罗米修斯(2) 嵌入模型(2) productivity(2) 编码(2) Qt(2) 前端(2) Rust语言(2) NeRF(2) 神经辐射场(2) 元宇宙(2) CPP(2) spark(2) 流处理(2) Ionic(2) 人体姿势估计(2) human-pose-estimation(2) 视频处理(2) deep-learning(2) kotlin语言(2) kotlin开发(2) burp(2) Chatbot(2) npm(2) quantum(2) OCR(2) 游戏(2) game(2) 内容管理系统(2) MySQL(2) python-books(2) pentest(2) opengl(2) IDE(2) 漏洞赏金(2) Web(2) 知识图谱(2) PyTorch(2) 数据库(2) reverse-engineering(2) 数据工程(2) swift开发(2) rest(2) robotics(2) ios-animation(2) 知识蒸馏(2) 安卓开发(2) nestjs(2) solidity(2) 爬虫(2) 面试(2) 容器(2) C++精选(2) 人工智能资源(2) 备忘单(2) 编程书籍(2) angular资源(2) 速查表(2) cheatsheets(2) SecOps(2) mlops资源(2) R资源(2) DDD(2) 架构设计模式(2) 量化(2) Hacking资源(2) 强化学习(2) flask(2) 设计(2) 性能(2) Sysadmin(2) 系统管理员(2) Java资源(2) 机器学习精选(2) android资源(2) android-UI(2) Mac资源(2) iOS资源(2) Vue资源(2) flutter资源(2) JavaScript精选(2) JavaScript资源(2) Rust开发(2) deeplearning(2) RAD(2)
SEO Title

category

Java MCP客户端

了解如何使用模型上下文协议(MCP)客户端与MCP服务器交互

转到Java MCP服务器了解如何构建MCP服务器,或转到Java MCP概述了解整体架构。
 

模型上下文协议客户端

MCP客户端是模型上下文协议(MCP)架构中的关键组件,负责建立和管理与MCP服务器的连接。它实现了协议的客户端,处理:

  • 协议版本协商,以确保与服务器的兼容性
  • 能力协商以确定可用功能
  • 消息传输和JSON-RPC通信
  • 工具发现和执行
  • 资源访问和管理
  • 及时的系统交互
  • 可选功能,如根管理和采样支持
     

核心io.modelcontextprotocol.sdk:mcp模块提供STDIO和SSE客户端传输实现,无需外部web框架。
Spring特定的传输实现可作为可选依赖项io.modelcontextprotocol.sdk:mcp-Spring-webflux提供给Spring Framework用户。
这个基于Spring AI MCP的快速入门演示将向您展示如何构建连接到MCP服务器的AI客户端。
客户端提供同步和异步API,以在不同的应用程序上下文中实现灵活性。

  •  
// Create a sync client with custom configuration
McpSyncClient client = McpClient.sync(transport)
    .requestTimeout(Duration.ofSeconds(10))
    .capabilities(ClientCapabilities.builder()
        .roots(true)      // Enable roots capability
        .sampling()       // Enable sampling capability
        .build())
    .sampling(request -> new CreateMessageResult(response))
    .build();

// Initialize connection
client.initialize();

// List available tools
ListToolsResult tools = client.listTools();

// Call a tool
CallToolResult result = client.callTool(
    new CallToolRequest("calculator",
        Map.of("operation", "add", "a", 2, "b", 3))
);

// List and read resources
ListResourcesResult resources = client.listResources();
ReadResourceResult resource = client.readResource(
    new ReadResourceRequest("resource://uri")
);

// List and use prompts
ListPromptsResult prompts = client.listPrompts();
GetPromptResult prompt = client.getPrompt(
    new GetPromptRequest("greeting", Map.of("name", "Spring"))
);

// Add/remove roots
client.addRoot(new Root("file:///path", "description"));
client.removeRoot("file:///path");

// Close client
client.closeGracefully();
// Create an async client with custom configuration
McpAsyncClient client = McpClient.async(transport)
    .requestTimeout(Duration.ofSeconds(10))
    .capabilities(ClientCapabilities.builder()
        .roots(true)      // Enable roots capability
        .sampling()       // Enable sampling capability
        .build())
    .sampling(request -> Mono.just(new CreateMessageResult(response)))
    .toolsChangeConsumer(tools -> Mono.fromRunnable(() -> {
        logger.info("Tools updated: {}", tools);
    }))
    .resourcesChangeConsumer(resources -> Mono.fromRunnable(() -> {
        logger.info("Resources updated: {}", resources);
    }))
    .promptsChangeConsumer(prompts -> Mono.fromRunnable(() -> {
        logger.info("Prompts updated: {}", prompts);
    }))
    .build();

// Initialize connection and use features
client.initialize()
    .flatMap(initResult -> client.listTools())
    .flatMap(tools -> {
        return client.callTool(new CallToolRequest(
            "calculator",
            Map.of("operation", "add", "a", 2, "b", 3)
        ));
    })
    .flatMap(result -> {
        return client.listResources()
            .flatMap(resources ->
                client.readResource(new ReadResourceRequest("resource://uri"))
            );
    })
    .flatMap(resource -> {
        return client.listPrompts()
            .flatMap(prompts ->
                client.getPrompt(new GetPromptRequest(
                    "greeting",
                    Map.of("name", "Spring")
                ))
            );
    })
    .flatMap(prompt -> {
        return client.addRoot(new Root("file:///path", "description"))
            .then(client.removeRoot("file:///path"));
    })
    .doFinally(signalType -> {
        client.closeGracefully().subscribe();
    })
    .subscribe();

 

客户端传输


传输层处理MCP客户端和服务器之间的通信,为各种用例提供不同的实现。客户端传输管理消息序列化、连接建立和特定于协议的通信模式。

Creates transport for in-process based communication

ServerParameters params = ServerParameters.builder("npx")
    .args("-y", "@modelcontextprotocol/server-everything", "dir")
    .build();
McpTransport transport = new StdioClientTransport(params);
  •  

Creates a framework agnostic (pure Java API) SSE client transport. Included in the core mcp module.

McpTransport transport = new HttpClientSseClientTransport("http://your-mcp-server");

 

Creates WebFlux-based SSE client transport. Requires the mcp-webflux-sse-transport dependency.

WebClient.Builder webClientBuilder = WebClient.builder()
    .baseUrl("http://your-mcp-server");
McpTransport transport = new WebFluxSseClientTransport(webClientBuilder);

Client Capabilities

The client can be configured with various capabilities:

var capabilities = ClientCapabilities.builder()
    .roots(true)      // Enable filesystem roots support with list changes notifications
    .sampling()       // Enable LLM sampling support
    .build();

Roots Support

Roots define the boundaries of where servers can operate within the filesystem:

// Add a root dynamically
client.addRoot(new Root("file:///path", "description"));

// Remove a root
client.removeRoot("file:///path");

// Notify server of roots changes
client.rootsListChangedNotification();

The roots capability allows servers to:

  • Request the list of accessible filesystem roots
  • Receive notifications when the roots list changes
  • Understand which directories and files they have access to

Sampling Support

Sampling enables servers to request LLM interactions (“completions” or “generations”) through the client:

// Configure sampling handler
Function<CreateMessageRequest, CreateMessageResult> samplingHandler = request -> {
    // Sampling implementation that interfaces with LLM
    return new CreateMessageResult(response);
};

// Create client with sampling support
var client = McpClient.sync(transport)
    .capabilities(ClientCapabilities.builder()
        .sampling()
        .build())
    .sampling(samplingHandler)
    .build();

This capability allows:

  • 无需API密钥即可利用人工智能功能的服务器
  • 客户端保持对模型访问和权限的控制
  • 支持基于文本和图像的交互
  • 在提示中可选地包含MCP服务器上下文

Logging Support

The client can register a logging consumer to receive log messages from the server and set the minimum logging level to filter messages:

var mcpClient = McpClient.sync(transport)
        .loggingConsumer(notification -> {
            System.out.println("Received log message: " + notification.data());
        })
        .build();

mcpClient.initialize();

mcpClient.setLoggingLevel(McpSchema.LoggingLevel.INFO);

// Call the tool that can sends logging notifications
CallToolResult result = mcpClient.callTool(new McpSchema.CallToolRequest("logging-test", Map.of()));

Clients can control the minimum logging level they receive through the mcpClient.setLoggingLevel(level) request. Messages below the set level will be filtered out. Supported logging levels (in order of increasing severity): DEBUG (0), INFO (1), NOTICE (2), WARNING (3), ERROR (4), CRITICAL (5), ALERT (6), EMERGENCY (7)

使用MCP客户端

工具执行

 

工具是客户端可以发现和执行的服务器端功能。MCP客户端提供列出可用工具并使用特定参数执行这些工具的方法。每个工具都有一个唯一的名称,并接受参数映射。

  •  
// List available tools and their names
var tools = client.listTools();
tools.forEach(tool -> System.out.println(tool.getName()));

// Execute a tool with parameters
var result = client.callTool("calculator", Map.of(
    "operation", "add",
    "a", 1,
    "b", 2
));

 

// List available tools and their names
var tools = client.listTools();
tools.forEach(tool -> System.out.println(tool.getName()));

// Execute a tool with parameters
var result = client.callTool("calculator", Map.of(
    "operation", "add",
    "a", 1,
    "b", 2
));

 

资源访问


资源表示客户端可以使用URI模板访问的服务器端数据源。MCP客户端提供了通过标准化接口发现可用资源并检索其内容的方法。

  •  
// List available resources and their names
var resources = client.listResources();
resources.forEach(resource -> System.out.println(resource.getName()));

// Retrieve resource content using a URI template
var content = client.getResource("file", Map.of(
    "path", "/path/to/file.txt"
));

 

// List available resources and their names
var resources = client.listResources();
resources.forEach(resource -> System.out.println(resource.getName()));

// Retrieve resource content using a URI template
var content = client.getResource("file", Map.of(
    "path", "/path/to/file.txt"
));

 

提示系统


提示系统允许与服务器端提示模板进行交互。这些模板可以使用自定义参数进行发现和执行,从而允许基于预定义模式进行动态文本生成。

  •  
// List available prompt templates
var prompts = client.listPrompts();
prompts.forEach(prompt -> System.out.println(prompt.getName()));

// Execute a prompt template with parameters
var response = client.executePrompt("echo", Map.of(
    "text", "Hello, World!"
));

 

// List available prompt templates
var prompts = client.listPrompts();
prompts.forEach(prompt -> System.out.println(prompt.getName()));

// Execute a prompt template with parameters
var response = client.executePrompt("echo", Map.of(
    "text", "Hello, World!"
));

 

使用完成


作为完成功能的一部分,MCP为服务器提供了一种标准化的方式,为提示和资源URI提供参数自动完成建议。
检查服务器完成功能,了解如何在服务器端启用和配置完成。
在客户端,MCP客户端提供请求自动补全的方法:

  •  

CompleteRequest request = new CompleteRequest(
        new PromptReference("code_review"),
        new CompleteRequest.CompleteArgument("language", "py"));

CompleteResult result = syncMcpClient.completeCompletion(request);



CompleteRequest request = new CompleteRequest(
        new PromptReference("code_review"),
        new CompleteRequest.CompleteArgument("language", "py"));

CompleteResult result = syncMcpClient.completeCompletion(request);

 

文章链接

标签