|
| 1 | +package io.modelcontextprotocol.examples.stateless.server; |
| 2 | + |
| 3 | +import io.modelcontextprotocol.server.McpStatelessServerFeatures.SyncToolSpecification; |
| 4 | +import io.modelcontextprotocol.spec.McpError; |
| 5 | +import io.modelcontextprotocol.spec.McpSchema; |
| 6 | +import io.modelcontextprotocol.spec.McpSchema.CallToolResult; |
| 7 | +import io.modelcontextprotocol.spec.McpSchema.JSONRPCResponse.JSONRPCError; |
| 8 | +import jakarta.servlet.http.HttpServletRequest; |
| 9 | + |
| 10 | +import static io.modelcontextprotocol.examples.stateless.server.McpServerBuilder.CONTEXT_REQUEST_KEY; |
| 11 | +import static io.modelcontextprotocol.spec.McpSchema.ErrorCodes.INVALID_REQUEST; |
| 12 | + |
| 13 | +public interface Tools { |
| 14 | + |
| 15 | + String addTwoNumbersSchemaJson = """ |
| 16 | + { |
| 17 | + "type": "object", |
| 18 | + "properties": { |
| 19 | + "a": { |
| 20 | + "type": "integer" |
| 21 | + }, |
| 22 | + "b": { |
| 23 | + "type": "integer" |
| 24 | + } |
| 25 | + }, |
| 26 | + "required": ["a", "b"] |
| 27 | + } |
| 28 | + """; |
| 29 | + |
| 30 | + String requestHeaderSchemaJson = """ |
| 31 | + { |
| 32 | + "type": "object", |
| 33 | + "properties": { |
| 34 | + "headerName": { |
| 35 | + "type": "string" |
| 36 | + } |
| 37 | + }, |
| 38 | + "required": ["headerName"] |
| 39 | + } |
| 40 | + """; |
| 41 | + |
| 42 | + SyncToolSpecification addTwoNumbers = SyncToolSpecification.builder() |
| 43 | + .tool(McpSchema.Tool.builder().name("add").inputSchema(addTwoNumbersSchemaJson).build()) |
| 44 | + .callHandler((transportContext, callToolRequest) -> { |
| 45 | + int a = Integer.parseInt(String.valueOf(callToolRequest.arguments().get("a"))); |
| 46 | + int b = Integer.parseInt(String.valueOf(callToolRequest.arguments().get("b"))); |
| 47 | + |
| 48 | + return new CallToolResult(String.valueOf(a + b), null); |
| 49 | + }) |
| 50 | + .build(); |
| 51 | + |
| 52 | + SyncToolSpecification requestHeader = SyncToolSpecification.builder() |
| 53 | + .tool(McpSchema.Tool.builder().name("requestHeader").inputSchema(requestHeaderSchemaJson).build()) |
| 54 | + .callHandler((transportContext, callToolRequest) -> { |
| 55 | + HttpServletRequest request = (HttpServletRequest) transportContext.get(CONTEXT_REQUEST_KEY); |
| 56 | + String headerName = String.valueOf(callToolRequest.arguments().get("headerName")); |
| 57 | + |
| 58 | + String value = request.getHeader(headerName); |
| 59 | + if (value == null) { |
| 60 | + throw new McpError(new JSONRPCError(INVALID_REQUEST, "Header '" + headerName + "' not found", null)); |
| 61 | + } |
| 62 | + |
| 63 | + return new CallToolResult(value, null); |
| 64 | + }) |
| 65 | + .build(); |
| 66 | + |
| 67 | +} |
0 commit comments