001/* 002 * Copyright 2022-2026 Revetware LLC. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package com.soklet; 018 019import org.jspecify.annotations.NonNull; 020 021import javax.annotation.concurrent.ThreadSafe; 022 023import static java.util.Objects.requireNonNull; 024 025/** 026 * Common contract implemented by MCP endpoint classes. 027 * 028 * @author <a href="https://www.revetkn.com">Mark Allen</a> 029 */ 030@ThreadSafe 031public interface McpEndpoint { 032 /** 033 * Initializes a newly-created MCP session. 034 * 035 * @param context the initialization request context 036 * @param session the blank or previously-composed session context 037 * @return the session context that should be persisted for the new session 038 * @throws Exception if initialization fails 039 */ 040 @NonNull 041 default McpSessionContext initialize(@NonNull McpInitializationContext context, 042 @NonNull McpSessionContext session) throws Exception { 043 requireNonNull(context); 044 requireNonNull(session); 045 return session; 046 } 047 048 /** 049 * Maps a thrown tool exception to an MCP tool result. 050 * 051 * @param throwable the thrown exception 052 * @param context the tool-call context 053 * @return the tool result to return to the client 054 */ 055 @NonNull 056 default McpToolResult handleToolError(@NonNull Throwable throwable, 057 @NonNull McpToolCallContext context) { 058 requireNonNull(throwable); 059 requireNonNull(context); 060 return McpToolResult.fromErrorMessage(throwable.getMessage() == null ? throwable.getClass().getSimpleName() : throwable.getMessage()); 061 } 062 063 /** 064 * Maps a non-tool MCP exception to a JSON-RPC error. 065 * 066 * @param throwable the thrown exception 067 * @param context the request context 068 * @return the JSON-RPC error to return to the client 069 */ 070 @NonNull 071 default McpJsonRpcError handleError(@NonNull Throwable throwable, 072 @NonNull McpRequestContext context) { 073 requireNonNull(throwable); 074 requireNonNull(context); 075 return McpJsonRpcError.fromCodeAndMessage(-32603, "Internal error"); 076 } 077}