Skip to content

fix(core): check resource URI depth before splitting - #1175

Open
Christiansada wants to merge 1 commit into
modelcontextprotocol:mainfrom
Christiansada:fix/1084-bound-template-path-allocation
Open

Christiansada wants to merge 1 commit into
modelcontextprotocol:mainfrom
Christiansada:fix/1084-bound-template-path-allocation

Conversation

@Christiansada

@Christiansada Christiansada commented Nov 13, 2026 •

Copy link
Copy Markdown

Updates #1084.

PathSegmentTemplateMatcher.match() splits an incoming URI into a list before rejecting it for exceeding maxDepth. Count separators after the existing normalization and trimming steps, then reject over-depth paths before allocating the segment list. Matching results and public APIs remain unchanged.

The server tie-breaker should stay: test://items/{id}/{id} and test://items/{first}/{second} match test://items/42/42 with equal scores but one versus two distinct captured keys. The new in-memory client/server test demonstrates this counterexample to the issue's second premise. Temporarily deleting the tie-breaker made it fail with expected:<repeated> but was:<distinct>; it was restored before final validation.

Validation

macOS 26.6.2 arm64, Temurin 21.0.13+9, Gradle 9.8.2; base 61500503990410e1015e35a602c3d2aefe1bdcaf:

  • 272 core JVM tests and 9 resource-template integration tests pass, freshly rerun with --rerun-tasks.
  • Core/integration ktlintCheck, core checkKotlinAbi (including multiplatform comparison), and git diff --check pass.
  • detektMainJvm exits successfully but reports 110 compiler-analysis errors on both unchanged base and fixed source, limiting its analysis accuracy.
./gradlew :kotlin-sdk-core:jvmTest :integration-test:jvmTest --tests '*ServerResourceTemplateTest' --rerun-tasks
./gradlew :kotlin-sdk-core:ktlintCheck :integration-test:ktlintCheck :kotlin-sdk-core:checkKotlinAbi

Local allocation evidence

A separate JVM probe measured mean current-thread allocated bytes over 20 calls after 30 warmups:

Rejected path segments Base bytes/call Fixed bytes/call
100 8,048 1,824
1,000 64,872 1,824

These are measurements in the instrumented test environment, not throughput, peak-heap, or end-to-end results. The probe uses maxDepth=2; both inputs fit the normal 2,048-character length limit. Behavioral tests pass before and after, as expected for an allocation improvement.

Accepted paths gain a separator-counting pass. Normalization/trimming can still allocate, and the default URI length limit already bounds inputs. Full multiplatform runtime tests, the whole-repository JVM suite and external conformance were not run.

Manual allocation probe and reproduction

Temporarily save the following as kotlin-sdk-core/src/jvmTest/kotlin/io/modelcontextprotocol/kotlin/sdk/utils/PathAllocationProbeTest.kt in isolated base and PR checkouts, using JDK 21. Run each with a separate output filename:

MCP_ALLOCATION_PROBE_OUTPUT=/tmp/mcp-1084-allocation.txt ./gradlew :kotlin-sdk-core:jvmTest --tests '*PathAllocationProbeTest' --rerun-tasks
cat /tmp/mcp-1084-allocation.txt

Remove the temporary file afterward. It is a diagnostic probe, not a CI allocation threshold.

package io.modelcontextprotocol.kotlin.sdk.utils

import io.modelcontextprotocol.kotlin.sdk.types.ResourceTemplate
import java.lang.management.ManagementFactory
import kotlin.test.Test
import kotlin.test.assertNull

class PathAllocationProbeTest {
    @Test
    fun `measure rejected path allocation`() {
        val bean = ManagementFactory.getThreadMXBean() as com.sun.management.ThreadMXBean
        bean.isThreadAllocatedMemoryEnabled = true
        val threadId = Thread.currentThread().threadId()
        val measurements = mutableListOf<String>()
        for (depth in listOf(100, 1000)) {
            val uri = List(depth) { "a" }.joinToString("/")
            val matcher = PathSegmentTemplateMatcher(ResourceTemplate("a/{id}", "Probe"), 2, Int.MAX_VALUE)
            repeat(30) { assertNull(matcher.match(uri)) }
            val before = bean.getThreadAllocatedBytes(threadId)
            repeat(20) { assertNull(matcher.match(uri)) }
            val allocated = (bean.getThreadAllocatedBytes(threadId) - before) / 20
            measurements.add("depth=$depth bytesPerMatch=$allocated")
        }
        java.nio.file.Files.writeString(
            java.nio.file.Path.of(System.getenv("MCP_ALLOCATION_PROBE_OUTPUT")),
            measurements.joinToString("\n") + "\n",
            java.nio.charset.StandardCharsets.UTF_8,
        )
    }
}

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant