modelcontextprotocol / modelcontextprotocol/java-sdk

Add null-safety validation and safe fallbacks for features / clientCapabilities in McpAsyncClient constructor and feature branches

Đang mở
#634 0 bình luận 1 reaction 0 người được giao Xem trên GitHub

Chưa có ai nhận issue này.

enhancement P3
Ngôn ngữ chính
Java
Star
3.7k
Fork
1.1k
Merge trung bình
1 ngày 15 giờ
Pull request đã merge (30 ngày)
9

Mô tả

Add null-safety validation and safe fallbacks for features / clientCapabilities in McpAsyncClient constructor and feature branches

Background

The current io.modelcontextprotocol.client.McpAsyncClient constructor performs null checks for transport, requestTimeout, and initializationTimeout, but does not validate the features object itself or its derived fields such as features.clientCapabilities() and features.roots().
Throughout the class, several branches directly dereference clientCapabilities (and its nested capabilities such as roots(), sampling(), and elicitation()), which can lead to NullPointerException with limited diagnostic information.

Example excerpt:

McpAsyncClient(McpClientTransport transport, Duration requestTimeout, Duration initializationTimeout,
               McpClientFeatures.Async features) {
    Assert.notNull(transport, "Transport must not be null");
    Assert.notNull(requestTimeout, "Request timeout must not be null");
    Assert.notNull(initializationTimeout, "Initialization timeout must not be null");

    this.clientInfo = features.clientInfo();                // direct dereference
    this.clientCapabilities = features.clientCapabilities(); // direct dereference
    this.roots = new ConcurrentHashMap<>(features.roots());  // may NPE

    if (this.clientCapabilities.roots() != null) { ... }        // clientCapabilities could be null
    if (this.clientCapabilities.sampling() != null) { ... }
    if (this.clientCapabilities.elicitation() != null) { ... }
}

Reproduction Example

// features may be constructed dynamically, with some fields unset or null
McpAsyncClient client = new McpAsyncClient(
    transport,
    Duration.ofSeconds(5),
    Duration.ofSeconds(10),
    new McpClientFeatures.Async(/* some fields return null */)
);

// During initialization or feature checks, a NullPointerException occurs

Expected Behavior

  • Perform explicit validation or safe fallback initialization during construction, providing clear and actionable error messages (e.g., IllegalArgumentException or McpError) instead of hidden NPEs.
  • Handle optional fields gracefully by using default values or null-safe checks, improving SDK robustness and developer experience.

Proposed Solution

  1. Constructor Validation

    • Add:
      Assert.notNull(features, "Features must not be null");
      
    • Depending on design intent:
      • Strict mode:
        Assert.notNull(features.clientCapabilities(), "ClientCapabilities must not be null");
        
      • Lenient mode: allow clientCapabilities == null, handle null safely later.
  2. Null-Safe Fallbacks

    • Initialize roots safely:
      Map<String, Root> initialRoots = (features.roots() != null)
          ? features.roots()
          : Collections.emptyMap();
      this.roots = new ConcurrentHashMap<>(initialRoots);
      
    • Add double null checks in all feature branches:
      if (this.clientCapabilities != null && this.clientCapabilities.roots() != null) { ... }
      if (this.clientCapabilities != null && this.clientCapabilities.sampling() != null) { ... }
      if (this.clientCapabilities != null && this.clientCapabilities.elicitation() != null) { ... }
      
    • Retain current behavior for declared but unhandled capabilities (still throwing McpError), but ensure the branch is entered safely.
  3. Improve Error Messages

    • Use consistent, developer-friendly error messages like:
      • "Features must not be null"
      • "ClientCapabilities is required when enabling sampling/elicitation"

Compatibility

  • No API changes — only internal validation and null-safety improvements.
  • If “strict mode” is chosen (enforcing non-null clientCapabilities), note this in release notes; otherwise, lenient handling remains fully backward compatible.

Test Recommendations

  • Constructor tests
    • features == null → expect meaningful exception (not NPE).
    • features.roots() == null → no NPE; roots initialized as empty map.
    • features.clientCapabilities() == null → no NPE during construction or branching.
  • Feature branches
    • Missing roots/sampling/elicitation → branches skipped safely, no NPE.
    • Declared capability but missing handler → same McpError as before, readable message.

Impacted Areas

  • io.modelcontextprotocol.client.McpAsyncClient constructor
  • Branches based on clientCapabilities

Benefits

  • Eliminates hidden NullPointerExceptions during initialization.
  • Improves error traceability and developer experience.
  • Small, low-risk change; easy to review and merge.

Environment (example)

  • MCP Java SDK: current main branch
  • JDK: 17 or 21
  • OS: macOS / Linux / Windows

If maintainers agree, I’d be happy to open a PR implementing this improvement.

Hướng dẫn đóng góp

Mở hướng dẫn đóng góp

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Hướng nghiên cứu

Bắt đầu từ constructor của io.modelcontextprotocol.client.McpAsyncClient và kiểm tra mọi nhánh đọc clientCapabilities, roots, sampling hoặc elicitation. Thêm các bài kiểm thử cho constructor và các nhánh tính năng đối với features null và các trường tùy chọn bị thiếu, theo các khuyến nghị của issue. Được coi là hoàn tất khi các lỗi tạo ra hành vi xác thực rõ ràng hoặc fallback an toàn mà không có NullPointerExceptions ẩn, trong khi hành vi McpError hiện có vẫn không thay đổi.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Đánh giá

Công nghệ
java
Lĩnh vực
api, backend
Loại issue
Lỗi
Độ khó
4/5
Thời gian dự kiến
3-5 ngày
Mức độ hoạt động
Đình trệ
Độ rõ ràng
Khá rõ ràng
Mức phù hợp với người mới
35/100

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.