Implementing Sampling in MCP (Model Context Protocol) with Java: A Comprehensive Guide
# How to Implement Sampling in MCP (Model Context Protocol) with Java
## What is MCP Sampling?
MCP sampling allows you to capture and process streaming messages from AI models in real-time. It’s useful for monitoring AI outputs, logging interactions, or processing data as it’s generated.
## Simple Implementation
Here’s a complete, simple example of how to implement MCP sampling in Java:
### 1. Create a Sampling Handler
“`java
package com.example.mcp;
import io.modelcontextprotocol.spec.McpSchema.CreateMessageRequest;
import io.modelcontextprotocol.spec.McpSchema.CreateMessageResult;
import io.modelcontextprotocol.spec.McpSchema.TextContent;
/**
* Simple sampling handler that processes AI model messages
*/
public class SimpleSamplingHandler {
public CreateMessageResult handleSampling(CreateMessageRequest request) {
System.out.println(“Received ” + request.messages().size() + ” messages”);
// Process each message
for (var message : request.messages()) {
System.out.println(“Message: ” + message.toString());
// Add your custom processing logic here
}
return CreateMessageResult.builder()
.content(new TextContent(“Processing completed”))
.build();
}
}
“`
### 2. Create a Sampling Consumer
“`java
package com.example.mcp;
import io.modelcontextprotocol.spec.McpSchema.CreateMessageRequest;
import io.modelcontextprotocol.spec.McpSchema.CreateMessageResult;
import io.modelcontextprotocol.spec.McpSchema.TextContent;
import java.util.function.Function;
/**
* Wrapper that connects MCP to your sampling handler
*/
public class SamplingConsumer implements Function<CreateMessageRequest, CreateMessageResult> {
private final SimpleSamplingHandler handler;
public SamplingConsumer(SimpleSamplingHandler handler) {
this.handler = handler;
}
@Override
public CreateMessageResult apply(CreateMessageRequest request) {
try {
return handler.handleSampling(request);
} catch (Exception e) {
System.err.println(“Error processing sampling: ” + e.getMessage());
return CreateMessageResult.builder()
.content(new TextContent(“Error: ” + e.getMessage()))
.build();
}
}
}
“`
### 3. Use with MCP Client
“`java
package com.example.mcp;
import io.modelcontextprotocol.client.McpClient;
import io.modelcontextprotocol.client.McpSyncClient;
public class McpSamplingExample {
public static void main(String[] args) {
// Create your sampling handler
SimpleSamplingHandler handler = new SimpleSamplingHandler();
// Create the sampling consumer
SamplingConsumer consumer = new SamplingConsumer(handler);
// Create MCP client with sampling
McpSyncClient client = McpClient.sync(transport)
.sampling(consumer)
.build();
// Your MCP client is now ready to use with sampling!
// All AI model messages will be processed by your handler
}
}
“`
## That’s It!
This simple implementation:
1. **Captures** all messages from the AI model
2. **Processes** them in your `SimpleSamplingHandler`
3. **Logs** them to the console (you can change this to whatever you need)
4. **Handles errors** gracefully
## Customize Your Handler
You can modify the `SimpleSamplingHandler` to do whatever you need:
“`java
public CreateMessageResult handleSampling(CreateMessageRequest request) {
for (var message : request.messages()) {
String messageText = message.toString();
// Example: Save to database
// database.save(messageText);
// Example: Send to external API
// httpClient.post(“https://api.example.com”, messageText);
// Example: Filter specific content
if (messageText.contains(“important”)) {
System.out.println(“Important message: ” + messageText);
}
}
return CreateMessageResult.builder()
.content(new TextContent(“Done”))
.build();
}
“`
## Maven Dependency
Add this to your `pom.xml`:
“`xml
<dependency>
<groupId>io.modelcontextprotocol</groupId>
<artifactId>mcp-client</artifactId>
<version>1.0.0</version>
</dependency>
“`
That’s all you need to get started with MCP sampling in Java!