Add isolated rmcp Tools adapter prototype
CI / Rust Checks (pull_request) Failing after 40s
CI / Rust Feature Validation (pull_request) Skipped
CI / UI Checks (pull_request) Successful in 12s
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Required Checks (pull_request) Failing after 2s
CI / Deploy (pull_request) Skipped
CI / Rust Checks (pull_request) Failing after 40s
CI / Rust Feature Validation (pull_request) Skipped
CI / UI Checks (pull_request) Successful in 12s
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Required Checks (pull_request) Failing after 2s
CI / Deploy (pull_request) Skipped
This commit is contained in:
1 parent
e4953abcd2
commit
1c256e6c75
17 files changed
+1978
-91
No files matched your search
Generated
+204
-62
@@ -25,7 +25,7 @@ dependencies = [
|
||||
"async-trait",
|
||||
"axum",
|
||||
"axum-extra",
|
||||
"base64",
|
||||
"base64 0.22.1",
|
||||
"crank-artifacts",
|
||||
"crank-community-auth",
|
||||
"crank-community-mcp",
|
||||
@@ -186,7 +186,7 @@ checksum = "c7c24de15d275a1ecfd47a380fb4d5ec9bfe0933f309ed5e705b775596a3574d"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 2.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -197,7 +197,7 @@ checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 2.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -349,6 +349,12 @@ version = "0.22.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
|
||||
|
||||
[[package]]
|
||||
name = "base64"
|
||||
version = "0.23.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
|
||||
|
||||
[[package]]
|
||||
name = "base64ct"
|
||||
version = "1.8.3"
|
||||
@@ -398,7 +404,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ee04c4c84f1f811b017f2fbb7dd8815c976e7ca98593de9c1e2afad0f636bff4"
|
||||
dependencies = [
|
||||
"async-stream",
|
||||
"base64",
|
||||
"base64 0.22.1",
|
||||
"bitflags",
|
||||
"bollard-buildkit-proto",
|
||||
"bollard-stubs",
|
||||
@@ -455,7 +461,7 @@ version = "1.52.1-rc.29.1.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0f0a8ca8799131c1837d1282c3f81f31e76ceb0ce426e04a7fe1ccee3287c066"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"base64 0.22.1",
|
||||
"bollard-buildkit-proto",
|
||||
"bytes",
|
||||
"prost",
|
||||
@@ -653,7 +659,7 @@ version = "0.3.1"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"axum",
|
||||
"base64",
|
||||
"base64 0.22.1",
|
||||
"crank-core",
|
||||
"crank-metrics",
|
||||
"crank-trace",
|
||||
@@ -688,7 +694,7 @@ dependencies = [
|
||||
"argon2",
|
||||
"async-trait",
|
||||
"axum-extra",
|
||||
"base64",
|
||||
"base64 0.22.1",
|
||||
"crank-core",
|
||||
"crank-registry",
|
||||
"rand 0.10.2",
|
||||
@@ -705,7 +711,7 @@ version = "0.3.1"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"axum",
|
||||
"base64",
|
||||
"base64 0.22.1",
|
||||
"crank-adapter-rest",
|
||||
"crank-artifacts",
|
||||
"crank-core",
|
||||
@@ -722,6 +728,7 @@ dependencies = [
|
||||
"opentelemetry",
|
||||
"opentelemetry_sdk",
|
||||
"reqwest 0.12.28",
|
||||
"rmcp",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2 0.10.9",
|
||||
@@ -850,7 +857,7 @@ dependencies = [
|
||||
"aes-gcm",
|
||||
"async-trait",
|
||||
"axum",
|
||||
"base64",
|
||||
"base64 0.22.1",
|
||||
"crank-adapter-rest",
|
||||
"crank-core",
|
||||
"crank-import",
|
||||
@@ -992,8 +999,18 @@ version = "0.23.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "25ae13da2f202d56bd7f91c25fba009e7717a1e4a1cc98a76d844b65ae912e9d"
|
||||
dependencies = [
|
||||
"darling_core",
|
||||
"darling_macro",
|
||||
"darling_core 0.23.0",
|
||||
"darling_macro 0.23.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "darling"
|
||||
version = "0.24.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec"
|
||||
dependencies = [
|
||||
"darling_core 0.24.1",
|
||||
"darling_macro 0.24.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1006,7 +1023,20 @@ dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"strsim",
|
||||
"syn",
|
||||
"syn 2.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "darling_core"
|
||||
version = "0.24.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff"
|
||||
dependencies = [
|
||||
"ident_case",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"strsim",
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1015,9 +1045,20 @@ version = "0.23.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ac3984ec7bd6cfa798e62b4a642426a5be0e68f9401cfc2a01e3fa9ea2fcdb8d"
|
||||
dependencies = [
|
||||
"darling_core",
|
||||
"darling_core 0.23.0",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 2.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "darling_macro"
|
||||
version = "0.24.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785"
|
||||
dependencies = [
|
||||
"darling_core 0.24.1",
|
||||
"quote",
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1069,7 +1110,7 @@ checksum = "1ac70aa55017e108007fbaf5aa0f54b021c98f92ff8af59d42eda9da96e3dd4f"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 2.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1078,7 +1119,7 @@ version = "1.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "29547a1dc60885a552306986316bc9701ba120c1a8db6769fa68691529ad373d"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"base64 0.22.1",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
@@ -1147,7 +1188,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1309,7 +1350,7 @@ checksum = "e835b70203e41293343137df5c0664546da5745f82ec9b84d40be8336958447b"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 2.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1661,7 +1702,7 @@ version = "0.1.20"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"base64 0.22.1",
|
||||
"bytes",
|
||||
"futures-channel",
|
||||
"futures-util",
|
||||
@@ -1672,7 +1713,7 @@ dependencies = [
|
||||
"libc",
|
||||
"percent-encoding",
|
||||
"pin-project-lite",
|
||||
"socket2 0.5.10",
|
||||
"socket2 0.6.4",
|
||||
"tokio",
|
||||
"tower-service",
|
||||
"tracing",
|
||||
@@ -1920,7 +1961,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264"
|
||||
dependencies = [
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 2.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2056,7 +2097,7 @@ version = "0.3.1"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"axum",
|
||||
"base64",
|
||||
"base64 0.22.1",
|
||||
"crank-artifacts",
|
||||
"crank-community-mcp",
|
||||
"crank-config",
|
||||
@@ -2121,7 +2162,7 @@ version = "0.18.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1db0d8f1fc9e62caebd0319e11eaec5822b0186c171568f0480b46a0137f9108"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"base64 0.22.1",
|
||||
"evmap",
|
||||
"indexmap 2.14.0",
|
||||
"metrics",
|
||||
@@ -2457,7 +2498,7 @@ dependencies = [
|
||||
"regex",
|
||||
"regex-syntax",
|
||||
"structmeta",
|
||||
"syn",
|
||||
"syn 2.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2471,6 +2512,12 @@ dependencies = [
|
||||
"subtle",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pastey"
|
||||
version = "0.2.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4"
|
||||
|
||||
[[package]]
|
||||
name = "percent-encoding"
|
||||
version = "2.3.2"
|
||||
@@ -2494,7 +2541,7 @@ checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 2.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2580,7 +2627,7 @@ dependencies = [
|
||||
"itertools",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 2.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2636,7 +2683,7 @@ dependencies = [
|
||||
"quinn-udp",
|
||||
"rustc-hash",
|
||||
"rustls",
|
||||
"socket2 0.5.10",
|
||||
"socket2 0.6.4",
|
||||
"thiserror 2.0.18",
|
||||
"tokio",
|
||||
"tracing",
|
||||
@@ -2675,9 +2722,9 @@ dependencies = [
|
||||
"cfg_aliases",
|
||||
"libc",
|
||||
"once_cell",
|
||||
"socket2 0.5.10",
|
||||
"socket2 0.6.4",
|
||||
"tracing",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2852,7 +2899,7 @@ checksum = "b7186006dcb21920990093f30e3dea63b7d6e977bf1256be20c3563a5db070da"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 2.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2890,7 +2937,7 @@ version = "0.12.28"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"base64 0.22.1",
|
||||
"bytes",
|
||||
"cookie",
|
||||
"cookie_store",
|
||||
@@ -2934,7 +2981,7 @@ version = "0.13.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "219c5811de6525e5416c7d5d53bb656d3afdbc6c5af816e0802bcfa42dbdc1c3"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"base64 0.22.1",
|
||||
"bytes",
|
||||
"futures-channel",
|
||||
"futures-core",
|
||||
@@ -2981,6 +3028,52 @@ dependencies = [
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rmcp"
|
||||
version = "3.7.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ece64e19631fc38758181e637c15509a2c2709ee53bfde1e1d58f9dc991f919e"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"base64 0.23.1",
|
||||
"bytes",
|
||||
"chrono",
|
||||
"futures",
|
||||
"http",
|
||||
"http-body",
|
||||
"http-body-util",
|
||||
"indexmap 2.14.0",
|
||||
"libc",
|
||||
"pastey",
|
||||
"pin-project-lite",
|
||||
"rand 0.10.2",
|
||||
"rmcp-macros",
|
||||
"schemars 1.2.1",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sse-stream",
|
||||
"thiserror 2.0.18",
|
||||
"tokio",
|
||||
"tokio-stream",
|
||||
"tokio-util",
|
||||
"tower-service",
|
||||
"tracing",
|
||||
"uuid",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rmcp-macros"
|
||||
version = "3.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b3140f24a766f80f9ec1607bde85680959a69b83d46fa9ce87dadab7e67ab029"
|
||||
dependencies = [
|
||||
"darling 0.24.1",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"serde_json",
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustc-demangle"
|
||||
version = "0.1.28"
|
||||
@@ -3016,7 +3109,7 @@ dependencies = [
|
||||
"errno",
|
||||
"libc",
|
||||
"linux-raw-sys 0.12.1",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3075,7 +3168,7 @@ dependencies = [
|
||||
"security-framework",
|
||||
"security-framework-sys",
|
||||
"webpki-root-certs",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3144,12 +3237,26 @@ version = "1.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a2b42f36aa1cd011945615b92222f6bf73c599a102a300334cd7f8dbeec726cc"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"dyn-clone",
|
||||
"ref-cast",
|
||||
"schemars_derive",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "schemars_derive"
|
||||
version = "1.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7d115b50f4aaeea07e79c1912f645c7513d81715d0420f8bc77a18c6260b307f"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"serde_derive_internals",
|
||||
"syn 2.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "scoped-tls"
|
||||
version = "1.0.1"
|
||||
@@ -3293,7 +3400,18 @@ checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 2.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_derive_internals"
|
||||
version = "0.29.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "18d26a20a969b9e3fdf2fc2d9f21eda6c40e2de84c9408bb5d3b05d499aae711"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3328,7 +3446,7 @@ checksum = "175ee3e80ae9982737ca543e96133087cbd9a485eecc3bc4de9c1a37b47ea59c"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 2.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3349,7 +3467,7 @@ version = "3.21.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "76a5c54c7310e7b8b9577c286d7e399ddd876c3e12b3ed917a8aabc4b96e9e8c"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"base64 0.22.1",
|
||||
"bs58",
|
||||
"chrono",
|
||||
"hex",
|
||||
@@ -3369,10 +3487,10 @@ version = "3.21.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "84d57bc0c8b9a17920c178daa6bb924850d54a9c97ab45194bb8c17ad66bb660"
|
||||
dependencies = [
|
||||
"darling",
|
||||
"darling 0.23.0",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 2.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3410,7 +3528,7 @@ checksum = "94e153fc76e1c6a068703d6d29c508a0b15c061c4b7e43da59cc097bc342673c"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 2.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3544,7 +3662,7 @@ dependencies = [
|
||||
name = "sqlx-core"
|
||||
version = "0.9.0"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"base64 0.22.1",
|
||||
"bytes",
|
||||
"cfg-if",
|
||||
"crc",
|
||||
@@ -3586,7 +3704,7 @@ dependencies = [
|
||||
"quote",
|
||||
"sqlx-core",
|
||||
"sqlx-macros-core",
|
||||
"syn",
|
||||
"syn 2.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3609,7 +3727,7 @@ dependencies = [
|
||||
"sqlx-mysql",
|
||||
"sqlx-postgres",
|
||||
"sqlx-sqlite",
|
||||
"syn",
|
||||
"syn 2.0.118",
|
||||
"thiserror 2.0.18",
|
||||
"tokio",
|
||||
"url",
|
||||
@@ -3650,7 +3768,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "87a2bdd6e83f6b3ea525ca9fee568030508b58355a43d0b2c1674d5f79dcd65e"
|
||||
dependencies = [
|
||||
"atoi",
|
||||
"base64",
|
||||
"base64 0.22.1",
|
||||
"bitflags",
|
||||
"byteorder",
|
||||
"crc",
|
||||
@@ -3706,6 +3824,19 @@ dependencies = [
|
||||
"uuid",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sse-stream"
|
||||
version = "0.2.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c25ac7aff0abd1dbc474536e40416e1102c7dd9bfba0b9861c6d357f835dcfb4"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"futures-util",
|
||||
"http-body",
|
||||
"http-body-util",
|
||||
"pin-project-lite",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "stable_deref_trait"
|
||||
version = "1.2.1"
|
||||
@@ -3738,7 +3869,7 @@ dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"structmeta-derive",
|
||||
"syn",
|
||||
"syn 2.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3749,7 +3880,7 @@ checksum = "152a0b65a590ff6c3da95cabe2353ee04e6167c896b28e3b14478c2636c922fc"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 2.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3769,6 +3900,17 @@ dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "3.0.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sync_wrapper"
|
||||
version = "1.0.2"
|
||||
@@ -3786,7 +3928,7 @@ checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 2.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3855,7 +3997,7 @@ checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 2.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3866,7 +4008,7 @@ checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 2.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3957,7 +4099,7 @@ checksum = "385a6cb71ab9ab790c5fe8d67f1645e6c450a7ce006a33de03daa956cf70a496"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 2.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4002,7 +4144,7 @@ checksum = "ac2a5518c70fa84342385732db33fb3f44bc4cc748936eb5833d2df34d6445ef"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"axum",
|
||||
"base64",
|
||||
"base64 0.22.1",
|
||||
"bytes",
|
||||
"h2",
|
||||
"http",
|
||||
@@ -4103,7 +4245,7 @@ checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 2.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4232,7 +4374,7 @@ version = "3.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dea7109cdcd5864d4eeb1b58a1648dc9bf520360d7af16ec26d0a9354bafcfc0"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"base64 0.22.1",
|
||||
"log",
|
||||
"percent-encoding",
|
||||
"rustls",
|
||||
@@ -4248,7 +4390,7 @@ version = "0.6.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e994ba84b0bd1b1b0cf92878b7ef898a5c1760108fe7b6010327e274917a808c"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"base64 0.22.1",
|
||||
"http",
|
||||
"httparse",
|
||||
"log",
|
||||
@@ -4385,7 +4527,7 @@ dependencies = [
|
||||
"bumpalo",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 2.0.118",
|
||||
"wasm-bindgen-shared",
|
||||
]
|
||||
|
||||
@@ -4477,7 +4619,7 @@ version = "0.1.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
|
||||
dependencies = [
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4507,7 +4649,7 @@ checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 2.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4518,7 +4660,7 @@ checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 2.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4734,7 +4876,7 @@ checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 2.0.118",
|
||||
"synstructure",
|
||||
]
|
||||
|
||||
@@ -4755,7 +4897,7 @@ checksum = "4714fd92cf900833d49538023a9b3915155210801d1c1169eba513b2addefd71"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 2.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4775,7 +4917,7 @@ checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 2.0.118",
|
||||
"synstructure",
|
||||
]
|
||||
|
||||
@@ -4815,7 +4957,7 @@ checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 2.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
@@ -21,6 +21,7 @@ crank-schema = { path = "../crank-schema" }
|
||||
crank-trace = { path = "../crank-trace" }
|
||||
futures-util = "0.3"
|
||||
reqwest.workspace = true
|
||||
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
sha2.workspace = true
|
||||
@@ -32,6 +33,7 @@ tracing.workspace = true
|
||||
uuid.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
rmcp = { version = "=3.7.0", features = ["transport-streamable-http-server"] }
|
||||
crank-mapping = { path = "../crank-mapping" }
|
||||
crank-test-support = { path = "../crank-test-support" }
|
||||
metrics-util = "0.20.4"
|
||||
|
||||
@@ -34,6 +34,18 @@ pub(crate) mod lifecycle;
|
||||
mod metrics;
|
||||
mod request;
|
||||
mod response;
|
||||
#[cfg(test)]
|
||||
mod rmcp_http;
|
||||
#[cfg(test)]
|
||||
#[path = "rmcp_http_tests.rs"]
|
||||
mod rmcp_http_tests;
|
||||
#[cfg(test)]
|
||||
mod rmcp_session_tests;
|
||||
#[cfg(test)]
|
||||
mod rmcp_tools;
|
||||
#[cfg(test)]
|
||||
#[path = "rmcp_tools_tests.rs"]
|
||||
mod rmcp_tools_tests;
|
||||
mod stages;
|
||||
mod tool_resolution;
|
||||
pub(crate) use self::approval_policy::{
|
||||
|
||||
@@ -144,7 +144,7 @@ fn increment(counter: impl Fn(&CounterSet) -> &AtomicUsize) {
|
||||
/// execution-boundary reason as the tests below).
|
||||
#[cfg(test)]
|
||||
#[path = "../dispatch_observer_support.rs"]
|
||||
mod support;
|
||||
pub(crate) mod support;
|
||||
|
||||
/// The behavioural section 7.2 harness: real app, real PostgreSQL, one counted loopback upstream and
|
||||
/// one request-scoped observer per request. Its file lives outside `src/app/` only because the
|
||||
|
||||
@@ -133,7 +133,7 @@ pub(crate) struct ProgressEvent {
|
||||
|
||||
/// The pinned `notifications/progress` frame. Both supported revisions declare the same parameters,
|
||||
/// so the projection is shared; the token is echoed verbatim and never validated as a credential.
|
||||
fn progress_frame(token: &ProgressToken, event: &ProgressEvent) -> Value {
|
||||
pub(super) fn progress_frame(token: &ProgressToken, event: &ProgressEvent) -> Value {
|
||||
json!({
|
||||
"jsonrpc": "2.0",
|
||||
"method": "notifications/progress",
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
//! Isolated single-Agent loopback experiment. Not installed in the production router.
|
||||
//! Each instance owns one route and one SDK manager; no durable store is replaced.
|
||||
|
||||
use super::{
|
||||
AgentRoutePath, AppState,
|
||||
lifecycle::InFlightScope,
|
||||
metrics::ActiveStreamGuard,
|
||||
rmcp_tools::{RmcpRequestIdentity, RmcpTools},
|
||||
stages::{enforce_traced_rate_limit, require_traced_machine_access},
|
||||
};
|
||||
use crate::{
|
||||
protocol::{self, ContinuationSupport, RequestEra},
|
||||
transport,
|
||||
};
|
||||
use axum::{
|
||||
Router,
|
||||
body::{Body, to_bytes},
|
||||
extract::Request,
|
||||
http::{Method, StatusCode},
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
use crank_core::PlatformApiKeyScope;
|
||||
use futures_util::StreamExt;
|
||||
use rmcp::transport::streamable_http_server::{
|
||||
StreamableHttpServerConfig, StreamableHttpService, session::local::LocalSessionManager,
|
||||
};
|
||||
use serde_json::Value;
|
||||
use std::sync::Arc;
|
||||
|
||||
const BODY_LIMIT: usize = 2 * 1024 * 1024;
|
||||
|
||||
pub(super) fn router(
|
||||
state: Arc<AppState>,
|
||||
path: AgentRoutePath,
|
||||
active: Arc<std::sync::atomic::AtomicUsize>,
|
||||
) -> Router {
|
||||
let handler_state = state.clone();
|
||||
let mut config = StreamableHttpServerConfig::default().with_json_response(true);
|
||||
config.max_request_body_bytes = BODY_LIMIT;
|
||||
let shutdown = Arc::new(config.cancellation_token.clone().drop_guard());
|
||||
let mut manager = LocalSessionManager::default();
|
||||
manager.session_config.channel_capacity = 16;
|
||||
let service = StreamableHttpService::new(
|
||||
move || {
|
||||
Ok(RmcpTools {
|
||||
state: handler_state.clone(),
|
||||
active: active.clone(),
|
||||
})
|
||||
},
|
||||
Arc::new(manager),
|
||||
config,
|
||||
);
|
||||
let route = format!("/v1/{}/{}", path.workspace_slug, path.agent_slug);
|
||||
Router::new()
|
||||
.route(
|
||||
&route,
|
||||
axum::routing::any(move |request: Request| {
|
||||
let state = state.clone();
|
||||
let path = path.clone();
|
||||
let service = service.clone();
|
||||
let shutdown = shutdown.clone();
|
||||
async move {
|
||||
let _shutdown = shutdown;
|
||||
let (mut parts, body) = request.into_parts();
|
||||
if let Err(status) =
|
||||
transport::validate_origin(&state.allowed_origins, &parts.headers)
|
||||
{
|
||||
return status.into_response();
|
||||
}
|
||||
let bytes = match to_bytes(body, BODY_LIMIT).await {
|
||||
Ok(bytes) => bytes,
|
||||
Err(_) => return StatusCode::PAYLOAD_TOO_LARGE.into_response(),
|
||||
};
|
||||
let message: Value = if parts.method == Method::POST {
|
||||
match serde_json::from_slice(&bytes) {
|
||||
Ok(message) => message,
|
||||
Err(_) => return StatusCode::BAD_REQUEST.into_response(),
|
||||
}
|
||||
} else {
|
||||
Value::Null
|
||||
};
|
||||
let method = message["method"].as_str().unwrap_or("");
|
||||
let required = if method == "tools/call" {
|
||||
PlatformApiKeyScope::Write
|
||||
} else {
|
||||
PlatformApiKeyScope::Read
|
||||
};
|
||||
let credential = match require_traced_machine_access(
|
||||
&state,
|
||||
&path,
|
||||
&parts.headers,
|
||||
required,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(credential) => credential,
|
||||
Err(error) => return error.into_response(),
|
||||
};
|
||||
let session = match transport::session_id_from_headers(&parts.headers) {
|
||||
Ok(session) => session,
|
||||
Err(_) => {
|
||||
return protocol::ambiguous_session_carrier_response(
|
||||
&parts.headers,
|
||||
&message,
|
||||
);
|
||||
}
|
||||
};
|
||||
let era = if parts.method == Method::POST {
|
||||
if let Err(response) = protocol::validate_jsonrpc_envelope(&message) {
|
||||
return *response;
|
||||
}
|
||||
if let Err(status) = transport::negotiate_post_response_mode(&parts.headers)
|
||||
{
|
||||
return status.into_response();
|
||||
}
|
||||
match protocol::resolve_request_identity(&parts.headers, &message) {
|
||||
Ok(identity) => identity.era,
|
||||
Err(response) => return *response,
|
||||
}
|
||||
} else {
|
||||
if let Err(response) = protocol::session_lifecycle_admission(&parts.headers)
|
||||
{
|
||||
return *response;
|
||||
}
|
||||
RequestEra::Legacy
|
||||
};
|
||||
if matches!(era, RequestEra::Modern) && session.is_some() {
|
||||
return protocol::modern_carrier_conflict_response(&message);
|
||||
}
|
||||
if let Err(error) =
|
||||
enforce_traced_rate_limit(&state, &path, &parts.headers).await
|
||||
{
|
||||
return crate::rate_limit::rate_limited_status_response(error);
|
||||
}
|
||||
// SDK cancellation is keyed only by request id. Never forward an unchecked cancel.
|
||||
if method == "notifications/cancelled" {
|
||||
if let Some(session_id) = session {
|
||||
state.in_flight.cancel(
|
||||
&InFlightScope {
|
||||
session_id,
|
||||
owner: credential
|
||||
.platform_api_key_id
|
||||
.as_ref()
|
||||
.map(|id| id.as_str())
|
||||
.unwrap_or("")
|
||||
.to_owned(),
|
||||
},
|
||||
&message["params"]["requestId"],
|
||||
);
|
||||
}
|
||||
return StatusCode::ACCEPTED.into_response();
|
||||
}
|
||||
let Some(context) = parts
|
||||
.extensions
|
||||
.get::<crate::request_context::RequestContext>()
|
||||
else {
|
||||
return StatusCode::INTERNAL_SERVER_ERROR.into_response();
|
||||
};
|
||||
let correlation = context.correlation.clone();
|
||||
|
||||
parts.extensions.insert(RmcpRequestIdentity {
|
||||
workspace_slug: path.workspace_slug,
|
||||
agent_slug: path.agent_slug,
|
||||
credential,
|
||||
correlation,
|
||||
continuation: ContinuationSupport::from_supported(false),
|
||||
locale: crate::tool_error::execution_locale(&message),
|
||||
session_id: session,
|
||||
progress_meta: message.pointer("/params/_meta").cloned(),
|
||||
sse_acceptable: transport::accepts_event_stream(&parts.headers),
|
||||
});
|
||||
// Legacy SDK calls outlive disconnected bodies: both lifetimes share one slot.
|
||||
let permit = match ActiveStreamGuard::try_acquire(&state.session_slots) {
|
||||
Ok(permit) => Arc::new(permit),
|
||||
Err(_) => return StatusCode::TOO_MANY_REQUESTS.into_response(),
|
||||
};
|
||||
if method == "tools/call" {
|
||||
parts.extensions.insert(permit.clone());
|
||||
}
|
||||
let response = service
|
||||
.handle(Request::from_parts(parts, Body::from(bytes)))
|
||||
.await;
|
||||
let (parts, body) = response.into_parts();
|
||||
let stream = futures_util::stream::unfold(
|
||||
(Box::pin(Body::new(body).into_data_stream()), permit),
|
||||
|(mut stream, permit)| async move {
|
||||
stream.next().await.map(|chunk| (chunk, (stream, permit)))
|
||||
},
|
||||
);
|
||||
Response::from_parts(parts, Body::from_stream(stream))
|
||||
}
|
||||
}),
|
||||
)
|
||||
.layer(axum::middleware::from_fn(
|
||||
crate::request_context::apply_request_context,
|
||||
))
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
//! Behavioural ATDD for rmcp 3.7.0 LocalSessionManager reconnect/restart semantics.
|
||||
|
||||
use rmcp::transport::streamable_http_server::session::{
|
||||
SessionManager, local::LocalSessionManager,
|
||||
};
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_local_session_manager_preserves_access_to_created_session() {
|
||||
let manager = LocalSessionManager::default();
|
||||
|
||||
let (session_id, _transport) = manager
|
||||
.create_session()
|
||||
.await
|
||||
.expect("local manager must create a session");
|
||||
|
||||
assert!(
|
||||
manager
|
||||
.has_session(&session_id)
|
||||
.await
|
||||
.expect("live manager must answer has_session"),
|
||||
"a live manager must keep access to a session it created"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_fresh_session_manager_without_external_store_rejects_known_session_id() {
|
||||
let first_manager = LocalSessionManager::default();
|
||||
|
||||
let (session_id, _transport) = first_manager
|
||||
.create_session()
|
||||
.await
|
||||
.expect("first local manager must create a session");
|
||||
|
||||
let second_manager = LocalSessionManager::default();
|
||||
|
||||
assert!(
|
||||
!second_manager
|
||||
.has_session(&session_id)
|
||||
.await
|
||||
.expect("fresh manager must answer has_session"),
|
||||
"a fresh in-memory manager must not claim ownership of another manager's session"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,258 @@
|
||||
//! Isolated rmcp 3.7.0 Tools adapter over Crank's existing typed Tools service.
|
||||
//!
|
||||
//! This module deliberately does not provide a second command engine. It owns only
|
||||
//! the verified request identity (`ServiceContext` data) and delegates both
|
||||
//! `tools/list` and `tools/call` to `handle_tools_command` via rmcp's
|
||||
//! `ServerHandler` trait. HTTP admission must supply identity for each request.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use crank_core::{CorrelationContext, ExecutionLocale};
|
||||
|
||||
use crate::app::{AppState, lifecycle::ToolCallLifecycle};
|
||||
use crate::auth::VerifiedMachineCredential;
|
||||
use crate::protocol::{
|
||||
ContinuationSupport, ServiceContext, ToolCallCommand, ToolsCommand, ToolsListCommand,
|
||||
ToolsOutcome, handle_tools_command,
|
||||
};
|
||||
|
||||
/// Long-lived handler: never stores credentials obtained on initialization.
|
||||
#[derive(Clone)]
|
||||
pub(super) struct RmcpTools {
|
||||
pub(super) state: Arc<AppState>,
|
||||
pub(super) active: Arc<std::sync::atomic::AtomicUsize>,
|
||||
}
|
||||
|
||||
struct ActiveCall(Arc<std::sync::atomic::AtomicUsize>);
|
||||
impl Drop for ActiveCall {
|
||||
fn drop(&mut self) {
|
||||
self.0.fetch_sub(1, std::sync::atomic::Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
/// Server-created identity attached to the individual admitted HTTP request.
|
||||
#[derive(Clone)]
|
||||
pub(super) struct RmcpRequestIdentity {
|
||||
pub(super) workspace_slug: String,
|
||||
pub(super) agent_slug: String,
|
||||
pub(super) credential: VerifiedMachineCredential,
|
||||
pub(super) correlation: CorrelationContext,
|
||||
pub(super) continuation: ContinuationSupport,
|
||||
pub(super) locale: ExecutionLocale,
|
||||
pub(super) session_id: Option<String>,
|
||||
pub(super) progress_meta: Option<serde_json::Value>,
|
||||
pub(super) sse_acceptable: bool,
|
||||
}
|
||||
|
||||
impl RmcpRequestIdentity {
|
||||
/// Build the neutral `ServiceContext` borrowed from this adapter's owned data.
|
||||
pub(super) fn service_context(&self) -> ServiceContext<'_> {
|
||||
ServiceContext {
|
||||
workspace_slug: &self.workspace_slug,
|
||||
agent_slug: &self.agent_slug,
|
||||
credential: &self.credential,
|
||||
correlation: &self.correlation,
|
||||
continuation: self.continuation,
|
||||
locale: self.locale,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl RmcpTools {
|
||||
/// Delegate one neutral Tools command to the existing shared service.
|
||||
pub(super) async fn handle(
|
||||
&self,
|
||||
identity: &RmcpRequestIdentity,
|
||||
command: ToolsCommand,
|
||||
lifecycle: Option<ToolCallLifecycle>,
|
||||
) -> ToolsOutcome {
|
||||
handle_tools_command(&self.state, identity.service_context(), command, lifecycle).await
|
||||
}
|
||||
|
||||
pub(super) async fn list_tools(
|
||||
&self,
|
||||
identity: &RmcpRequestIdentity,
|
||||
command: ToolsListCommand,
|
||||
lifecycle: Option<ToolCallLifecycle>,
|
||||
) -> ToolsOutcome {
|
||||
self.handle(identity, ToolsCommand::List(command), lifecycle)
|
||||
.await
|
||||
}
|
||||
|
||||
pub(super) async fn call_tool(
|
||||
&self,
|
||||
identity: &RmcpRequestIdentity,
|
||||
command: ToolCallCommand,
|
||||
lifecycle: Option<ToolCallLifecycle>,
|
||||
) -> ToolsOutcome {
|
||||
self.handle(identity, ToolsCommand::Call(command), lifecycle)
|
||||
.await
|
||||
}
|
||||
}
|
||||
use rmcp::ErrorData as McpError;
|
||||
use rmcp::model::{
|
||||
CallToolRequestParams, CallToolResult, ContentBlock, ListToolsResult, PaginatedRequestParams,
|
||||
Tool,
|
||||
};
|
||||
use rmcp::service::RequestContext;
|
||||
use rmcp::{RoleServer, ServerHandler};
|
||||
|
||||
fn request_identity(context: &RequestContext<RoleServer>) -> Result<RmcpRequestIdentity, McpError> {
|
||||
context
|
||||
.extensions
|
||||
.get::<axum::http::request::Parts>()
|
||||
.and_then(|parts| parts.extensions.get::<RmcpRequestIdentity>())
|
||||
.cloned()
|
||||
.ok_or_else(|| McpError::internal_error("missing authenticated request context", None))
|
||||
}
|
||||
|
||||
impl ServerHandler for RmcpTools {
|
||||
fn supported_protocol_versions(
|
||||
&self,
|
||||
) -> std::borrow::Cow<'static, [rmcp::model::ProtocolVersion]> {
|
||||
std::borrow::Cow::Borrowed(&[
|
||||
rmcp::model::ProtocolVersion::V_2025_11_25,
|
||||
rmcp::model::ProtocolVersion::V_2026_07_28,
|
||||
])
|
||||
}
|
||||
|
||||
fn get_info(&self) -> rmcp::model::ServerConfig {
|
||||
let mut info = rmcp::model::ServerConfig::default();
|
||||
info.capabilities = rmcp::model::ServerCapabilities::builder()
|
||||
.enable_tools()
|
||||
.build();
|
||||
info
|
||||
}
|
||||
fn list_tools(
|
||||
&self,
|
||||
request: Option<PaginatedRequestParams>,
|
||||
context: RequestContext<RoleServer>,
|
||||
) -> impl std::future::Future<Output = Result<ListToolsResult, McpError>> + Send + '_ {
|
||||
let request = request.unwrap_or_default();
|
||||
async move {
|
||||
let identity = request_identity(&context)?;
|
||||
let cursor = request.cursor;
|
||||
let command = crate::protocol::ToolsListCommand {
|
||||
cursor,
|
||||
limit: None,
|
||||
};
|
||||
match self.list_tools(&identity, command, None).await {
|
||||
crate::protocol::ToolsOutcome::List { tools, next_cursor } => {
|
||||
let tools = tools
|
||||
.into_iter()
|
||||
.map(serde_json::from_value::<Tool>)
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.map_err(|_| {
|
||||
McpError::internal_error("invalid tool catalog entry", None)
|
||||
})?;
|
||||
Ok(ListToolsResult {
|
||||
tools,
|
||||
next_cursor,
|
||||
..Default::default()
|
||||
})
|
||||
}
|
||||
crate::protocol::ToolsOutcome::InvalidParams(message) => {
|
||||
Err(McpError::invalid_params(message, None))
|
||||
}
|
||||
_ => Err(McpError::internal_error("crate catalog unavailable", None)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn call_tool(
|
||||
&self,
|
||||
request: CallToolRequestParams,
|
||||
context: RequestContext<RoleServer>,
|
||||
) -> Result<rmcp::model::CallToolResponse, McpError> {
|
||||
let identity = request_identity(&context)?;
|
||||
let arguments = request
|
||||
.arguments
|
||||
.map(serde_json::Value::Object)
|
||||
.unwrap_or_else(|| serde_json::json!({}));
|
||||
let command = crate::protocol::ToolCallCommand {
|
||||
tool_name: request.name.to_string(),
|
||||
arguments,
|
||||
confirmation_token: None,
|
||||
};
|
||||
let token = identity
|
||||
.sse_acceptable
|
||||
.then(|| super::lifecycle::token_from_meta(identity.progress_meta.as_ref()))
|
||||
.flatten();
|
||||
// Observe future cleanup directly in the isolated loopback oracle.
|
||||
self.active
|
||||
.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
|
||||
let _active = ActiveCall(self.active.clone());
|
||||
let (mut lifecycle, mut events) = ToolCallLifecycle::new(token.clone());
|
||||
let entry = identity.session_id.as_ref().and_then(|session_id| {
|
||||
self.state.in_flight.register(
|
||||
&super::lifecycle::InFlightScope {
|
||||
session_id: session_id.clone(),
|
||||
owner: identity
|
||||
.credential
|
||||
.platform_api_key_id
|
||||
.as_ref()
|
||||
.map(|id| id.as_str())
|
||||
.unwrap_or("")
|
||||
.to_owned(),
|
||||
},
|
||||
&serde_json::to_value(&context.id).expect("request id serializes"),
|
||||
)
|
||||
});
|
||||
if let Some(entry) = &entry {
|
||||
lifecycle = lifecycle.with_cancel(entry.cancel_signal());
|
||||
}
|
||||
let call = self.call_tool(&identity, command, Some(lifecycle.clone()));
|
||||
tokio::pin!(call);
|
||||
let outcome = loop {
|
||||
tokio::select! {
|
||||
biased;
|
||||
event = async { match events.as_mut() { Some(events) => events.recv().await, None => std::future::pending().await } } => {
|
||||
if let Some(event) = event {
|
||||
if let Some(token) = &token {
|
||||
let params = serde_json::from_value(super::lifecycle::progress_frame(token, &event)["params"].clone()).map_err(|_| McpError::internal_error("invalid progress event", None))?;
|
||||
let _ = context.peer.notify_progress(params).await;
|
||||
}
|
||||
} else { events = None; }
|
||||
}
|
||||
outcome = &mut call => break outcome,
|
||||
_ = lifecycle.cancelled() => { return Err(McpError::internal_error("request cancelled", None)); },
|
||||
_ = context.ct.cancelled() => { return Err(McpError::internal_error("request cancelled", None)); },
|
||||
}
|
||||
};
|
||||
match outcome {
|
||||
crate::protocol::ToolsOutcome::Call(outcome) => match outcome {
|
||||
crate::protocol::ToolCallOutcome::Completed(value)
|
||||
| crate::protocol::ToolCallOutcome::ApprovalPending(value) => {
|
||||
let text = value.to_string();
|
||||
let mut result = CallToolResult::default();
|
||||
result.content = vec![ContentBlock::text(text)];
|
||||
result.structured_content = if value.is_null() { None } else { Some(value) };
|
||||
Ok(result.into())
|
||||
}
|
||||
crate::protocol::ToolCallOutcome::ApprovalUnavailable(_) => {
|
||||
let mut result = CallToolResult::default();
|
||||
result.is_error = Some(true);
|
||||
result.content = vec![ContentBlock::text("approval elicitation not supported")];
|
||||
Ok(result.into())
|
||||
}
|
||||
crate::protocol::ToolCallOutcome::InvalidParams(message) => {
|
||||
Err(McpError::invalid_params(message, None))
|
||||
}
|
||||
crate::protocol::ToolCallOutcome::Error(contract) => {
|
||||
let text = serde_json::to_string(&contract).unwrap_or_default();
|
||||
let mut result = CallToolResult::default();
|
||||
result.is_error = Some(true);
|
||||
result.content = vec![ContentBlock::text(text)];
|
||||
Ok(result.into())
|
||||
}
|
||||
crate::protocol::ToolCallOutcome::InternalFailure => {
|
||||
Err(McpError::internal_error("tool execution failed", None))
|
||||
}
|
||||
},
|
||||
crate::protocol::ToolsOutcome::InvalidParams(message) => {
|
||||
Err(McpError::invalid_params(message, None))
|
||||
}
|
||||
_ => Err(McpError::internal_error("crate catalog unavailable", None)),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -415,7 +415,7 @@ pub(super) fn agent_id() -> AgentId {
|
||||
AgentId::new(format!("agent_{AGENT_SLUG}"))
|
||||
}
|
||||
|
||||
pub(super) async fn publish_agent(
|
||||
pub(crate) async fn publish_agent(
|
||||
registry: &PostgresRegistry,
|
||||
operation: &Operation<Schema, MappingSet>,
|
||||
) {
|
||||
@@ -470,7 +470,7 @@ pub(super) async fn publish_agent(
|
||||
.expect("the agent must be published");
|
||||
}
|
||||
|
||||
pub(super) async fn create_api_key(registry: &PostgresRegistry) -> String {
|
||||
pub(crate) async fn create_api_key(registry: &PostgresRegistry) -> String {
|
||||
let secret = format!("crk_dispatch_observer_{}", uuid::Uuid::now_v7().simple());
|
||||
let api_key = PlatformApiKey {
|
||||
id: PlatformApiKeyId::new("pk_dispatch_observer"),
|
||||
@@ -500,7 +500,7 @@ pub(super) fn hash_access_secret(secret: &str) -> String {
|
||||
URL_SAFE_NO_PAD.encode(Sha256::digest(secret.as_bytes()))
|
||||
}
|
||||
|
||||
pub(super) fn test_operation(base_url: &str) -> Operation<Schema, MappingSet> {
|
||||
pub(crate) fn test_operation(base_url: &str) -> Operation<Schema, MappingSet> {
|
||||
Operation {
|
||||
id: OperationId::new(format!("op_{TOOL_NAME}")),
|
||||
name: TOOL_NAME.to_owned(),
|
||||
|
||||
@@ -0,0 +1,409 @@
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_http_catalog_follows_new_publication_without_reinitializing() {
|
||||
let h = Harness::new().await;
|
||||
let session = h.initialize().await;
|
||||
let list = json!({"jsonrpc":"2.0","id":60,"method":"tools/list"});
|
||||
let listed = frames(
|
||||
h.request("2025-11-25", Some(&session), &list)
|
||||
.send()
|
||||
.await
|
||||
.unwrap(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
listed.last().unwrap()["result"]["tools"][0]["name"],
|
||||
"create_lead"
|
||||
);
|
||||
let workspace = crank_core::WorkspaceId::new("ws_default");
|
||||
let agent = crank_core::AgentId::new("agent_dispatch-observer");
|
||||
let now = time::OffsetDateTime::now_utc();
|
||||
let version = crank_core::AgentVersion {
|
||||
agent_id: agent.clone(),
|
||||
version: 2,
|
||||
status: crank_core::AgentStatus::Draft,
|
||||
instructions: json!({}),
|
||||
tool_selection_policy: crank_core::ToolSelectionPolicy::default(),
|
||||
created_at: now,
|
||||
};
|
||||
let bindings = [crank_core::AgentOperationBinding {
|
||||
operation_id: crank_core::OperationId::new("op_create_lead"),
|
||||
operation_version: 1,
|
||||
tool_name: "new_publication_tool".into(),
|
||||
tool_title: "New Tool".into(),
|
||||
tool_description_override: None,
|
||||
enabled: true,
|
||||
}];
|
||||
h.state
|
||||
.registry
|
||||
.create_agent_draft_version(crank_registry::CreateAgentDraftVersionRequest {
|
||||
workspace_id: &workspace,
|
||||
agent_id: &agent,
|
||||
version: &version,
|
||||
bindings: &bindings,
|
||||
updated_at: &now,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
h.state
|
||||
.registry
|
||||
.publish_agent(crank_registry::PublishAgentRequest {
|
||||
workspace_id: &workspace,
|
||||
agent_id: &agent,
|
||||
version: 2,
|
||||
published_at: &now,
|
||||
published_by: Some("alice"),
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let listed = frames(
|
||||
h.request("2025-11-25", Some(&session), &list)
|
||||
.send()
|
||||
.await
|
||||
.unwrap(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
listed.last().unwrap()["result"]["tools"][0]["name"],
|
||||
"new_publication_tool"
|
||||
);
|
||||
let mut message = call(61, "new-publication@example.test", false, false);
|
||||
message["params"]["name"] = json!("new_publication_tool");
|
||||
let result = frames(
|
||||
h.request("2025-11-25", Some(&session), &message)
|
||||
.send()
|
||||
.await
|
||||
.unwrap(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
result.last().unwrap()["result"]["structuredContent"]["id"],
|
||||
"lead_for_new-publication@example.test"
|
||||
);
|
||||
assert_eq!(h.calls.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_http_identical_request_ids_in_two_sessions_cancel_independently() {
|
||||
let h = Harness::new().await;
|
||||
let a = h.initialize().await;
|
||||
let b = h.initialize().await;
|
||||
let message = call(62, "slow-same-id@example.test", false, true);
|
||||
let first = h
|
||||
.request("2025-11-25", Some(&a), &message)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
let second = h
|
||||
.request("2025-11-25", Some(&b), &message)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
wait_count(&h.calls, 2).await;
|
||||
let cancel =
|
||||
json!({"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":62}});
|
||||
assert_eq!(
|
||||
h.request("2025-11-25", Some(&a), &cancel)
|
||||
.send()
|
||||
.await
|
||||
.unwrap()
|
||||
.status(),
|
||||
202
|
||||
);
|
||||
wait_count(&h.active, 1).await;
|
||||
assert_eq!(
|
||||
h.request("2025-11-25", Some(&b), &cancel)
|
||||
.send()
|
||||
.await
|
||||
.unwrap()
|
||||
.status(),
|
||||
202
|
||||
);
|
||||
wait_count(&h.active, 0).await;
|
||||
for response in [first, second] {
|
||||
assert_eq!(
|
||||
frames(response).await.last().unwrap()["error"]["message"],
|
||||
"request cancelled"
|
||||
);
|
||||
}
|
||||
assert_eq!(h.calls.load(Ordering::SeqCst), 2);
|
||||
}
|
||||
|
||||
// Independent QA: dropped legacy response bodies must not bypass the stream ceiling.
|
||||
#[tokio::test]
|
||||
async fn rmcp_http_qa_legacy_disconnect_does_not_bypass_admission() {
|
||||
let h = Harness::new().await;
|
||||
let session = h.initialize().await;
|
||||
let mut admitted = Vec::new();
|
||||
for id in 100..117 {
|
||||
let response = h
|
||||
.request(
|
||||
"2025-11-25",
|
||||
Some(&session),
|
||||
&call(id, "slow-qa-limit@example.test", false, true),
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
if response.status() == 429 {
|
||||
break;
|
||||
}
|
||||
assert_eq!(response.status(), 200);
|
||||
admitted.push(id);
|
||||
wait_count(&h.calls, admitted.len()).await;
|
||||
drop(response);
|
||||
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
|
||||
}
|
||||
let active_before_cleanup = h.active.load(Ordering::SeqCst);
|
||||
let free_slots = h.state.session_slots.available_permits();
|
||||
let calls_before_cleanup = h.calls.load(Ordering::SeqCst);
|
||||
for id in &admitted {
|
||||
let cancel =
|
||||
json!({"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":id}});
|
||||
assert_eq!(
|
||||
h.request("2025-11-25", Some(&session), &cancel)
|
||||
.send()
|
||||
.await
|
||||
.unwrap()
|
||||
.status(),
|
||||
202
|
||||
);
|
||||
}
|
||||
wait_count(&h.active, 0).await;
|
||||
assert!(
|
||||
admitted.len() <= 16 && calls_before_cleanup <= 16 && active_before_cleanup <= 16,
|
||||
"legacy disconnect bypassed admission: admitted={}, calls={calls_before_cleanup}, active={active_before_cleanup}, free_slots={free_slots}",
|
||||
admitted.len()
|
||||
);
|
||||
tokio::time::timeout(std::time::Duration::from_secs(2), async {
|
||||
while h.state.session_slots.available_permits() != 16 {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("owned cancellation cleanup must release all admission permits");
|
||||
assert_eq!(h.state.session_slots.available_permits(), 16);
|
||||
|
||||
// After cleanup, normal admission and REST execution must work again.
|
||||
let calls_before = h.calls.load(Ordering::SeqCst);
|
||||
let message = call(199, "recovery-after-cleanup@example.test", false, false);
|
||||
let response = h
|
||||
.request("2025-11-25", Some(&session), &message)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), 200);
|
||||
let result = frames(response).await;
|
||||
assert_eq!(
|
||||
result.last().unwrap()["result"]["structuredContent"]["id"],
|
||||
"lead_for_recovery-after-cleanup@example.test"
|
||||
);
|
||||
assert_eq!(h.calls.load(Ordering::SeqCst), calls_before + 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_http_correlation_headers_preserve_each_concurrent_request() {
|
||||
let h = Harness::new().await;
|
||||
let first = call(50, "correlation-first@example.test", true, false);
|
||||
let second = call(51, "correlation-second@example.test", true, false);
|
||||
let (a, b) = tokio::join!(
|
||||
h.request("2026-07-28", None, &first)
|
||||
.header("x-request-id", "rmcp-oracle-first")
|
||||
.send(),
|
||||
h.request("2026-07-28", None, &second)
|
||||
.header("x-request-id", "rmcp-oracle-second")
|
||||
.send()
|
||||
);
|
||||
let a = a.unwrap();
|
||||
let b = b.unwrap();
|
||||
assert_eq!(a.headers()["x-request-id"], "rmcp-oracle-first");
|
||||
assert_eq!(b.headers()["x-request-id"], "rmcp-oracle-second");
|
||||
assert_eq!(
|
||||
frames(a).await[0]["result"]["structuredContent"]["id"],
|
||||
"lead_for_correlation-first@example.test"
|
||||
);
|
||||
assert_eq!(
|
||||
frames(b).await[0]["result"]["structuredContent"]["id"],
|
||||
"lead_for_correlation-second@example.test"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_http_stream_limit_rejects_without_dispatch_then_recovers() {
|
||||
let h = Harness::new().await;
|
||||
let permits = h
|
||||
.state
|
||||
.session_slots
|
||||
.clone()
|
||||
.acquire_many_owned(16)
|
||||
.await
|
||||
.unwrap();
|
||||
let message = call(40, "limit@example.test", true, false);
|
||||
assert_eq!(
|
||||
h.request("2026-07-28", None, &message)
|
||||
.send()
|
||||
.await
|
||||
.unwrap()
|
||||
.status(),
|
||||
429
|
||||
);
|
||||
assert_eq!(h.calls.load(Ordering::SeqCst), 0);
|
||||
drop(permits);
|
||||
let response = h
|
||||
.request("2026-07-28", None, &message)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
frames(response).await[0]["result"]["structuredContent"]["id"],
|
||||
"lead_for_limit@example.test"
|
||||
);
|
||||
assert_eq!(h.calls.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_http_rate_limit_is_existing_admission_not_sdk_default() {
|
||||
let h = Harness::with_rate(1).await;
|
||||
let list = json!({"jsonrpc":"2.0","id":41,"method":"tools/list","params":{"_meta":meta()}});
|
||||
assert_eq!(
|
||||
h.request("2026-07-28", None, &list)
|
||||
.send()
|
||||
.await
|
||||
.unwrap()
|
||||
.status(),
|
||||
200
|
||||
);
|
||||
assert_eq!(
|
||||
h.request(
|
||||
"2026-07-28",
|
||||
None,
|
||||
&call(42, "rate@example.test", true, false)
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.unwrap()
|
||||
.status(),
|
||||
429
|
||||
);
|
||||
assert_eq!(h.calls.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_http_current_durable_store_survives_recreation_but_is_not_sdk_store() {
|
||||
use crate::session::{PostgresTransportSessionStore, TransportSessionStore};
|
||||
let h = Harness::new().await;
|
||||
let store = PostgresTransportSessionStore::from_pool(h.state.registry.pool().clone())
|
||||
.await
|
||||
.unwrap();
|
||||
let now = time::OffsetDateTime::now_utc();
|
||||
let id = store
|
||||
.create(
|
||||
"2025-11-25",
|
||||
"default",
|
||||
"dispatch-observer",
|
||||
false,
|
||||
now,
|
||||
Some(now + time::Duration::hours(24)),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(store.mark_initialized(&id, now).await.unwrap());
|
||||
drop(store);
|
||||
let restarted = PostgresTransportSessionStore::from_pool(h.state.registry.pool().clone())
|
||||
.await
|
||||
.unwrap();
|
||||
let persisted = restarted.get(&id).await.unwrap().unwrap();
|
||||
assert!(persisted.initialized);
|
||||
assert_eq!(persisted.workspace_slug, "default");
|
||||
assert_eq!(persisted.protocol_version, "2025-11-25");
|
||||
assert_eq!(
|
||||
h.request(
|
||||
"2025-11-25",
|
||||
Some(&id),
|
||||
&call(43, "durable@example.test", false, false)
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.unwrap()
|
||||
.status(),
|
||||
404
|
||||
);
|
||||
assert!(
|
||||
restarted.get(&id).await.unwrap().is_some(),
|
||||
"SDK experiment never mutates existing storage"
|
||||
);
|
||||
assert_eq!(h.calls.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_http_json_modern_and_legacy_sse_only_gap_are_observed() {
|
||||
let h = Harness::new().await;
|
||||
let session = h.initialize().await;
|
||||
let response = h
|
||||
.request(
|
||||
"2026-07-28",
|
||||
None,
|
||||
&call(44, "json@example.test", true, false),
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
response.headers()["content-type"]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.starts_with("application/json")
|
||||
);
|
||||
assert_eq!(
|
||||
frames(response).await[0]["result"]["structuredContent"]["id"],
|
||||
"lead_for_json@example.test"
|
||||
);
|
||||
// Build a JSON-only request (not two contradictory Accept carriers).
|
||||
let response = reqwest::Client::new()
|
||||
.post(format!("{}/v1/default/dispatch-observer", h.server.1))
|
||||
.bearer_auth(&h.key)
|
||||
.header("Accept", "application/json")
|
||||
.header("MCP-Protocol-Version", "2025-11-25")
|
||||
.header("MCP-Session-Id", &session)
|
||||
.json(&call(45, "legacy-json@example.test", false, false))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
response.status(),
|
||||
406,
|
||||
"bundled SDK legacy mode requires SSE Accept; not transport parity"
|
||||
);
|
||||
assert_eq!(h.calls.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_http_concurrent_keys_keep_outputs_and_cancel_ownership_separate() {
|
||||
let h = Harness::new().await;
|
||||
let session = h.initialize().await;
|
||||
sqlx::query("insert into platform_api_keys (id, workspace_id, agent_id, key_kind, name, prefix, secret_hash, scopes_json, status, created_at) select 'pk_second', workspace_id, agent_id, key_kind, 'second', prefix, $1, scopes_json, status, created_at from platform_api_keys where id = 'pk_dispatch_observer'")
|
||||
.bind(crate::access::hash_access_secret("test-second-valid-key")).execute(h.state.registry.pool()).await.unwrap();
|
||||
let first = call(46, "first@example.test", false, false);
|
||||
let second = call(47, "second@example.test", false, false);
|
||||
let (a, b) = tokio::join!(
|
||||
h.request("2025-11-25", Some(&session), &first).send(),
|
||||
h.request_as(
|
||||
"2025-11-25",
|
||||
Some(&session),
|
||||
&second,
|
||||
"test-second-valid-key"
|
||||
)
|
||||
.send()
|
||||
);
|
||||
assert_eq!(
|
||||
frames(a.unwrap()).await.last().unwrap()["result"]["structuredContent"]["id"],
|
||||
"lead_for_first@example.test"
|
||||
);
|
||||
assert_eq!(
|
||||
frames(b.unwrap()).await.last().unwrap()["result"]["structuredContent"]["id"],
|
||||
"lead_for_second@example.test"
|
||||
);
|
||||
assert_eq!(h.calls.load(Ordering::SeqCst), 2);
|
||||
}
|
||||
@@ -0,0 +1,563 @@
|
||||
//! Wire oracle for the isolated SDK adapter, with real registry and REST execution.
|
||||
#[path = "rmcp_http_limits.rs"]
|
||||
mod limits;
|
||||
use super::{AgentRoutePath, dispatch_observer::support, rmcp_http, rmcp_tools_tests::test_state};
|
||||
use axum::{Json, Router, extract::State, routing::post};
|
||||
use serde_json::{Value, json};
|
||||
use std::sync::{
|
||||
Arc,
|
||||
atomic::{AtomicUsize, Ordering},
|
||||
};
|
||||
|
||||
struct Server(tokio::task::JoinHandle<()>, String);
|
||||
impl Drop for Server {
|
||||
fn drop(&mut self) {
|
||||
self.0.abort();
|
||||
}
|
||||
}
|
||||
async fn serve(router: Router) -> Server {
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let url = format!("http://{}", listener.local_addr().unwrap());
|
||||
Server(
|
||||
tokio::spawn(async move {
|
||||
axum::serve(listener, router).await.unwrap();
|
||||
}),
|
||||
url,
|
||||
)
|
||||
}
|
||||
async fn upstream(State(count): State<Arc<AtomicUsize>>, Json(body): Json<Value>) -> Json<Value> {
|
||||
count.fetch_add(1, Ordering::SeqCst);
|
||||
if body["email"].as_str().unwrap().starts_with("slow") {
|
||||
tokio::time::sleep(std::time::Duration::from_secs(8)).await;
|
||||
}
|
||||
Json(json!({"id": format!("lead_for_{}", body["email"].as_str().unwrap())}))
|
||||
}
|
||||
struct Harness {
|
||||
server: Server,
|
||||
_upstream: Server,
|
||||
key: String,
|
||||
calls: Arc<AtomicUsize>,
|
||||
state: Arc<super::AppState>,
|
||||
active: Arc<AtomicUsize>,
|
||||
}
|
||||
impl Harness {
|
||||
async fn new() -> Self {
|
||||
Self::with_rate(10_000).await
|
||||
}
|
||||
async fn with_rate(burst: u32) -> Self {
|
||||
let mut state = test_state().await;
|
||||
Arc::get_mut(&mut state).unwrap().api_rate_limiter = crank_runtime::RequestRateLimiter::new(
|
||||
crank_runtime::RequestRateLimitConfig::new(burst, burst).unwrap(),
|
||||
);
|
||||
let calls = Arc::new(AtomicUsize::new(0));
|
||||
let upstream = serve(
|
||||
Router::new()
|
||||
.route("/crm/leads", post(upstream))
|
||||
.with_state(calls.clone()),
|
||||
)
|
||||
.await;
|
||||
let mut operation = support::test_operation(&upstream.1);
|
||||
operation.execution_config.timeout_ms = 10_000;
|
||||
state
|
||||
.registry
|
||||
.create_operation(
|
||||
&crank_core::WorkspaceId::new("ws_default"),
|
||||
&operation,
|
||||
Some("alice"),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
state
|
||||
.registry
|
||||
.publish_operation(crank_registry::PublishRequest {
|
||||
workspace_id: &crank_core::WorkspaceId::new("ws_default"),
|
||||
operation_id: &operation.id,
|
||||
version: 1,
|
||||
published_at: &operation.created_at,
|
||||
published_by: Some("alice"),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
support::publish_agent(&state.registry, &operation).await;
|
||||
let key = support::create_api_key(&state.registry).await;
|
||||
let active = Arc::new(AtomicUsize::new(0));
|
||||
let server = serve(rmcp_http::router(
|
||||
state.clone(),
|
||||
AgentRoutePath {
|
||||
workspace_slug: "default".into(),
|
||||
agent_slug: "dispatch-observer".into(),
|
||||
},
|
||||
active.clone(),
|
||||
))
|
||||
.await;
|
||||
Self {
|
||||
server,
|
||||
_upstream: upstream,
|
||||
key,
|
||||
calls,
|
||||
state,
|
||||
active,
|
||||
}
|
||||
}
|
||||
fn request(
|
||||
&self,
|
||||
revision: &str,
|
||||
session: Option<&str>,
|
||||
message: &Value,
|
||||
) -> reqwest::RequestBuilder {
|
||||
self.request_as(revision, session, message, &self.key)
|
||||
}
|
||||
fn request_as(
|
||||
&self,
|
||||
revision: &str,
|
||||
session: Option<&str>,
|
||||
message: &Value,
|
||||
key: &str,
|
||||
) -> reqwest::RequestBuilder {
|
||||
let mut request = reqwest::Client::new()
|
||||
.post(format!("{}/v1/default/dispatch-observer", self.server.1))
|
||||
.bearer_auth(key)
|
||||
.header("Accept", "application/json, text/event-stream")
|
||||
.header("MCP-Protocol-Version", revision);
|
||||
if let Some(session) = session {
|
||||
request = request.header("MCP-Session-Id", session);
|
||||
}
|
||||
if revision == "2026-07-28" {
|
||||
request = request.header("Mcp-Method", message["method"].as_str().unwrap());
|
||||
if let Some(name) = message.pointer("/params/name").and_then(Value::as_str) {
|
||||
request = request.header("Mcp-Name", name);
|
||||
}
|
||||
}
|
||||
request
|
||||
.json(message)
|
||||
.timeout(std::time::Duration::from_secs(10))
|
||||
}
|
||||
async fn initialize(&self) -> String {
|
||||
let message = json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"oracle","version":"1"}}});
|
||||
let response = self
|
||||
.request("2025-11-25", None, &message)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), 200);
|
||||
let session = response.headers()["MCP-Session-Id"]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.to_owned();
|
||||
let body = frames(response).await;
|
||||
assert_eq!(
|
||||
body.last().unwrap()["result"]["protocolVersion"],
|
||||
"2025-11-25"
|
||||
);
|
||||
let response = self
|
||||
.request(
|
||||
"2025-11-25",
|
||||
Some(&session),
|
||||
&json!({"jsonrpc":"2.0","method":"notifications/initialized"}),
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), 202);
|
||||
session
|
||||
}
|
||||
}
|
||||
fn meta() -> Value {
|
||||
json!({"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{},"io.modelcontextprotocol/clientInfo":{"name":"oracle","version":"1"}})
|
||||
}
|
||||
async fn frames(response: reqwest::Response) -> Vec<Value> {
|
||||
let status = response.status();
|
||||
let text = response.text().await.unwrap();
|
||||
if let Ok(json) = serde_json::from_str(&text) {
|
||||
return vec![json];
|
||||
}
|
||||
let values: Vec<Value> = text
|
||||
.lines()
|
||||
.filter_map(|line| line.strip_prefix("data:"))
|
||||
.filter_map(|data| serde_json::from_str(data.trim()).ok())
|
||||
.collect();
|
||||
assert!(!values.is_empty(), "{status}: {text}");
|
||||
values
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_http_positive_tools_both_revisions() {
|
||||
let h = Harness::new().await;
|
||||
let session = h.initialize().await;
|
||||
for (revision, session) in [("2025-11-25", Some(session.as_str())), ("2026-07-28", None)] {
|
||||
if session.is_none() {
|
||||
let discover = json!({"jsonrpc":"2.0","id":2,"method":"server/discover","params":{"_meta":meta()}});
|
||||
let response = h.request(revision, None, &discover).send().await.unwrap();
|
||||
assert_eq!(response.status(), 200);
|
||||
assert!(!frames(response).await[0]["result"].is_null());
|
||||
}
|
||||
let list = json!({"jsonrpc":"2.0","id":3,"method":"tools/list","params":{"_meta": if session.is_none() { meta() } else { json!({}) }}});
|
||||
let response = h.request(revision, session, &list).send().await.unwrap();
|
||||
assert_eq!(response.status(), 200);
|
||||
assert!(response.headers().contains_key("x-request-id"));
|
||||
let listed = frames(response).await;
|
||||
assert_eq!(
|
||||
listed.last().unwrap()["result"]["tools"][0]["name"],
|
||||
"create_lead"
|
||||
);
|
||||
let call = json!({"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"create_lead","arguments":{"email":"rmcp@example.test"},"_meta":if session.is_none() { meta() } else { json!({}) }}});
|
||||
let response = h.request(revision, session, &call).send().await.unwrap();
|
||||
assert_eq!(response.status(), 200);
|
||||
if session.is_none() {
|
||||
assert!(!response.headers().contains_key("MCP-Session-Id"));
|
||||
}
|
||||
let result = frames(response).await;
|
||||
assert_eq!(
|
||||
result.last().unwrap()["result"]["structuredContent"]["id"],
|
||||
"lead_for_rmcp@example.test",
|
||||
"{result:?}"
|
||||
);
|
||||
}
|
||||
assert_eq!(h.calls.load(Ordering::SeqCst), 2);
|
||||
}
|
||||
|
||||
fn call(id: i64, email: &str, modern: bool, progress: bool) -> Value {
|
||||
let mut metadata = if modern { meta() } else { json!({}) };
|
||||
if progress {
|
||||
metadata["progressToken"] = json!("wire-progress");
|
||||
}
|
||||
json!({"jsonrpc":"2.0","id":id,"method":"tools/call","params":{"name":"create_lead","arguments":{"email":email},"_meta":metadata}})
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_http_credentials_revalidated_after_initialize_and_no_outbound() {
|
||||
let h = Harness::new().await;
|
||||
let session = h.initialize().await;
|
||||
let message = call(10, "denied@example.test", false, false);
|
||||
assert_eq!(
|
||||
h.request_as("2025-11-25", Some(&session), &message, "invalid-test-key")
|
||||
.send()
|
||||
.await
|
||||
.unwrap()
|
||||
.status(),
|
||||
401
|
||||
);
|
||||
// A scope change and expiry are authoritative registry changes, not session credentials.
|
||||
sqlx::query("update platform_api_keys set scopes_json = '[\"read\"]'::jsonb where id = 'pk_dispatch_observer'").execute(h.state.registry.pool()).await.unwrap();
|
||||
assert_eq!(
|
||||
h.request("2025-11-25", Some(&session), &message)
|
||||
.send()
|
||||
.await
|
||||
.unwrap()
|
||||
.status(),
|
||||
403
|
||||
);
|
||||
sqlx::query("update platform_api_keys set scopes_json = '[\"read\",\"write\"]'::jsonb, expires_at = now() - interval '1 second' where id = 'pk_dispatch_observer'").execute(h.state.registry.pool()).await.unwrap();
|
||||
assert_eq!(
|
||||
h.request("2025-11-25", Some(&session), &message)
|
||||
.send()
|
||||
.await
|
||||
.unwrap()
|
||||
.status(),
|
||||
401
|
||||
);
|
||||
sqlx::query("update platform_api_keys set expires_at = null where id = 'pk_dispatch_observer'")
|
||||
.execute(h.state.registry.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
h.state
|
||||
.registry
|
||||
.revoke_platform_api_key(
|
||||
&crank_core::WorkspaceId::new("ws_default"),
|
||||
&crank_core::PlatformApiKeyId::new("pk_dispatch_observer"),
|
||||
&time::OffsetDateTime::now_utc(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
for method in [reqwest::Method::GET, reqwest::Method::DELETE] {
|
||||
assert_eq!(
|
||||
reqwest::Client::new()
|
||||
.request(
|
||||
method,
|
||||
format!("{}/v1/default/dispatch-observer", h.server.1)
|
||||
)
|
||||
.bearer_auth(&h.key)
|
||||
.header("MCP-Session-Id", &session)
|
||||
.header("MCP-Protocol-Version", "2025-11-25")
|
||||
.header("Accept", "text/event-stream")
|
||||
.send()
|
||||
.await
|
||||
.unwrap()
|
||||
.status(),
|
||||
401
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
h.request("2025-11-25", Some(&session), &message)
|
||||
.send()
|
||||
.await
|
||||
.unwrap()
|
||||
.status(),
|
||||
401
|
||||
);
|
||||
assert_eq!(h.calls.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_http_admission_rejects_foreign_route_revision_headers_and_body_overflow() {
|
||||
let h = Harness::new().await;
|
||||
let message = call(11, "denied@example.test", true, false);
|
||||
let response = h
|
||||
.request("2026-07-28", Some("foreign"), &message)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), 400);
|
||||
let response = h
|
||||
.request("2026-07-28", None, &message)
|
||||
.header("Mcp-Name", "foreign")
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), 400);
|
||||
let response = h
|
||||
.request("2026-07-28", None, &message)
|
||||
.header("Origin", "https://evil.example")
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), 403);
|
||||
assert_eq!(
|
||||
h.request("2030-01-01", None, &message)
|
||||
.send()
|
||||
.await
|
||||
.unwrap()
|
||||
.status(),
|
||||
400
|
||||
);
|
||||
let response = reqwest::Client::new()
|
||||
.post(format!("{}/v1/default/foreign-agent", h.server.1))
|
||||
.bearer_auth(&h.key)
|
||||
.json(&message)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), 404);
|
||||
let response = h
|
||||
.request("2026-07-28", None, &message)
|
||||
.body(vec![b' '; 2 * 1024 * 1024 + 1])
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), 413);
|
||||
assert_eq!(h.calls.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_http_progress_is_real_and_tool_error_is_not_protocol_error() {
|
||||
let h = Harness::new().await;
|
||||
let session = h.initialize().await;
|
||||
for (revision, session) in [("2025-11-25", Some(session.as_str())), ("2026-07-28", None)] {
|
||||
let response = h
|
||||
.request(
|
||||
revision,
|
||||
session,
|
||||
&call(20, "progress@example.test", session.is_none(), true),
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), 200);
|
||||
assert!(
|
||||
response.headers()["content-type"]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.starts_with("text/event-stream")
|
||||
);
|
||||
let messages = frames(response).await;
|
||||
let progress: Vec<_> = messages
|
||||
.iter()
|
||||
.filter(|m| m["method"] == "notifications/progress")
|
||||
.collect();
|
||||
assert_eq!(progress.len(), 3, "{messages:?}");
|
||||
for (index, phase) in [
|
||||
"tool_resolved",
|
||||
"authorization_resolved",
|
||||
"execution_dispatched",
|
||||
]
|
||||
.iter()
|
||||
.enumerate()
|
||||
{
|
||||
assert_eq!(progress[index]["params"]["message"], *phase);
|
||||
assert_eq!(
|
||||
progress[index]["params"]["progress"].as_f64(),
|
||||
Some((index + 1) as f64)
|
||||
);
|
||||
assert_eq!(progress[index]["params"]["progressToken"], "wire-progress");
|
||||
}
|
||||
let mut invalid = call(21, "unused", session.is_none(), false);
|
||||
invalid["params"]["arguments"] = json!({"email":123});
|
||||
let response = h.request(revision, session, &invalid).send().await.unwrap();
|
||||
let messages = frames(response).await;
|
||||
let result = messages.last().unwrap();
|
||||
assert_eq!(result["result"]["isError"], true, "{messages:?}");
|
||||
assert!(result.get("error").is_none());
|
||||
}
|
||||
assert_eq!(h.calls.load(Ordering::SeqCst), 2);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_http_reconnect_live_manager_and_restart_loses_sdk_session() {
|
||||
let h = Harness::new().await;
|
||||
let session = h.initialize().await;
|
||||
for _ in 0..2 {
|
||||
let response = reqwest::Client::new()
|
||||
.get(format!("{}/v1/default/dispatch-observer", h.server.1))
|
||||
.bearer_auth(&h.key)
|
||||
.header("MCP-Session-Id", &session)
|
||||
.header("MCP-Protocol-Version", "2025-11-25")
|
||||
.header("Accept", "text/event-stream")
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), 200);
|
||||
drop(response);
|
||||
}
|
||||
let response = h
|
||||
.request(
|
||||
"2025-11-25",
|
||||
Some(&session),
|
||||
&call(22, "reconnect@example.test", false, false),
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
frames(response).await.last().unwrap()["result"]["structuredContent"]["id"],
|
||||
"lead_for_reconnect@example.test"
|
||||
);
|
||||
let fresh = serve(rmcp_http::router(
|
||||
h.state.clone(),
|
||||
AgentRoutePath {
|
||||
workspace_slug: "default".into(),
|
||||
agent_slug: "dispatch-observer".into(),
|
||||
},
|
||||
h.active.clone(),
|
||||
))
|
||||
.await;
|
||||
let response = reqwest::Client::new()
|
||||
.post(format!("{}/v1/default/dispatch-observer", fresh.1))
|
||||
.bearer_auth(&h.key)
|
||||
.header("MCP-Session-Id", &session)
|
||||
.header("MCP-Protocol-Version", "2025-11-25")
|
||||
.header("Accept", "application/json, text/event-stream")
|
||||
.json(&call(23, "restart@example.test", false, false))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
response.status(),
|
||||
404,
|
||||
"new SDK manager cannot restore from Crank session storage"
|
||||
);
|
||||
assert_eq!(h.calls.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
async fn wait_count(counter: &AtomicUsize, expected: usize) {
|
||||
tokio::time::timeout(std::time::Duration::from_secs(3), async {
|
||||
while counter.load(Ordering::SeqCst) != expected {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("bounded wait for the real execution/cleanup");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_http_legacy_cancel_is_owned_by_session_and_current_key() {
|
||||
let h = Harness::new().await;
|
||||
let session = h.initialize().await;
|
||||
let foreign_session = h.initialize().await;
|
||||
// A second valid credential can use this Agent/session but does not own the first call.
|
||||
sqlx::query("insert into platform_api_keys (id, workspace_id, agent_id, key_kind, name, prefix, secret_hash, scopes_json, status, created_at) select 'pk_second', workspace_id, agent_id, key_kind, 'second', prefix, $1, scopes_json, status, created_at from platform_api_keys where id = 'pk_dispatch_observer'")
|
||||
.bind(crate::access::hash_access_secret("test-second-valid-key")).execute(h.state.registry.pool()).await.unwrap();
|
||||
let response = h
|
||||
.request(
|
||||
"2025-11-25",
|
||||
Some(&session),
|
||||
&call(30, "slow-cancel@example.test", false, true),
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
wait_count(&h.calls, 1).await;
|
||||
let cancel =
|
||||
json!({"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":30}});
|
||||
assert_eq!(
|
||||
h.request_as(
|
||||
"2025-11-25",
|
||||
Some(&session),
|
||||
&cancel,
|
||||
"test-second-valid-key"
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.unwrap()
|
||||
.status(),
|
||||
202
|
||||
);
|
||||
assert_eq!(
|
||||
h.request("2025-11-25", Some(&foreign_session), &cancel)
|
||||
.send()
|
||||
.await
|
||||
.unwrap()
|
||||
.status(),
|
||||
202
|
||||
);
|
||||
tokio::time::sleep(std::time::Duration::from_millis(75)).await;
|
||||
assert_eq!(
|
||||
h.active.load(Ordering::SeqCst),
|
||||
1,
|
||||
"foreign cancel must not stop call"
|
||||
);
|
||||
assert_eq!(
|
||||
h.request("2025-11-25", Some(&session), &cancel)
|
||||
.send()
|
||||
.await
|
||||
.unwrap()
|
||||
.status(),
|
||||
202
|
||||
);
|
||||
wait_count(&h.active, 0).await;
|
||||
// Gap: SDK emits an error frame where the existing transport suppresses all terminal frames.
|
||||
let messages = frames(response).await;
|
||||
assert_eq!(
|
||||
messages.last().unwrap()["error"]["message"],
|
||||
"request cancelled"
|
||||
);
|
||||
assert!(!messages.iter().any(|m| m.get("result").is_some()));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_http_modern_disconnect_drops_execution_and_releases_stream_slot() {
|
||||
let h = Harness::new().await;
|
||||
let response = h
|
||||
.request(
|
||||
"2026-07-28",
|
||||
None,
|
||||
&call(31, "slow-disconnect@example.test", true, true),
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
wait_count(&h.calls, 1).await;
|
||||
assert_eq!(h.active.load(Ordering::SeqCst), 1);
|
||||
drop(response);
|
||||
wait_count(&h.active, 0).await;
|
||||
tokio::time::timeout(std::time::Duration::from_secs(2), async {
|
||||
while h.state.session_slots.available_permits() != 16 {
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
h.calls.load(Ordering::SeqCst),
|
||||
1,
|
||||
"disconnect never retries a possible external effect"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
//! Behavioural ATDD for the rmcp 3.7.0 Tools adapter over the existing typed Tools service.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use crank_core::{
|
||||
AdmissionSchedulerConfig, CoordinationStateStore, CorrelationContext, ExecutionLocale,
|
||||
MachineAccessMode, OperationSecurityLevel, PlatformApiKeyScope,
|
||||
};
|
||||
use crank_registry::{AdmissionLimits, MigrationAuthority, PostgresRegistry, PostgresTaskStore};
|
||||
use crank_runtime::{
|
||||
InMemoryCoordinationStateStore, RequestRateLimitConfig, RequestRateLimiter, SecretCrypto,
|
||||
TaskService,
|
||||
};
|
||||
|
||||
use rmcp::model::{CallToolRequestParams, PaginatedRequestParams, RequestId};
|
||||
use rmcp::service::{RequestContext, serve_directly};
|
||||
use rmcp::{RoleServer, ServerHandler};
|
||||
|
||||
use super::{
|
||||
AppState,
|
||||
rmcp_tools::{RmcpRequestIdentity, RmcpTools},
|
||||
};
|
||||
use crate::app::TaskApplication;
|
||||
use crate::auth::{CommunityMachineCredentialVerifier, VerifiedMachineCredential};
|
||||
use crate::catalog::PublishedToolCatalog;
|
||||
use crate::session::{ActiveSessionMetrics, InMemorySessionStore};
|
||||
use crate::transport::AllowedOrigins;
|
||||
|
||||
pub(super) async fn test_state() -> Arc<AppState> {
|
||||
let database_url =
|
||||
crank_test_support::postgres_schema_url_for_task("rmcp_tools_tests", "t_fdcc7df8").await;
|
||||
let pool = sqlx::PgPool::connect(&database_url).await.unwrap();
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
let registry = PostgresRegistry::connect(&database_url).await.unwrap();
|
||||
|
||||
let coordination: Arc<dyn CoordinationStateStore> =
|
||||
Arc::new(InMemoryCoordinationStateStore::default());
|
||||
let sessions = Arc::new(InMemorySessionStore::default());
|
||||
let session_metrics = ActiveSessionMetrics::start(sessions.clone());
|
||||
let catalog = PublishedToolCatalog::new(registry.clone(), Duration::ZERO, coordination.clone());
|
||||
|
||||
let tasks_store = PostgresTaskStore::new(
|
||||
registry.pool().clone(),
|
||||
AdmissionLimits::default(),
|
||||
AdmissionSchedulerConfig::default(),
|
||||
)
|
||||
.expect("default admission limits and scheduler weights are valid");
|
||||
let tasks = Arc::new(TaskApplication::new(
|
||||
registry.clone(),
|
||||
Duration::from_secs(60),
|
||||
coordination.clone(),
|
||||
TaskService::new(Arc::new(tasks_store)),
|
||||
));
|
||||
|
||||
Arc::new(AppState {
|
||||
registry,
|
||||
catalog,
|
||||
runtime: crank_runtime::community_with_outbound_policy(
|
||||
crank_runtime::OutboundHttpPolicy::allowing_hosts(["127.0.0.1"]),
|
||||
)
|
||||
.build(),
|
||||
api_rate_limiter: RequestRateLimiter::new(RequestRateLimitConfig {
|
||||
requests_per_second: 10_000,
|
||||
burst: 10_000,
|
||||
}),
|
||||
artifact_store: None,
|
||||
secret_crypto: SecretCrypto::new("01234567890123456789012345678901")
|
||||
.expect("test master key"),
|
||||
sessions,
|
||||
session_metrics,
|
||||
session_slots: Arc::new(tokio::sync::Semaphore::new(16)),
|
||||
credential_verifier: Arc::new(CommunityMachineCredentialVerifier),
|
||||
allowed_origins: AllowedOrigins::new(None),
|
||||
logging_levels: Arc::new(crate::protocol::LogLevelStore::new()),
|
||||
signal_streams: Arc::new(crate::protocol::StreamRegistry::new()),
|
||||
in_flight: Arc::new(super::lifecycle::InFlightCalls::new(
|
||||
super::lifecycle::MAX_IN_FLIGHT_CALLS,
|
||||
)),
|
||||
tasks,
|
||||
})
|
||||
}
|
||||
|
||||
fn verified_credential() -> VerifiedMachineCredential {
|
||||
VerifiedMachineCredential {
|
||||
machine_access_mode: MachineAccessMode::StaticAgentKey,
|
||||
max_security_level: OperationSecurityLevel::Standard,
|
||||
scopes: vec![PlatformApiKeyScope::Write],
|
||||
platform_api_key_id: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn rmcp_tools(state: Arc<AppState>) -> RmcpTools {
|
||||
RmcpTools {
|
||||
state,
|
||||
active: Arc::default(),
|
||||
}
|
||||
}
|
||||
|
||||
async fn request_context(adapter: &RmcpTools) -> RequestContext<RoleServer> {
|
||||
let (client_io, server_io) = tokio::io::duplex(1024);
|
||||
let (server_reader, server_writer) = tokio::io::split(server_io);
|
||||
let running = serve_directly::<RoleServer, _, _, _, _>(
|
||||
adapter.clone(),
|
||||
(server_reader, server_writer),
|
||||
None,
|
||||
);
|
||||
// keep client side alive for transport lifetime
|
||||
let _ = client_io;
|
||||
let mut context = RequestContext::new(RequestId::Number(1), running.peer().clone());
|
||||
let (mut parts, _) = axum::http::Request::new(()).into_parts();
|
||||
parts.extensions.insert(RmcpRequestIdentity {
|
||||
workspace_slug: "missing-workspace".into(),
|
||||
agent_slug: "missing-agent".into(),
|
||||
credential: verified_credential(),
|
||||
correlation: CorrelationContext::generate(),
|
||||
continuation: crate::protocol::ContinuationSupport::from_supported(false),
|
||||
locale: ExecutionLocale::En,
|
||||
session_id: None,
|
||||
progress_meta: None,
|
||||
sse_acceptable: false,
|
||||
});
|
||||
context.extensions.insert(parts);
|
||||
context
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_adapter_rejects_missing_request_identity() {
|
||||
let adapter = rmcp_tools(test_state().await);
|
||||
let mut context = request_context(&adapter).await;
|
||||
context.extensions.remove::<axum::http::request::Parts>();
|
||||
let result = <RmcpTools as ServerHandler>::list_tools(&adapter, None, context).await;
|
||||
assert!(
|
||||
result
|
||||
.unwrap_err()
|
||||
.message
|
||||
.contains("missing authenticated request context")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_adapter_list_tools_reports_catalog_unavailable_for_unknown_agent() {
|
||||
let state = test_state().await;
|
||||
let adapter = rmcp_tools(state);
|
||||
let ctx = request_context(&adapter).await;
|
||||
|
||||
match <RmcpTools as ServerHandler>::list_tools(
|
||||
&adapter,
|
||||
Some(PaginatedRequestParams::default()),
|
||||
ctx,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Err(err) => assert!(
|
||||
err.message.contains("crate catalog unavailable"),
|
||||
"unexpected error: {}",
|
||||
err.message
|
||||
),
|
||||
Ok(_) => panic!("expected error outcome for unknown agent"),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_adapter_call_tool_reports_catalog_unavailable_for_unknown_agent() {
|
||||
let state = test_state().await;
|
||||
let adapter = rmcp_tools(state);
|
||||
let ctx = request_context(&adapter).await;
|
||||
|
||||
let request = CallToolRequestParams::new("missing_tool");
|
||||
match <RmcpTools as ServerHandler>::call_tool(&adapter, request, ctx).await {
|
||||
Err(err) => assert!(
|
||||
err.message.contains("crate catalog unavailable"),
|
||||
"unexpected error: {}",
|
||||
err.message
|
||||
),
|
||||
Ok(_) => panic!("expected error outcome for unknown agent"),
|
||||
}
|
||||
}
|
||||
@@ -19,11 +19,20 @@ struct TestPostgres {
|
||||
}
|
||||
|
||||
pub async fn postgres_database_url() -> &'static str {
|
||||
&test_postgres().await.database_url
|
||||
&test_postgres("local-tests").await.database_url
|
||||
}
|
||||
|
||||
pub async fn postgres_schema_url(prefix: &str) -> String {
|
||||
let database_url = postgres_database_url().await;
|
||||
create_schema_url(prefix, database_url).await
|
||||
}
|
||||
|
||||
/// The first caller owns the process-wide disposable PostgreSQL container.
|
||||
pub async fn postgres_schema_url_for_task(prefix: &str, task: &str) -> String {
|
||||
create_schema_url(prefix, &test_postgres(task).await.database_url).await
|
||||
}
|
||||
|
||||
async fn create_schema_url(prefix: &str, database_url: &str) -> String {
|
||||
let schema = unique_schema_name(prefix);
|
||||
let mut connection = connect_admin_with_retry(database_url).await;
|
||||
|
||||
@@ -73,22 +82,26 @@ pub fn unique_schema_name(prefix: &str) -> String {
|
||||
format!("{}_{}", normalized_prefix, uuid::Uuid::now_v7().simple())
|
||||
}
|
||||
|
||||
async fn test_postgres() -> &'static TestPostgres {
|
||||
async fn test_postgres(task: &str) -> &'static TestPostgres {
|
||||
POSTGRES
|
||||
.get_or_init(|| async {
|
||||
tokio::task::spawn_blocking(start_postgres)
|
||||
let task = task.to_owned();
|
||||
tokio::task::spawn_blocking(move || start_postgres(task))
|
||||
.await
|
||||
.expect("test PostgreSQL container startup task must complete")
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
fn start_postgres() -> TestPostgres {
|
||||
fn start_postgres(task: String) -> TestPostgres {
|
||||
let container = Postgres::default()
|
||||
.with_db_name("crank")
|
||||
.with_user("crank")
|
||||
.with_password("crank")
|
||||
.with_tag("16-alpine")
|
||||
.with_label("hermes.disposable", "true")
|
||||
.with_label("hermes.task", task)
|
||||
.with_label("hermes.board", "crank")
|
||||
.start()
|
||||
.expect("test PostgreSQL container must start");
|
||||
register_container_cleanup(container.id().to_owned());
|
||||
|
||||
@@ -195,7 +195,7 @@
|
||||
| 0 — исполняемый фундамент | `1.1 → 1.2 → 1.3 → 1.4 → 1.5 → 1.6` | Capability Inventory/baseline сначала; затем единые config, migrations, correlation и typed metric contracts. |
|
||||
| 1 — hardened core | `1.7 → … → 1.16` | Immutable Operation/runtime/outbound и security identity последовательно дают catalog, approvals, history и manual onboarding. |
|
||||
| 2 — import и modern MCP | `2.1 → … → 2.15`; `3.1 → 3.2 → 3.3 → 3.4 → 3.5`, Resource branch `3.6 → 3.7 → {3.8,3.9,3.10 → 3.11}`, Prompt branch `3.12 → 3.13 → 3.14 → 3.15`, composition `3.16`, затем `3.17 → 3.18 → 3.19 → 3.20` | OpenAPI branch закрывает immutable storage, scoped metadata, reconciliation/recovery, Admin API и UX/evidence; MCP foundation открывает независимые Resources, Prompts и Tasks branches. |
|
||||
| 3 — durable execution | после `3.4`: `4.1 → 4.2 → 4.3 → {4.4,4.5,4.6} → 4.7 → 4.8 → 4.9 → 4.10` | Admission/persistence/leases предшествуют lifecycle policy, Tasks extension/UI и capacity/recovery evidence. |
|
||||
| 3 — durable execution | после `3.4`: `4.1 → 4.2 → 4.3 → {4.4,4.5} → 4.7 → 4.8 → 4.9 → 4.10`; business scope 4.6 cancelled | Admission/persistence/leases предшествуют lifecycle policy, Tasks extension/UI и capacity/recovery evidence; business reconciliation не является prerequisite. |
|
||||
| 4 — operational visibility | `5.1 → … → 5.13` | Correlation/search предшествуют browser/server export; spool/loss evidence и metrics предшествуют Prometheus/Grafana/SLO. |
|
||||
| 5 — встроенная нагрузка | `6.1 → {6.2,6.3} → 6.4 → 6.5 → 6.6` | Versioned Scenario → модель/authorization → runner → live control/report. |
|
||||
| 6 — поставка и recovery | `7.1 → … → 7.9` | Config/migration и profiles предшествуют exposure/bundle/hardening; backup/restore предшествуют upgrade. |
|
||||
@@ -276,7 +276,7 @@ Explicit зависимости Epic 8: `8.1 → 8.2`; `8.3,8.4,8.5,8.7,8.8` з
|
||||
| 4.3 | 4 | FR-22, FR-23 | 10 | `AT-4.3-01 … AT-4.3-10` |
|
||||
| 4.4 | 4 | FR-25 | 8 | `AT-4.4-01 … AT-4.4-08` |
|
||||
| 4.5 | 4 | FR-25 | 4 | `AT-4.5-01 … AT-4.5-04` |
|
||||
| 4.6 | 4 | FR-25 | 3 | `AT-4.6-01 … AT-4.6-03` |
|
||||
| 4.6 (business scope cancelled) | 4 | FR-25 | 1 active invariant, 2 historical N/A | `AT-4.6-02`; `AT-4.6-01/03` cancelled, не PASS |
|
||||
| 4.7 | 4 | FR-21, FR-22, FR-25 | 11 | `AT-4.7-01 … AT-4.7-11` |
|
||||
| 4.8 | 4 | FR-26 | 6 | `AT-4.8-01 … AT-4.8-06` |
|
||||
| 4.9 | 4 | FR-26 | 5 | `AT-4.9-01 … AT-4.9-05` |
|
||||
@@ -1243,16 +1243,23 @@ Explicit зависимости Epic 8: `8.1 → 8.2`; `8.3,8.4,8.5,8.7,8.8` з
|
||||
|
||||
**FR:** FR-20 (Tasks cells), FR-21..FR-26.
|
||||
|
||||
Пользователь запускает долгие Tools как durable Tasks, наблюдает progress, отменяет, восстанавливает после restart и разрешает `outcome_unknown` без неконтролируемого повторения side effects.
|
||||
Пользователь запускает долгие Tools как durable Tasks, наблюдает progress, отменяет и восстанавливает protocol-level состояние после restart. При `outcome_unknown` Crank честно сообщает неопределённость; подтверждение внешнего бизнес-эффекта и решение о новой бизнес-попытке принадлежат потребителю.
|
||||
|
||||
**Canonical amendment FR-25 / FR-26 / AR9 (решение владельца 31.10.2026, [issue #34](https://git.itexp.me/bsodfather/crank/issues/34)):**
|
||||
|
||||
- FR-25 сохраняет input continuation, retry/cancel policy и unknown safety. Business reconciliation, external effect verifier, evidence-bearing operator resolution и confirmed new attempt исключены; исторические AC 4.6 cancelled/not_applicable, не реализованы и не PASS.
|
||||
- FR-26 сохраняет Task input UI, permission-aware lifecycle, честный unknown и safety-warning. Business reconciliation/evidence UI и новое cross-owner полномочие больше не являются требованием.
|
||||
- AR9: Crank — MCP proxy/gateway, не business-workflow engine. Temporal/Kafka/verifier не добавляются. Timeout, disconnect и cancel ack не доказывают отсутствие внешнего эффекта; автоматический повтор опасного write запрещён. Опубликованный код и миграции 4.3–4.5 не удаляются.
|
||||
- Итоговая квалификация использует активную scope; исключённые business AC фиксируются N/A, не PASS, и не блокируют 4.7/4.9/4.10. Остальные release gates, blockers 3.3/P4/auth3.20 и production NO_GO сохраняются. Выполнение #106 не разрешает #107/#108/4.7 или production без отдельного решения.
|
||||
|
||||
**Пошаговый интеграционный сценарий:**
|
||||
|
||||
1. Опубликовать execution mode и применить admission limits; sync/background/adaptive + fallback (4.1).
|
||||
2. Атомарно принять durable Task с dispatch intent до acknowledgement (4.2).
|
||||
3. Исполнить Tasks через PostgreSQL CAS leases и fencing; исключить stale writes/duplicate terminal transitions (4.3).
|
||||
4. Проверить retry/cancellation/outcome_unknown; input update; reconciliation evidence (4.4–4.6).
|
||||
4. Проверить retry/cancellation/outcome_unknown; input update и safety warning для unknown (4.4, 4.5; 4.6 business reconciliation отменена).
|
||||
5. Проверить MCP Tasks extension (`tools/call`, `tasks/get|update|cancel`) и fallback для клиентов без extension (4.7).
|
||||
6. Найти Tasks и выполнить безопасные Admin actions; проверить input/reconciliation UI (4.8, 4.9).
|
||||
6. Найти Tasks и выполнить безопасные Admin actions; проверить input UI и unknown-outcome safety display (4.8, 4.9; business reconciliation UI не требуется).
|
||||
7. Доказать capacity/recovery envelope: ≥128 concurrent, 10 000 queued, restart recovery, crash/partition matrix (4.10).
|
||||
|
||||
#### Story 4.1: Публиковать execution mode и применять admission limits
|
||||
@@ -1345,22 +1352,23 @@ Explicit зависимости Epic 8: `8.1 → 8.2`; `8.3,8.4,8.5,8.7,8.8` з
|
||||
| `AT-4.5-03` | **Given** input TTL истёк<br>**When** sweeper обрабатывает Task<br>**Then** Task становится `failed` без нового dispatch<br>**And** expiry reason сохраняется в audit. | Отчёт AT-4.5-03: фактический результат указанного When и наблюдения/значения для каждого Then/And; процедура, revision/config/environment, исполнитель/дата и bounded артефакты с digest. Для мутации/отказа — состояние до/после и число side effects. | Task становится `failed` без нового dispatch; expiry reason сохраняется в audit. |
|
||||
| `AT-4.5-04` | **Given** input-update suite<br>**When** выполняются TTL/replay/conflict/scope/race tests<br>**Then** доказаны schema validation и idempotent update<br>**And** `just verify` проходит. | Отчёт AT-4.5-04: фактический результат указанного When и наблюдения/значения для каждого Then/And; процедура, revision/config/environment, исполнитель/дата и bounded артефакты с digest. Для мутации/отказа — состояние до/после и число side effects. | доказаны schema validation и idempotent update; `just verify` проходит. |
|
||||
|
||||
#### Story 4.6: Разрешать outcome_unknown через reconciliation evidence
|
||||
#### Story 4.6 (CANCELLED / OUT-OF-SCOPE): Разрешать outcome_unknown — только safety invariant, без business reconciliation
|
||||
|
||||
**Requirements:** FR-25 · **Depends on:** Story 4.4 · **Work type:** implementation
|
||||
**Requirements:** FR-25 · **Depends on:** Story 4.4 · **Work type:** historical/cancelled for business scope
|
||||
|
||||
- **Deliverable:** Разрешать outcome_unknown через reconciliation evidence.
|
||||
- **Completion:** outcome этой story и все её AC проверены; будущая qualification не выполняется попутно.
|
||||
- **Deliverable:** Базовая безопасность `outcome_unknown` остаётся: честное состояние, safety-warning, запрет auto retry/cancel-as-success. Business reconciliation, evidence gathering и подтверждённый новый attempt сняты из scope Crank и выполняются потребителем/его оркестрацией.
|
||||
- **Canonical scope amendment (issue #34, 31.10.2026):** исторические `AT-4.6-01` и `AT-4.6-03` — CANCELLED / NOT_APPLICABLE, не PASS. Сохраняется только `AT-4.6-02` invariant: timeout/cancel не доказывают отсутствие внешнего эффекта, `outcome_unknown` не может быть обычной retriable failure, автоматический повтор опасного write запрещён. Gitea verifier, общий reconciliation framework и cross-owner permission не разрабатывать. Уже опубликованные 4.3–4.5 сохраняются; исторические blockers и production NO_GO сохраняются.
|
||||
- **Completion:** безопасный invariant подтверждается; reconciliation business completion не требуется для завершения Epic 4 и 4.7/4.9/4.10.
|
||||
|
||||
| Case ID | Проверка (Given / When / Then) | Expected evidence | PASS criterion |
|
||||
|---|---|---|---|
|
||||
| `AT-4.6-01` | **Given** `outcome_unknown`<br>**When** оператор предоставляет reconciliation evidence<br>**Then** разрешены только переходы в `completed`, `failed` либо новый явно подтверждённый attempt<br>**And** evidence immutable, bounded, redacted и связано с attempt/trace без raw secrets или произвольного payload. | Отчёт AT-4.6-01: фактический результат указанного When и наблюдения/значения для каждого Then/And; процедура, revision/config/environment, исполнитель/дата и bounded артефакты с digest. Для мутации/отказа — состояние до/после и число side effects. | разрешены только переходы в `completed`, `failed` либо новый явно подтверждённый attempt; evidence immutable, bounded, redacted и связано с attempt/trace без raw secrets или произвольного payload. |
|
||||
| `AT-4.6-02` | **Given** обычный retry/cancel request для `outcome_unknown`<br>**When** reconciliation отсутствует<br>**Then** request блокируется с предупреждением о side effect<br>**And** protocol adapter не отображает состояние как retriable failure. | Отчёт AT-4.6-02: фактический результат указанного When и наблюдения/значения для каждого Then/And; процедура, revision/config/environment, исполнитель/дата и bounded артефакты с digest. Для мутации/отказа — состояние до/после и число side effects. | request блокируется с предупреждением о side effect; protocol adapter не отображает состояние как retriable failure. |
|
||||
| `AT-4.6-03` | **Given** reconciliation suite<br>**When** выполняются replay/conflict/scope/race tests<br>**Then** доказаны evidence-bearing transitions и запрет retry/cancel без reconciliation<br>**And** `just verify` проходит. | Отчёт AT-4.6-03: фактический результат указанного When и наблюдения/значения для каждого Then/And; процедура, revision/config/environment, исполнитель/дата и bounded артефакты с digest. Для мутации/отказа — состояние до/после и число side effects. | доказаны evidence-bearing transitions и запрет retry/cancel без reconciliation; `just verify` проходит. |
|
||||
| `AT-4.6-01` (historical, cancelled, not PASS) | **Given** `outcome_unknown`<br>**When** оператор ранее рассчитывал предоставить reconciliation evidence<br>**Then** business-reconciliation transition, evidence-bearing operator resolution и confirmed new attempt больше не являются AC Crank<br>**And** verification внешнего бизнес-эффекта выполняется потребителем в собственной оркестрацией. | Запись canonical amendment issue #34 (cancelled/out-of-scope); нет business PASS evidence. | historical / not applicable; не входит в PASS criterion Epic 4. |
|
||||
| `AT-4.6-02` | **Given** обычный retry/cancel request для `outcome_unknown`<br>**When** внешний исход ещё неизвестен<br>**Then** request блокируется с предупреждением о side effect<br>**And** protocol adapter не отображает состояние как retriable failure. | Отчёт AT-4.6-02: фактический результат указанного When и наблюдения/значения для каждого Then/And; процедура, revision/config/environment, исполнитель/дата и bounded артефакты с digest. Для мутации/отказа — состояние до/после и число side effects. | request блокируется с предупреждением о side effect; protocol adapter не отображает состояние как retriable failure. |
|
||||
| `AT-4.6-03` (historical, cancelled, not PASS) | **Given** reconciliation suite<br>**When** ранее ожидались evidence-bearing reconciliation tests<br>**Then** business-reconciliation/race/evidence suite снята из активного scope и не считается PASS<br>**And** остаётся обычный timeout/cancel safety contract из 4.4. | Запись canonical amendment issue #34 (cancelled/out-of-scope); нет business PASS evidence. | historical / not applicable; не входит в PASS criterion Epic 4. |
|
||||
|
||||
#### Story 4.7: Предоставить MCP Task operations и fallback
|
||||
|
||||
**Requirements:** FR-21, FR-22, FR-25 · **Depends on:** Story 4.4, Story 4.5, Story 4.6 · **Work type:** implementation
|
||||
**Requirements:** FR-21, FR-22, FR-25 · **Depends on:** Story 4.4, Story 4.5 · **Work type:** implementation
|
||||
|
||||
- **Deliverable:** Предоставить MCP Task operations и fallback.
|
||||
- **Completion:** outcome этой story и все её AC проверены; будущая qualification не выполняется попутно.
|
||||
@@ -1395,20 +1403,20 @@ Explicit зависимости Epic 8: `8.1 → 8.2`; `8.3,8.4,8.5,8.7,8.8` з
|
||||
| `AT-4.8-05` | **Given** оператор открывает Tasks navigation, filters либо detail<br>**When** он использует keyboard, back/forward, refresh или reconnect<br>**Then** URL-addressable state, permission-aware visibility, focus restoration, semantic labels/errors и `aria-live` updates сохраняют authoritative context<br>**And** contrast соответствует WCAG 2.2 AA, смысл не зависит только от цвета, animation уважает reduced-motion, stale response не перезаписывает новый state. | Отчёт AT-4.8-05: фактический результат указанного When и наблюдения/значения для каждого Then/And; процедура, revision/config/environment, исполнитель/дата и bounded артефакты с digest. Для мутации/отказа — состояние до/после и число side effects. | URL-addressable state, permission-aware visibility, focus restoration, semantic labels/errors и `aria-live` updates сохраняют authoritative context; contrast соответствует WCAG 2.2 AA, смысл не зависит только от цвета, animation уважает reduced-motion, stale response не перезаписывает новый state. |
|
||||
| `AT-4.8-06` | **Given** Task UI suite<br>**When** выполняется Playwright/API testing<br>**Then** покрыты filters, lifecycle, races, bulk confirmation и localization<br>**And** `just verify` проходит. | Отчёт AT-4.8-06: фактический результат указанного When и наблюдения/значения для каждого Then/And; процедура, revision/config/environment, исполнитель/дата и bounded артефакты с digest. Для мутации/отказа — состояние до/после и число side effects. | покрыты filters, lifecycle, races, bulk confirmation и localization; `just verify` проходит. |
|
||||
|
||||
#### Story 4.9: Предоставить Task input и reconciliation UI
|
||||
#### Story 4.9: Предоставить Task input и unknown-outcome safety UI
|
||||
|
||||
**Requirements:** FR-26 · **Depends on:** Story 4.8, Story 4.5, Story 4.6 · **Work type:** implementation
|
||||
**Requirements:** FR-26 · **Depends on:** Story 4.8, Story 4.5 · **Work type:** implementation
|
||||
|
||||
- **Deliverable:** Предоставить Task input и reconciliation UI.
|
||||
- **Deliverable:** Предоставить Task input и unknown-outcome safety UI без business reconciliation/evidence/confirmed new attempt.
|
||||
- **Completion:** outcome этой story и все её AC проверены; будущая qualification не выполняется попутно.
|
||||
|
||||
| Case ID | Проверка (Given / When / Then) | Expected evidence | PASS criterion |
|
||||
|---|---|---|---|
|
||||
| `AT-4.9-01` | **Given** `input_required`<br>**When** вводится дополнительный input<br>**Then** form строится из versioned schema и server validates again<br>**And** duplicate submit idempotent, conflicting stale submit видим. | Отчёт AT-4.9-01: фактический результат указанного When и наблюдения/значения для каждого Then/And; процедура, revision/config/environment, исполнитель/дата и bounded артефакты с digest. Для мутации/отказа — состояние до/после и число side effects. | form строится из versioned schema и server validates again; duplicate submit idempotent, conflicting stale submit видим. |
|
||||
| `AT-4.9-02` | **Given** `outcome_unknown`<br>**When** details открыты<br>**Then** обычные Retry/Cancel disabled, отображается предупреждение и reconciliation flow<br>**And** evidence/explicit new attempt требуют confirmation. | Отчёт AT-4.9-02: фактический результат указанного When и наблюдения/значения для каждого Then/And; процедура, revision/config/environment, исполнитель/дата и bounded артефакты с digest. Для мутации/отказа — состояние до/после и число side effects. | обычные Retry/Cancel disabled, отображается предупреждение и reconciliation flow; evidence/explicit new attempt требуют confirmation. |
|
||||
| `AT-4.9-02` | **Given** `outcome_unknown`<br>**When** details открыты<br>**Then** обычные Retry/Cancel disabled, отображается предупреждение о возможном внешнем эффекте<br>**And** UI не предлагает business reconciliation, evidence upload или confirmed new attempt. | Фактическое состояние UI/actions и safety-warning; historical business reconciliation AC cancelled, не PASS. | Честный unknown и предупреждение; автоматический повтор опасного write запрещён; business-reconciliation flow не требуется. |
|
||||
| `AT-4.9-03` | **Given** UI polling/live updates<br>**When** workspace/filter/request generation меняется<br>**Then** old response не перезаписывает новый context<br>**And** listeners не дублируются. | Отчёт AT-4.9-03: фактический результат указанного When и наблюдения/значения для каждого Then/And; процедура, revision/config/environment, исполнитель/дата и bounded артефакты с digest. Для мутации/отказа — состояние до/после и число side effects. | old response не перезаписывает новый context; listeners не дублируются. |
|
||||
| `AT-4.9-04` | **Given** оператор открывает Task input либо reconciliation flow<br>**When** он использует keyboard, back/forward, refresh или reconnect<br>**Then** URL-addressable state, permission-aware visibility, focus restoration, semantic labels/errors и `aria-live` updates сохраняют authoritative context<br>**And** contrast соответствует WCAG 2.2 AA, смысл не зависит только от цвета, animation уважает reduced-motion, stale response не перезаписывает новый state. | Отчёт AT-4.9-04: фактический результат указанного When и наблюдения/значения для каждого Then/And; процедура, revision/config/environment, исполнитель/дата и bounded артефакты с digest. Для мутации/отказа — состояние до/после и число side effects. | URL-addressable state, permission-aware visibility, focus restoration, semantic labels/errors и `aria-live` updates сохраняют authoritative context; contrast соответствует WCAG 2.2 AA, смысл не зависит только от цвета, animation уважает reduced-motion, stale response не перезаписывает новый state. |
|
||||
| `AT-4.9-05` | **Given** Task UI suite<br>**When** выполняется Playwright/API testing<br>**Then** покрыты input, reconciliation, races, confirmation и localization<br>**And** `just verify` проходит. | Отчёт AT-4.9-05: фактический результат указанного When и наблюдения/значения для каждого Then/And; процедура, revision/config/environment, исполнитель/дата и bounded артефакты с digest. Для мутации/отказа — состояние до/после и число side effects. | покрыты input, reconciliation, races, confirmation и localization; `just verify` проходит. |
|
||||
| `AT-4.9-04` | **Given** оператор открывает Task input либо unknown-outcome safety details<br>**When** он использует keyboard, back/forward, refresh или reconnect<br>**Then** URL-addressable state, permission-aware visibility, focus restoration, semantic labels/errors и `aria-live` updates сохраняют authoritative context<br>**And** contrast соответствует WCAG 2.2 AA, смысл не зависит только от цвета, animation уважает reduced-motion, stale response не перезаписывает новый state. | Отчёт AT-4.9-04: фактический результат указанного When и наблюдения/значения для каждого Then/And; процедура, revision/config/environment, исполнитель/дата и bounded артефакты с digest. Для мутации/отказа — состояние до/после и число side effects. | URL-addressable state, permission-aware visibility, focus restoration, semantic labels/errors и `aria-live` updates сохраняют authoritative context; contrast соответствует WCAG 2.2 AA, смысл не зависит только от цвета, animation уважает reduced-motion, stale response не перезаписывает новый state. |
|
||||
| `AT-4.9-05` | **Given** Task UI suite<br>**When** выполняется Playwright/API testing<br>**Then** покрыты input, unknown safety, races, confirmation и localization<br>**And** `just verify` проходит. | Отчёт AT-4.9-05: фактический результат указанного When и наблюдения/значения для каждого Then/And; процедура, revision/config/environment, исполнитель/дата и bounded артефакты с digest. Для мутации/отказа — состояние до/после и число side effects. | покрыты input, unknown safety, races, confirmation и localization; `just verify` проходит. |
|
||||
|
||||
#### Story 4.10: Доказать Task capacity и recovery envelope
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Переход Crank на официальный MCP SDK rmcp
|
||||
|
||||
Статус: планирование одобрено владельцем 27.10.2026. Полная миграция и production-переключение этим планом не запускаются. Владелец планирования и очереди — hermes_tl; реализация — hermes_dev; независимая проверка — hermes_qa; Git/CI/релизы — hermes_devops. ARC подключается к конкретному техническому затруднению, не как обязательный новый этап.
|
||||
Статус: планирование одобрено владельцем 27.10.2026; 05.11.2026 отдельно разрешён только изолированный опыт этапа 1 (#106). Этапы 2/3 (#107/#108), новая реализация 4.7 и production-переключение этим разрешением не запускаются. Исполняемый кандидат и конкретные несовместимости: [rmcp106-tools-adapter.md](rmcp106-tools-adapter.md); это не завершённая миграция. Владелец очереди — hermes_tl; реализация — hermes_dev; независимая проверка — hermes_qa; Git/CI/релизы — hermes_devops. ARC подключается к конкретному техническому затруднению, не как обязательный новый этап. Business reconciliation 4.6 отменена решением владельца и [issue #34](https://git.itexp.me/bsodfather/crank/issues/34); она не prerequisite SDK. Input/unknown safety и остальные защитные ограничения сохраняются.
|
||||
|
||||
## Результат
|
||||
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
# Изолированный rmcp Tools adapter (#106)
|
||||
|
||||
## Граница кандидата
|
||||
|
||||
База: `e4953abcd2f5320e1729249221ce9472a175c5f1` (принятый main 4.5).
|
||||
W: `/home/codex/code/crank-worktrees/rmcp106-tools-adapter`.
|
||||
Основание: [#106](https://git.itexp.me/bsodfather/crank/issues/106), comment 2277 и отдельное разрешение владельца 05.11.2026 на этап 1.
|
||||
Это работающий изолированный опыт, не завершённая миграция и не production endpoint.
|
||||
Независимая QA и решение TL следуют после DEV-проверок; документ не заменяет их.
|
||||
|
||||
`app/rmcp_http.rs` создаёт один настоящий `StreamableHttpService` и `LocalSessionManager` на один явно заданный Agent route. Это test-only router, запускаемый wire-набором через настоящий TCP loopback; в `build_app_inner` он не подключён. Отдельный manager на Agent делает session/route ownership явным без новой session database. Все проверки доступа (POST/GET/DELETE), scopes, rate admission, Origin, envelope/revision/session carrier используют существующие Crank helpers. SDK получает только проверенный snapshot текущего запроса через HTTP `Parts.extensions`, не credential из initialize.
|
||||
|
||||
`app/rmcp_tools.rs` реализует официальный `ServerHandler`, но делегирует list/call существующему `handle_tools_command`: опубликованный каталог, runtime, REST mapping, security и error contracts не заменяются. Перезапись публикации и фоновые бизнес-workflows не добавлены. Новый handler рекламирует только Tools и две поддерживаемые revisions.
|
||||
|
||||
SDK закреплён как `rmcp = "=3.7.0"`, HTTP server feature включён, зависимость только dev/test. Cargo.lock сохраняется вместе с кандидатом; фактический transitive `rmcp-macros` — 3.9.0 по semver SDK. Автоматического обновления rmcp нет. Существующие package versions не повышались; lock содержит новые SDK-зависимости и переразрешённые dependency edges.
|
||||
|
||||
## Исполняемые результаты
|
||||
|
||||
Команды выполняются в W с `CARGO_BUILD_JOBS=2 CARGO_INCREMENTAL=0 SQLX_OFFLINE=true`, `HERMES_KANBAN_TASK=t_fdcc7df8`, `HERMES_KANBAN_BOARD=crank`.
|
||||
|
||||
- `cargo test --locked -p crank-community-mcp --lib rmcp_ -- --nocapture --test-threads=1`: exit 0, 20 passed, 0 ignored; 15 wire-тестов и 5 прежних direct-handler/manager проверок. Финальный тестовый прогон — 56.07 s, без полной workspace suite.
|
||||
- `cargo test --locked -p crank-community-mcp --lib app::lifecycle -- --test-threads=1`: exit 0, 7 passed, 0 ignored. Подтверждает существующие progress queue=8, token bound=128, cancellation table=256 и full-table/cleanup семантику. Это existing GREEN, не новый transport benchmark.
|
||||
- Wire positive control: legacy initialize/initialized/session и modern discover/stateless; dynamic list после публикации Agent v2 без reinitialize; реальные calls с проверяемым output и outbound counter. Modern single response — JSON; progress — SSE в обеих revisions.
|
||||
- Реальная проверка invalid/revoked/expired/scope-changed credentials после initialize, чужого route, Origin, неверной revision/name, конфликтующего modern session carrier и body overflow. Rejected calls не достигают upstream. Два валидных ключа могут использовать одну session, без credential pinning.
|
||||
- Progress отражает только три реально пройденные фазы (`tool_resolved`, `authorization_resolved`, `execution_dispatched`), token возвращается клиенту. Tool input-validation error остаётся `isError`, не JSON-RPC protocol error.
|
||||
- Cancel проверен до SDK по `session + platform_api_key_id + typed requestId`: чужой ключ/другая session не отменяют оригинал, одинаковые ids двух sessions независимы. Своё уведомление прекращает pending execution; modern disconnect прекращает future и возвращает stream permit. Эти факты не доказывают отсутствие внешнего бизнес-эффекта; повторного dispatch нет.
|
||||
- Live SDK manager допускает GET reconnect и последующий call. Новый manager со старым SDK id получает 404. Отдельно существующий PostgreSQL session store переживает пересоздание, его запись не удаляется SDK-опытом, но SDK не может обслужить такой durable id.
|
||||
- Небольшой admission smoke: удержанные 16 stream permits дают 429 до dispatch; освобождение восстанавливает call. QA дополнительно выявила обход при legacy disconnect: response body освобождал permit, пока SDK execution продолжался. Correction F1 делит один permit между body и request-local HTTP Parts SDK; слот освобождается только после завершения обеих жизней. Owned cancel проходит до admission, поэтому доступен и при заполненном бюджете. Регрессия использует реальные slow upstream calls с закрытием response, а не ручной захват semaphore. Настроенный существующий rate limiter даёт 429 без outbound. Request body ограничен прежним Axum default 2 MiB; ceilings не увеличены.
|
||||
- Correlation oracle сначала реально упал (exit 101): сервер подменял `x-request-id` сгенерированным UUID. После подключения существующего request-context middleware два конкурентных запроса сохраняют каждый свой id/output, тест GREEN. Это behavioral RED, не compile/setup failure. Для первоначального Tools positive control ранний behavioral RED не записан; последующие успешные проверки не выдаются за исторический RED.
|
||||
|
||||
Correction F1 после первой независимой QA: `cargo test --locked -p crank-community-mcp --lib rmcp_http_ -- --nocapture --test-threads=1` — exit 0, 16 passed, 0 ignored, 50.94 s (отдельно 2m05s пересборки). Включены legacy disconnect/admission regression, восстановление всех 16 permits после owned cancel и новый реальный call с output/counter; также owned/foreign cancel, reconnect, modern disconnect и обычные list/call. Исходный behavioral RED QA (17 продолжающихся executions при 16 свободных slots) переиспользован, не подменён setup failure. Beam `t_c21c9876` усилил этот же oracle; DEV проверил cleanup до assertions и исполнил итоговый файл. Повторные affected clippy и все перечисленные cheap gates — exit 0. Неизменённые 5 direct/manager и 7 lifecycle tests переиспользованы; нового full suite нет.
|
||||
|
||||
Исходные native logs и обновлённый SHA-256 manifest точной дельты приложены к Kanban handoff. Первоначальные setup/compile ошибки и исправленная тестовая ошибка с добавлением второго Authorization header не считаются behavioral RED.
|
||||
|
||||
Дешёвые gates финального кандидата: `cargo clippy --locked -p crank-community-mcp -p crank-test-support --all-targets -- -D warnings`, `cargo fmt --all -- --check`, `git diff --check`, `bash -n scripts/ci-story-checks.sh`, `scripts/check-rust-code-health.sh`, `scripts/check-rust-boundaries.sh` (включая config/migration/metrics/execution boundaries), явный Community-scope scan всех 11 изменённых/новых Rust files — exit 0. Clippy findings исправлены без suppressions. Labels test fixture передаются явно, без чтения environment вне crank-config. Story CI получил тот же непустой `rmcp_` selector; остальные required selectors не удалены. Full workspace, нагрузочная кампания и UI не запускались: production/UI/runtime execution logic не менялись.
|
||||
|
||||
## Конкретные несовместимости — не включать опыт в production
|
||||
|
||||
1. **Хранение сессий — не drop-in.** `TransportSessionStore` хранит Crank-generated id, revision, initialized, elicitation flag, route и TTL; SDK `SessionStore` требует SDK-generated id и полные `InitializeRequestParams` (clientInfo/capabilities). Их нельзя без потерь восстановить из существующего DTO. `LocalSessionManager` умеет restore, но это не совместимость с Crank store: runtime oracle выше отдельно показывает live reconnect, потерю session новым manager и сохранность Crank PostgreSQL state. Last-Event-ID replay и восстановление in-flight execution не доказаны.
|
||||
2. **Legacy JSON-only — несовместимость.** Реальный `Accept: application/json` получает 406 у SDK legacy session path, тогда как modern simple call возвращает JSON. `json_response=true` не исправляет legacy mode. Не скрывать это преобразующим transport framework без отдельного решения.
|
||||
3. **Legacy cancelled terminal frame — несовместимость.** Владение отменой и остановка future работают. Однако при завершении handler с ошибкой SDK пишет `request cancelled` JSON-RPC error frame, а действующий Crank lifecycle заканчивает отменённый stream без terminal frame. Это явно asserted gap, не объявленная wire parity. Бесконечно pending handler ради подавления frame не используется: он удерживал бы execution/память.
|
||||
4. **Budgets SDK требуют дальнейшего решения.** Сохранены Crank limits и bounded queue перед forwarding; SDK channel capacity явно 16, EventStore не включён. SDK session map, request-router/cache и completed-cache TTL (60 s), idle keepalive (300 s) не дают автоматически прежний durable TTL 24 h или доказанный общий memory budget. Smoke выше не является long-run/slow-reader/load qualification. Await SDK notification delivery также требует проверки backpressure до общего включения.
|
||||
|
||||
Минимальные варианты для TL после независимой QA: сохранить Crank endpoint/session/lifecycle и применять SDK на request-scoped dispatch/model seam (вариант ARC), либо отдельно согласовать тонкую persistence mapping и точную transport parity перед #107. Не заменять PostgreSQL in-memory хранилищем, не ослаблять JSON/cancel contract и не строить новый общий framework молча. Текущий опыт доказывает работоспособность Tools, но не даёт GO на замену transport.
|
||||
|
||||
## Остальные MCP-функции и ближайший потребитель
|
||||
|
||||
- Resources/read/list/templates, Prompts/get/list, completion и composition не перенесены; их существующие shared services остаются будущими границами SDK handlers.
|
||||
- Catalog change notifications, subscriptions/listen, resume/replay и logging policy не подключены. Наличие SDK traits не означает parity; эти capabilities не рекламируются новым handler.
|
||||
- Background/adaptive Tasks, input continuation/elicitation, approval flows и Tasks extension этим router не реализованы. `ContinuationSupport=false` — явная граница опыта; сохранённый 4.3–4.5 task state/runtime не меняется. Подтверждён только synchronous shared Tools path.
|
||||
- Ближайший реальный потребитель — #107: `build_app_inner` и действующие endpoint/era adapters могли бы подключить SDK на проверенной typed-command границе после решения по перечисленным gaps. #107/#108/4.7 не запущены и требуют отдельного разрешения. Production NO_GO, blockers3.3/P4/auth3.20 остаются.
|
||||
|
||||
## Передача и сохранность
|
||||
|
||||
Переиспользованы вклады Ornith `t_1597bde6`/`t_de107aae` (частичный Tools handler), Beam `t_c5472eeb` (direct negative tests), Beam `t_1a3e54ff` (два manager tests), Ornith `t_c5611492` (частичная acceptance-plan правка), решение ARC `t_e76984d9`. HTTP поручение `t_bf7332df` осталось superseded partial, не готовой реализацией. Неделимую admission/Parts/cancel/HTTP интеграцию и wire oracle завершил DEV: повторное поручение с запретом integration paths уже приводило к deadlock.
|
||||
|
||||
Общий acceptance plan содержит ограниченный canonical amendment FR-25/FR-26/AR9 по live #34: business reconciliation отменена, не PASS; input/unknown safety сохранены. Исторические архивы PRD/epics не force-added, R WIP не перенесён. План rmcp остаётся планом этапов 2/3.
|
||||
|
||||
Новые loopback servers принадлежат RAII guards и abort при выходе теста; SDK cancellation token связан с lifetime router. Test PostgreSQL получает disposable/task/board labels и удаляется существующим atexit cleanup. Пример одного из проверенных прогонов: контейнер `9737b010c3dd` (task `t_fdcc7df8`, board `crank`, disposable=true). Чужие контейнеры не затрагиваются. `app.rs.orig`/`app.rs.rej` сохранены как прежний WIP, не входят в delivery manifest.
|
||||
@@ -99,3 +99,6 @@ run_atdd "durable task retry attempt spans" -p crank-runtime --test stages retry
|
||||
# durable_tasks::` (the full application -> worker -> PG -> counted upstream input
|
||||
# continuation ATDD, including TTL/replay/conflict/scope races). Duplicating them here
|
||||
# would only run the same bounded set twice.
|
||||
|
||||
# Isolated rmcp #106: real loopback HTTP Tools oracle, plus manager/handler contracts.
|
||||
run_atdd "isolated rmcp Tools adapter" --locked -p crank-community-mcp --lib rmcp_ -- --test-threads=1
|
||||
Reference in new issue
Block a user