|
| 1 | +package mcp; |
| 2 | + |
| 3 | +import java.io.IOException; |
| 4 | +import java.util.Map; |
| 5 | + |
| 6 | +import org.slf4j.Logger; |
| 7 | +import org.slf4j.LoggerFactory; |
| 8 | + |
| 9 | +import com.fasterxml.jackson.databind.ObjectMapper; |
| 10 | + |
| 11 | +import io.modelcontextprotocol.client.McpClient; |
| 12 | +import io.modelcontextprotocol.client.McpSyncClient; |
| 13 | +import io.modelcontextprotocol.client.transport.ServerParameters; |
| 14 | +import io.modelcontextprotocol.client.transport.StdioClientTransport; |
| 15 | +import io.modelcontextprotocol.json.jackson.JacksonMcpJsonMapper; |
| 16 | +import io.modelcontextprotocol.spec.McpClientTransport; |
| 17 | +import io.modelcontextprotocol.spec.McpSchema.CallToolRequest; |
| 18 | +import io.modelcontextprotocol.spec.McpSchema.CallToolResult; |
| 19 | +import io.modelcontextprotocol.spec.McpSchema.ListToolsResult; |
| 20 | + |
| 21 | + |
| 22 | +public class McpClientApp2 { |
| 23 | + |
| 24 | + private static final Logger log = LoggerFactory.getLogger(McpClientApp2.class); |
| 25 | + |
| 26 | + public static void main(String[] args) { |
| 27 | + String jarPath = new java.io.File("java-mcp/target/java-mcp-1.0.0-SNAPSHOT.jar").getAbsolutePath(); |
| 28 | + ServerParameters params = ServerParameters.builder("java") |
| 29 | + .args("-jar", jarPath) |
| 30 | + .build(); |
| 31 | + |
| 32 | + JacksonMcpJsonMapper jsonMapper = new JacksonMcpJsonMapper(new ObjectMapper()); |
| 33 | + McpClientTransport transport = new StdioClientTransport(params, jsonMapper); |
| 34 | + |
| 35 | + McpSyncClient client = McpClient.sync(transport) |
| 36 | + .build(); |
| 37 | + |
| 38 | + client.initialize(); |
| 39 | + |
| 40 | + ListToolsResult tools = client.listTools(); |
| 41 | + McpClientApp2.log.info("Tools exposed by the server:"); |
| 42 | + tools.tools() |
| 43 | + .forEach(tool -> System.out.println(" - " + tool.name())); |
| 44 | + |
| 45 | + McpClientApp2.log.info("\nCalling 'logPrompt' tool..."); |
| 46 | + CallToolResult result = client.callTool(new CallToolRequest("logPrompt", Map.of("prompt", "Hello from MCP client!"))); |
| 47 | + McpClientApp2.log.info("Result: " + result.content()); |
| 48 | + |
| 49 | + client.closeGracefully(); |
| 50 | + } |
| 51 | +} |
0 commit comments