repo
stringclasses
1k values
file_url
stringlengths
96
373
file_path
stringlengths
11
294
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
6 values
commit_sha
stringclasses
1k values
retrieved_at
stringdate
2026-01-04 14:45:56
2026-01-04 18:30:23
truncated
bool
2 classes
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/labs/arthas-jfr-backend/src/main/java/org/example/jfranalyzerbackend/vo/Metadata.java
labs/arthas-jfr-backend/src/main/java/org/example/jfranalyzerbackend/vo/Metadata.java
package org.example.jfranalyzerbackend.vo; import lombok.Getter; import lombok.Setter; import org.example.jfranalyzerbackend.model.PerfDimension; @Setter @Getter public class Metadata { private PerfDimension[] perfDimensions; }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/labs/arthas-jfr-backend/src/main/java/org/example/jfranalyzerbackend/config/Result.java
labs/arthas-jfr-backend/src/main/java/org/example/jfranalyzerbackend/config/Result.java
package org.example.jfranalyzerbackend.config; import java.util.Objects; public class Result<T> { private Integer code; private String msg; private T data; public Result() { } public Result(Integer code, String msg, T data) { this.code = code; this.msg = msg; this.data = data; } public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public T getData() { return data; } public void setData(T data) { this.data = data; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Result<?> result = (Result<?>) o; return Objects.equals(code, result.code) && Objects.equals(msg, result.msg) && Objects.equals(data, result.data); } @Override public int hashCode() { return Objects.hash(code, msg, data); } @Override public String toString() { return "Result{" + "code=" + code + ", msg='" + msg + '\'' + ", data=" + data + '}'; } public static <T> Result<T> success(T data) { Result<T> result = new Result<>(); result.code = 1; result.msg = "success"; result.data = data; return result; } public static Result<Void> success() { Result<Void> result = new Result<>(); result.code = 1; result.msg = "success"; return result; } public static Result<Void> error(String msg) { Result<Void> result = new Result<>(); result.code = 0; result.msg = msg; return result; } /** * 泛型错误方法,用于返回指定类型的错误结果 * @param msg 错误消息 * @param <T> 数据类型 * @return 错误结果 */ public static <T> Result<T> errorWithType(String msg) { Result<T> result = new Result<>(); result.code = 0; result.msg = msg; result.data = null; return result; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/labs/arthas-jfr-backend/src/main/java/org/example/jfranalyzerbackend/config/ArthasConfig.java
labs/arthas-jfr-backend/src/main/java/org/example/jfranalyzerbackend/config/ArthasConfig.java
package org.example.jfranalyzerbackend.config; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @Component @ConfigurationProperties(prefix = "arthas") public class ArthasConfig { private String jfrStoragePath; public String getJfrStoragePath() { return jfrStoragePath; } public void setJfrStoragePath(String jfrStoragePath) { this.jfrStoragePath = jfrStoragePath; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/labs/arthas-jfr-backend/src/main/java/org/example/jfranalyzerbackend/config/CorsConfig.java
labs/arthas-jfr-backend/src/main/java/org/example/jfranalyzerbackend/config/CorsConfig.java
package org.example.jfranalyzerbackend.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.CorsConfigurationSource; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOriginPatterns("*") .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") .allowedHeaders("*") .allowCredentials(true) .maxAge(3600); } @Bean public CorsConfigurationSource corsConfigurationSource() { CorsConfiguration configuration = new CorsConfiguration(); configuration.addAllowedOriginPattern("*"); configuration.addAllowedMethod("*"); configuration.addAllowedHeader("*"); configuration.setAllowCredentials(true); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", configuration); return source; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/labs/arthas-jfr-backend/src/main/java/org/example/jfranalyzerbackend/request/AnalysisRequest.java
labs/arthas-jfr-backend/src/main/java/org/example/jfranalyzerbackend/request/AnalysisRequest.java
package org.example.jfranalyzerbackend.request; import lombok.Getter; import java.io.InputStream; import java.nio.file.Path; @Getter public class AnalysisRequest { private final int parallelWorkers; private final Path input; private final InputStream inputStream; private final int dimensions; public AnalysisRequest(Path input, int dimensions) { this(1, input, dimensions); } public AnalysisRequest(int parallelWorkers, Path input, int dimensions) { this(parallelWorkers, input, null, dimensions); } private AnalysisRequest(int parallelWorkers, Path p, InputStream stream, int dimensions) { this.parallelWorkers = parallelWorkers; this.input = p; this.dimensions = dimensions; this.inputStream = stream; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/labs/arthas-jfr-backend/src/main/java/org/example/jfranalyzerbackend/enums/FileType.java
labs/arthas-jfr-backend/src/main/java/org/example/jfranalyzerbackend/enums/FileType.java
package org.example.jfranalyzerbackend.enums; public enum FileType { JFR, LOG, OTHER }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/labs/arthas-jfr-backend/src/main/java/org/example/jfranalyzerbackend/enums/CommonErrorCode.java
labs/arthas-jfr-backend/src/main/java/org/example/jfranalyzerbackend/enums/CommonErrorCode.java
package org.example.jfranalyzerbackend.enums; import org.example.jfranalyzerbackend.exception.ErrorCode; public enum CommonErrorCode implements ErrorCode { ILLEGAL_ARGUMENT("Illegal argument"), VALIDATION_FAILURE("Validation failure"), INTERNAL_ERROR("Internal error"); private final String message; CommonErrorCode(String message) { this.message = message; } @Override public String message() { return message; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/labs/arthas-jfr-backend/src/main/java/org/example/jfranalyzerbackend/enums/Unit.java
labs/arthas-jfr-backend/src/main/java/org/example/jfranalyzerbackend/enums/Unit.java
package org.example.jfranalyzerbackend.enums; import com.fasterxml.jackson.annotation.JsonValue; public enum Unit { NANO_SECOND("ns"), BYTE("byte"), COUNT("count"); private final String tag; Unit(String tag) { this.tag = tag; } @JsonValue public String getTag() { return tag; } @Override public String toString() { return tag; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/labs/arthas-jfr-backend/src/main/java/org/example/jfranalyzerbackend/enums/EventConstant.java
labs/arthas-jfr-backend/src/main/java/org/example/jfranalyzerbackend/enums/EventConstant.java
package org.example.jfranalyzerbackend.enums; public abstract class EventConstant { public static String UNSIGNED_INT_FLAG = "jdk.UnsignedIntFlag"; public static String GARBAGE_COLLECTION = "jdk.GarbageCollection"; public static String CPU_INFORMATION = "jdk.CPUInformation"; public static String CPC_RUNTIME_INFORMATION = "cpc.RuntimeInformation"; public static String ENV_VAR = "jdk.InitialEnvironmentVariable"; public static String PROCESS_CPU_LOAD = "jdk.CPULoad"; public static String ACTIVE_SETTING = "jdk.ActiveSetting"; public static String THREAD_START = "jdk.ThreadStart"; public static String THREAD_CPU_LOAD = "jdk.ThreadCPULoad"; public static String EXECUTION_SAMPLE = "jdk.ExecutionSample"; public static String WALL_CLOCK_SAMPLE = "jdk.ExecutionSample"; public static String NATIVE_EXECUTION_SAMPLE = "jdk.NativeMethodSample"; public static String EXECUTE_VM_OPERATION = "jdk.ExecuteVMOperation"; public static String OBJECT_ALLOCATION_SAMPLE = "jdk.ObjectAllocationSample"; public static String OBJECT_ALLOCATION_IN_NEW_TLAB = "jdk.ObjectAllocationInNewTLAB"; public static String OBJECT_ALLOCATION_OUTSIDE_TLAB = "jdk.ObjectAllocationOutsideTLAB"; public static String FILE_WRITE = "jdk.FileWrite"; public static String FILE_READ = "jdk.FileRead"; public static String FILE_FORCE = "jdk.FileForce"; public static String SOCKET_READ = "jdk.SocketRead"; public static String SOCKET_WRITE = "jdk.SocketWrite"; public static String JAVA_MONITOR_ENTER = "jdk.JavaMonitorEnter"; public static String JAVA_MONITOR_WAIT = "jdk.JavaMonitorWait"; public static String THREAD_PARK = "jdk.ThreadPark"; public static String CLASS_LOAD = "jdk.ClassLoad"; public static String THREAD_SLEEP = "jdk.ThreadSleep"; public static String PERIOD = "period"; public static String INTERVAL = "interval"; public static String WALL = "wall"; public static String EVENT = "event"; }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/labs/arthas-jfr-backend/src/main/java/org/example/jfranalyzerbackend/enums/ServerErrorCode.java
labs/arthas-jfr-backend/src/main/java/org/example/jfranalyzerbackend/enums/ServerErrorCode.java
package org.example.jfranalyzerbackend.enums; import org.example.jfranalyzerbackend.exception.ErrorCode; public enum ServerErrorCode implements ErrorCode { UNAVAILABLE("Unavailable"), USER_NOT_FOUND("User not found"), USERNAME_EXISTS("Username exists"), INCORRECT_PASSWORD("Incorrect password"), ACCESS_DENIED("Access denied"), FILE_NOT_FOUND("File not found"), FILE_DELETED("File deleted"), UNSUPPORTED_NAMESPACE("Unsupported namespace"), UNSUPPORTED_API("Unsupported API"), FILE_TRANSFER_INCOMPLETE("File transfer incomplete"), FILE_TYPE_MISMATCH("File type mismatch"), FILE_TRANSFER_METHOD_DISABLED("File transfer method disabled"), STATIC_WORKER_UNAVAILABLE("Static worker Unavailable"), ELASTIC_WORKER_NOT_READY("Elastic worker not ready"), ELASTIC_WORKER_STARTUP_FAILURE("Elastic worker startup failure"), NO_AVAILABLE_LOCATION("No available location"), INVALID_FILENAME("Invalid filename"), ; private final String message; ServerErrorCode(String message) { this.message = message; } @Override public String message() { return message; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/labs/arthas-grpc-server/src/test/java/unittest/grpc/GrpcTest.java
labs/arthas-grpc-server/src/test/java/unittest/grpc/GrpcTest.java
package unittest.grpc; import arthas.grpc.unittest.ArthasUnittest; import arthas.grpc.unittest.ArthasUnittestServiceGrpc; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.LoggerContext; import com.taobao.arthas.grpc.server.ArthasGrpcServer; import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; import io.grpc.stub.StreamObserver; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.slf4j.LoggerFactory; import java.lang.invoke.MethodHandles; import java.util.Random; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; /** * @author: FengYe * @date: 2024/9/24 00:17 * @description: GrpcUnaryTest */ public class GrpcTest { private static final String HOST = "localhost"; private static final int PORT = 9092; private static final String HOST_PORT = HOST + ":" + PORT; private static final String UNIT_TEST_GRPC_SERVICE_PACKAGE_NAME = "unittest.grpc.service.impl"; private static final Logger log = (Logger) LoggerFactory.getLogger(GrpcTest.class); private ManagedChannel clientChannel; Random random = new Random(); ExecutorService threadPool = Executors.newFixedThreadPool(10); @Before public void startServer() { LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); Logger rootLogger = loggerContext.getLogger("ROOT"); rootLogger.setLevel(Level.INFO); Thread grpcWebProxyStart = new Thread(() -> { ArthasGrpcServer arthasGrpcServer = new ArthasGrpcServer(PORT, UNIT_TEST_GRPC_SERVICE_PACKAGE_NAME); arthasGrpcServer.start(); }); grpcWebProxyStart.start(); clientChannel = ManagedChannelBuilder.forTarget(HOST_PORT) .usePlaintext() .build(); } @Test public void testUnary() { log.info("testUnary start!"); ArthasUnittestServiceGrpc.ArthasUnittestServiceBlockingStub stub = ArthasUnittestServiceGrpc.newBlockingStub(clientChannel); try { ArthasUnittest.ArthasUnittestRequest request = ArthasUnittest.ArthasUnittestRequest.newBuilder().setMessage("unaryInvoke").build(); ArthasUnittest.ArthasUnittestResponse res = stub.unary(request); System.out.println(res.getMessage()); } finally { clientChannel.shutdownNow(); } log.info("testUnary success!"); } @Test public void testUnarySum() throws InterruptedException { log.info("testUnarySum start!"); ArthasUnittestServiceGrpc.ArthasUnittestServiceBlockingStub stub = ArthasUnittestServiceGrpc.newBlockingStub(clientChannel); for (int i = 0; i < 10; i++) { AtomicInteger sum = new AtomicInteger(0); int finalId = i; for (int j = 0; j < 10; j++) { int num = random.nextInt(101); sum.addAndGet(num); threadPool.submit(() -> { addSum(stub, finalId, num); }); } Thread.sleep(2000L); int grpcSum = getSum(stub, finalId); System.out.println("id:" + finalId + ",sum:" + sum.get() + ",grpcSum:" + grpcSum); Assert.assertEquals(sum.get(), grpcSum); } clientChannel.shutdown(); log.info("testUnarySum success!"); } // 用于测试客户端流 @Test public void testClientStreamSum() throws Throwable { log.info("testClientStreamSum start!"); ArthasUnittestServiceGrpc.ArthasUnittestServiceStub stub = ArthasUnittestServiceGrpc.newStub(clientChannel); AtomicInteger sum = new AtomicInteger(0); CountDownLatch latch = new CountDownLatch(1); StreamObserver<ArthasUnittest.ArthasUnittestRequest> clientStreamObserver = stub.clientStreamSum(new StreamObserver<ArthasUnittest.ArthasUnittestResponse>() { @Override public void onNext(ArthasUnittest.ArthasUnittestResponse response) { System.out.println("local sum:" + sum + ", grpc sum:" + response.getNum()); Assert.assertEquals(sum.get(), response.getNum()); } @Override public void onError(Throwable t) { System.err.println("Error: " + t); } @Override public void onCompleted() { System.out.println("testClientStreamSum completed."); latch.countDown(); } }); for (int j = 0; j < 100; j++) { int num = random.nextInt(1001); sum.addAndGet(num); clientStreamObserver.onNext(ArthasUnittest.ArthasUnittestRequest.newBuilder().setNum(num).build()); } clientStreamObserver.onCompleted(); latch.await(20,TimeUnit.SECONDS); clientChannel.shutdown(); log.info("testClientStreamSum success!"); } // 用于测试请求数据隔离性 @Test public void testDataIsolation() throws InterruptedException { log.info("testDataIsolation start!"); ArthasUnittestServiceGrpc.ArthasUnittestServiceStub stub = ArthasUnittestServiceGrpc.newStub(clientChannel); for (int i = 0; i < 10; i++) { threadPool.submit(() -> { AtomicInteger sum = new AtomicInteger(0); CountDownLatch latch = new CountDownLatch(1); StreamObserver<ArthasUnittest.ArthasUnittestRequest> clientStreamObserver = stub.clientStreamSum(new StreamObserver<ArthasUnittest.ArthasUnittestResponse>() { @Override public void onNext(ArthasUnittest.ArthasUnittestResponse response) { System.out.println("local sum:" + sum + ", grpc sum:" + response.getNum()); Assert.assertEquals(sum.get(), response.getNum()); } @Override public void onError(Throwable t) { System.err.println("Error: " + t); } @Override public void onCompleted() { System.out.println("testDataIsolation completed."); latch.countDown(); } }); for (int j = 0; j < 5; j++) { int num = random.nextInt(101); try { Thread.sleep(1000L); } catch (InterruptedException e) { throw new RuntimeException(e); } sum.addAndGet(num); clientStreamObserver.onNext(ArthasUnittest.ArthasUnittestRequest.newBuilder().setNum(num).build()); } clientStreamObserver.onCompleted(); try { latch.await(20,TimeUnit.SECONDS); } catch (InterruptedException e) { throw new RuntimeException(e); } clientChannel.shutdown(); }); } Thread.sleep(10000L); log.info("testDataIsolation success!"); } @Test public void testServerStream() throws InterruptedException { log.info("testServerStream start!"); ArthasUnittestServiceGrpc.ArthasUnittestServiceStub stub = ArthasUnittestServiceGrpc.newStub(clientChannel); ArthasUnittest.ArthasUnittestRequest request = ArthasUnittest.ArthasUnittestRequest.newBuilder().setMessage("serverStream").build(); stub.serverStream(request, new StreamObserver<ArthasUnittest.ArthasUnittestResponse>() { @Override public void onNext(ArthasUnittest.ArthasUnittestResponse value) { System.out.println("testServerStream client receive: " + value.getMessage()); } @Override public void onError(Throwable t) { } @Override public void onCompleted() { System.out.println("testServerStream completed"); } }); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } finally { clientChannel.shutdown(); } log.info("testServerStream success!"); } // 用于测试双向流 @Test public void testBiStream() throws Throwable { log.info("testBiStream start!"); ArthasUnittestServiceGrpc.ArthasUnittestServiceStub stub = ArthasUnittestServiceGrpc.newStub(clientChannel); CountDownLatch latch = new CountDownLatch(1); StreamObserver<ArthasUnittest.ArthasUnittestRequest> biStreamObserver = stub.biStream(new StreamObserver<ArthasUnittest.ArthasUnittestResponse>() { @Override public void onNext(ArthasUnittest.ArthasUnittestResponse response) { System.out.println("testBiStream receive: "+response.getMessage()); } @Override public void onError(Throwable t) { System.err.println("Error: " + t); } @Override public void onCompleted() { System.out.println("testBiStream completed."); latch.countDown(); } }); String[] messages = new String[]{"testBiStream1","testBiStream2","testBiStream3"}; for (String msg : messages) { ArthasUnittest.ArthasUnittestRequest request = ArthasUnittest.ArthasUnittestRequest.newBuilder().setMessage(msg).build(); biStreamObserver.onNext(request); } Thread.sleep(2000); biStreamObserver.onCompleted(); latch.await(20, TimeUnit.SECONDS); clientChannel.shutdown(); log.info("testBiStream success!"); } private void addSum(ArthasUnittestServiceGrpc.ArthasUnittestServiceBlockingStub stub, int id, int num) { ArthasUnittest.ArthasUnittestRequest request = ArthasUnittest.ArthasUnittestRequest.newBuilder().setId(id).setNum(num).build(); ArthasUnittest.ArthasUnittestResponse res = stub.unaryAddSum(request); } private int getSum(ArthasUnittestServiceGrpc.ArthasUnittestServiceBlockingStub stub, int id) { ArthasUnittest.ArthasUnittestRequest request = ArthasUnittest.ArthasUnittestRequest.newBuilder().setId(id).build(); ArthasUnittest.ArthasUnittestResponse res = stub.unaryGetSum(request); return res.getNum(); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/labs/arthas-grpc-server/src/test/java/unittest/grpc/service/ArthasUnittestService.java
labs/arthas-grpc-server/src/test/java/unittest/grpc/service/ArthasUnittestService.java
package unittest.grpc.service; import arthas.grpc.unittest.ArthasUnittest.ArthasUnittestRequest; import arthas.grpc.unittest.ArthasUnittest.ArthasUnittestResponse; import com.taobao.arthas.grpc.server.handler.GrpcRequest; import com.taobao.arthas.grpc.server.handler.GrpcResponse; import com.taobao.arthas.grpc.server.handler.StreamObserver; /** * @author: FengYe * @date: 2024/6/30 下午11:42 * @description: ArthasSampleService */ public interface ArthasUnittestService { ArthasUnittestResponse unary(ArthasUnittestRequest command); ArthasUnittestResponse unaryAddSum(ArthasUnittestRequest command); ArthasUnittestResponse unaryGetSum(ArthasUnittestRequest command); StreamObserver<GrpcRequest<ArthasUnittestRequest>> clientStreamSum(StreamObserver<GrpcResponse<ArthasUnittestResponse>> observer); void serverStream(ArthasUnittestRequest request, StreamObserver<GrpcResponse<ArthasUnittestResponse>> observer); StreamObserver<GrpcRequest<ArthasUnittestRequest>> biStream(StreamObserver<GrpcResponse<ArthasUnittestResponse>> observer); }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/labs/arthas-grpc-server/src/test/java/unittest/grpc/service/impl/ArthasUnittestServiceImpl.java
labs/arthas-grpc-server/src/test/java/unittest/grpc/service/impl/ArthasUnittestServiceImpl.java
package unittest.grpc.service.impl; import arthas.grpc.unittest.ArthasUnittest; import arthas.grpc.unittest.ArthasUnittest.ArthasUnittestRequest; import arthas.grpc.unittest.ArthasUnittest.ArthasUnittestResponse; import com.google.protobuf.InvalidProtocolBufferException; import com.taobao.arthas.grpc.server.handler.GrpcRequest; import com.taobao.arthas.grpc.server.handler.GrpcResponse; import com.taobao.arthas.grpc.server.handler.StreamObserver; import com.taobao.arthas.grpc.server.handler.annotation.GrpcMethod; import com.taobao.arthas.grpc.server.handler.annotation.GrpcService; import com.taobao.arthas.grpc.server.handler.constant.GrpcInvokeTypeEnum; import unittest.grpc.service.ArthasUnittestService; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; /** * @author: FengYe * @date: 2024/6/30 下午11:43 * @description: ArthasSampleServiceImpl */ @GrpcService("arthas.grpc.unittest.ArthasUnittestService") public class ArthasUnittestServiceImpl implements ArthasUnittestService { private ConcurrentHashMap<Integer, Integer> map = new ConcurrentHashMap<>(); @Override @GrpcMethod(value = "unary") public ArthasUnittestResponse unary(ArthasUnittestRequest command) { ArthasUnittestResponse.Builder builder = ArthasUnittestResponse.newBuilder(); builder.setMessage(command.getMessage()); return builder.build(); } @Override @GrpcMethod(value = "unaryAddSum") public ArthasUnittestResponse unaryAddSum(ArthasUnittestRequest command) { ArthasUnittestResponse.Builder builder = ArthasUnittestResponse.newBuilder(); builder.setMessage(command.getMessage()); map.merge(command.getId(), command.getNum(), Integer::sum); return builder.build(); } @Override @GrpcMethod(value = "unaryGetSum") public ArthasUnittestResponse unaryGetSum(ArthasUnittestRequest command) { ArthasUnittestResponse.Builder builder = ArthasUnittestResponse.newBuilder(); builder.setMessage(command.getMessage()); Integer sum = map.getOrDefault(command.getId(), 0); builder.setNum(sum); return builder.build(); } @Override @GrpcMethod(value = "clientStreamSum", grpcType = GrpcInvokeTypeEnum.CLIENT_STREAM) public StreamObserver<GrpcRequest<ArthasUnittestRequest>> clientStreamSum(StreamObserver<GrpcResponse<ArthasUnittestResponse>> observer) { return new StreamObserver<GrpcRequest<ArthasUnittestRequest>>() { AtomicInteger sum = new AtomicInteger(0); @Override public void onNext(GrpcRequest<ArthasUnittestRequest> req) { try { byte[] bytes = req.readData(); while (bytes != null && bytes.length != 0) { ArthasUnittestRequest request = ArthasUnittestRequest.parseFrom(bytes); sum.addAndGet(request.getNum()); bytes = req.readData(); } } catch (InvalidProtocolBufferException e) { throw new RuntimeException(e); } } @Override public void onCompleted() { ArthasUnittestResponse response = ArthasUnittestResponse.newBuilder() .setNum(sum.get()) .build(); GrpcResponse<ArthasUnittestResponse> grpcResponse = new GrpcResponse<>(); grpcResponse.setService("arthas.grpc.unittest.ArthasUnittestService"); grpcResponse.setMethod("clientStreamSum"); grpcResponse.writeResponseData(response); observer.onNext(grpcResponse); observer.onCompleted(); } }; } @Override @GrpcMethod(value = "serverStream", grpcType = GrpcInvokeTypeEnum.SERVER_STREAM) public void serverStream(ArthasUnittestRequest request, StreamObserver<GrpcResponse<ArthasUnittestResponse>> observer) { for (int i = 0; i < 5; i++) { ArthasUnittest.ArthasUnittestResponse response = ArthasUnittest.ArthasUnittestResponse.newBuilder() .setMessage("Server response " + i + " to " + request.getMessage()) .build(); GrpcResponse<ArthasUnittestResponse> grpcResponse = new GrpcResponse<>(); grpcResponse.setService("arthas.grpc.unittest.ArthasUnittestService"); grpcResponse.setMethod("serverStream"); grpcResponse.writeResponseData(response); observer.onNext(grpcResponse); } observer.onCompleted(); } @Override @GrpcMethod(value = "biStream", grpcType = GrpcInvokeTypeEnum.BI_STREAM) public StreamObserver<GrpcRequest<ArthasUnittestRequest>> biStream(StreamObserver<GrpcResponse<ArthasUnittestResponse>> observer) { return new StreamObserver<GrpcRequest<ArthasUnittestRequest>>() { @Override public void onNext(GrpcRequest<ArthasUnittestRequest> req) { try { byte[] bytes = req.readData(); while (bytes != null && bytes.length != 0) { GrpcResponse<ArthasUnittestResponse> grpcResponse = new GrpcResponse<>(); grpcResponse.setService("arthas.grpc.unittest.ArthasUnittestService"); grpcResponse.setMethod("biStream"); grpcResponse.writeResponseData(ArthasUnittestResponse.parseFrom(bytes)); observer.onNext(grpcResponse); bytes = req.readData(); } } catch (InvalidProtocolBufferException e) { throw new RuntimeException(e); } } @Override public void onCompleted() { observer.onCompleted(); } }; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/labs/arthas-grpc-server/src/main/java/com/taobao/arthas/grpc/server/ArthasGrpcServer.java
labs/arthas-grpc-server/src/main/java/com/taobao/arthas/grpc/server/ArthasGrpcServer.java
package com.taobao.arthas.grpc.server; import com.alibaba.arthas.deps.ch.qos.logback.classic.Level; import com.alibaba.arthas.deps.ch.qos.logback.classic.LoggerContext; import com.alibaba.arthas.deps.org.slf4j.Logger; import com.alibaba.arthas.deps.org.slf4j.LoggerFactory; import com.taobao.arthas.grpc.server.handler.GrpcDispatcher; import com.taobao.arthas.grpc.server.handler.Http2Handler; import com.taobao.arthas.grpc.server.handler.executor.GrpcExecutorFactory; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.http2.Http2FrameCodecBuilder; import io.netty.util.concurrent.DefaultEventExecutorGroup; import io.netty.util.concurrent.EventExecutorGroup; import java.lang.invoke.MethodHandles; /** * @author: FengYe * @date: 2024/7/3 上午12:30 * @description: ArthasGrpcServer */ public class ArthasGrpcServer { private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass().getName()); private int port = 9091; private String grpcServicePackageName; public ArthasGrpcServer(int port, String grpcServicePackageName) { this.port = port; this.grpcServicePackageName = grpcServicePackageName; } public void start() { EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(10); GrpcDispatcher grpcDispatcher = new GrpcDispatcher(); grpcDispatcher.loadGrpcService(grpcServicePackageName); GrpcExecutorFactory grpcExecutorFactory = new GrpcExecutorFactory(); grpcExecutorFactory.loadExecutor(grpcDispatcher); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 1024) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) { ch.pipeline().addLast(Http2FrameCodecBuilder.forServer().build()); ch.pipeline().addLast(new Http2Handler(grpcDispatcher, grpcExecutorFactory)); } }); Channel channel = b.bind(port).sync().channel(); logger.info("ArthasGrpcServer start successfully on port: {}", port); channel.closeFuture().sync(); } catch (InterruptedException e) { logger.error("ArthasGrpcServer start error", e); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/labs/arthas-grpc-server/src/main/java/com/taobao/arthas/grpc/server/ArthasGrpcBootstrap.java
labs/arthas-grpc-server/src/main/java/com/taobao/arthas/grpc/server/ArthasGrpcBootstrap.java
package com.taobao.arthas.grpc.server; /** * @author: FengYe * @date: 2024/10/13 02:40 * @description: ArthasGrpcServerBootstrap */ public class ArthasGrpcBootstrap { public static void main(String[] args) { ArthasGrpcServer arthasGrpcServer = new ArthasGrpcServer(9091, null); arthasGrpcServer.start(); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/labs/arthas-grpc-server/src/main/java/com/taobao/arthas/grpc/server/service/ArthasSampleService.java
labs/arthas-grpc-server/src/main/java/com/taobao/arthas/grpc/server/service/ArthasSampleService.java
package com.taobao.arthas.grpc.server.service; import arthas.grpc.unittest.ArthasUnittest; import com.taobao.arthas.grpc.server.handler.GrpcRequest; import com.taobao.arthas.grpc.server.handler.GrpcResponse; import com.taobao.arthas.grpc.server.handler.StreamObserver; /** * @author: FengYe * @date: 2024/6/30 下午11:42 * @description: ArthasSampleService */ public interface ArthasSampleService { ArthasUnittest.ArthasUnittestResponse unary(ArthasUnittest.ArthasUnittestRequest command); ArthasUnittest.ArthasUnittestResponse unaryAddSum(ArthasUnittest.ArthasUnittestRequest command); ArthasUnittest.ArthasUnittestResponse unaryGetSum(ArthasUnittest.ArthasUnittestRequest command); StreamObserver<GrpcRequest<ArthasUnittest.ArthasUnittestRequest>> clientStreamSum(StreamObserver<GrpcResponse<ArthasUnittest.ArthasUnittestResponse>> observer); void serverStream(ArthasUnittest.ArthasUnittestRequest request, StreamObserver<GrpcResponse<ArthasUnittest.ArthasUnittestResponse>> observer); StreamObserver<GrpcRequest<ArthasUnittest.ArthasUnittestRequest>> biStream(StreamObserver<GrpcResponse<ArthasUnittest.ArthasUnittestResponse>> observer); }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/labs/arthas-grpc-server/src/main/java/com/taobao/arthas/grpc/server/service/impl/ArthasSampleServiceImpl.java
labs/arthas-grpc-server/src/main/java/com/taobao/arthas/grpc/server/service/impl/ArthasSampleServiceImpl.java
package com.taobao.arthas.grpc.server.service.impl; import arthas.grpc.unittest.ArthasUnittest; import com.google.protobuf.InvalidProtocolBufferException; import com.taobao.arthas.grpc.server.handler.GrpcRequest; import com.taobao.arthas.grpc.server.handler.GrpcResponse; import com.taobao.arthas.grpc.server.handler.StreamObserver; import com.taobao.arthas.grpc.server.handler.annotation.GrpcMethod; import com.taobao.arthas.grpc.server.handler.annotation.GrpcService; import com.taobao.arthas.grpc.server.handler.constant.GrpcInvokeTypeEnum; import com.taobao.arthas.grpc.server.service.ArthasSampleService; import com.taobao.arthas.grpc.server.utils.ByteUtil; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; /** * @author: FengYe * @date: 2024/6/30 下午11:43 * @description: ArthasSampleServiceImpl */ @GrpcService("arthas.grpc.unittest.ArthasUnittestService") public class ArthasSampleServiceImpl implements ArthasSampleService { private ConcurrentHashMap<Integer, Integer> map = new ConcurrentHashMap<>(); @Override @GrpcMethod(value = "unary") public ArthasUnittest.ArthasUnittestResponse unary(ArthasUnittest.ArthasUnittestRequest command) { ArthasUnittest.ArthasUnittestResponse.Builder builder = ArthasUnittest.ArthasUnittestResponse.newBuilder(); builder.setMessage(command.getMessage()); return builder.build(); } @Override @GrpcMethod(value = "unaryAddSum") public ArthasUnittest.ArthasUnittestResponse unaryAddSum(ArthasUnittest.ArthasUnittestRequest command) { ArthasUnittest.ArthasUnittestResponse.Builder builder = ArthasUnittest.ArthasUnittestResponse.newBuilder(); builder.setMessage(command.getMessage()); map.merge(command.getId(), command.getNum(), Integer::sum); return builder.build(); } @Override @GrpcMethod(value = "unaryGetSum") public ArthasUnittest.ArthasUnittestResponse unaryGetSum(ArthasUnittest.ArthasUnittestRequest command) { ArthasUnittest.ArthasUnittestResponse.Builder builder = ArthasUnittest.ArthasUnittestResponse.newBuilder(); builder.setMessage(command.getMessage()); Integer sum = map.getOrDefault(command.getId(), 0); builder.setNum(sum); return builder.build(); } @Override @GrpcMethod(value = "clientStreamSum", grpcType = GrpcInvokeTypeEnum.CLIENT_STREAM) public StreamObserver<GrpcRequest<ArthasUnittest.ArthasUnittestRequest>> clientStreamSum(StreamObserver<GrpcResponse<ArthasUnittest.ArthasUnittestResponse>> observer) { return new StreamObserver<GrpcRequest<ArthasUnittest.ArthasUnittestRequest>>() { AtomicInteger sum = new AtomicInteger(0); @Override public void onNext(GrpcRequest<ArthasUnittest.ArthasUnittestRequest> req) { try { byte[] bytes = req.readData(); while (bytes != null && bytes.length != 0) { ArthasUnittest.ArthasUnittestRequest request = ArthasUnittest.ArthasUnittestRequest.parseFrom(bytes); sum.addAndGet(request.getNum()); bytes = req.readData(); } } catch (InvalidProtocolBufferException e) { throw new RuntimeException(e); } } @Override public void onCompleted() { ArthasUnittest.ArthasUnittestResponse response = ArthasUnittest.ArthasUnittestResponse.newBuilder() .setNum(sum.get()) .build(); GrpcResponse<ArthasUnittest.ArthasUnittestResponse> grpcResponse = new GrpcResponse<>(); grpcResponse.setService("arthas.grpc.unittest.ArthasUnittestService"); grpcResponse.setMethod("clientStreamSum"); grpcResponse.writeResponseData(response); observer.onNext(grpcResponse); observer.onCompleted(); } }; } @Override @GrpcMethod(value = "serverStream", grpcType = GrpcInvokeTypeEnum.SERVER_STREAM) public void serverStream(ArthasUnittest.ArthasUnittestRequest request, StreamObserver<GrpcResponse<ArthasUnittest.ArthasUnittestResponse>> observer) { for (int i = 0; i < 5; i++) { ArthasUnittest.ArthasUnittestResponse response = ArthasUnittest.ArthasUnittestResponse.newBuilder() .setMessage("Server response " + i + " to " + request.getMessage()) .build(); GrpcResponse<ArthasUnittest.ArthasUnittestResponse> grpcResponse = new GrpcResponse<>(); grpcResponse.setService("arthas.grpc.unittest.ArthasUnittestService"); grpcResponse.setMethod("serverStream"); grpcResponse.writeResponseData(response); observer.onNext(grpcResponse); } observer.onCompleted(); } @Override @GrpcMethod(value = "biStream", grpcType = GrpcInvokeTypeEnum.BI_STREAM) public StreamObserver<GrpcRequest<ArthasUnittest.ArthasUnittestRequest>> biStream(StreamObserver<GrpcResponse<ArthasUnittest.ArthasUnittestResponse>> observer) { return new StreamObserver<GrpcRequest<ArthasUnittest.ArthasUnittestRequest>>() { @Override public void onNext(GrpcRequest<ArthasUnittest.ArthasUnittestRequest> req) { try { byte[] bytes = req.readData(); while (bytes != null && bytes.length != 0) { GrpcResponse<ArthasUnittest.ArthasUnittestResponse> grpcResponse = new GrpcResponse<>(); grpcResponse.setService("arthas.grpc.unittest.ArthasUnittestService"); grpcResponse.setMethod("biStream"); grpcResponse.writeResponseData(ArthasUnittest.ArthasUnittestResponse.parseFrom(bytes)); observer.onNext(grpcResponse); bytes = req.readData(); } } catch (InvalidProtocolBufferException e) { throw new RuntimeException(e); } } @Override public void onCompleted() { observer.onCompleted(); } }; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/labs/arthas-grpc-server/src/main/java/com/taobao/arthas/grpc/server/utils/ByteUtil.java
labs/arthas-grpc-server/src/main/java/com/taobao/arthas/grpc/server/utils/ByteUtil.java
package com.taobao.arthas.grpc.server.utils; import io.netty.buffer.ByteBuf; import io.netty.buffer.PooledByteBufAllocator; /** * @author: FengYe * @date: 2024/9/5 00:51 * @description: ByteUtil */ public class ByteUtil { public static ByteBuf newByteBuf() { return PooledByteBufAllocator.DEFAULT.buffer(); } public static ByteBuf newByteBuf(byte[] bytes) { return PooledByteBufAllocator.DEFAULT.buffer(bytes.length).writeBytes(bytes); } public static byte[] getBytes(ByteBuf buf) { if (buf.hasArray()) { // 如果 ByteBuf 是一个支持底层数组的实现,直接获取数组 return buf.array(); } else { // 创建一个新的 byte 数组 byte[] bytes = new byte[buf.readableBytes()]; // 将 ByteBuf 的内容复制到 byte 数组中 buf.getBytes(buf.readerIndex(), bytes); return bytes; } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/labs/arthas-grpc-server/src/main/java/com/taobao/arthas/grpc/server/utils/ReflectUtil.java
labs/arthas-grpc-server/src/main/java/com/taobao/arthas/grpc/server/utils/ReflectUtil.java
package com.taobao.arthas.grpc.server.utils; import java.io.File; import java.net.URL; import java.util.ArrayList; import java.util.List; /** * @author: FengYe * @date: 2024/9/6 02:20 * @description: ReflectUtil */ public class ReflectUtil { public static List<Class<?>> findClasses(String packageName) { List<Class<?>> classes = new ArrayList<>(); String path = packageName.replace('.', '/'); try { URL resource = Thread.currentThread().getContextClassLoader().getResource(path); if (resource != null) { File directory = new File(resource.toURI()); if (directory.exists()) { for (File file : directory.listFiles()) { if (file.isFile() && file.getName().endsWith(".class")) { String className = packageName + '.' + file.getName().replace(".class", ""); classes.add(Class.forName(className)); } } } } } catch (Exception e) { } return classes; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/labs/arthas-grpc-server/src/main/java/com/taobao/arthas/grpc/server/handler/StreamObserver.java
labs/arthas-grpc-server/src/main/java/com/taobao/arthas/grpc/server/handler/StreamObserver.java
package com.taobao.arthas.grpc.server.handler; /** * @author: FengYe * @date: 2024/10/24 00:22 * @description: StreamObserver */ public interface StreamObserver<V> { void onNext(V req); void onCompleted(); }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/labs/arthas-grpc-server/src/main/java/com/taobao/arthas/grpc/server/handler/GrpcResponse.java
labs/arthas-grpc-server/src/main/java/com/taobao/arthas/grpc/server/handler/GrpcResponse.java
package com.taobao.arthas.grpc.server.handler; import arthas.grpc.common.ArthasGrpc; import com.taobao.arthas.grpc.server.handler.annotation.GrpcMethod; import com.taobao.arthas.grpc.server.handler.annotation.GrpcService; import com.taobao.arthas.grpc.server.utils.ByteUtil; import io.netty.buffer.ByteBuf; import io.netty.handler.codec.http2.DefaultHttp2Headers; import io.netty.handler.codec.http2.Http2Headers; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; /** * @author: FengYe * @date: 2024/9/5 02:05 * @description: GrpcResponse */ public class GrpcResponse<T> { private Map<String, String> headers; /** * 请求的 service */ private String service; /** * 请求的 method */ private String method; /** * 二进制数据 */ private ByteBuf byteData; /** * 响应class */ private Class<?> clazz; { headers = new HashMap<>(); headers.put("content-type", "application/grpc"); headers.put("grpc-encoding", "identity"); headers.put("grpc-accept-encoding", "identity,deflate,gzip"); } public GrpcResponse() { } public GrpcResponse(Method method) { this.service = method.getDeclaringClass().getAnnotation(GrpcService.class).value(); this.method = method.getAnnotation(GrpcMethod.class).value(); } public Http2Headers getEndHeader() { Http2Headers endHeader = new DefaultHttp2Headers().status("200"); headers.forEach(endHeader::set); return endHeader; } public Http2Headers getEndStreamHeader() { return new DefaultHttp2Headers().set("grpc-status", "0"); } public static Http2Headers getDefaultEndStreamHeader() { return new DefaultHttp2Headers().set("grpc-status", "0"); } public ByteBuf getResponseData() { return byteData; } public void writeResponseData(Object response) { byte[] encode = null; try { if (ArthasGrpc.ErrorRes.class.equals(clazz)) { encode = ((ArthasGrpc.ErrorRes) response).toByteArray(); } else { encode = (byte[]) GrpcDispatcher.responseToByteArrayMap.get(GrpcDispatcher.generateGrpcMethodKey(service, method)).invoke(response); } } catch (Throwable e) { throw new RuntimeException(e); } this.byteData = ByteUtil.newByteBuf(); this.byteData.writeBoolean(false); this.byteData.writeInt(encode.length); this.byteData.writeBytes(encode); } public void setClazz(Class<?> clazz) { this.clazz = clazz; } public String getService() { return service; } public void setService(String service) { this.service = service; } public String getMethod() { return method; } public void setMethod(String method) { this.method = method; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/labs/arthas-grpc-server/src/main/java/com/taobao/arthas/grpc/server/handler/Http2FrameRequest.java
labs/arthas-grpc-server/src/main/java/com/taobao/arthas/grpc/server/handler/Http2FrameRequest.java
package com.taobao.arthas.grpc.server.handler; import java.util.List; /** * @author: FengYe * @date: 2024/9/18 23:12 * @description: 一个 http2 的 frame 中可能存在多个 grpc 的请求体 */ public class Http2FrameRequest { /** * grpc 请求体 */ private List<GrpcRequest> grpcRequests; }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/labs/arthas-grpc-server/src/main/java/com/taobao/arthas/grpc/server/handler/GrpcDispatcher.java
labs/arthas-grpc-server/src/main/java/com/taobao/arthas/grpc/server/handler/GrpcDispatcher.java
package com.taobao.arthas.grpc.server.handler; import com.alibaba.arthas.deps.org.slf4j.Logger; import com.alibaba.arthas.deps.org.slf4j.LoggerFactory; import com.taobao.arthas.grpc.server.handler.annotation.GrpcMethod; import com.taobao.arthas.grpc.server.handler.annotation.GrpcService; import com.taobao.arthas.grpc.server.handler.constant.GrpcInvokeTypeEnum; import com.taobao.arthas.grpc.server.utils.ReflectUtil; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodType; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; /** * @author: FengYe * @date: 2024/9/6 01:12 * @description: GrpcDelegrate */ public class GrpcDispatcher { private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass().getName()); public static final String DEFAULT_GRPC_SERVICE_PACKAGE_NAME = "com.taobao.arthas.grpc.server.service.impl"; public static Map<String, MethodHandle> grpcInvokeMap = new HashMap<>(); // public static Map<String, StreamObserver> clientStreamInvokeMap = new HashMap<>(); public static Map<String, MethodHandle> requestParseFromMap = new HashMap<>(); public static Map<String, MethodHandle> requestToByteArrayMap = new HashMap<>(); public static Map<String, MethodHandle> responseParseFromMap = new HashMap<>(); public static Map<String, MethodHandle> responseToByteArrayMap = new HashMap<>(); public static Map<String, GrpcInvokeTypeEnum> grpcInvokeTypeMap = new HashMap<>(); public void loadGrpcService(String grpcServicePackageName) { List<Class<?>> classes = ReflectUtil.findClasses(Optional.ofNullable(grpcServicePackageName).orElse(DEFAULT_GRPC_SERVICE_PACKAGE_NAME)); for (Class<?> clazz : classes) { if (clazz.isAnnotationPresent(GrpcService.class)) { try { // 处理 service GrpcService grpcService = clazz.getAnnotation(GrpcService.class); Object instance = clazz.getDeclaredConstructor().newInstance(); // 处理 method MethodHandles.Lookup lookup = MethodHandles.lookup(); Method[] declaredMethods = clazz.getDeclaredMethods(); for (Method method : declaredMethods) { if (method.isAnnotationPresent(GrpcMethod.class)) { GrpcMethod grpcMethod = method.getAnnotation(GrpcMethod.class); MethodHandle grpcInvoke = lookup.unreflect(method); String grpcMethodKey = generateGrpcMethodKey(grpcService.value(), grpcMethod.value()); grpcInvokeTypeMap.put(grpcMethodKey, grpcMethod.grpcType()); grpcInvokeMap.put(grpcMethodKey, grpcInvoke.bindTo(instance)); Class<?> requestClass = null; Class<?> responseClass = null; if (GrpcInvokeTypeEnum.UNARY.equals(grpcMethod.grpcType())) { requestClass = grpcInvoke.type().parameterType(1); responseClass = grpcInvoke.type().returnType(); } else if (GrpcInvokeTypeEnum.CLIENT_STREAM.equals(grpcMethod.grpcType()) || GrpcInvokeTypeEnum.BI_STREAM.equals(grpcMethod.grpcType())) { responseClass = getInnerGenericClass(method.getGenericParameterTypes()[0]); requestClass = getInnerGenericClass(method.getGenericReturnType()); } else if (GrpcInvokeTypeEnum.SERVER_STREAM.equals(grpcMethod.grpcType())) { requestClass = getInnerGenericClass(method.getGenericParameterTypes()[0]); responseClass = getInnerGenericClass(method.getGenericParameterTypes()[1]); } MethodHandle requestParseFrom = lookup.findStatic(requestClass, "parseFrom", MethodType.methodType(requestClass, byte[].class)); MethodHandle responseParseFrom = lookup.findStatic(responseClass, "parseFrom", MethodType.methodType(responseClass, byte[].class)); MethodHandle requestToByteArray = lookup.findVirtual(requestClass, "toByteArray", MethodType.methodType(byte[].class)); MethodHandle responseToByteArray = lookup.findVirtual(responseClass, "toByteArray", MethodType.methodType(byte[].class)); requestParseFromMap.put(grpcMethodKey, requestParseFrom); responseParseFromMap.put(grpcMethodKey, responseParseFrom); requestToByteArrayMap.put(grpcMethodKey, requestToByteArray); responseToByteArrayMap.put(grpcMethodKey, responseToByteArray); // switch (grpcMethod.grpcType()) { // case UNARY: // unaryInvokeMap.put(grpcMethodKey, grpcInvoke.bindTo(instance)); // return; // case CLIENT_STREAM: // Object invoke = grpcInvoke.bindTo(instance).invoke(); // if (!(invoke instanceof StreamObserver)) { // throw new RuntimeException(grpcMethodKey + " return class is not StreamObserver!"); // } // clientStreamInvokeMap.put(grpcMethodKey, (StreamObserver) invoke); // return; // case SERVER_STREAM: // return; // case BI_STREAM: // return; // } } } } catch (Throwable e) { logger.error("GrpcDispatcher loadGrpcService error.", e); } } } } public GrpcResponse doUnaryExecute(String service, String method, byte[] arg) throws Throwable { MethodHandle methodHandle = grpcInvokeMap.get(generateGrpcMethodKey(service, method)); MethodType type = grpcInvokeMap.get(generateGrpcMethodKey(service, method)).type(); Object req = requestParseFromMap.get(generateGrpcMethodKey(service, method)).invoke(arg); Object execute = methodHandle.invoke(req); GrpcResponse grpcResponse = new GrpcResponse(); grpcResponse.setClazz(type.returnType()); grpcResponse.setService(service); grpcResponse.setMethod(method); grpcResponse.writeResponseData(execute); return grpcResponse; } public GrpcResponse unaryExecute(GrpcRequest request) throws Throwable { MethodHandle methodHandle = grpcInvokeMap.get(request.getGrpcMethodKey()); MethodType type = grpcInvokeMap.get(request.getGrpcMethodKey()).type(); Object req = requestParseFromMap.get(request.getGrpcMethodKey()).invoke(request.readData()); Object execute = methodHandle.invoke(req); GrpcResponse grpcResponse = new GrpcResponse(); grpcResponse.setClazz(type.returnType()); grpcResponse.setService(request.getService()); grpcResponse.setMethod(request.getMethod()); grpcResponse.writeResponseData(execute); return grpcResponse; } public StreamObserver<GrpcRequest> clientStreamExecute(GrpcRequest request, StreamObserver<GrpcResponse> responseObserver) throws Throwable { MethodHandle methodHandle = grpcInvokeMap.get(request.getGrpcMethodKey()); return (StreamObserver<GrpcRequest>) methodHandle.invoke(responseObserver); } public void serverStreamExecute(GrpcRequest request, StreamObserver<GrpcResponse> responseObserver) throws Throwable { MethodHandle methodHandle = grpcInvokeMap.get(request.getGrpcMethodKey()); Object req = requestParseFromMap.get(request.getGrpcMethodKey()).invoke(request.readData()); methodHandle.invoke(req, responseObserver); } public StreamObserver<GrpcRequest> biStreamExecute(GrpcRequest request, StreamObserver<GrpcResponse> responseObserver) throws Throwable { MethodHandle methodHandle = grpcInvokeMap.get(request.getGrpcMethodKey()); return (StreamObserver<GrpcRequest>) methodHandle.invoke(responseObserver); } /** * 获取指定 service method 对应的入参类型 * * @param serviceName * @param methodName * @return */ public static Class<?> getRequestClass(String serviceName, String methodName) { //protobuf 规范只能有单入参 return Optional.ofNullable(grpcInvokeMap.get(generateGrpcMethodKey(serviceName, methodName))).orElseThrow(() -> new RuntimeException("The specified grpc method does not exist")).type().parameterArray()[0]; } public static String generateGrpcMethodKey(String serviceName, String methodName) { return serviceName + "." + methodName; } public static void checkGrpcType(GrpcRequest request) { request.setGrpcType( Optional.ofNullable(grpcInvokeTypeMap.get(generateGrpcMethodKey(request.getService(), request.getMethod()))) .orElse(GrpcInvokeTypeEnum.UNARY) ); request.setStreamFirstData(true); } public static Class<?> getInnerGenericClass(Type type) { if (type instanceof Class<?>) { return (Class<?>) type; } if (type instanceof ParameterizedType) { ParameterizedType paramType = (ParameterizedType) type; Type[] actualTypeArguments = paramType.getActualTypeArguments(); if (actualTypeArguments.length > 0) { Type innerType = actualTypeArguments[0]; // 获取第一个实际类型参数 if (innerType instanceof ParameterizedType) { return getInnerGenericClass(innerType); // 递归调用获取最内层类型 } else if (innerType instanceof Class) { return (Class<?>) innerType; // 直接返回 Class 类型 } } } return null; // 如果没有找到对应的类型 } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/labs/arthas-grpc-server/src/main/java/com/taobao/arthas/grpc/server/handler/GrpcRequest.java
labs/arthas-grpc-server/src/main/java/com/taobao/arthas/grpc/server/handler/GrpcRequest.java
package com.taobao.arthas.grpc.server.handler; import com.taobao.arthas.grpc.server.handler.constant.GrpcInvokeTypeEnum; import com.taobao.arthas.grpc.server.utils.ByteUtil; import io.netty.buffer.ByteBuf; import io.netty.handler.codec.http2.Http2Headers; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.zip.GZIPInputStream; /** * @author: FengYe * @date: 2024/9/4 23:07 * @description: GrpcRequest grpc 请求体 */ public class GrpcRequest<T> { /** * 请求对应的 streamId */ private Integer streamId; /** * 请求的 service */ private String service; /** * 请求的 method */ private String method; /** * 二进制数据,可能包含多个 grpc body,每个 body 都带有 5 个 byte 的前缀,分别是 boolean compressed - int length */ private ByteBuf byteData; /** * 二进制数据的长度 */ private int length; /** * 请求class */ private Class<?> clazz; /** * 是否是 grpc 流式请求 */ private boolean stream; /** * 是否是 grpc 流式请求的第一个data */ private boolean streamFirstData; /** * http2 headers */ private Http2Headers headers; /** * grpc 调用类型 */ private GrpcInvokeTypeEnum grpcType; public GrpcRequest(Integer streamId, String path, String method) { this.streamId = streamId; this.service = path; this.method = method; this.byteData = ByteUtil.newByteBuf(); } public void writeData(ByteBuf byteBuf) { byte[] bytes = ByteUtil.getBytes(byteBuf); if (bytes.length == 0) { return; } byte[] decompressedData = decompressGzip(bytes); if (decompressedData == null) { return; } byteData.writeBytes(ByteUtil.newByteBuf(decompressedData)); } /** * 读取部分数据 * * @return */ public synchronized byte[] readData() { if (byteData.readableBytes() == 0) { return null; } boolean compressed = byteData.readBoolean(); int length = byteData.readInt(); byte[] bytes = new byte[length]; byteData.readBytes(bytes); return bytes; } public void clearData() { byteData.clear(); } private byte[] decompressGzip(byte[] compressedData) { boolean isGzip = (compressedData.length > 2 && (compressedData[0] & 0xff) == 0x1f && (compressedData[1] & 0xff) == 0x8b); if (isGzip) { try (InputStream byteStream = new ByteArrayInputStream(compressedData); GZIPInputStream gzipStream = new GZIPInputStream(byteStream); ByteArrayOutputStream out = new ByteArrayOutputStream()) { byte[] buffer = new byte[1024]; int len; while ((len = gzipStream.read(buffer)) != -1) { out.write(buffer, 0, len); } return out.toByteArray(); } catch (IOException e) { System.err.println("Failed to decompress GZIP data: " + e.getMessage()); // Optionally rethrow the exception or return an Optional<byte[]> return null; // or throw new RuntimeException(e); } } else { return compressedData; } } public String getGrpcMethodKey() { return service + "." + method; } public Integer getStreamId() { return streamId; } public String getService() { return service; } public String getMethod() { return method; } public ByteBuf getByteData() { return byteData; } public Class<?> getClazz() { return clazz; } public void setClazz(Class<?> clazz) { this.clazz = clazz; } public boolean isStream() { return stream; } public void setStream(boolean stream) { this.stream = stream; } public boolean isStreamFirstData() { return streamFirstData; } public void setStreamFirstData(boolean streamFirstData) { this.streamFirstData = streamFirstData; } public Http2Headers getHeaders() { return headers; } public void setHeaders(Http2Headers headers) { this.headers = headers; } public GrpcInvokeTypeEnum getGrpcType() { return grpcType; } public void setGrpcType(GrpcInvokeTypeEnum grpcType) { this.grpcType = grpcType; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/labs/arthas-grpc-server/src/main/java/com/taobao/arthas/grpc/server/handler/Http2Handler.java
labs/arthas-grpc-server/src/main/java/com/taobao/arthas/grpc/server/handler/Http2Handler.java
package com.taobao.arthas.grpc.server.handler; import arthas.grpc.common.ArthasGrpc; import com.alibaba.arthas.deps.org.slf4j.Logger; import com.alibaba.arthas.deps.org.slf4j.LoggerFactory; import com.taobao.arthas.grpc.server.handler.executor.GrpcExecutorFactory; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.handler.codec.http2.*; import io.netty.util.concurrent.EventExecutorGroup; import java.io.*; import java.lang.invoke.MethodHandles; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; /** * @author: FengYe * @date: 2024/7/7 下午9:58 * @description: Http2Handler */ public class Http2Handler extends SimpleChannelInboundHandler<Http2Frame> { private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass().getName()); private GrpcDispatcher grpcDispatcher; private GrpcExecutorFactory grpcExecutorFactory; private final EventExecutorGroup executorGroup = new NioEventLoopGroup(); /** * 暂存收到的所有请求的数据 */ private ConcurrentHashMap<Integer, GrpcRequest> dataBuffer = new ConcurrentHashMap<>(); private static final String HEADER_PATH = ":path"; public Http2Handler(GrpcDispatcher grpcDispatcher, GrpcExecutorFactory grpcExecutorFactory) { this.grpcDispatcher = grpcDispatcher; this.grpcExecutorFactory = grpcExecutorFactory; } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { super.channelRead(ctx, msg); } @Override protected void channelRead0(ChannelHandlerContext ctx, Http2Frame frame) throws IOException { if (frame instanceof Http2HeadersFrame) { handleGrpcRequest((Http2HeadersFrame) frame, ctx); } else if (frame instanceof Http2DataFrame) { handleGrpcData((Http2DataFrame) frame, ctx); } else if (frame instanceof Http2ResetFrame) { handleResetStream((Http2ResetFrame) frame, ctx); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { cause.printStackTrace(); ctx.close(); } private void handleGrpcRequest(Http2HeadersFrame headersFrame, ChannelHandlerContext ctx) { int id = headersFrame.stream().id(); String path = headersFrame.headers().get(HEADER_PATH).toString(); // 去掉前面的斜杠,然后按斜杠分割 String[] parts = path.substring(1).split("/"); GrpcRequest grpcRequest = new GrpcRequest(headersFrame.stream().id(), parts[0], parts[1]); grpcRequest.setHeaders(headersFrame.headers()); GrpcDispatcher.checkGrpcType(grpcRequest); dataBuffer.put(id, grpcRequest); System.out.println("Received headers: " + headersFrame.headers()); } private void handleGrpcData(Http2DataFrame dataFrame, ChannelHandlerContext ctx) throws IOException { int streamId = dataFrame.stream().id(); GrpcRequest grpcRequest = dataBuffer.get(streamId); ByteBuf content = dataFrame.content(); grpcRequest.writeData(content); executorGroup.execute(() -> { try { grpcExecutorFactory.getExecutor(grpcRequest.getGrpcType()).execute(grpcRequest, dataFrame, ctx); } catch (Throwable e) { logger.error("handleGrpcData error", e); processError(ctx, e, dataFrame.stream()); } }); } private void handleResetStream(Http2ResetFrame resetFrame, ChannelHandlerContext ctx) { int id = resetFrame.stream().id(); System.out.println("handleResetStream"); dataBuffer.remove(id); } private void processError(ChannelHandlerContext ctx, Throwable e, Http2FrameStream stream) { GrpcResponse response = new GrpcResponse(); ArthasGrpc.ErrorRes.Builder builder = ArthasGrpc.ErrorRes.newBuilder(); ArthasGrpc.ErrorRes errorRes = builder.setErrorMsg(Optional.ofNullable(e.getMessage()).orElse("")).build(); response.setClazz(ArthasGrpc.ErrorRes.class); response.writeResponseData(errorRes); ctx.writeAndFlush(new DefaultHttp2HeadersFrame(response.getEndHeader()).stream(stream)); ctx.writeAndFlush(new DefaultHttp2DataFrame(response.getResponseData()).stream(stream)); ctx.writeAndFlush(new DefaultHttp2HeadersFrame(response.getEndStreamHeader(), true).stream(stream)); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/labs/arthas-grpc-server/src/main/java/com/taobao/arthas/grpc/server/handler/constant/GrpcInvokeTypeEnum.java
labs/arthas-grpc-server/src/main/java/com/taobao/arthas/grpc/server/handler/constant/GrpcInvokeTypeEnum.java
package com.taobao.arthas.grpc.server.handler.constant; /** * @author: FengYe * @date: 2024/10/24 01:06 * @description: StreamTypeEnum */ public enum GrpcInvokeTypeEnum { UNARY, SERVER_STREAM, CLIENT_STREAM, BI_STREAM; }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/labs/arthas-grpc-server/src/main/java/com/taobao/arthas/grpc/server/handler/annotation/GrpcMethod.java
labs/arthas-grpc-server/src/main/java/com/taobao/arthas/grpc/server/handler/annotation/GrpcMethod.java
package com.taobao.arthas.grpc.server.handler.annotation; import com.taobao.arthas.grpc.server.handler.constant.GrpcInvokeTypeEnum; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @author: FengYe * @date: 2024/9/6 01:57 * @description: GrpcMethod */ @Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) public @interface GrpcMethod { String value() default ""; boolean stream() default false; GrpcInvokeTypeEnum grpcType() default GrpcInvokeTypeEnum.UNARY; }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/labs/arthas-grpc-server/src/main/java/com/taobao/arthas/grpc/server/handler/annotation/GrpcService.java
labs/arthas-grpc-server/src/main/java/com/taobao/arthas/grpc/server/handler/annotation/GrpcService.java
package com.taobao.arthas.grpc.server.handler.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @author: FengYe * @date: 2024/9/6 01:57 * @description: GrpcService */ @Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface GrpcService { String value() default ""; }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/labs/arthas-grpc-server/src/main/java/com/taobao/arthas/grpc/server/handler/executor/ClientStreamExecutor.java
labs/arthas-grpc-server/src/main/java/com/taobao/arthas/grpc/server/handler/executor/ClientStreamExecutor.java
package com.taobao.arthas.grpc.server.handler.executor; import com.taobao.arthas.grpc.server.handler.GrpcDispatcher; import com.taobao.arthas.grpc.server.handler.GrpcRequest; import com.taobao.arthas.grpc.server.handler.GrpcResponse; import com.taobao.arthas.grpc.server.handler.StreamObserver; import com.taobao.arthas.grpc.server.handler.constant.GrpcInvokeTypeEnum; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http2.DefaultHttp2DataFrame; import io.netty.handler.codec.http2.DefaultHttp2HeadersFrame; import io.netty.handler.codec.http2.Http2DataFrame; import java.util.concurrent.atomic.AtomicBoolean; /** * @author: FengYe * @date: 2024/10/24 01:51 * @description: UnaryProcessor */ public class ClientStreamExecutor extends AbstractGrpcExecutor { public ClientStreamExecutor(GrpcDispatcher dispatcher) { super(dispatcher); } @Override public GrpcInvokeTypeEnum supportGrpcType() { return GrpcInvokeTypeEnum.CLIENT_STREAM; } @Override public void execute(GrpcRequest request, Http2DataFrame frame, ChannelHandlerContext context) throws Throwable { Integer streamId = request.getStreamId(); StreamObserver<GrpcRequest> requestObserver = requestStreamObserverMap.computeIfAbsent(streamId, id->{ StreamObserver<GrpcResponse> responseObserver = new StreamObserver<GrpcResponse>() { AtomicBoolean sendHeader = new AtomicBoolean(false); @Override public void onNext(GrpcResponse res) { // 控制流只能响应一次header if (!sendHeader.get()) { sendHeader.compareAndSet(false, true); context.writeAndFlush(new DefaultHttp2HeadersFrame(res.getEndHeader()).stream(frame.stream())); } context.writeAndFlush(new DefaultHttp2DataFrame(res.getResponseData()).stream(frame.stream())); } @Override public void onCompleted() { context.writeAndFlush(new DefaultHttp2HeadersFrame(GrpcResponse.getDefaultEndStreamHeader(), true).stream(frame.stream())); } }; try { return dispatcher.clientStreamExecute(request, responseObserver); } catch (Throwable e) { throw new RuntimeException(e); } }); requestObserver.onNext(request); if (frame.isEndStream()) { requestObserver.onCompleted(); } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/labs/arthas-grpc-server/src/main/java/com/taobao/arthas/grpc/server/handler/executor/UnaryExecutor.java
labs/arthas-grpc-server/src/main/java/com/taobao/arthas/grpc/server/handler/executor/UnaryExecutor.java
package com.taobao.arthas.grpc.server.handler.executor; import com.taobao.arthas.grpc.server.handler.GrpcDispatcher; import com.taobao.arthas.grpc.server.handler.GrpcRequest; import com.taobao.arthas.grpc.server.handler.GrpcResponse; import com.taobao.arthas.grpc.server.handler.constant.GrpcInvokeTypeEnum; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http2.DefaultHttp2DataFrame; import io.netty.handler.codec.http2.DefaultHttp2HeadersFrame; import io.netty.handler.codec.http2.Http2DataFrame; /** * @author: FengYe * @date: 2024/10/24 01:51 * @description: UnaryProcessor */ public class UnaryExecutor extends AbstractGrpcExecutor { public UnaryExecutor(GrpcDispatcher dispatcher) { super(dispatcher); } @Override public GrpcInvokeTypeEnum supportGrpcType() { return GrpcInvokeTypeEnum.UNARY; } @Override public void execute(GrpcRequest request, Http2DataFrame frame, ChannelHandlerContext context) throws Throwable { // 一元调用,等到 endStream 再响应 if (frame.isEndStream()) { GrpcResponse response = dispatcher.unaryExecute(request); context.writeAndFlush(new DefaultHttp2HeadersFrame(response.getEndHeader()).stream(frame.stream())); context.writeAndFlush(new DefaultHttp2DataFrame(response.getResponseData()).stream(frame.stream())); context.writeAndFlush(new DefaultHttp2HeadersFrame(response.getEndStreamHeader(), true).stream(frame.stream())); } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/labs/arthas-grpc-server/src/main/java/com/taobao/arthas/grpc/server/handler/executor/ServerStreamExecutor.java
labs/arthas-grpc-server/src/main/java/com/taobao/arthas/grpc/server/handler/executor/ServerStreamExecutor.java
package com.taobao.arthas.grpc.server.handler.executor; import com.taobao.arthas.grpc.server.handler.GrpcDispatcher; import com.taobao.arthas.grpc.server.handler.GrpcRequest; import com.taobao.arthas.grpc.server.handler.GrpcResponse; import com.taobao.arthas.grpc.server.handler.StreamObserver; import com.taobao.arthas.grpc.server.handler.constant.GrpcInvokeTypeEnum; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http2.DefaultHttp2DataFrame; import io.netty.handler.codec.http2.DefaultHttp2HeadersFrame; import io.netty.handler.codec.http2.Http2DataFrame; import java.util.concurrent.atomic.AtomicBoolean; /** * @author: FengYe * @date: 2024/10/24 01:51 * @description: UnaryProcessor */ public class ServerStreamExecutor extends AbstractGrpcExecutor { public ServerStreamExecutor(GrpcDispatcher dispatcher) { super(dispatcher); } @Override public GrpcInvokeTypeEnum supportGrpcType() { return GrpcInvokeTypeEnum.SERVER_STREAM; } @Override public void execute(GrpcRequest request, Http2DataFrame frame, ChannelHandlerContext context) throws Throwable { StreamObserver<GrpcResponse> responseObserver = new StreamObserver<GrpcResponse>() { AtomicBoolean sendHeader = new AtomicBoolean(false); @Override public void onNext(GrpcResponse res) { // 控制流只能响应一次header if (!sendHeader.get()) { sendHeader.compareAndSet(false, true); context.writeAndFlush(new DefaultHttp2HeadersFrame(res.getEndHeader()).stream(frame.stream())); } context.writeAndFlush(new DefaultHttp2DataFrame(res.getResponseData()).stream(frame.stream())); } @Override public void onCompleted() { context.writeAndFlush(new DefaultHttp2HeadersFrame(GrpcResponse.getDefaultEndStreamHeader(), true).stream(frame.stream())); } }; try { dispatcher.serverStreamExecute(request, responseObserver); } catch (Throwable e) { throw new RuntimeException(e); } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/labs/arthas-grpc-server/src/main/java/com/taobao/arthas/grpc/server/handler/executor/AbstractGrpcExecutor.java
labs/arthas-grpc-server/src/main/java/com/taobao/arthas/grpc/server/handler/executor/AbstractGrpcExecutor.java
package com.taobao.arthas.grpc.server.handler.executor; import com.taobao.arthas.grpc.server.handler.GrpcDispatcher; import com.taobao.arthas.grpc.server.handler.GrpcRequest; import com.taobao.arthas.grpc.server.handler.StreamObserver; import java.util.concurrent.ConcurrentHashMap; /** * @author: FengYe * @date: 2024/10/24 02:07 * @description: AbstractGrpcExecutor */ public abstract class AbstractGrpcExecutor implements GrpcExecutor{ protected GrpcDispatcher dispatcher; protected ConcurrentHashMap<Integer, StreamObserver<GrpcRequest>> requestStreamObserverMap = new ConcurrentHashMap<>(); public AbstractGrpcExecutor(GrpcDispatcher dispatcher) { this.dispatcher = dispatcher; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/labs/arthas-grpc-server/src/main/java/com/taobao/arthas/grpc/server/handler/executor/GrpcExecutor.java
labs/arthas-grpc-server/src/main/java/com/taobao/arthas/grpc/server/handler/executor/GrpcExecutor.java
package com.taobao.arthas.grpc.server.handler.executor; import com.taobao.arthas.grpc.server.handler.GrpcRequest; import com.taobao.arthas.grpc.server.handler.constant.GrpcInvokeTypeEnum; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http2.Http2DataFrame; /** * @author: FengYe * @date: 2024/10/24 01:50 * @description: GrpcProcessor */ public interface GrpcExecutor { GrpcInvokeTypeEnum supportGrpcType(); void execute(GrpcRequest request, Http2DataFrame frame, ChannelHandlerContext context) throws Throwable; }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/labs/arthas-grpc-server/src/main/java/com/taobao/arthas/grpc/server/handler/executor/GrpcExecutorFactory.java
labs/arthas-grpc-server/src/main/java/com/taobao/arthas/grpc/server/handler/executor/GrpcExecutorFactory.java
package com.taobao.arthas.grpc.server.handler.executor; import com.alibaba.arthas.deps.org.slf4j.Logger; import com.alibaba.arthas.deps.org.slf4j.LoggerFactory; import com.taobao.arthas.grpc.server.handler.GrpcDispatcher; import com.taobao.arthas.grpc.server.handler.constant.GrpcInvokeTypeEnum; import com.taobao.arthas.grpc.server.utils.ReflectUtil; import java.lang.invoke.MethodHandles; import java.lang.reflect.Constructor; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author: FengYe * @date: 2024/10/24 01:56 * @description: GrpcExecutorFactory */ public class GrpcExecutorFactory { private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass().getName()); public static final String DEFAULT_GRPC_EXECUTOR_PACKAGE_NAME = "com.taobao.arthas.grpc.server.handler.executor"; private final Map<GrpcInvokeTypeEnum, GrpcExecutor> map = new HashMap<>(); public void loadExecutor(GrpcDispatcher dispatcher) { List<Class<?>> classes = ReflectUtil.findClasses(DEFAULT_GRPC_EXECUTOR_PACKAGE_NAME); for (Class<?> clazz : classes) { if (GrpcExecutor.class.isAssignableFrom(clazz)) { try { if (AbstractGrpcExecutor.class.equals(clazz) || GrpcExecutor.class.equals(clazz)) { continue; } if (AbstractGrpcExecutor.class.isAssignableFrom(clazz)) { Constructor<?> constructor = clazz.getConstructor(GrpcDispatcher.class); GrpcExecutor executor = (GrpcExecutor) constructor.newInstance(dispatcher); map.put(executor.supportGrpcType(), executor); } else { Constructor<?> constructor = clazz.getConstructor(); GrpcExecutor executor = (GrpcExecutor) constructor.newInstance(); map.put(executor.supportGrpcType(), executor); } } catch (Exception e) { logger.error("GrpcExecutorFactory loadExecutor error", e); } } } } public GrpcExecutor getExecutor(GrpcInvokeTypeEnum grpcType) { return map.get(grpcType); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/labs/arthas-grpc-server/src/main/java/com/taobao/arthas/grpc/server/handler/executor/BiStreamExecutor.java
labs/arthas-grpc-server/src/main/java/com/taobao/arthas/grpc/server/handler/executor/BiStreamExecutor.java
package com.taobao.arthas.grpc.server.handler.executor; import com.taobao.arthas.grpc.server.handler.GrpcDispatcher; import com.taobao.arthas.grpc.server.handler.GrpcRequest; import com.taobao.arthas.grpc.server.handler.GrpcResponse; import com.taobao.arthas.grpc.server.handler.StreamObserver; import com.taobao.arthas.grpc.server.handler.constant.GrpcInvokeTypeEnum; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http2.DefaultHttp2DataFrame; import io.netty.handler.codec.http2.DefaultHttp2HeadersFrame; import io.netty.handler.codec.http2.Http2DataFrame; import java.util.concurrent.atomic.AtomicBoolean; /** * @author: FengYe * @date: 2024/10/24 01:52 * @description: BiStreamProcessor */ public class BiStreamExecutor extends AbstractGrpcExecutor { public BiStreamExecutor(GrpcDispatcher dispatcher) { super(dispatcher); } @Override public GrpcInvokeTypeEnum supportGrpcType() { return GrpcInvokeTypeEnum.BI_STREAM; } @Override public void execute(GrpcRequest request, Http2DataFrame frame, ChannelHandlerContext context) throws Throwable { Integer streamId = request.getStreamId(); StreamObserver<GrpcRequest> requestObserver = requestStreamObserverMap.computeIfAbsent(streamId, id->{ StreamObserver<GrpcResponse> responseObserver = new StreamObserver<GrpcResponse>() { AtomicBoolean sendHeader = new AtomicBoolean(false); @Override public void onNext(GrpcResponse res) { // 控制流只能响应一次header if (!sendHeader.get()) { sendHeader.compareAndSet(false, true); context.writeAndFlush(new DefaultHttp2HeadersFrame(res.getEndHeader()).stream(frame.stream())); } context.writeAndFlush(new DefaultHttp2DataFrame(res.getResponseData()).stream(frame.stream())); } @Override public void onCompleted() { context.writeAndFlush(new DefaultHttp2HeadersFrame(GrpcResponse.getDefaultEndStreamHeader(), true).stream(frame.stream())); } }; try { return dispatcher.biStreamExecute(request, responseObserver); } catch (Throwable e) { throw new RuntimeException(e); } }); requestObserver.onNext(request); if (frame.isEndStream()) { requestObserver.onCompleted(); } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/memorycompiler/src/test/java/com/taobao/arthas/compiler/PackageInternalsFinderTest.java
memorycompiler/src/test/java/com/taobao/arthas/compiler/PackageInternalsFinderTest.java
package com.taobao.arthas.compiler; import org.junit.Assert; import org.junit.Test; import javax.tools.JavaFileObject; import java.io.IOException; import java.util.List; /** * description: PackageInternalsFinderTest <br> * date: 2021/9/23 12:55 下午 <br> * author: zzq0324 <br> * version: 1.0 <br> */ public class PackageInternalsFinderTest { @Test public void testFilePathContainWhitespace() throws IOException { PackageInternalsFinder finder = new PackageInternalsFinder(this.getClass().getClassLoader()); List<JavaFileObject> fileObjectList= finder.find("file/test folder"); Assert.assertEquals(fileObjectList.size(), 0); } @Test public void testFilePathContainChineseCharacter() throws IOException { PackageInternalsFinder finder = new PackageInternalsFinder(this.getClass().getClassLoader()); List<JavaFileObject> fileObjectList= finder.find("file/测试目录"); Assert.assertEquals(fileObjectList.size(), 0); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/memorycompiler/src/test/java/com/taobao/arthas/compiler/DynamicCompilerTest.java
memorycompiler/src/test/java/com/taobao/arthas/compiler/DynamicCompilerTest.java
package com.taobao.arthas.compiler; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.net.URLClassLoader; import java.util.Map; import org.junit.Assert; import org.junit.Test; import org.slf4j.LoggerFactory; /** * * @author hengyunabc 2019-02-06 * */ public class DynamicCompilerTest { @Test public void test() throws IOException { String jarPath = LoggerFactory.class.getProtectionDomain().getCodeSource().getLocation().getFile(); File file = new File(jarPath); URLClassLoader classLoader = new URLClassLoader(new URL[] { file.toURI().toURL() }, ClassLoader.getSystemClassLoader().getParent()); DynamicCompiler dynamicCompiler = new DynamicCompiler(classLoader); InputStream logger1Stream = DynamicCompilerTest.class.getClassLoader().getResourceAsStream("TestLogger1.java"); InputStream logger2Stream = DynamicCompilerTest.class.getClassLoader().getResourceAsStream("TestLogger2.java"); dynamicCompiler.addSource("TestLogger2", toString(logger2Stream)); dynamicCompiler.addSource("TestLogger1", toString(logger1Stream)); Map<String, byte[]> byteCodes = dynamicCompiler.buildByteCodes(); Assert.assertTrue("TestLogger1", byteCodes.containsKey("com.test.TestLogger1")); Assert.assertTrue("TestLogger2", byteCodes.containsKey("com.hello.TestLogger2")); } /** * Get the contents of an <code>InputStream</code> as a String * using the default character encoding of the platform. * <p> * This method buffers the input internally, so there is no need to use a * <code>BufferedInputStream</code>. * * @param input the <code>InputStream</code> to read from * @return the requested String * @throws NullPointerException if the input is null * @throws IOException if an I/O error occurs */ public static String toString(InputStream input) throws IOException { BufferedReader br = null; try { StringBuilder sb = new StringBuilder(); br = new BufferedReader(new InputStreamReader(input)); String line; while ((line = br.readLine()) != null) { sb.append(line).append("\n"); } return sb.toString(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { // ignore } } } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/memorycompiler/src/test/resources/TestLogger2.java
memorycompiler/src/test/resources/TestLogger2.java
package com.hello; import com.test.TestLogger1; public class TestLogger2 extends TestLogger1 { }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/memorycompiler/src/test/resources/TestLogger1.java
memorycompiler/src/test/resources/TestLogger1.java
package com.test; import org.slf4j.Marker; public class TestLogger1 implements org.slf4j.Logger { @Override public String getName() { return null; } @Override public boolean isTraceEnabled() { return false; } @Override public void trace(String arg0) { } @Override public void trace(String arg0, Object arg1) { } @Override public void trace(String arg0, Object arg1, Object arg2) { } @Override public void trace(String arg0, Object... arg1) { } @Override public void trace(String arg0, Throwable arg1) { } @Override public boolean isTraceEnabled(Marker arg0) { return false; } @Override public void trace(Marker arg0, String arg1) { } @Override public void trace(Marker arg0, String arg1, Object arg2) { } @Override public void trace(Marker arg0, String arg1, Object arg2, Object arg3) { } @Override public void trace(Marker arg0, String arg1, Object... arg2) { } @Override public void trace(Marker arg0, String arg1, Throwable arg2) { } @Override public boolean isDebugEnabled() { return false; } @Override public void debug(String arg0) { } @Override public void debug(String arg0, Object arg1) { } @Override public void debug(String arg0, Object arg1, Object arg2) { } @Override public void debug(String arg0, Object... arg1) { } @Override public void debug(String arg0, Throwable arg1) { } @Override public boolean isDebugEnabled(Marker arg0) { return false; } @Override public void debug(Marker arg0, String arg1) { } @Override public void debug(Marker arg0, String arg1, Object arg2) { } @Override public void debug(Marker arg0, String arg1, Object arg2, Object arg3) { } @Override public void debug(Marker arg0, String arg1, Object... arg2) { } @Override public void debug(Marker arg0, String arg1, Throwable arg2) { } @Override public boolean isInfoEnabled() { return false; } @Override public void info(String arg0) { } @Override public void info(String arg0, Object arg1) { } @Override public void info(String arg0, Object arg1, Object arg2) { } @Override public void info(String arg0, Object... arg1) { } @Override public void info(String arg0, Throwable arg1) { } @Override public boolean isInfoEnabled(Marker arg0) { return false; } @Override public void info(Marker arg0, String arg1) { } @Override public void info(Marker arg0, String arg1, Object arg2) { } @Override public void info(Marker arg0, String arg1, Object arg2, Object arg3) { } @Override public void info(Marker arg0, String arg1, Object... arg2) { } @Override public void info(Marker arg0, String arg1, Throwable arg2) { } @Override public boolean isWarnEnabled() { return false; } @Override public void warn(String arg0) { } @Override public void warn(String arg0, Object arg1) { } @Override public void warn(String arg0, Object... arg1) { } @Override public void warn(String arg0, Object arg1, Object arg2) { } @Override public void warn(String arg0, Throwable arg1) { } @Override public boolean isWarnEnabled(Marker arg0) { return false; } @Override public void warn(Marker arg0, String arg1) { } @Override public void warn(Marker arg0, String arg1, Object arg2) { } @Override public void warn(Marker arg0, String arg1, Object arg2, Object arg3) { } @Override public void warn(Marker arg0, String arg1, Object... arg2) { } @Override public void warn(Marker arg0, String arg1, Throwable arg2) { } @Override public boolean isErrorEnabled() { return false; } @Override public void error(String arg0) { } @Override public void error(String arg0, Object arg1) { } @Override public void error(String arg0, Object arg1, Object arg2) { } @Override public void error(String arg0, Object... arg1) { } @Override public void error(String arg0, Throwable arg1) { } @Override public boolean isErrorEnabled(Marker arg0) { return false; } @Override public void error(Marker arg0, String arg1) { } @Override public void error(Marker arg0, String arg1, Object arg2) { } @Override public void error(Marker arg0, String arg1, Object arg2, Object arg3) { } @Override public void error(Marker arg0, String arg1, Object... arg2) { } @Override public void error(Marker arg0, String arg1, Throwable arg2) { } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/memorycompiler/src/main/java/com/taobao/arthas/compiler/MemoryByteCode.java
memorycompiler/src/main/java/com/taobao/arthas/compiler/MemoryByteCode.java
package com.taobao.arthas.compiler; /*- * #%L * compiler * %% * Copyright (C) 2017 - 2018 SkaLogs * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import javax.tools.SimpleJavaFileObject; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.net.URI; import java.net.URISyntaxException; public class MemoryByteCode extends SimpleJavaFileObject { private static final char PKG_SEPARATOR = '.'; private static final char DIR_SEPARATOR = '/'; private static final String CLASS_FILE_SUFFIX = ".class"; private ByteArrayOutputStream byteArrayOutputStream; public MemoryByteCode(String className) { super(URI.create("byte:///" + className.replace(PKG_SEPARATOR, DIR_SEPARATOR) + Kind.CLASS.extension), Kind.CLASS); } public MemoryByteCode(String className, ByteArrayOutputStream byteArrayOutputStream) throws URISyntaxException { this(className); this.byteArrayOutputStream = byteArrayOutputStream; } @Override public OutputStream openOutputStream() throws IOException { if (byteArrayOutputStream == null) { byteArrayOutputStream = new ByteArrayOutputStream(); } return byteArrayOutputStream; } public byte[] getByteCode() { return byteArrayOutputStream.toByteArray(); } public String getClassName() { String className = getName(); className = className.replace(DIR_SEPARATOR, PKG_SEPARATOR); className = className.substring(1, className.indexOf(CLASS_FILE_SUFFIX)); return className; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/memorycompiler/src/main/java/com/taobao/arthas/compiler/DynamicJavaFileManager.java
memorycompiler/src/main/java/com/taobao/arthas/compiler/DynamicJavaFileManager.java
package com.taobao.arthas.compiler; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Set; import javax.tools.FileObject; import javax.tools.ForwardingJavaFileManager; import javax.tools.JavaFileManager; import javax.tools.JavaFileObject; import javax.tools.StandardLocation; public class DynamicJavaFileManager extends ForwardingJavaFileManager<JavaFileManager> { private static final String[] superLocationNames = { StandardLocation.PLATFORM_CLASS_PATH.name(), /** JPMS StandardLocation.SYSTEM_MODULES **/ "SYSTEM_MODULES" }; private final PackageInternalsFinder finder; private final DynamicClassLoader classLoader; private final List<MemoryByteCode> byteCodes = new ArrayList<MemoryByteCode>(); public DynamicJavaFileManager(JavaFileManager fileManager, DynamicClassLoader classLoader) { super(fileManager); this.classLoader = classLoader; this.finder = new PackageInternalsFinder(classLoader); } @Override public JavaFileObject getJavaFileForOutput(JavaFileManager.Location location, String className, JavaFileObject.Kind kind, FileObject sibling) throws IOException { for (MemoryByteCode byteCode : byteCodes) { if (byteCode.getClassName().equals(className)) { return byteCode; } } MemoryByteCode innerClass = new MemoryByteCode(className); byteCodes.add(innerClass); classLoader.registerCompiledSource(innerClass); return innerClass; } @Override public ClassLoader getClassLoader(JavaFileManager.Location location) { return classLoader; } @Override public String inferBinaryName(Location location, JavaFileObject file) { if (file instanceof CustomJavaFileObject) { return ((CustomJavaFileObject) file).getClassName(); } else { /** * if it's not CustomJavaFileObject, then it's coming from standard file manager * - let it handle the file */ return super.inferBinaryName(location, file); } } @Override public Iterable<JavaFileObject> list(Location location, String packageName, Set<JavaFileObject.Kind> kinds, boolean recurse) throws IOException { if (location instanceof StandardLocation) { String locationName = ((StandardLocation) location).name(); for (String name : superLocationNames) { if (name.equals(locationName)) { return super.list(location, packageName, kinds, recurse); } } } // merge JavaFileObjects from specified ClassLoader if (location == StandardLocation.CLASS_PATH && kinds.contains(JavaFileObject.Kind.CLASS)) { return new IterableJoin<JavaFileObject>(super.list(location, packageName, kinds, recurse), finder.find(packageName)); } return super.list(location, packageName, kinds, recurse); } static class IterableJoin<T> implements Iterable<T> { private final Iterable<T> first, next; public IterableJoin(Iterable<T> first, Iterable<T> next) { this.first = first; this.next = next; } @Override public Iterator<T> iterator() { return new IteratorJoin<T>(first.iterator(), next.iterator()); } } static class IteratorJoin<T> implements Iterator<T> { private final Iterator<T> first, next; public IteratorJoin(Iterator<T> first, Iterator<T> next) { this.first = first; this.next = next; } @Override public boolean hasNext() { return first.hasNext() || next.hasNext(); } @Override public T next() { if (first.hasNext()) { return first.next(); } return next.next(); } @Override public void remove() { throw new UnsupportedOperationException("remove"); } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/memorycompiler/src/main/java/com/taobao/arthas/compiler/CustomJavaFileObject.java
memorycompiler/src/main/java/com/taobao/arthas/compiler/CustomJavaFileObject.java
package com.taobao.arthas.compiler; /*- * #%L * compiler * %% * Copyright (C) 2017 - 2018 SkaLogs * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import javax.lang.model.element.Modifier; import javax.lang.model.element.NestingKind; import javax.tools.JavaFileObject; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.Writer; import java.net.URI; public class CustomJavaFileObject implements JavaFileObject { private final String className; private final URI uri; public CustomJavaFileObject(String className, URI uri) { this.uri = uri; this.className = className; } public URI toUri() { return uri; } public InputStream openInputStream() throws IOException { return uri.toURL().openStream(); } public OutputStream openOutputStream() { throw new UnsupportedOperationException(); } public String getName() { return this.className; } public Reader openReader(boolean ignoreEncodingErrors) { throw new UnsupportedOperationException(); } public CharSequence getCharContent(boolean ignoreEncodingErrors) { throw new UnsupportedOperationException(); } public Writer openWriter() throws IOException { throw new UnsupportedOperationException(); } public long getLastModified() { return 0; } public boolean delete() { throw new UnsupportedOperationException(); } public Kind getKind() { return Kind.CLASS; } public boolean isNameCompatible(String simpleName, Kind kind) { return Kind.CLASS.equals(getKind()) && this.className.endsWith(simpleName); } public NestingKind getNestingKind() { throw new UnsupportedOperationException(); } public Modifier getAccessLevel() { throw new UnsupportedOperationException(); } public String getClassName() { return this.className; } public String toString() { return this.getClass().getName() + "[" + this.toUri() + "]"; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/memorycompiler/src/main/java/com/taobao/arthas/compiler/DynamicClassLoader.java
memorycompiler/src/main/java/com/taobao/arthas/compiler/DynamicClassLoader.java
package com.taobao.arthas.compiler; /*- * #%L * compiler * %% * Copyright (C) 2017 - 2018 SkaLogs * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; public class DynamicClassLoader extends ClassLoader { private final Map<String, MemoryByteCode> byteCodes = new HashMap<String, MemoryByteCode>(); public DynamicClassLoader(ClassLoader classLoader) { super(classLoader); } public void registerCompiledSource(MemoryByteCode byteCode) { byteCodes.put(byteCode.getClassName(), byteCode); } @Override protected Class<?> findClass(String name) throws ClassNotFoundException { MemoryByteCode byteCode = byteCodes.get(name); if (byteCode == null) { return super.findClass(name); } return super.defineClass(name, byteCode.getByteCode(), 0, byteCode.getByteCode().length); } public Map<String, Class<?>> getClasses() throws ClassNotFoundException { Map<String, Class<?>> classes = new HashMap<String, Class<?>>(); for (MemoryByteCode byteCode : byteCodes.values()) { classes.put(byteCode.getClassName(), findClass(byteCode.getClassName())); } return classes; } public Map<String, byte[]> getByteCodes() { Map<String, byte[]> result = new HashMap<String, byte[]>(byteCodes.size()); for (Entry<String, MemoryByteCode> entry : byteCodes.entrySet()) { result.put(entry.getKey(), entry.getValue().getByteCode()); } return result; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/memorycompiler/src/main/java/com/taobao/arthas/compiler/DynamicCompilerException.java
memorycompiler/src/main/java/com/taobao/arthas/compiler/DynamicCompilerException.java
package com.taobao.arthas.compiler; /*- * #%L * compiler * %% * Copyright (C) 2017 - 2018 SkaLogs * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import javax.tools.Diagnostic; import javax.tools.JavaFileObject; import java.util.*; public class DynamicCompilerException extends RuntimeException { private static final long serialVersionUID = 1L; private List<Diagnostic<? extends JavaFileObject>> diagnostics; public DynamicCompilerException(String message, List<Diagnostic<? extends JavaFileObject>> diagnostics) { super(message); this.diagnostics = diagnostics; } public DynamicCompilerException(Throwable cause, List<Diagnostic<? extends JavaFileObject>> diagnostics) { super(cause); this.diagnostics = diagnostics; } private List<Map<String, Object>> getErrorList() { List<Map<String, Object>> messages = new ArrayList<Map<String, Object>>(); if (diagnostics != null) { for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics) { Map<String, Object> message = new HashMap<String, Object>(2); message.put("line", diagnostic.getLineNumber()); message.put("message", diagnostic.getMessage(Locale.US)); messages.add(message); } } return messages; } private String getErrors() { StringBuilder errors = new StringBuilder(); for (Map<String, Object> message : getErrorList()) { for (Map.Entry<String, Object> entry : message.entrySet()) { Object value = entry.getValue(); if (value != null && !value.toString().isEmpty()) { errors.append(entry.getKey()); errors.append(": "); errors.append(value); } errors.append(" , "); } errors.append("\n"); } return errors.toString(); } @Override public String getMessage() { return super.getMessage() + "\n" + getErrors(); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/memorycompiler/src/main/java/com/taobao/arthas/compiler/ClassUriWrapper.java
memorycompiler/src/main/java/com/taobao/arthas/compiler/ClassUriWrapper.java
package com.taobao.arthas.compiler; /*- * #%L * compiler * %% * Copyright (C) 2017 - 2018 SkaLogs * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import java.net.URI; public class ClassUriWrapper { private final URI uri; private final String className; public ClassUriWrapper(String className, URI uri) { this.className = className; this.uri = uri; } public URI getUri() { return uri; } public String getClassName() { return className; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/memorycompiler/src/main/java/com/taobao/arthas/compiler/PackageInternalsFinder.java
memorycompiler/src/main/java/com/taobao/arthas/compiler/PackageInternalsFinder.java
package com.taobao.arthas.compiler; /*- * #%L * compiler * %% * Copyright (C) 2017 - 2018 SkaLogs * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import javax.tools.JavaFileObject; import java.io.File; import java.io.IOException; import java.net.JarURLConnection; import java.net.URI; import java.net.URL; import java.net.URLDecoder; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.jar.JarEntry; import java.util.stream.Collectors; public class PackageInternalsFinder { private final ClassLoader classLoader; private static final String CLASS_FILE_EXTENSION = ".class"; private static final Map<String, JarFileIndex> INDEXS = new ConcurrentHashMap<>(); public PackageInternalsFinder(ClassLoader classLoader) { this.classLoader = classLoader; } public List<JavaFileObject> find(String packageName) throws IOException { String javaPackageName = packageName.replaceAll("\\.", "/"); List<JavaFileObject> result = new ArrayList<JavaFileObject>(); Enumeration<URL> urlEnumeration = classLoader.getResources(javaPackageName); while (urlEnumeration.hasMoreElements()) { // one URL for each jar on the classpath that has the given package URL packageFolderURL = urlEnumeration.nextElement(); result.addAll(listUnder(packageName, packageFolderURL)); } return result; } private Collection<JavaFileObject> listUnder(String packageName, URL packageFolderURL) { File directory = new File(decode(packageFolderURL.getFile())); if (directory.isDirectory()) { // browse local .class files - useful for local execution return processDir(packageName, directory); } else { // browse a jar file return processJar(packageName, packageFolderURL); } } private List<JavaFileObject> processJar(String packageName, URL packageFolderURL) { try { String jarUri = packageFolderURL.toExternalForm().substring(0, packageFolderURL.toExternalForm().lastIndexOf("!/")); JarFileIndex jarFileIndex = INDEXS.get(jarUri); if (jarFileIndex == null) { jarFileIndex = new JarFileIndex(jarUri, URI.create(jarUri + "!/")); INDEXS.put(jarUri, jarFileIndex); } List<JavaFileObject> result = jarFileIndex.search(packageName); if (result != null) { return result; } } catch (Exception e) { // ignore } // 保底 return fuse(packageFolderURL); } private List<JavaFileObject> fuse(URL packageFolderURL) { List<JavaFileObject> result = new ArrayList<JavaFileObject>(); try { String jarUri = packageFolderURL.toExternalForm().substring(0, packageFolderURL.toExternalForm().lastIndexOf("!/")); JarURLConnection jarConn = (JarURLConnection) packageFolderURL.openConnection(); String rootEntryName = jarConn.getEntryName(); if (rootEntryName != null) { //可能为 null(自己没有类文件时) int rootEnd = rootEntryName.length() + 1; Enumeration<JarEntry> entryEnum = jarConn.getJarFile().entries(); while (entryEnum.hasMoreElements()) { JarEntry jarEntry = entryEnum.nextElement(); String name = jarEntry.getName(); if (name.startsWith(rootEntryName) && name.indexOf('/', rootEnd) == -1 && name.endsWith(CLASS_FILE_EXTENSION)) { URI uri = URI.create(jarUri + "!/" + name); String binaryName = name.replaceAll("/", "."); binaryName = binaryName.replaceAll(CLASS_FILE_EXTENSION + "$", ""); result.add(new CustomJavaFileObject(binaryName, uri)); } } } } catch (Exception e) { throw new RuntimeException("Wasn't able to open " + packageFolderURL + " as a jar file", e); } return result; } private List<JavaFileObject> processDir(String packageName, File directory) { File[] files = directory.listFiles(item -> item.isFile() && getKind(item.getName()) == JavaFileObject.Kind.CLASS); if (files != null) { return Arrays.stream(files).map(item -> { String className = packageName + "." + item.getName() .replaceAll(CLASS_FILE_EXTENSION + "$", ""); return new CustomJavaFileObject(className, item.toURI()); }).collect(Collectors.toList()); } return Collections.emptyList(); } private String decode(String filePath) { try { return URLDecoder.decode(filePath, "utf-8"); } catch (Exception e) { // ignore, return original string } return filePath; } public static JavaFileObject.Kind getKind(String name) { if (name.endsWith(JavaFileObject.Kind.CLASS.extension)) return JavaFileObject.Kind.CLASS; else if (name.endsWith(JavaFileObject.Kind.SOURCE.extension)) return JavaFileObject.Kind.SOURCE; else if (name.endsWith(JavaFileObject.Kind.HTML.extension)) return JavaFileObject.Kind.HTML; else return JavaFileObject.Kind.OTHER; } public static class JarFileIndex { private String jarUri; private URI uri; private Map<String, List<ClassUriWrapper>> packages = new HashMap<>(); public JarFileIndex(String jarUri, URI uri) throws IOException { this.jarUri = jarUri; this.uri = uri; loadIndex(); } private void loadIndex() throws IOException { JarURLConnection jarConn = (JarURLConnection) uri.toURL().openConnection(); String rootEntryName = jarConn.getEntryName() == null ? "" : jarConn.getEntryName(); Enumeration<JarEntry> entryEnum = jarConn.getJarFile().entries(); while (entryEnum.hasMoreElements()) { JarEntry jarEntry = entryEnum.nextElement(); String entryName = jarEntry.getName(); if (entryName.startsWith(rootEntryName) && entryName.endsWith(CLASS_FILE_EXTENSION)) { String className = entryName .substring(0, entryName.length() - CLASS_FILE_EXTENSION.length()) .replace(rootEntryName, "") .replace("/", "."); if (className.startsWith(".")) className = className.substring(1); if (className.equals("package-info") || className.equals("module-info") || className.lastIndexOf(".") == -1) { continue; } String packageName = className.substring(0, className.lastIndexOf(".")); List<ClassUriWrapper> classes = packages.get(packageName); if (classes == null) { classes = new ArrayList<>(); packages.put(packageName, classes); } classes.add(new ClassUriWrapper(className, URI.create(jarUri + "!/" + entryName))); } } } public List<JavaFileObject> search(String packageName) { if (this.packages.isEmpty()) { return null; } if (this.packages.containsKey(packageName)) { return packages.get(packageName).stream().map(item -> { return new CustomJavaFileObject(item.getClassName(), item.getUri()); }).collect(Collectors.toList()); } return Collections.emptyList(); } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/memorycompiler/src/main/java/com/taobao/arthas/compiler/StringSource.java
memorycompiler/src/main/java/com/taobao/arthas/compiler/StringSource.java
package com.taobao.arthas.compiler; /*- * #%L * compiler * %% * Copyright (C) 2017 - 2018 SkaLogs * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import javax.tools.SimpleJavaFileObject; import java.io.IOException; import java.net.URI; public class StringSource extends SimpleJavaFileObject { private final String contents; public StringSource(String className, String contents) { super(URI.create("string:///" + className.replace('.', '/') + Kind.SOURCE.extension), Kind.SOURCE); this.contents = contents; } @Override public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException { return contents; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/memorycompiler/src/main/java/com/taobao/arthas/compiler/DynamicCompiler.java
memorycompiler/src/main/java/com/taobao/arthas/compiler/DynamicCompiler.java
package com.taobao.arthas.compiler; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Locale; import java.util.Map; import javax.tools.Diagnostic; import javax.tools.DiagnosticCollector; import javax.tools.JavaCompiler; import javax.tools.JavaFileManager; import javax.tools.JavaFileObject; import javax.tools.StandardJavaFileManager; import javax.tools.ToolProvider; public class DynamicCompiler { private final JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler(); private final StandardJavaFileManager standardFileManager; private final List<String> options = new ArrayList<String>(); private final DynamicClassLoader dynamicClassLoader; private final Collection<JavaFileObject> compilationUnits = new ArrayList<JavaFileObject>(); private final List<Diagnostic<? extends JavaFileObject>> errors = new ArrayList<Diagnostic<? extends JavaFileObject>>(); private final List<Diagnostic<? extends JavaFileObject>> warnings = new ArrayList<Diagnostic<? extends JavaFileObject>>(); public DynamicCompiler(ClassLoader classLoader) { if (javaCompiler == null) { throw new IllegalStateException( "Can not load JavaCompiler from javax.tools.ToolProvider#getSystemJavaCompiler()," + " please confirm the application running in JDK not JRE."); } standardFileManager = javaCompiler.getStandardFileManager(null, null, null); options.add("-Xlint:unchecked"); options.add("-g"); dynamicClassLoader = new DynamicClassLoader(classLoader); } public void addSource(String className, String source) { addSource(new StringSource(className, source)); } public void addSource(JavaFileObject javaFileObject) { compilationUnits.add(javaFileObject); } public Map<String, Class<?>> build() { errors.clear(); warnings.clear(); JavaFileManager fileManager = new DynamicJavaFileManager(standardFileManager, dynamicClassLoader); DiagnosticCollector<JavaFileObject> collector = new DiagnosticCollector<JavaFileObject>(); JavaCompiler.CompilationTask task = javaCompiler.getTask(null, fileManager, collector, options, null, compilationUnits); try { if (!compilationUnits.isEmpty()) { boolean result = task.call(); if (!result || collector.getDiagnostics().size() > 0) { for (Diagnostic<? extends JavaFileObject> diagnostic : collector.getDiagnostics()) { switch (diagnostic.getKind()) { case NOTE: case MANDATORY_WARNING: case WARNING: warnings.add(diagnostic); break; case OTHER: case ERROR: default: errors.add(diagnostic); break; } } if (!errors.isEmpty()) { throw new DynamicCompilerException("Compilation Error", errors); } } } return dynamicClassLoader.getClasses(); } catch (Throwable e) { throw new DynamicCompilerException(e, errors); } finally { compilationUnits.clear(); } } public Map<String, byte[]> buildByteCodes() { errors.clear(); warnings.clear(); JavaFileManager fileManager = new DynamicJavaFileManager(standardFileManager, dynamicClassLoader); DiagnosticCollector<JavaFileObject> collector = new DiagnosticCollector<JavaFileObject>(); JavaCompiler.CompilationTask task = javaCompiler.getTask(null, fileManager, collector, options, null, compilationUnits); try { if (!compilationUnits.isEmpty()) { boolean result = task.call(); if (!result || collector.getDiagnostics().size() > 0) { for (Diagnostic<? extends JavaFileObject> diagnostic : collector.getDiagnostics()) { switch (diagnostic.getKind()) { case NOTE: case MANDATORY_WARNING: case WARNING: warnings.add(diagnostic); break; case OTHER: case ERROR: default: errors.add(diagnostic); break; } } if (!errors.isEmpty()) { throw new DynamicCompilerException("Compilation Error", errors); } } } return dynamicClassLoader.getByteCodes(); } catch (ClassFormatError e) { throw new DynamicCompilerException(e, errors); } finally { compilationUnits.clear(); } } private List<String> diagnosticToString(List<Diagnostic<? extends JavaFileObject>> diagnostics) { List<String> diagnosticMessages = new ArrayList<String>(); for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics) { diagnosticMessages.add( "line: " + diagnostic.getLineNumber() + ", message: " + diagnostic.getMessage(Locale.US)); } return diagnosticMessages; } public List<String> getErrors() { return diagnosticToString(errors); } public List<String> getWarnings() { return diagnosticToString(warnings); } public ClassLoader getClassLoader() { return dynamicClassLoader; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/testcase/src/main/java/com/alibaba/arthas/Test.java
testcase/src/main/java/com/alibaba/arthas/Test.java
package com.alibaba.arthas; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; /** * @author diecui1202 on 2017/9/13. */ public class Test { public static final Map m = new HashMap(); public static final Map n = new HashMap(); public static final Map p = null; static { m.put("a", "aaa"); m.put("b", "bbb"); n.put(Type.RUN, "aaa"); n.put(Type.STOP, "bbb"); } public static void main(String[] args) throws InterruptedException { List<Pojo> list = new ArrayList<Pojo>(); for (int i = 0; i < 40; i ++) { Pojo pojo = new Pojo(); pojo.setName("name " + i); pojo.setAge(i + 2); list.add(pojo); } System.out.println(p); while (true) { int random = new Random().nextInt(40); String name = list.get(random).getName(); list.get(random).setName(null); test(list); list.get(random).setName(name); Thread.sleep(1000L); } } public static void test(List<Pojo> list) { // do nothing } public static void invoke(String a) { System.out.println(a); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/testcase/src/main/java/com/alibaba/arthas/Type.java
testcase/src/main/java/com/alibaba/arthas/Type.java
package com.alibaba.arthas; public enum Type { RUN, STOP }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/testcase/src/main/java/com/alibaba/arthas/Pojo.java
testcase/src/main/java/com/alibaba/arthas/Pojo.java
package com.alibaba.arthas; public class Pojo { String name; int age; String hobby; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getHobby() { return hobby; } public void setHobby(String hobby) { this.hobby = hobby; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-model/src/main/java/com/taobao/arthas/core/command/model/WelcomeModel.java
arthas-model/src/main/java/com/taobao/arthas/core/command/model/WelcomeModel.java
package com.taobao.arthas.core.command.model; /** * @author gongdewei 2020/4/20 */ public class WelcomeModel extends ResultModel { private String pid; private String time; private String version; private String wiki; private String tutorials; private String mainClass; public WelcomeModel() { } @Override public String getType() { return "welcome"; } public String getPid() { return pid; } public void setPid(String pid) { this.pid = pid; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public String getWiki() { return wiki; } public void setWiki(String wiki) { this.wiki = wiki; } public String getTutorials() { return tutorials; } public void setTutorials(String tutorials) { this.tutorials = tutorials; } public String getMainClass() { return mainClass; } public void setMainClass(String mainClass) { this.mainClass = mainClass; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-model/src/main/java/com/taobao/arthas/core/command/model/MessageModel.java
arthas-model/src/main/java/com/taobao/arthas/core/command/model/MessageModel.java
package com.taobao.arthas.core.command.model; /** * @author gongdewei 2020/4/2 */ public class MessageModel extends ResultModel { private String message; public MessageModel() { } public MessageModel(String message) { this.message = message; } public String getMessage() { return message; } @Override public String getType() { return "message"; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-model/src/main/java/com/taobao/arthas/core/command/model/CommandRequestModel.java
arthas-model/src/main/java/com/taobao/arthas/core/command/model/CommandRequestModel.java
package com.taobao.arthas.core.command.model; /** * Command async exec process result, not the command exec result * @author gongdewei 2020/4/2 */ public class CommandRequestModel extends ResultModel { private String state; private String command; private String message; public CommandRequestModel() { } public CommandRequestModel(String command, String state) { this.command = command; this.state = state; } public CommandRequestModel(String command, String state, String message) { this.state = state; this.command = command; this.message = message; } public String getCommand() { return command; } public void setCommand(String command) { this.command = command; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } @Override public String getType() { return "command"; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-model/src/main/java/com/taobao/arthas/core/command/model/InputStatusModel.java
arthas-model/src/main/java/com/taobao/arthas/core/command/model/InputStatusModel.java
package com.taobao.arthas.core.command.model; /** * Input status for webui * @author gongdewei 2020/4/14 */ public class InputStatusModel extends ResultModel { private InputStatus inputStatus; public InputStatusModel(InputStatus inputStatus) { this.inputStatus = inputStatus; } public InputStatus getInputStatus() { return inputStatus; } public void setInputStatus(InputStatus inputStatus) { this.inputStatus = inputStatus; } @Override public String getType() { return "input_status"; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-model/src/main/java/com/taobao/arthas/core/command/model/StatusModel.java
arthas-model/src/main/java/com/taobao/arthas/core/command/model/StatusModel.java
package com.taobao.arthas.core.command.model; public class StatusModel extends ResultModel { private int statusCode; private String message; public StatusModel(int statusCode) { this.statusCode = statusCode; } public StatusModel(int statusCode, String message) { this.statusCode = statusCode; this.message = message; } public int getStatusCode() { return statusCode; } public String getMessage() { return message; } @Override public String getType() { return "status"; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-model/src/main/java/com/taobao/arthas/core/command/model/SessionModel.java
arthas-model/src/main/java/com/taobao/arthas/core/command/model/SessionModel.java
package com.taobao.arthas.core.command.model; /** * Session command result model * * @author gongdewei 2020/03/27 */ public class SessionModel extends ResultModel { private long javaPid; private String sessionId; private String agentId; private String tunnelServer; private String statUrl; private String userId; private boolean tunnelConnected; @Override public String getType() { return "session"; } public long getJavaPid() { return javaPid; } public void setJavaPid(long javaPid) { this.javaPid = javaPid; } public String getSessionId() { return sessionId; } public void setSessionId(String sessionId) { this.sessionId = sessionId; } public String getAgentId() { return agentId; } public void setAgentId(String agentId) { this.agentId = agentId; } public String getTunnelServer() { return tunnelServer; } public void setTunnelServer(String tunnelServer) { this.tunnelServer = tunnelServer; } public String getStatUrl() { return statUrl; } public void setStatUrl(String statUrl) { this.statUrl = statUrl; } public boolean isTunnelConnected() { return tunnelConnected; } public void setTunnelConnected(boolean tunnelConnected) { this.tunnelConnected = tunnelConnected; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-model/src/main/java/com/taobao/arthas/core/command/model/ObjectVO.java
arthas-model/src/main/java/com/taobao/arthas/core/command/model/ObjectVO.java
package com.taobao.arthas.core.command.model; /** * <pre> * 包装一层,解决json输出问题 * https://github.com/alibaba/arthas/issues/2261 * </pre> * * @author hengyunabc 2022-08-24 * */ public class ObjectVO { private Object object; private Integer expand; public ObjectVO(Object object, Integer expand) { this.object = object; this.expand = expand; } public static ObjectVO[] array(Object[] objects, Integer expand) { ObjectVO[] result = new ObjectVO[objects.length]; for (int i = 0; i < objects.length; ++i) { result[i] = new ObjectVO(objects[i], expand); } return result; } public int expandOrDefault() { if (expand != null) { return expand; } return 1; } public boolean needExpand() { return null != expand && expand > 0; } public Object getObject() { return object; } public void setObject(Object object) { this.object = object; } public Integer getExpand() { return expand; } public void setExpand(Integer expand) { this.expand = expand; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-model/src/main/java/com/taobao/arthas/core/command/model/ResultModel.java
arthas-model/src/main/java/com/taobao/arthas/core/command/model/ResultModel.java
package com.taobao.arthas.core.command.model; /** * Command execute result * * @author gongdewei 2020-03-26 */ public abstract class ResultModel { private int jobId; /** * Command type (name) * * @return */ public abstract String getType(); public int getJobId() { return jobId; } public void setJobId(int jobId) { this.jobId = jobId; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-model/src/main/java/com/taobao/arthas/core/command/model/InputStatus.java
arthas-model/src/main/java/com/taobao/arthas/core/command/model/InputStatus.java
package com.taobao.arthas.core.command.model; /** * Command input status for webui * @author gongdewei 2020/4/14 */ public enum InputStatus { /** * Allow input new commands */ ALLOW_INPUT, /** * Allow interrupt running job */ ALLOW_INTERRUPT, /** * Disable input and interrupt */ DISABLED }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-model/src/main/java/com/taobao/arthas/core/command/model/EnhancerAffectVO.java
arthas-model/src/main/java/com/taobao/arthas/core/command/model/EnhancerAffectVO.java
package com.taobao.arthas.core.command.model; import java.util.List; /** * Class enhance affect vo - pure data transfer object * @author gongdewei 2020/6/22 */ public class EnhancerAffectVO { private long cost; private int methodCount; private int classCount; private long listenerId; private Throwable throwable; private List<String> classDumpFiles; private List<String> methods; private String overLimitMsg; public EnhancerAffectVO() { } public EnhancerAffectVO(long cost, int methodCount, int classCount, long listenerId) { this.cost = cost; this.methodCount = methodCount; this.classCount = classCount; this.listenerId = listenerId; } public long getCost() { return cost; } public void setCost(long cost) { this.cost = cost; } public int getClassCount() { return classCount; } public void setClassCount(int classCount) { this.classCount = classCount; } public int getMethodCount() { return methodCount; } public void setMethodCount(int methodCount) { this.methodCount = methodCount; } public long getListenerId() { return listenerId; } public void setListenerId(long listenerId) { this.listenerId = listenerId; } public Throwable getThrowable() { return throwable; } public void setThrowable(Throwable throwable) { this.throwable = throwable; } public List<String> getClassDumpFiles() { return classDumpFiles; } public void setClassDumpFiles(List<String> classDumpFiles) { this.classDumpFiles = classDumpFiles; } public List<String> getMethods() { return methods; } public void setMethods(List<String> methods) { this.methods = methods; } public void setOverLimitMsg(String overLimitMsg) { this.overLimitMsg = overLimitMsg; } public String getOverLimitMsg() { return overLimitMsg; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-model/src/main/java/com/taobao/arthas/core/command/model/EnhancerModel.java
arthas-model/src/main/java/com/taobao/arthas/core/command/model/EnhancerModel.java
package com.taobao.arthas.core.command.model; /** * Data model of EnhancerCommand * * @author gongdewei 2020/7/20 */ public class EnhancerModel extends ResultModel { private EnhancerAffectVO effect; private boolean success; private String message; public EnhancerModel() { } public EnhancerModel(EnhancerAffectVO effect, boolean success) { this.effect = effect; this.success = success; } public EnhancerModel(EnhancerAffectVO effect, boolean success, String message) { this.effect = effect; this.success = success; this.message = message; } @Override public String getType() { return "enhancer"; } public EnhancerAffectVO getEffect() { return effect; } public void setEffect(EnhancerAffectVO effect) { this.effect = effect; } public boolean isSuccess() { return success; } public void setSuccess(boolean success) { this.success = success; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-agent-attach/src/main/java/com/taobao/arthas/agent/attach/ArthasAgent.java
arthas-agent-attach/src/main/java/com/taobao/arthas/agent/attach/ArthasAgent.java
package com.taobao.arthas.agent.attach; import java.arthas.SpyAPI; import java.io.File; import java.lang.instrument.Instrumentation; import java.net.URL; import java.util.HashMap; import java.util.Map; import org.zeroturnaround.zip.ZipUtil; import net.bytebuddy.agent.ByteBuddyAgent; /** * * @author hengyunabc 2020-06-22 * */ public class ArthasAgent { private static final int TEMP_DIR_ATTEMPTS = 10000; private static final String ARTHAS_CORE_JAR = "arthas-core.jar"; private static final String ARTHAS_BOOTSTRAP = "com.taobao.arthas.core.server.ArthasBootstrap"; private static final String GET_INSTANCE = "getInstance"; private static final String IS_BIND = "isBind"; private String errorMessage; private Map<String, String> configMap = new HashMap<String, String>(); private String arthasHome; private boolean slientInit; private Instrumentation instrumentation; public ArthasAgent() { this(null, null, false, null); } public ArthasAgent(Map<String, String> configMap) { this(configMap, null, false, null); } public ArthasAgent(String arthasHome) { this(null, arthasHome, false, null); } public ArthasAgent(Map<String, String> configMap, String arthasHome, boolean slientInit, Instrumentation instrumentation) { if (configMap != null) { this.configMap = configMap; } this.arthasHome = arthasHome; this.slientInit = slientInit; this.instrumentation = instrumentation; } public static void attach() { new ArthasAgent().init(); } /** * @see https://arthas.aliyun.com/doc/arthas-properties.html * @param configMap */ public static void attach(Map<String, String> configMap) { new ArthasAgent(configMap).init(); } /** * use the specified arthas * @param arthasHome arthas directory */ public static void attach(String arthasHome) { new ArthasAgent(arthasHome).init(); } public void init() throws IllegalStateException { // 尝试判断arthas是否已在运行,如果是的话,直接就退出 try { Class.forName("java.arthas.SpyAPI"); // 加载不到会抛异常 if (SpyAPI.isInited()) { return; } } catch (Throwable e) { // ignore } try { if (instrumentation == null) { instrumentation = ByteBuddyAgent.install(); } // 检查 arthasHome if (arthasHome == null || arthasHome.trim().isEmpty()) { // 解压出 arthasHome URL coreJarUrl = this.getClass().getClassLoader().getResource("arthas-bin.zip"); if (coreJarUrl != null) { File tempArthasDir = createTempDir(); ZipUtil.unpack(coreJarUrl.openStream(), tempArthasDir); arthasHome = tempArthasDir.getAbsolutePath(); } else { throw new IllegalArgumentException("can not getResources arthas-bin.zip from classloader: " + this.getClass().getClassLoader()); } } // find arthas-core.jar File arthasCoreJarFile = new File(arthasHome, ARTHAS_CORE_JAR); if (!arthasCoreJarFile.exists()) { throw new IllegalStateException("can not find arthas-core.jar under arthasHome: " + arthasHome); } AttachArthasClassloader arthasClassLoader = new AttachArthasClassloader( new URL[] { arthasCoreJarFile.toURI().toURL() }); /** * <pre> * ArthasBootstrap bootstrap = ArthasBootstrap.getInstance(inst); * </pre> */ Class<?> bootstrapClass = arthasClassLoader.loadClass(ARTHAS_BOOTSTRAP); Object bootstrap = bootstrapClass.getMethod(GET_INSTANCE, Instrumentation.class, Map.class).invoke(null, instrumentation, configMap); boolean isBind = (Boolean) bootstrapClass.getMethod(IS_BIND).invoke(bootstrap); if (!isBind) { String errorMsg = "Arthas server port binding failed! Please check $HOME/logs/arthas/arthas.log for more details."; throw new RuntimeException(errorMsg); } } catch (Throwable e) { errorMessage = e.getMessage(); if (!slientInit) { throw new IllegalStateException(e); } } } private static File createTempDir() { File baseDir = new File(System.getProperty("java.io.tmpdir")); String baseName = "arthas-" + System.currentTimeMillis() + "-"; for (int counter = 0; counter < TEMP_DIR_ATTEMPTS; counter++) { File tempDir = new File(baseDir, baseName + counter); if (tempDir.mkdir()) { return tempDir; } } throw new IllegalStateException("Failed to create directory within " + TEMP_DIR_ATTEMPTS + " attempts (tried " + baseName + "0 to " + baseName + (TEMP_DIR_ATTEMPTS - 1) + ')'); } public String getErrorMessage() { return errorMessage; } public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-agent-attach/src/main/java/com/taobao/arthas/agent/attach/AttachArthasClassloader.java
arthas-agent-attach/src/main/java/com/taobao/arthas/agent/attach/AttachArthasClassloader.java
package com.taobao.arthas.agent.attach; import java.net.URL; import java.net.URLClassLoader; /** * * @author hengyunabc 2020-06-22 * */ public class AttachArthasClassloader extends URLClassLoader { public AttachArthasClassloader(URL[] urls) { super(urls, ClassLoader.getSystemClassLoader().getParent()); } @Override protected synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { final Class<?> loadedClass = findLoadedClass(name); if (loadedClass != null) { return loadedClass; } // 优先从parent(SystemClassLoader)里加载系统类,避免抛出ClassNotFoundException if (name != null && (name.startsWith("sun.") || name.startsWith("java."))) { return super.loadClass(name, resolve); } try { Class<?> aClass = findClass(name); if (resolve) { resolveClass(aClass); } return aClass; } catch (Exception e) { // ignore } return super.loadClass(name, resolve); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-vmtool/src/test/java/arthas/VmToolTest.java
arthas-vmtool/src/test/java/arthas/VmToolTest.java
package arthas; import java.io.File; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import org.assertj.core.api.Assertions; import org.junit.Assert; import org.junit.Test; import com.taobao.arthas.common.VmToolUtils; /** * 以下本地测试的jvm参数均为:-Xms128m -Xmx128m */ public class VmToolTest { private VmTool initVmTool() { File path = new File(VmTool.class.getProtectionDomain().getCodeSource().getLocation().getPath()).getParentFile(); String libPath = new File(path, VmToolUtils.detectLibName()).getAbsolutePath(); return VmTool.getInstance(libPath); } /** * macbook上运行结果如下 * allLoadedClasses->1050 * arthas.VmTool@5bb21b69 arthas.VmTool@6b9651f3 * before instances->[arthas.VmTool@5bb21b69, arthas.VmTool@6b9651f3] * size->16 * count->2 * sum size->32 * null null * after instances->[] */ @Test public void testIsSnapshot() { try { VmTool vmtool = initVmTool(); //调用native方法,获取已加载的类,不包括小类型(如int) Class<?>[] allLoadedClasses = vmtool.getAllLoadedClasses(); System.out.println("allLoadedClasses->" + allLoadedClasses.length); //通过下面的例子,可以看到getInstances(Class<T> klass)拿到的是当前存活的所有对象 WeakReference<VmToolTest> weakReference1 = new WeakReference<VmToolTest>(new VmToolTest()); WeakReference<VmToolTest> weakReference2 = new WeakReference<VmToolTest>(new VmToolTest()); System.out.println(weakReference1.get() + " " + weakReference2.get()); VmTool[] beforeInstances = vmtool.getInstances(VmTool.class); System.out.println("before instances->" + beforeInstances); System.out.println("size->" + vmtool.getInstanceSize(weakReference1.get())); System.out.println("count->" + vmtool.countInstances(VmTool.class)); System.out.println("sum size->" + vmtool.sumInstanceSize(VmTool.class)); beforeInstances = null; vmtool.forceGc(); Thread.sleep(100); System.out.println(weakReference1.get() + " " + weakReference2.get()); VmTool[] afterInstances = vmtool.getInstances(VmTool.class); System.out.println("after instances->" + afterInstances); } catch (Exception e) { e.printStackTrace(); } } @Test public void testGetInstancesMemoryLeak() { //这里睡20s是为了方便用jprofiler连接上进程 // try { // Thread.sleep(20000); // } catch (InterruptedException e) { // e.printStackTrace(); // } VmTool vmtool = initVmTool(); final AtomicLong totalTime = new AtomicLong(); //本地测试请改成200000 for (int i = 1; i <= 2; i++) { long start = System.currentTimeMillis(); WeakReference<Object[]> reference = new WeakReference<Object[]>(vmtool.getInstances(Object.class)); Object[] instances = reference.get(); long cost = System.currentTimeMillis() - start; totalTime.addAndGet(cost); System.out.println(i + " instance size:" + (instances == null ? 0 : instances.length) + ", cost " + cost + "ms avgCost " + totalTime.doubleValue() / i + "ms"); instances = null; vmtool.forceGc(); } } @Test public void testSumInstancesMemoryLeak() { //这里睡20s是为了方便用jprofiler连接上进程 // try { // Thread.sleep(20000); // } catch (InterruptedException e) { // e.printStackTrace(); // } VmTool vmtool = initVmTool(); final AtomicLong totalTime = new AtomicLong(); //本地测试请改成200000 for (int i = 1; i <= 2; i++) { long start = System.currentTimeMillis(); long sum = vmtool.sumInstanceSize(Object.class); long cost = System.currentTimeMillis() - start; totalTime.addAndGet(cost); System.out.println(i + " sum:" + sum + ", cost " + cost + "ms avgCost " + totalTime.doubleValue() / i + "ms"); } } @Test public void testCountInstancesMemoryLeak() { //这里睡20s是为了方便用jprofiler连接上进程 // try { // Thread.sleep(20000); // } catch (InterruptedException e) { // e.printStackTrace(); // } VmTool vmtool = initVmTool(); final AtomicLong totalTime = new AtomicLong(); //本地测试请改成200000 for (int i = 1; i <= 2; i++) { long start = System.currentTimeMillis(); long count = vmtool.countInstances(Object.class); long cost = System.currentTimeMillis() - start; totalTime.addAndGet(cost); System.out.println(i + " count:" + count + ", cost " + cost + "ms avgCost " + totalTime.doubleValue() / i + "ms"); } } @Test public void testGetAllLoadedClassesMemoryLeak() { //这里睡20s是为了方便用jprofiler连接上进程 // try { // Thread.sleep(20000); // } catch (InterruptedException e) { // e.printStackTrace(); // } VmTool vmtool = initVmTool(); final AtomicLong totalTime = new AtomicLong(); //本地测试请改成200000 for (int i = 1; i <= 2; i++) { long start = System.currentTimeMillis(); Class<?>[] allLoadedClasses = vmtool.getAllLoadedClasses(); long cost = System.currentTimeMillis() - start; totalTime.addAndGet(cost); System.out.println(i + " class size:" + allLoadedClasses.length + ", cost " + cost + "ms avgCost " + totalTime.doubleValue() / i + "ms"); allLoadedClasses = null; } } class LimitTest { } @Test public void test_getInstances_lmiit() { VmTool vmtool = initVmTool(); ArrayList<LimitTest> list = new ArrayList<LimitTest>(); for (int i = 0; i < 10; ++i) { list.add(new LimitTest()); } LimitTest[] instances = vmtool.getInstances(LimitTest.class, 5); Assertions.assertThat(instances).hasSize(5); LimitTest[] instances2 = vmtool.getInstances(LimitTest.class, -1); Assertions.assertThat(instances2).hasSize(10); LimitTest[] instances3 = vmtool.getInstances(LimitTest.class, 1); Assertions.assertThat(instances3).hasSize(1); } interface III { } class AAA implements III { } @Test public void test_getInstances_interface() { AAA aaa = new AAA(); VmTool vmtool = initVmTool(); III[] interfaceInstances = vmtool.getInstances(III.class); Assertions.assertThat(interfaceInstances.length).isEqualTo(1); AAA[] ObjectInstances = vmtool.getInstances(AAA.class); Assertions.assertThat(ObjectInstances.length).isEqualTo(1); Assertions.assertThat(interfaceInstances[0]).isEqualTo(ObjectInstances[0]); } @Test public void test_interrupt_thread() throws InterruptedException { String threadName = "interruptMe"; final RuntimeException[] re = new RuntimeException[1]; Runnable runnable = new Runnable() { @Override public void run() { try { System.out.printf("Thread name is: [%s], thread id is: [%d].\n", Thread.currentThread().getName(),Thread.currentThread().getId()); TimeUnit.SECONDS.sleep(1000); } catch (InterruptedException e) { re[0] = new RuntimeException("interrupted " + Thread.currentThread().getId() + " thread success."); } } }; Thread interruptMe = new Thread(runnable,threadName); Thread interruptMe1 = new Thread(runnable,threadName); interruptMe.start(); interruptMe1.start(); VmTool tool = initVmTool(); tool.interruptSpecialThread((int) interruptMe.getId()); TimeUnit.SECONDS.sleep(5); Assert.assertEquals(("interrupted " + interruptMe.getId() + " thread success."), re[0].getMessage()); } @Test public void testMallocTrim() { VmTool vmtool = initVmTool(); vmtool.mallocTrim(); } @Test public void testMallocStats() { VmTool vmtool = initVmTool(); vmtool.mallocStats(); } static class ByteHolder { byte[] bytes; ByteHolder(int sizeMb) { this.bytes = new byte[sizeMb * 1024 * 1024]; } } @Test public void testHeapAnalyze() { VmTool vmtool = initVmTool(); String result = vmtool.heapAnalyze(5, 3); Assertions.assertThat(result).contains("class_number:").contains("object_number:"); } @Test public void testReferenceAnalyze() { // 通过本地变量制造 root(stack local) 引用,便于回溯链输出 ByteHolder bh1 = new ByteHolder(1); ByteHolder bh2 = new ByteHolder(2); Assertions.assertThat(bh1).isNotNull(); Assertions.assertThat(bh2).isNotNull(); VmTool vmtool = initVmTool(); String result = vmtool.referenceAnalyze(ByteHolder.class, 2, -1); Assertions.assertThat(result).contains("ByteHolder").contains("root"); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-vmtool/src/main/java/arthas/VmTool.java
arthas-vmtool/src/main/java/arthas/VmTool.java
package arthas; import java.util.Map; /** * @author ZhangZiCheng 2021-02-12 * @author hengyunabc 2021-04-26 * @since 3.5.1 */ public class VmTool implements VmToolMXBean { /** * 不要修改jni-lib的名称 */ public final static String JNI_LIBRARY_NAME = "ArthasJniLibrary"; private static VmTool instance; private VmTool() { } public static VmTool getInstance() { return getInstance(null); } public static synchronized VmTool getInstance(String libPath) { if (instance != null) { return instance; } if (libPath == null) { System.loadLibrary(JNI_LIBRARY_NAME); } else { System.load(libPath); } instance = new VmTool(); return instance; } private static synchronized native void forceGc0(); /** * 获取某个class在jvm中当前所有存活实例 */ private static synchronized native <T> T[] getInstances0(Class<T> klass, int limit); /** * 统计某个class在jvm中当前所有存活实例的总占用内存,单位:Byte */ private static synchronized native long sumInstanceSize0(Class<?> klass); /** * 获取某个实例的占用内存,单位:Byte */ private static native long getInstanceSize0(Object instance); /** * 统计某个class在jvm中当前所有存活实例的总个数 */ private static synchronized native long countInstances0(Class<?> klass); /** * 获取所有已加载的类 * @param klass 这个参数必须是 Class.class * @return */ private static synchronized native Class<?>[] getAllLoadedClasses0(Class<?> klass); /** * 分析堆内存占用最大的对象与类。 */ private static synchronized native String heapAnalyze0(int classNum, int objectNum); /** * 分析指定类实例的引用回溯链。 */ private static synchronized native String referenceAnalyze0(Class<?> klass, int objectNum, int backtraceNum); @Override public void forceGc() { forceGc0(); } @Override public void interruptSpecialThread(int threadId) { Map<Thread, StackTraceElement[]> allThread = Thread.getAllStackTraces(); for (Map.Entry<Thread, StackTraceElement[]> entry : allThread.entrySet()) { if (entry.getKey().getId() == threadId) { entry.getKey().interrupt(); return; } } } @Override public <T> T[] getInstances(Class<T> klass) { return getInstances0(klass, -1); } @Override public <T> T[] getInstances(Class<T> klass, int limit) { if (limit == 0) { throw new IllegalArgumentException("limit can not be 0"); } return getInstances0(klass, limit); } @Override public long sumInstanceSize(Class<?> klass) { return sumInstanceSize0(klass); } @Override public long getInstanceSize(Object instance) { return getInstanceSize0(instance); } @Override public long countInstances(Class<?> klass) { return countInstances0(klass); } @Override public Class<?>[] getAllLoadedClasses() { return getAllLoadedClasses0(Class.class); } @Override public int mallocTrim() { return mallocTrim0(); } private static synchronized native int mallocTrim0(); @Override public boolean mallocStats() { return mallocStats0(); } private static synchronized native boolean mallocStats0(); @Override public String heapAnalyze(int classNum, int objectNum) { return heapAnalyze0(classNum, objectNum); } @Override public String referenceAnalyze(Class<?> klass, int objectNum, int backtraceNum) { return referenceAnalyze0(klass, objectNum, backtraceNum); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-vmtool/src/main/java/arthas/package-info.java
arthas-vmtool/src/main/java/arthas/package-info.java
package arthas;
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-vmtool/src/main/java/arthas/VmToolMXBean.java
arthas-vmtool/src/main/java/arthas/VmToolMXBean.java
package arthas; /** * VmTool interface for JMX server. How to register VmTool MBean: * * <pre> * {@code * ManagementFactory.getPlatformMBeanServer().registerMBean( * VmTool.getInstance(), * new ObjectName("arthas:type=VmTool") * ); * } * </pre> * @author hengyunabc 2021-04-26 */ public interface VmToolMXBean { /** * https://docs.oracle.com/javase/8/docs/platform/jvmti/jvmti.html#ForceGarbageCollection */ public void forceGc(); /** * 打断指定线程 * * @param threadId 线程ID */ void interruptSpecialThread(int threadId); public <T> T[] getInstances(Class<T> klass); /** * 获取某个class在jvm中当前所有存活实例 * @param <T> * @param klass * @param limit 如果小于 0 ,则不限制 * @return */ public <T> T[] getInstances(Class<T> klass, int limit); /** * 统计某个class在jvm中当前所有存活实例的总占用内存,单位:Byte */ public long sumInstanceSize(Class<?> klass); /** * 获取某个实例的占用内存,单位:Byte */ public long getInstanceSize(Object instance); /** * 统计某个class在jvm中当前所有存活实例的总个数 */ public long countInstances(Class<?> klass); /** * 获取所有已加载的类 */ public Class<?>[] getAllLoadedClasses(); /** * glibc 释放空闲内存 */ public int mallocTrim(); /** * glibc 输出内存状态到应用的 stderr */ public boolean mallocStats(); /** * 分析堆内存占用最大的对象与类(从 GC Root 可达对象出发)。 * * @param classNum 需要展示的类数量 * @param objectNum 需要展示的对象数量 * @return 分析结果文本 */ public String heapAnalyze(int classNum, int objectNum); /** * 分析某个类的实例对象,并输出占用最大的若干对象及其引用回溯链(从对象回溯到 GC Root)。 * * @param klass 目标类 * @param objectNum 需要展示的对象数量 * @param backtraceNum 回溯层数,-1 表示一直回溯到 root,0 表示不输出引用链 * @return 分析结果文本 */ public String referenceAnalyze(Class<?> klass, int objectNum, int backtraceNum); }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/CommandExecutor.java
arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/CommandExecutor.java
package com.taobao.arthas.mcp.server; import java.util.Map; /** * 命令执行器接口 * * @author Yeaury 2025/5/26 */ public interface CommandExecutor { default Map<String, Object> executeSync(String commandLine, long timeout) { return executeSync(commandLine, timeout, null, null, null); } default Map<String, Object> executeSync(String commandLine, Object authSubject) { return executeSync(commandLine, 30000L, null, authSubject, null); } /** * 同步执行命令,支持指定 userId * * @param commandLine 命令行 * @param authSubject 认证主体 * @param userId 用户 ID,用于统计上报 * @return 执行结果 */ default Map<String, Object> executeSync(String commandLine, Object authSubject, String userId) { return executeSync(commandLine, 30000L, null, authSubject, userId); } /** * 同步执行命令 * * @param commandLine 命令行 * @param timeout 超时时间 * @param sessionId session ID,如果为null则创建临时session * @param authSubject 认证主体,如果不为null则应用到session * @param userId 用户 ID,用于统计上报 * @return 执行结果 */ Map<String, Object> executeSync(String commandLine, long timeout, String sessionId, Object authSubject, String userId); Map<String, Object> executeAsync(String commandLine, String sessionId); Map<String, Object> pullResults(String sessionId, String consumerId); Map<String, Object> interruptJob(String sessionId); Map<String, Object> createSession(); Map<String, Object> closeSession(String sessionId); void setSessionAuth(String sessionId, Object authSubject); /** * 设置 session 的 userId * * @param sessionId session ID * @param userId 用户 ID */ void setSessionUserId(String sessionId, String userId); }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/util/Assert.java
arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/util/Assert.java
package com.taobao.arthas.mcp.server.util; import java.util.Collection; import java.util.Map; /** * Assertion utility class for parameter validation. */ public final class Assert { private Assert() { } public static void notNull(Object object, String message) { if (object == null) { throw new IllegalArgumentException(message); } } public static void hasText(String text, String message) { if (text == null || text.trim().isEmpty()) { throw new IllegalArgumentException(message); } } public static void notEmpty(Collection<?> collection, String message) { if (collection == null || collection.isEmpty()) { throw new IllegalArgumentException(message); } } public static void notEmpty(Map<?, ?> map, String message) { if (map == null || map.isEmpty()) { throw new IllegalArgumentException(message); } } public static void isTrue(boolean condition, String message) { if (!condition) { throw new IllegalArgumentException(message); } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/util/Utils.java
arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/util/Utils.java
package com.taobao.arthas.mcp.server.util; import java.util.Collection; import java.util.Map; public final class Utils { public static boolean hasText(String str) { return str != null && !str.trim().isEmpty(); } public static boolean isEmpty(Collection<?> collection) { return (collection == null || collection.isEmpty()); } public static boolean isEmpty(Map<?, ?> map) { return (map == null || map.isEmpty()); } public static boolean isAssignable(Class<?> targetType, Class<?> sourceType) { if (targetType == null || sourceType == null) { return false; } if (targetType.equals(sourceType)) { return true; } if (targetType.isAssignableFrom(sourceType)) { return true; } if (targetType.isPrimitive()) { Class<?> resolvedPrimitive = getPrimitiveClassForWrapper(sourceType); return resolvedPrimitive != null && targetType.equals(resolvedPrimitive); } else if (sourceType.isPrimitive()) { Class<?> resolvedWrapper = getWrapperClassForPrimitive(sourceType); return resolvedWrapper != null && targetType.equals(resolvedWrapper); } return false; } public static Class<?> getPrimitiveClassForWrapper(Class<?> wrapperClass) { if (Boolean.class.equals(wrapperClass)) return boolean.class; if (Byte.class.equals(wrapperClass)) return byte.class; if (Character.class.equals(wrapperClass)) return char.class; if (Double.class.equals(wrapperClass)) return double.class; if (Float.class.equals(wrapperClass)) return float.class; if (Integer.class.equals(wrapperClass)) return int.class; if (Long.class.equals(wrapperClass)) return long.class; if (Short.class.equals(wrapperClass)) return short.class; if (Void.class.equals(wrapperClass)) return void.class; return null; } public static Class<?> getWrapperClassForPrimitive(Class<?> primitiveClass) { if (boolean.class.equals(primitiveClass)) return Boolean.class; if (byte.class.equals(primitiveClass)) return Byte.class; if (char.class.equals(primitiveClass)) return Character.class; if (double.class.equals(primitiveClass)) return Double.class; if (float.class.equals(primitiveClass)) return Float.class; if (int.class.equals(primitiveClass)) return Integer.class; if (long.class.equals(primitiveClass)) return Long.class; if (short.class.equals(primitiveClass)) return Short.class; if (void.class.equals(primitiveClass)) return Void.class; return null; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/util/KeepAliveScheduler.java
arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/util/KeepAliveScheduler.java
/** * Copyright 2025 - 2025 the original author or authors. */ package com.taobao.arthas.mcp.server.util; import com.fasterxml.jackson.core.type.TypeReference; import com.taobao.arthas.mcp.server.protocol.spec.McpSchema; import com.taobao.arthas.mcp.server.protocol.spec.McpSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.time.Duration; import java.util.Collection; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Supplier; /** * A utility class for scheduling regular keep-alive calls to maintain connections. It * sends periodic keep-alive, ping, messages to connected mcp clients to prevent idle * timeouts. * * The pings are sent to all active mcp sessions at regular intervals. * */ public class KeepAliveScheduler { private static final Logger logger = LoggerFactory.getLogger(KeepAliveScheduler.class); private static final TypeReference<Object> OBJECT_TYPE_REF = new TypeReference<Object>() { }; /** Initial delay before the first keepAlive call */ private final Duration initialDelay; /** Interval between subsequent keepAlive calls */ private final Duration interval; /** The scheduler used for executing keepAlive calls */ private final ScheduledExecutorService scheduler; /** Whether this scheduler owns the executor and should shut it down */ private final boolean ownsExecutor; /** The current state of the scheduler */ private final AtomicBoolean isRunning = new AtomicBoolean(false); /** The current scheduled task */ private volatile ScheduledFuture<?> currentTask; /** Supplier for McpSession instances */ private final Supplier<? extends Collection<? extends McpSession>> mcpSessions; /** * Creates a KeepAliveScheduler with a custom scheduler, initial delay, interval and a * supplier for McpSession instances. * @param scheduler The scheduler to use for executing keepAlive calls * @param ownsExecutor Whether this scheduler owns the executor and should shut it down * @param initialDelay Initial delay before the first keepAlive call * @param interval Interval between subsequent keepAlive calls * @param mcpSessions Supplier for McpSession instances */ private KeepAliveScheduler(ScheduledExecutorService scheduler, boolean ownsExecutor, Duration initialDelay, Duration interval, Supplier<? extends Collection<? extends McpSession>> mcpSessions) { this.scheduler = scheduler; this.ownsExecutor = ownsExecutor; this.initialDelay = initialDelay; this.interval = interval; this.mcpSessions = mcpSessions; } public static Builder builder(Supplier<? extends Collection<? extends McpSession>> mcpSessions) { return new Builder(mcpSessions); } /** * Starts regular keepAlive calls with sessions supplier. * @return This scheduler instance for method chaining */ public KeepAliveScheduler start() { if (this.isRunning.compareAndSet(false, true)) { logger.debug("Starting KeepAlive scheduler with initial delay: {}ms, interval: {}ms", initialDelay.toMillis(), interval.toMillis()); this.currentTask = this.scheduler.scheduleAtFixedRate( this::sendKeepAlivePings, this.initialDelay.toMillis(), this.interval.toMillis(), TimeUnit.MILLISECONDS ); return this; } else { throw new IllegalStateException("KeepAlive scheduler is already running. Stop it first."); } } /** * Sends keep-alive pings to all active sessions. */ private void sendKeepAlivePings() { try { Collection<? extends McpSession> sessions = this.mcpSessions.get(); if (sessions == null || sessions.isEmpty()) { logger.trace("No active sessions to ping"); return; } logger.trace("Sending keep-alive pings to {} sessions", sessions.size()); for (McpSession session : sessions) { try { session.sendRequest(McpSchema.METHOD_PING, null, OBJECT_TYPE_REF) .whenComplete((result, error) -> { if (error != null) { logger.warn("Failed to send keep-alive ping to session {}: {}", session, error.getMessage()); } else { logger.trace("Keep-alive ping sent successfully to session {}", session); } }); } catch (Exception e) { logger.warn("Exception while sending keep-alive ping to session {}: {}", session, e.getMessage()); } } } catch (Exception e) { logger.error("Error during keep-alive ping cycle", e); } } public void stop() { if (this.currentTask != null && !this.currentTask.isCancelled()) { this.currentTask.cancel(false); logger.debug("KeepAlive scheduler stopped"); } this.isRunning.set(false); } public boolean isRunning() { return this.isRunning.get(); } public void shutdown() { stop(); if (this.ownsExecutor && !this.scheduler.isShutdown()) { this.scheduler.shutdown(); try { if (!this.scheduler.awaitTermination(5, TimeUnit.SECONDS)) { this.scheduler.shutdownNow(); } } catch (InterruptedException e) { this.scheduler.shutdownNow(); Thread.currentThread().interrupt(); } logger.debug("KeepAlive scheduler executor shut down"); } } public static class Builder { private ScheduledExecutorService scheduler; private boolean ownsExecutor = false; private Duration initialDelay = Duration.ofSeconds(0); private Duration interval = Duration.ofSeconds(30); private Supplier<? extends Collection<? extends McpSession>> mcpSessions; Builder(Supplier<? extends Collection<? extends McpSession>> mcpSessions) { Assert.notNull(mcpSessions, "McpSessions supplier must not be null"); this.mcpSessions = mcpSessions; } public Builder scheduler(ScheduledExecutorService scheduler) { Assert.notNull(scheduler, "Scheduler must not be null"); this.scheduler = scheduler; this.ownsExecutor = false; return this; } public Builder initialDelay(Duration initialDelay) { Assert.notNull(initialDelay, "Initial delay must not be null"); this.initialDelay = initialDelay; return this; } public Builder interval(Duration interval) { Assert.notNull(interval, "Interval must not be null"); this.interval = interval; return this; } public KeepAliveScheduler build() { if (this.scheduler == null) { this.scheduler = Executors.newSingleThreadScheduledExecutor(r -> { Thread t = new Thread(r, "mcp-keep-alive-scheduler"); t.setDaemon(true); return t; }); this.ownsExecutor = true; } return new KeepAliveScheduler(scheduler, ownsExecutor, initialDelay, interval, mcpSessions); } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/util/JsonParser.java
arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/util/JsonParser.java
package com.taobao.arthas.mcp.server.util; import com.alibaba.fastjson2.JSON; import com.alibaba.fastjson2.filter.ValueFilter; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.json.JsonMapper; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.reflect.Type; import java.math.BigDecimal; import java.util.concurrent.CopyOnWriteArrayList; import java.util.List; /** * Utilities to perform parsing operations between JSON and Java. */ public final class JsonParser { private static final Logger logger = LoggerFactory.getLogger(JsonParser.class); private static final ObjectMapper OBJECT_MAPPER = createObjectMapper(); private static final List<ValueFilter> JSON_FILTERS = new CopyOnWriteArrayList<>(); /** * Register a custom JSON value filter */ public static void registerFilter(ValueFilter filter) { if (filter != null) { JSON_FILTERS.add(filter); } } /** * Clear all registered filters */ public static void clearFilters() { JSON_FILTERS.clear(); } private static ObjectMapper createObjectMapper() { return JsonMapper.builder() .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) .disable(SerializationFeature.FAIL_ON_EMPTY_BEANS) .addModule(new JavaTimeModule()) .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) .build(); } private JsonParser() { } public static ObjectMapper getObjectMapper() { return OBJECT_MAPPER; } public static <T> T fromJson(String json, Class<T> type) { Assert.notNull(json, "json cannot be null"); Assert.notNull(type, "type cannot be null"); try { return JSON.parseObject(json, type); } catch (Exception ex) { try { return OBJECT_MAPPER.readValue(json, type); } catch (JsonProcessingException jacksonEx) { throw new IllegalStateException("Conversion from JSON to " + type.getName() + " failed", ex); } } } public static <T> T fromJson(String json, Type type) { Assert.notNull(json, "json cannot be null"); Assert.notNull(type, "type cannot be null"); try { return JSON.parseObject(json, type); } catch (Exception ex) { try { return OBJECT_MAPPER.readValue(json, OBJECT_MAPPER.constructType(type)); } catch (JsonProcessingException jacksonEx) { throw new IllegalStateException("Conversion from JSON to " + type.getTypeName() + " failed", ex); } } } public static <T> T fromJson(String json, TypeReference<T> type) { Assert.notNull(json, "json cannot be null"); Assert.notNull(type, "type cannot be null"); try { return OBJECT_MAPPER.readValue(json, type); } catch (JsonProcessingException ex) { throw new IllegalStateException("Conversion from JSON to " + type.getType().getTypeName() + " failed", ex); } } /** * Converts a Java object to a JSON string. */ public static String toJson(Object object) { if (object == null) { return "null"; } try { String result; if (JSON_FILTERS.isEmpty()) { result = JSON.toJSONString(object); } else { result = JSON.toJSONString(object, JSON_FILTERS.toArray(new ValueFilter[0])); } return (result != null) ? result : "{}"; } catch (Exception ex) { logger.warn("FastJSON2 with MCP filter serialization failed for {}, falling back to Jackson: {}", object.getClass().getSimpleName(), ex.getMessage()); try { String result = OBJECT_MAPPER.writeValueAsString(object); return (result != null) ? result : "{}"; } catch (JsonProcessingException jacksonEx) { logger.error("Both FastJSON2 and Jackson serialization failed", ex); return "{\"error\":\"Serialization failed\"}"; } } } public static Object toTypedObject(Object value, Class<?> type) { if (value == null) { throw new IllegalArgumentException("value cannot be null"); } if (type == null) { throw new IllegalArgumentException("type cannot be null"); } Class<?> javaType = resolvePrimitiveIfNecessary(type); if (javaType == String.class) { return value.toString(); } else if (javaType == Byte.class) { return Byte.parseByte(value.toString()); } else if (javaType == Integer.class) { BigDecimal bigDecimal = new BigDecimal(value.toString()); return bigDecimal.intValueExact(); } else if (javaType == Short.class) { return Short.parseShort(value.toString()); } else if (javaType == Long.class) { BigDecimal bigDecimal = new BigDecimal(value.toString()); return bigDecimal.longValueExact(); } else if (javaType == Double.class) { return Double.parseDouble(value.toString()); } else if (javaType == Float.class) { return Float.parseFloat(value.toString()); } else if (javaType == Boolean.class) { return Boolean.parseBoolean(value.toString()); } else if (javaType == Character.class) { String s = value.toString(); if (s.length() == 1) { return s.charAt(0); } throw new IllegalArgumentException("Cannot convert to char: " + value); } else if (javaType.isEnum()) { @SuppressWarnings("unchecked") Class<Enum> enumType = (Class<Enum>) javaType; return Enum.valueOf(enumType, value.toString()); } String json = JsonParser.toJson(value); return JsonParser.fromJson(json, javaType); } public static Class<?> resolvePrimitiveIfNecessary(Class<?> type) { if (type.isPrimitive()) { return Utils.getWrapperClassForPrimitive(type); } return type; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/util/McpAuthExtractor.java
arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/util/McpAuthExtractor.java
package com.taobao.arthas.mcp.server.util; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.util.AttributeKey; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Utility class for extracting authentication information from Netty context and HTTP headers. */ public class McpAuthExtractor { private static final Logger logger = LoggerFactory.getLogger(McpAuthExtractor.class); /** * String key for MCP transport context */ public static final String MCP_AUTH_SUBJECT_KEY = "mcp.auth.subject"; public static final String MCP_USER_ID_KEY = "mcp.user.id"; public static final String USER_ID_HEADER = "X-User-Id"; /** * AttributeKey for Netty channel */ public static final AttributeKey<Object> CHANNEL_AUTH_SUBJECT_KEY = AttributeKey.valueOf("mcp.auth.subject"); public static final AttributeKey<String> CHANNEL_USER_ID_KEY = AttributeKey.valueOf("mcp.user.id"); public static final AttributeKey<Object> SUBJECT_ATTRIBUTE_KEY = AttributeKey.valueOf("arthas.auth.subject"); /** * Extract auth subject from ChannelHandlerContext */ public static Object extractAuthSubjectFromContext(ChannelHandlerContext ctx) { if (ctx == null || ctx.channel() == null) { return null; } try { Object subject = ctx.channel().attr(SUBJECT_ATTRIBUTE_KEY).get(); if (subject != null) { logger.debug("Extracted auth subject from channel context: {}", subject.getClass().getSimpleName()); return subject; } } catch (Exception e) { logger.debug("Failed to extract auth subject from context: {}", e.getMessage()); } return null; } /** * Extract user ID from HTTP request headers */ public static String extractUserIdFromRequest(FullHttpRequest request) { if (request == null) { return null; } String userId = request.headers().get(USER_ID_HEADER); if (userId != null && !userId.trim().isEmpty()) { logger.debug("Extracted userId from HTTP header {}: {}", USER_ID_HEADER, userId); return userId.trim(); } return null; } /** * Extract user ID from channel attributes */ public static String extractUserId(Channel channel) { if (channel == null) { return null; } return channel.attr(CHANNEL_USER_ID_KEY).get(); } /** * Set user ID to channel attributes */ public static void setUserId(Channel channel, String userId) { if (channel != null && userId != null) { channel.attr(CHANNEL_USER_ID_KEY).set(userId); } } /** * Extract auth subject from channel attributes */ public static Object extractAuthSubject(Channel channel) { if (channel == null) { return null; } return channel.attr(CHANNEL_AUTH_SUBJECT_KEY).get(); } /** * Set auth subject to channel attributes */ public static void setAuthSubject(Channel channel, Object subject) { if (channel != null && subject != null) { channel.attr(CHANNEL_AUTH_SUBJECT_KEY).set(subject); } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/session/ArthasCommandSessionManager.java
arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/session/ArthasCommandSessionManager.java
package com.taobao.arthas.mcp.server.session; import com.taobao.arthas.mcp.server.CommandExecutor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; /** * Manager for MCP-to-Command session bindings. * Handles the lifecycle of command sessions associated with MCP sessions. */ public class ArthasCommandSessionManager { private static final Logger logger = LoggerFactory.getLogger(ArthasCommandSessionManager.class); // Arthas 默认 session 超时时间是 30 分钟,这里设置一个稍短的时间作为预判断 // 如果距离上次访问超过这个时间,认为 session 可能已过期,主动重建 private static final long SESSION_EXPIRY_THRESHOLD_MS = 25 * 60 * 1000; // 25 分钟 private final CommandExecutor commandExecutor; private final ConcurrentHashMap<String, CommandSessionBinding> sessionBindings = new ConcurrentHashMap<>(); public ArthasCommandSessionManager(CommandExecutor commandExecutor) { this.commandExecutor = commandExecutor; } public static class CommandSessionBinding { private final String mcpSessionId; private final String arthasSessionId; private final String consumerId; private final long createdTime; private volatile long lastAccessTime; public CommandSessionBinding(String mcpSessionId, String arthasSessionId, String consumerId) { this.mcpSessionId = mcpSessionId; this.arthasSessionId = arthasSessionId; this.consumerId = consumerId; this.createdTime = System.currentTimeMillis(); this.lastAccessTime = this.createdTime; } public String getMcpSessionId() { return mcpSessionId; } public String getArthasSessionId() { return arthasSessionId; } public String getConsumerId() { return consumerId; } public long getCreatedTime() { return createdTime; } public long getLastAccessTime() { return lastAccessTime; } public void updateAccessTime() { this.lastAccessTime = System.currentTimeMillis(); } } public CommandSessionBinding createCommandSession(String mcpSessionId) { Map<String, Object> result = commandExecutor.createSession(); CommandSessionBinding binding = new CommandSessionBinding( mcpSessionId, (String) result.get("sessionId"), (String) result.get("consumerId") ); return binding; } /** * 获取命令执行session,支持认证信息 * * @param mcpSessionId MCP session ID * @param authSubject 认证主体对象,可以为null * @return CommandSessionBinding */ public CommandSessionBinding getCommandSession(String mcpSessionId, Object authSubject) { CommandSessionBinding binding = sessionBindings.get(mcpSessionId); if (binding == null) { binding = createCommandSession(mcpSessionId); sessionBindings.put(mcpSessionId, binding); logger.debug("Created new command session: MCP={}, Arthas={}", mcpSessionId, binding.getArthasSessionId()); } else if (!isSessionValid(binding)) { logger.info("Session expired, recreating: MCP={}, Arthas={}", mcpSessionId, binding.getArthasSessionId()); try { commandExecutor.closeSession(binding.getArthasSessionId()); } catch (Exception e) { logger.debug("Failed to close expired session (may already be cleaned up): {}", e.getMessage()); } CommandSessionBinding newBinding = createCommandSession(mcpSessionId); sessionBindings.put(mcpSessionId, newBinding); logger.info("Recreated command session: MCP={}, Old Arthas={}, New Arthas={}", mcpSessionId, binding.getArthasSessionId(), newBinding.getArthasSessionId()); binding = newBinding; } else { logger.debug("Using existing valid session: MCP={}, Arthas={}", mcpSessionId, binding.getArthasSessionId()); } binding.updateAccessTime(); if (authSubject != null) { try { commandExecutor.setSessionAuth(binding.getArthasSessionId(), authSubject); logger.debug("Applied auth to Arthas session: MCP={}, Arthas={}", mcpSessionId, binding.getArthasSessionId()); } catch (Exception e) { logger.warn("Failed to apply auth to session: MCP={}, Arthas={}, error={}", mcpSessionId, binding.getArthasSessionId(), e.getMessage()); } } return binding; } /** * 检查session是否有效 * 通过尝试获取结果来验证session和consumer是否仍然存在 */ private boolean isSessionValid(CommandSessionBinding binding) { long timeSinceLastAccess = System.currentTimeMillis() - binding.getLastAccessTime(); if (timeSinceLastAccess > SESSION_EXPIRY_THRESHOLD_MS) { logger.debug("Session possibly expired (inactive for {} ms): MCP={}, Arthas={}", timeSinceLastAccess, binding.getMcpSessionId(), binding.getArthasSessionId()); return false; } return true; } public void closeCommandSession(String mcpSessionId) { CommandSessionBinding binding = sessionBindings.remove(mcpSessionId); if (binding != null) { commandExecutor.closeSession(binding.getArthasSessionId()); logger.debug("Closed command session: MCP={}, Arthas={}", mcpSessionId, binding.getArthasSessionId()); } } public void closeAllSessions() { sessionBindings.keySet().forEach(this::closeCommandSession); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/session/ArthasCommandContext.java
arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/session/ArthasCommandContext.java
package com.taobao.arthas.mcp.server.session; import com.taobao.arthas.mcp.server.CommandExecutor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * Command execution context for MCP server. * Manages command execution lifecycle and result collection. */ public class ArthasCommandContext { private static final Logger logger = LoggerFactory.getLogger(ArthasCommandContext.class); private static final long DEFAULT_SYNC_TIMEOUT = 30000L; private final CommandExecutor commandExecutor; private final ArthasCommandSessionManager.CommandSessionBinding binding; private volatile boolean executionComplete = false; private final List<Object> results = new CopyOnWriteArrayList<>(); private final Lock resultLock = new ReentrantLock(); public ArthasCommandContext(CommandExecutor commandExecutor) { this.commandExecutor = Objects.requireNonNull(commandExecutor, "commandExecutor cannot be null"); this.binding = null; } public ArthasCommandContext(CommandExecutor commandExecutor, ArthasCommandSessionManager.CommandSessionBinding binding) { this.commandExecutor = Objects.requireNonNull(commandExecutor, "commandExecutor cannot be null"); this.binding = binding; } public CommandExecutor getCommandExecutor() { return commandExecutor; } public String getSessionId() { return binding != null ? binding.getArthasSessionId() : null; } /** * Alias for getSessionId() for compatibility */ public String getArthasSessionId() { requireSessionSupport(); return binding.getArthasSessionId(); } private void requireSessionSupport() { if (binding == null) { throw new IllegalStateException("Session-based operations are not supported in temporary mode. " + "Use ArthasCommandContext(CommandExecutor, CommandSessionBinding) constructor to enable session support."); } } public String getConsumerId() { return binding != null ? binding.getConsumerId() : null; } public ArthasCommandSessionManager.CommandSessionBinding getBinding() { return binding; } public boolean isExecutionComplete() { return executionComplete; } public void setExecutionComplete(boolean executionComplete) { this.executionComplete = executionComplete; } public void addResult(Object result) { results.add(result); } public List<Object> getResults() { return results; } public void clearResults() { results.clear(); } public Lock getResultLock() { return resultLock; } /** * Execute command synchronously with default timeout */ public Map<String, Object> executeSync(String commandLine) { return executeSync(commandLine, DEFAULT_SYNC_TIMEOUT); } /** * Execute command synchronously with specified timeout */ public Map<String, Object> executeSync(String commandLine, long timeout) { return commandExecutor.executeSync(commandLine, timeout); } /** * Execute command synchronously with auth subject */ public Map<String, Object> executeSync(String commandStr, Object authSubject) { return commandExecutor.executeSync(commandStr, DEFAULT_SYNC_TIMEOUT, null, authSubject, null); } /** * Execute command synchronously with auth subject and userId * * @param commandStr 命令行 * @param authSubject 认证主体 * @param userId 用户 ID,用于统计上报 * @return 执行结果 */ public Map<String, Object> executeSync(String commandStr, Object authSubject, String userId) { return commandExecutor.executeSync(commandStr, DEFAULT_SYNC_TIMEOUT, null, authSubject, userId); } /** * Execute command asynchronously */ public Map<String, Object> executeAsync(String commandLine) { requireSessionSupport(); return commandExecutor.executeAsync(commandLine, binding.getArthasSessionId()); } /** * Pull command execution results */ public Map<String, Object> pullResults() { requireSessionSupport(); return commandExecutor.pullResults(binding.getArthasSessionId(), binding.getConsumerId()); } /** * Interrupt the current job */ public Map<String, Object> interruptJob() { requireSessionSupport(); return commandExecutor.interruptJob(binding.getArthasSessionId()); } /** * Set session userId for statistics reporting * * @param userId 用户 ID */ public void setSessionUserId(String userId) { if (binding != null && userId != null) { commandExecutor.setSessionUserId(binding.getArthasSessionId(), userId); logger.debug("Set userId for session {}: {}", binding.getArthasSessionId(), userId); } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/spec/McpServerTransportProvider.java
arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/spec/McpServerTransportProvider.java
/* * Copyright 2024-2024 the original author or authors. */ package com.taobao.arthas.mcp.server.protocol.spec; import com.taobao.arthas.mcp.server.protocol.server.handler.McpStreamableHttpRequestHandler; import java.util.concurrent.CompletableFuture; /** * Provides the abstraction for server-side transport providers in MCP protocol. * Defines methods for session factory setup, client notification, and graceful shutdown. * * @author Yeaury */ public interface McpServerTransportProvider { CompletableFuture<Void> notifyClients(String method, Object params); CompletableFuture<Void> closeGracefully(); default void close() { closeGracefully(); } McpStreamableHttpRequestHandler getMcpRequestHandler(); }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/spec/DefaultMcpStreamableServerSessionFactory.java
arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/spec/DefaultMcpStreamableServerSessionFactory.java
/* * Copyright 2024-2024 the original author or authors. */ package com.taobao.arthas.mcp.server.protocol.spec; import com.taobao.arthas.mcp.server.CommandExecutor; import com.taobao.arthas.mcp.server.protocol.server.McpInitRequestHandler; import com.taobao.arthas.mcp.server.protocol.server.McpNotificationHandler; import com.taobao.arthas.mcp.server.protocol.server.McpRequestHandler; import com.taobao.arthas.mcp.server.protocol.server.store.InMemoryEventStore; import java.time.Duration; import java.util.Map; import java.util.UUID; import java.util.concurrent.CompletableFuture; /** * Default implementation of the streamable server session factory. * This factory creates new MCP streamable server sessions with the provided configuration. * */ public class DefaultMcpStreamableServerSessionFactory implements McpStreamableServerSession.Factory { private final Duration requestTimeout; private final McpInitRequestHandler mcpInitRequestHandler; private final Map<String, McpRequestHandler<?>> requestHandlers; private final Map<String, McpNotificationHandler> notificationHandlers; private final CommandExecutor commandExecutor; public DefaultMcpStreamableServerSessionFactory(Duration requestTimeout, McpInitRequestHandler mcpInitRequestHandler, Map<String, McpRequestHandler<?>> requestHandlers, Map<String, McpNotificationHandler> notificationHandlers, CommandExecutor commandExecutor) { this.requestTimeout = requestTimeout; this.mcpInitRequestHandler = mcpInitRequestHandler; this.requestHandlers = requestHandlers; this.notificationHandlers = notificationHandlers; this.commandExecutor = commandExecutor; } @Override public McpStreamableServerSession.McpStreamableServerSessionInit startSession( McpSchema.InitializeRequest initializeRequest) { // Create a new session with a unique ID McpStreamableServerSession session = new McpStreamableServerSession( UUID.randomUUID().toString(), initializeRequest.getCapabilities(), initializeRequest.getClientInfo(), requestTimeout, requestHandlers, notificationHandlers, commandExecutor, new InMemoryEventStore()); // Handle the initialization request CompletableFuture<McpSchema.InitializeResult> initResult = this.mcpInitRequestHandler.handle(initializeRequest); return new McpStreamableServerSession.McpStreamableServerSessionInit(session, initResult); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/spec/ProtocolVersions.java
arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/spec/ProtocolVersions.java
package com.taobao.arthas.mcp.server.protocol.spec; public interface ProtocolVersions { /** * MCP protocol version for 2024-11-05. * https://modelcontextprotocol.io/specification/2024-11-05 */ String MCP_2024_11_05 = "2024-11-05"; /** * MCP protocol version for 2025-03-26. * https://modelcontextprotocol.io/specification/2025-03-26 */ String MCP_2025_03_26 = "2025-03-26"; /** * MCP protocol version for 2025-06-18. * https://modelcontextprotocol.io/specification/2025-06-18 */ String MCP_2025_06_18 = "2025-06-18"; }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/spec/EventStore.java
arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/spec/EventStore.java
package com.taobao.arthas.mcp.server.protocol.spec; import java.time.Instant; import java.util.List; import java.util.function.Consumer; import java.util.stream.Stream; /** * EventStore interface for storing and replaying JSON-RPC events. * Supports event persistence and stream resumability for MCP Streamable HTTP protocol. * * @author Yeaury */ public interface EventStore { class StoredEvent { private final String eventId; private final String sessionId; private final McpSchema.JSONRPCMessage message; private final Instant timestamp; public StoredEvent(String eventId, String sessionId, McpSchema.JSONRPCMessage message, Instant timestamp) { this.eventId = eventId; this.sessionId = sessionId; this.message = message; this.timestamp = timestamp; } public String getEventId() { return eventId; } public String getSessionId() { return sessionId; } public McpSchema.JSONRPCMessage getMessage() { return message; } public Instant getTimestamp() { return timestamp; } } String storeEvent(String sessionId, McpSchema.JSONRPCMessage message); Stream<StoredEvent> getEventsForSession(String sessionId, String fromEventId); void cleanupOldEvents(String sessionId, long maxAge); void removeSessionEvents(String sessionId); }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/spec/McpError.java
arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/spec/McpError.java
/* * Copyright 2024-2024 the original author or authors. */ package com.taobao.arthas.mcp.server.protocol.spec; import com.taobao.arthas.mcp.server.protocol.spec.McpSchema.JSONRPCResponse.JSONRPCError; /** * Exception class for representing JSON-RPC errors in MCP protocol. * * @author Yeaury */ public class McpError extends RuntimeException { private JSONRPCError jsonRpcError; public McpError(JSONRPCError jsonRpcError) { super(jsonRpcError.getMessage()); this.jsonRpcError = jsonRpcError; } public McpError(Object error) { super(error.toString()); } public JSONRPCError getJsonRpcError() { return jsonRpcError; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/spec/McpSchema.java
arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/spec/McpSchema.java
/* * Copyright 2024-2024 the original author or authors. */ package com.taobao.arthas.mcp.server.protocol.spec; import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.annotation.JsonTypeInfo.As; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.taobao.arthas.mcp.server.util.Assert; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.*; /** * Based on the <a href="http://www.jsonrpc.org/specification">JSON-RPC 2.0 specification</a> * and the <a href="https://github.com/modelcontextprotocol/specification/blob/main/schema/2024-11-05/schema.ts"> * Model Context Protocol Schema</a>. * * @author Yeaury */ public final class McpSchema { private static final Logger logger = LoggerFactory.getLogger(McpSchema.class); private McpSchema() { } public static final String LATEST_PROTOCOL_VERSION = ProtocolVersions.MCP_2025_06_18; public static final String JSONRPC_VERSION = "2.0"; // --------------------------- // Method Names // --------------------------- // Lifecycle Methods public static final String METHOD_INITIALIZE = "initialize"; public static final String METHOD_NOTIFICATION_INITIALIZED = "notifications/initialized"; public static final String METHOD_PING = "ping"; public static final String METHOD_NOTIFICATION_PROGRESS = "notifications/progress"; // Tool Methods public static final String METHOD_TOOLS_LIST = "tools/list"; public static final String METHOD_TOOLS_CALL = "tools/call"; public static final String METHOD_NOTIFICATION_TOOLS_LIST_CHANGED = "notifications/tools/list_changed"; // Resources Methods public static final String METHOD_RESOURCES_LIST = "resources/list"; public static final String METHOD_RESOURCES_READ = "resources/read"; public static final String METHOD_NOTIFICATION_RESOURCES_LIST_CHANGED = "notifications/resources/list_changed"; public static final String METHOD_RESOURCES_TEMPLATES_LIST = "resources/templates/list"; // Prompt Methods public static final String METHOD_PROMPT_LIST = "prompts/list"; public static final String METHOD_PROMPT_GET = "prompts/get"; public static final String METHOD_NOTIFICATION_PROMPTS_LIST_CHANGED = "notifications/prompts/list_changed"; // Logging Methods public static final String METHOD_LOGGING_SET_LEVEL = "logging/setLevel"; public static final String METHOD_NOTIFICATION_MESSAGE = "notifications/message"; // Roots Methods public static final String METHOD_ROOTS_LIST = "roots/list"; public static final String METHOD_NOTIFICATION_ROOTS_LIST_CHANGED = "notifications/roots/list_changed"; // Sampling Methods public static final String METHOD_SAMPLING_CREATE_MESSAGE = "sampling/createMessage"; // Elicitation Methods public static final String METHOD_ELICITATION_CREATE = "elicitation/create"; private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); // --------------------------- // JSON-RPC Error Codes // --------------------------- /** * Standard error codes used in MCP JSON-RPC responses. */ public static final class ErrorCodes { /** * The JSON received by the server is invalid. */ public static final int PARSE_ERROR = -32700; /** * The JSON sent is not a valid Request object. */ public static final int INVALID_REQUEST = -32600; /** * The method does not exist or is unavailable. */ public static final int METHOD_NOT_FOUND = -32601; /** * Invalid method parameters. */ public static final int INVALID_PARAMS = -32602; /** * Internal JSON-RPC error. */ public static final int INTERNAL_ERROR = -32603; } public interface Meta { default Map<String, Object> meta() { return null; } } public interface Request extends Meta { default Object progressToken() { Map<String, Object> metadata = meta(); if (metadata != null && metadata.containsKey("progressToken")) { return metadata.get("progressToken"); } return null; } } public interface Result extends Meta { } private static final TypeReference<HashMap<String, Object>> MAP_TYPE_REF = new TypeReference<HashMap<String, Object>>() { }; /** * Deserializes a JSON string into a JSONRPCMessage object. * @param objectMapper The ObjectMapper instance to use for deserialization * @param jsonText The JSON string to deserialize * @return A JSONRPCMessage instance using either the {@link JSONRPCRequest}, * {@link JSONRPCNotification}, or {@link JSONRPCResponse} classes. * @throws IOException If there's an error during deserialization * @throws IllegalArgumentException If the JSON structure doesn't match any known * message type */ public static JSONRPCMessage deserializeJsonRpcMessage(ObjectMapper objectMapper, String jsonText) throws IOException { logger.debug("Received JSON message: {}", jsonText); Map<String, Object> map = objectMapper.readValue(jsonText, MAP_TYPE_REF); // Determine message type based on specific JSON structure if (map.containsKey("method") && map.containsKey("id")) { return objectMapper.convertValue(map, JSONRPCRequest.class); } else if (map.containsKey("method") && !map.containsKey("id")) { return objectMapper.convertValue(map, JSONRPCNotification.class); } else if (map.containsKey("result") || map.containsKey("error")) { return objectMapper.convertValue(map, JSONRPCResponse.class); } throw new IllegalArgumentException("Cannot deserialize JSONRPCMessage: " + jsonText); } // --------------------------- // JSON-RPC Message Types // --------------------------- public interface JSONRPCMessage { String getJsonrpc(); } @JsonInclude(JsonInclude.Include.NON_ABSENT) @JsonIgnoreProperties(ignoreUnknown = true) public static class JSONRPCRequest implements JSONRPCMessage { private final String jsonrpc; private final String method; private final Object id; private final Object params; public JSONRPCRequest( @JsonProperty("jsonrpc") String jsonrpc, @JsonProperty("method") String method, @JsonProperty("id") Object id, @JsonProperty("params") Object params) { this.jsonrpc = jsonrpc; this.method = method; this.id = id; this.params = params; } @Override public String getJsonrpc() { return jsonrpc; } public String getMethod() { return method; } public Object getId() { return id; } public Object getParams() { return params; } } @JsonInclude(JsonInclude.Include.NON_ABSENT) @JsonIgnoreProperties(ignoreUnknown = true) public static class JSONRPCNotification implements JSONRPCMessage { private final String jsonrpc; private final String method; private final Object params; public JSONRPCNotification( @JsonProperty("jsonrpc") String jsonrpc, @JsonProperty("method") String method, @JsonProperty("params") Object params) { this.jsonrpc = jsonrpc; this.method = method; this.params = params; } @Override public String getJsonrpc() { return jsonrpc; } public String getMethod() { return method; } public Object getParams() { return params; } } @JsonInclude(JsonInclude.Include.NON_ABSENT) @JsonIgnoreProperties(ignoreUnknown = true) public static class JSONRPCResponse implements JSONRPCMessage { private final String jsonrpc; private final Object id; private final Object result; private final JSONRPCError error; public JSONRPCResponse( @JsonProperty("jsonrpc") String jsonrpc, @JsonProperty("id") Object id, @JsonProperty("result") Object result, @JsonProperty("error") JSONRPCError error) { this.jsonrpc = jsonrpc; this.id = id; this.result = result; this.error = error; } @Override public String getJsonrpc() { return jsonrpc; } public Object getId() { return id; } public Object getResult() { return result; } public JSONRPCError getError() { return error; } @JsonInclude(JsonInclude.Include.NON_ABSENT) @JsonIgnoreProperties(ignoreUnknown = true) public static class JSONRPCError { private final int code; private final String message; private final Object data; public JSONRPCError( @JsonProperty("code") int code, @JsonProperty("message") String message, @JsonProperty("data") Object data) { this.code = code; this.message = message; this.data = data; } public int getCode() { return code; } public String getMessage() { return message; } public Object getData() { return data; } } } // --------------------------- // Initialization // --------------------------- @JsonInclude(JsonInclude.Include.NON_ABSENT) @JsonIgnoreProperties(ignoreUnknown = true) public static class InitializeRequest implements Request { private final String protocolVersion; private final ClientCapabilities capabilities; private final Implementation clientInfo; public InitializeRequest( @JsonProperty("protocolVersion") String protocolVersion, @JsonProperty("capabilities") ClientCapabilities capabilities, @JsonProperty("clientInfo") Implementation clientInfo) { this.protocolVersion = protocolVersion; this.capabilities = capabilities; this.clientInfo = clientInfo; } public String getProtocolVersion() { return protocolVersion; } public ClientCapabilities getCapabilities() { return capabilities; } public Implementation getClientInfo() { return clientInfo; } } @JsonInclude(JsonInclude.Include.NON_ABSENT) @JsonIgnoreProperties(ignoreUnknown = true) public static class InitializeResult implements Result { private final String protocolVersion; private final ServerCapabilities capabilities; private final Implementation serverInfo; private final String instructions; public InitializeResult( @JsonProperty("protocolVersion") String protocolVersion, @JsonProperty("capabilities") ServerCapabilities capabilities, @JsonProperty("serverInfo") Implementation serverInfo, @JsonProperty("instructions") String instructions) { this.protocolVersion = protocolVersion; this.capabilities = capabilities; this.serverInfo = serverInfo; this.instructions = instructions; } public String getProtocolVersion() { return protocolVersion; } public ServerCapabilities getCapabilities() { return capabilities; } public Implementation getServerInfo() { return serverInfo; } public String getInstructions() { return instructions; } } /** * Clients can implement additional features to enrich connected MCP servers with * additional capabilities. These capabilities can be used to extend the functionality * of the server, or to provide additional information to the server about the * client's capabilities. */ @JsonInclude(JsonInclude.Include.NON_ABSENT) @JsonIgnoreProperties(ignoreUnknown = true) public static class ClientCapabilities { private final Map<String, Object> experimental; private final RootCapabilities roots; private final Sampling sampling; private final Elicitation elicitation; public ClientCapabilities( @JsonProperty("experimental") Map<String, Object> experimental, @JsonProperty("roots") RootCapabilities roots, @JsonProperty("sampling") Sampling sampling, @JsonProperty("elicitation") Elicitation elicitation) { this.experimental = experimental; this.roots = roots; this.sampling = sampling; this.elicitation = elicitation; } /** * Roots define the boundaries of where servers can operate within the filesystem, * allowing them to understand which directories and files they have access to. * Servers can request the list of roots from supporting clients and * receive notifications when that list changes. */ @JsonInclude(JsonInclude.Include.NON_ABSENT) @JsonIgnoreProperties(ignoreUnknown = true) public static class RootCapabilities { private final Boolean listChanged; public RootCapabilities( @JsonProperty("listChanged") Boolean listChanged) { this.listChanged = listChanged; } public Boolean getListChanged() { return listChanged; } } /** * Provides a standardized way for servers to request LLM * sampling ("completions" or "generations") from language * models via clients. This flow allows clients to maintain * control over model access, selection, and permissions * while enabling servers to leverage AI capabilities—with * no server API keys necessary. Servers can request text or * image-based interactions and optionally include context * from MCP servers in their prompts. */ @JsonInclude(JsonInclude.Include.NON_ABSENT) public static class Sampling { } @JsonInclude(JsonInclude.Include.NON_ABSENT) public static class Elicitation { } public Map<String, Object> getExperimental() { return experimental; } public RootCapabilities getRoots() { return roots; } public Sampling getSampling() { return sampling; } public Elicitation getElicitation() { return elicitation; } public static Builder builder() { return new Builder(); } public static class Builder { private Map<String, Object> experimental; private RootCapabilities roots; private Sampling sampling; private Elicitation elicitation; public Builder experimental(Map<String, Object> experimental) { this.experimental = experimental; return this; } public Builder roots(Boolean listChanged) { this.roots = new RootCapabilities(listChanged); return this; } public Builder sampling() { this.sampling = new Sampling(); return this; } public Builder elicitation() { this.elicitation = new Elicitation(); return this; } public ClientCapabilities build() { return new ClientCapabilities(experimental, roots, sampling, elicitation); } } } @JsonInclude(JsonInclude.Include.NON_ABSENT) @JsonIgnoreProperties(ignoreUnknown = true) public static class ServerCapabilities { private final Map<String, Object> experimental; private final LoggingCapabilities logging; private final PromptCapabilities prompts; private final ResourceCapabilities resources; private final ToolCapabilities tools; public ServerCapabilities( @JsonProperty("experimental") Map<String, Object> experimental, @JsonProperty("logging") LoggingCapabilities logging, @JsonProperty("prompts") PromptCapabilities prompts, @JsonProperty("resources") ResourceCapabilities resources, @JsonProperty("tools") ToolCapabilities tools) { this.experimental = experimental; this.logging = logging; this.prompts = prompts; this.resources = resources; this.tools = tools; } public static Builder builder() { return new Builder(); } public static class Builder { private Map<String, Object> experimental; private LoggingCapabilities logging; private PromptCapabilities prompts; private ResourceCapabilities resources; private ToolCapabilities tools; public Builder experimental(Map<String, Object> experimental) { this.experimental = experimental; return this; } public Builder logging(LoggingCapabilities logging) { this.logging = logging; return this; } public Builder prompts(PromptCapabilities prompts) { this.prompts = prompts; return this; } public Builder resources(ResourceCapabilities resources) { this.resources = resources; return this; } public Builder tools(ToolCapabilities tools) { this.tools = tools; return this; } public ServerCapabilities build() { return new ServerCapabilities(experimental, logging, prompts, resources, tools); } } @JsonInclude(JsonInclude.Include.NON_ABSENT) public static class LoggingCapabilities { } @JsonInclude(JsonInclude.Include.NON_ABSENT) public static class PromptCapabilities { private final Boolean listChanged; public PromptCapabilities(@JsonProperty("listChanged") Boolean listChanged) { this.listChanged = listChanged; } public Boolean getListChanged() { return listChanged; } } @JsonInclude(JsonInclude.Include.NON_ABSENT) public static class ResourceCapabilities { private final Boolean subscribe; private final Boolean listChanged; public ResourceCapabilities( @JsonProperty("subscribe") Boolean subscribe, @JsonProperty("listChanged") Boolean listChanged) { this.subscribe = subscribe; this.listChanged = listChanged; } public Boolean getSubscribe() { return subscribe; } public Boolean getListChanged() { return listChanged; } } @JsonInclude(JsonInclude.Include.NON_ABSENT) public static class ToolCapabilities { private final Boolean listChanged; public ToolCapabilities(@JsonProperty("listChanged") Boolean listChanged) { this.listChanged = listChanged; } public Boolean getListChanged() { return listChanged; } } public Map<String, Object> getExperimental() { return experimental; } public LoggingCapabilities getLogging() { return logging; } public PromptCapabilities getPrompts() { return prompts; } public ResourceCapabilities getResources() { return resources; } public ToolCapabilities getTools() { return tools; } } @JsonInclude(JsonInclude.Include.NON_ABSENT) @JsonIgnoreProperties(ignoreUnknown = true) public static class Implementation { private final String name; private final String version; public Implementation( @JsonProperty("name") String name, @JsonProperty("version") String version) { this.name = name; this.version = version; } public String getName() { return name; } public String getVersion() { return version; } } // Existing Enums and Base Types public enum Role { @JsonProperty("user") USER, @JsonProperty("assistant") ASSISTANT } public enum StopReason { @JsonProperty("stop") STOP, @JsonProperty("length") LENGTH, @JsonProperty("content_filter") CONTENT_FILTER } public enum ContextInclusionStrategy { @JsonProperty("none") NONE, @JsonProperty("all") ALL, @JsonProperty("relevant") RELEVANT } // --------------------------- // Resource Interfaces // --------------------------- /** * Base for objects that include optional annotations for the client. The client can * use annotations to inform how objects are used or displayed */ public interface Annotated { Annotations annotations(); } /** * Optional annotations for the client. The client can use annotations to inform how * objects are used or displayed. */ @JsonInclude(JsonInclude.Include.NON_ABSENT) @JsonIgnoreProperties(ignoreUnknown = true) public static class Annotations { private final List<Role> audience; private final Double priority; public Annotations( @JsonProperty("audience") List<Role> audience, @JsonProperty("priority") Double priority) { this.audience = audience; this.priority = priority; } public List<Role> getAudience() { return audience; } public Double getPriority() { return priority; } } /** * A known resource that the server is capable of reading. */ @JsonInclude(JsonInclude.Include.NON_ABSENT) @JsonIgnoreProperties(ignoreUnknown = true) public static class Resource implements Annotated { private final String uri; private final String name; private final String description; private final String mimeType; private final Annotations annotations; public Resource( @JsonProperty("uri") String uri, @JsonProperty("name") String name, @JsonProperty("description") String description, @JsonProperty("mimeType") String mimeType, @JsonProperty("annotations") Annotations annotations) { this.uri = uri; this.name = name; this.description = description; this.mimeType = mimeType; this.annotations = annotations; } @Override public Annotations annotations() { return annotations; } public String getUri() { return uri; } public String getName() { return name; } public String getDescription() { return description; } public String getMimeType() { return mimeType; } } /** * Resource templates allow servers to expose parameterized resources using URI * templates. * * @see <a href="https://datatracker.ietf.org/doc/html/rfc6570">RFC 6570</a> */ @JsonInclude(JsonInclude.Include.NON_ABSENT) @JsonIgnoreProperties(ignoreUnknown = true) public static class ResourceTemplate implements Annotated { private final String uriTemplate; private final String name; private final String description; private final String mimeType; private final Annotations annotations; public ResourceTemplate( @JsonProperty("uriTemplate") String uriTemplate, @JsonProperty("name") String name, @JsonProperty("description") String description, @JsonProperty("mimeType") String mimeType, @JsonProperty("annotations") Annotations annotations) { this.uriTemplate = uriTemplate; this.name = name; this.description = description; this.mimeType = mimeType; this.annotations = annotations; } @Override public Annotations annotations() { return annotations; } public String getUriTemplate() { return uriTemplate; } public String getName() { return name; } public String getDescription() { return description; } public String getMimeType() { return mimeType; } } @JsonInclude(JsonInclude.Include.NON_ABSENT) @JsonIgnoreProperties(ignoreUnknown = true) public static class ListResourcesResult implements Result { private final List<Resource> resources; private final String nextCursor; private final Map<String, Object> meta; public ListResourcesResult( @JsonProperty("resources") List<Resource> resources, @JsonProperty("nextCursor") String nextCursor, @JsonProperty("_meta") Map<String, Object> meta) { this.resources = resources; this.nextCursor = nextCursor; this.meta = meta; } public ListResourcesResult(List<Resource> resources, String nextCursor) { this(resources, nextCursor, null); } public List<Resource> getResources() { return resources; } public String getNextCursor() { return nextCursor; } @Override public Map<String, Object> meta() { return meta; } public Map<String, Object> getMeta() { return meta(); } public Object getProgressToken() { return (meta() != null) ? meta().get("progressToken") : null; } } @JsonInclude(JsonInclude.Include.NON_ABSENT) @JsonIgnoreProperties(ignoreUnknown = true) public static class ListResourceTemplatesResult implements Result { private final List<ResourceTemplate> resourceTemplates; private final String nextCursor; private final Map<String, Object> meta; public ListResourceTemplatesResult( @JsonProperty("resourceTemplates") List<ResourceTemplate> resourceTemplates, @JsonProperty("nextCursor") String nextCursor, @JsonProperty("_meta") Map<String, Object> meta) { this.resourceTemplates = resourceTemplates; this.nextCursor = nextCursor; this.meta = meta; } public ListResourceTemplatesResult(List<ResourceTemplate> resourceTemplates, String nextCursor) { this(resourceTemplates, nextCursor, null); } public List<ResourceTemplate> getResourceTemplates() { return resourceTemplates; } public String getNextCursor() { return nextCursor; } @Override public Map<String, Object> meta() { return meta; } public Map<String, Object> getMeta() { return meta(); } } @JsonInclude(JsonInclude.Include.NON_ABSENT) @JsonIgnoreProperties(ignoreUnknown = true) public static class ReadResourceRequest { private final String uri; public ReadResourceRequest( @JsonProperty("uri") String uri) { this.uri = uri; } public String getUri() { return uri; } } @JsonInclude(JsonInclude.Include.NON_ABSENT) @JsonIgnoreProperties(ignoreUnknown = true) public static class ReadResourceResult implements Result { private final List<ResourceContents> contents; private final Map<String, Object> meta; public ReadResourceResult( @JsonProperty("contents") List<ResourceContents> contents, @JsonProperty("_meta") Map<String, Object> meta) { this.contents = contents; this.meta = meta; } public ReadResourceResult(List<ResourceContents> contents) { this(contents, null); } public List<ResourceContents> getContents() { return contents; } @Override public Map<String, Object> meta() { return meta; } public Map<String, Object> getMeta() { return meta(); } } /** * Sent from the client to request resources/updated notifications from the server * whenever a particular resource changes. */ @JsonInclude(JsonInclude.Include.NON_ABSENT) @JsonIgnoreProperties(ignoreUnknown = true) public static class SubscribeRequest { private final String uri; public SubscribeRequest( @JsonProperty("uri") String uri) { this.uri = uri; } public String getUri() { return uri; } } @JsonInclude(JsonInclude.Include.NON_ABSENT) @JsonIgnoreProperties(ignoreUnknown = true) public static class UnsubscribeRequest { private final String uri; public UnsubscribeRequest( @JsonProperty("uri") String uri) { this.uri = uri; } public String getUri() { return uri; } } /** * The contents of a specific resource or sub-resource. */ @JsonTypeInfo(use = JsonTypeInfo.Id.DEDUCTION, include = As.PROPERTY) @JsonSubTypes({ @JsonSubTypes.Type(value = TextResourceContents.class, name = "text"), @JsonSubTypes.Type(value = BlobResourceContents.class, name = "blob") }) public interface ResourceContents { /** * The URI of this resource. * @return the URI of this resource. */ String uri(); /** * The MIME type of this resource. * @return the MIME type of this resource. */ String mimeType(); } /** * Text contents of a resource. */ @JsonInclude(JsonInclude.Include.NON_ABSENT) @JsonIgnoreProperties(ignoreUnknown = true) public static class TextResourceContents implements ResourceContents { private final String uri; private final String mimeType; private final String text; public TextResourceContents( @JsonProperty("uri") String uri, @JsonProperty("mimeType") String mimeType, @JsonProperty("text") String text) { this.uri = uri; this.mimeType = mimeType; this.text = text; } @Override public String uri() { return uri; } @Override public String mimeType() { return mimeType; } public String getText() { return text; } } /** * Binary contents of a resource. * * This must only be set if the resource can actually be represented as binary data * (not text). */ @JsonInclude(JsonInclude.Include.NON_ABSENT) @JsonIgnoreProperties(ignoreUnknown = true) public static class BlobResourceContents implements ResourceContents { private final String uri; private final String mimeType; private final String blob; public BlobResourceContents( @JsonProperty("uri") String uri, @JsonProperty("mimeType") String mimeType, @JsonProperty("blob") String blob) { this.uri = uri; this.mimeType = mimeType; this.blob = blob; } @Override public String uri() { return uri; } @Override public String mimeType() { return mimeType; } public String getBlob() { return blob; } } // --------------------------- // Prompt Interfaces // --------------------------- /** * A prompt or prompt template that the server offers. */ @JsonInclude(JsonInclude.Include.NON_ABSENT) @JsonIgnoreProperties(ignoreUnknown = true) public static class Prompt { private final String name; private final String description; private final List<PromptArgument> arguments; public Prompt( @JsonProperty("name") String name, @JsonProperty("description") String description, @JsonProperty("arguments") List<PromptArgument> arguments) { this.name = name; this.description = description; this.arguments = arguments; } public String getName() { return name; } public String getDescription() { return description; } public List<PromptArgument> getArguments() { return arguments; } } /** * Describes an argument that a prompt can accept. */ @JsonInclude(JsonInclude.Include.NON_ABSENT) @JsonIgnoreProperties(ignoreUnknown = true) public static class PromptArgument { private final String name; private final String description; private final Boolean required; public PromptArgument( @JsonProperty("name") String name, @JsonProperty("description") String description, @JsonProperty("required") Boolean required) { this.name = name; this.description = description; this.required = required; } public String getName() { return name; } public String getDescription() { return description; } public Boolean getRequired() { return required; } } /** * Describes a message returned as part of a prompt. * This is similar to `SamplingMessage`, but also supports the embedding of resources * from the MCP server. */ @JsonInclude(JsonInclude.Include.NON_ABSENT) @JsonIgnoreProperties(ignoreUnknown = true) public static class PromptMessage { private final Role role; private final Content content; public PromptMessage( @JsonProperty("role") Role role, @JsonProperty("content") Content content) { this.role = role; this.content = content; } public Role getRole() { return role; } public Content getContent() { return content; } } /** * The server's response to a prompts/list request from the client. */ @JsonInclude(JsonInclude.Include.NON_ABSENT) @JsonIgnoreProperties(ignoreUnknown = true) public static class ListPromptsResult implements Result { private final List<Prompt> prompts; private final String nextCursor; private final Map<String, Object> meta; public ListPromptsResult( @JsonProperty("prompts") List<Prompt> prompts, @JsonProperty("nextCursor") String nextCursor, @JsonProperty("_meta") Map<String, Object> meta) { this.prompts = prompts; this.nextCursor = nextCursor; this.meta = meta; } public ListPromptsResult(List<Prompt> prompts, String nextCursor) { this(prompts, nextCursor, null); } public List<Prompt> getPrompts() { return prompts; } public String getNextCursor() { return nextCursor; } @Override public Map<String, Object> meta() { return meta; } public Map<String, Object> getMeta() { return meta(); } } /** * Used by the client to get a prompt provided by the server. */ @JsonInclude(JsonInclude.Include.NON_ABSENT) @JsonIgnoreProperties(ignoreUnknown = true) public static class GetPromptRequest implements Request { private final String name; private final Map<String, Object> arguments; public GetPromptRequest( @JsonProperty("name") String name, @JsonProperty("arguments") Map<String, Object> arguments) { this.name = name; this.arguments = arguments; } public String getName() { return name; } public Map<String, Object> getArguments() { return arguments; } } /** * The server's response to a prompts/get request from the client. */ @JsonInclude(JsonInclude.Include.NON_ABSENT) @JsonIgnoreProperties(ignoreUnknown = true) public static class GetPromptResult implements Result { private final String description; private final List<PromptMessage> messages; private final Map<String, Object> meta; public GetPromptResult( @JsonProperty("description") String description, @JsonProperty("messages") List<PromptMessage> messages, @JsonProperty("_meta") Map<String, Object> meta) { this.description = description; this.messages = messages; this.meta = meta; } public GetPromptResult(String description, List<PromptMessage> messages) { this(description, messages, null); } public String getDescription() { return description; } public List<PromptMessage> getMessages() { return messages; } @Override public Map<String, Object> meta() { return meta; } public Map<String, Object> getMeta() { return meta(); } } // --------------------------- // Tool Interfaces // --------------------------- /** * The server's response to a tools/list request from the client. */ @JsonInclude(JsonInclude.Include.NON_ABSENT)
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
true
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/spec/McpStreamableServerTransport.java
arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/spec/McpStreamableServerTransport.java
/* * Copyright 2024-2024 the original author or authors. */ package com.taobao.arthas.mcp.server.protocol.spec; import com.fasterxml.jackson.core.type.TypeReference; import java.util.concurrent.CompletableFuture; /** * Marker interface for the server-side MCP streamable transport. * This extends the basic server transport with streamable message sending capabilities. * */ public interface McpStreamableServerTransport extends McpServerTransport { CompletableFuture<Void> sendMessage(McpSchema.JSONRPCMessage message, String messageId); <T> T unmarshalFrom(Object value, TypeReference<T> typeRef); }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/spec/McpServerTransport.java
arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/spec/McpServerTransport.java
/* * Copyright 2024-2024 the original author or authors. */ package com.taobao.arthas.mcp.server.protocol.spec; import io.netty.channel.Channel; /** * Extends McpTransport to provide access to the underlying Netty Channel for server-side transport. * * @author Yeaury */ public interface McpServerTransport extends McpTransport { Channel getChannel(); }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/spec/McpStreamableServerTransportProvider.java
arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/spec/McpStreamableServerTransportProvider.java
/* * Copyright 2024-2024 the original author or authors. */ package com.taobao.arthas.mcp.server.protocol.spec; import java.util.Arrays; import java.util.List; import java.util.concurrent.CompletableFuture; public interface McpStreamableServerTransportProvider extends McpServerTransportProvider { void setSessionFactory(McpStreamableServerSession.Factory sessionFactory); CompletableFuture<Void> notifyClients(String method, Object params); default void close() { this.closeGracefully(); } default List<String> protocolVersions() { return Arrays.asList(ProtocolVersions.MCP_2024_11_05); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/spec/HttpHeaders.java
arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/spec/HttpHeaders.java
/* * Copyright 2024-2024 the original author or authors. */ package com.taobao.arthas.mcp.server.protocol.spec; public interface HttpHeaders { /** * Identifies individual MCP sessions. */ String MCP_SESSION_ID = "mcp-session-id"; /** * Identifies events within an SSE Stream. */ String LAST_EVENT_ID = "last-event-id"; /** * Identifies the MCP protocol version. */ String PROTOCOL_VERSION = "MCP-Protocol-Version"; }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/spec/MissingMcpTransportSession.java
arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/spec/MissingMcpTransportSession.java
/* * Copyright 2024-2024 the original author or authors. */ package com.taobao.arthas.mcp.server.protocol.spec; import com.fasterxml.jackson.core.type.TypeReference; import java.util.concurrent.CompletableFuture; /** * A placeholder implementation of McpLoggableSession that represents a missing or unavailable transport session. * This class is used when no active transport is available but session operations are attempted. */ public class MissingMcpTransportSession implements McpSession { private final String sessionId; public MissingMcpTransportSession(String sessionId) { this.sessionId = sessionId; } @Override public <T> CompletableFuture<T> sendRequest(String method, Object requestParams, TypeReference<T> typeRef) { CompletableFuture<T> future = new CompletableFuture<>(); future.completeExceptionally( new IllegalStateException("Stream unavailable for session " + this.sessionId) ); return future; } @Override public CompletableFuture<Void> sendNotification(String method, Object params) { CompletableFuture<Void> future = new CompletableFuture<>(); future.completeExceptionally( new IllegalStateException("Stream unavailable for session " + this.sessionId) ); return future; } @Override public CompletableFuture<Void> closeGracefully() { return CompletableFuture.completedFuture(null); } @Override public void close() { // Nothing to close for a missing session } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/spec/McpSession.java
arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/spec/McpSession.java
/* * Copyright 2024-2024 the original author or authors. */ package com.taobao.arthas.mcp.server.protocol.spec; import java.util.concurrent.CompletableFuture; import com.fasterxml.jackson.core.type.TypeReference; /** * Represents a server-side MCP session that manages bidirectional JSON-RPC communication with the client. * * @author Yeaury */ public interface McpSession { <T> CompletableFuture<T> sendRequest(String method, Object requestParams, TypeReference<T> typeRef); default CompletableFuture<Void> sendNotification(String method) { return sendNotification(method, null); } CompletableFuture<Void> sendNotification(String method, Object params); CompletableFuture<Void> closeGracefully(); void close(); }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/spec/McpStatelessServerTransport.java
arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/spec/McpStatelessServerTransport.java
/* * Copyright 2024-2024 the original author or authors. */ package com.taobao.arthas.mcp.server.protocol.spec; import com.taobao.arthas.mcp.server.protocol.server.McpStatelessServerHandler; import java.util.Arrays; import java.util.List; import java.util.concurrent.CompletableFuture; public interface McpStatelessServerTransport { void setMcpHandler(McpStatelessServerHandler mcpHandler); default void close() { this.closeGracefully(); } CompletableFuture<Void> closeGracefully(); default List<String> protocolVersions() { return Arrays.asList(ProtocolVersions.MCP_2025_03_26, ProtocolVersions.MCP_2025_06_18); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/spec/McpTransport.java
arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/spec/McpTransport.java
/* * Copyright 2024-2024 the original author or authors. */ package com.taobao.arthas.mcp.server.protocol.spec; import java.util.concurrent.CompletableFuture; import com.fasterxml.jackson.core.type.TypeReference; /** * Defines the transport abstraction for sending messages and unmarshalling data in MCP protocol. * * @author Yeaury */ public interface McpTransport { CompletableFuture<Void> closeGracefully(); default void close() { this.closeGracefully(); } CompletableFuture<Void> sendMessage(McpSchema.JSONRPCMessage message); <T> T unmarshalFrom(Object data, TypeReference<T> typeRef); }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/spec/McpStreamableServerSession.java
arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/spec/McpStreamableServerSession.java
/* * Copyright 2024-2024 the original author or authors. */ package com.taobao.arthas.mcp.server.protocol.spec; import com.fasterxml.jackson.core.type.TypeReference; import com.taobao.arthas.mcp.server.CommandExecutor; import com.taobao.arthas.mcp.server.protocol.server.McpNettyServerExchange; import com.taobao.arthas.mcp.server.protocol.server.McpNotificationHandler; import com.taobao.arthas.mcp.server.protocol.server.McpRequestHandler; import com.taobao.arthas.mcp.server.protocol.server.McpTransportContext; import com.taobao.arthas.mcp.server.session.ArthasCommandContext; import com.taobao.arthas.mcp.server.session.ArthasCommandSessionManager; import com.taobao.arthas.mcp.server.util.Assert; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.time.Duration; import java.util.Map; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Supplier; import java.util.stream.Stream; import static com.taobao.arthas.mcp.server.util.McpAuthExtractor.MCP_AUTH_SUBJECT_KEY; /** * Main implementation of a streamable MCP server session that manages client connections * and handles JSON-RPC communication using CompletableFuture for async operations. */ public class McpStreamableServerSession implements McpSession { private static final Logger logger = LoggerFactory.getLogger(McpStreamableServerSession.class); private final ConcurrentHashMap<Object, McpStreamableServerSessionStream> requestIdToStream = new ConcurrentHashMap<>(); private final String id; private final Duration requestTimeout; private final AtomicLong requestCounter = new AtomicLong(0); private final Map<String, McpRequestHandler<?>> requestHandlers; private final Map<String, McpNotificationHandler> notificationHandlers; private final AtomicReference<McpSchema.ClientCapabilities> clientCapabilities = new AtomicReference<>(); private final AtomicReference<McpSchema.Implementation> clientInfo = new AtomicReference<>(); private final AtomicReference<McpSession> listeningStreamRef; private final MissingMcpTransportSession missingMcpTransportSession; private volatile McpSchema.LoggingLevel minLoggingLevel = McpSchema.LoggingLevel.INFO; private final CommandExecutor commandExecutor; private final ArthasCommandSessionManager commandSessionManager; private final EventStore eventStore; public McpStreamableServerSession(String id, McpSchema.ClientCapabilities clientCapabilities, McpSchema.Implementation clientInfo, Duration requestTimeout, Map<String, McpRequestHandler<?>> requestHandlers, Map<String, McpNotificationHandler> notificationHandlers, CommandExecutor commandExecutor, EventStore eventStore) { this.id = id; this.missingMcpTransportSession = new MissingMcpTransportSession(id); this.listeningStreamRef = new AtomicReference<>(this.missingMcpTransportSession); this.clientCapabilities.lazySet(clientCapabilities); this.clientInfo.lazySet(clientInfo); this.requestTimeout = requestTimeout; this.requestHandlers = requestHandlers; this.notificationHandlers = notificationHandlers; this.commandExecutor = commandExecutor; this.commandSessionManager = new ArthasCommandSessionManager(commandExecutor); this.eventStore = eventStore; } /** * Sets the minimum logging level for this session. * @param minLoggingLevel the minimum logging level */ public void setMinLoggingLevel(McpSchema.LoggingLevel minLoggingLevel) { Assert.notNull(minLoggingLevel, "minLoggingLevel must not be null"); this.minLoggingLevel = minLoggingLevel; } /** * Checks if notifications for the given logging level are allowed. * @param loggingLevel the logging level to check * @return true if notifications for this level are allowed */ public boolean isNotificationForLevelAllowed(McpSchema.LoggingLevel loggingLevel) { return loggingLevel.level() >= this.minLoggingLevel.level(); } public String getId() { return this.id; } private String generateRequestId() { return this.id + "-" + this.requestCounter.getAndIncrement(); } @Override public <T> CompletableFuture<T> sendRequest(String method, Object requestParams, TypeReference<T> typeRef) { McpSession listeningStream = this.listeningStreamRef.get(); return listeningStream.sendRequest(method, requestParams, typeRef); } @Override public CompletableFuture<Void> sendNotification(String method, Object params) { McpSession listeningStream = this.listeningStreamRef.get(); return listeningStream.sendNotification(method, params); } public CompletableFuture<Void> delete() { return this.closeGracefully().thenRun(() -> { try { eventStore.removeSessionEvents(this.id); commandSessionManager.closeCommandSession(this.id); } catch (Exception e) { logger.warn("Failed to clear session during deletion: {}", e.getMessage()); } }); } public McpStreamableServerSessionStream listeningStream(McpStreamableServerTransport transport) { McpStreamableServerSessionStream listeningStream = new McpStreamableServerSessionStream(transport); this.listeningStreamRef.set(listeningStream); return listeningStream; } /** * 重播会话事件,从指定的最后事件ID之后开始 * * @param lastEventId 最后一个事件ID,如果为null则从头开始重播 * @return 事件消息流 */ public Stream<McpSchema.JSONRPCMessage> replay(Object lastEventId) { String lastEventIdStr = lastEventId != null ? lastEventId.toString() : null; return eventStore.getEventsForSession(this.id, lastEventIdStr) .map(EventStore.StoredEvent::getMessage); } public CompletableFuture<Void> responseStream(McpSchema.JSONRPCRequest jsonrpcRequest, McpStreamableServerTransport transport, McpTransportContext transportContext) { McpStreamableServerSessionStream stream = new McpStreamableServerSessionStream(transport); McpRequestHandler<?> requestHandler = this.requestHandlers.get(jsonrpcRequest.getMethod()); if (requestHandler == null) { MethodNotFoundError error = getMethodNotFoundError(jsonrpcRequest.getMethod()); McpSchema.JSONRPCResponse errorResponse = new McpSchema.JSONRPCResponse(McpSchema.JSONRPC_VERSION, jsonrpcRequest.getId(), null, new McpSchema.JSONRPCResponse.JSONRPCError(McpSchema.ErrorCodes.METHOD_NOT_FOUND, error.getMessage(), error.getData())); // 存储错误响应 try { eventStore.storeEvent(this.id, errorResponse); } catch (Exception e) { logger.warn("Failed to store error response event: {}", e.getMessage()); } return transport.sendMessage(errorResponse, null) .thenCompose(v -> transport.closeGracefully()); } ArthasCommandContext commandContext = createCommandContext(transportContext.get(MCP_AUTH_SUBJECT_KEY)); return requestHandler .handle(new McpNettyServerExchange(this.id, stream, clientCapabilities.get(), clientInfo.get(), transportContext), commandContext, jsonrpcRequest.getParams()) .thenApply(result -> new McpSchema.JSONRPCResponse(McpSchema.JSONRPC_VERSION, jsonrpcRequest.getId(), result, null)) .thenCompose(response -> transport.sendMessage(response, null)) .thenCompose(v -> transport.closeGracefully()); } public CompletableFuture<Void> accept(McpSchema.JSONRPCNotification notification, McpTransportContext transportContext) { McpNotificationHandler notificationHandler = this.notificationHandlers.get(notification.getMethod()); if (notificationHandler == null) { logger.error("No handler registered for notification method: {}", notification.getMethod()); return CompletableFuture.completedFuture(null); } ArthasCommandContext commandContext = createCommandContext(transportContext.get(MCP_AUTH_SUBJECT_KEY)); McpSession listeningStream = this.listeningStreamRef.get(); return notificationHandler.handle(new McpNettyServerExchange(this.id, listeningStream, this.clientCapabilities.get(), this.clientInfo.get(), transportContext), commandContext, notification.getParams()); } public CompletableFuture<Void> accept(McpSchema.JSONRPCResponse response) { McpStreamableServerSessionStream stream = this.requestIdToStream.get(response.getId()); if (stream == null) { CompletableFuture<Void> f = CompletableFuture.completedFuture(null); f.completeExceptionally(new McpError("Unexpected response for unknown id " + response.getId())); return f; } CompletableFuture<McpSchema.JSONRPCResponse> future = stream.pendingResponses.remove(response.getId()); if (future == null) { CompletableFuture<Void> f = CompletableFuture.completedFuture(null); f.completeExceptionally(new McpError("Unexpected response for unknown id " + response.getId())); return f; } else { future.complete(response); } return CompletableFuture.completedFuture(null); } public class MethodNotFoundError { private final String method; private final String message; private final Object data; public MethodNotFoundError(String method, String message, Object data) { this.method = method; this.message = message; this.data = data; } public String getMethod() { return method; } public String getMessage() { return message; } public Object getData() { return data; } } private MethodNotFoundError getMethodNotFoundError(String method) { return new MethodNotFoundError(method, "Method not found: " + method, null); } @Override public CompletableFuture<Void> closeGracefully() { McpSession listeningStream = this.listeningStreamRef.getAndSet(missingMcpTransportSession); // 清理 Arthas 命令会话 try { commandSessionManager.closeCommandSession(this.id); logger.debug("Successfully closed command session during graceful shutdown: {}", this.id); } catch (Exception e) { logger.warn("Failed to close command session during graceful shutdown: {}", e.getMessage()); } return listeningStream.closeGracefully(); // TODO: Also close all the open streams } @Override public void close() { McpSession listeningStream = this.listeningStreamRef.getAndSet(missingMcpTransportSession); // 清理 Arthas 命令会话 try { commandSessionManager.closeCommandSession(this.id); logger.debug("Successfully closed command session during close: {}", this.id); } catch (Exception e) { logger.warn("Failed to close command session during close: {}", e.getMessage()); } if (listeningStream != null) { listeningStream.close(); } // TODO: Also close all open streams } public interface Factory { McpStreamableServerSessionInit startSession(McpSchema.InitializeRequest initializeRequest); } public static class McpStreamableServerSessionInit { private final McpStreamableServerSession session; private final CompletableFuture<McpSchema.InitializeResult> initResult; public McpStreamableServerSessionInit( McpStreamableServerSession session, CompletableFuture<McpSchema.InitializeResult> initResult) { this.session = session; this.initResult = initResult; } public McpStreamableServerSession session() { return session; } public CompletableFuture<McpSchema.InitializeResult> initResult() { return initResult; } } public final class McpStreamableServerSessionStream implements McpSession { private final ConcurrentHashMap<Object, CompletableFuture<McpSchema.JSONRPCResponse>> pendingResponses = new ConcurrentHashMap<>(); private final McpStreamableServerTransport transport; private final String transportId; private final Supplier<String> uuidGenerator; public McpStreamableServerSessionStream(McpStreamableServerTransport transport) { this.transport = transport; this.transportId = UUID.randomUUID().toString(); // This ID design allows for a constant-time extraction of the history by // precisely identifying the SSE stream using the first component this.uuidGenerator = () -> this.transportId + "_" + UUID.randomUUID(); } @Override public <T> CompletableFuture<T> sendRequest(String method, Object requestParams, TypeReference<T> typeRef) { String requestId = McpStreamableServerSession.this.generateRequestId(); McpStreamableServerSession.this.requestIdToStream.put(requestId, this); CompletableFuture<McpSchema.JSONRPCResponse> responseFuture = new CompletableFuture<>(); this.pendingResponses.put(requestId, responseFuture); McpSchema.JSONRPCRequest jsonrpcRequest = new McpSchema.JSONRPCRequest(McpSchema.JSONRPC_VERSION, method, requestId, requestParams); String messageId = null; // 存储发送的请求到事件存储 try { messageId = McpStreamableServerSession.this.eventStore.storeEvent( McpStreamableServerSession.this.id, jsonrpcRequest); } catch (Exception e) { logger.warn("Failed to store outbound request event: {}", e.getMessage()); } // Send the message this.transport.sendMessage(jsonrpcRequest, messageId).exceptionally(ex -> { responseFuture.completeExceptionally(ex); return null; }); return responseFuture.handle((jsonRpcResponse, throwable) -> { // Cleanup this.pendingResponses.remove(requestId); McpStreamableServerSession.this.requestIdToStream.remove(requestId); if (throwable != null) { if (throwable instanceof RuntimeException) { throw (RuntimeException) throwable; } throw new RuntimeException(throwable); } if (jsonRpcResponse.getError() != null) { throw new RuntimeException(new McpError(jsonRpcResponse.getError())); } else { if (typeRef.getType().equals(Void.class)) { return null; } else { return this.transport.unmarshalFrom(jsonRpcResponse.getResult(), typeRef); } } }); } @Override public CompletableFuture<Void> sendNotification(String method, Object params) { McpSchema.JSONRPCNotification jsonrpcNotification = new McpSchema.JSONRPCNotification( McpSchema.JSONRPC_VERSION, method, params); String messageId = null; try { messageId = McpStreamableServerSession.this.eventStore.storeEvent( McpStreamableServerSession.this.id, jsonrpcNotification); } catch (Exception e) { logger.warn("Failed to store outbound notification event: {}", e.getMessage()); } return this.transport.sendMessage(jsonrpcNotification, messageId); } @Override public CompletableFuture<Void> closeGracefully() { // Complete all pending responses with error this.pendingResponses.values().forEach(future -> future.completeExceptionally(new RuntimeException("Stream closed"))); this.pendingResponses.clear(); // If this was the generic stream, reset it McpStreamableServerSession.this.listeningStreamRef.compareAndSet(this, McpStreamableServerSession.this.missingMcpTransportSession); McpStreamableServerSession.this.requestIdToStream.values().removeIf(this::equals); return this.transport.closeGracefully(); } @Override public void close() { this.pendingResponses.values().forEach(future -> future.completeExceptionally(new RuntimeException("Stream closed"))); this.pendingResponses.clear(); // If this was the generic stream, reset it McpStreamableServerSession.this.listeningStreamRef.compareAndSet(this, McpStreamableServerSession.this.missingMcpTransportSession); McpStreamableServerSession.this.requestIdToStream.values().removeIf(this::equals); this.transport.close(); } } /** * 创建命令执行上下文 * * @return 命令执行上下文 */ private ArthasCommandContext createCommandContext(Object authSubject) { ArthasCommandSessionManager.CommandSessionBinding binding = commandSessionManager.getCommandSession(this.id, authSubject); return new ArthasCommandContext(commandExecutor, binding); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/server/McpNettyServer.java
arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/server/McpNettyServer.java
/* * Copyright 2024-2024 the original author or authors. */ package com.taobao.arthas.mcp.server.protocol.server; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.taobao.arthas.mcp.server.CommandExecutor; import com.taobao.arthas.mcp.server.protocol.spec.*; import com.taobao.arthas.mcp.server.util.Assert; import com.taobao.arthas.mcp.server.util.Utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.time.Duration; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.function.BiFunction; /** * A Netty-based MCP server implementation that provides access to tools, resources, and prompts. * * @author Yeaury */ public class McpNettyServer { private static final Logger logger = LoggerFactory.getLogger(McpNettyServer.class); private final McpServerTransportProvider mcpTransportProvider; private final ObjectMapper objectMapper; private final McpSchema.ServerCapabilities serverCapabilities; private final McpSchema.Implementation serverInfo; private final String instructions; private final CopyOnWriteArrayList<McpServerFeatures.ToolSpecification> tools = new CopyOnWriteArrayList<>(); private final CopyOnWriteArrayList<McpSchema.ResourceTemplate> resourceTemplates = new CopyOnWriteArrayList<>(); private final ConcurrentHashMap<String, McpServerFeatures.ResourceSpecification> resources = new ConcurrentHashMap<>(); private final ConcurrentHashMap<String, McpServerFeatures.PromptSpecification> prompts = new ConcurrentHashMap<>(); private McpSchema.LoggingLevel minLoggingLevel = McpSchema.LoggingLevel.DEBUG; private List<String> protocolVersions; McpNettyServer(McpStreamableServerTransportProvider mcpTransportProvider, ObjectMapper objectMapper, Duration requestTimeout, McpServerFeatures.McpServerConfig features, CommandExecutor commandExecutor) { this.mcpTransportProvider = mcpTransportProvider; this.objectMapper = objectMapper; this.serverInfo = features.getServerInfo(); this.serverCapabilities = features.getServerCapabilities(); this.instructions = features.getInstructions(); this.tools.addAll(features.getTools()); this.resources.putAll(features.getResources()); this.resourceTemplates.addAll(features.getResourceTemplates()); this.prompts.putAll(features.getPrompts()); Map<String, McpRequestHandler<?>> requestHandlers = prepareRequestHandlers(); Map<String, McpNotificationHandler> notificationHandlers = prepareNotificationHandlers(features); this.protocolVersions = mcpTransportProvider.protocolVersions(); mcpTransportProvider.setSessionFactory(new DefaultMcpStreamableServerSessionFactory(requestTimeout, this::initializeRequestHandler, requestHandlers, notificationHandlers, commandExecutor)); } private Map<String, McpNotificationHandler> prepareNotificationHandlers(McpServerFeatures.McpServerConfig features) { Map<String, McpNotificationHandler> notificationHandlers = new HashMap<>(); notificationHandlers.put(McpSchema.METHOD_NOTIFICATION_INITIALIZED, (exchange, commandContext, params) -> CompletableFuture.completedFuture(null)); List<BiFunction<McpNettyServerExchange, List<McpSchema.Root>, CompletableFuture<Void>>> rootsChangeConsumers = features .getRootsChangeConsumers(); if (Utils.isEmpty(rootsChangeConsumers)) { rootsChangeConsumers = Collections.singletonList( (exchange, roots) -> CompletableFuture.runAsync(() -> logger.warn("Roots list changed notification, but no consumers provided. Roots list changed: {}", roots)) ); } notificationHandlers.put(McpSchema.METHOD_NOTIFICATION_ROOTS_LIST_CHANGED, rootsListChangedNotificationHandler(rootsChangeConsumers)); return notificationHandlers; } private Map<String, McpRequestHandler<?>> prepareRequestHandlers() { Map<String, McpRequestHandler<?>> requestHandlers = new HashMap<>(); // Initialize request handlers for standard MCP methods // Ping MUST respond with an empty data, but not NULL response. requestHandlers.put(McpSchema.METHOD_PING, (exchange, commandContext, params) -> CompletableFuture.completedFuture(Collections.emptyMap())); // Add tools API handlers if the tool capability is enabled if (this.serverCapabilities.getTools() != null) { requestHandlers.put(McpSchema.METHOD_TOOLS_LIST, toolsListRequestHandler()); requestHandlers.put(McpSchema.METHOD_TOOLS_CALL, toolsCallRequestHandler()); } // Add resources API handlers if provided if (this.serverCapabilities.getResources() != null) { requestHandlers.put(McpSchema.METHOD_RESOURCES_LIST, resourcesListRequestHandler()); requestHandlers.put(McpSchema.METHOD_RESOURCES_READ, resourcesReadRequestHandler()); requestHandlers.put(McpSchema.METHOD_RESOURCES_TEMPLATES_LIST, resourceTemplateListRequestHandler()); } // Add prompts API handlers if provider exists if (this.serverCapabilities.getPrompts() != null) { requestHandlers.put(McpSchema.METHOD_PROMPT_LIST, promptsListRequestHandler()); requestHandlers.put(McpSchema.METHOD_PROMPT_GET, promptsGetRequestHandler()); } // Add logging API handlers if the logging capability is enabled if (this.serverCapabilities.getLogging() != null) { requestHandlers.put(McpSchema.METHOD_LOGGING_SET_LEVEL, setLoggerRequestHandler()); } return requestHandlers; } // --------------------------------------- // Lifecycle Management // --------------------------------------- private CompletableFuture<McpSchema.InitializeResult> initializeRequestHandler( McpSchema.InitializeRequest initializeRequest) { return CompletableFuture.supplyAsync(() -> { logger.info("Client initialize request - Protocol: {}, Capabilities: {}, Info: {}", initializeRequest.getProtocolVersion(), initializeRequest.getCapabilities(), initializeRequest.getClientInfo()); // The server MUST respond with the highest protocol version it supports // if // it does not support the requested (e.g. Client) version. String serverProtocolVersion = protocolVersions.get(protocolVersions.size() - 1); if (protocolVersions.contains(initializeRequest.getProtocolVersion())) { serverProtocolVersion = initializeRequest.getProtocolVersion(); } else { logger.warn( "Client requested unsupported protocol version: {}, " + "so the server will suggest {} instead", initializeRequest.getProtocolVersion(), serverProtocolVersion); } return new McpSchema.InitializeResult(serverProtocolVersion, serverCapabilities, serverInfo, instructions); }); } public McpSchema.ServerCapabilities getServerCapabilities() { return this.serverCapabilities; } public McpSchema.Implementation getServerInfo() { return this.serverInfo; } public CompletableFuture<Void> closeGracefully() { return this.mcpTransportProvider.closeGracefully(); } public void close() { this.mcpTransportProvider.close(); } private McpNotificationHandler rootsListChangedNotificationHandler( List<BiFunction<McpNettyServerExchange, List<McpSchema.Root>, CompletableFuture<Void>>> rootsChangeConsumers) { return (exchange, commandContext, params) -> { CompletableFuture<McpSchema.ListRootsResult> futureRoots = exchange.listRoots(); return futureRoots.thenCompose(listRootsResult -> { List<McpSchema.Root> roots = listRootsResult.getRoots(); List<CompletableFuture<?>> futures = new ArrayList<>(); for (BiFunction<McpNettyServerExchange, List<McpSchema.Root>, CompletableFuture<Void>> consumer : rootsChangeConsumers) { CompletableFuture<Void> future = consumer.apply(exchange, roots).exceptionally(error -> { logger.error("Error handling roots list change notification", error); return null; }); futures.add(future); } return CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])); }); }; } // --------------------------------------- // Tool Management // --------------------------------------- public CompletableFuture<Void> addTool(McpServerFeatures.ToolSpecification toolSpecification) { if (toolSpecification == null) { CompletableFuture<Void> future = new CompletableFuture<>(); future.completeExceptionally(new McpError("Tool specification must not be null")); return future; } if (toolSpecification.getTool() == null) { CompletableFuture<Void> future = new CompletableFuture<>(); future.completeExceptionally(new McpError("Tool must not be null")); return future; } if (toolSpecification.getCall() == null) { CompletableFuture<Void> future = new CompletableFuture<>(); future.completeExceptionally(new McpError("Tool call handler must not be null")); return future; } if (this.serverCapabilities.getTools() == null) { CompletableFuture<Void> future = new CompletableFuture<>(); future.completeExceptionally(new McpError("Server must be configured with tool capabilities")); return future; } return CompletableFuture.supplyAsync(() -> { // Check for duplicate tool names if (this.tools.stream().anyMatch(th -> th.getTool().getName().equals(toolSpecification.getTool().getName()))) { throw new CompletionException( new McpError("Tool with name '" + toolSpecification.getTool().getName() + "' already exists")); } this.tools.add(toolSpecification); logger.debug("Added tool handler: {}", toolSpecification.getTool().getName()); return null; }).thenCompose(ignored -> { if (this.serverCapabilities.getTools().getListChanged()) { return notifyToolsListChanged(); } return CompletableFuture.completedFuture(null); }).exceptionally(ex -> { Throwable cause = ex instanceof CompletionException ? ex.getCause() : ex; logger.error("Error while adding tool", cause); throw new CompletionException(cause); }); } public CompletableFuture<Void> removeTool(String toolName) { if (toolName == null) { CompletableFuture<Void> future = new CompletableFuture<>(); future.completeExceptionally(new McpError("Tool name must not be null")); return future; } if (this.serverCapabilities.getTools() == null) { CompletableFuture<Void> future = new CompletableFuture<>(); future.completeExceptionally(new McpError("Server must be configured with tool capabilities")); return future; } return CompletableFuture.supplyAsync(() -> { boolean removed = this.tools.removeIf(spec -> spec.getTool().getName().equals(toolName)); if (!removed) { throw new CompletionException(new McpError("Tool with name '" + toolName + "' not found")); } logger.debug("Removed tool handler: {}", toolName); return null; }).thenCompose(ignored -> { if (this.serverCapabilities.getTools().getListChanged()) { return notifyToolsListChanged(); } return CompletableFuture.completedFuture(null); }).exceptionally(ex -> { Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex; logger.error("Error while removing tool '{}'", toolName, cause); throw new CompletionException(cause); }); } public CompletableFuture<Void> notifyToolsListChanged() { logger.debug("Notifying clients about tool list changes"); return this.mcpTransportProvider.notifyClients(McpSchema.METHOD_NOTIFICATION_TOOLS_LIST_CHANGED, null); } private McpRequestHandler<McpSchema.ListToolsResult> toolsListRequestHandler() { return (exchange, commandContext, params) -> { List<McpSchema.Tool> tools = new ArrayList<>(); for (McpServerFeatures.ToolSpecification toolSpec : this.tools) { tools.add(toolSpec.getTool()); } return CompletableFuture.completedFuture(new McpSchema.ListToolsResult(tools, null)); }; } private McpRequestHandler<McpSchema.CallToolResult> toolsCallRequestHandler() { return (exchange, commandContext, params) -> { McpSchema.CallToolRequest callToolRequest = objectMapper.convertValue(params, new TypeReference<McpSchema.CallToolRequest>() { }); Optional<McpServerFeatures.ToolSpecification> toolSpecification = this.tools.stream() .filter(tr -> callToolRequest.getName().equals(tr.getTool().getName())) .findAny(); if (!toolSpecification.isPresent()) { CompletableFuture<McpSchema.CallToolResult> future = new CompletableFuture<>(); future.completeExceptionally(new McpError("no tool found: " + callToolRequest.getName())); return future; } return toolSpecification.get().getCall().apply(exchange, commandContext, callToolRequest); }; } // --------------------------------------- // Resource Management // --------------------------------------- public CompletableFuture<Void> addResource(McpServerFeatures.ResourceSpecification resourceSpecification) { if (resourceSpecification == null || resourceSpecification.getResource() == null) { CompletableFuture<Void> future = new CompletableFuture<>(); future.completeExceptionally(new McpError("Resource must not be null")); return future; } if (this.serverCapabilities.getResources() == null) { CompletableFuture<Void> future = new CompletableFuture<>(); future.completeExceptionally(new McpError("Server must be configured with resource capabilities")); return future; } return CompletableFuture.supplyAsync(() -> { if (this.resources.putIfAbsent(resourceSpecification.getResource().getUri(), resourceSpecification) != null) { throw new CompletionException(new McpError( "Resource with URI '" + resourceSpecification.getResource().getUri() + "' already exists")); } logger.debug("Added resource handler: {}", resourceSpecification.getResource().getUri()); return null; }).thenCompose(ignored -> { if (this.serverCapabilities.getResources().getListChanged()) { return notifyResourcesListChanged(); } return CompletableFuture.completedFuture(null); }).exceptionally(ex -> { Throwable cause = ex instanceof CompletionException ? ex.getCause() : ex; logger.error("Error while adding resource '{}'", resourceSpecification.getResource().getUri(), cause); throw new CompletionException(cause); }); } public CompletableFuture<Void> removeResource(String resourceUri) { if (resourceUri == null) { CompletableFuture<Void> future = new CompletableFuture<>(); future.completeExceptionally(new McpError("Resource URI must not be null")); return future; } if (this.serverCapabilities.getResources() == null) { CompletableFuture<Void> future = new CompletableFuture<>(); future.completeExceptionally(new McpError("Server must be configured with resource capabilities")); return future; } return CompletableFuture.supplyAsync(() -> { McpServerFeatures.ResourceSpecification removed = this.resources.remove(resourceUri); if (removed == null) { throw new CompletionException(new McpError("Resource with URI '" + resourceUri + "' not found")); } logger.debug("Removed resource handler: {}", resourceUri); return null; }).thenCompose(ignored -> { if (this.serverCapabilities.getResources().getListChanged()) { return notifyResourcesListChanged(); } return CompletableFuture.completedFuture(null); }).exceptionally(ex -> { Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex; logger.error("Error while removing resource '{}'", resourceUri, cause); throw new CompletionException(cause); }); } public CompletableFuture<Void> notifyResourcesListChanged() { return this.mcpTransportProvider.notifyClients(McpSchema.METHOD_NOTIFICATION_RESOURCES_LIST_CHANGED, null); } private McpRequestHandler<McpSchema.ListResourcesResult> resourcesListRequestHandler() { return (exchange, commandContext, params) -> { List<McpSchema.Resource> resourceList = new ArrayList<>(); for (McpServerFeatures.ResourceSpecification spec : this.resources.values()) { resourceList.add(spec.getResource()); } return CompletableFuture.completedFuture(new McpSchema.ListResourcesResult(resourceList, null)); }; } private McpRequestHandler<McpSchema.ListResourceTemplatesResult> resourceTemplateListRequestHandler() { return (exchange, commandContext, params) -> CompletableFuture .completedFuture(new McpSchema.ListResourceTemplatesResult(this.resourceTemplates, null)); } private McpRequestHandler<McpSchema.ReadResourceResult> resourcesReadRequestHandler() { return (exchange, commandContext, params) -> { McpSchema.ReadResourceRequest resourceRequest = objectMapper.convertValue(params, new TypeReference<McpSchema.ReadResourceRequest>() { }); String resourceUri = resourceRequest.getUri(); McpServerFeatures.ResourceSpecification specification = this.resources.get(resourceUri); if (specification != null) { return specification.getReadHandler().apply(exchange, resourceRequest); } CompletableFuture<McpSchema.ReadResourceResult> future = new CompletableFuture<>(); future.completeExceptionally(new McpError("Resource not found: " + resourceUri)); return future; }; } // --------------------------------------- // Prompt Management // --------------------------------------- public CompletableFuture<Void> addPrompt(McpServerFeatures.PromptSpecification promptSpecification) { if (promptSpecification == null) { CompletableFuture<Void> future = new CompletableFuture<>(); future.completeExceptionally(new McpError("Prompt specification must not be null")); return future; } if (this.serverCapabilities.getPrompts() == null) { CompletableFuture<Void> future = new CompletableFuture<>(); future.completeExceptionally(new McpError("Server must be configured with prompt capabilities")); return future; } return CompletableFuture.supplyAsync(() -> { McpServerFeatures.PromptSpecification existing = this.prompts .putIfAbsent(promptSpecification.getPrompt().getName(), promptSpecification); if (existing != null) { throw new CompletionException( new McpError("Prompt with name '" + promptSpecification.getPrompt().getName() + "' already exists")); } logger.debug("Added prompt handler: {}", promptSpecification.getPrompt().getName()); return null; }).thenCompose(ignored -> { if (this.serverCapabilities.getPrompts().getListChanged()) { return notifyPromptsListChanged(); } return CompletableFuture.completedFuture(null); }).exceptionally(ex -> { Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex; logger.error("Error while adding prompt '{}'", promptSpecification.getPrompt().getName(), cause); throw new CompletionException(cause); }); } public CompletableFuture<Void> removePrompt(String promptName) { if (promptName == null) { CompletableFuture<Void> future = new CompletableFuture<>(); future.completeExceptionally(new McpError("Prompt name must not be null")); return future; } if (this.serverCapabilities.getPrompts() == null) { CompletableFuture<Void> future = new CompletableFuture<>(); future.completeExceptionally(new McpError("Server must be configured with prompt capabilities")); return future; } return CompletableFuture.supplyAsync(() -> { McpServerFeatures.PromptSpecification removed = this.prompts.remove(promptName); if (removed == null) { throw new CompletionException(new McpError("Prompt with name '" + promptName + "' not found")); } logger.debug("Removed prompt handler: {}", promptName); return null; }).thenCompose(ignored -> { if (this.serverCapabilities.getPrompts().getListChanged()) { return notifyPromptsListChanged(); } return CompletableFuture.completedFuture(null); }).exceptionally(ex -> { Throwable cause = ex instanceof CompletionException ? ex.getCause() : ex; logger.error("Error while removing prompt '{}'", promptName, cause); throw new CompletionException(cause); }); } public CompletableFuture<Void> notifyPromptsListChanged() { return this.mcpTransportProvider.notifyClients(McpSchema.METHOD_NOTIFICATION_PROMPTS_LIST_CHANGED, null); } private McpRequestHandler<McpSchema.ListPromptsResult> promptsListRequestHandler() { return (exchange, commandContext, params) -> { List<McpSchema.Prompt> promptList = new ArrayList<>(); for (McpServerFeatures.PromptSpecification promptSpec : this.prompts.values()) { promptList.add(promptSpec.getPrompt()); } return CompletableFuture.completedFuture(new McpSchema.ListPromptsResult(promptList, null)); }; } private McpRequestHandler<McpSchema.GetPromptResult> promptsGetRequestHandler() { return (exchange, commandContext, params) -> { McpSchema.GetPromptRequest promptRequest = objectMapper.convertValue(params, new TypeReference<McpSchema.GetPromptRequest>() { }); McpServerFeatures.PromptSpecification specification = this.prompts.get(promptRequest.getName()); if (specification != null) { return specification.getPromptHandler().apply(exchange, promptRequest); } CompletableFuture<McpSchema.GetPromptResult> future = new CompletableFuture<>(); future.completeExceptionally(new McpError("Prompt not found: " + promptRequest.getName())); return future; }; } // --------------------------------------- // Logging Management // --------------------------------------- public CompletableFuture<Void> loggingNotification( McpSchema.LoggingMessageNotification loggingMessageNotification) { Assert.notNull(loggingMessageNotification, "Logging message must not be null"); if (loggingMessageNotification.getLevel().level() < minLoggingLevel.level()) { return CompletableFuture.completedFuture(null); } return this.mcpTransportProvider.notifyClients(McpSchema.METHOD_NOTIFICATION_MESSAGE, loggingMessageNotification); } private McpRequestHandler<Map<String, Object>> setLoggerRequestHandler() { return (exchange, commandContext, params) -> { try { McpSchema.SetLevelRequest request = this.objectMapper.convertValue(params, McpSchema.SetLevelRequest.class); this.minLoggingLevel = request.getLevel(); return CompletableFuture.completedFuture(Collections.emptyMap()); } catch (Exception e) { CompletableFuture<Map<String, Object>> future = new CompletableFuture<>(); future.completeExceptionally(new McpError("An error occurred while processing a request to set the log level: " + e.getMessage())); return future; } }; } // --------------------------------------- // Sampling // --------------------------------------- public void setProtocolVersions(List<String> protocolVersions) { this.protocolVersions = protocolVersions; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/server/McpNotificationHandler.java
arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/server/McpNotificationHandler.java
/* * Copyright 2024-2024 the original author or authors. */ package com.taobao.arthas.mcp.server.protocol.server; import com.taobao.arthas.mcp.server.session.ArthasCommandContext; import java.util.concurrent.CompletableFuture; /** * Handles MCP notifications from clients using CompletableFuture for async operations. * This is the Netty-specific version that doesn't depend on Reactor. */ public interface McpNotificationHandler { /** * Handles a notification from the client. * @param exchange the exchange associated with the client that allows calling back to * the connected client or inspecting its capabilities. * @param params the parameters of the notification. * @return a CompletableFuture that completes once the notification is handled. */ CompletableFuture<Void> handle(McpNettyServerExchange exchange, ArthasCommandContext arthasCommandContext, Object params); }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/server/McpServerFeatures.java
arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/server/McpServerFeatures.java
/* * Copyright 2024-2024 the original author or authors. */ package com.taobao.arthas.mcp.server.protocol.server; import com.taobao.arthas.mcp.server.protocol.spec.McpSchema; import com.taobao.arthas.mcp.server.session.ArthasCommandContext; import com.taobao.arthas.mcp.server.util.Assert; import com.taobao.arthas.mcp.server.util.Utils; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.function.BiFunction; /** * MCP server function specification, the server can choose the supported features. * This implementation only provides an asynchronous API. * * @author Yeaury */ public class McpServerFeatures { public static class McpServerConfig { private final McpSchema.Implementation serverInfo; private final McpSchema.ServerCapabilities serverCapabilities; private final List<ToolSpecification> tools; private final Map<String, ResourceSpecification> resources; private final List<McpSchema.ResourceTemplate> resourceTemplates; private final Map<String, PromptSpecification> prompts; private final List<BiFunction<McpNettyServerExchange, List<McpSchema.Root>, CompletableFuture<Void>>> rootsChangeConsumers; private final String instructions; public McpServerConfig( McpSchema.Implementation serverInfo, McpSchema.ServerCapabilities serverCapabilities, List<ToolSpecification> tools, Map<String, ResourceSpecification> resources, List<McpSchema.ResourceTemplate> resourceTemplates, Map<String, PromptSpecification> prompts, List<BiFunction<McpNettyServerExchange, List<McpSchema.Root>, CompletableFuture<Void>>> rootsChangeConsumers, String instructions) { Assert.notNull(serverInfo, "The server information cannot be empty"); // If serverCapabilities is empty, the appropriate capability configuration // is automatically built based on the provided capabilities if (serverCapabilities == null) { serverCapabilities = new McpSchema.ServerCapabilities( null, // experimental new McpSchema.ServerCapabilities.LoggingCapabilities(), !Utils.isEmpty(prompts) ? new McpSchema.ServerCapabilities.PromptCapabilities(false) : null, !Utils.isEmpty(resources) ? new McpSchema.ServerCapabilities.ResourceCapabilities(false, false) : null, !Utils.isEmpty(tools) ? new McpSchema.ServerCapabilities.ToolCapabilities(false) : null); } this.tools = (tools != null) ? tools : Collections.emptyList(); this.resources = (resources != null) ? resources : Collections.emptyMap(); this.resourceTemplates = (resourceTemplates != null) ? resourceTemplates : Collections.emptyList(); this.prompts = (prompts != null) ? prompts : Collections.emptyMap(); this.rootsChangeConsumers = (rootsChangeConsumers != null) ? rootsChangeConsumers : Collections.emptyList(); this.serverInfo = serverInfo; this.serverCapabilities = serverCapabilities; this.instructions = instructions; } public McpSchema.Implementation getServerInfo() { return serverInfo; } public McpSchema.ServerCapabilities getServerCapabilities() { return serverCapabilities; } public List<ToolSpecification> getTools() { return tools; } public Map<String, ResourceSpecification> getResources() { return resources; } public List<McpSchema.ResourceTemplate> getResourceTemplates() { return resourceTemplates; } public Map<String, PromptSpecification> getPrompts() { return prompts; } public List<BiFunction<McpNettyServerExchange, List<McpSchema.Root>, CompletableFuture<Void>>> getRootsChangeConsumers() { return rootsChangeConsumers; } public String getInstructions() { return instructions; } public static Builder builder() { return new Builder(); } public static class Builder { private McpSchema.Implementation serverInfo; private McpSchema.ServerCapabilities serverCapabilities; private final List<ToolSpecification> tools = new ArrayList<>(); private final Map<String, ResourceSpecification> resources = new HashMap<>(); private final List<McpSchema.ResourceTemplate> resourceTemplates = new ArrayList<>(); private final Map<String, PromptSpecification> prompts = new HashMap<>(); private final List<BiFunction<McpNettyServerExchange, List<McpSchema.Root>, CompletableFuture<Void>>> rootsChangeConsumers = new ArrayList<>(); private String instructions; public Builder serverInfo(McpSchema.Implementation serverInfo) { this.serverInfo = serverInfo; return this; } public Builder serverCapabilities(McpSchema.ServerCapabilities serverCapabilities) { this.serverCapabilities = serverCapabilities; return this; } public Builder addTool(ToolSpecification tool) { this.tools.add(tool); return this; } public Builder addResource(String key, ResourceSpecification resource) { this.resources.put(key, resource); return this; } public Builder addResourceTemplate(McpSchema.ResourceTemplate template) { this.resourceTemplates.add(template); return this; } public Builder addPrompt(String key, PromptSpecification prompt) { this.prompts.put(key, prompt); return this; } public Builder addRootsChangeConsumer( BiFunction<McpNettyServerExchange, List<McpSchema.Root>, CompletableFuture<Void>> consumer) { this.rootsChangeConsumers.add(consumer); return this; } public Builder instructions(String instructions) { this.instructions = instructions; return this; } public McpServerConfig build() { return new McpServerConfig(serverInfo, serverCapabilities, tools, resources, resourceTemplates, prompts, rootsChangeConsumers, instructions); } } } public static class ToolSpecification { private final McpSchema.Tool tool; private final ToolCallFunction call; public ToolSpecification( McpSchema.Tool tool, ToolCallFunction call) { this.tool = tool; this.call = call; } public McpSchema.Tool getTool() { return tool; } public ToolCallFunction getCall() { return call; } } /** * Tool call function interface with three parameters */ @FunctionalInterface public interface ToolCallFunction { CompletableFuture<McpSchema.CallToolResult> apply( McpNettyServerExchange exchange, ArthasCommandContext commandContext, McpSchema.CallToolRequest arguments ); } public static class ResourceSpecification { private final McpSchema.Resource resource; private final BiFunction<McpNettyServerExchange, McpSchema.ReadResourceRequest, CompletableFuture<McpSchema.ReadResourceResult>> readHandler; public ResourceSpecification( McpSchema.Resource resource, BiFunction<McpNettyServerExchange, McpSchema.ReadResourceRequest, CompletableFuture<McpSchema.ReadResourceResult>> readHandler) { this.resource = resource; this.readHandler = readHandler; } public McpSchema.Resource getResource() { return resource; } public BiFunction<McpNettyServerExchange, McpSchema.ReadResourceRequest, CompletableFuture<McpSchema.ReadResourceResult>> getReadHandler() { return readHandler; } } public static class PromptSpecification { private final McpSchema.Prompt prompt; private final BiFunction<McpNettyServerExchange, McpSchema.GetPromptRequest, CompletableFuture<McpSchema.GetPromptResult>> promptHandler; public PromptSpecification( McpSchema.Prompt prompt, BiFunction<McpNettyServerExchange, McpSchema.GetPromptRequest, CompletableFuture<McpSchema.GetPromptResult>> promptHandler) { this.prompt = prompt; this.promptHandler = promptHandler; } public McpSchema.Prompt getPrompt() { return prompt; } public BiFunction<McpNettyServerExchange, McpSchema.GetPromptRequest, CompletableFuture<McpSchema.GetPromptResult>> getPromptHandler() { return promptHandler; } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/server/McpStatelessServerFeatures.java
arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/server/McpStatelessServerFeatures.java
/* * Copyright 2024-2024 the original author or authors. */ package com.taobao.arthas.mcp.server.protocol.server; import com.taobao.arthas.mcp.server.protocol.spec.McpSchema; import com.taobao.arthas.mcp.server.session.ArthasCommandContext; import com.taobao.arthas.mcp.server.util.Assert; import com.taobao.arthas.mcp.server.util.Utils; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.function.BiFunction; /** * MCP server function specification, the server can choose the supported features. * This implementation only provides an asynchronous API. * * @author Yeaury */ public class McpStatelessServerFeatures { public static class McpServerConfig { private final McpSchema.Implementation serverInfo; private final McpSchema.ServerCapabilities serverCapabilities; private final List<ToolSpecification> tools; private final Map<String, ResourceSpecification> resources; private final List<McpSchema.ResourceTemplate> resourceTemplates; private final Map<String, PromptSpecification> prompts; private final String instructions; public McpServerConfig( McpSchema.Implementation serverInfo, McpSchema.ServerCapabilities serverCapabilities, List<ToolSpecification> tools, Map<String, ResourceSpecification> resources, List<McpSchema.ResourceTemplate> resourceTemplates, Map<String, PromptSpecification> prompts, String instructions) { Assert.notNull(serverInfo, "The server information cannot be empty"); // If serverCapabilities is empty, the appropriate capability configuration // is automatically built based on the provided capabilities if (serverCapabilities == null) { serverCapabilities = new McpSchema.ServerCapabilities( null, // experimental new McpSchema.ServerCapabilities.LoggingCapabilities(), !Utils.isEmpty(prompts) ? new McpSchema.ServerCapabilities.PromptCapabilities(false) : null, !Utils.isEmpty(resources) ? new McpSchema.ServerCapabilities.ResourceCapabilities(false, false) : null, !Utils.isEmpty(tools) ? new McpSchema.ServerCapabilities.ToolCapabilities(false) : null); } this.tools = (tools != null) ? tools : Collections.emptyList(); this.resources = (resources != null) ? resources : Collections.emptyMap(); this.resourceTemplates = (resourceTemplates != null) ? resourceTemplates : Collections.emptyList(); this.prompts = (prompts != null) ? prompts : Collections.emptyMap(); this.serverInfo = serverInfo; this.serverCapabilities = serverCapabilities; this.instructions = instructions; } public McpSchema.Implementation getServerInfo() { return serverInfo; } public McpSchema.ServerCapabilities getServerCapabilities() { return serverCapabilities; } public List<ToolSpecification> getTools() { return tools; } public Map<String, ResourceSpecification> getResources() { return resources; } public List<McpSchema.ResourceTemplate> getResourceTemplates() { return resourceTemplates; } public Map<String, PromptSpecification> getPrompts() { return prompts; } public String getInstructions() { return instructions; } public static Builder builder() { return new Builder(); } public static class Builder { private McpSchema.Implementation serverInfo; private McpSchema.ServerCapabilities serverCapabilities; private final List<ToolSpecification> tools = new ArrayList<>(); private final Map<String, ResourceSpecification> resources = new HashMap<>(); private final List<McpSchema.ResourceTemplate> resourceTemplates = new ArrayList<>(); private final Map<String, PromptSpecification> prompts = new HashMap<>(); private String instructions; public Builder serverInfo(McpSchema.Implementation serverInfo) { this.serverInfo = serverInfo; return this; } public Builder serverCapabilities(McpSchema.ServerCapabilities serverCapabilities) { this.serverCapabilities = serverCapabilities; return this; } public Builder addTool(ToolSpecification tool) { this.tools.add(tool); return this; } public Builder addResource(String key, ResourceSpecification resource) { this.resources.put(key, resource); return this; } public Builder addResourceTemplate(McpSchema.ResourceTemplate template) { this.resourceTemplates.add(template); return this; } public Builder addPrompt(String key, PromptSpecification prompt) { this.prompts.put(key, prompt); return this; } public Builder instructions(String instructions) { this.instructions = instructions; return this; } public McpServerConfig build() { return new McpServerConfig(serverInfo, serverCapabilities, tools, resources, resourceTemplates, prompts, instructions); } } } public static class ToolSpecification { private final McpSchema.Tool tool; private final ToolCallFunction call; public ToolSpecification( McpSchema.Tool tool, ToolCallFunction call) { this.tool = tool; this.call = call; } public McpSchema.Tool getTool() { return tool; } public ToolCallFunction getCall() { return call; } } /** * Tool call function interface with three parameters */ @FunctionalInterface public interface ToolCallFunction { CompletableFuture<McpSchema.CallToolResult> apply( McpTransportContext context, ArthasCommandContext commandContext, Map<String, Object> arguments ); } public static class ResourceSpecification { private final McpSchema.Resource resource; private final BiFunction<McpTransportContext, McpSchema.ReadResourceRequest, CompletableFuture<McpSchema.ReadResourceResult>> readHandler; public ResourceSpecification( McpSchema.Resource resource, BiFunction<McpTransportContext, McpSchema.ReadResourceRequest, CompletableFuture<McpSchema.ReadResourceResult>> readHandler) { this.resource = resource; this.readHandler = readHandler; } public McpSchema.Resource getResource() { return resource; } public BiFunction<McpTransportContext, McpSchema.ReadResourceRequest, CompletableFuture<McpSchema.ReadResourceResult>> getReadHandler() { return readHandler; } } public static class PromptSpecification { private final McpSchema.Prompt prompt; private final BiFunction<McpTransportContext, McpSchema.GetPromptRequest, CompletableFuture<McpSchema.GetPromptResult>> promptHandler; public PromptSpecification( McpSchema.Prompt prompt, BiFunction<McpTransportContext, McpSchema.GetPromptRequest, CompletableFuture<McpSchema.GetPromptResult>> promptHandler) { this.prompt = prompt; this.promptHandler = promptHandler; } public McpSchema.Prompt getPrompt() { return prompt; } public BiFunction<McpTransportContext, McpSchema.GetPromptRequest, CompletableFuture<McpSchema.GetPromptResult>> getPromptHandler() { return promptHandler; } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/server/McpServer.java
arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/server/McpServer.java
/* * Copyright 2024-2024 the original author or authors. */ package com.taobao.arthas.mcp.server.protocol.server; import com.fasterxml.jackson.databind.ObjectMapper; import com.taobao.arthas.mcp.server.util.JsonParser; import com.taobao.arthas.mcp.server.CommandExecutor; import com.taobao.arthas.mcp.server.protocol.spec.McpSchema; import com.taobao.arthas.mcp.server.protocol.spec.McpStatelessServerTransport; import com.taobao.arthas.mcp.server.protocol.spec.McpStreamableServerTransportProvider; import com.taobao.arthas.mcp.server.util.Assert; import java.time.Duration; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.function.BiFunction; /** * MCP server interface and builder for Netty-based implementation. * * @author Yeaury */ public interface McpServer { McpSchema.Implementation DEFAULT_SERVER_INFO = new McpSchema.Implementation("mcp-server", "1.0.0"); static StreamableServerNettySpecification netty(McpStreamableServerTransportProvider transportProvider) { return new StreamableServerNettySpecification(transportProvider); } static StatelessServerNettySpecification netty(McpStatelessServerTransport transport) { return new StatelessServerNettySpecification(transport); } class StreamableServerNettySpecification { ObjectMapper objectMapper; McpSchema.Implementation serverInfo = DEFAULT_SERVER_INFO; McpSchema.ServerCapabilities serverCapabilities; String instructions; CommandExecutor commandExecutor; private final McpStreamableServerTransportProvider transportProvider; final List<McpServerFeatures.ToolSpecification> tools = new ArrayList<>(); final Map<String, McpServerFeatures.ResourceSpecification> resources = new HashMap<>(); final List<McpSchema.ResourceTemplate> resourceTemplates = new ArrayList<>(); final Map<String, McpServerFeatures.PromptSpecification> prompts = new HashMap<>(); final List<BiFunction<McpNettyServerExchange, List<McpSchema.Root>, CompletableFuture<Void>>> rootsChangeHandlers = new ArrayList<>(); Duration requestTimeout = Duration.ofSeconds(10); // Default timeout public StreamableServerNettySpecification(McpStreamableServerTransportProvider transportProvider) { this.transportProvider = transportProvider; } public StreamableServerNettySpecification serverInfo(McpSchema.Implementation serverInfo) { Assert.notNull(serverInfo, "Server info must not be null"); this.serverInfo = serverInfo; return this; } public StreamableServerNettySpecification requestTimeout(Duration requestTimeout) { Assert.notNull(requestTimeout, "Request timeout must not be null"); this.requestTimeout = requestTimeout; return this; } public StreamableServerNettySpecification serverInfo(String name, String version) { Assert.hasText(name, "Name must not be null or empty"); Assert.hasText(version, "Version must not be null or empty"); this.serverInfo = new McpSchema.Implementation(name, version); return this; } public StreamableServerNettySpecification instructions(String instructions) { this.instructions = instructions; return this; } public StreamableServerNettySpecification capabilities(McpSchema.ServerCapabilities serverCapabilities) { this.serverCapabilities = serverCapabilities; return this; } public StreamableServerNettySpecification tool(McpSchema.Tool tool, McpServerFeatures.ToolCallFunction handler) { Assert.notNull(tool, "Tool must not be null"); Assert.notNull(handler, "Handler must not be null"); this.tools.add(new McpServerFeatures.ToolSpecification(tool, handler)); return this; } public StreamableServerNettySpecification tools(List<McpServerFeatures.ToolSpecification> toolRegistrations) { Assert.notNull(toolRegistrations, "Tool handlers list must not be null"); this.tools.addAll(toolRegistrations); return this; } public StreamableServerNettySpecification tools(McpServerFeatures.ToolSpecification... toolRegistrations) { this.tools.addAll(Arrays.asList(toolRegistrations)); return this; } public StreamableServerNettySpecification resources(Map<String, McpServerFeatures.ResourceSpecification> resourceSpecifications) { Assert.notNull(resourceSpecifications, "Resource handlers map must not be null"); this.resources.putAll(resourceSpecifications); return this; } public StreamableServerNettySpecification resources(List<McpServerFeatures.ResourceSpecification> resourceSpecifications) { Assert.notNull(resourceSpecifications, "Resource handlers list must not be null"); for (McpServerFeatures.ResourceSpecification resource : resourceSpecifications) { this.resources.put(resource.getResource().getUri(), resource); } return this; } public StreamableServerNettySpecification resources(McpServerFeatures.ResourceSpecification... resourceSpecifications) { Assert.notNull(resourceSpecifications, "Resource handlers list must not be null"); for (McpServerFeatures.ResourceSpecification resource : resourceSpecifications) { this.resources.put(resource.getResource().getUri(), resource); } return this; } public StreamableServerNettySpecification resourceTemplates(List<McpSchema.ResourceTemplate> resourceTemplates) { Assert.notNull(resourceTemplates, "Resource templates must not be null"); this.resourceTemplates.addAll(resourceTemplates); return this; } public StreamableServerNettySpecification resourceTemplates(McpSchema.ResourceTemplate... resourceTemplates) { Assert.notNull(resourceTemplates, "Resource templates must not be null"); this.resourceTemplates.addAll(Arrays.asList(resourceTemplates)); return this; } public StreamableServerNettySpecification prompts(Map<String, McpServerFeatures.PromptSpecification> prompts) { Assert.notNull(prompts, "Prompts map must not be null"); this.prompts.putAll(prompts); return this; } public StreamableServerNettySpecification prompts(List<McpServerFeatures.PromptSpecification> prompts) { Assert.notNull(prompts, "Prompts map must not be null"); for (McpServerFeatures.PromptSpecification prompt : prompts) { this.prompts.put(prompt.getPrompt().getName(), prompt); } return this; } public StreamableServerNettySpecification prompts(McpServerFeatures.PromptSpecification... prompts) { Assert.notNull(prompts, "Prompts map must not be null"); for (McpServerFeatures.PromptSpecification prompt : prompts) { this.prompts.put(prompt.getPrompt().getName(), prompt); } return this; } public StreamableServerNettySpecification rootsChangeHandler( BiFunction<McpNettyServerExchange, List<McpSchema.Root>, CompletableFuture<Void>> handler) { Assert.notNull(handler, "Consumer must not be null"); this.rootsChangeHandlers.add(handler); return this; } public StreamableServerNettySpecification rootsChangeHandlers( List<BiFunction<McpNettyServerExchange, List<McpSchema.Root>, CompletableFuture<Void>>> handlers) { Assert.notNull(handlers, "Handlers list must not be null"); this.rootsChangeHandlers.addAll(handlers); return this; } public StreamableServerNettySpecification rootsChangeHandlers( @SuppressWarnings("unchecked") BiFunction<McpNettyServerExchange, List<McpSchema.Root>, CompletableFuture<Void>>... handlers) { Assert.notNull(handlers, "Handlers list must not be null"); return this.rootsChangeHandlers(Arrays.asList(handlers)); } public StreamableServerNettySpecification objectMapper(ObjectMapper objectMapper) { Assert.notNull(objectMapper, "ObjectMapper must not be null"); this.objectMapper = objectMapper; return this; } public StreamableServerNettySpecification commandExecutor(CommandExecutor commandExecutor) { Assert.notNull(commandExecutor, "CommandExecutor must not be null"); this.commandExecutor = commandExecutor; return this; } public McpNettyServer build() { ObjectMapper mapper = this.objectMapper != null ? this.objectMapper : JsonParser.getObjectMapper(); Assert.notNull(this.commandExecutor, "CommandExecutor must be set before building"); return new McpNettyServer( this.transportProvider, mapper, this.requestTimeout, new McpServerFeatures.McpServerConfig(this.serverInfo, this.serverCapabilities, this.tools, this.resources, this.resourceTemplates, this.prompts, this.rootsChangeHandlers, this.instructions ), this.commandExecutor ); } } class StatelessServerNettySpecification { private final McpStatelessServerTransport transport; ObjectMapper objectMapper; McpSchema.Implementation serverInfo = DEFAULT_SERVER_INFO; McpSchema.ServerCapabilities serverCapabilities; String instructions; CommandExecutor commandExecutor; final List<McpStatelessServerFeatures.ToolSpecification> tools = new ArrayList<>(); final Map<String, McpStatelessServerFeatures.ResourceSpecification> resources = new HashMap<>(); final List<McpSchema.ResourceTemplate> resourceTemplates = new ArrayList<>(); final Map<String, McpStatelessServerFeatures.PromptSpecification> prompts = new HashMap<>(); final List<BiFunction<McpNettyServerExchange, List<McpSchema.Root>, CompletableFuture<Void>>> rootsChangeHandlers = new ArrayList<>(); Duration requestTimeout = Duration.ofSeconds(10); // Default timeout StatelessServerNettySpecification(McpStatelessServerTransport transport) { this.transport = transport; } public StatelessServerNettySpecification serverInfo(McpSchema.Implementation serverInfo) { Assert.notNull(serverInfo, "Server info must not be null"); this.serverInfo = serverInfo; return this; } public StatelessServerNettySpecification requestTimeout(Duration requestTimeout) { Assert.notNull(requestTimeout, "Request timeout must not be null"); this.requestTimeout = requestTimeout; return this; } public StatelessServerNettySpecification serverInfo(String name, String version) { Assert.hasText(name, "Name must not be null or empty"); Assert.hasText(version, "Version must not be null or empty"); this.serverInfo = new McpSchema.Implementation(name, version); return this; } public StatelessServerNettySpecification instructions(String instructions) { this.instructions = instructions; return this; } public StatelessServerNettySpecification capabilities(McpSchema.ServerCapabilities serverCapabilities) { this.serverCapabilities = serverCapabilities; return this; } public StatelessServerNettySpecification tools(List<McpStatelessServerFeatures.ToolSpecification> toolRegistrations) { Assert.notNull(toolRegistrations, "Tool handlers list must not be null"); this.tools.addAll(toolRegistrations); return this; } public StatelessServerNettySpecification tools(McpStatelessServerFeatures.ToolSpecification... toolRegistrations) { for (McpStatelessServerFeatures.ToolSpecification tool : toolRegistrations) { this.tools.add(tool); } return this; } public StatelessServerNettySpecification resources(Map<String, McpStatelessServerFeatures.ResourceSpecification> resourceSpecifications) { Assert.notNull(resourceSpecifications, "Resource handlers map must not be null"); this.resources.putAll(resourceSpecifications); return this; } public StatelessServerNettySpecification resources(List<McpStatelessServerFeatures.ResourceSpecification> resourceSpecifications) { Assert.notNull(resourceSpecifications, "Resource handlers list must not be null"); for (McpStatelessServerFeatures.ResourceSpecification resource : resourceSpecifications) { this.resources.put(resource.getResource().getUri(), resource); } return this; } public StatelessServerNettySpecification resources(McpStatelessServerFeatures.ResourceSpecification... resourceSpecifications) { Assert.notNull(resourceSpecifications, "Resource handlers list must not be null"); for (McpStatelessServerFeatures.ResourceSpecification resource : resourceSpecifications) { this.resources.put(resource.getResource().getUri(), resource); } return this; } public StatelessServerNettySpecification resourceTemplates(List<McpSchema.ResourceTemplate> resourceTemplates) { Assert.notNull(resourceTemplates, "Resource templates must not be null"); this.resourceTemplates.addAll(resourceTemplates); return this; } public StatelessServerNettySpecification resourceTemplates(McpSchema.ResourceTemplate... resourceTemplates) { Assert.notNull(resourceTemplates, "Resource templates must not be null"); this.resourceTemplates.addAll(Arrays.asList(resourceTemplates)); return this; } public StatelessServerNettySpecification prompts(Map<String, McpStatelessServerFeatures.PromptSpecification> prompts) { Assert.notNull(prompts, "Prompts map must not be null"); this.prompts.putAll(prompts); return this; } public StatelessServerNettySpecification prompts(List<McpStatelessServerFeatures.PromptSpecification> prompts) { Assert.notNull(prompts, "Prompts map must not be null"); for (McpStatelessServerFeatures.PromptSpecification prompt : prompts) { this.prompts.put(prompt.getPrompt().getName(), prompt); } return this; } public StatelessServerNettySpecification prompts(McpStatelessServerFeatures.PromptSpecification... prompts) { Assert.notNull(prompts, "Prompts map must not be null"); for (McpStatelessServerFeatures.PromptSpecification prompt : prompts) { this.prompts.put(prompt.getPrompt().getName(), prompt); } return this; } public StatelessServerNettySpecification rootsChangeHandler( BiFunction<McpNettyServerExchange, List<McpSchema.Root>, CompletableFuture<Void>> handler) { Assert.notNull(handler, "Consumer must not be null"); this.rootsChangeHandlers.add(handler); return this; } public StatelessServerNettySpecification rootsChangeHandlers( List<BiFunction<McpNettyServerExchange, List<McpSchema.Root>, CompletableFuture<Void>>> handlers) { Assert.notNull(handlers, "Handlers list must not be null"); this.rootsChangeHandlers.addAll(handlers); return this; } public StatelessServerNettySpecification rootsChangeHandlers( @SuppressWarnings("unchecked") BiFunction<McpNettyServerExchange, List<McpSchema.Root>, CompletableFuture<Void>>... handlers) { Assert.notNull(handlers, "Handlers list must not be null"); return this.rootsChangeHandlers(Arrays.asList(handlers)); } public StatelessServerNettySpecification objectMapper(ObjectMapper objectMapper) { Assert.notNull(objectMapper, "ObjectMapper must not be null"); this.objectMapper = objectMapper; return this; } public StatelessServerNettySpecification commandExecutor(CommandExecutor commandExecutor) { Assert.notNull(commandExecutor, "CommandExecutor must not be null"); this.commandExecutor = commandExecutor; return this; } public McpStatelessNettyServer build() { ObjectMapper mapper = this.objectMapper != null ? this.objectMapper : JsonParser.getObjectMapper(); return new McpStatelessNettyServer( this.transport, mapper, this.requestTimeout, new McpStatelessServerFeatures.McpServerConfig( this.serverInfo, this.serverCapabilities, this.tools, this.resources, this.resourceTemplates, this.prompts, this.instructions ), this.commandExecutor ); } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/server/McpInitRequestHandler.java
arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/server/McpInitRequestHandler.java
/* * Copyright 2024-2024 the original author or authors. */ package com.taobao.arthas.mcp.server.protocol.server; import com.taobao.arthas.mcp.server.protocol.spec.McpSchema; import java.util.concurrent.CompletableFuture; /** * Handles MCP initialization requests from clients using CompletableFuture for async operations. * This is the Netty-specific version that doesn't depend on Reactor. */ public interface McpInitRequestHandler { /** * Handles the initialization request. * @param initializeRequest the initialization request by the client * @return a CompletableFuture that will emit the result of the initialization */ CompletableFuture<McpSchema.InitializeResult> handle(McpSchema.InitializeRequest initializeRequest); }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/server/DefaultMcpTransportContext.java
arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/server/DefaultMcpTransportContext.java
/* * Copyright 2024-2024 the original author or authors. */ package com.taobao.arthas.mcp.server.protocol.server; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * Default implementation for {@link McpTransportContext} which uses a Thread-safe map. * Objects of this kind are mutable. */ public class DefaultMcpTransportContext implements McpTransportContext { private final Map<String, Object> storage; /** * Create an empty instance. */ public DefaultMcpTransportContext() { this.storage = new ConcurrentHashMap<>(); } DefaultMcpTransportContext(Map<String, Object> storage) { this.storage = storage; } @Override public Object get(String key) { return this.storage.get(key); } @Override public void put(String key, Object value) { if (value != null) { this.storage.put(key, value); } else { this.storage.remove(key); } } /** * Allows copying the contents. * @return new instance with the copy of the underlying map */ public McpTransportContext copy() { return new DefaultMcpTransportContext(new ConcurrentHashMap<>(this.storage)); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/server/McpStatelessServerHandler.java
arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/server/McpStatelessServerHandler.java
/* * Copyright 2024-2024 the original author or authors. */ package com.taobao.arthas.mcp.server.protocol.server; import com.taobao.arthas.mcp.server.protocol.spec.McpSchema; import java.util.concurrent.CompletableFuture; public interface McpStatelessServerHandler { /** * Handle the request using user-provided feature implementations. * @param transportContext {@link McpTransportContext} carrying transport layer * metadata * @param request the request JSON object * @return Mono containing the JSON response */ CompletableFuture<McpSchema.JSONRPCResponse> handleRequest(McpTransportContext transportContext, McpSchema.JSONRPCRequest request); /** * Handle the notification. * @param transportContext {@link McpTransportContext} carrying transport layer * metadata * @param notification the notification JSON object * @return Mono that completes once handling is finished */ CompletableFuture<Void> handleNotification(McpTransportContext transportContext, McpSchema.JSONRPCNotification notification); }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/server/McpStatelessNotificationHandler.java
arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/server/McpStatelessNotificationHandler.java
/* * Copyright 2024-2024 the original author or authors. */ package com.taobao.arthas.mcp.server.protocol.server; import java.util.concurrent.CompletableFuture; /** * Handler for MCP notifications in a stateless server. */ public interface McpStatelessNotificationHandler { /** * Handle to notification and complete once done. * @param transportContext {@link McpTransportContext} associated with the transport * @param params the payload of the MCP notification * @return Mono which completes once the processing is done */ CompletableFuture<Void> handle(McpTransportContext transportContext, Object params); }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false