fix(integration-test): refactor integration test infrastructure, fix and enable tests with ts-client (#478)

# Refactor integration test infrastructure, fix and enable tests with
ts-client

- Refactor TypeScript integration test infrastructure to support
parallel execution and real I/O operations.
- Extract reusable TypeScriptClient component
- Migrate some tests from `runTest` to `runBlocking` for tests that
spawn actual processes and communicate over real network connections.

## Key Changes 

  - Extract `TypeScriptClient` class for managing TS client processes
- Move client scripts to integration-test/src/jvmTest/typescript/client/
- Migrate typescript: `myClient.ts`(2) → `sse-client.ts`,
`stdio-client.ts`
  - Automate TypeScript dependency installation in static initializer
  
- Enable JUnit parallel execution (dynamic strategy, concurrent mode)
with test timeout of 2 minutes
- Replace `mutableListOf` with `ConcurrentLinkedQueue` for thread-safe
notification handling
  - Migrate integration tests from `runTest` to `runBlocking`
**Rationale:** Integration tests that spawn real TypeScript processes,
establish actual
HTTP/SSE connections, and manage server lifecycles require real-time I/O
behavior. The runTest framework's virtual time is designed for fast unit
tests with simulated timing, not for integration scenarios where
external processes and network communication must occur in real time.
Parallel execution requires thread-safe data structures
(ConcurrentLinkedQueue)
to safely collect notifications from multiple concurrent test instances.

  - Add `EmbeddedServer.actualPort()` extension to get bound port
  - Standardize kotlin.time.Duration usage across test utilities
  - Update processUtils.stopProcess() to accept Duration parameter
  - Replace RuntimeException checks with idiomatic check() calls
  - Revert `--rerun-tasks` flag to Gradle workflows for reliable builds

## Motivation and Context

Integration tests with typescript client are now broken. Enabling
parallel test execution will force writing thread-safe independent tests
and will highlight problems faster.

## How Has This Been Tested?
CI

## Breaking Changes
<!-- Will users need to update their code or configurations? -->

## Types of changes
<!-- What types of changes does your code introduce? Put an `x` in all
the boxes that apply: -->
- [x] CI Update
- [x] Test Fix

## Checklist
<!-- Go over all the following points, and put an `x` in all the boxes
that apply. -->
- [x] I have read the [MCP
Documentation](https://modelcontextprotocol.io)
- [x] My code follows the repository's style guidelines
- [x] New and existing tests pass locally
- [ ] I have added appropriate error handling
- [ ] I have added or updated documentation as needed

## Additional context
Follow up for #477
This commit is contained in:
Konstantin Pavlov 2026-01-11 09:38:13 +02:00 • committed by GitHub
commit 6ad9bf2122
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
27 changed files with 419 additions and 441 deletions

View file

@ -84,7 +84,7 @@ jobs:
- name: ${{ matrix.job-name }} - name: ${{ matrix.job-name }}
run: |- run: |-
./gradlew ${{ matrix.gradle-tasks }} -x :conformance-test:test --max-workers ${{ matrix.max-workers }} --continue --configure-on-demand --parallel ./gradlew ${{ matrix.gradle-tasks }} -x :conformance-test:test --max-workers ${{ matrix.max-workers }} --continue --rerun-tasks --configure-on-demand --parallel
- name: Upload Reports - name: Upload Reports
if: always() if: always()
@ -168,7 +168,7 @@ jobs:
- name: "Build Sample: ${{ matrix.sample }}" - name: "Build Sample: ${{ matrix.sample }}"
working-directory: ./samples/${{ matrix.sample }} working-directory: ./samples/${{ matrix.sample }}
run: ./gradlew build -Pmcp.kotlin.overrideVersion=1-SNAPSHOT run: ./gradlew build -Pmcp.kotlin.overrideVersion=1-SNAPSHOT --rerun-tasks
- name: Upload Reports - name: Upload Reports
if: ${{ !cancelled() }} if: ${{ !cancelled() }}

View file

@ -35,7 +35,7 @@ jobs:
uses: gradle/actions/setup-gradle@v5 uses: gradle/actions/setup-gradle@v5
- name: Clean Build with Gradle - name: Clean Build with Gradle
run: ./gradlew clean build -x :conformance-test:test run: ./gradlew clean build -x :conformance-test:test --rerun-tasks
- name: Publish to Maven Central Portal - name: Publish to Maven Central Portal
id: publish id: publish

View file

@ -5,6 +5,7 @@ import io.modelcontextprotocol.kotlin.sdk.types.Implementation
import io.modelcontextprotocol.kotlin.sdk.types.McpException import io.modelcontextprotocol.kotlin.sdk.types.McpException
import io.modelcontextprotocol.kotlin.test.utils.createSleepyProcessBuilder import io.modelcontextprotocol.kotlin.test.utils.createSleepyProcessBuilder
import io.modelcontextprotocol.kotlin.test.utils.createTeeProcessBuilder import io.modelcontextprotocol.kotlin.test.utils.createTeeProcessBuilder
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.runTest import kotlinx.coroutines.test.runTest
@ -30,7 +31,7 @@ import kotlin.time.Duration.Companion.seconds
class StdioClientTransportTest : BaseTransportTest() { class StdioClientTransportTest : BaseTransportTest() {
@Test @Test
fun `handle stdio error`(): Unit = runBlocking { fun `handle stdio error`(): Unit = runBlocking(Dispatchers.IO) {
val processBuilder = createSleepyProcessBuilder() val processBuilder = createSleepyProcessBuilder()
val process = processBuilder.start() val process = processBuilder.start()

View file

@ -1,3 +1,5 @@
@file:Suppress("DEPRECATION")
package io.modelcontextprotocol.kotlin.sdk.integration.kotlin.websocket package io.modelcontextprotocol.kotlin.sdk.integration.kotlin.websocket
import io.ktor.client.HttpClient import io.ktor.client.HttpClient
@ -21,11 +23,9 @@ import io.modelcontextprotocol.kotlin.sdk.server.ServerOptions
import io.modelcontextprotocol.kotlin.sdk.server.mcpWebSocket import io.modelcontextprotocol.kotlin.sdk.server.mcpWebSocket
import io.modelcontextprotocol.kotlin.sdk.types.GetPromptRequestParams import io.modelcontextprotocol.kotlin.sdk.types.GetPromptRequestParams
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.test.runTest import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import kotlin.test.Test import kotlin.test.Test
import kotlin.test.assertTrue import kotlin.test.assertTrue
import kotlin.time.Duration.Companion.seconds
import io.ktor.client.engine.cio.CIO as ClientCIO import io.ktor.client.engine.cio.CIO as ClientCIO
import io.ktor.client.plugins.websocket.WebSockets as ClientWebSocket import io.ktor.client.plugins.websocket.WebSockets as ClientWebSocket
import io.ktor.server.cio.CIO as ServerCIO import io.ktor.server.cio.CIO as ServerCIO
@ -34,16 +34,14 @@ import io.ktor.server.websocket.WebSockets as ServerWebSockets
class OldSchemaWebSocketIntegrationTest { class OldSchemaWebSocketIntegrationTest {
@Test @Test
fun `client should be able to connect to websocket server 2`() = runTest(timeout = 5.seconds) { fun `client should be able to connect to websocket server 2`() = runBlocking(Dispatchers.IO) {
var server: EmbeddedServer<CIOApplicationEngine, CIOApplicationEngine.Configuration>? = null var server: EmbeddedServer<CIOApplicationEngine, CIOApplicationEngine.Configuration>? = null
var client: Client? = null var client: Client? = null
try { try {
withContext(Dispatchers.Default) { server = initServer()
server = initServer() val port = server.engine.resolvedConnectors().first().port
val port = server.engine.resolvedConnectors().first().port client = initClient(serverPort = port)
client = initClient(serverPort = port)
}
} finally { } finally {
client?.close() client?.close()
server?.stop(1000, 2000) server?.stop(1000, 2000)
@ -58,19 +56,17 @@ class OldSchemaWebSocketIntegrationTest {
* 3. Observe that Client A receives a response related to it. * 3. Observe that Client A receives a response related to it.
*/ */
@Test @Test
fun `single websocket connection`() = runTest(timeout = 5.seconds) { fun `single websocket connection`() = runBlocking(Dispatchers.IO) {
var server: EmbeddedServer<CIOApplicationEngine, CIOApplicationEngine.Configuration>? = null var server: EmbeddedServer<CIOApplicationEngine, CIOApplicationEngine.Configuration>? = null
var client: Client? = null var client: Client? = null
try { try {
withContext(Dispatchers.Default) { server = initServer()
server = initServer() val port = server.engine.resolvedConnectors().first().port
val port = server.engine.resolvedConnectors().first().port client = initClient("Client A", port)
client = initClient("Client A", port)
val promptA = getPrompt(client, "Client A") val promptA = getPrompt(client, "Client A")
assertTrue { "Client A" in promptA } assertTrue { "Client A" in promptA }
}
} finally { } finally {
client?.close() client?.close()
server?.stop(1000, 2000) server?.stop(1000, 2000)
@ -86,26 +82,24 @@ class OldSchemaWebSocketIntegrationTest {
* 4. Observe that Client B (connection #2) receives a response related to sessionId#1. * 4. Observe that Client B (connection #2) receives a response related to sessionId#1.
*/ */
@Test @Test
fun `multiple websocket connections`() = runTest(timeout = 5.seconds) { fun `multiple websocket connections`() = runBlocking(Dispatchers.IO) {
var server: EmbeddedServer<CIOApplicationEngine, CIOApplicationEngine.Configuration>? = null var server: EmbeddedServer<CIOApplicationEngine, CIOApplicationEngine.Configuration>? = null
var clientA: Client? = null var clientA: Client? = null
var clientB: Client? = null var clientB: Client? = null
try { try {
withContext(Dispatchers.Default) { server = initServer()
server = initServer() val port = server.engine.resolvedConnectors().first().port
val port = server.engine.resolvedConnectors().first().port clientA = initClient("Client A", port)
clientA = initClient("Client A", port) clientB = initClient("Client B", port)
clientB = initClient("Client B", port)
// Step 3: Send a prompt request from Client A // Step 3: Send a prompt request from Client A
val promptA = getPrompt(clientA, "Client A") val promptA = getPrompt(clientA, "Client A")
// Step 4: Send a prompt request from Client B // Step 4: Send a prompt request from Client B
val promptB = getPrompt(clientB, "Client B") val promptB = getPrompt(clientB, "Client B")
assertTrue { "Client A" in promptA } assertTrue { "Client A" in promptA }
assertTrue { "Client B" in promptB } assertTrue { "Client B" in promptB }
}
} finally { } finally {
clientA?.close() clientA?.close()
clientB?.close() clientB?.close()

View file

@ -21,11 +21,9 @@ import io.modelcontextprotocol.kotlin.sdk.types.Role
import io.modelcontextprotocol.kotlin.sdk.types.ServerCapabilities import io.modelcontextprotocol.kotlin.sdk.types.ServerCapabilities
import io.modelcontextprotocol.kotlin.sdk.types.TextContent import io.modelcontextprotocol.kotlin.sdk.types.TextContent
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.test.runTest import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import kotlin.test.Test import kotlin.test.Test
import kotlin.test.assertTrue import kotlin.test.assertTrue
import kotlin.time.Duration.Companion.seconds
import io.ktor.client.engine.cio.CIO as ClientCIO import io.ktor.client.engine.cio.CIO as ClientCIO
import io.ktor.client.plugins.websocket.WebSockets as ClientWebSocket import io.ktor.client.plugins.websocket.WebSockets as ClientWebSocket
import io.ktor.server.cio.CIO as ServerCIO import io.ktor.server.cio.CIO as ServerCIO
@ -34,16 +32,14 @@ import io.ktor.server.websocket.WebSockets as ServerWebSockets
class WebSocketIntegrationTest { class WebSocketIntegrationTest {
@Test @Test
fun `client should be able to connect to websocket server 2`() = runTest(timeout = 5.seconds) { fun `client should be able to connect to websocket server 2`() = runBlocking(Dispatchers.IO) {
var server: EmbeddedServer<CIOApplicationEngine, CIOApplicationEngine.Configuration>? = null var server: EmbeddedServer<CIOApplicationEngine, CIOApplicationEngine.Configuration>? = null
var client: Client? = null var client: Client? = null
try { try {
withContext(Dispatchers.Default) { server = initServer()
server = initServer() val port = server.engine.resolvedConnectors().first().port
val port = server.engine.resolvedConnectors().first().port client = initClient(serverPort = port)
client = initClient(serverPort = port)
}
} finally { } finally {
client?.close() client?.close()
server?.stop(1000, 2000) server?.stop(1000, 2000)
@ -58,19 +54,17 @@ class WebSocketIntegrationTest {
* 3. Observe that Client A receives a response related to it. * 3. Observe that Client A receives a response related to it.
*/ */
@Test @Test
fun `single websocket connection`() = runTest(timeout = 5.seconds) { fun `single websocket connection`() = runBlocking(Dispatchers.IO) {
var server: EmbeddedServer<CIOApplicationEngine, CIOApplicationEngine.Configuration>? = null var server: EmbeddedServer<CIOApplicationEngine, CIOApplicationEngine.Configuration>? = null
var client: Client? = null var client: Client? = null
try { try {
withContext(Dispatchers.Default) { server = initServer()
server = initServer() val port = server.engine.resolvedConnectors().first().port
val port = server.engine.resolvedConnectors().first().port client = initClient("Client A", port)
client = initClient("Client A", port)
val promptA = getPrompt(client, "Client A") val promptA = getPrompt(client, "Client A")
assertTrue { "Client A" in promptA } assertTrue { "Client A" in promptA }
}
} finally { } finally {
client?.close() client?.close()
server?.stop(1000, 2000) server?.stop(1000, 2000)
@ -86,26 +80,24 @@ class WebSocketIntegrationTest {
* 4. Observe that Client B (connection #2) receives a response related to sessionId#1. * 4. Observe that Client B (connection #2) receives a response related to sessionId#1.
*/ */
@Test @Test
fun `multiple websocket connections`() = runTest(timeout = 5.seconds) { fun `multiple websocket connections`() = runBlocking(Dispatchers.IO) {
var server: EmbeddedServer<CIOApplicationEngine, CIOApplicationEngine.Configuration>? = null var server: EmbeddedServer<CIOApplicationEngine, CIOApplicationEngine.Configuration>? = null
var clientA: Client? = null var clientA: Client? = null
var clientB: Client? = null var clientB: Client? = null
try { try {
withContext(Dispatchers.Default) { server = initServer()
server = initServer() val port = server.engine.resolvedConnectors().first().port
val port = server.engine.resolvedConnectors().first().port clientA = initClient("Client A", port)
clientA = initClient("Client A", port) clientB = initClient("Client B", port)
clientB = initClient("Client B", port)
// Step 3: Send a prompt request from Client A // Step 3: Send a prompt request from Client A
val promptA = getPrompt(clientA, "Client A") val promptA = getPrompt(clientA, "Client A")
// Step 4: Send a prompt request from Client B // Step 4: Send a prompt request from Client B
val promptB = getPrompt(clientB, "Client B") val promptB = getPrompt(clientB, "Client B")
assertTrue { "Client A" in promptA } assertTrue { "Client A" in promptA }
assertTrue { "Client B" in promptB } assertTrue { "Client B" in promptB }
}
} finally { } finally {
clientA?.close() clientA?.close()
clientB?.close() clientB?.close()

View file

@ -25,8 +25,6 @@ import io.ktor.server.sse.SSE as ServerSSE
open class AbstractSseIntegrationTest { open class AbstractSseIntegrationTest {
suspend fun EmbeddedServer<*, *>.actualPort() = engine.resolvedConnectors().single().port
suspend fun initTestClient(serverPort: Int, name: String? = null): Client { suspend fun initTestClient(serverPort: Int, name: String? = null): Client {
val client = Client( val client = Client(
Implementation(name = name ?: DEFAULT_CLIENT_NAME, version = VERSION), Implementation(name = name ?: DEFAULT_CLIENT_NAME, version = VERSION),

View file

@ -1,3 +1,5 @@
@file:Suppress("DEPRECATION")
package io.modelcontextprotocol.kotlin.sdk.integration.sse package io.modelcontextprotocol.kotlin.sdk.integration.sse
import io.ktor.client.HttpClient import io.ktor.client.HttpClient
@ -25,8 +27,6 @@ import io.ktor.server.sse.SSE as ServerSSE
open class OldSchemaAbstractSseIntegrationTest { open class OldSchemaAbstractSseIntegrationTest {
suspend fun EmbeddedServer<*, *>.actualPort() = engine.resolvedConnectors().single().port
suspend fun initTestClient(serverPort: Int, name: String? = null): Client { suspend fun initTestClient(serverPort: Int, name: String? = null): Client {
val client = Client( val client = Client(
Implementation(name = name ?: DEFAULT_CLIENT_NAME, version = VERSION), Implementation(name = name ?: DEFAULT_CLIENT_NAME, version = VERSION),

View file

@ -1,3 +1,5 @@
@file:Suppress("DEPRECATION")
package io.modelcontextprotocol.kotlin.sdk.integration.sse package io.modelcontextprotocol.kotlin.sdk.integration.sse
import io.ktor.server.cio.CIOApplicationEngine import io.ktor.server.cio.CIOApplicationEngine
@ -6,26 +8,23 @@ import io.modelcontextprotocol.kotlin.sdk.GetPromptRequest
import io.modelcontextprotocol.kotlin.sdk.TextContent import io.modelcontextprotocol.kotlin.sdk.TextContent
import io.modelcontextprotocol.kotlin.sdk.client.Client import io.modelcontextprotocol.kotlin.sdk.client.Client
import io.modelcontextprotocol.kotlin.sdk.types.GetPromptRequestParams import io.modelcontextprotocol.kotlin.sdk.types.GetPromptRequestParams
import io.modelcontextprotocol.kotlin.test.utils.actualPort
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.test.runTest import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import kotlin.test.Test import kotlin.test.Test
import kotlin.test.assertTrue import kotlin.test.assertTrue
import kotlin.time.Duration.Companion.seconds
class OldSchemaSseIntegrationTest : OldSchemaAbstractSseIntegrationTest() { class OldSchemaSseIntegrationTest : OldSchemaAbstractSseIntegrationTest() {
@Test @Test
fun `client should be able to connect to sse server`() = runTest(timeout = 5.seconds) { fun `client should be able to connect to sse server`() = runBlocking(Dispatchers.IO) {
var server: EmbeddedServer<CIOApplicationEngine, CIOApplicationEngine.Configuration>? = null var server: EmbeddedServer<CIOApplicationEngine, CIOApplicationEngine.Configuration>? = null
var client: Client? = null var client: Client? = null
try { try {
withContext(Dispatchers.Default) { server = initTestServer()
server = initTestServer() val port = server.actualPort()
val port = server.engine.resolvedConnectors().single().port client = initTestClient(serverPort = port)
client = initTestClient(serverPort = port)
}
} finally { } finally {
client?.close() client?.close()
server?.stopSuspend(1000, 2000) server?.stopSuspend(1000, 2000)
@ -40,18 +39,16 @@ class OldSchemaSseIntegrationTest : OldSchemaAbstractSseIntegrationTest() {
* 3. Observe that Client A receives a response related to it. * 3. Observe that Client A receives a response related to it.
*/ */
@Test @Test
fun `single sse connection`() = runTest(timeout = 5.seconds) { fun `single sse connection`() = runBlocking(Dispatchers.IO) {
var server: EmbeddedServer<CIOApplicationEngine, CIOApplicationEngine.Configuration>? = null var server: EmbeddedServer<CIOApplicationEngine, CIOApplicationEngine.Configuration>? = null
var client: Client? = null var client: Client? = null
try { try {
withContext(Dispatchers.Default) { server = initTestServer()
server = initTestServer() val port = server.actualPort()
val port = server.engine.resolvedConnectors().single().port client = initTestClient(port, "Client A")
client = initTestClient(port, "Client A")
val promptA = getPrompt(client, "Client A") val promptA = getPrompt(client, "Client A")
assertTrue { "Client A" in promptA } assertTrue { "Client A" in promptA }
}
} finally { } finally {
client?.close() client?.close()
server?.stopSuspend(1000, 2000) server?.stopSuspend(1000, 2000)
@ -67,27 +64,25 @@ class OldSchemaSseIntegrationTest : OldSchemaAbstractSseIntegrationTest() {
* 4. Observe that Client B (connection #2) receives a response related to sessionId#1. * 4. Observe that Client B (connection #2) receives a response related to sessionId#1.
*/ */
@Test @Test
fun `multiple sse connections`() = runTest(timeout = 5.seconds) { fun `multiple sse connections`() = runBlocking(Dispatchers.IO) {
var server: EmbeddedServer<CIOApplicationEngine, CIOApplicationEngine.Configuration>? = null var server: EmbeddedServer<CIOApplicationEngine, CIOApplicationEngine.Configuration>? = null
var clientA: Client? = null var clientA: Client? = null
var clientB: Client? = null var clientB: Client? = null
try { try {
withContext(Dispatchers.Default) { server = initTestServer()
server = initTestServer() val port = server.engine.resolvedConnectors().first().port
val port = server.engine.resolvedConnectors().first().port
clientA = initTestClient(port, "Client A") clientA = initTestClient(port, "Client A")
clientB = initTestClient(port, "Client B") clientB = initTestClient(port, "Client B")
// Step 3: Send a prompt request from Client A // Step 3: Send a prompt request from Client A
val promptA = getPrompt(clientA, "Client A") val promptA = getPrompt(clientA, "Client A")
// Step 4: Send a prompt request from Client B // Step 4: Send a prompt request from Client B
val promptB = getPrompt(clientB, "Client B") val promptB = getPrompt(clientB, "Client B")
assertTrue { "Client A" in promptA } assertTrue { "Client A" in promptA }
assertTrue { "Client B" in promptB } assertTrue { "Client B" in promptB }
}
} finally { } finally {
clientA?.close() clientA?.close()
clientB?.close() clientB?.close()

View file

@ -6,26 +6,23 @@ import io.modelcontextprotocol.kotlin.sdk.client.Client
import io.modelcontextprotocol.kotlin.sdk.types.GetPromptRequest import io.modelcontextprotocol.kotlin.sdk.types.GetPromptRequest
import io.modelcontextprotocol.kotlin.sdk.types.GetPromptRequestParams import io.modelcontextprotocol.kotlin.sdk.types.GetPromptRequestParams
import io.modelcontextprotocol.kotlin.sdk.types.TextContent import io.modelcontextprotocol.kotlin.sdk.types.TextContent
import io.modelcontextprotocol.kotlin.test.utils.actualPort
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.test.runTest import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import kotlin.test.Test import kotlin.test.Test
import kotlin.test.assertTrue import kotlin.test.assertTrue
import kotlin.time.Duration.Companion.seconds
class SseIntegrationTest : AbstractSseIntegrationTest() { class SseIntegrationTest : AbstractSseIntegrationTest() {
@Test @Test
fun `client should be able to connect to sse server`() = runTest(timeout = 5.seconds) { fun `client should be able to connect to sse server`() = runBlocking(Dispatchers.IO) {
var server: EmbeddedServer<CIOApplicationEngine, CIOApplicationEngine.Configuration>? = null var server: EmbeddedServer<CIOApplicationEngine, CIOApplicationEngine.Configuration>? = null
var client: Client? = null var client: Client? = null
try { try {
withContext(Dispatchers.Default) { server = initTestServer()
server = initTestServer() val port = server.actualPort()
val port = server.engine.resolvedConnectors().single().port client = initTestClient(serverPort = port)
client = initTestClient(serverPort = port)
}
} finally { } finally {
client?.close() client?.close()
server?.stopSuspend(1000, 2000) server?.stopSuspend(1000, 2000)
@ -40,18 +37,16 @@ class SseIntegrationTest : AbstractSseIntegrationTest() {
* 3. Observe that Client A receives a response related to it. * 3. Observe that Client A receives a response related to it.
*/ */
@Test @Test
fun `single sse connection`() = runTest(timeout = 5.seconds) { fun `single sse connection`() = runBlocking(Dispatchers.IO) {
var server: EmbeddedServer<CIOApplicationEngine, CIOApplicationEngine.Configuration>? = null var server: EmbeddedServer<CIOApplicationEngine, CIOApplicationEngine.Configuration>? = null
var client: Client? = null var client: Client? = null
try { try {
withContext(Dispatchers.Default) { server = initTestServer()
server = initTestServer() val port = server.actualPort()
val port = server.engine.resolvedConnectors().single().port client = initTestClient(port, "Client A")
client = initTestClient(port, "Client A")
val promptA = getPrompt(client, "Client A") val promptA = getPrompt(client, "Client A")
assertTrue { "Client A" in promptA } assertTrue { "Client A" in promptA }
}
} finally { } finally {
client?.close() client?.close()
server?.stopSuspend(1000, 2000) server?.stopSuspend(1000, 2000)
@ -67,27 +62,25 @@ class SseIntegrationTest : AbstractSseIntegrationTest() {
* 4. Observe that Client B (connection #2) receives a response related to sessionId#1. * 4. Observe that Client B (connection #2) receives a response related to sessionId#1.
*/ */
@Test @Test
fun `multiple sse connections`() = runTest(timeout = 5.seconds) { fun `multiple sse connections`() = runBlocking(Dispatchers.IO) {
var server: EmbeddedServer<CIOApplicationEngine, CIOApplicationEngine.Configuration>? = null var server: EmbeddedServer<CIOApplicationEngine, CIOApplicationEngine.Configuration>? = null
var clientA: Client? = null var clientA: Client? = null
var clientB: Client? = null var clientB: Client? = null
try { try {
withContext(Dispatchers.Default) { server = initTestServer()
server = initTestServer() val port = server.actualPort()
val port = server.engine.resolvedConnectors().first().port
clientA = initTestClient(port, "Client A") clientA = initTestClient(port, "Client A")
clientB = initTestClient(port, "Client B") clientB = initTestClient(port, "Client B")
// Step 3: Send a prompt request from Client A // Step 3: Send a prompt request from Client A
val promptA = getPrompt(clientA, "Client A") val promptA = getPrompt(clientA, "Client A")
// Step 4: Send a prompt request from Client B // Step 4: Send a prompt request from Client B
val promptB = getPrompt(clientB, "Client B") val promptB = getPrompt(clientB, "Client B")
assertTrue { "Client A" in promptA } assertTrue { "Client A" in promptA }
assertTrue { "Client B" in promptB } assertTrue { "Client B" in promptB }
}
} finally { } finally {
clientA?.close() clientA?.close()
clientB?.close() clientB?.close()

View file

@ -2,7 +2,6 @@ package io.modelcontextprotocol.kotlin.sdk.integration.typescript
import io.modelcontextprotocol.kotlin.sdk.client.Client import io.modelcontextprotocol.kotlin.sdk.client.Client
import io.modelcontextprotocol.kotlin.sdk.types.TextContent import io.modelcontextprotocol.kotlin.sdk.types.TextContent
import io.modelcontextprotocol.kotlin.test.utils.DisabledOnCI
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking import kotlinx.coroutines.runBlocking
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Test
@ -12,7 +11,6 @@ import kotlin.test.assertEquals
import kotlin.test.assertNotNull import kotlin.test.assertNotNull
import kotlin.test.assertTrue import kotlin.test.assertTrue
@DisabledOnCI
abstract class AbstractKotlinClientTsServerTest : TsTestBase() { abstract class AbstractKotlinClientTsServerTest : TsTestBase() {
protected abstract suspend fun <T> useClient(block: suspend (Client) -> T): T protected abstract suspend fun <T> useClient(block: suspend (Client) -> T): T

View file

@ -1,13 +1,14 @@
package io.modelcontextprotocol.kotlin.sdk.integration.typescript package io.modelcontextprotocol.kotlin.sdk.integration.typescript
import io.modelcontextprotocol.kotlin.test.utils.DisabledOnCI import io.kotest.assertions.nondeterministic.eventually
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.runTest import kotlinx.coroutines.test.runTest
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Test
import org.junit.jupiter.api.Timeout import org.junit.jupiter.api.Timeout
import java.util.concurrent.TimeUnit import java.util.concurrent.TimeUnit
import kotlin.test.assertTrue import kotlin.test.assertTrue
import kotlin.time.Duration.Companion.seconds
@DisabledOnCI
abstract class AbstractTsClientKotlinServerTest : TsTestBase() { abstract class AbstractTsClientKotlinServerTest : TsTestBase() {
protected open fun beforeServer() {} protected open fun beforeServer() {}
@ -25,8 +26,10 @@ abstract class AbstractTsClientKotlinServerTest : TsTestBase() {
try { try {
val testName = "TestUser" val testName = "TestUser"
val out = runClient("greet", testName) val out = runClient("greet", testName)
assertTrue(out.contains("Text content:"), "Output should contain the text content section.\n$out") eventually(5.seconds) {
assertTrue(out.contains("Hello, $testName!"), "Tool response should contain the greeting.\n$out") assertTrue(out.contains("Text content:"), "Output should contain the text content section.\n$out")
assertTrue(out.contains("Hello, $testName!"), "Tool response should contain the greeting.\n$out")
}
assertTrue( assertTrue(
out.contains("Structured content:"), out.contains("Structured content:"),
"Output should contain the structured content section.\n$out", "Output should contain the structured content section.\n$out",
@ -46,7 +49,7 @@ abstract class AbstractTsClientKotlinServerTest : TsTestBase() {
@Test @Test
@Timeout(60, unit = TimeUnit.SECONDS) @Timeout(60, unit = TimeUnit.SECONDS)
fun notifications() = runTest { fun notifications() = runBlocking {
beforeServer() beforeServer()
try { try {
val name = "NotifUser" val name = "NotifUser"
@ -66,7 +69,7 @@ abstract class AbstractTsClientKotlinServerTest : TsTestBase() {
@Test @Test
@Timeout(120, unit = TimeUnit.SECONDS) @Timeout(120, unit = TimeUnit.SECONDS)
fun multipleClientSequence() = runTest { fun multipleClientSequence() = runBlocking {
beforeServer() beforeServer()
try { try {
val out1 = runClient("greet", "FirstClient") val out1 = runClient("greet", "FirstClient")

View file

@ -11,7 +11,7 @@ import io.modelcontextprotocol.kotlin.sdk.server.Server
import io.modelcontextprotocol.kotlin.sdk.server.StdioServerTransport import io.modelcontextprotocol.kotlin.sdk.server.StdioServerTransport
import io.modelcontextprotocol.kotlin.sdk.types.Implementation import io.modelcontextprotocol.kotlin.sdk.types.Implementation
import io.modelcontextprotocol.kotlin.test.utils.Retry import io.modelcontextprotocol.kotlin.test.utils.Retry
import io.modelcontextprotocol.kotlin.test.utils.TypeScriptRunner import io.modelcontextprotocol.kotlin.test.utils.TypeScriptRunner.installDependencies
import io.modelcontextprotocol.kotlin.test.utils.isWindows import io.modelcontextprotocol.kotlin.test.utils.isWindows
import kotlinx.coroutines.withTimeout import kotlinx.coroutines.withTimeout
import kotlinx.io.Sink import kotlinx.io.Sink
@ -19,12 +19,11 @@ import kotlinx.io.Source
import kotlinx.io.asSink import kotlinx.io.asSink
import kotlinx.io.asSource import kotlinx.io.asSource
import kotlinx.io.buffered import kotlinx.io.buffered
import org.junit.jupiter.api.BeforeAll
import java.io.BufferedReader import java.io.BufferedReader
import java.io.File import java.io.File
import java.io.InputStreamReader import java.io.InputStreamReader
import java.util.concurrent.TimeUnit import java.util.concurrent.TimeUnit
import kotlin.io.path.createTempDirectory import kotlin.time.Duration
import kotlin.time.Duration.Companion.seconds import kotlin.time.Duration.Companion.seconds
enum class TransportKind { SSE, STDIO } enum class TransportKind { SSE, STDIO }
@ -34,20 +33,14 @@ abstract class TsTestBase {
protected abstract val transportKind: TransportKind protected abstract val transportKind: TransportKind
protected val tsClient: TypeScriptClient get() = TypeScriptClient(typescriptDir)
companion object { companion object {
@JvmStatic @JvmStatic
protected val projectRoot: File get() = File(System.getProperty("user.dir")) protected val projectRoot = File(System.getProperty("user.dir"))
@JvmStatic @JvmStatic
protected val tsClientDir: File protected val typescriptDir = File(projectRoot, "src/jvmTest/typescript")
get() = File(projectRoot, "src/jvmTest/typescript")
@JvmStatic
protected val tsSourceDir: File
get() = File(
projectRoot,
"src/jvmTest/kotlin/io/modelcontextprotocol/kotlin/sdk/integration/typescript",
)
@JvmStatic @JvmStatic
private var sharedSseServer: Process? = null private var sharedSseServer: Process? = null
@ -55,12 +48,16 @@ abstract class TsTestBase {
@JvmStatic @JvmStatic
private var sharedSsePort: Int = 0 private var sharedSsePort: Int = 0
init {
installDependencies(typescriptDir)
}
@JvmStatic @JvmStatic
@Synchronized @Synchronized
protected fun getSharedSseUrl(): String { protected fun getSharedSseUrl(): String {
if (sharedSseServer == null || !sharedSseServer!!.isAlive) { if (sharedSseServer == null || !sharedSseServer!!.isAlive) {
sharedSsePort = io.modelcontextprotocol.kotlin.test.utils.findFreePort() sharedSsePort = io.modelcontextprotocol.kotlin.test.utils.findFreePort()
val server = TypeScriptServer(tsClientDir) val server = TypeScriptServer(typescriptDir)
sharedSseServer = server.startSse(sharedSsePort) sharedSseServer = server.startSse(sharedSsePort)
println("Shared TypeScript SSE server started on port $sharedSsePort") println("Shared TypeScript SSE server started on port $sharedSsePort")
@ -76,69 +73,6 @@ abstract class TsTestBase {
return "http://localhost:$sharedSsePort/mcp" return "http://localhost:$sharedSsePort/mcp"
} }
@JvmStatic
private val tempRootDir: File = createTempDirectory("typescript-sdk-").toFile().apply { deleteOnExit() }
@JvmStatic
protected val sdkDir: File = File(tempRootDir, "typescript-sdk")
@JvmStatic
@BeforeAll
@Deprecated("Use setupTypeScriptSdkWithDependencies instead")
fun setupTypeScriptSdk() {
println("Cloning TypeScript SDK repository")
if (!sdkDir.exists()) {
val process = ProcessBuilder(
"git",
"clone",
"--depth",
"1",
"https://github.com/modelcontextprotocol/typescript-sdk.git",
sdkDir.absolutePath,
)
.redirectErrorStream(true)
.start()
val exitCode = process.waitFor()
require(exitCode == 0) {
"Failed to clone TypeScript SDK repository: exit code $exitCode"
}
}
println("Installing TypeScript SDK dependencies")
val npmInstallResult = executeCommand("npm install", sdkDir, allowFailure = true, timeoutSeconds = null)
if (npmInstallResult.contains("EUNSUPPORTEDPROTOCOL") || npmInstallResult.contains("catalog:")) {
println("npm install failed due to catalog protocol. Trying pnpm...")
try {
// Try to use npx pnpm to ensure it's available
executeCommand("npx pnpm install", sdkDir, allowFailure = false, timeoutSeconds = null)
} catch (e: Exception) {
println("pnpm install failed or not found: ${e.message}")
println("Attempting to patch package.json to remove catalog: protocol and use npm")
patchPackageJson(sdkDir)
// Also patch other package.json files in the workspace if they exist
sdkDir.walk().filter { it.name == "package.json" }.forEach { patchPackageJson(it.parentFile) }
executeCommand("npm install", sdkDir, allowFailure = false, timeoutSeconds = null)
}
}
}
@Deprecated("never patch package.json")
private fun patchPackageJson(dir: File) {
val packageJson = File(dir, "package.json")
if (!packageJson.exists()) return
var content = packageJson.readText()
// Replace "catalog:something" with "*" or a reasonable default if we knew it.
// Since we don't know the exact versions in the catalog, "*" is a risky but possible fallback for tests.
// However, a better approach is to use pnpm if available.
content = content.replace(Regex(""""catalog:[^"]*""""), "\"*\"")
// Also replace workspace: protocol if we are using npm fallback
content = content.replace(Regex(""""workspace:[^"]*""""), "\"*\"")
// And any other unsupported protocols that might be in the package.json
content = content.replace(Regex(""""link:[^"]*""""), "\"*\"")
packageJson.writeText(content)
}
@JvmStatic @JvmStatic
protected fun executeCommand( protected fun executeCommand(
command: String, command: String,
@ -147,21 +81,21 @@ abstract class TsTestBase {
timeoutSeconds: Long? = null, timeoutSeconds: Long? = null,
): String { ): String {
if (!workingDir.exists()) { if (!workingDir.exists()) {
if (!workingDir.mkdirs()) { check(workingDir.mkdirs()) {
throw RuntimeException("Failed to create working directory: ${workingDir.absolutePath}") "Failed to create working directory: ${workingDir.absolutePath}"
} }
} }
if (!workingDir.isDirectory || !workingDir.canRead()) { check(workingDir.isDirectory && workingDir.canRead()) {
throw RuntimeException("Working directory is not accessible: ${workingDir.absolutePath}") "Working directory is not accessible: ${workingDir.absolutePath}"
} }
val processBuilder = if (isWindows) { val processBuilder = if (isWindows) {
ProcessBuilder() ProcessBuilder()
.command("cmd.exe", "/c", "set TYPESCRIPT_SDK_DIR=${sdkDir.absolutePath} && $command") .command("cmd.exe", "/c", command)
} else { } else {
ProcessBuilder() ProcessBuilder()
.command("bash", "-c", "TYPESCRIPT_SDK_DIR='${sdkDir.absolutePath}' $command") .command("bash", "-c", command)
} }
val process = processBuilder val process = processBuilder
@ -192,24 +126,18 @@ abstract class TsTestBase {
} }
} }
private fun waitForProcessTermination(process: Process, timeoutSeconds: Long): Boolean {
io.modelcontextprotocol.kotlin.test.utils.stopProcess(process)
return true
}
protected fun waitForPort(host: String = "localhost", port: Int, timeoutSeconds: Long = 10): Boolean = protected fun waitForPort(host: String = "localhost", port: Int, timeoutSeconds: Long = 10): Boolean =
io.modelcontextprotocol.kotlin.test.utils.waitForPort(host, port, timeoutSeconds) io.modelcontextprotocol.kotlin.test.utils.waitForPort(host, port, timeoutSeconds)
protected fun executeCommandAllowingFailure(command: String, workingDir: File, timeoutSeconds: Long = 20): String = protected fun executeCommandAllowingFailure(command: String, workingDir: File, timeoutSeconds: Long = 20): String =
executeCommand(command, workingDir, allowFailure = true, timeoutSeconds = timeoutSeconds) executeCommand(command, workingDir, allowFailure = true, timeoutSeconds = timeoutSeconds)
protected fun startTypeScriptServer(port: Int): Process { protected fun stopProcess(
val server = TypeScriptServer(tsClientDir) process: Process,
return server.startSse(port) waitDuration: Duration = 3.seconds,
} name: String = "TypeScript server",
) {
protected fun stopProcess(process: Process, waitSeconds: Long = 3, name: String = "TypeScript server") { io.modelcontextprotocol.kotlin.test.utils.stopProcess(process, waitDuration)
io.modelcontextprotocol.kotlin.test.utils.stopProcess(process)
println("$name stopped") println("$name stopped")
} }
@ -232,7 +160,7 @@ abstract class TsTestBase {
// ===== STDIO client + server helpers ===== // ===== STDIO client + server helpers =====
protected fun startTypeScriptServerStdio(): Process { protected fun startTypeScriptServerStdio(): Process {
val server = TypeScriptServer(tsClientDir) val server = TypeScriptServer(typescriptDir)
return server.startStdio() return server.startStdio()
} }
@ -263,22 +191,9 @@ abstract class TsTestBase {
} }
// ===== Helpers to run TypeScript client over STDIO against Kotlin server over STDIO ===== // ===== Helpers to run TypeScript client over STDIO against Kotlin server over STDIO =====
protected fun runStdioClient(vararg args: String): String { protected fun runStdioClient(vararg args: String): String = tsClient.use { client ->
// Start Node stdio client (it will speak MCP over its stdout/stdin) // Start Node stdio client (it will speak MCP over its stdout/stdin)
val subDirName = when (transportKind) { val process = client.startStdio(args.toList(), log = false)
TransportKind.STDIO -> "stdio"
TransportKind.SSE -> "sse"
}
val clientPath = File(tsSourceDir, "$subDirName/myClient.ts").absolutePath
val process = TypeScriptRunner.run(
typescriptDir = tsClientDir,
scriptPath = clientPath,
arguments = args.toList(),
env = mapOf("TYPESCRIPT_SDK_DIR" to sdkDir.absolutePath),
redirectErrorStream = false,
logPrefix = "TS-CLIENT-STDIO",
)
// Create Kotlin server and attach stdio transport to the process streams // Create Kotlin server and attach stdio transport to the process streams
val server: Server = KotlinServerForTsClient().createMcpServer() val server: Server = KotlinServerForTsClient().createMcpServer()
@ -327,6 +242,6 @@ abstract class TsTestBase {
} catch (_: Exception) { } catch (_: Exception) {
} }
return output.toString() output.toString()
} }
} }

View file

@ -0,0 +1,69 @@
package io.modelcontextprotocol.kotlin.sdk.integration.typescript
import io.modelcontextprotocol.kotlin.test.utils.TypeScriptRunner
import io.modelcontextprotocol.kotlin.test.utils.stopProcess
import java.io.File
/**
* Component for starting and managing TypeScript MCP clients for integration tests.
*
* This class provides methods to start TypeScript clients using SSE or STDIO transports.
* The clients are started using npx tsx to execute TypeScript files directly.
*/
class TypeScriptClient(private val typescriptDir: File) : AutoCloseable {
private var process: Process? = null
/**
* Starts a TypeScript MCP client using SSE transport.
*
* @param arguments Arguments to pass to the client (typically server URL, tool name, and tool args)
* @param log Whether to automatically log process output/error
* @return The started Process
*/
fun startSse(arguments: List<String>, log: Boolean = true): Process {
val scriptPath = File(typescriptDir, "client/sse-client.ts").absolutePath
val proc = TypeScriptRunner.run(
typescriptDir = typescriptDir,
scriptPath = scriptPath,
arguments = arguments,
env = emptyMap(),
redirectErrorStream = false,
logPrefix = "TS-CLIENT-SSE",
log = log,
)
process = proc
return proc
}
/**
* Starts a TypeScript MCP client using STDIO transport.
*
* @param arguments Arguments to pass to the client (typically tool name and tool args)
* @param log Whether to automatically log process output/error
* @return The started Process
*/
fun startStdio(arguments: List<String>, log: Boolean = true): Process {
val scriptPath = File(typescriptDir, "client/stdio-client.ts").absolutePath
val proc = TypeScriptRunner.run(
typescriptDir = typescriptDir,
scriptPath = scriptPath,
arguments = arguments,
env = emptyMap(),
redirectErrorStream = false,
logPrefix = "TS-CLIENT-STDIO",
log = log,
)
process = proc
return proc
}
/**
* Stops the currently running client process.
*/
override fun close() {
process?.let {
stopProcess(it)
}
process = null
}
}

View file

@ -25,7 +25,6 @@ class KotlinClientTsServerEdgeCasesTestSse : TsTestBase() {
override val transportKind = TransportKind.SSE override val transportKind = TransportKind.SSE
private val host = "localhost"
private val serverUrl: String by lazy { getSharedSseUrl() } private val serverUrl: String by lazy { getSharedSseUrl() }
private lateinit var client: Client private lateinit var client: Client

View file

@ -2,13 +2,11 @@ package io.modelcontextprotocol.kotlin.sdk.integration.typescript.sse
import io.modelcontextprotocol.kotlin.sdk.integration.typescript.AbstractTsClientKotlinServerTest import io.modelcontextprotocol.kotlin.sdk.integration.typescript.AbstractTsClientKotlinServerTest
import io.modelcontextprotocol.kotlin.sdk.integration.typescript.TransportKind import io.modelcontextprotocol.kotlin.sdk.integration.typescript.TransportKind
import io.modelcontextprotocol.kotlin.test.utils.DisabledOnCI
import io.modelcontextprotocol.kotlin.test.utils.findFreePort import io.modelcontextprotocol.kotlin.test.utils.findFreePort
import io.modelcontextprotocol.kotlin.test.utils.killProcessOnPort import io.modelcontextprotocol.kotlin.test.utils.killProcessOnPort
import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.BeforeEach
@DisabledOnCI
class TsClientKotlinServerTestSse : AbstractTsClientKotlinServerTest() { class TsClientKotlinServerTestSse : AbstractTsClientKotlinServerTest() {
override val transportKind = TransportKind.SSE override val transportKind = TransportKind.SSE
@ -37,18 +35,16 @@ class TsClientKotlinServerTestSse : AbstractTsClientKotlinServerTest() {
} }
} }
override fun beforeServer() {} override fun runClient(vararg args: String): String = tsClient.use { client ->
override fun afterServer() {} val process = client.startSse(listOf(serverUrl) + args.toList(), log = true)
val output = StringBuilder()
override fun runClient(vararg args: String): String { process.inputStream.bufferedReader().useLines { lines ->
val cmd = buildString { lines.forEach { line ->
append("npx tsx myClient.ts ") println("[TS-CLIENT-SSE] $line")
append(serverUrl) output.append(line).append("\n")
if (args.isNotEmpty()) {
append(' ')
append(args.joinToString(" "))
} }
} }
return executeCommand(cmd, tsClientDir) process.waitFor(25, java.util.concurrent.TimeUnit.SECONDS)
output.toString()
} }
} }

View file

@ -2,18 +2,18 @@ package io.modelcontextprotocol.kotlin.sdk.integration.typescript.sse
import io.modelcontextprotocol.kotlin.sdk.integration.typescript.TransportKind import io.modelcontextprotocol.kotlin.sdk.integration.typescript.TransportKind
import io.modelcontextprotocol.kotlin.sdk.integration.typescript.TsTestBase import io.modelcontextprotocol.kotlin.sdk.integration.typescript.TsTestBase
import io.modelcontextprotocol.kotlin.test.utils.DisabledOnCI
import io.modelcontextprotocol.kotlin.test.utils.findFreePort import io.modelcontextprotocol.kotlin.test.utils.findFreePort
import io.modelcontextprotocol.kotlin.test.utils.killProcessOnPort import io.modelcontextprotocol.kotlin.test.utils.killProcessOnPort
import kotlinx.coroutines.async import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.runTest import kotlinx.coroutines.test.runTest
import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Test
import org.junit.jupiter.api.Timeout import org.junit.jupiter.api.Timeout
import org.junit.jupiter.api.condition.EnabledOnOs import org.junit.jupiter.api.condition.DisabledOnOs
import org.junit.jupiter.api.condition.OS import org.junit.jupiter.api.condition.OS
import java.io.File import java.io.File
import java.util.concurrent.TimeUnit import java.util.concurrent.TimeUnit
@ -21,7 +21,6 @@ import kotlin.test.assertEquals
import kotlin.test.assertTrue import kotlin.test.assertTrue
import kotlin.test.fail import kotlin.test.fail
@DisabledOnCI
class TsEdgeCasesTestSse : TsTestBase() { class TsEdgeCasesTestSse : TsTestBase() {
override val transportKind = TransportKind.SSE override val transportKind = TransportKind.SSE
@ -56,16 +55,16 @@ class TsEdgeCasesTestSse : TsTestBase() {
@Test @Test
@Timeout(30, unit = TimeUnit.SECONDS) @Timeout(30, unit = TimeUnit.SECONDS)
fun testInvalidURL() = runTest { fun testInvalidURL() = runTest {
val nonExistentToolCommand = "npx tsx myClient.ts $serverUrl non-existent-tool" val nonExistentToolCommand = "npx tsx client/sse-client.ts $serverUrl non-existent-tool"
val nonExistentToolOutput = executeCommandAllowingFailure(nonExistentToolCommand, tsClientDir) val nonExistentToolOutput = executeCommandAllowingFailure(nonExistentToolCommand, typescriptDir)
assertTrue( assertTrue(
nonExistentToolOutput.contains("Tool \"non-existent-tool\" not found"), nonExistentToolOutput.contains("Tool \"non-existent-tool\" not found"),
"Client should handle non-existent tool gracefully", "Client should handle non-existent tool gracefully",
) )
val invalidUrlCommand = "npx tsx myClient.ts http://localhost:${port + 1000}/mcp greet TestUser" val invalidUrlCommand = "npx tsx client/sse-client.ts http://localhost:${port + 1000}/mcp greet TestUser"
val invalidUrlOutput = executeCommandAllowingFailure(invalidUrlCommand, tsClientDir) val invalidUrlOutput = executeCommandAllowingFailure(invalidUrlCommand, typescriptDir)
assertTrue( assertTrue(
invalidUrlOutput.contains("Invalid URL") || invalidUrlOutput.contains("Invalid URL") ||
@ -85,8 +84,8 @@ class TsEdgeCasesTestSse : TsTestBase() {
tempFile.deleteOnExit() tempFile.deleteOnExit()
val specialCharsContent = tempFile.readText() val specialCharsContent = tempFile.readText()
val specialCharsCommand = "npx tsx myClient.ts $serverUrl greet \"$specialCharsContent\"" val specialCharsCommand = "npx tsx client/sse-client.ts $serverUrl greet \"$specialCharsContent\""
val specialCharsOutput = executeCommand(specialCharsCommand, tsClientDir) val specialCharsOutput = executeCommand(specialCharsCommand, typescriptDir)
assertTrue( assertTrue(
specialCharsOutput.contains("Hello, $specialChars!"), specialCharsOutput.contains("Hello, $specialChars!"),
@ -100,8 +99,8 @@ class TsEdgeCasesTestSse : TsTestBase() {
// skip on windows as it can't handle long commands // skip on windows as it can't handle long commands
@Test @Test
@Timeout(30, unit = TimeUnit.SECONDS) @Timeout(40, unit = TimeUnit.SECONDS)
@EnabledOnOs(OS.MAC, OS.LINUX) @DisabledOnOs(OS.WINDOWS)
fun testLargePayload() = runTest { fun testLargePayload() = runTest {
val largeName = "A".repeat(10 * 1024) val largeName = "A".repeat(10 * 1024)
@ -110,8 +109,8 @@ class TsEdgeCasesTestSse : TsTestBase() {
tempFile.deleteOnExit() tempFile.deleteOnExit()
val largeNameContent = tempFile.readText() val largeNameContent = tempFile.readText()
val largePayloadCommand = "npx tsx myClient.ts $serverUrl greet \"$largeNameContent\"" val largePayloadCommand = "npx tsx client/sse-client.ts $serverUrl greet \"$largeNameContent\""
val largePayloadOutput = executeCommand(largePayloadCommand, tsClientDir) val largePayloadOutput = executeCommand(largePayloadCommand, typescriptDir)
tempFile.delete() tempFile.delete()
@ -126,8 +125,8 @@ class TsEdgeCasesTestSse : TsTestBase() {
} }
@Test @Test
@Timeout(60, unit = TimeUnit.SECONDS) @Timeout(30, unit = TimeUnit.SECONDS)
fun testComplexConcurrentRequests() = runTest { fun testComplexConcurrentRequests(): Unit = runBlocking {
fun prettyFail( fun prettyFail(
index: Int, index: Int,
command: String, command: String,
@ -158,18 +157,18 @@ class TsEdgeCasesTestSse : TsTestBase() {
} }
val commands = listOf( val commands = listOf(
"npx tsx myClient.ts $serverUrl greet \"Client1\"", "npx tsx client/sse-client.ts $serverUrl greet \"Client1\"",
"npx tsx myClient.ts $serverUrl multi-greet \"Client2\"", "npx tsx client/sse-client.ts $serverUrl multi-greet \"Client2\"",
"npx tsx myClient.ts $serverUrl greet \"Client3\"", "npx tsx client/sse-client.ts $serverUrl greet \"Client3\"",
"npx tsx myClient.ts $serverUrl", "npx tsx client/sse-client.ts $serverUrl",
"npx tsx myClient.ts $serverUrl multi-greet \"Client5\"", "npx tsx client/sse-client.ts $serverUrl multi-greet \"Client5\"",
) )
coroutineScope { coroutineScope {
val jobs = commands.mapIndexed { index, command -> val jobs = commands.mapIndexed { index, command ->
async(kotlinx.coroutines.Dispatchers.IO) { async(kotlinx.coroutines.Dispatchers.IO) {
println("Starting client $index") println("Starting client $index")
val output = executeCommand(command, tsClientDir) val output = executeCommand(command, typescriptDir)
println("Client $index completed") println("Client $index completed")
assertContains( assertContains(
@ -241,10 +240,10 @@ class TsEdgeCasesTestSse : TsTestBase() {
@Test @Test
@Timeout(120, unit = TimeUnit.SECONDS) @Timeout(120, unit = TimeUnit.SECONDS)
fun testRapidSequentialRequests() = runTest { fun testRapidSequentialRequests() = runBlocking {
val outputs = (1..10).map { i -> val outputs = (1..10).map { i ->
val command = "npx tsx myClient.ts $serverUrl greet \"RapidClient$i\"" val command = "npx tsx client/sse-client.ts $serverUrl greet \"RapidClient$i\""
val output = executeCommand(command, tsClientDir) val output = executeCommand(command, typescriptDir)
assertTrue( assertTrue(
output.contains("Connected to server"), output.contains("Connected to server"),

View file

@ -2,9 +2,7 @@ package io.modelcontextprotocol.kotlin.sdk.integration.typescript.stdio
import io.modelcontextprotocol.kotlin.sdk.integration.typescript.AbstractTsClientKotlinServerTest import io.modelcontextprotocol.kotlin.sdk.integration.typescript.AbstractTsClientKotlinServerTest
import io.modelcontextprotocol.kotlin.sdk.integration.typescript.TransportKind import io.modelcontextprotocol.kotlin.sdk.integration.typescript.TransportKind
import io.modelcontextprotocol.kotlin.test.utils.DisabledOnCI
@DisabledOnCI
class TsClientKotlinServerTestStdio : AbstractTsClientKotlinServerTest() { class TsClientKotlinServerTestStdio : AbstractTsClientKotlinServerTest() {
override val transportKind = TransportKind.STDIO override val transportKind = TransportKind.STDIO
override fun runClient(vararg args: String): String = runStdioClient(*args) override fun runClient(vararg args: String): String = runStdioClient(*args)

View file

@ -2,7 +2,6 @@ package io.modelcontextprotocol.kotlin.sdk.integration.typescript.stdio
import io.modelcontextprotocol.kotlin.sdk.integration.typescript.TransportKind import io.modelcontextprotocol.kotlin.sdk.integration.typescript.TransportKind
import io.modelcontextprotocol.kotlin.sdk.integration.typescript.TsTestBase import io.modelcontextprotocol.kotlin.sdk.integration.typescript.TsTestBase
import io.modelcontextprotocol.kotlin.test.utils.DisabledOnCI
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Test
import org.junit.jupiter.api.Timeout import org.junit.jupiter.api.Timeout
import org.junit.jupiter.api.condition.EnabledOnOs import org.junit.jupiter.api.condition.EnabledOnOs
@ -12,7 +11,6 @@ import java.util.concurrent.TimeUnit
import kotlin.test.assertEquals import kotlin.test.assertEquals
import kotlin.test.assertTrue import kotlin.test.assertTrue
@DisabledOnCI
class TsEdgeCasesTestStdio : TsTestBase() { class TsEdgeCasesTestStdio : TsTestBase() {
override val transportKind: TransportKind = TransportKind.STDIO override val transportKind: TransportKind = TransportKind.STDIO

View file

@ -1,6 +1,7 @@
package io.modelcontextprotocol.kotlin.sdk.server package io.modelcontextprotocol.kotlin.sdk.server
import io.modelcontextprotocol.kotlin.sdk.types.Method import io.kotest.matchers.collections.shouldHaveSize
import io.modelcontextprotocol.kotlin.sdk.types.Method.Defined.NotificationsResourcesUpdated
import io.modelcontextprotocol.kotlin.sdk.types.ReadResourceResult import io.modelcontextprotocol.kotlin.sdk.types.ReadResourceResult
import io.modelcontextprotocol.kotlin.sdk.types.ResourceUpdatedNotification import io.modelcontextprotocol.kotlin.sdk.types.ResourceUpdatedNotification
import io.modelcontextprotocol.kotlin.sdk.types.ServerCapabilities import io.modelcontextprotocol.kotlin.sdk.types.ServerCapabilities
@ -8,13 +9,19 @@ import io.modelcontextprotocol.kotlin.sdk.types.SubscribeRequest
import io.modelcontextprotocol.kotlin.sdk.types.SubscribeRequestParams import io.modelcontextprotocol.kotlin.sdk.types.SubscribeRequestParams
import io.modelcontextprotocol.kotlin.sdk.types.TextResourceContents import io.modelcontextprotocol.kotlin.sdk.types.TextResourceContents
import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.test.runTest import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import org.awaitility.kotlin.await import org.awaitility.kotlin.await
import org.awaitility.kotlin.untilAsserted import org.awaitility.kotlin.untilAsserted
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Test
import java.util.concurrent.ConcurrentLinkedQueue
import kotlin.test.assertFalse import kotlin.test.assertFalse
import kotlin.test.assertTrue import kotlin.test.assertTrue
import kotlin.time.Duration.Companion.seconds
import kotlin.uuid.ExperimentalUuidApi
import kotlin.uuid.Uuid
@OptIn(ExperimentalUuidApi::class)
class ServerResourcesNotificationSubscribeTest : AbstractServerFeaturesTest() { class ServerResourcesNotificationSubscribeTest : AbstractServerFeaturesTest() {
override fun getServerCapabilities(): ServerCapabilities = ServerCapabilities( override fun getServerCapabilities(): ServerCapabilities = ServerCapabilities(
@ -22,159 +29,107 @@ class ServerResourcesNotificationSubscribeTest : AbstractServerFeaturesTest() {
) )
@Test @Test
fun `removeResource should send resource update notification`() = runTest { fun `should send resource notifications`() = runBlocking {
val notifications = mutableListOf<ResourceUpdatedNotification>() val notifications = ConcurrentLinkedQueue<ResourceUpdatedNotification>()
client.setNotificationHandler<ResourceUpdatedNotification>(Method.Defined.NotificationsResourcesUpdated) {
client.setNotificationHandler<ResourceUpdatedNotification>(NotificationsResourcesUpdated) {
notifications.add(it) notifications.add(it)
CompletableDeferred(Unit) CompletableDeferred(Unit)
} }
// Add resources // Add resources
val testResourceUri1 = "test://resource1" val testResourceUri1 = "test://resource1-${Uuid.random()}"
val testResourceUri2 = "test://resource2" val testResourceUri2 = "test://resource2-${Uuid.random()}"
server.addResource(
uri = testResourceUri1,
name = "Test Resource 1",
description = "A test resource 1",
mimeType = "text/plain",
) {
ReadResourceResult(
contents = listOf(
TextResourceContents(
text = "Test resource content 1",
uri = testResourceUri1,
mimeType = "text/plain",
),
),
)
}
server.addResource(
uri = testResourceUri2,
name = "Test Resource 2",
description = "A test resource 2",
mimeType = "text/plain",
) {
ReadResourceResult(
contents = listOf(
TextResourceContents(
text = "Test resource content 2",
uri = testResourceUri2,
mimeType = "text/plain",
),
),
)
}
client.subscribeResource(SubscribeRequest(SubscribeRequestParams(uri = testResourceUri1)))
// Remove the resource
val result = server.removeResource(testResourceUri1)
// Verify the resource was removed
assertTrue(result, "Resource should be removed successfully")
// Verify that the notification was sent
await untilAsserted {
assertTrue(
notifications.any { it.params.uri == testResourceUri1 },
"Notification should be sent when resource 1 was deleted",
)
}
}
@Test
fun `removeResource for two resources should send two separate notifications`() = runTest {
val notifications = mutableListOf<ResourceUpdatedNotification>()
client.setNotificationHandler<ResourceUpdatedNotification>(Method.Defined.NotificationsResourcesUpdated) {
notifications.add(it)
CompletableDeferred(Unit)
}
// Add resources
val testResourceUri1 = "test://resource1"
val testResourceUri2 = "test://resource2"
server.addResource(
uri = testResourceUri1,
name = "Test Resource 1",
description = "A test resource 1",
mimeType = "text/plain",
) {
ReadResourceResult(
contents = listOf(
TextResourceContents(
text = "Test resource content 1",
uri = testResourceUri1,
mimeType = "text/plain",
),
),
)
}
server.addResource(
uri = testResourceUri2,
name = "Test Resource 2",
description = "A test resource 2",
mimeType = "text/plain",
) {
ReadResourceResult(
contents = listOf(
TextResourceContents(
text = "Test resource content 2",
uri = testResourceUri2,
mimeType = "text/plain",
),
),
)
}
client.subscribeResource(SubscribeRequest(SubscribeRequestParams(uri = testResourceUri1))) client.subscribeResource(SubscribeRequest(SubscribeRequestParams(uri = testResourceUri1)))
client.subscribeResource(SubscribeRequest(SubscribeRequestParams(uri = testResourceUri2))) client.subscribeResource(SubscribeRequest(SubscribeRequestParams(uri = testResourceUri2)))
// Remove the resource server.addResource(
val result1 = server.removeResource(testResourceUri1) uri = testResourceUri1,
val result2 = server.removeResource(testResourceUri2) name = "Test Resource 1",
description = "A test resource 1",
// Verify the resource was removed mimeType = "text/plain",
assertTrue(result1, "Resource 1 should be removed successfully") ) {
assertTrue(result2, "Resource 2 should be removed successfully") ReadResourceResult(
contents = listOf(
println(notifications.map { it.params.uri }) TextResourceContents(
// Verify that the notification was sent text = "Test resource content 1",
await untilAsserted { uri = it.uri,
assertTrue( mimeType = "text/plain",
notifications.any { it.params.uri == testResourceUri1 }, ),
"Notification should be sent when resource 1 and resource 2 was deleted", ),
) )
} }
val deletedResources = listOf(notifications[0].params.uri, notifications[1].params.uri) server.addResource(
assertTrue( uri = testResourceUri2,
deletedResources.contains(testResourceUri1), name = "Test Resource 2",
"Notification should contain the removed resource 1 URI", description = "A test resource 2",
) mimeType = "text/plain",
assertTrue( ) {
deletedResources.contains(testResourceUri2), ReadResourceResult(
"Notification should contain the removed resource 2 URI", contents = listOf(
) TextResourceContents(
text = "Test resource content 2",
uri = it.uri,
mimeType = "text/plain",
),
),
)
}
// Verify that the notification was sent
await untilAsserted {
notifications.shouldHaveSize(2)
assertTrue(
notifications.any { it.params.uri == testResourceUri1 && it.method == NotificationsResourcesUpdated },
"Notification should be sent when resource 1 was deleted",
)
assertTrue(
notifications.any { it.params.uri == testResourceUri2 && it.method == NotificationsResourcesUpdated },
"Notification should be sent when resource 2 was deleted",
)
}
notifications.clear()
// Remove the resource
val result1 = server.removeResource(testResourceUri1)
assertTrue(result1, "Resource 1 should be removed successfully")
val result2 = server.removeResource(testResourceUri2)
// Verify the resource was removed
assertTrue(result2, "Resource 2 should be removed successfully")
// Verify that the notification was sent
await untilAsserted {
notifications.shouldHaveSize(2)
assertTrue(
notifications.any { it.params.uri == testResourceUri1 && it.method == NotificationsResourcesUpdated },
"Notification should be sent when resource 1 was deleted",
)
assertTrue(
notifications.any { it.params.uri == testResourceUri2 && it.method == NotificationsResourcesUpdated },
"Notification should be sent when resource 2 was deleted",
)
}
} }
@Test @Test
fun `notification should not be send when removed resource does not exists`() = runTest { fun `notification should not be send when removed resource does not exists`() = runBlocking {
println("Thread ${Thread.currentThread().name} test 1")
// Track notifications // Track notifications
val notifications = mutableListOf<ResourceUpdatedNotification>() val notifications = ConcurrentLinkedQueue<ResourceUpdatedNotification>()
client.setNotificationHandler<ResourceUpdatedNotification>(Method.Defined.NotificationsResourcesUpdated) { client.setNotificationHandler<ResourceUpdatedNotification>(NotificationsResourcesUpdated) {
notifications.add(it) notifications.add(it)
CompletableDeferred(Unit) CompletableDeferred(Unit)
} }
// Try to remove a non-existent resource // Try to remove a non-existent resource
val result = server.removeResource("non-existent-resource") val result = server.removeResource("non-existent-resource")
assertFalse(result, "Removing non-existent resource should return false")
// Verify the result // Verify the result
assertFalse(result, "Removing non-existent resource should return false") delay(1.seconds)
assertTrue( assertTrue(
notifications.isEmpty(), notifications.isEmpty(),
"No notification should be sent when resource doesn't exist", "No notification should be sent when resource doesn't exist",

View file

@ -0,0 +1,6 @@
## https://docs.junit.org/5.3.0-M1/user-guide/index.html#writing-tests-parallel-execution
junit.jupiter.execution.parallel.enabled=true
junit.jupiter.execution.parallel.config.strategy=dynamic
junit.jupiter.execution.parallel.mode.default=concurrent
junit.jupiter.execution.parallel.mode.classes.default=concurrent
junit.jupiter.execution.timeout.default=2m

Some files were not shown because too many files have changed in this diff Show more