@@ -11,6 +11,7 @@ import io.modelcontextprotocol.kotlin.sdk.client.StreamableHttpClientTransport
1111import io.modelcontextprotocol.kotlin.sdk.types.ClientCapabilities
1212import io.modelcontextprotocol.kotlin.sdk.types.Implementation
1313import kotlinx.serialization.json.buildJsonObject
14+ import kotlinx.serialization.json.jsonArray
1415import kotlinx.serialization.json.jsonPrimitive
1516import kotlinx.serialization.json.put
1617import java.security.KeyFactory
@@ -33,10 +34,17 @@ internal suspend fun runClientCredentialsJwt(serverUrl: String) {
3334 }
3435
3536 httpClient.use { client ->
36- val tokenEndpoint = discoverTokenEndpoint(client, serverUrl)
37+ val resourceMetadata = discoverResourceMetadata(client, serverUrl)
38+ val authServer = resourceMetadata[" authorization_servers" ]?.jsonArray?.firstOrNull()?.jsonPrimitive?.content
39+ ? : error(" No authorization_servers in resource metadata" )
40+ val oauthMetadata = fetchOAuthMetadata(client, authServer)
41+ val tokenEndpoint = oauthMetadata[" token_endpoint" ]?.jsonPrimitive?.content
42+ ? : error(" No token_endpoint in AS metadata" )
43+ val issuer = oauthMetadata[" issuer" ]?.jsonPrimitive?.content
44+ ? : error(" No issuer in AS metadata" )
3745
3846 // Create JWT client assertion
39- val assertion = createJwtAssertion(clientId, tokenEndpoint , privateKeyPem, signingAlgorithm)
47+ val assertion = createJwtAssertion(clientId, issuer , privateKeyPem, signingAlgorithm)
4048
4149 // Exchange for token
4250 val tokenResponse = client.submitForm(
@@ -67,7 +75,7 @@ internal suspend fun runClientCredentialsJwt(serverUrl: String) {
6775@OptIn(ExperimentalUuidApi ::class )
6876private fun createJwtAssertion (
6977 clientId : String ,
70- tokenEndpoint : String ,
78+ audience : String ,
7179 privateKeyPem : String ,
7280 algorithm : String ,
7381): String {
@@ -80,7 +88,7 @@ private fun createJwtAssertion(
8088 val payload = buildJsonObject {
8189 put(" iss" , clientId)
8290 put(" sub" , clientId)
83- put(" aud" , tokenEndpoint )
91+ put(" aud" , audience )
8492 put(" iat" , now)
8593 put(" exp" , now + 300 )
8694 put(" jti" , Uuid .random().toString())
0 commit comments