Compare commits
26
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1ac5b10c67 | ||
|
|
07a9ef0a4a | ||
|
|
4f83d8d24c | ||
|
|
2a57800f63 | ||
|
|
e359077f6e | ||
|
|
c0117ff6b8 | ||
|
|
24bba2cf33 | ||
|
|
f56553c4d6 | ||
|
|
027e2cb911 | ||
|
|
adabb2065a | ||
|
|
bf773d61b8 | ||
|
|
74a98d9362 | ||
|
|
7f18bce679 | ||
|
|
4ec9d9201b | ||
|
|
cf2909273b | ||
|
|
4a7b230f35 | ||
|
|
cfe11a0a04 | ||
|
|
35a21f8ab5 | ||
|
|
2d0deb8963 | ||
|
|
f0a79362eb | ||
|
|
27f86d4916 | ||
|
|
f728d31dbf | ||
|
|
29ee01b6ef | ||
|
|
bcf8b43516 | ||
|
|
1c256e6c75 | ||
|
|
e4953abcd2 |
No files matched your search
+34
-9
@@ -40,6 +40,15 @@ jobs:
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Detect release-tooling-only changes
|
||||
id: release_tooling
|
||||
env:
|
||||
GITEA_EVENT_NAME: ${{ gitea.event_name }}
|
||||
GITEA_EVENT_BEFORE: ${{ gitea.event.before }}
|
||||
GITEA_PR_BASE_SHA: ${{ gitea.event.pull_request.base.sha }}
|
||||
FORCE_FULL: ${{ inputs.validation_level == 'feature' || contains(gitea.event.pull_request.labels.*.name, 'feature-ready') }}
|
||||
run: python3 scripts/ci-release-tooling-scope.py
|
||||
|
||||
- name: Install Rust toolchain
|
||||
run: |
|
||||
set -eu
|
||||
@@ -48,9 +57,13 @@ jobs:
|
||||
echo "Unable to read Rust toolchain channel from rust-toolchain.toml" >&2
|
||||
exit 1
|
||||
fi
|
||||
rustup toolchain install "$toolchain" --profile minimal --component clippy --component rustfmt
|
||||
rustup default "$toolchain"
|
||||
host="$(rustc -vV | sed -n 's/^host: //p')"
|
||||
if ! rustup run "$toolchain" rustc --version >/dev/null 2>&1 || \
|
||||
! rustup run "$toolchain" cargo --version >/dev/null 2>&1 || \
|
||||
! rustup run "$toolchain" rustfmt --version >/dev/null 2>&1 || \
|
||||
! rustup run "$toolchain" cargo-clippy --version >/dev/null 2>&1; then
|
||||
rustup toolchain install "$toolchain" --profile minimal --component clippy --component rustfmt
|
||||
fi
|
||||
host="$(rustup run "$toolchain" rustc -vV | sed -n 's/^host: //p')"
|
||||
toolchain_dir="${RUSTUP_HOME:-$HOME/.rustup}/toolchains/${toolchain}-${host}"
|
||||
toolchain_bin="$toolchain_dir/bin"
|
||||
if [ ! -x "$toolchain_bin/rustc" ] || [ ! -x "$toolchain_bin/cargo" ]; then
|
||||
@@ -74,15 +87,18 @@ jobs:
|
||||
docker info
|
||||
|
||||
- name: Check typed runtime configuration contract
|
||||
if: steps.release_tooling.outputs.ci_only != 'true'
|
||||
run: |
|
||||
cargo run -p crank-config --bin crank-config-contract -- --check
|
||||
python3 scripts/check-runtime-config.py --root .
|
||||
python3 scripts/check-config-boundaries.py --root .
|
||||
|
||||
- name: Check canonical migration contract
|
||||
if: steps.release_tooling.outputs.ci_only != 'true'
|
||||
run: cargo run -p admin-api --bin crank-migrate -- plan --check
|
||||
|
||||
- name: Check typed metrics contract
|
||||
if: steps.release_tooling.outputs.ci_only != 'true'
|
||||
run: |
|
||||
cargo run -p crank-metrics --bin crank-metrics-contract -- --check
|
||||
python3 scripts/check-metrics-boundaries.py --root .
|
||||
@@ -138,6 +154,7 @@ jobs:
|
||||
python3 scripts/check-openapi-matrix-compatibility.py --base "$base_ref"
|
||||
|
||||
- name: Run Crank story ATDD
|
||||
if: steps.release_tooling.outputs.ci_only != 'true'
|
||||
run: scripts/ci-story-checks.sh
|
||||
ui:
|
||||
name: UI Checks
|
||||
@@ -187,9 +204,13 @@ jobs:
|
||||
echo "Unable to read Rust toolchain channel from rust-toolchain.toml" >&2
|
||||
exit 1
|
||||
fi
|
||||
rustup toolchain install "$toolchain" --profile minimal --component clippy --component rustfmt
|
||||
rustup default "$toolchain"
|
||||
host="$(rustc -vV | sed -n 's/^host: //p')"
|
||||
if ! rustup run "$toolchain" rustc --version >/dev/null 2>&1 || \
|
||||
! rustup run "$toolchain" cargo --version >/dev/null 2>&1 || \
|
||||
! rustup run "$toolchain" rustfmt --version >/dev/null 2>&1 || \
|
||||
! rustup run "$toolchain" cargo-clippy --version >/dev/null 2>&1; then
|
||||
rustup toolchain install "$toolchain" --profile minimal --component clippy --component rustfmt
|
||||
fi
|
||||
host="$(rustup run "$toolchain" rustc -vV | sed -n 's/^host: //p')"
|
||||
toolchain_dir="${RUSTUP_HOME:-$HOME/.rustup}/toolchains/${toolchain}-${host}"
|
||||
toolchain_bin="$toolchain_dir/bin"
|
||||
if [ ! -x "$toolchain_bin/rustc" ] || [ ! -x "$toolchain_bin/cargo" ]; then
|
||||
@@ -266,9 +287,13 @@ jobs:
|
||||
echo "Unable to read Rust toolchain channel from rust-toolchain.toml" >&2
|
||||
exit 1
|
||||
fi
|
||||
rustup toolchain install "$toolchain" --profile minimal --component clippy --component rustfmt
|
||||
rustup default "$toolchain"
|
||||
host="$(rustc -vV | sed -n 's/^host: //p')"
|
||||
if ! rustup run "$toolchain" rustc --version >/dev/null 2>&1 || \
|
||||
! rustup run "$toolchain" cargo --version >/dev/null 2>&1 || \
|
||||
! rustup run "$toolchain" rustfmt --version >/dev/null 2>&1 || \
|
||||
! rustup run "$toolchain" cargo-clippy --version >/dev/null 2>&1; then
|
||||
rustup toolchain install "$toolchain" --profile minimal --component clippy --component rustfmt
|
||||
fi
|
||||
host="$(rustup run "$toolchain" rustc -vV | sed -n 's/^host: //p')"
|
||||
toolchain_dir="${RUSTUP_HOME:-$HOME/.rustup}/toolchains/${toolchain}-${host}"
|
||||
toolchain_bin="$toolchain_dir/bin"
|
||||
if [ ! -x "$toolchain_bin/rustc" ] || [ ! -x "$toolchain_bin/cargo" ]; then
|
||||
|
||||
@@ -12,10 +12,20 @@ on:
|
||||
options: [story, feature]
|
||||
default: story
|
||||
required: true
|
||||
resume_tag:
|
||||
description: Existing draft release tag to resume with image-only steps
|
||||
type: string
|
||||
default: ""
|
||||
required: false
|
||||
resume_source_sha:
|
||||
description: Exact accepted source commit SHA for the resume tag
|
||||
type: string
|
||||
default: ""
|
||||
required: false
|
||||
|
||||
env:
|
||||
REGISTRY: git.itexp.me
|
||||
IMAGE_TAG: ${{ gitea.ref_name }}
|
||||
IMAGE_TAG: ${{ inputs.resume_tag || gitea.ref_name }}
|
||||
ADMIN_API_IMAGE: git.itexp.me/bsodfather/crank-community-admin-api
|
||||
MCP_SERVER_IMAGE: git.itexp.me/bsodfather/crank-community-mcp-server
|
||||
UI_IMAGE: git.itexp.me/bsodfather/crank-community-ui
|
||||
@@ -31,12 +41,47 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: Verify existing release before resume
|
||||
id: resume
|
||||
if: inputs.resume_tag != ''
|
||||
env:
|
||||
GITEA_SERVER_URL: https://git.itexp.me
|
||||
GITEA_REPOSITORY: ${{ gitea.repository }}
|
||||
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
|
||||
RELEASE_TAG: ${{ inputs.resume_tag }}
|
||||
RESUME_SOURCE_SHA: ${{ inputs.resume_source_sha }}
|
||||
run: python3 scripts/ci-release-resume.py
|
||||
- name: Preserve updated image scanner for resume
|
||||
id: pin_resume_scanner
|
||||
if: inputs.resume_tag != ''
|
||||
run: |
|
||||
set -eu
|
||||
scanner_dir="$(mktemp -d "${RUNNER_TEMP:?RUNNER_TEMP is unavailable}/crank-release-scanner.XXXXXX")"
|
||||
cp scripts/scan-images.sh "$scanner_dir/scan-images.sh"
|
||||
cp scripts/check-image-scan.py "$scanner_dir/check-image-scan.py"
|
||||
chmod +x "$scanner_dir/scan-images.sh"
|
||||
printf 'path=%s\n' "$scanner_dir/scan-images.sh" >> "$GITHUB_OUTPUT"
|
||||
- name: Checkout validated release source
|
||||
if: inputs.resume_tag != ''
|
||||
uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
|
||||
with:
|
||||
ref: ${{ steps.resume.outputs.release_tag }}
|
||||
fetch-depth: 0
|
||||
- name: Assert exact release source checkout
|
||||
if: inputs.resume_tag != ''
|
||||
env:
|
||||
EXPECTED_SOURCE_SHA: ${{ steps.resume.outputs.source_sha }}
|
||||
run: test "$(git rev-parse HEAD)" = "$EXPECTED_SOURCE_SHA"
|
||||
- name: Clear optional release evidence
|
||||
if: inputs.resume_tag == ''
|
||||
run: rm -f .tmp/openapi-playwright.json .tmp/openapi-ui-evidence.json
|
||||
|
||||
|
||||
|
||||
- name: Use preinstalled Rust toolchain
|
||||
if: inputs.resume_tag == ''
|
||||
run: |
|
||||
set -eu
|
||||
toolchain_dir="${RUSTUP_HOME:-$HOME/.rustup}/toolchains/1.96.1-x86_64-unknown-linux-gnu"
|
||||
@@ -54,6 +99,7 @@ jobs:
|
||||
"$toolchain_bin/cargo-clippy" --version
|
||||
|
||||
- name: Verify runner toolchain
|
||||
if: inputs.resume_tag == ''
|
||||
run: |
|
||||
python3 --version
|
||||
rustc --version
|
||||
@@ -65,19 +111,23 @@ jobs:
|
||||
bao version
|
||||
|
||||
- name: Install dependency policy tool
|
||||
if: inputs.resume_tag == ''
|
||||
run: cargo install cargo-deny --version 0.20.2 --locked
|
||||
|
||||
- name: Check formatting
|
||||
if: inputs.resume_tag == ''
|
||||
run: cargo fmt --all --check
|
||||
|
||||
- name: Audit Rust dependencies
|
||||
if: inputs.resume_tag == ''
|
||||
run: cargo deny --locked check advisories bans licenses sources
|
||||
|
||||
- name: Run tooling unit tests
|
||||
if: inputs.validation_level == 'feature'
|
||||
if: inputs.resume_tag == '' && inputs.validation_level == 'feature'
|
||||
run: python3 -m unittest discover -s tests/unit
|
||||
|
||||
- name: Check typed runtime configuration contract
|
||||
if: inputs.resume_tag == ''
|
||||
run: |
|
||||
cargo run -p crank-config --bin crank-config-contract -- --check
|
||||
python3 scripts/check-runtime-config.py --root .
|
||||
@@ -85,14 +135,17 @@ jobs:
|
||||
scripts/check-rust-boundaries.sh
|
||||
|
||||
- name: Check canonical migration contract
|
||||
if: inputs.resume_tag == ''
|
||||
run: cargo run -p admin-api --bin crank-migrate -- plan --check
|
||||
|
||||
- name: Check typed metrics contract
|
||||
if: inputs.resume_tag == ''
|
||||
run: |
|
||||
cargo run -p crank-metrics --bin crank-metrics-contract -- --check
|
||||
python3 scripts/check-metrics-boundaries.py --root .
|
||||
|
||||
- name: Check Capability Inventory
|
||||
if: inputs.resume_tag == ''
|
||||
run: |
|
||||
required_args=""
|
||||
for number in $(seq 1 54); do
|
||||
@@ -105,6 +158,7 @@ jobs:
|
||||
$required_args
|
||||
|
||||
- name: Check Capability Baseline
|
||||
if: inputs.resume_tag == ''
|
||||
run: |
|
||||
python3 scripts/validate-capability-baseline.py \
|
||||
--root . \
|
||||
@@ -112,40 +166,46 @@ jobs:
|
||||
--schema docs/schemas/capability-baseline.schema.json
|
||||
|
||||
- name: Check Community scope
|
||||
if: inputs.resume_tag == ''
|
||||
run: scripts/check-community-scope.sh
|
||||
|
||||
- name: Run Crank story ATDD
|
||||
if: inputs.resume_tag == ''
|
||||
run: scripts/ci-story-checks.sh
|
||||
|
||||
- name: Run release quality gates
|
||||
if: inputs.validation_level == 'feature'
|
||||
if: inputs.resume_tag == '' && inputs.validation_level == 'feature'
|
||||
run: |
|
||||
cargo clippy --workspace --all-targets --all-features -- -D warnings
|
||||
cargo test --workspace --all-targets -- --test-threads=1
|
||||
|
||||
- name: Build release binaries
|
||||
if: inputs.resume_tag == ''
|
||||
run: cargo build --release -p admin-api -p mcp-server
|
||||
|
||||
|
||||
- name: Install UI dependencies
|
||||
if: inputs.resume_tag == ''
|
||||
working-directory: apps/ui
|
||||
run: npm ci
|
||||
|
||||
- name: Audit UI dependencies
|
||||
if: inputs.resume_tag == ''
|
||||
working-directory: apps/ui
|
||||
run: npm audit --audit-level=high
|
||||
|
||||
- name: Build UI dist
|
||||
if: inputs.resume_tag == ''
|
||||
working-directory: apps/ui
|
||||
run: npm run build
|
||||
|
||||
- name: Install Playwright browser
|
||||
if: inputs.validation_level == 'feature'
|
||||
if: inputs.resume_tag == '' && inputs.validation_level == 'feature'
|
||||
working-directory: apps/ui
|
||||
run: npx playwright install --with-deps chromium
|
||||
|
||||
- name: Run release end-to-end tests
|
||||
if: inputs.validation_level == 'feature'
|
||||
if: inputs.resume_tag == '' && inputs.validation_level == 'feature'
|
||||
working-directory: apps/ui
|
||||
run: |
|
||||
mkdir -p ../../.tmp
|
||||
@@ -153,7 +213,7 @@ jobs:
|
||||
PLAYWRIGHT_JSON_OUTPUT=../../.tmp/openapi-playwright.json npm run e2e
|
||||
|
||||
- name: Collect sanitized OpenAPI UI release evidence
|
||||
if: inputs.validation_level == 'feature'
|
||||
if: inputs.resume_tag == '' && inputs.validation_level == 'feature'
|
||||
working-directory: apps/ui
|
||||
run: |
|
||||
trap 'rm -f ../../.tmp/openapi-playwright.json' EXIT
|
||||
@@ -175,12 +235,14 @@ jobs:
|
||||
--require-accepted
|
||||
|
||||
- name: Validate deployment manifests
|
||||
if: inputs.resume_tag == ''
|
||||
run: |
|
||||
docker compose -f docker-compose.yml --env-file .env.example config -q
|
||||
docker compose -f deploy/community/docker-compose.yml --env-file deploy/community/.env.example config -q
|
||||
docker compose -f deploy/community/docker-compose.images.yml --env-file deploy/community/.env.images.example --profile local-db config -q
|
||||
|
||||
- name: Package release artifacts
|
||||
if: inputs.resume_tag == ''
|
||||
run: |
|
||||
set -euo pipefail
|
||||
mkdir -p dist/release
|
||||
@@ -204,13 +266,14 @@ jobs:
|
||||
sha256sum "${files[@]}" > "dist/crank-community-${IMAGE_TAG}-checksums.txt"
|
||||
|
||||
- name: Generate SBOM
|
||||
if: inputs.resume_tag == ''
|
||||
run: |
|
||||
docker run --rm -v "$PWD:/workspace" anchore/syft:latest \
|
||||
dir:/workspace -o spdx-json \
|
||||
> dist/crank-community-${IMAGE_TAG}-sbom.spdx.json
|
||||
|
||||
- name: Publish release bundles, checksums, evidence, and SBOM to Gitea
|
||||
if: startsWith(gitea.ref, 'refs/tags/v')
|
||||
if: inputs.resume_tag == '' && startsWith(gitea.ref, 'refs/tags/v')
|
||||
env:
|
||||
# gitea.server_url inside the job container is the internal http://gitea:3000 origin;
|
||||
# the publisher only forwards its token to the public HTTPS origin.
|
||||
@@ -249,6 +312,8 @@ jobs:
|
||||
docker login '${{ env.REGISTRY }}' -u "$DEPLOY_REGISTRY_USER" --password-stdin
|
||||
|
||||
- name: Build and push release images
|
||||
env:
|
||||
RELEASE_IMAGE_SCANNER: ${{ steps.pin_resume_scanner.outputs.path || 'scripts/scan-images.sh' }}
|
||||
run: |
|
||||
docker build -f apps/admin-api/Dockerfile \
|
||||
-t '${{ env.ADMIN_API_IMAGE }}:${{ env.IMAGE_TAG }}' \
|
||||
@@ -285,7 +350,7 @@ jobs:
|
||||
--env-file .tmp/release-migration-smoke.env --profile local-db up -d --wait
|
||||
docker compose -f deploy/community/docker-compose.images.yml \
|
||||
--env-file .tmp/release-migration-smoke.env --profile local-db logs migrate | grep '"status":"applied"'
|
||||
scripts/scan-images.sh \
|
||||
"$RELEASE_IMAGE_SCANNER" \
|
||||
'${{ env.ADMIN_API_IMAGE }}:${{ env.IMAGE_TAG }}' \
|
||||
'${{ env.MCP_SERVER_IMAGE }}:${{ env.IMAGE_TAG }}' \
|
||||
'${{ env.UI_IMAGE }}:${{ env.IMAGE_TAG }}'
|
||||
@@ -297,5 +362,6 @@ jobs:
|
||||
docker push '${{ env.UI_IMAGE }}:latest'
|
||||
|
||||
- name: Show release bundle summary
|
||||
if: inputs.resume_tag == ''
|
||||
run: |
|
||||
ls -lh dist
|
||||
Generated
+215
-65
@@ -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",
|
||||
@@ -584,6 +590,12 @@ dependencies = [
|
||||
"tokio-util",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "const-oid"
|
||||
version = "0.10.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a"
|
||||
|
||||
[[package]]
|
||||
name = "cookie"
|
||||
version = "0.18.1"
|
||||
@@ -653,7 +665,7 @@ version = "0.3.1"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"axum",
|
||||
"base64",
|
||||
"base64 0.22.1",
|
||||
"crank-core",
|
||||
"crank-metrics",
|
||||
"crank-trace",
|
||||
@@ -688,7 +700,7 @@ dependencies = [
|
||||
"argon2",
|
||||
"async-trait",
|
||||
"axum-extra",
|
||||
"base64",
|
||||
"base64 0.22.1",
|
||||
"crank-core",
|
||||
"crank-registry",
|
||||
"rand 0.10.2",
|
||||
@@ -705,7 +717,7 @@ version = "0.3.1"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"axum",
|
||||
"base64",
|
||||
"base64 0.22.1",
|
||||
"crank-adapter-rest",
|
||||
"crank-artifacts",
|
||||
"crank-core",
|
||||
@@ -722,6 +734,7 @@ dependencies = [
|
||||
"opentelemetry",
|
||||
"opentelemetry_sdk",
|
||||
"reqwest 0.12.28",
|
||||
"rmcp",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2 0.10.9",
|
||||
@@ -850,7 +863,7 @@ dependencies = [
|
||||
"aes-gcm",
|
||||
"async-trait",
|
||||
"axum",
|
||||
"base64",
|
||||
"base64 0.22.1",
|
||||
"crank-adapter-rest",
|
||||
"crank-core",
|
||||
"crank-import",
|
||||
@@ -992,8 +1005,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 +1029,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 +1051,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]]
|
||||
@@ -1057,6 +1104,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
|
||||
dependencies = [
|
||||
"block-buffer 0.12.1",
|
||||
"const-oid",
|
||||
"crypto-common 0.2.2",
|
||||
"ctutils",
|
||||
]
|
||||
@@ -1069,7 +1117,7 @@ checksum = "1ac70aa55017e108007fbaf5aa0f54b021c98f92ff8af59d42eda9da96e3dd4f"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 2.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1078,7 +1126,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 +1195,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 +1357,7 @@ checksum = "e835b70203e41293343137df5c0664546da5745f82ec9b84d40be8336958447b"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 2.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1661,7 +1709,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 +1720,7 @@ dependencies = [
|
||||
"libc",
|
||||
"percent-encoding",
|
||||
"pin-project-lite",
|
||||
"socket2 0.5.10",
|
||||
"socket2 0.6.4",
|
||||
"tokio",
|
||||
"tower-service",
|
||||
"tracing",
|
||||
@@ -1920,7 +1968,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264"
|
||||
dependencies = [
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 2.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2056,7 +2104,7 @@ version = "0.3.1"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"axum",
|
||||
"base64",
|
||||
"base64 0.22.1",
|
||||
"crank-artifacts",
|
||||
"crank-community-mcp",
|
||||
"crank-config",
|
||||
@@ -2121,7 +2169,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 +2505,7 @@ dependencies = [
|
||||
"regex",
|
||||
"regex-syntax",
|
||||
"structmeta",
|
||||
"syn",
|
||||
"syn 2.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2471,6 +2519,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 +2548,7 @@ checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 2.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2580,7 +2634,7 @@ dependencies = [
|
||||
"itertools",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 2.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2636,7 +2690,7 @@ dependencies = [
|
||||
"quinn-udp",
|
||||
"rustc-hash",
|
||||
"rustls",
|
||||
"socket2 0.5.10",
|
||||
"socket2 0.6.4",
|
||||
"thiserror 2.0.18",
|
||||
"tokio",
|
||||
"tracing",
|
||||
@@ -2675,9 +2729,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 +2906,7 @@ checksum = "b7186006dcb21920990093f30e3dea63b7d6e977bf1256be20c3563a5db070da"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 2.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2890,7 +2944,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 +2988,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 +3035,53 @@ dependencies = [
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rmcp"
|
||||
version = "3.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d24a7e92f4bcaa36b97fa93c4fa7ca8f3e669eced949345b3462dba333c7f909"
|
||||
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",
|
||||
"sha2 0.11.0",
|
||||
"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"
|
||||
@@ -3008,15 +3109,15 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustix"
|
||||
version = "1.1.4"
|
||||
version = "1.1.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"
|
||||
checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"errno",
|
||||
"libc",
|
||||
"linux-raw-sys 0.12.1",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3075,7 +3176,7 @@ dependencies = [
|
||||
"security-framework",
|
||||
"security-framework-sys",
|
||||
"webpki-root-certs",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3144,12 +3245,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 +3408,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 +3454,7 @@ checksum = "175ee3e80ae9982737ca543e96133087cbd9a485eecc3bc4de9c1a37b47ea59c"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 2.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3349,7 +3475,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 +3495,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 +3536,7 @@ checksum = "94e153fc76e1c6a068703d6d29c508a0b15c061c4b7e43da59cc097bc342673c"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 2.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3544,7 +3670,7 @@ dependencies = [
|
||||
name = "sqlx-core"
|
||||
version = "0.9.0"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"base64 0.22.1",
|
||||
"bytes",
|
||||
"cfg-if",
|
||||
"crc",
|
||||
@@ -3586,7 +3712,7 @@ dependencies = [
|
||||
"quote",
|
||||
"sqlx-core",
|
||||
"sqlx-macros-core",
|
||||
"syn",
|
||||
"syn 2.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3609,7 +3735,7 @@ dependencies = [
|
||||
"sqlx-mysql",
|
||||
"sqlx-postgres",
|
||||
"sqlx-sqlite",
|
||||
"syn",
|
||||
"syn 2.0.118",
|
||||
"thiserror 2.0.18",
|
||||
"tokio",
|
||||
"url",
|
||||
@@ -3650,7 +3776,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 +3832,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 +3877,7 @@ dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"structmeta-derive",
|
||||
"syn",
|
||||
"syn 2.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3749,7 +3888,7 @@ checksum = "152a0b65a590ff6c3da95cabe2353ee04e6167c896b28e3b14478c2636c922fc"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 2.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3769,6 +3908,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 +3936,7 @@ checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 2.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3855,7 +4005,7 @@ checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 2.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3866,7 +4016,7 @@ checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 2.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3957,7 +4107,7 @@ checksum = "385a6cb71ab9ab790c5fe8d67f1645e6c450a7ce006a33de03daa956cf70a496"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 2.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4002,7 +4152,7 @@ checksum = "ac2a5518c70fa84342385732db33fb3f44bc4cc748936eb5833d2df34d6445ef"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"axum",
|
||||
"base64",
|
||||
"base64 0.22.1",
|
||||
"bytes",
|
||||
"h2",
|
||||
"http",
|
||||
@@ -4103,7 +4253,7 @@ checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 2.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4232,7 +4382,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 +4398,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 +4535,7 @@ dependencies = [
|
||||
"bumpalo",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 2.0.118",
|
||||
"wasm-bindgen-shared",
|
||||
]
|
||||
|
||||
@@ -4477,7 +4627,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 +4657,7 @@ checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 2.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4518,7 +4668,7 @@ checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 2.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4712,7 +4862,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"rustix 1.1.4",
|
||||
"rustix 1.1.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4734,7 +4884,7 @@ checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 2.0.118",
|
||||
"synstructure",
|
||||
]
|
||||
|
||||
@@ -4755,7 +4905,7 @@ checksum = "4714fd92cf900833d49538023a9b3915155210801d1c1169eba513b2addefd71"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 2.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4775,7 +4925,7 @@ checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 2.0.118",
|
||||
"synstructure",
|
||||
]
|
||||
|
||||
@@ -4815,7 +4965,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
|
||||
@@ -31,7 +32,11 @@ tokio = { workspace = true, features = ["sync"] }
|
||||
tracing.workspace = true
|
||||
uuid.workspace = true
|
||||
|
||||
# Typed Tools dispatch uses the SDK; its HTTP transport remains test-only.
|
||||
rmcp = { version = "=3.9.0" }
|
||||
|
||||
[dev-dependencies]
|
||||
rmcp = { version = "=3.9.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,19 @@ pub(crate) mod lifecycle;
|
||||
mod metrics;
|
||||
mod request;
|
||||
mod response;
|
||||
mod rmcp_dispatch;
|
||||
#[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::{
|
||||
|
||||
@@ -7,6 +7,9 @@
|
||||
|
||||
use super::request::{InitializeParams, ToolCallParams};
|
||||
use super::response::take_confirmation_token;
|
||||
use super::rmcp_dispatch::{
|
||||
handle_resources_command, handle_tools_command, list_resource_templates,
|
||||
};
|
||||
use crate::{
|
||||
auth::VerifiedMachineCredential,
|
||||
jsonrpc::{
|
||||
@@ -18,8 +21,7 @@ use crate::{
|
||||
PromptGetCommand, PromptsCommand, PromptsListCommand, PromptsOutcome, RequestIdentity,
|
||||
ResourceReadCommand, ResourcesCommand, ResourcesListCommand, ResourcesOutcome,
|
||||
ServiceContext, ToolCallCommand, ToolsCommand, ToolsListCommand, ToolsOutcome,
|
||||
declared_mcp_method, discover_result, handle_completion_command, handle_prompts_command,
|
||||
handle_resources_command, handle_tools_command, validate_modern_request_name,
|
||||
declared_mcp_method, discover_result, validate_modern_request_name,
|
||||
},
|
||||
session::SessionState,
|
||||
tool_error::execution_locale,
|
||||
@@ -42,7 +44,7 @@ use super::response::{
|
||||
resource_templates_list_result, resources_list_result, tools_list_result,
|
||||
};
|
||||
use super::{AgentRoutePath, AppState, TRANSPORT_SESSION_TTL_MS};
|
||||
use crate::protocol::{ResourceTemplatesListError, list_resource_templates};
|
||||
use crate::protocol::ResourceTemplatesListError;
|
||||
const SERVER_NAME: &str = "crank-mcp-server";
|
||||
const SERVER_VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
|
||||
@@ -160,19 +162,18 @@ pub(super) async fn handle_modern_request(
|
||||
)
|
||||
.await;
|
||||
match outcome {
|
||||
ToolsOutcome::List { tools, next_cursor } => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
crate::protocol::project_modern_cacheable_result(
|
||||
version,
|
||||
tools_list_result(tools, next_cursor),
|
||||
ToolsOutcome::List { tools, next_cursor } => {
|
||||
match tools_list_result(tools, next_cursor, version) {
|
||||
Ok(result) => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(request_id(message), result),
|
||||
response_mode,
|
||||
None,
|
||||
Some(version),
|
||||
),
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(version),
|
||||
),
|
||||
Err(error) => internal_jsonrpc_error(message, error),
|
||||
}
|
||||
}
|
||||
ToolsOutcome::InvalidParams(message_text) => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(request_id(message), -32602, message_text),
|
||||
@@ -286,10 +287,10 @@ pub(super) async fn handle_modern_request(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
crate::protocol::project_modern_cacheable_result(
|
||||
version,
|
||||
resources_list_result(resources, next_cursor),
|
||||
),
|
||||
match resources_list_result(resources, next_cursor, version) {
|
||||
Ok(result) => result,
|
||||
Err(error) => return internal_jsonrpc_error(message, error),
|
||||
},
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
@@ -345,10 +346,10 @@ pub(super) async fn handle_modern_request(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
crate::protocol::project_modern_cacheable_result(
|
||||
version,
|
||||
resource_read_result(contents),
|
||||
),
|
||||
match resource_read_result(contents, version) {
|
||||
Ok(result) => result,
|
||||
Err(error) => return internal_jsonrpc_error(message, error),
|
||||
},
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
@@ -434,10 +435,10 @@ pub(super) async fn handle_modern_request(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
crate::protocol::project_modern_cacheable_result(
|
||||
version,
|
||||
resource_templates_list_result(templates, next_cursor),
|
||||
),
|
||||
match resource_templates_list_result(templates, next_cursor, version) {
|
||||
Ok(result) => result,
|
||||
Err(error) => return internal_jsonrpc_error(message, error),
|
||||
},
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
@@ -466,7 +467,7 @@ pub(super) async fn handle_modern_request(
|
||||
);
|
||||
}
|
||||
};
|
||||
let outcome = handle_prompts_command(
|
||||
let outcome = super::rmcp_dispatch::handle_prompts_command(
|
||||
state,
|
||||
resource_service_context(path, credential, transport_correlation, message),
|
||||
version,
|
||||
@@ -483,7 +484,10 @@ pub(super) async fn handle_modern_request(
|
||||
request_id(message),
|
||||
crate::protocol::project_modern_cacheable_result(
|
||||
version,
|
||||
prompts_list_result(prompts, next_cursor),
|
||||
match prompts_list_result(prompts, next_cursor) {
|
||||
Ok(result) => result,
|
||||
Err(error) => return internal_jsonrpc_error(message, error),
|
||||
},
|
||||
),
|
||||
),
|
||||
response_mode,
|
||||
@@ -525,7 +529,7 @@ pub(super) async fn handle_modern_request(
|
||||
if let Err(response) = validate_modern_request_name(message, headers, &command.name) {
|
||||
return *response;
|
||||
}
|
||||
let outcome = handle_prompts_command(
|
||||
let outcome = super::rmcp_dispatch::handle_prompts_command(
|
||||
state,
|
||||
resource_service_context(path, credential, transport_correlation, message),
|
||||
version,
|
||||
@@ -542,7 +546,10 @@ pub(super) async fn handle_modern_request(
|
||||
request_id(message),
|
||||
crate::protocol::project_modern_result(
|
||||
version,
|
||||
prompt_get_result(description, messages),
|
||||
match prompt_get_result(description, messages) {
|
||||
Ok(result) => result,
|
||||
Err(error) => return internal_jsonrpc_error(message, error),
|
||||
},
|
||||
),
|
||||
),
|
||||
response_mode,
|
||||
@@ -616,7 +623,7 @@ pub(super) async fn handle_modern_request(
|
||||
);
|
||||
}
|
||||
};
|
||||
let outcome = handle_completion_command(
|
||||
let outcome = super::rmcp_dispatch::handle_completion_command(
|
||||
state,
|
||||
resource_service_context(path, credential, transport_correlation, message),
|
||||
version,
|
||||
|
||||
@@ -51,9 +51,72 @@ pub(crate) struct CounterSet {
|
||||
era_modern: AtomicUsize,
|
||||
era_legacy: AtomicUsize,
|
||||
tools_service: AtomicUsize,
|
||||
sdk_tools_dispatch: AtomicUsize,
|
||||
sdk_tools_list_result: AtomicUsize,
|
||||
sdk_tools_call_result: AtomicUsize,
|
||||
sdk_resources_dispatch: AtomicUsize,
|
||||
sdk_resources_list_result: AtomicUsize,
|
||||
sdk_resources_read_result: AtomicUsize,
|
||||
sdk_resource_templates_list_result: AtomicUsize,
|
||||
sdk_prompts_dispatch: AtomicUsize,
|
||||
sdk_prompts_list_result: AtomicUsize,
|
||||
sdk_prompts_get_result: AtomicUsize,
|
||||
sdk_completion_dispatch: AtomicUsize,
|
||||
sdk_completion_result: AtomicUsize,
|
||||
}
|
||||
|
||||
impl CounterSet {
|
||||
pub(crate) fn sdk_completion_dispatch(&self) -> usize {
|
||||
self.sdk_completion_dispatch.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
pub(crate) fn sdk_completion_result(&self) -> usize {
|
||||
self.sdk_completion_result.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_prompts_dispatch(&self) -> usize {
|
||||
self.sdk_prompts_dispatch.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
pub(crate) fn sdk_prompts_list_result(&self) -> usize {
|
||||
self.sdk_prompts_list_result.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
pub(crate) fn sdk_prompts_get_result(&self) -> usize {
|
||||
self.sdk_prompts_get_result.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
pub(crate) fn sdk_resources_dispatch(&self) -> usize {
|
||||
self.sdk_resources_dispatch.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
pub(crate) fn sdk_resources_list_result(&self) -> usize {
|
||||
self.sdk_resources_list_result.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
pub(crate) fn sdk_resources_read_result(&self) -> usize {
|
||||
self.sdk_resources_read_result.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
pub(crate) fn sdk_resource_templates_list_result(&self) -> usize {
|
||||
self.sdk_resource_templates_list_result
|
||||
.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
/// SDK typed Tools dispatch entries, separate from the existing era/service snapshot.
|
||||
pub(crate) fn sdk_tools_dispatch(&self) -> usize {
|
||||
self.sdk_tools_dispatch.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
/// Successfully serialized SDK ListToolsResult values, not dispatch entries.
|
||||
pub(crate) fn sdk_tools_list_result(&self) -> usize {
|
||||
self.sdk_tools_list_result.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
/// Successfully serialized SDK CallToolResult values, not dispatch entries.
|
||||
pub(crate) fn sdk_tools_call_result(&self) -> usize {
|
||||
self.sdk_tools_call_result.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
/// Read the counters of one observed request as one comparable snapshot.
|
||||
pub(crate) fn snapshot(&self) -> Snapshot {
|
||||
Snapshot {
|
||||
@@ -134,6 +197,78 @@ pub(crate) fn tools_service_enter() {
|
||||
increment(|counters| &counters.tools_service);
|
||||
}
|
||||
|
||||
/// `SDK_TOOLS_DISPATCH`: entered the real SDK typed Tools dispatch, not just admission.
|
||||
pub(crate) fn sdk_tools_dispatch_enter() {
|
||||
increment(|counters| &counters.sdk_tools_dispatch);
|
||||
}
|
||||
|
||||
/// Mark only after serializing a real SDK ListToolsResult successfully.
|
||||
pub(crate) fn sdk_tools_list_result_serialized() {
|
||||
increment(|counters| &counters.sdk_tools_list_result);
|
||||
}
|
||||
|
||||
/// Mark only after serializing a real SDK CallToolResult successfully.
|
||||
pub(crate) fn sdk_tools_call_result_serialized() {
|
||||
increment(|counters| &counters.sdk_tools_call_result);
|
||||
}
|
||||
|
||||
/// Mark only after converting a Resources request through the real SDK typed path.
|
||||
pub(crate) fn sdk_resources_dispatch_enter() {
|
||||
increment(|counters| &counters.sdk_resources_dispatch);
|
||||
}
|
||||
|
||||
/// Mark only after successfully serializing a real SDK ListResourcesResult.
|
||||
pub(crate) fn sdk_resources_list_result_serialized() {
|
||||
increment(|counters| &counters.sdk_resources_list_result);
|
||||
}
|
||||
|
||||
/// Mark only after successfully serializing a real SDK ReadResourceResult.
|
||||
pub(crate) fn sdk_resources_read_result_serialized() {
|
||||
increment(|counters| &counters.sdk_resources_read_result);
|
||||
}
|
||||
|
||||
/// Mark only after successfully serializing a real SDK ListResourceTemplatesResult.
|
||||
pub(crate) fn sdk_resource_templates_list_result_serialized() {
|
||||
increment(|counters| &counters.sdk_resource_templates_list_result);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "../rmcp_resources_runtime_tests.rs"]
|
||||
mod rmcp_resources_runtime_tests;
|
||||
|
||||
/// Mark only after converting a Prompts request through the real SDK typed path.
|
||||
pub(crate) fn sdk_prompts_dispatch_enter() {
|
||||
increment(|counters| &counters.sdk_prompts_dispatch);
|
||||
}
|
||||
|
||||
/// Mark only after successfully serializing a real SDK ListPromptsResult.
|
||||
pub(crate) fn sdk_prompts_list_result_serialized() {
|
||||
increment(|counters| &counters.sdk_prompts_list_result);
|
||||
}
|
||||
|
||||
/// Mark only after successfully serializing a real SDK GetPromptResult.
|
||||
pub(crate) fn sdk_prompts_get_result_serialized() {
|
||||
increment(|counters| &counters.sdk_prompts_get_result);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "../rmcp_prompts_runtime_tests.rs"]
|
||||
mod rmcp_prompts_runtime_tests;
|
||||
|
||||
/// Mark only after constructing real SDK CompleteRequestParams.
|
||||
pub(crate) fn sdk_completion_dispatch_enter() {
|
||||
increment(|counters| &counters.sdk_completion_dispatch);
|
||||
}
|
||||
|
||||
/// Mark only after successfully serializing real SDK CompleteResult/CompletionInfo.
|
||||
pub(crate) fn sdk_completion_result_serialized() {
|
||||
increment(|counters| &counters.sdk_completion_result);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "../rmcp_completion_runtime_tests.rs"]
|
||||
mod rmcp_completion_runtime_tests;
|
||||
|
||||
fn increment(counter: impl Fn(&CounterSet) -> &AtomicUsize) {
|
||||
let _ = OBSERVER.try_with(|counters| {
|
||||
counter(counters).fetch_add(1, Ordering::SeqCst);
|
||||
@@ -144,7 +279,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
|
||||
@@ -153,3 +288,7 @@ mod support;
|
||||
#[cfg(test)]
|
||||
#[path = "../dispatch_observer_harness.rs"]
|
||||
mod tests;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "../rmcp_runtime_tests.rs"]
|
||||
mod rmcp_runtime_tests;
|
||||
@@ -24,6 +24,9 @@ use super::response::{
|
||||
resource_templates_list_result, resources_list_result, take_confirmation_token,
|
||||
tools_list_result,
|
||||
};
|
||||
use super::rmcp_dispatch::{
|
||||
handle_resources_command, handle_tools_command, list_resource_templates,
|
||||
};
|
||||
use super::{AgentRoutePath, AppState};
|
||||
use crate::{
|
||||
auth::VerifiedMachineCredential,
|
||||
@@ -36,9 +39,7 @@ use crate::{
|
||||
EVENT_LEVEL_APPLIED, INVALID_LEVEL, Kind, LoggingOutcome, MethodHandler, PromptGetCommand,
|
||||
PromptsCommand, PromptsListCommand, PromptsOutcome, RequestIdentity, ResourceReadCommand,
|
||||
ResourcesCommand, ResourcesListCommand, ResourcesOutcome, ServiceContext, SetLevelCommand,
|
||||
ToolCallCommand, ToolsCommand, ToolsListCommand, ToolsOutcome, handle_completion_command,
|
||||
handle_logging_command, handle_prompts_command, handle_resources_command,
|
||||
handle_tools_command,
|
||||
ToolCallCommand, ToolsCommand, ToolsListCommand, ToolsOutcome, handle_logging_command,
|
||||
},
|
||||
tool_error::execution_locale,
|
||||
transport::{ResponseMode, session_id_from_headers, transport_response},
|
||||
@@ -143,13 +144,18 @@ pub(super) async fn handle_legacy_request(
|
||||
)
|
||||
.await;
|
||||
match outcome {
|
||||
ToolsOutcome::List { tools, next_cursor } => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(request_id(message), tools_list_result(tools, next_cursor)),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
),
|
||||
ToolsOutcome::List { tools, next_cursor } => {
|
||||
match tools_list_result(tools, next_cursor, &session.protocol_version) {
|
||||
Ok(result) => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(request_id(message), result),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
),
|
||||
Err(error) => internal_jsonrpc_error(message, error),
|
||||
}
|
||||
}
|
||||
ToolsOutcome::InvalidParams(message_text) => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(request_id(message), -32602, message_text),
|
||||
@@ -278,7 +284,14 @@ pub(super) async fn handle_legacy_request(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
resources_list_result(resources, next_cursor),
|
||||
match resources_list_result(
|
||||
resources,
|
||||
next_cursor,
|
||||
&session.protocol_version,
|
||||
) {
|
||||
Ok(result) => result,
|
||||
Err(error) => return internal_jsonrpc_error(message, error),
|
||||
},
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
@@ -335,7 +348,13 @@ pub(super) async fn handle_legacy_request(
|
||||
match outcome {
|
||||
ResourcesOutcome::Read { contents } => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(request_id(message), resource_read_result(contents)),
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
match resource_read_result(contents, &session.protocol_version) {
|
||||
Ok(result) => result,
|
||||
Err(error) => return internal_jsonrpc_error(message, error),
|
||||
},
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
@@ -394,7 +413,7 @@ pub(super) async fn handle_legacy_request(
|
||||
);
|
||||
}
|
||||
};
|
||||
let (templates, next_cursor) = match crate::protocol::list_resource_templates(
|
||||
let (templates, next_cursor) = match list_resource_templates(
|
||||
&state,
|
||||
&path.workspace_slug,
|
||||
&path.agent_slug,
|
||||
@@ -425,7 +444,14 @@ pub(super) async fn handle_legacy_request(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
resource_templates_list_result(templates, next_cursor),
|
||||
match resource_templates_list_result(
|
||||
templates,
|
||||
next_cursor,
|
||||
&session.protocol_version,
|
||||
) {
|
||||
Ok(result) => result,
|
||||
Err(error) => return internal_jsonrpc_error(message, error),
|
||||
},
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
@@ -458,7 +484,7 @@ pub(super) async fn handle_legacy_request(
|
||||
);
|
||||
}
|
||||
};
|
||||
let outcome = handle_prompts_command(
|
||||
let outcome = super::rmcp_dispatch::handle_prompts_command(
|
||||
&state,
|
||||
ServiceContext {
|
||||
workspace_slug: &session.workspace_slug,
|
||||
@@ -480,7 +506,10 @@ pub(super) async fn handle_legacy_request(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
prompts_list_result(prompts, next_cursor),
|
||||
match prompts_list_result(prompts, next_cursor) {
|
||||
Ok(result) => result,
|
||||
Err(error) => return internal_jsonrpc_error(message, error),
|
||||
},
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
@@ -520,7 +549,7 @@ pub(super) async fn handle_legacy_request(
|
||||
);
|
||||
}
|
||||
};
|
||||
let outcome = handle_prompts_command(
|
||||
let outcome = super::rmcp_dispatch::handle_prompts_command(
|
||||
&state,
|
||||
ServiceContext {
|
||||
workspace_slug: &session.workspace_slug,
|
||||
@@ -542,7 +571,10 @@ pub(super) async fn handle_legacy_request(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
prompt_get_result(description, messages),
|
||||
match prompt_get_result(description, messages) {
|
||||
Ok(result) => result,
|
||||
Err(error) => return internal_jsonrpc_error(message, error),
|
||||
},
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
@@ -615,7 +647,7 @@ pub(super) async fn handle_legacy_request(
|
||||
);
|
||||
}
|
||||
};
|
||||
let outcome = handle_completion_command(
|
||||
let outcome = super::rmcp_dispatch::handle_completion_command(
|
||||
&state,
|
||||
ServiceContext {
|
||||
workspace_slug: &session.workspace_slug,
|
||||
|
||||
@@ -37,16 +37,14 @@ use futures_util::stream;
|
||||
use serde_json::{Number, Value, json};
|
||||
use tokio::sync::{mpsc, watch};
|
||||
|
||||
use super::rmcp_dispatch::handle_tools_command;
|
||||
use super::{
|
||||
AppState,
|
||||
response::{ToolCommandPayload, tool_command_payload, tool_command_response},
|
||||
};
|
||||
use crate::{
|
||||
jsonrpc::request_id,
|
||||
protocol::{
|
||||
ContinuationSupport, ServiceContext, ToolCallCommand, ToolsCommand, ToolsOutcome,
|
||||
handle_tools_command,
|
||||
},
|
||||
protocol::{ContinuationSupport, ServiceContext, ToolCallCommand, ToolsCommand, ToolsOutcome},
|
||||
transport::{ResponseMode, sse_response},
|
||||
};
|
||||
|
||||
@@ -133,7 +131,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",
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
use axum::{http::StatusCode, response::Response};
|
||||
use rmcp::model::{CacheScope, CallToolResult, ContentBlock, ListToolsResult, ResultType, Tool};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::{
|
||||
jsonrpc::{jsonrpc_result, request_id},
|
||||
protocol::project_modern_result,
|
||||
tool_error::{ToolErrorContract, tool_error_text, tool_error_value},
|
||||
transport::{ResponseMode, transport_response},
|
||||
};
|
||||
@@ -30,22 +30,7 @@ pub(super) fn success_tool_payload(
|
||||
protocol_version: &str,
|
||||
output: Value,
|
||||
) -> Value {
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
project_modern_result(
|
||||
protocol_version,
|
||||
json!({
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": serde_json::to_string_pretty(&output).unwrap_or_else(|_| "{}".to_owned())
|
||||
}
|
||||
],
|
||||
"structuredContent": output,
|
||||
"isError": false
|
||||
}),
|
||||
),
|
||||
)
|
||||
call_result_payload(message, protocol_version, sdk_success_tool_result(output))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -69,85 +54,273 @@ pub(super) fn tool_error_payload(
|
||||
protocol_version: &str,
|
||||
error: ToolErrorContract,
|
||||
) -> Value {
|
||||
let error_message = tool_error_text(&error);
|
||||
let error_value = tool_error_value(&error);
|
||||
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
project_modern_result(
|
||||
protocol_version,
|
||||
json!({
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": error_message
|
||||
}
|
||||
],
|
||||
"structuredContent": {
|
||||
"error": error_value
|
||||
},
|
||||
"isError": true
|
||||
}),
|
||||
),
|
||||
)
|
||||
call_result_payload(message, protocol_version, sdk_error_tool_result(error))
|
||||
}
|
||||
|
||||
/// The era-neutral `tools/list` result shape built from the shared command outcome. Object keys end
|
||||
/// up byte-lexicographically ordered, exactly as before the extraction.
|
||||
pub(super) fn tools_list_result(tools: Vec<Value>, next_cursor: Option<String>) -> Value {
|
||||
let mut result = json!({ "tools": tools });
|
||||
if let Some(next_cursor) = next_cursor {
|
||||
result["nextCursor"] = Value::String(next_cursor);
|
||||
}
|
||||
pub(super) fn sdk_success_tool_result(output: Value) -> CallToolResult {
|
||||
let text = serde_json::to_string_pretty(&output).expect("JSON value serializes");
|
||||
let mut result = CallToolResult::success(vec![ContentBlock::text(text)]);
|
||||
result.structured_content = Some(output);
|
||||
result
|
||||
}
|
||||
|
||||
/// The era-neutral `resources/list` result shape (Story 3.8). Same pagination wire keys as
|
||||
/// `tools/list`; `nextCursor` is absent on the last page.
|
||||
pub(super) fn resources_list_result(resources: Vec<Value>, next_cursor: Option<String>) -> Value {
|
||||
let mut result = json!({ "resources": resources });
|
||||
if let Some(next_cursor) = next_cursor {
|
||||
result["nextCursor"] = Value::String(next_cursor);
|
||||
}
|
||||
pub(super) fn sdk_error_tool_result(error: ToolErrorContract) -> CallToolResult {
|
||||
let mut result = CallToolResult::error(vec![ContentBlock::text(tool_error_text(&error))]);
|
||||
result.structured_content = Some(json!({ "error": tool_error_value(&error) }));
|
||||
result
|
||||
}
|
||||
|
||||
/// The era-neutral `resources/read` result shape: exactly the typed `contents[]` the revision
|
||||
/// converter produced.
|
||||
pub(super) fn resource_read_result(contents: Value) -> Value {
|
||||
json!({ "contents": contents })
|
||||
fn call_result_payload(message: &Value, version: &str, mut result: CallToolResult) -> Value {
|
||||
result.result_type =
|
||||
(version == crate::jsonrpc::MODERN_PROTOCOL_VERSION).then_some(ResultType::COMPLETE);
|
||||
let result = serde_json::to_value(result).expect("SDK call result contains JSON values");
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_tools_call_result_serialized();
|
||||
jsonrpc_result(request_id(message), result)
|
||||
}
|
||||
|
||||
pub(super) fn sdk_tools_list_result(
|
||||
tools: &[Value],
|
||||
next_cursor: Option<String>,
|
||||
) -> Result<ListToolsResult, serde_json::Error> {
|
||||
Ok(ListToolsResult {
|
||||
tools: tools
|
||||
.iter()
|
||||
.cloned()
|
||||
.map(serde_json::from_value::<Tool>)
|
||||
.collect::<Result<Vec<_>, _>>()?,
|
||||
next_cursor,
|
||||
..Default::default()
|
||||
})
|
||||
}
|
||||
|
||||
/// Serialize the SDK model, preserving catalog extensions that pinned Tool serde cannot represent.
|
||||
pub(super) fn tools_list_result(
|
||||
tools: Vec<Value>,
|
||||
next_cursor: Option<String>,
|
||||
version: &str,
|
||||
) -> Result<Value, serde_json::Error> {
|
||||
let mut result = sdk_tools_list_result(&tools, next_cursor)?;
|
||||
let modern = version == crate::jsonrpc::MODERN_PROTOCOL_VERSION;
|
||||
result.result_type = modern.then_some(ResultType::COMPLETE);
|
||||
result.ttl_ms = modern.then_some(0);
|
||||
result.cache_scope = modern.then_some(CacheScope::Private);
|
||||
let mut result = serde_json::to_value(result)?;
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_tools_list_result_serialized();
|
||||
for (raw, serialized) in tools
|
||||
.iter()
|
||||
.zip(result["tools"].as_array_mut().expect("SDK tools array"))
|
||||
{
|
||||
let serialized = serialized.as_object_mut().expect("SDK Tool object");
|
||||
for (key, value) in raw.as_object().expect("validated Tool object") {
|
||||
if matches!(key.as_str(), "annotations" | "icons")
|
||||
|| !matches!(
|
||||
key.as_str(),
|
||||
"name" | "title" | "description" | "inputSchema" | "outputSchema" | "_meta"
|
||||
)
|
||||
|| value.is_null()
|
||||
{
|
||||
serialized.insert(key.clone(), value.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// SDK results are serialized before the minimal lossless projection of descriptor extensions.
|
||||
pub(super) fn resources_list_result(
|
||||
resources: Vec<Value>,
|
||||
next_cursor: Option<String>,
|
||||
version: &str,
|
||||
) -> Result<Value, serde_json::Error> {
|
||||
let modern = version == crate::jsonrpc::MODERN_PROTOCOL_VERSION;
|
||||
let result = rmcp::model::ListResourcesResult {
|
||||
resources: resources
|
||||
.iter()
|
||||
.cloned()
|
||||
.map(serde_json::from_value)
|
||||
.collect::<Result<_, _>>()?,
|
||||
next_cursor,
|
||||
result_type: modern.then_some(ResultType::COMPLETE),
|
||||
ttl_ms: modern.then_some(0),
|
||||
cache_scope: modern.then_some(CacheScope::Private),
|
||||
meta: None,
|
||||
};
|
||||
let mut result = serde_json::to_value(result)?;
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_resources_list_result_serialized();
|
||||
preserve_resource_fields(
|
||||
&resources,
|
||||
&mut result["resources"],
|
||||
&[
|
||||
"uri",
|
||||
"name",
|
||||
"title",
|
||||
"description",
|
||||
"mimeType",
|
||||
"size",
|
||||
"_meta",
|
||||
],
|
||||
);
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
pub(super) fn resource_read_result(
|
||||
contents: Value,
|
||||
version: &str,
|
||||
) -> Result<Value, serde_json::Error> {
|
||||
let mut result =
|
||||
rmcp::model::ReadResourceResult::new(serde_json::from_value(contents.clone())?);
|
||||
let modern = version == crate::jsonrpc::MODERN_PROTOCOL_VERSION;
|
||||
result.result_type = modern.then_some(ResultType::COMPLETE);
|
||||
result.ttl_ms = modern.then_some(0);
|
||||
result.cache_scope = modern.then_some(CacheScope::Private);
|
||||
let mut result = serde_json::to_value(result)?;
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_resources_read_result_serialized();
|
||||
preserve_resource_fields(
|
||||
contents.as_array().expect("validated contents array"),
|
||||
&mut result["contents"],
|
||||
&["uri", "mimeType", "text", "blob", "_meta"],
|
||||
);
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// The era-neutral `resources/templates/list` result shape.
|
||||
pub(super) fn resource_templates_list_result(
|
||||
templates: Vec<Value>,
|
||||
next_cursor: Option<String>,
|
||||
) -> Value {
|
||||
let mut result = json!({ "resourceTemplates": templates });
|
||||
if let Some(cursor) = next_cursor {
|
||||
result["nextCursor"] = Value::String(cursor);
|
||||
}
|
||||
result
|
||||
version: &str,
|
||||
) -> Result<Value, serde_json::Error> {
|
||||
let modern = version == crate::jsonrpc::MODERN_PROTOCOL_VERSION;
|
||||
let result = rmcp::model::ListResourceTemplatesResult {
|
||||
resource_templates: templates
|
||||
.iter()
|
||||
.cloned()
|
||||
.map(serde_json::from_value)
|
||||
.collect::<Result<_, _>>()?,
|
||||
next_cursor,
|
||||
result_type: modern.then_some(ResultType::COMPLETE),
|
||||
ttl_ms: modern.then_some(0),
|
||||
cache_scope: modern.then_some(CacheScope::Private),
|
||||
meta: None,
|
||||
};
|
||||
let mut result = serde_json::to_value(result)?;
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_resource_templates_list_result_serialized();
|
||||
preserve_resource_fields(
|
||||
&templates,
|
||||
&mut result["resourceTemplates"],
|
||||
&[
|
||||
"uriTemplate",
|
||||
"name",
|
||||
"title",
|
||||
"description",
|
||||
"mimeType",
|
||||
"_meta",
|
||||
],
|
||||
);
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// The era-neutral `prompts/list` result shape (Story 3.14). Same pagination wire keys as
|
||||
/// `resources/list`; `nextCursor` is absent on the last page.
|
||||
pub(super) fn prompts_list_result(prompts: Vec<Value>, next_cursor: Option<String>) -> Value {
|
||||
let mut result = json!({ "prompts": prompts });
|
||||
if let Some(cursor) = next_cursor {
|
||||
result["nextCursor"] = Value::String(cursor);
|
||||
// Pinned SDK serde drops unknown fields and optional nulls, including Crank template parameters.
|
||||
// Treat annotations/icons as opaque too: their nested extensions are not represented by the SDK.
|
||||
fn preserve_resource_fields(raw: &[Value], serialized: &mut Value, sdk_fields: &[&str]) {
|
||||
for (raw, serialized) in raw
|
||||
.iter()
|
||||
.zip(serialized.as_array_mut().expect("SDK array"))
|
||||
{
|
||||
let serialized = serialized.as_object_mut().expect("SDK object");
|
||||
for (key, value) in raw.as_object().expect("validated resource object") {
|
||||
if !sdk_fields.contains(&key.as_str()) || value.is_null() {
|
||||
serialized.insert(key.clone(), value.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// The era-neutral `prompts/get` result shape: the rendered `messages[]` and the description of the
|
||||
/// exact bound Published Prompt Version it came from.
|
||||
pub(super) fn prompt_get_result(description: Option<String>, messages: Vec<Value>) -> Value {
|
||||
let mut result = json!({ "messages": messages });
|
||||
if let Some(description) = description {
|
||||
result["description"] = Value::String(description);
|
||||
/// SDK pagination with lossless Crank argument schemas/defaults and optional nulls.
|
||||
pub(super) fn prompts_list_result(
|
||||
prompts: Vec<Value>,
|
||||
next_cursor: Option<String>,
|
||||
) -> Result<Value, serde_json::Error> {
|
||||
let result = rmcp::model::ListPromptsResult {
|
||||
prompts: prompts
|
||||
.iter()
|
||||
.cloned()
|
||||
.map(serde_json::from_value)
|
||||
.collect::<Result<Vec<rmcp::model::Prompt>, _>>()?,
|
||||
next_cursor,
|
||||
result_type: None,
|
||||
ttl_ms: None,
|
||||
cache_scope: None,
|
||||
meta: None,
|
||||
};
|
||||
let mut result = serde_json::to_value(result)?;
|
||||
preserve_resource_fields(
|
||||
&prompts,
|
||||
&mut result["prompts"],
|
||||
&["name", "title", "description", "arguments", "_meta"],
|
||||
);
|
||||
for (raw, serialized) in prompts
|
||||
.iter()
|
||||
.zip(result["prompts"].as_array_mut().expect("SDK prompts"))
|
||||
{
|
||||
if let Some(arguments) = raw["arguments"].as_array() {
|
||||
preserve_resource_fields(
|
||||
arguments,
|
||||
&mut serialized["arguments"],
|
||||
&["name", "title", "description", "required"],
|
||||
);
|
||||
}
|
||||
}
|
||||
result
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_prompts_list_result_serialized();
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// Preserve Crank's system role, which the pinned SDK's user/assistant Role cannot express.
|
||||
pub(super) fn prompt_get_result(
|
||||
description: Option<String>,
|
||||
messages: Vec<Value>,
|
||||
) -> Result<Value, serde_json::Error> {
|
||||
let sdk_messages = messages
|
||||
.iter()
|
||||
.cloned()
|
||||
.map(|mut message| {
|
||||
if message["role"] == "system" {
|
||||
message["role"] = json!("user");
|
||||
}
|
||||
serde_json::from_value::<rmcp::model::PromptMessage>(message)
|
||||
})
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
let mut result = rmcp::model::GetPromptResult::new(sdk_messages);
|
||||
result.description = description;
|
||||
// Era-specific resultType/cache projection remains at the existing dispatch boundary.
|
||||
result.result_type = None;
|
||||
let mut result = serde_json::to_value(result)?;
|
||||
preserve_resource_fields(&messages, &mut result["messages"], &["role", "content"]);
|
||||
for (raw, serialized) in messages
|
||||
.iter()
|
||||
.zip(result["messages"].as_array_mut().expect("SDK messages"))
|
||||
{
|
||||
if raw["role"] == "system" {
|
||||
serialized["role"] = raw["role"].clone();
|
||||
}
|
||||
// Content extensions/optional nulls are opaque to the pinned SDK.
|
||||
let content = serialized["content"].as_object_mut().expect("SDK content");
|
||||
for (key, value) in raw["content"].as_object().expect("validated content") {
|
||||
if !content.contains_key(key)
|
||||
|| value.is_null()
|
||||
|| matches!(key.as_str(), "annotations" | "resource")
|
||||
{
|
||||
content.insert(key.clone(), value.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_prompts_get_result_serialized();
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// The era-neutral `completion/complete` result shape (Story 3.17): the bounded `values[]`, the
|
||||
@@ -158,14 +331,18 @@ pub(super) fn completion_result(
|
||||
total: Option<usize>,
|
||||
has_more: bool,
|
||||
) -> Value {
|
||||
let mut completion = json!({ "values": values });
|
||||
if let Some(total) = total {
|
||||
completion["total"] = json!(total);
|
||||
}
|
||||
if has_more {
|
||||
completion["hasMore"] = json!(true);
|
||||
}
|
||||
json!({ "completion": completion })
|
||||
let mut completion = rmcp::model::CompletionInfo::default();
|
||||
completion.values = values;
|
||||
// The domain scans at most 1024 candidates, so its exact count fits the SDK's u32.
|
||||
completion.total = total.map(|total| u32::try_from(total).expect("bounded completion count"));
|
||||
completion.has_more = has_more.then_some(true);
|
||||
let mut result = rmcp::model::CompleteResult::new(completion);
|
||||
// Keep the shared result era-neutral; the existing caller projects modern resultType.
|
||||
result.result_type = None;
|
||||
let result = serde_json::to_value(result).expect("SDK completion contains strings and counts");
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_completion_result_serialized();
|
||||
result
|
||||
}
|
||||
|
||||
/// The structured `prompts/get` argument rejection (AT-3.14-02): a `-32602` error whose `data`
|
||||
@@ -310,3 +487,195 @@ pub(super) fn internal_jsonrpc_error(message: &Value, _error: impl std::fmt::Dis
|
||||
None,
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod sdk_result_tests {
|
||||
use super::*;
|
||||
use crate::jsonrpc::{LEGACY_PROTOCOL_VERSION, MODERN_PROTOCOL_VERSION};
|
||||
|
||||
#[test]
|
||||
fn prompts_sdk_projection_preserves_typed_extensions_and_system_content() {
|
||||
let prompt = json!({"name":"p", "description":null, "icons":null,
|
||||
"x-prompt":{}, "arguments":[{"name":"count", "description":null,
|
||||
"required":false, "schema":{"type":"integer"}, "default":7}]});
|
||||
for cursor in [None, Some(String::new()), Some("opaque".to_owned())] {
|
||||
let result = prompts_list_result(vec![prompt.clone()], cursor.clone()).unwrap();
|
||||
assert_eq!(result["prompts"], json!([prompt]));
|
||||
assert_eq!(result.get("nextCursor"), cursor.map(Value::String).as_ref());
|
||||
assert!(result.get("resultType").is_none());
|
||||
}
|
||||
let messages = vec![
|
||||
json!({"role":"system", "x-message":null,
|
||||
"content":{"type":"text", "text":"\0é\n", "annotations":null, "x-content":[]}}),
|
||||
json!({"role":"assistant", "content":{"type":"text", "text":""}}),
|
||||
];
|
||||
assert_eq!(
|
||||
prompt_get_result(None, messages.clone()).unwrap(),
|
||||
json!({"messages":messages})
|
||||
);
|
||||
assert_eq!(
|
||||
prompts_list_result(vec![], None).unwrap(),
|
||||
json!({"prompts":[]})
|
||||
);
|
||||
assert_eq!(
|
||||
prompt_get_result(Some(String::new()), vec![]).unwrap(),
|
||||
json!({"description":"", "messages":[]})
|
||||
);
|
||||
assert!(prompts_list_result(vec![json!({"name":42})], None).is_err());
|
||||
assert!(
|
||||
prompt_get_result(
|
||||
None,
|
||||
vec![json!({"role":"invalid", "content":{"type":"text", "text":"secret"}})]
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resources_sdk_projection_is_lossless_for_templates_contents_and_catalog() {
|
||||
for version in [LEGACY_PROTOCOL_VERSION, MODERN_PROTOCOL_VERSION] {
|
||||
for optional in [Value::Null, json!({}), json!({"x-extension":[null,{}]})] {
|
||||
let raw = json!({"uri":"crank://r","name":"r","description":null,
|
||||
"mimeType":"text/plain","_meta":optional,"x-resource":[],
|
||||
"annotations":{"x-nested":null},"icons":[{"src":"icon","x-icon":{}}]});
|
||||
for cursor in [None, Some(String::new()), Some("opaque".to_owned())] {
|
||||
let list =
|
||||
resources_list_result(vec![raw.clone()], cursor.clone(), version).unwrap();
|
||||
assert_eq!(list["resources"], json!([raw]));
|
||||
assert_eq!(
|
||||
list.get("nextCursor"),
|
||||
cursor.as_ref().map(|s| json!(s)).as_ref()
|
||||
);
|
||||
assert_eq!(
|
||||
list.get("resultType").is_some(),
|
||||
version == MODERN_PROTOCOL_VERSION
|
||||
);
|
||||
assert_eq!(
|
||||
list.get("ttlMs").is_some(),
|
||||
version == MODERN_PROTOCOL_VERSION
|
||||
);
|
||||
assert_eq!(
|
||||
list.get("cacheScope").is_some(),
|
||||
version == MODERN_PROTOCOL_VERSION
|
||||
);
|
||||
assert!(list.get("_meta").is_none());
|
||||
let template = json!({"uriTemplate":"crank://r/{id}","name":"r",
|
||||
"description":null,"mimeType":null,"_meta":optional,
|
||||
"parameters":[{"name":"id","required":true,"opaque":null}],
|
||||
"annotations":{"x-nested":[]},"icons":null});
|
||||
let list = resource_templates_list_result(
|
||||
vec![template.clone()],
|
||||
cursor.clone(),
|
||||
version,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(list["resourceTemplates"], json!([template]));
|
||||
assert_eq!(
|
||||
list.get("nextCursor"),
|
||||
cursor.as_ref().map(|s| json!(s)).as_ref()
|
||||
);
|
||||
}
|
||||
let contents = json!([
|
||||
{"uri":"crank://r","mimeType":null,"text":"\0é\n","_meta":optional,"x-content":[]},
|
||||
{"uri":"crank://b","mimeType":"application/octet-stream","blob":"AP8=","_meta":null}
|
||||
]);
|
||||
assert_eq!(
|
||||
resource_read_result(contents.clone(), version).unwrap()["contents"],
|
||||
contents
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
resources_list_result(vec![], None, version).unwrap()["resources"],
|
||||
json!([])
|
||||
);
|
||||
assert_eq!(
|
||||
resource_templates_list_result(vec![], None, version).unwrap()["resourceTemplates"],
|
||||
json!([])
|
||||
);
|
||||
assert_eq!(
|
||||
resource_read_result(json!([]), version).unwrap()["contents"],
|
||||
json!([])
|
||||
);
|
||||
assert!(resources_list_result(vec![json!({"uri":42})], None, version).is_err());
|
||||
assert!(
|
||||
resource_templates_list_result(vec![json!({"name":"r"})], None, version).is_err()
|
||||
);
|
||||
assert!(resource_read_result(json!([{"uri":"r"}]), version).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn catalog_projection_preserves_extensions_null_and_empty() {
|
||||
let descriptor = json!({
|
||||
"name":"tool", "title":"", "description":null,
|
||||
"inputSchema":{"type":"object", "x-schema":{"nested":null}},
|
||||
"outputSchema":{"type":"object", "x-output":[]},
|
||||
"_meta":{"custom":{"empty":{}}}, "x-tool":{"nested":[]},
|
||||
"annotations":{"readOnlyHint":true,"x-annotation":{"nested":null}},
|
||||
"icons":[{"src":"https://example.test/icon", "x-icon":{"nested":[]}}]
|
||||
});
|
||||
for version in [LEGACY_PROTOCOL_VERSION, MODERN_PROTOCOL_VERSION] {
|
||||
for raw in [
|
||||
descriptor.clone(),
|
||||
json!({"name":"tool","inputSchema":{},
|
||||
"title":null,"description":"","outputSchema":null,"_meta":null,
|
||||
"annotations":null,"icons":null}),
|
||||
json!({"name":"tool","inputSchema":{},
|
||||
"annotations":{},"icons":[]}),
|
||||
] {
|
||||
for cursor in [None, Some(String::new()), Some("next".to_owned())] {
|
||||
let value =
|
||||
tools_list_result(vec![raw.clone()], cursor.clone(), version).unwrap();
|
||||
assert_eq!(value["tools"], json!([raw]));
|
||||
assert_eq!(
|
||||
value.get("nextCursor"),
|
||||
cursor.as_ref().map(|s| Value::String(s.clone())).as_ref()
|
||||
);
|
||||
assert_eq!(
|
||||
value.get("resultType").is_some(),
|
||||
version == MODERN_PROTOCOL_VERSION
|
||||
);
|
||||
assert_eq!(
|
||||
value.get("ttlMs").is_some(),
|
||||
version == MODERN_PROTOCOL_VERSION
|
||||
);
|
||||
assert_eq!(
|
||||
value.get("cacheScope").is_some(),
|
||||
version == MODERN_PROTOCOL_VERSION
|
||||
);
|
||||
}
|
||||
}
|
||||
assert_eq!(
|
||||
tools_list_result(vec![], None, version).unwrap()["tools"],
|
||||
json!([])
|
||||
);
|
||||
assert!(tools_list_result(vec![json!({"name":42})], None, version).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn null_success_and_rpc_failures_keep_their_distinct_shapes() {
|
||||
for version in [LEGACY_PROTOCOL_VERSION, MODERN_PROTOCOL_VERSION] {
|
||||
let message = json!({"id":9007199254740993_u64});
|
||||
let payload = success_tool_payload(&message, version, Value::Null);
|
||||
assert_eq!(payload["id"], message["id"]);
|
||||
assert_eq!(
|
||||
payload["result"]["content"],
|
||||
json!([{"type":"text","text":"null"}])
|
||||
);
|
||||
assert_eq!(
|
||||
payload["result"].get("structuredContent"),
|
||||
Some(&Value::Null)
|
||||
);
|
||||
assert_eq!(payload["result"]["isError"], false);
|
||||
let correlation = CorrelationContext::generate();
|
||||
let internal = tool_command_payload(
|
||||
&message,
|
||||
version,
|
||||
&correlation,
|
||||
ToolsOutcome::Call(ToolCallOutcome::InternalFailure),
|
||||
);
|
||||
assert!(matches!(internal, ToolCommandPayload::Internal(_)));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
//! Runtime SDK dispatch; admission, lifecycle and response projection stay with the caller.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use rmcp::model::{CallToolRequestParams, PaginatedRequestParams, ReadResourceRequestParams};
|
||||
use serde_json::Value;
|
||||
|
||||
use super::{AppState, lifecycle::ToolCallLifecycle};
|
||||
use crate::protocol::{
|
||||
ServiceContext, ToolCallCommand, ToolCallOutcome, ToolsCommand, ToolsListCommand, ToolsOutcome,
|
||||
};
|
||||
|
||||
// Crank extensions are not SDK fields and must survive the typed request boundary unchanged.
|
||||
enum SdkToolsCommand {
|
||||
List {
|
||||
params: PaginatedRequestParams,
|
||||
limit: Option<usize>,
|
||||
},
|
||||
Call {
|
||||
params: CallToolRequestParams,
|
||||
confirmation_token: Option<String>,
|
||||
},
|
||||
}
|
||||
|
||||
pub(super) async fn handle_tools_command(
|
||||
state: &Arc<AppState>,
|
||||
context: ServiceContext<'_>,
|
||||
command: ToolsCommand,
|
||||
lifecycle: Option<ToolCallLifecycle>,
|
||||
) -> ToolsOutcome {
|
||||
let request = match command {
|
||||
ToolsCommand::List(list) => SdkToolsCommand::List {
|
||||
params: PaginatedRequestParams::default().with_cursor(list.cursor),
|
||||
limit: list.limit,
|
||||
},
|
||||
ToolsCommand::Call(call) => {
|
||||
let Value::Object(arguments) = call.arguments else {
|
||||
return ToolsOutcome::Call(ToolCallOutcome::InvalidParams(
|
||||
"tool arguments must be an object".to_owned(),
|
||||
));
|
||||
};
|
||||
SdkToolsCommand::Call {
|
||||
params: CallToolRequestParams::new(call.tool_name).with_arguments(arguments),
|
||||
confirmation_token: call.confirmation_token,
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_tools_dispatch_enter();
|
||||
|
||||
let command = match request {
|
||||
SdkToolsCommand::List { params, limit } => ToolsCommand::List(ToolsListCommand {
|
||||
cursor: params.cursor,
|
||||
limit,
|
||||
}),
|
||||
SdkToolsCommand::Call {
|
||||
params,
|
||||
confirmation_token,
|
||||
} => ToolsCommand::Call(ToolCallCommand {
|
||||
tool_name: params.name.into_owned(),
|
||||
arguments: Value::Object(params.arguments.unwrap_or_default()),
|
||||
confirmation_token,
|
||||
}),
|
||||
};
|
||||
crate::protocol::handle_tools_command(state, context, command, lifecycle).await
|
||||
}
|
||||
|
||||
pub(super) async fn handle_prompts_command(
|
||||
state: &Arc<AppState>,
|
||||
context: ServiceContext<'_>,
|
||||
revision: &str,
|
||||
command: crate::protocol::PromptsCommand,
|
||||
) -> crate::protocol::PromptsOutcome {
|
||||
use crate::protocol::{PromptGetCommand, PromptsCommand, PromptsListCommand};
|
||||
let command = match command {
|
||||
PromptsCommand::List(list) => {
|
||||
let params = PaginatedRequestParams::default().with_cursor(list.cursor);
|
||||
PromptsCommand::List(PromptsListCommand {
|
||||
cursor: params.cursor,
|
||||
limit: list.limit,
|
||||
})
|
||||
}
|
||||
PromptsCommand::Get(get) => {
|
||||
let mut params = rmcp::model::GetPromptRequestParams::new(get.name);
|
||||
params.arguments = get.arguments;
|
||||
PromptsCommand::Get(PromptGetCommand {
|
||||
name: params.name,
|
||||
arguments: params.arguments,
|
||||
})
|
||||
}
|
||||
};
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_prompts_dispatch_enter();
|
||||
crate::protocol::handle_prompts_command(state, context, revision, command).await
|
||||
}
|
||||
|
||||
pub(super) async fn handle_resources_command(
|
||||
state: &Arc<AppState>,
|
||||
context: ServiceContext<'_>,
|
||||
revision: &str,
|
||||
command: crate::protocol::ResourcesCommand,
|
||||
) -> crate::protocol::ResourcesOutcome {
|
||||
use crate::protocol::{ResourceReadCommand, ResourcesCommand};
|
||||
let command = match command {
|
||||
ResourcesCommand::List(list) => ResourcesCommand::List(sdk_resource_page(list)),
|
||||
ResourcesCommand::Read(read) => {
|
||||
let params = ReadResourceRequestParams::new(read.uri);
|
||||
ResourcesCommand::Read(ResourceReadCommand { uri: params.uri })
|
||||
}
|
||||
};
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_resources_dispatch_enter();
|
||||
crate::protocol::handle_resources_command(state, context, revision, command).await
|
||||
}
|
||||
|
||||
pub(super) async fn list_resource_templates(
|
||||
state: &Arc<AppState>,
|
||||
workspace_slug: &str,
|
||||
agent_slug: &str,
|
||||
revision: &str,
|
||||
command: crate::protocol::ResourcesListCommand,
|
||||
) -> Result<(Vec<Value>, Option<String>), crate::protocol::ResourceTemplatesListError> {
|
||||
let command = sdk_resource_page(command);
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_resources_dispatch_enter();
|
||||
crate::protocol::list_resource_templates(state, workspace_slug, agent_slug, revision, command)
|
||||
.await
|
||||
}
|
||||
|
||||
pub(super) async fn handle_completion_command(
|
||||
state: &Arc<AppState>,
|
||||
context: ServiceContext<'_>,
|
||||
revision: &str,
|
||||
command: crate::protocol::CompletionCommand,
|
||||
) -> crate::protocol::CompletionOutcome {
|
||||
use crate::protocol::{
|
||||
CompletionArgument, CompletionCommand, CompletionOutcome, CompletionReference,
|
||||
};
|
||||
use rmcp::model::{ArgumentInfo, CompleteRequestParams, Reference};
|
||||
|
||||
let reference = match command.reference {
|
||||
CompletionReference::Prompt { name } => Reference::for_prompt(name),
|
||||
CompletionReference::Resource { uri } => Reference::for_resource(uri),
|
||||
};
|
||||
let params = CompleteRequestParams::new(
|
||||
reference,
|
||||
ArgumentInfo::new(command.argument.name, command.argument.value),
|
||||
);
|
||||
// SDK context only supports strings; retain arbitrary JSON unchanged for domain validation.
|
||||
let context_arguments = command.context;
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_completion_dispatch_enter();
|
||||
let reference = match params.r#ref {
|
||||
Reference::Prompt(reference) => CompletionReference::Prompt {
|
||||
name: reference.name,
|
||||
},
|
||||
Reference::Resource(reference) => CompletionReference::Resource { uri: reference.uri },
|
||||
_ => return CompletionOutcome::InvalidParams("invalid completion/complete parameters"),
|
||||
};
|
||||
let command = CompletionCommand {
|
||||
reference,
|
||||
argument: CompletionArgument {
|
||||
name: params.argument.name,
|
||||
value: params.argument.value,
|
||||
},
|
||||
context: context_arguments,
|
||||
};
|
||||
crate::protocol::handle_completion_command(state, context, revision, command).await
|
||||
}
|
||||
|
||||
fn sdk_resource_page(
|
||||
list: crate::protocol::ResourcesListCommand,
|
||||
) -> crate::protocol::ResourcesListCommand {
|
||||
let params = PaginatedRequestParams::default().with_cursor(list.cursor);
|
||||
// Crank's page limit is not an SDK field; retain its existing validation and clamping.
|
||||
crate::protocol::ResourcesListCommand {
|
||||
cursor: params.cursor,
|
||||
limit: list.limit,
|
||||
}
|
||||
}
|
||||
@@ -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,242 @@
|
||||
//! 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, ListToolsResult, PaginatedRequestParams};
|
||||
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 } => {
|
||||
super::response::sdk_tools_list_result(&tools, next_cursor)
|
||||
.map_err(|_| McpError::internal_error("invalid tool catalog entry", None))
|
||||
}
|
||||
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) => {
|
||||
Ok(super::response::sdk_success_tool_result(value).into())
|
||||
}
|
||||
crate::protocol::ToolCallOutcome::ApprovalUnavailable(error) => {
|
||||
Ok(super::response::sdk_error_tool_result(
|
||||
crate::tool_error::control_tool_error_contract(
|
||||
error,
|
||||
identity.correlation.request_id().as_str(),
|
||||
identity.correlation.trace_id().as_str(),
|
||||
identity.locale,
|
||||
),
|
||||
)
|
||||
.into())
|
||||
}
|
||||
crate::protocol::ToolCallOutcome::InvalidParams(message) => {
|
||||
Err(McpError::invalid_params(message, None))
|
||||
}
|
||||
crate::protocol::ToolCallOutcome::Error(contract) => {
|
||||
Ok(super::response::sdk_error_tool_result(contract).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(),
|
||||
|
||||
@@ -36,7 +36,10 @@ pub(crate) use command::{
|
||||
ContinuationSupport, ServiceContext, ToolCallCommand, ToolCallOutcome, ToolsCommand,
|
||||
ToolsListCommand, ToolsOutcome, handle_tools_command,
|
||||
};
|
||||
pub(crate) use completion::{CompletionCommand, CompletionOutcome, handle_completion_command};
|
||||
pub(crate) use completion::{
|
||||
CompletionArgument, CompletionCommand, CompletionOutcome, CompletionReference,
|
||||
handle_completion_command,
|
||||
};
|
||||
pub(crate) use logging::{
|
||||
CarriedScope, EVENT_FAILED, EVENT_LEVEL_APPLIED, EVENT_REJECTED, EVENT_SERVED, INVALID_LEVEL,
|
||||
LogLevel, LogLevelStore, LoggingOutcome, SetLevelCommand, carry_scope, handle_logging_command,
|
||||
|
||||
@@ -0,0 +1,345 @@
|
||||
//! #107 Completion: real build_app HTTP wire controls and a separate SDK-path oracle.
|
||||
use super::{CounterSet, observe, support::*};
|
||||
use axum::{body::Body, response::Response};
|
||||
use futures_util::{StreamExt, stream};
|
||||
use serde_json::{Value, json};
|
||||
use std::{sync::Arc, time::Duration};
|
||||
#[path = "rmcp_completion_test_support.rs"]
|
||||
mod fixtures;
|
||||
use fixtures::{BOUNDED_URI, Endpoint, LARGE_URI, URI};
|
||||
|
||||
fn observe_body(response: Response, counters: Arc<CounterSet>) -> Response {
|
||||
let (parts, body) = response.into_parts();
|
||||
let body = stream::unfold(
|
||||
(body.into_data_stream(), counters),
|
||||
|(mut body, c)| async move {
|
||||
observe(c.clone(), body.next())
|
||||
.await
|
||||
.map(|chunk| (chunk, (body, c)))
|
||||
},
|
||||
);
|
||||
Response::from_parts(parts, Body::from_stream(body))
|
||||
}
|
||||
fn counts(c: &CounterSet) -> [usize; 2] {
|
||||
[c.sdk_completion_dispatch(), c.sdk_completion_result()]
|
||||
}
|
||||
fn params(reference: Value, name: &str, value: &str) -> Value {
|
||||
json!({"ref":reference,"argument":{"name":name,"value":value}})
|
||||
}
|
||||
fn prompt(name: &str) -> Value {
|
||||
json!({"type":"ref/prompt","name":name})
|
||||
}
|
||||
fn resource(uri: &str) -> Value {
|
||||
json!({"type":"ref/resource","uri":uri})
|
||||
}
|
||||
fn request(revision: &str, mut params: Value) -> Value {
|
||||
if revision == MODERN_REVISION {
|
||||
params["_meta"] = modern_meta();
|
||||
}
|
||||
json!({"jsonrpc":"2.0","id":9007199254740993_u64,"method":"completion/complete","params":params})
|
||||
}
|
||||
async fn wire(response: reqwest::Response, sse: bool) -> Value {
|
||||
assert_eq!(response.status(), 200);
|
||||
assert_eq!(response.headers()["x-request-id"], "sdk-completion-wire");
|
||||
assert_eq!(
|
||||
response.headers()["x-trace-id"],
|
||||
"11111111111111111111111111111111"
|
||||
);
|
||||
let content_type = response.headers()["content-type"]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.to_owned();
|
||||
let text = tokio::time::timeout(Duration::from_secs(5), response.text())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let body: Value = if sse {
|
||||
assert!(
|
||||
content_type.starts_with("text/event-stream"),
|
||||
"{content_type}: {text}"
|
||||
);
|
||||
let frames: Vec<Value> = text
|
||||
.lines()
|
||||
.filter_map(|line| {
|
||||
line.strip_prefix("data:")
|
||||
.map(|s| serde_json::from_str(s.trim()).unwrap())
|
||||
})
|
||||
.collect();
|
||||
let terminal: Vec<_> = frames
|
||||
.iter()
|
||||
.filter(|f| f.get("id") == Some(&json!(9007199254740993_u64)))
|
||||
.collect();
|
||||
assert_eq!(terminal.len(), 1, "{frames:?}");
|
||||
assert_eq!(frames.last(), Some(terminal[0]), "terminal must be last");
|
||||
terminal[0].clone()
|
||||
} else {
|
||||
assert!(
|
||||
content_type.starts_with("application/json"),
|
||||
"{content_type}: {text}"
|
||||
);
|
||||
serde_json::from_str(&text).unwrap()
|
||||
};
|
||||
assert_eq!(body["jsonrpc"], "2.0");
|
||||
assert_eq!(body["id"], json!(9007199254740993_u64));
|
||||
body
|
||||
}
|
||||
async fn success(
|
||||
h: &Endpoint,
|
||||
revision: &str,
|
||||
session: Option<&str>,
|
||||
p: Value,
|
||||
sse: bool,
|
||||
) -> (Value, [usize; 2]) {
|
||||
let before = counts(&h.counters);
|
||||
let body = wire(
|
||||
h.post(revision, session, &request(revision, p), sse).await,
|
||||
sse,
|
||||
)
|
||||
.await;
|
||||
assert!(body.get("error").is_none(), "{body}");
|
||||
let result = &body["result"];
|
||||
if revision == MODERN_REVISION {
|
||||
assert_eq!(result["resultType"], "complete", "{body}");
|
||||
} else {
|
||||
assert!(result.get("resultType").is_none(), "{body}");
|
||||
}
|
||||
for key in ["ttlMs", "cacheScope", "_meta"] {
|
||||
assert!(result.get(key).is_none(), "{body}");
|
||||
}
|
||||
let after = counts(&h.counters);
|
||||
(
|
||||
result["completion"].clone(),
|
||||
std::array::from_fn(|i| after[i] - before[i]),
|
||||
)
|
||||
}
|
||||
async fn control(revision: &str) -> Vec<[usize; 2]> {
|
||||
let h = Endpoint::started().await;
|
||||
let session = h.session(revision).await;
|
||||
let session = session.as_deref();
|
||||
let modes: &[bool] = if revision == MODERN_REVISION {
|
||||
&[false, true]
|
||||
} else {
|
||||
&[false]
|
||||
};
|
||||
let mut deltas = Vec::new();
|
||||
for &sse in modes {
|
||||
for (p, expected) in [
|
||||
(
|
||||
params(prompt("greeting"), "tone", ""),
|
||||
json!({"values":["warm","dry"],"total":2}),
|
||||
),
|
||||
(
|
||||
params(prompt("archived-prompt"), "tone", "W"),
|
||||
json!({"values":["warm"],"total":1}),
|
||||
),
|
||||
(
|
||||
params(prompt("greeting"), "name", "A"),
|
||||
json!({"values":[],"total":0}),
|
||||
),
|
||||
(
|
||||
params(resource(URI), "region", ""),
|
||||
json!({"values":["eu","us","apac"],"total":3}),
|
||||
),
|
||||
(
|
||||
params(resource(URI), "region", "A"),
|
||||
json!({"values":["apac"],"total":1}),
|
||||
),
|
||||
(
|
||||
params(resource(URI), "region", "zzz"),
|
||||
json!({"values":[],"total":0}),
|
||||
),
|
||||
] {
|
||||
let (completion, delta) = success(&h, revision, session, p, sse).await;
|
||||
assert_eq!(completion, expected);
|
||||
deltas.push(delta);
|
||||
}
|
||||
for (uri, total) in [(BOUNDED_URI, Some(150)), (LARGE_URI, None)] {
|
||||
let (completion, delta) = success(
|
||||
&h,
|
||||
revision,
|
||||
session,
|
||||
params(resource(uri), "region", "item"),
|
||||
sse,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
completion["values"],
|
||||
json!((0..100).map(|i| format!("item{i:04}")).collect::<Vec<_>>())
|
||||
);
|
||||
assert_eq!(completion["hasMore"], true);
|
||||
if let Some(total) = total {
|
||||
assert_eq!(completion["total"], total);
|
||||
} else {
|
||||
assert!(
|
||||
completion.get("total").is_none(),
|
||||
"partial scan: {completion}"
|
||||
);
|
||||
}
|
||||
deltas.push(delta);
|
||||
}
|
||||
let mut with_context = params(prompt("greeting"), "tone", "w");
|
||||
with_context["context"] = json!({"arguments":{"name":"Ada","tone":"dry"}});
|
||||
let (completion, delta) = success(&h, revision, session, with_context, sse).await;
|
||||
assert_eq!(completion, json!({"values":["warm"],"total":1}));
|
||||
deltas.push(delta);
|
||||
let mut unavailable = None;
|
||||
for p in [
|
||||
params(prompt("draft-prompt"), "tone", ""),
|
||||
params(prompt("unbound-prompt"), "tone", ""),
|
||||
params(prompt("other-agent-prompt"), "tone", ""),
|
||||
params(prompt("never-existed"), "tone", ""),
|
||||
params(prompt("changed-draft"), "tone", ""),
|
||||
params(prompt("greeting"), "unknown-argument", ""),
|
||||
params(resource("crank://foreign/{region}"), "region", ""),
|
||||
params(resource(URI), "unknown-parameter", ""),
|
||||
] {
|
||||
let body = wire(
|
||||
h.post(revision, session, &request(revision, p), sse).await,
|
||||
sse,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(body["error"]["code"], -32602, "{body}");
|
||||
assert_eq!(
|
||||
body["error"]["message"],
|
||||
"the completion reference is not available"
|
||||
);
|
||||
assert!(body.get("result").is_none());
|
||||
if let Some(ref previous) = unavailable {
|
||||
assert_eq!(&body, previous);
|
||||
}
|
||||
unavailable = Some(body);
|
||||
}
|
||||
let mut invalid = vec![
|
||||
json!({"argument":{"name":"tone","value":""}}),
|
||||
params(json!({"type":"ref/tool","name":"greeting"}), "tone", ""),
|
||||
params(prompt("greeting"), "tone", &"s".repeat(1025)),
|
||||
params(prompt("greeting"), &"n".repeat(129), ""),
|
||||
];
|
||||
// Preserve domain validation on arbitrary JSON, never drop or stringify context values for SDK.
|
||||
for value in [
|
||||
json!(7),
|
||||
json!(true),
|
||||
json!(null),
|
||||
json!(["eu"]),
|
||||
json!({"region":"eu"}),
|
||||
json!("s".repeat(1025)),
|
||||
] {
|
||||
let mut p = params(prompt("greeting"), "tone", "");
|
||||
p["context"] = json!({"arguments":{"secret-context":value}});
|
||||
invalid.push(p);
|
||||
}
|
||||
let mut p = params(prompt("greeting"), "tone", "");
|
||||
p["context"] = json!({"arguments":(0..33).map(|i| (format!("arg{i}"), json!("eu"))).collect::<serde_json::Map<_,_>>()});
|
||||
invalid.push(p);
|
||||
for p in invalid {
|
||||
let body = wire(
|
||||
h.post(revision, session, &request(revision, p), sse).await,
|
||||
sse,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(body["error"]["code"], -32602, "{body}");
|
||||
assert_eq!(
|
||||
body["error"]["message"],
|
||||
"invalid completion/complete parameters"
|
||||
);
|
||||
assert!(body.get("result").is_none());
|
||||
for leaked in ["secret-context", &"s".repeat(1025), &"n".repeat(129)] {
|
||||
assert!(!body.to_string().contains(leaked), "{body}");
|
||||
}
|
||||
}
|
||||
}
|
||||
h.registry
|
||||
.revoke_platform_api_key(
|
||||
&workspace_id(),
|
||||
&crank_core::PlatformApiKeyId::new("pk_dispatch_observer"),
|
||||
&time::OffsetDateTime::now_utc(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let before = h.counters.snapshot();
|
||||
let sdk_before = counts(&h.counters);
|
||||
let response = h
|
||||
.post(
|
||||
revision,
|
||||
session,
|
||||
&request(revision, params(prompt("greeting"), "tone", "")),
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(response.status(), 401);
|
||||
let _ = response.bytes().await.unwrap();
|
||||
assert_eq!(
|
||||
counts(&h.counters),
|
||||
sdk_before,
|
||||
"revoked key must not dispatch to SDK"
|
||||
);
|
||||
let after = h.counters.snapshot();
|
||||
assert_eq!(after.era_modern, before.era_modern);
|
||||
assert_eq!(after.era_legacy, before.era_legacy);
|
||||
assert_eq!(after.tools_service, before.tools_service);
|
||||
eprintln!(
|
||||
"existing GREEN Completion HTTP {revision}: Prompt+Resource refs, exact bound v1/archive, prefix/empty/bounded/truncated, JSON/context/errors/correlation/auth; SDK actual={deltas:?}, expected=[1,1] per success"
|
||||
);
|
||||
deltas
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_completion_wire_legacy() {
|
||||
control(LEGACY_REVISION).await;
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_completion_wire_modern() {
|
||||
control(MODERN_REVISION).await;
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_completion_sdk_legacy() {
|
||||
let deltas = control(LEGACY_REVISION).await;
|
||||
assert!(
|
||||
deltas.iter().all(|d| *d == [1, 1]),
|
||||
"SDK typed dispatch/result missing after successful HTTP: {deltas:?}"
|
||||
);
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_completion_sdk_modern() {
|
||||
let deltas = control(MODERN_REVISION).await;
|
||||
assert!(
|
||||
deltas.iter().all(|d| *d == [1, 1]),
|
||||
"SDK typed dispatch/result missing after successful HTTP: {deltas:?}"
|
||||
);
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_completion_observer_scope_control() {
|
||||
use super::{sdk_completion_dispatch_enter, sdk_completion_result_serialized};
|
||||
let a = Arc::new(CounterSet::default());
|
||||
let b = Arc::new(CounterSet::default());
|
||||
sdk_completion_dispatch_enter();
|
||||
sdk_completion_result_serialized();
|
||||
assert_eq!(counts(&a), [0; 2]);
|
||||
let snapshot = a.snapshot();
|
||||
tokio::join!(
|
||||
observe(a.clone(), async {
|
||||
sdk_completion_dispatch_enter();
|
||||
tokio::task::yield_now().await;
|
||||
sdk_completion_result_serialized();
|
||||
}),
|
||||
observe(b.clone(), async {
|
||||
sdk_completion_result_serialized();
|
||||
})
|
||||
);
|
||||
assert_eq!(counts(&a), [1, 1]);
|
||||
assert_eq!(counts(&b), [0, 1]);
|
||||
assert_eq!(a.snapshot(), snapshot);
|
||||
let body = Body::from_stream(stream::once(async {
|
||||
sdk_completion_result_serialized();
|
||||
Ok::<_, std::convert::Infallible>("data: terminal\n\n")
|
||||
}));
|
||||
let response = observe_body(Response::new(body), b.clone());
|
||||
assert_eq!(counts(&b), [0, 1], "body must be deferred");
|
||||
assert_eq!(
|
||||
&axum::body::to_bytes(response.into_body(), 100)
|
||||
.await
|
||||
.unwrap()[..],
|
||||
b"data: terminal\n\n"
|
||||
);
|
||||
assert_eq!(counts(&b), [0, 2]);
|
||||
assert_eq!(counts(&a), [1, 1]);
|
||||
}
|
||||
@@ -0,0 +1,445 @@
|
||||
//! Completion HTTP fixture using the existing observed HTTP app and disposable PostgreSQL.
|
||||
use super::*;
|
||||
use crank_core::prompt::{PromptDefinition, PromptSensitivity};
|
||||
use crank_core::{
|
||||
Agent, AgentStatus, AgentVersion, HttpMethod, RestTarget, Target, ToolSelectionPolicy,
|
||||
ids::PromptId,
|
||||
};
|
||||
use crank_registry::PostgresRegistry;
|
||||
use crank_registry::model::{
|
||||
AgentPromptBinding, ArchivePromptRequest, CreatePromptDraftRequest, PublishPromptRequest,
|
||||
SaveAgentCatalogConfigRequest, UpdatePromptDraftRequest,
|
||||
};
|
||||
use crank_registry::{CreateAgentRequest, PublishAgentRequest};
|
||||
use crank_runtime::{
|
||||
InMemoryCoordinationStateStore, RequestRateLimitConfig, RequestRateLimiter, SecretCrypto,
|
||||
};
|
||||
|
||||
pub(super) fn definition(name: &str, content: &str) -> PromptDefinition {
|
||||
PromptDefinition::parse(&json!({
|
||||
"name":name, "description":format!("Published {name}"),
|
||||
"arguments":[
|
||||
{"name":"name","schema":{"type":"string"},"required":true},
|
||||
{"name":"count","schema":{"type":"integer"},"required":false,"default":2},
|
||||
{"name":"enabled","schema":{"type":"boolean"},"required":false,"default":true},
|
||||
{"name":"tone","schema":{"type":"string","enum":["warm","dry"]},"required":false,"default":"warm"}
|
||||
],
|
||||
"messages":[{"role":"system","content":"Be brief."},{"role":"user","content":content}]
|
||||
})).unwrap()
|
||||
}
|
||||
|
||||
pub(super) struct Endpoint {
|
||||
pub registry: crank_registry::PostgresRegistry,
|
||||
pub counters: Arc<CounterSet>,
|
||||
pub key: String,
|
||||
pub url: String,
|
||||
server: tokio::task::JoinHandle<()>,
|
||||
}
|
||||
impl Drop for Endpoint {
|
||||
fn drop(&mut self) {
|
||||
self.server.abort();
|
||||
}
|
||||
}
|
||||
impl Endpoint {
|
||||
pub async fn started() -> Self {
|
||||
crank_test_support::postgres_schema_url_for_task("completion_owner", "t_3fa1ad63").await;
|
||||
let registry = test_registry().await;
|
||||
publish_region_operation(®istry, "completion_lookup").await;
|
||||
for (id, uri, size) in [
|
||||
("res_completion_small", URI, 3),
|
||||
("res_completion_large", LARGE_URI, 1025),
|
||||
("res_completion_bounded", BOUNDED_URI, 150),
|
||||
] {
|
||||
publish_template(®istry, &ResourceId::new(id), uri, size).await;
|
||||
}
|
||||
let mut archived_at = test_time();
|
||||
for (id, name, publish) in [
|
||||
("prm_a", "greeting", true),
|
||||
("prm_b", "archived-prompt", true),
|
||||
("prm_c", "unbound-prompt", true),
|
||||
("prm_d", "draft-prompt", false),
|
||||
("prm_e", "other-agent-prompt", true),
|
||||
] {
|
||||
let row = registry
|
||||
.create_prompt_draft(CreatePromptDraftRequest {
|
||||
workspace_id: workspace_id(),
|
||||
prompt_id: PromptId::new(id),
|
||||
sensitivity: PromptSensitivity::Internal,
|
||||
definition: definition(
|
||||
name,
|
||||
"Hello {{name}} count={{count}} enabled={{enabled}} tone={{tone}}",
|
||||
),
|
||||
created_at: time::OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
if publish {
|
||||
let row = registry
|
||||
.publish_prompt_draft(PublishPromptRequest {
|
||||
workspace_id: workspace_id(),
|
||||
prompt_id: PromptId::new(id),
|
||||
expected_updated_at: row.updated_at,
|
||||
published_at: time::OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
if id == "prm_b" {
|
||||
archived_at = row.updated_at;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (id, slug) in [
|
||||
(agent_id(), AGENT_SLUG),
|
||||
(
|
||||
crank_core::AgentId::new("agent_other_prompts"),
|
||||
"other-prompts",
|
||||
),
|
||||
] {
|
||||
registry
|
||||
.create_agent(CreateAgentRequest {
|
||||
agent: &Agent {
|
||||
id: id.clone(),
|
||||
workspace_id: workspace_id(),
|
||||
slug: slug.into(),
|
||||
display_name: "SDK Prompts".into(),
|
||||
description: String::new(),
|
||||
status: AgentStatus::Draft,
|
||||
current_draft_version: 1,
|
||||
latest_published_version: None,
|
||||
created_at: test_time(),
|
||||
updated_at: test_time(),
|
||||
published_at: None,
|
||||
},
|
||||
version: &AgentVersion {
|
||||
agent_id: id,
|
||||
version: 1,
|
||||
status: AgentStatus::Draft,
|
||||
instructions: json!({}),
|
||||
tool_selection_policy: ToolSelectionPolicy::default(),
|
||||
created_at: test_time(),
|
||||
},
|
||||
bindings: &[],
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
let other_agent = crank_core::AgentId::new("agent_other_prompts");
|
||||
registry
|
||||
.save_agent_catalog_config_editable_with_prompts(
|
||||
SaveAgentCatalogConfigRequest {
|
||||
workspace_id: &workspace_id(),
|
||||
agent_id: &other_agent,
|
||||
agent_version: 1,
|
||||
bindings: &[],
|
||||
tool_selection_policy: &ToolSelectionPolicy::default(),
|
||||
resource_bindings: &[],
|
||||
expected_state: None,
|
||||
},
|
||||
&[AgentPromptBinding {
|
||||
prompt_id: PromptId::new("prm_e"),
|
||||
prompt_version: 1,
|
||||
}],
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
registry
|
||||
.publish_agent(PublishAgentRequest {
|
||||
workspace_id: &workspace_id(),
|
||||
agent_id: &other_agent,
|
||||
version: 1,
|
||||
published_at: &test_time(),
|
||||
published_by: Some("alice"),
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
registry
|
||||
.save_agent_catalog_config_editable_with_prompts(
|
||||
SaveAgentCatalogConfigRequest {
|
||||
workspace_id: &workspace_id(),
|
||||
agent_id: &agent_id(),
|
||||
agent_version: 1,
|
||||
bindings: &[],
|
||||
tool_selection_policy: &ToolSelectionPolicy::default(),
|
||||
resource_bindings: &[
|
||||
AgentResourceBinding {
|
||||
resource_id: ResourceId::new("res_completion_small"),
|
||||
resource_version: 1,
|
||||
},
|
||||
AgentResourceBinding {
|
||||
resource_id: ResourceId::new("res_completion_large"),
|
||||
resource_version: 1,
|
||||
},
|
||||
AgentResourceBinding {
|
||||
resource_id: ResourceId::new("res_completion_bounded"),
|
||||
resource_version: 1,
|
||||
},
|
||||
],
|
||||
expected_state: None,
|
||||
},
|
||||
&[
|
||||
AgentPromptBinding {
|
||||
prompt_id: PromptId::new("prm_a"),
|
||||
prompt_version: 1,
|
||||
},
|
||||
AgentPromptBinding {
|
||||
prompt_id: PromptId::new("prm_b"),
|
||||
prompt_version: 1,
|
||||
},
|
||||
],
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
registry
|
||||
.publish_agent(PublishAgentRequest {
|
||||
workspace_id: &workspace_id(),
|
||||
agent_id: &agent_id(),
|
||||
version: 1,
|
||||
published_at: &test_time(),
|
||||
published_by: Some("alice"),
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
registry
|
||||
.archive_prompt_draft(ArchivePromptRequest {
|
||||
workspace_id: workspace_id(),
|
||||
prompt_id: PromptId::new("prm_b"),
|
||||
expected_updated_at: archived_at,
|
||||
archived_at: time::OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
// A mutable v2 draft must not change the bound v1 rendering or discovery metadata.
|
||||
let draft = registry
|
||||
.get_prompt_draft(&workspace_id(), &PromptId::new("prm_a"))
|
||||
.await
|
||||
.unwrap();
|
||||
registry
|
||||
.update_prompt_draft(UpdatePromptDraftRequest {
|
||||
workspace_id: workspace_id(),
|
||||
prompt_id: PromptId::new("prm_a"),
|
||||
sensitivity: PromptSensitivity::Internal,
|
||||
definition: definition("changed-draft", "Changed {{name}}"),
|
||||
expected_updated_at: draft.updated_at,
|
||||
updated_at: time::OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let key = create_api_key(®istry).await;
|
||||
let counters = Arc::new(CounterSet::default());
|
||||
let app = crate::build_app(
|
||||
registry.clone(),
|
||||
Duration::ZERO,
|
||||
None,
|
||||
SecretCrypto::new("test-master-key-00000000000000000000000000000000").unwrap(),
|
||||
crank_runtime::community_with_outbound_policy(
|
||||
crank_runtime::OutboundHttpPolicy::allowing_hosts(["127.0.0.1"]),
|
||||
)
|
||||
.build(),
|
||||
RequestRateLimiter::new(RequestRateLimitConfig::new(10_000, 10_000).unwrap()),
|
||||
Arc::new(InMemoryCoordinationStateStore::default()),
|
||||
Arc::new(crate::session::InMemorySessionStore::default()),
|
||||
Arc::new(crate::auth::CommunityMachineCredentialVerifier),
|
||||
);
|
||||
let app = observe_requests(app, counters.clone(), None).layer(axum::middleware::from_fn({
|
||||
let counters = counters.clone();
|
||||
move |request: axum::extract::Request, next: axum::middleware::Next| {
|
||||
let counters = counters.clone();
|
||||
async move { observe_body(next.run(request).await, counters) }
|
||||
}
|
||||
}));
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let url = format!(
|
||||
"http://{}/v1/{WORKSPACE_SLUG}/{AGENT_SLUG}",
|
||||
listener.local_addr().unwrap()
|
||||
);
|
||||
let server = tokio::spawn(async move {
|
||||
axum::serve(listener, app).await.unwrap();
|
||||
});
|
||||
Self {
|
||||
registry,
|
||||
counters,
|
||||
key,
|
||||
url,
|
||||
server,
|
||||
}
|
||||
}
|
||||
pub async fn post(
|
||||
&self,
|
||||
revision: &str,
|
||||
session: Option<&str>,
|
||||
body: &Value,
|
||||
sse: bool,
|
||||
) -> reqwest::Response {
|
||||
let mut request = reqwest::Client::new()
|
||||
.post(&self.url)
|
||||
.bearer_auth(&self.key)
|
||||
.header(
|
||||
"Accept",
|
||||
if sse {
|
||||
"text/event-stream, application/json"
|
||||
} else {
|
||||
"application/json"
|
||||
},
|
||||
)
|
||||
.header("x-request-id", "sdk-completion-wire")
|
||||
.header(
|
||||
"traceparent",
|
||||
"00-11111111111111111111111111111111-2222222222222222-01",
|
||||
)
|
||||
.header("MCP-Protocol-Version", revision);
|
||||
if let Some(session) = session {
|
||||
request = request.header("MCP-Session-Id", session);
|
||||
}
|
||||
if revision == MODERN_REVISION {
|
||||
request = request.header("Mcp-Method", body["method"].as_str().unwrap());
|
||||
}
|
||||
request.json(body).send().await.unwrap()
|
||||
}
|
||||
pub async fn session(&self, revision: &str) -> Option<String> {
|
||||
if revision == MODERN_REVISION {
|
||||
return None;
|
||||
}
|
||||
let response = self
|
||||
.post(revision, None, &legacy_initialize(1), false)
|
||||
.await;
|
||||
assert_eq!(response.status(), 200);
|
||||
let session = response.headers()["MCP-Session-Id"]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.to_owned();
|
||||
assert_eq!(
|
||||
json_body(response).await["result"]["protocolVersion"],
|
||||
revision
|
||||
);
|
||||
assert_eq!(
|
||||
self.post(revision, Some(&session), &initialized_notification(), false)
|
||||
.await
|
||||
.status(),
|
||||
202
|
||||
);
|
||||
Some(session)
|
||||
}
|
||||
}
|
||||
|
||||
use crank_core::{ids::ResourceId, resource::TemplateSource};
|
||||
use crank_mapping::{MappingRule, MappingSet};
|
||||
use crank_registry::model::{
|
||||
CreateResourceTemplateDraftRequest, PublishResourceTemplateVersionRequest,
|
||||
};
|
||||
use crank_registry::{AgentResourceBinding, PublishRequest};
|
||||
use sha2::{Digest, Sha256};
|
||||
pub(super) const URI: &str = "crank://completion-orders/{region}";
|
||||
pub(super) const LARGE_URI: &str = "crank://completion-large/{region}";
|
||||
pub(super) const BOUNDED_URI: &str = "crank://completion-bounded/{region}";
|
||||
async fn publish_region_operation(registry: &PostgresRegistry, name: &str) {
|
||||
let mut operation = test_operation("http://127.0.0.1:9");
|
||||
operation.id = crank_core::OperationId::new(format!("op_{name}"));
|
||||
operation.name = name.to_owned();
|
||||
operation.display_name = "Region lookup".to_owned();
|
||||
operation.target = Target::Rest(RestTarget {
|
||||
base_url: "http://127.0.0.1:9".to_owned(),
|
||||
method: HttpMethod::Get,
|
||||
path_template: "/regions/{region}".to_owned(),
|
||||
static_headers: Default::default(),
|
||||
request_contract: None,
|
||||
response_contract: Vec::new(),
|
||||
multipart_field_mime_types: Default::default(),
|
||||
});
|
||||
operation.input_schema = object_schema("region");
|
||||
operation
|
||||
.input_schema
|
||||
.fields
|
||||
.get_mut("region")
|
||||
.unwrap()
|
||||
.enum_values = vec!["eu".to_owned(), "us".to_owned(), "apac".to_owned()];
|
||||
operation.input_mapping = MappingSet {
|
||||
rules: vec![MappingRule {
|
||||
source: "$.mcp.region".to_owned(),
|
||||
target: "$.request.path.region".to_owned(),
|
||||
required: true,
|
||||
default_value: None,
|
||||
transform: None,
|
||||
condition: None,
|
||||
notes: None,
|
||||
}],
|
||||
};
|
||||
registry
|
||||
.create_operation(&workspace_id(), &operation, Some("alice"))
|
||||
.await
|
||||
.expect("the Read Operation is created through the registry API");
|
||||
registry
|
||||
.publish_operation(PublishRequest {
|
||||
workspace_id: &workspace_id(),
|
||||
operation_id: &operation.id,
|
||||
version: 1,
|
||||
published_at: &time::OffsetDateTime::now_utc(),
|
||||
published_by: Some("alice"),
|
||||
})
|
||||
.await
|
||||
.expect("the Read Operation exact version publishes");
|
||||
}
|
||||
|
||||
/// One published Resource template with an enumerated `region` parameter.
|
||||
async fn publish_template(
|
||||
registry: &PostgresRegistry,
|
||||
resource_id: &ResourceId,
|
||||
uri_template: &str,
|
||||
size: usize,
|
||||
) {
|
||||
let operation_name = "completion_lookup";
|
||||
let options: Vec<String> = if size == 3 {
|
||||
vec!["eu".into(), "us".into(), "apac".into()]
|
||||
} else {
|
||||
(0..size).map(|i| format!("item{i:04}")).collect()
|
||||
};
|
||||
let definition = json!({
|
||||
"operation_id": format!("op_{operation_name}"),
|
||||
"operation_version": 1,
|
||||
"uri_template": uri_template,
|
||||
"parameters": [{
|
||||
"name": "region",
|
||||
"input_path": "input.region",
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"enum_values": options
|
||||
}
|
||||
}],
|
||||
"cache": {"ttl_ms": 60_000, "vary": ["region"], "max_bytes": 65_536},
|
||||
"failure": {"outcome": "error"}
|
||||
});
|
||||
let source = TemplateSource::parse(&definition)
|
||||
.expect("the template fixture satisfies the Story 3.10 source contract");
|
||||
let definition_json =
|
||||
serde_json::to_string(&source).expect("the normalized definition serializes canonically");
|
||||
let digest = format!("{:x}", Sha256::digest(definition_json.as_bytes()));
|
||||
let draft = registry
|
||||
.create_resource_template_draft(CreateResourceTemplateDraftRequest {
|
||||
workspace_id: workspace_id(),
|
||||
resource_id: resource_id.clone(),
|
||||
uri: format!("crank://templates/{}", resource_id.as_str()),
|
||||
name: format!("{}_template", resource_id.as_str()),
|
||||
description: "Bound completion fixture template".to_owned(),
|
||||
kind: "text".to_owned(),
|
||||
mime_type: "application/json".to_owned(),
|
||||
sensitivity: "internal".to_owned(),
|
||||
definition_json: definition_json.clone(),
|
||||
definition_digest: digest.clone(),
|
||||
created_at: time::OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("the template Draft is created through the registry API");
|
||||
registry
|
||||
.publish_resource_template_version(PublishResourceTemplateVersionRequest {
|
||||
workspace_id: workspace_id(),
|
||||
resource_id: resource_id.clone(),
|
||||
expected_updated_at: draft.snapshot.resource.updated_at,
|
||||
expected_version: draft.snapshot.version.version,
|
||||
expected_digest: digest,
|
||||
published_at: time::OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("the template exact version publishes");
|
||||
}
|
||||
@@ -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,436 @@
|
||||
//! #107 Prompts: existing wire GREEN and an independent SDK typed-path RED oracle.
|
||||
use super::{CounterSet, observe, support::*};
|
||||
use axum::{body::Body, response::Response};
|
||||
use futures_util::{StreamExt, stream};
|
||||
use serde_json::{Value, json};
|
||||
use std::{sync::Arc, time::Duration};
|
||||
#[path = "rmcp_prompts_test_support.rs"]
|
||||
mod fixtures;
|
||||
use fixtures::Endpoint;
|
||||
|
||||
fn observe_body(response: Response, counters: Arc<CounterSet>) -> Response {
|
||||
let (parts, body) = response.into_parts();
|
||||
let body = stream::unfold(
|
||||
(body.into_data_stream(), counters),
|
||||
|(mut body, counters)| async move {
|
||||
observe(counters.clone(), body.next())
|
||||
.await
|
||||
.map(|chunk| (chunk, (body, counters)))
|
||||
},
|
||||
);
|
||||
Response::from_parts(parts, Body::from_stream(body))
|
||||
}
|
||||
fn counts(c: &CounterSet) -> [usize; 3] {
|
||||
[
|
||||
c.sdk_prompts_dispatch(),
|
||||
c.sdk_prompts_list_result(),
|
||||
c.sdk_prompts_get_result(),
|
||||
]
|
||||
}
|
||||
fn request(revision: &str, method: &str, mut params: Value) -> Value {
|
||||
if revision == MODERN_REVISION {
|
||||
params["_meta"] = modern_meta();
|
||||
}
|
||||
json!({"jsonrpc":"2.0","id":9007199254740993_u64,"method":method,"params":params})
|
||||
}
|
||||
async fn wire(response: reqwest::Response, id: &Value, sse: bool) -> Value {
|
||||
assert_eq!(response.status(), 200);
|
||||
assert_eq!(response.headers()["x-request-id"], "sdk-prompts-wire");
|
||||
assert_eq!(
|
||||
response.headers()["x-trace-id"],
|
||||
"11111111111111111111111111111111"
|
||||
);
|
||||
let content_type = response.headers()["content-type"]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.to_owned();
|
||||
let text = tokio::time::timeout(Duration::from_secs(5), response.text())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let body: Value = if sse {
|
||||
assert!(
|
||||
content_type.starts_with("text/event-stream"),
|
||||
"{content_type}: {text}"
|
||||
);
|
||||
let frames: Vec<Value> = text
|
||||
.lines()
|
||||
.filter_map(|line| {
|
||||
line.strip_prefix("data:")
|
||||
.map(|s| serde_json::from_str(s.trim()).unwrap())
|
||||
})
|
||||
.collect();
|
||||
let terminal: Vec<_> = frames.iter().filter(|f| f.get("id") == Some(id)).collect();
|
||||
assert_eq!(terminal.len(), 1, "{frames:?}");
|
||||
assert_eq!(frames.last(), Some(terminal[0]), "terminal must be last");
|
||||
terminal[0].clone()
|
||||
} else {
|
||||
assert!(
|
||||
content_type.starts_with("application/json"),
|
||||
"{content_type}: {text}"
|
||||
);
|
||||
serde_json::from_str(&text).unwrap()
|
||||
};
|
||||
assert_eq!(body["jsonrpc"], "2.0");
|
||||
assert_eq!(&body["id"], id);
|
||||
body
|
||||
}
|
||||
fn era(result: &Value, revision: &str, method: &str) {
|
||||
if revision == MODERN_REVISION {
|
||||
assert_eq!(result["resultType"], "complete", "{result}");
|
||||
if method == "prompts/list" {
|
||||
assert_eq!(result["ttlMs"], 0);
|
||||
assert_eq!(result["cacheScope"], "private");
|
||||
} else {
|
||||
assert!(result.get("ttlMs").is_none(), "{result}");
|
||||
assert!(result.get("cacheScope").is_none(), "{result}");
|
||||
}
|
||||
} else {
|
||||
for key in ["resultType", "ttlMs", "cacheScope"] {
|
||||
assert!(result.get(key).is_none(), "{result}");
|
||||
}
|
||||
}
|
||||
assert!(result.get("_meta").is_none(), "{result}");
|
||||
}
|
||||
async fn success(
|
||||
h: &Endpoint,
|
||||
revision: &str,
|
||||
session: Option<&str>,
|
||||
method: &str,
|
||||
params: Value,
|
||||
sse: bool,
|
||||
) -> (Value, [usize; 3]) {
|
||||
let req = request(revision, method, params);
|
||||
let before = counts(&h.counters);
|
||||
let body = wire(h.post(revision, session, &req, sse).await, &req["id"], sse).await;
|
||||
assert!(body.get("error").is_none(), "{body}");
|
||||
era(&body["result"], revision, method);
|
||||
let after = counts(&h.counters);
|
||||
(
|
||||
body["result"].clone(),
|
||||
std::array::from_fn(|i| after[i] - before[i]),
|
||||
)
|
||||
}
|
||||
async fn control(revision: &str) -> Vec<([usize; 3], [usize; 3])> {
|
||||
let h = Endpoint::started().await;
|
||||
let session = h.session(revision).await;
|
||||
let session = session.as_deref();
|
||||
let mut deltas = Vec::new();
|
||||
let mut first_cursor = None;
|
||||
// Both revisions' JSON contract, plus modern terminal SSE through the same normal app.
|
||||
let modes: &[bool] = if revision == MODERN_REVISION {
|
||||
&[false, true]
|
||||
} else {
|
||||
&[false]
|
||||
};
|
||||
for &sse in modes {
|
||||
let mut cursor = None;
|
||||
for (page, name) in ["greeting", "archived-prompt"].iter().enumerate() {
|
||||
let mut params = json!({"limit":1});
|
||||
if let Some(ref cursor) = cursor {
|
||||
params["cursor"] = json!(cursor);
|
||||
}
|
||||
let (result, delta) = success(&h, revision, session, "prompts/list", params, sse).await;
|
||||
let prompts = result["prompts"].as_array().unwrap();
|
||||
assert_eq!(prompts.len(), 1, "{result}");
|
||||
assert_eq!(
|
||||
prompts[0],
|
||||
json!({
|
||||
"name":name, "description":format!("Published {name}"),
|
||||
"arguments":[
|
||||
{"name":"name","schema":{"type":"string"},"required":true},
|
||||
{"name":"count","schema":{"type":"integer"},"required":false,"default":2},
|
||||
{"name":"enabled","schema":{"type":"boolean"},"required":false,"default":true},
|
||||
{"name":"tone","schema":{"type":"string","enum":["warm","dry"]},"required":false,"default":"warm"}
|
||||
]
|
||||
})
|
||||
);
|
||||
cursor = result
|
||||
.get("nextCursor")
|
||||
.map(|v| v.as_str().unwrap().to_owned());
|
||||
assert_eq!(cursor.is_some(), page == 0, "{result}");
|
||||
if page == 0 {
|
||||
assert_ne!(cursor.as_deref(), Some("1"));
|
||||
first_cursor = cursor.clone();
|
||||
}
|
||||
deltas.push((delta, [1, 1, 0]));
|
||||
}
|
||||
for (name, args, text) in [
|
||||
(
|
||||
"greeting",
|
||||
json!({"name":"Ada"}),
|
||||
"Hello Ada count=2 enabled=true tone=warm",
|
||||
),
|
||||
(
|
||||
"greeting",
|
||||
json!({"name":"Ada","count":7,"enabled":false,"tone":"dry"}),
|
||||
"Hello Ada count=7 enabled=false tone=dry",
|
||||
),
|
||||
(
|
||||
"archived-prompt",
|
||||
json!({"name":"Ada"}),
|
||||
"Hello Ada count=2 enabled=true tone=warm",
|
||||
),
|
||||
] {
|
||||
let mut previous = None;
|
||||
for _ in 0..2 {
|
||||
let (result, delta) = success(
|
||||
&h,
|
||||
revision,
|
||||
session,
|
||||
"prompts/get",
|
||||
json!({"name":name,"arguments":args}),
|
||||
sse,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(result["description"], format!("Published {name}"));
|
||||
assert_eq!(
|
||||
result["messages"],
|
||||
json!([
|
||||
{"role":"system","content":{"type":"text","text":"Be brief."}},
|
||||
{"role":"user","content":{"type":"text","text":text}}
|
||||
])
|
||||
);
|
||||
if let Some(ref previous) = previous {
|
||||
assert_eq!(&result, previous);
|
||||
}
|
||||
previous = Some(result);
|
||||
deltas.push((delta, [1, 0, 1]));
|
||||
}
|
||||
}
|
||||
for (arguments, reason, argument) in [
|
||||
(json!({}), "missing_argument", "name"),
|
||||
(
|
||||
json!({"name":"Ada","extra":"x"}),
|
||||
"unknown_argument",
|
||||
"extra",
|
||||
),
|
||||
(json!({"name":5}), "argument_invalid", "name"),
|
||||
(
|
||||
json!({"name":"Ada","count":"7"}),
|
||||
"argument_invalid",
|
||||
"count",
|
||||
),
|
||||
(
|
||||
json!({"name":"Ada","enabled":"false"}),
|
||||
"argument_invalid",
|
||||
"enabled",
|
||||
),
|
||||
(
|
||||
json!({"name":"Ada","tone":"loud"}),
|
||||
"argument_invalid",
|
||||
"tone",
|
||||
),
|
||||
(
|
||||
json!({"name":"x".repeat(crank_core::prompt::MAX_TEXT_BYTES + 1)}),
|
||||
"argument_too_large",
|
||||
"name",
|
||||
),
|
||||
] {
|
||||
let req = request(
|
||||
revision,
|
||||
"prompts/get",
|
||||
json!({"name":"greeting","arguments":arguments}),
|
||||
);
|
||||
let body = wire(h.post(revision, session, &req, sse).await, &req["id"], sse).await;
|
||||
assert_eq!(body["error"]["code"], -32602, "{body}");
|
||||
assert_eq!(body["error"]["data"]["reason"], reason, "{body}");
|
||||
assert_eq!(body["error"]["data"]["argument"], argument);
|
||||
assert!(body.get("result").is_none(), "{body}");
|
||||
for leaked in [
|
||||
"Be brief.",
|
||||
"Hello ",
|
||||
"Changed ",
|
||||
"Published unbound-prompt",
|
||||
] {
|
||||
assert!(!body.to_string().contains(leaked), "{body}");
|
||||
}
|
||||
}
|
||||
let mut unavailable = None;
|
||||
for name in [
|
||||
"draft-prompt",
|
||||
"unbound-prompt",
|
||||
"other-agent-prompt",
|
||||
"never-existed",
|
||||
"prm_a",
|
||||
] {
|
||||
let req = request(revision, "prompts/get", json!({"name":name}));
|
||||
let body = wire(h.post(revision, session, &req, sse).await, &req["id"], sse).await;
|
||||
assert_eq!(body["error"]["code"], -32602, "{body}");
|
||||
assert_eq!(
|
||||
body["error"]["message"],
|
||||
"the requested prompt is not available"
|
||||
);
|
||||
assert!(body.get("result").is_none());
|
||||
if let Some(ref previous) = unavailable {
|
||||
assert_eq!(&body, previous);
|
||||
}
|
||||
unavailable = Some(body);
|
||||
}
|
||||
}
|
||||
for params in [json!({"cursor":"invalid"}), json!({"limit":"invalid"})] {
|
||||
let req = request(revision, "prompts/list", params);
|
||||
let body = wire(
|
||||
h.post(revision, session, &req, false).await,
|
||||
&req["id"],
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(body["error"]["code"], -32602, "{body}");
|
||||
}
|
||||
let other = if revision == MODERN_REVISION {
|
||||
LEGACY_REVISION
|
||||
} else {
|
||||
MODERN_REVISION
|
||||
};
|
||||
let other_session = h.session(other).await;
|
||||
let req = request(
|
||||
other,
|
||||
"prompts/list",
|
||||
json!({"cursor":first_cursor.unwrap()}),
|
||||
);
|
||||
let body = wire(
|
||||
h.post(other, other_session.as_deref(), &req, false).await,
|
||||
&req["id"],
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
body["error"]["code"], -32602,
|
||||
"cross-revision cursor: {body}"
|
||||
);
|
||||
// Archive keeps serving v1 above, but disallows new publications and bindings.
|
||||
use crank_core::ids::PromptId;
|
||||
use crank_registry::model::{
|
||||
AgentPromptBinding, PublishPromptRequest, SaveAgentCatalogConfigRequest,
|
||||
};
|
||||
let publication = h
|
||||
.registry
|
||||
.publish_prompt_draft(PublishPromptRequest {
|
||||
workspace_id: workspace_id(),
|
||||
prompt_id: PromptId::new("prm_b"),
|
||||
expected_updated_at: h.archived_at,
|
||||
published_at: time::OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await;
|
||||
assert!(
|
||||
matches!(
|
||||
publication,
|
||||
Err(crank_registry::RegistryError::PromptNotDraft { .. })
|
||||
),
|
||||
"{publication:?}"
|
||||
);
|
||||
let binding = h
|
||||
.registry
|
||||
.save_agent_catalog_config_editable_with_prompts(
|
||||
SaveAgentCatalogConfigRequest {
|
||||
workspace_id: &workspace_id(),
|
||||
agent_id: &agent_id(),
|
||||
agent_version: 1,
|
||||
bindings: &[],
|
||||
tool_selection_policy: &crank_core::ToolSelectionPolicy::default(),
|
||||
resource_bindings: &[],
|
||||
expected_state: None,
|
||||
},
|
||||
&[AgentPromptBinding {
|
||||
prompt_id: PromptId::new("prm_b"),
|
||||
prompt_version: 1,
|
||||
}],
|
||||
)
|
||||
.await;
|
||||
assert!(
|
||||
matches!(
|
||||
binding,
|
||||
Err(crank_registry::RegistryError::PromptArchived { .. })
|
||||
),
|
||||
"{binding:?}"
|
||||
);
|
||||
h.registry
|
||||
.revoke_platform_api_key(
|
||||
&workspace_id(),
|
||||
&crank_core::PlatformApiKeyId::new("pk_dispatch_observer"),
|
||||
&time::OffsetDateTime::now_utc(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
for (method, params) in [
|
||||
("prompts/list", json!({})),
|
||||
(
|
||||
"prompts/get",
|
||||
json!({"name":"greeting","arguments":{"name":"Ada"}}),
|
||||
),
|
||||
] {
|
||||
assert_eq!(
|
||||
h.post(revision, session, &request(revision, method, params), false)
|
||||
.await
|
||||
.status(),
|
||||
401
|
||||
);
|
||||
}
|
||||
eprintln!(
|
||||
"existing GREEN Prompts wire {revision}: populated pagination, typed metadata/values, exact immutable rendering, archive, structured refusals/non-disclosure, correlation/ID/cache, revoked401; SDK actual/expected={deltas:?}"
|
||||
);
|
||||
deltas
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_prompts_wire_legacy() {
|
||||
control(LEGACY_REVISION).await;
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_prompts_wire_modern() {
|
||||
control(MODERN_REVISION).await;
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_prompts_sdk_legacy() {
|
||||
let deltas = control(LEGACY_REVISION).await;
|
||||
assert!(
|
||||
deltas.iter().all(|(a, e)| a == e),
|
||||
"SDK typed dispatch/result missing after successful HTTP: {deltas:?}"
|
||||
);
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_prompts_sdk_modern() {
|
||||
let deltas = control(MODERN_REVISION).await;
|
||||
assert!(
|
||||
deltas.iter().all(|(a, e)| a == e),
|
||||
"SDK typed dispatch/result missing after successful HTTP: {deltas:?}"
|
||||
);
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_prompts_observer_scope_control() {
|
||||
use super::{
|
||||
sdk_prompts_dispatch_enter, sdk_prompts_get_result_serialized,
|
||||
sdk_prompts_list_result_serialized,
|
||||
};
|
||||
let a = Arc::new(CounterSet::default());
|
||||
let b = Arc::new(CounterSet::default());
|
||||
sdk_prompts_dispatch_enter();
|
||||
assert_eq!(counts(&a), [0; 3]);
|
||||
let snapshot = a.snapshot();
|
||||
observe(a.clone(), async {
|
||||
sdk_prompts_dispatch_enter();
|
||||
sdk_prompts_list_result_serialized();
|
||||
sdk_prompts_get_result_serialized();
|
||||
})
|
||||
.await;
|
||||
observe(b.clone(), async {
|
||||
sdk_prompts_get_result_serialized();
|
||||
})
|
||||
.await;
|
||||
assert_eq!(counts(&a), [1; 3]);
|
||||
assert_eq!(counts(&b), [0, 0, 1]);
|
||||
assert_eq!(a.snapshot(), snapshot);
|
||||
let body = Body::from_stream(stream::once(async {
|
||||
sdk_prompts_list_result_serialized();
|
||||
Ok::<_, std::convert::Infallible>("terminal")
|
||||
}));
|
||||
let response = observe_body(Response::new(body), b.clone());
|
||||
assert_eq!(
|
||||
&axum::body::to_bytes(response.into_body(), 100)
|
||||
.await
|
||||
.unwrap()[..],
|
||||
b"terminal"
|
||||
);
|
||||
assert_eq!(counts(&b), [0, 1, 1]);
|
||||
assert_eq!(counts(&a), [1; 3]);
|
||||
}
|
||||
@@ -0,0 +1,305 @@
|
||||
//! Published Prompts fixture using the existing observed HTTP app and disposable PostgreSQL.
|
||||
use super::*;
|
||||
use crank_core::prompt::{PromptDefinition, PromptSensitivity};
|
||||
use crank_core::{Agent, AgentStatus, AgentVersion, ToolSelectionPolicy, ids::PromptId};
|
||||
use crank_registry::model::{
|
||||
AgentPromptBinding, ArchivePromptRequest, CreatePromptDraftRequest, PublishPromptRequest,
|
||||
SaveAgentCatalogConfigRequest, UpdatePromptDraftRequest,
|
||||
};
|
||||
use crank_registry::{CreateAgentRequest, PublishAgentRequest};
|
||||
use crank_runtime::{
|
||||
InMemoryCoordinationStateStore, RequestRateLimitConfig, RequestRateLimiter, SecretCrypto,
|
||||
};
|
||||
|
||||
pub(super) fn definition(name: &str, content: &str) -> PromptDefinition {
|
||||
PromptDefinition::parse(&json!({
|
||||
"name":name, "description":format!("Published {name}"),
|
||||
"arguments":[
|
||||
{"name":"name","schema":{"type":"string"},"required":true},
|
||||
{"name":"count","schema":{"type":"integer"},"required":false,"default":2},
|
||||
{"name":"enabled","schema":{"type":"boolean"},"required":false,"default":true},
|
||||
{"name":"tone","schema":{"type":"string","enum":["warm","dry"]},"required":false,"default":"warm"}
|
||||
],
|
||||
"messages":[{"role":"system","content":"Be brief."},{"role":"user","content":content}]
|
||||
})).unwrap()
|
||||
}
|
||||
|
||||
pub(super) struct Endpoint {
|
||||
pub registry: crank_registry::PostgresRegistry,
|
||||
pub counters: Arc<CounterSet>,
|
||||
pub key: String,
|
||||
pub url: String,
|
||||
pub archived_at: time::OffsetDateTime,
|
||||
server: tokio::task::JoinHandle<()>,
|
||||
}
|
||||
impl Drop for Endpoint {
|
||||
fn drop(&mut self) {
|
||||
self.server.abort();
|
||||
}
|
||||
}
|
||||
impl Endpoint {
|
||||
pub async fn started() -> Self {
|
||||
crank_test_support::postgres_schema_url_for_task("prompts_owner", "t_160a763a").await;
|
||||
let registry = test_registry().await;
|
||||
let mut archived_at = test_time();
|
||||
for (id, name, publish) in [
|
||||
("prm_a", "greeting", true),
|
||||
("prm_b", "archived-prompt", true),
|
||||
("prm_c", "unbound-prompt", true),
|
||||
("prm_d", "draft-prompt", false),
|
||||
("prm_e", "other-agent-prompt", true),
|
||||
] {
|
||||
let row = registry
|
||||
.create_prompt_draft(CreatePromptDraftRequest {
|
||||
workspace_id: workspace_id(),
|
||||
prompt_id: PromptId::new(id),
|
||||
sensitivity: PromptSensitivity::Internal,
|
||||
definition: definition(
|
||||
name,
|
||||
"Hello {{name}} count={{count}} enabled={{enabled}} tone={{tone}}",
|
||||
),
|
||||
created_at: time::OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
if publish {
|
||||
let row = registry
|
||||
.publish_prompt_draft(PublishPromptRequest {
|
||||
workspace_id: workspace_id(),
|
||||
prompt_id: PromptId::new(id),
|
||||
expected_updated_at: row.updated_at,
|
||||
published_at: time::OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
if id == "prm_b" {
|
||||
archived_at = row.updated_at;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (id, slug) in [
|
||||
(agent_id(), AGENT_SLUG),
|
||||
(
|
||||
crank_core::AgentId::new("agent_other_prompts"),
|
||||
"other-prompts",
|
||||
),
|
||||
] {
|
||||
registry
|
||||
.create_agent(CreateAgentRequest {
|
||||
agent: &Agent {
|
||||
id: id.clone(),
|
||||
workspace_id: workspace_id(),
|
||||
slug: slug.into(),
|
||||
display_name: "SDK Prompts".into(),
|
||||
description: String::new(),
|
||||
status: AgentStatus::Draft,
|
||||
current_draft_version: 1,
|
||||
latest_published_version: None,
|
||||
created_at: test_time(),
|
||||
updated_at: test_time(),
|
||||
published_at: None,
|
||||
},
|
||||
version: &AgentVersion {
|
||||
agent_id: id,
|
||||
version: 1,
|
||||
status: AgentStatus::Draft,
|
||||
instructions: json!({}),
|
||||
tool_selection_policy: ToolSelectionPolicy::default(),
|
||||
created_at: test_time(),
|
||||
},
|
||||
bindings: &[],
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
let other_agent = crank_core::AgentId::new("agent_other_prompts");
|
||||
registry
|
||||
.save_agent_catalog_config_editable_with_prompts(
|
||||
SaveAgentCatalogConfigRequest {
|
||||
workspace_id: &workspace_id(),
|
||||
agent_id: &other_agent,
|
||||
agent_version: 1,
|
||||
bindings: &[],
|
||||
tool_selection_policy: &ToolSelectionPolicy::default(),
|
||||
resource_bindings: &[],
|
||||
expected_state: None,
|
||||
},
|
||||
&[AgentPromptBinding {
|
||||
prompt_id: PromptId::new("prm_e"),
|
||||
prompt_version: 1,
|
||||
}],
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
registry
|
||||
.publish_agent(PublishAgentRequest {
|
||||
workspace_id: &workspace_id(),
|
||||
agent_id: &other_agent,
|
||||
version: 1,
|
||||
published_at: &test_time(),
|
||||
published_by: Some("alice"),
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
registry
|
||||
.save_agent_catalog_config_editable_with_prompts(
|
||||
SaveAgentCatalogConfigRequest {
|
||||
workspace_id: &workspace_id(),
|
||||
agent_id: &agent_id(),
|
||||
agent_version: 1,
|
||||
bindings: &[],
|
||||
tool_selection_policy: &ToolSelectionPolicy::default(),
|
||||
resource_bindings: &[],
|
||||
expected_state: None,
|
||||
},
|
||||
&[
|
||||
AgentPromptBinding {
|
||||
prompt_id: PromptId::new("prm_a"),
|
||||
prompt_version: 1,
|
||||
},
|
||||
AgentPromptBinding {
|
||||
prompt_id: PromptId::new("prm_b"),
|
||||
prompt_version: 1,
|
||||
},
|
||||
],
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
registry
|
||||
.publish_agent(PublishAgentRequest {
|
||||
workspace_id: &workspace_id(),
|
||||
agent_id: &agent_id(),
|
||||
version: 1,
|
||||
published_at: &test_time(),
|
||||
published_by: Some("alice"),
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let archived_at = registry
|
||||
.archive_prompt_draft(ArchivePromptRequest {
|
||||
workspace_id: workspace_id(),
|
||||
prompt_id: PromptId::new("prm_b"),
|
||||
expected_updated_at: archived_at,
|
||||
archived_at: time::OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.unwrap()
|
||||
.updated_at;
|
||||
// A mutable v2 draft must not change the bound v1 rendering or discovery metadata.
|
||||
let draft = registry
|
||||
.get_prompt_draft(&workspace_id(), &PromptId::new("prm_a"))
|
||||
.await
|
||||
.unwrap();
|
||||
registry
|
||||
.update_prompt_draft(UpdatePromptDraftRequest {
|
||||
workspace_id: workspace_id(),
|
||||
prompt_id: PromptId::new("prm_a"),
|
||||
sensitivity: PromptSensitivity::Internal,
|
||||
definition: definition("changed-draft", "Changed {{name}}"),
|
||||
expected_updated_at: draft.updated_at,
|
||||
updated_at: time::OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let key = create_api_key(®istry).await;
|
||||
let counters = Arc::new(CounterSet::default());
|
||||
let app = crate::build_app(
|
||||
registry.clone(),
|
||||
Duration::ZERO,
|
||||
None,
|
||||
SecretCrypto::new("test-master-key-00000000000000000000000000000000").unwrap(),
|
||||
crank_runtime::community_with_outbound_policy(
|
||||
crank_runtime::OutboundHttpPolicy::allowing_hosts(["127.0.0.1"]),
|
||||
)
|
||||
.build(),
|
||||
RequestRateLimiter::new(RequestRateLimitConfig::new(10_000, 10_000).unwrap()),
|
||||
Arc::new(InMemoryCoordinationStateStore::default()),
|
||||
Arc::new(crate::session::InMemorySessionStore::default()),
|
||||
Arc::new(crate::auth::CommunityMachineCredentialVerifier),
|
||||
);
|
||||
let app = observe_requests(app, counters.clone(), None).layer(axum::middleware::from_fn({
|
||||
let counters = counters.clone();
|
||||
move |request: axum::extract::Request, next: axum::middleware::Next| {
|
||||
let counters = counters.clone();
|
||||
async move { observe_body(next.run(request).await, counters) }
|
||||
}
|
||||
}));
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let url = format!(
|
||||
"http://{}/v1/{WORKSPACE_SLUG}/{AGENT_SLUG}",
|
||||
listener.local_addr().unwrap()
|
||||
);
|
||||
let server = tokio::spawn(async move {
|
||||
axum::serve(listener, app).await.unwrap();
|
||||
});
|
||||
Self {
|
||||
registry,
|
||||
counters,
|
||||
key,
|
||||
url,
|
||||
archived_at,
|
||||
server,
|
||||
}
|
||||
}
|
||||
pub async fn post(
|
||||
&self,
|
||||
revision: &str,
|
||||
session: Option<&str>,
|
||||
body: &Value,
|
||||
sse: bool,
|
||||
) -> reqwest::Response {
|
||||
let mut request = reqwest::Client::new()
|
||||
.post(&self.url)
|
||||
.bearer_auth(&self.key)
|
||||
.header(
|
||||
"Accept",
|
||||
if sse {
|
||||
"text/event-stream, application/json"
|
||||
} else {
|
||||
"application/json"
|
||||
},
|
||||
)
|
||||
.header("x-request-id", "sdk-prompts-wire")
|
||||
.header(
|
||||
"traceparent",
|
||||
"00-11111111111111111111111111111111-2222222222222222-01",
|
||||
)
|
||||
.header("MCP-Protocol-Version", revision);
|
||||
if let Some(session) = session {
|
||||
request = request.header("MCP-Session-Id", session);
|
||||
}
|
||||
if revision == MODERN_REVISION {
|
||||
request = request.header("Mcp-Method", body["method"].as_str().unwrap());
|
||||
if let Some(name) = body["params"]["name"].as_str() {
|
||||
request = request.header("Mcp-Name", name);
|
||||
}
|
||||
}
|
||||
request.json(body).send().await.unwrap()
|
||||
}
|
||||
pub async fn session(&self, revision: &str) -> Option<String> {
|
||||
if revision == MODERN_REVISION {
|
||||
return None;
|
||||
}
|
||||
let response = self
|
||||
.post(revision, None, &legacy_initialize(1), false)
|
||||
.await;
|
||||
assert_eq!(response.status(), 200);
|
||||
let session = response.headers()["MCP-Session-Id"]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.to_owned();
|
||||
assert_eq!(
|
||||
json_body(response).await["result"]["protocolVersion"],
|
||||
revision
|
||||
);
|
||||
assert_eq!(
|
||||
self.post(revision, Some(&session), &initialized_notification(), false)
|
||||
.await
|
||||
.status(),
|
||||
202
|
||||
);
|
||||
Some(session)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,287 @@
|
||||
//! #107 Resources: existing wire GREEN is independent of the missing SDK typed-path oracle.
|
||||
use super::{CounterSet, observe, support::*};
|
||||
use axum::{body::Body, response::Response};
|
||||
use futures_util::{StreamExt, stream};
|
||||
use serde_json::{Value, json};
|
||||
use std::{sync::Arc, time::Duration};
|
||||
#[path = "rmcp_resources_test_support.rs"]
|
||||
mod fixtures;
|
||||
use fixtures::{Endpoint, TEXT, URI};
|
||||
|
||||
// As in rmcp_result_runtime_tests: deferred body polling keeps this request's observer.
|
||||
fn observe_body(response: Response, counters: Arc<CounterSet>) -> Response {
|
||||
let (parts, body) = response.into_parts();
|
||||
let body = stream::unfold(
|
||||
(body.into_data_stream(), counters),
|
||||
|(mut body, counters)| async move {
|
||||
observe(counters.clone(), body.next())
|
||||
.await
|
||||
.map(|chunk| (chunk, (body, counters)))
|
||||
},
|
||||
);
|
||||
Response::from_parts(parts, Body::from_stream(body))
|
||||
}
|
||||
fn counts(c: &CounterSet) -> [usize; 4] {
|
||||
[
|
||||
c.sdk_resources_dispatch(),
|
||||
c.sdk_resources_list_result(),
|
||||
c.sdk_resources_read_result(),
|
||||
c.sdk_resource_templates_list_result(),
|
||||
]
|
||||
}
|
||||
fn request(revision: &str, method: &str, mut params: Value) -> Value {
|
||||
if revision == MODERN_REVISION {
|
||||
params["_meta"] = modern_meta();
|
||||
}
|
||||
json!({"jsonrpc":"2.0", "id":9007199254740993_u64, "method":method, "params":params})
|
||||
}
|
||||
async fn wire(response: reqwest::Response, id: &Value, sse: bool) -> Value {
|
||||
assert_eq!(response.status(), 200);
|
||||
assert_eq!(response.headers()["x-request-id"], "sdk-resources-wire");
|
||||
assert_eq!(
|
||||
response.headers()["x-trace-id"],
|
||||
"11111111111111111111111111111111"
|
||||
);
|
||||
let content_type = response.headers()["content-type"]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.to_owned();
|
||||
let text = tokio::time::timeout(Duration::from_secs(5), response.text())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let body: Value = if sse {
|
||||
assert!(
|
||||
content_type.starts_with("text/event-stream"),
|
||||
"{content_type}: {text}"
|
||||
);
|
||||
let frames: Vec<Value> = text
|
||||
.lines()
|
||||
.filter_map(|line| {
|
||||
line.strip_prefix("data:")
|
||||
.map(|s| serde_json::from_str(s.trim()).unwrap())
|
||||
})
|
||||
.collect();
|
||||
let terminal: Vec<_> = frames.iter().filter(|f| f.get("id") == Some(id)).collect();
|
||||
assert_eq!(terminal.len(), 1, "{frames:?}");
|
||||
assert_eq!(frames.last(), Some(terminal[0]), "terminal must be last");
|
||||
terminal[0].clone()
|
||||
} else {
|
||||
assert!(
|
||||
content_type.starts_with("application/json"),
|
||||
"{content_type}: {text}"
|
||||
);
|
||||
serde_json::from_str(&text).unwrap()
|
||||
};
|
||||
assert_eq!(body["jsonrpc"], "2.0");
|
||||
assert_eq!(&body["id"], id);
|
||||
body
|
||||
}
|
||||
fn era(result: &Value, revision: &str) {
|
||||
if revision == MODERN_REVISION {
|
||||
assert_eq!(result["resultType"], "complete", "{result}");
|
||||
assert_eq!(result["ttlMs"], 0);
|
||||
assert_eq!(result["cacheScope"], "private");
|
||||
} else {
|
||||
for key in ["resultType", "ttlMs", "cacheScope"] {
|
||||
assert!(result.get(key).is_none(), "{result}");
|
||||
}
|
||||
}
|
||||
assert!(result.get("_meta").is_none(), "{result}");
|
||||
}
|
||||
async fn success(
|
||||
h: &Endpoint,
|
||||
revision: &str,
|
||||
session: Option<&str>,
|
||||
method: &str,
|
||||
params: Value,
|
||||
sse_accept: bool,
|
||||
) -> (Value, [usize; 4]) {
|
||||
let req = request(revision, method, params);
|
||||
let before = counts(&h.counters);
|
||||
let body = wire(
|
||||
h.post(revision, session, &req, sse_accept).await,
|
||||
&req["id"],
|
||||
sse_accept,
|
||||
)
|
||||
.await;
|
||||
assert!(body.get("error").is_none(), "{body}");
|
||||
era(&body["result"], revision);
|
||||
let after = counts(&h.counters);
|
||||
(
|
||||
body["result"].clone(),
|
||||
std::array::from_fn(|i| after[i] - before[i]),
|
||||
)
|
||||
}
|
||||
async fn control(revision: &str) -> Vec<([usize; 4], [usize; 4])> {
|
||||
let h = Endpoint::started().await;
|
||||
let session = h.session(revision).await;
|
||||
let session = session.as_deref();
|
||||
let mut deltas = Vec::new();
|
||||
// Preference order negotiates JSON or terminal SSE in both Resources revisions.
|
||||
for sse in [false, true] {
|
||||
let mut cursor = None;
|
||||
let mut names = Vec::new();
|
||||
for page in 0..2 {
|
||||
let mut params = json!({"limit":1});
|
||||
if let Some(ref cursor) = cursor {
|
||||
params["cursor"] = json!(cursor);
|
||||
}
|
||||
let (result, delta) =
|
||||
success(&h, revision, session, "resources/list", params, sse).await;
|
||||
let resources = result["resources"].as_array().unwrap();
|
||||
assert_eq!(resources.len(), 1, "{result}");
|
||||
let item = &resources[0];
|
||||
assert_eq!(item["mimeType"], "text/plain");
|
||||
assert!(
|
||||
item.get("description").is_none(),
|
||||
"static descriptors omit description: {item}"
|
||||
);
|
||||
names.push((item["name"].clone(), item["uri"].clone()));
|
||||
cursor = result
|
||||
.get("nextCursor")
|
||||
.map(|v| v.as_str().unwrap().to_owned());
|
||||
assert_eq!(cursor.is_some(), page == 0, "{result}");
|
||||
if let Some(ref cursor) = cursor {
|
||||
assert_ne!(cursor, "1", "opaque cursor required");
|
||||
}
|
||||
deltas.push((delta, [1, 1, 0, 0]));
|
||||
}
|
||||
names.sort_by_key(|n| n.0.as_str().unwrap().to_owned());
|
||||
assert_eq!(
|
||||
names,
|
||||
vec![
|
||||
(json!("sdk_a"), json!(URI)),
|
||||
(json!("sdk_b"), json!("crank://resources/sdk-b"))
|
||||
]
|
||||
);
|
||||
let (result, delta) = success(
|
||||
&h,
|
||||
revision,
|
||||
session,
|
||||
"resources/read",
|
||||
json!({"uri":URI}),
|
||||
sse,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
result["contents"],
|
||||
json!([{"uri":URI,"mimeType":"text/plain","text":TEXT}])
|
||||
);
|
||||
deltas.push((delta, [1, 0, 1, 0]));
|
||||
let (result, delta) = success(
|
||||
&h,
|
||||
revision,
|
||||
session,
|
||||
"resources/templates/list",
|
||||
json!({}),
|
||||
sse,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(result["resourceTemplates"], json!([]));
|
||||
assert!(result.get("nextCursor").is_none());
|
||||
deltas.push((delta, [1, 0, 0, 1]));
|
||||
}
|
||||
// Malformed parameters/cursors and indistinguishable unavailable URIs remain command errors.
|
||||
for (method, params) in [
|
||||
("resources/list", json!({"cursor":"invalid"})),
|
||||
("resources/list", json!({"limit":"invalid"})),
|
||||
("resources/templates/list", json!({"cursor":"invalid"})),
|
||||
("resources/templates/list", json!({"limit":"invalid"})),
|
||||
("resources/read", json!({"uri":"crank://resources/unbound"})),
|
||||
] {
|
||||
let req = request(revision, method, params);
|
||||
let body = wire(
|
||||
h.post(revision, session, &req, false).await,
|
||||
&req["id"],
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(body["error"]["code"], -32602, "{body}");
|
||||
assert!(body.get("result").is_none(), "{body}");
|
||||
}
|
||||
// An existing session does not preserve revoked authorization.
|
||||
h.registry
|
||||
.revoke_platform_api_key(
|
||||
&workspace_id(),
|
||||
&crank_core::PlatformApiKeyId::new("pk_dispatch_observer"),
|
||||
&time::OffsetDateTime::now_utc(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
for (method, params) in [
|
||||
("resources/list", json!({})),
|
||||
("resources/read", json!({"uri":URI})),
|
||||
("resources/templates/list", json!({})),
|
||||
] {
|
||||
let req = request(revision, method, params);
|
||||
assert_eq!(h.post(revision, session, &req, false).await.status(), 401);
|
||||
}
|
||||
eprintln!(
|
||||
"existing GREEN Resources wire {revision}: pagination, exact content URI/bytes, empty templates, JSON/SSE negotiation, InvalidParams, revoked401; actual/expected SDK deltas={deltas:?}"
|
||||
);
|
||||
deltas
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_resources_wire_legacy() {
|
||||
control(LEGACY_REVISION).await;
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_resources_wire_modern() {
|
||||
control(MODERN_REVISION).await;
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_resources_sdk_legacy() {
|
||||
let deltas = control(LEGACY_REVISION).await;
|
||||
assert!(
|
||||
deltas.iter().all(|(actual, expected)| actual == expected),
|
||||
"SDK typed dispatch/result missing after successful HTTP: {deltas:?}"
|
||||
);
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_resources_sdk_modern() {
|
||||
let deltas = control(MODERN_REVISION).await;
|
||||
assert!(
|
||||
deltas.iter().all(|(actual, expected)| actual == expected),
|
||||
"SDK typed dispatch/result missing after successful HTTP: {deltas:?}"
|
||||
);
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_resources_observer_scope_control() {
|
||||
use super::{
|
||||
sdk_resource_templates_list_result_serialized, sdk_resources_dispatch_enter,
|
||||
sdk_resources_list_result_serialized, sdk_resources_read_result_serialized,
|
||||
};
|
||||
let a = Arc::new(CounterSet::default());
|
||||
let b = Arc::new(CounterSet::default());
|
||||
sdk_resources_dispatch_enter();
|
||||
assert_eq!(counts(&a), [0; 4]);
|
||||
let snapshot = a.snapshot();
|
||||
observe(a.clone(), async {
|
||||
sdk_resources_dispatch_enter();
|
||||
sdk_resources_list_result_serialized();
|
||||
sdk_resources_read_result_serialized();
|
||||
sdk_resource_templates_list_result_serialized();
|
||||
})
|
||||
.await;
|
||||
observe(b.clone(), async {
|
||||
sdk_resources_read_result_serialized();
|
||||
})
|
||||
.await;
|
||||
assert_eq!(counts(&a), [1; 4]);
|
||||
assert_eq!(counts(&b), [0, 0, 1, 0]);
|
||||
assert_eq!(a.snapshot(), snapshot, "old Snapshot stays unchanged");
|
||||
let body = Body::from_stream(stream::once(async {
|
||||
sdk_resource_templates_list_result_serialized();
|
||||
Ok::<_, std::convert::Infallible>("terminal")
|
||||
}));
|
||||
let response = observe_body(Response::new(body), b.clone());
|
||||
assert_eq!(
|
||||
&axum::body::to_bytes(response.into_body(), 100)
|
||||
.await
|
||||
.unwrap()[..],
|
||||
b"terminal"
|
||||
);
|
||||
assert_eq!(counts(&b), [0, 0, 1, 1]);
|
||||
assert_eq!(counts(&a), [1; 4]);
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
//! Small Resources fixture: existing observer helpers, exact artifact publications, normal app.
|
||||
use super::*;
|
||||
use crank_artifacts::ArtifactStore;
|
||||
use crank_core::{Agent, AgentStatus, AgentVersion, ToolSelectionPolicy, ids::ResourceId};
|
||||
use crank_registry::{
|
||||
AgentResourceBinding, CreateAgentRequest, PublishAgentRequest, SaveAgentCatalogConfigRequest,
|
||||
};
|
||||
use crank_runtime::{
|
||||
InMemoryCoordinationStateStore, RequestRateLimitConfig, RequestRateLimiter, SecretCrypto,
|
||||
};
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
pub(super) const URI: &str = "crank://resources/sdk-a";
|
||||
pub(super) const TEXT: &str = "published v1\n";
|
||||
|
||||
pub(super) struct Endpoint {
|
||||
pub registry: crank_registry::PostgresRegistry,
|
||||
pub counters: Arc<CounterSet>,
|
||||
pub key: String,
|
||||
pub url: String,
|
||||
server: tokio::task::JoinHandle<()>,
|
||||
root: std::path::PathBuf,
|
||||
}
|
||||
impl Drop for Endpoint {
|
||||
fn drop(&mut self) {
|
||||
self.server.abort();
|
||||
let _ = std::fs::remove_dir_all(&self.root);
|
||||
}
|
||||
}
|
||||
impl Endpoint {
|
||||
pub async fn started() -> Self {
|
||||
crank_test_support::postgres_schema_url_for_task("resources_owner", "t_73561633").await;
|
||||
let registry = test_registry().await;
|
||||
let root = std::env::temp_dir().join(format!("rmcp-resources-{}", uuid::Uuid::now_v7()));
|
||||
std::fs::create_dir(&root).unwrap();
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(&root, std::fs::Permissions::from_mode(0o700)).unwrap();
|
||||
let store = ArtifactStore::open(&root).unwrap();
|
||||
// Same immutable row shapes and real ArtifactStore::put as static_resources/fixtures.rs.
|
||||
for (id, uri, name, bytes) in [
|
||||
("res_sdk_a", URI, "sdk_a", TEXT),
|
||||
(
|
||||
"res_sdk_b",
|
||||
"crank://resources/sdk-b",
|
||||
"sdk_b",
|
||||
"second published resource\n",
|
||||
),
|
||||
] {
|
||||
let stored = store.put(bytes.as_bytes()).unwrap();
|
||||
let digest = format!("{:x}", Sha256::digest(bytes.as_bytes()));
|
||||
let source = format!("src_{id}");
|
||||
sqlx::query("insert into artifact_blobs (digest, artifact_ref, size_bytes, storage_lifecycle, created_at, updated_at) values ($1,$2,$3,'available',now(),now())")
|
||||
.bind(&digest).bind(format!("sha256:{digest}")).bind(stored.size_bytes as i64).execute(registry.pool()).await.unwrap();
|
||||
sqlx::query("insert into artifact_sources (workspace_id,source_id,blob_digest,mime_type,sensitivity,lifecycle,created_at,updated_at) values ('ws_default',$1,$2,'text/plain','internal','active',now(),now())")
|
||||
.bind(&source).bind(&digest).execute(registry.pool()).await.unwrap();
|
||||
sqlx::query("insert into resources (workspace_id,resource_id,uri,name,description,status,kind,current_draft_version,created_at,updated_at) values ('ws_default',$1,$2,$3,'','published','text',1,now(),now())")
|
||||
.bind(id).bind(uri).bind(name).execute(registry.pool()).await.unwrap();
|
||||
sqlx::query("insert into resource_versions (workspace_id,resource_id,version,kind,mime_type,size_bytes,digest,sensitivity,artifact_source_id,created_at,superseded_at) values ('ws_default',$1,1,'text','text/plain',$2,$3,'internal',$4,now(),null)")
|
||||
.bind(id).bind(stored.size_bytes as i64).bind(&digest).bind(&source).execute(registry.pool()).await.unwrap();
|
||||
sqlx::query("insert into resource_publications (workspace_id,resource_id,version,uri,name,description,kind,mime_type,size_bytes,digest,sensitivity,artifact_source_id,published_at) values ('ws_default',$1,1,$2,$3,'','text','text/plain',$4,$5,'internal',$6,now())")
|
||||
.bind(id).bind(uri).bind(name).bind(stored.size_bytes as i64).bind(&digest).bind(&source).execute(registry.pool()).await.unwrap();
|
||||
}
|
||||
registry
|
||||
.create_agent(CreateAgentRequest {
|
||||
agent: &Agent {
|
||||
id: agent_id(),
|
||||
workspace_id: workspace_id(),
|
||||
slug: AGENT_SLUG.into(),
|
||||
display_name: "SDK Resources".into(),
|
||||
description: String::new(),
|
||||
status: AgentStatus::Draft,
|
||||
current_draft_version: 1,
|
||||
latest_published_version: None,
|
||||
created_at: test_time(),
|
||||
updated_at: test_time(),
|
||||
published_at: None,
|
||||
},
|
||||
version: &AgentVersion {
|
||||
agent_id: agent_id(),
|
||||
version: 1,
|
||||
status: AgentStatus::Draft,
|
||||
instructions: json!({}),
|
||||
tool_selection_policy: ToolSelectionPolicy::default(),
|
||||
created_at: test_time(),
|
||||
},
|
||||
bindings: &[],
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
registry
|
||||
.save_agent_catalog_config(SaveAgentCatalogConfigRequest {
|
||||
workspace_id: &workspace_id(),
|
||||
agent_id: &agent_id(),
|
||||
agent_version: 1,
|
||||
bindings: &[],
|
||||
tool_selection_policy: &ToolSelectionPolicy::default(),
|
||||
resource_bindings: &[
|
||||
AgentResourceBinding {
|
||||
resource_id: ResourceId::new("res_sdk_a"),
|
||||
resource_version: 1,
|
||||
},
|
||||
AgentResourceBinding {
|
||||
resource_id: ResourceId::new("res_sdk_b"),
|
||||
resource_version: 1,
|
||||
},
|
||||
],
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
registry
|
||||
.publish_agent(PublishAgentRequest {
|
||||
workspace_id: &workspace_id(),
|
||||
agent_id: &agent_id(),
|
||||
version: 1,
|
||||
published_at: &test_time(),
|
||||
published_by: Some("alice"),
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let key = create_api_key(®istry).await;
|
||||
let counters = Arc::new(CounterSet::default());
|
||||
// Normal build_app composition with its sanctioned artifact root, not the isolated SDK router.
|
||||
let app = crate::build_app_with_artifacts(
|
||||
registry.clone(),
|
||||
Duration::ZERO,
|
||||
None,
|
||||
SecretCrypto::new("test-master-key-00000000000000000000000000000000").unwrap(),
|
||||
crank_runtime::community_with_outbound_policy(
|
||||
crank_runtime::OutboundHttpPolicy::allowing_hosts(["127.0.0.1"]),
|
||||
)
|
||||
.build(),
|
||||
RequestRateLimiter::new(RequestRateLimitConfig::new(10_000, 10_000).unwrap()),
|
||||
Arc::new(InMemoryCoordinationStateStore::default()),
|
||||
Arc::new(crate::session::InMemorySessionStore::default()),
|
||||
Arc::new(crate::auth::CommunityMachineCredentialVerifier),
|
||||
16,
|
||||
store,
|
||||
);
|
||||
let app = observe_requests(app, counters.clone(), None).layer(axum::middleware::from_fn({
|
||||
let counters = counters.clone();
|
||||
move |request: axum::extract::Request, next: axum::middleware::Next| {
|
||||
let counters = counters.clone();
|
||||
async move {
|
||||
let response = next.run(request).await;
|
||||
observe_body(response, counters)
|
||||
}
|
||||
}
|
||||
}));
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let url = format!(
|
||||
"http://{}/v1/{WORKSPACE_SLUG}/{AGENT_SLUG}",
|
||||
listener.local_addr().unwrap()
|
||||
);
|
||||
let server = tokio::spawn(async move {
|
||||
axum::serve(listener, app).await.unwrap();
|
||||
});
|
||||
Self {
|
||||
registry,
|
||||
counters,
|
||||
key,
|
||||
url,
|
||||
server,
|
||||
root,
|
||||
}
|
||||
}
|
||||
pub async fn post(
|
||||
&self,
|
||||
revision: &str,
|
||||
session: Option<&str>,
|
||||
body: &Value,
|
||||
sse: bool,
|
||||
) -> reqwest::Response {
|
||||
let mut request = reqwest::Client::new()
|
||||
.post(&self.url)
|
||||
.bearer_auth(&self.key)
|
||||
.header(
|
||||
"Accept",
|
||||
if sse {
|
||||
"text/event-stream, application/json"
|
||||
} else {
|
||||
"application/json"
|
||||
},
|
||||
)
|
||||
.header("x-request-id", "sdk-resources-wire")
|
||||
.header(
|
||||
"traceparent",
|
||||
"00-11111111111111111111111111111111-2222222222222222-01",
|
||||
)
|
||||
.header("MCP-Protocol-Version", revision);
|
||||
if let Some(session) = session {
|
||||
request = request.header("MCP-Session-Id", session);
|
||||
}
|
||||
if revision == MODERN_REVISION {
|
||||
request = request.header("Mcp-Method", body["method"].as_str().unwrap());
|
||||
if let Some(uri) = body["params"]["uri"].as_str() {
|
||||
request = request.header("Mcp-Name", uri);
|
||||
}
|
||||
}
|
||||
request.json(body).send().await.unwrap()
|
||||
}
|
||||
pub async fn session(&self, revision: &str) -> Option<String> {
|
||||
if revision == MODERN_REVISION {
|
||||
return None;
|
||||
}
|
||||
let response = self
|
||||
.post(revision, None, &legacy_initialize(1), false)
|
||||
.await;
|
||||
assert_eq!(response.status(), 200);
|
||||
let session = response.headers()["MCP-Session-Id"]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.to_owned();
|
||||
assert_eq!(
|
||||
json_body(response).await["result"]["protocolVersion"],
|
||||
revision
|
||||
);
|
||||
assert_eq!(
|
||||
self.post(revision, Some(&session), &initialized_notification(), false)
|
||||
.await
|
||||
.status(),
|
||||
202
|
||||
);
|
||||
Some(session)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,437 @@
|
||||
//! #107 result serialization: wire controls run independently of the structural SDK oracle.
|
||||
use super::*;
|
||||
use axum::{
|
||||
Json,
|
||||
body::Body,
|
||||
extract::State,
|
||||
http::StatusCode,
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
use futures_util::{StreamExt, stream};
|
||||
|
||||
const ERROR_EMAIL: &str = "upstream-error@example.test";
|
||||
const REQUEST_ID: &str = "sdk-result-wire";
|
||||
const TRACE_ID: &str = "11111111111111111111111111111111";
|
||||
|
||||
pub(super) async fn upstream(state: State<Arc<AtomicUsize>>, payload: Json<Value>) -> Response {
|
||||
if payload.0["email"] == ERROR_EMAIL {
|
||||
state.0.fetch_add(1, Ordering::SeqCst);
|
||||
return (
|
||||
StatusCode::UNPROCESSABLE_ENTITY,
|
||||
Json(json!({"error":"fixture rejection"})),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
create_lead(state, payload).await.into_response()
|
||||
}
|
||||
|
||||
// The HTTP body is polled after next.run returns. Carry only the test observer, not a new lifecycle.
|
||||
pub(super) fn observe_body(response: Response, counters: Arc<CounterSet>) -> Response {
|
||||
let (parts, body) = response.into_parts();
|
||||
let body = stream::unfold(
|
||||
(body.into_data_stream(), counters),
|
||||
|(mut body, counters)| async move {
|
||||
observe(counters.clone(), body.next())
|
||||
.await
|
||||
.map(|chunk| (chunk, (body, counters)))
|
||||
},
|
||||
);
|
||||
Response::from_parts(parts, Body::from_stream(body))
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_result_http_pagination_both_revisions() {
|
||||
let h = Endpoint::started().await;
|
||||
let mut operation = test_operation(&h._upstream.1);
|
||||
operation.id = crank_core::OperationId::new("op_second_lead");
|
||||
operation.name = "second_lead".to_owned();
|
||||
h.registry
|
||||
.create_operation(&workspace_id(), &operation, Some("alice"))
|
||||
.await
|
||||
.unwrap();
|
||||
h.registry
|
||||
.publish_operation(PublishRequest {
|
||||
workspace_id: &workspace_id(),
|
||||
operation_id: &operation.id,
|
||||
version: 1,
|
||||
published_at: &test_time(),
|
||||
published_by: Some("alice"),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let now = time::OffsetDateTime::now_utc();
|
||||
h.registry
|
||||
.create_agent_draft_version(CreateAgentDraftVersionRequest {
|
||||
workspace_id: &workspace_id(),
|
||||
agent_id: &agent_id(),
|
||||
version: &AgentVersion {
|
||||
agent_id: agent_id(),
|
||||
version: 2,
|
||||
status: AgentStatus::Draft,
|
||||
instructions: json!({}),
|
||||
tool_selection_policy: ToolSelectionPolicy::default(),
|
||||
created_at: now,
|
||||
},
|
||||
bindings: &[
|
||||
AgentOperationBinding {
|
||||
operation_id: crank_core::OperationId::new("op_create_lead"),
|
||||
operation_version: 1,
|
||||
tool_name: TOOL_NAME.into(),
|
||||
tool_title: "Create Lead".into(),
|
||||
tool_description_override: None,
|
||||
enabled: true,
|
||||
},
|
||||
AgentOperationBinding {
|
||||
operation_id: operation.id,
|
||||
operation_version: 1,
|
||||
tool_name: "second_lead".into(),
|
||||
tool_title: "Second Lead".into(),
|
||||
tool_description_override: None,
|
||||
enabled: true,
|
||||
},
|
||||
],
|
||||
updated_at: &now,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
h.registry
|
||||
.publish_agent(PublishAgentRequest {
|
||||
workspace_id: &workspace_id(),
|
||||
agent_id: &agent_id(),
|
||||
version: 2,
|
||||
published_at: &now,
|
||||
published_by: Some("alice"),
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
for revision in [LEGACY_REVISION, MODERN_REVISION] {
|
||||
let session = h.session(revision).await;
|
||||
let mut names = Vec::new();
|
||||
for (cursor, expected_next, expected_len) in [
|
||||
(None, Some("1"), 1),
|
||||
(Some("1"), None, 1),
|
||||
(Some("2"), None, 0),
|
||||
] {
|
||||
let id = json!(format!("page-{cursor:?}"));
|
||||
let mut request =
|
||||
json!({"jsonrpc":"2.0","id":id,"method":"tools/list","params":{"limit":1}});
|
||||
if let Some(cursor) = cursor {
|
||||
request["params"]["cursor"] = json!(cursor);
|
||||
}
|
||||
if revision == MODERN_REVISION {
|
||||
request["params"]["_meta"] = modern_meta();
|
||||
}
|
||||
let before = h.counters.sdk_tools_list_result();
|
||||
let body = wire_body(
|
||||
h.post(revision, session.as_deref(), &request).await,
|
||||
&id,
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
assert_era(&body["result"], revision, true);
|
||||
assert_eq!(
|
||||
body["result"].get("nextCursor"),
|
||||
expected_next.map(|s| json!(s)).as_ref()
|
||||
);
|
||||
let tools = body["result"]["tools"].as_array().unwrap();
|
||||
assert_eq!(tools.len(), expected_len);
|
||||
names.extend(
|
||||
tools
|
||||
.iter()
|
||||
.map(|tool| tool["name"].as_str().unwrap().to_owned()),
|
||||
);
|
||||
assert_eq!(h.counters.sdk_tools_list_result() - before, 1);
|
||||
}
|
||||
names.sort();
|
||||
let mut expected = vec![TOOL_NAME.to_owned(), "second_lead".to_owned()];
|
||||
expected.sort();
|
||||
assert_eq!(names, expected);
|
||||
}
|
||||
assert_eq!(h.calls.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
|
||||
fn assert_era(result: &Value, revision: &str, list: bool) {
|
||||
if revision == MODERN_REVISION {
|
||||
assert_eq!(result["resultType"], "complete", "{result}");
|
||||
if list {
|
||||
assert_eq!(result["ttlMs"], 0);
|
||||
assert_eq!(result["cacheScope"], "private");
|
||||
}
|
||||
} else {
|
||||
assert!(result.get("resultType").is_none(), "{result}");
|
||||
assert!(result.get("ttlMs").is_none(), "{result}");
|
||||
assert!(result.get("cacheScope").is_none(), "{result}");
|
||||
}
|
||||
assert!(result.get("_meta").is_none(), "{result}");
|
||||
}
|
||||
|
||||
async fn wire_body(response: reqwest::Response, id: &Value, sse: bool) -> Value {
|
||||
assert_eq!(response.status(), 200);
|
||||
assert_eq!(response.headers()["x-request-id"], REQUEST_ID);
|
||||
assert_eq!(response.headers()["x-trace-id"], TRACE_ID);
|
||||
let content_type = response.headers()["content-type"]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.to_owned();
|
||||
let text = tokio::time::timeout(Duration::from_secs(5), response.text())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let body: Value = if sse {
|
||||
assert!(
|
||||
content_type.starts_with("text/event-stream"),
|
||||
"{content_type}"
|
||||
);
|
||||
let frames: Vec<Value> = text
|
||||
.lines()
|
||||
.filter_map(|line| {
|
||||
line.strip_prefix("data:")
|
||||
.map(|data| serde_json::from_str(data.trim()).unwrap())
|
||||
})
|
||||
.collect();
|
||||
let terminal: Vec<_> = frames
|
||||
.iter()
|
||||
.filter(|frame| frame.get("id") == Some(id))
|
||||
.collect();
|
||||
assert_eq!(terminal.len(), 1, "{frames:?}");
|
||||
assert_eq!(frames.last(), Some(terminal[0]), "terminal must be last");
|
||||
assert!(
|
||||
frames
|
||||
.iter()
|
||||
.any(|frame| frame["method"] == "notifications/progress"
|
||||
&& frame["params"]["progressToken"] == "result-progress"),
|
||||
"{frames:?}"
|
||||
);
|
||||
terminal[0].clone()
|
||||
} else {
|
||||
assert!(
|
||||
content_type.starts_with("application/json"),
|
||||
"{content_type}"
|
||||
);
|
||||
serde_json::from_str(&text).unwrap()
|
||||
};
|
||||
assert_eq!(body["jsonrpc"], "2.0");
|
||||
assert_eq!(&body["id"], id);
|
||||
body
|
||||
}
|
||||
|
||||
fn assert_call_result(body: &Value, revision: &str, email: &str) {
|
||||
assert!(body.get("error").is_none(), "{body}");
|
||||
let result = &body["result"];
|
||||
assert_era(result, revision, false);
|
||||
let (output, text, is_error) = if email == ERROR_EMAIL {
|
||||
let contract = crate::tool_error::tool_error_contract_from_runtime(
|
||||
&crank_runtime::RuntimeError::ProtocolAdapter(
|
||||
crank_core::ProtocolAdapterError::UnexpectedStatus {
|
||||
status: 422,
|
||||
dispatch: crank_core::DispatchEvidence::MayHaveDispatched,
|
||||
},
|
||||
),
|
||||
REQUEST_ID,
|
||||
TRACE_ID,
|
||||
crank_core::ExecutionLocale::En,
|
||||
);
|
||||
(
|
||||
json!({"error":crate::tool_error::tool_error_value(&contract)}),
|
||||
crate::tool_error::tool_error_text(&contract),
|
||||
true,
|
||||
)
|
||||
} else {
|
||||
let output = json!({"id":format!("lead_for_{email}")});
|
||||
let text = serde_json::to_string_pretty(&output).unwrap();
|
||||
(output, text, false)
|
||||
};
|
||||
assert_eq!(result["structuredContent"], output, "{body}");
|
||||
assert_eq!(result["content"], json!([{"type":"text", "text":text}]));
|
||||
assert_eq!(result["isError"], is_error);
|
||||
assert_eq!(
|
||||
result.as_object().unwrap().len(),
|
||||
if revision == MODERN_REVISION { 4 } else { 3 },
|
||||
"no unexpected optional fields: {result}"
|
||||
);
|
||||
}
|
||||
|
||||
async fn result_control(revision: &str) -> Vec<usize> {
|
||||
let h = Endpoint::started().await;
|
||||
let session = h.session(revision).await;
|
||||
let session = session.as_deref();
|
||||
let mut counts = Vec::new();
|
||||
// Actual published descriptor and schema, then the empty page at the catalog boundary.
|
||||
for (cursor, expected_tools, id) in [
|
||||
(
|
||||
None,
|
||||
json!([{"name":TOOL_NAME,"title":"Create Lead","description":"Creates a CRM lead","inputSchema":{"type":"object","properties":{"email":{"type":"string"}},"required":["email"]}}]),
|
||||
json!("list-string-id"),
|
||||
),
|
||||
(Some("1"), json!([]), json!(9007199254740993_u64)),
|
||||
] {
|
||||
let mut request =
|
||||
json!({"jsonrpc":"2.0","id":id,"method":"tools/list","params":{"limit":1}});
|
||||
if revision == MODERN_REVISION {
|
||||
request["params"]["_meta"] = modern_meta();
|
||||
}
|
||||
if let Some(cursor) = cursor {
|
||||
request["params"]["cursor"] = json!(cursor);
|
||||
}
|
||||
let before = h.counters.sdk_tools_list_result();
|
||||
let before_call = h.counters.sdk_tools_call_result();
|
||||
let before_dispatch = h.counters.sdk_tools_dispatch();
|
||||
let body = wire_body(h.post(revision, session, &request).await, &id, false).await;
|
||||
assert!(body.get("error").is_none(), "{body}");
|
||||
assert_eq!(body["result"]["tools"], expected_tools);
|
||||
assert!(body["result"].get("nextCursor").is_none(), "{body}");
|
||||
assert_era(&body["result"], revision, true);
|
||||
assert_eq!(h.counters.sdk_tools_call_result(), before_call);
|
||||
assert_eq!(h.counters.sdk_tools_dispatch() - before_dispatch, 1);
|
||||
counts.push(h.counters.sdk_tools_list_result() - before);
|
||||
}
|
||||
assert_eq!(h.calls.load(Ordering::SeqCst), 0);
|
||||
for (email, id, sse) in [
|
||||
(
|
||||
"result-success@example.test",
|
||||
json!(9007199254740993_u64),
|
||||
false,
|
||||
),
|
||||
(ERROR_EMAIL, json!("tool-error-string-id"), false),
|
||||
("result-sse@example.test", json!("sse-string-id"), true),
|
||||
(ERROR_EMAIL, json!(92), true),
|
||||
] {
|
||||
if sse && revision != MODERN_REVISION {
|
||||
continue;
|
||||
}
|
||||
let mut request = if revision == MODERN_REVISION {
|
||||
modern_tool_call(90, email)
|
||||
} else {
|
||||
legacy_tool_call(90, email)
|
||||
};
|
||||
request["id"] = id.clone();
|
||||
if sse {
|
||||
request["params"]["_meta"]["progressToken"] = json!("result-progress");
|
||||
}
|
||||
let before = h.counters.sdk_tools_call_result();
|
||||
let before_list = h.counters.sdk_tools_list_result();
|
||||
let before_dispatch = h.counters.sdk_tools_dispatch();
|
||||
let arrivals = h.calls.load(Ordering::SeqCst);
|
||||
let response = h
|
||||
.post_accept(
|
||||
revision,
|
||||
session,
|
||||
&request,
|
||||
if sse {
|
||||
"application/json, text/event-stream"
|
||||
} else {
|
||||
"application/json"
|
||||
},
|
||||
)
|
||||
.await;
|
||||
let body = wire_body(response, &id, sse).await;
|
||||
assert_call_result(&body, revision, email);
|
||||
assert_eq!(h.calls.load(Ordering::SeqCst) - arrivals, 1);
|
||||
assert_eq!(h.counters.sdk_tools_list_result(), before_list);
|
||||
assert_eq!(h.counters.sdk_tools_dispatch() - before_dispatch, 1);
|
||||
counts.push(h.counters.sdk_tools_call_result() - before);
|
||||
}
|
||||
// Unknown tool is a command InvalidParams, not an execution tool-error result.
|
||||
let mut invalid = if revision == MODERN_REVISION {
|
||||
modern_tool_call(93, "unused@example.test")
|
||||
} else {
|
||||
legacy_tool_call(93, "unused@example.test")
|
||||
};
|
||||
invalid["params"]["name"] = json!("missing_tool");
|
||||
invalid["id"] = json!("invalid-params-id");
|
||||
let before = h.counters.sdk_tools_call_result();
|
||||
let arrivals = h.calls.load(Ordering::SeqCst);
|
||||
let body = wire_body(
|
||||
h.post(revision, session, &invalid).await,
|
||||
&invalid["id"],
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(body["error"]["code"], -32602, "{body}");
|
||||
assert!(body.get("result").is_none(), "{body}");
|
||||
assert_eq!(body["error"]["data"]["request_id"], REQUEST_ID);
|
||||
assert_eq!(body["error"]["data"]["trace_id"], TRACE_ID);
|
||||
assert_eq!(h.counters.sdk_tools_call_result(), before);
|
||||
assert_eq!(h.calls.load(Ordering::SeqCst), arrivals);
|
||||
eprintln!(
|
||||
"existing GREEN result wire {revision}: published list/schema + empty page, exact success/error JSON{}; InvalidParams/no result/no marker/no outbound; SDK result deltas={counts:?}",
|
||||
if revision == MODERN_REVISION {
|
||||
" + success/error terminal SSE"
|
||||
} else {
|
||||
" (legacy JSON-only)"
|
||||
}
|
||||
);
|
||||
counts
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_result_wire_modern() {
|
||||
result_control(MODERN_REVISION).await;
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_result_wire_legacy() {
|
||||
result_control(LEGACY_REVISION).await;
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_result_sdk_serialization_modern() {
|
||||
assert_eq!(
|
||||
result_control(MODERN_REVISION).await,
|
||||
vec![1; 6],
|
||||
"structural oracle: SDK list/final-empty/success/error/SSE-success/SSE-error must each serialize once after successful real HTTP wire controls"
|
||||
);
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_result_sdk_serialization_legacy() {
|
||||
assert_eq!(
|
||||
result_control(LEGACY_REVISION).await,
|
||||
vec![1; 4],
|
||||
"structural oracle: SDK list/final-empty/success/error must each serialize once after successful real HTTP wire controls"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_result_observer_scope_control() {
|
||||
use crate::app::dispatch_observer::{
|
||||
sdk_tools_call_result_serialized, sdk_tools_list_result_serialized,
|
||||
};
|
||||
let a = Arc::new(CounterSet::default());
|
||||
let b = Arc::new(CounterSet::default());
|
||||
sdk_tools_list_result_serialized();
|
||||
sdk_tools_call_result_serialized();
|
||||
assert_eq!(
|
||||
(a.sdk_tools_list_result(), a.sdk_tools_call_result()),
|
||||
(0, 0)
|
||||
);
|
||||
observe(a.clone(), async {
|
||||
sdk_tools_list_result_serialized();
|
||||
sdk_tools_call_result_serialized();
|
||||
})
|
||||
.await;
|
||||
// A different request cannot alter a's result counters.
|
||||
observe(b.clone(), async {
|
||||
sdk_tools_list_result_serialized();
|
||||
})
|
||||
.await;
|
||||
assert_eq!(
|
||||
(a.sdk_tools_list_result(), a.sdk_tools_call_result()),
|
||||
(1, 1)
|
||||
);
|
||||
assert_eq!(
|
||||
(b.sdk_tools_list_result(), b.sdk_tools_call_result()),
|
||||
(1, 0)
|
||||
);
|
||||
// Prove the stream-body scope actually records deferred work after the header scope ended.
|
||||
let stream_counters = b.clone();
|
||||
let body = Body::from_stream(stream::once(async move {
|
||||
sdk_tools_call_result_serialized();
|
||||
Ok::<_, std::convert::Infallible>("terminal")
|
||||
}));
|
||||
let response = observe_body(Response::new(body), stream_counters);
|
||||
let bytes = axum::body::to_bytes(response.into_body(), 100)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(&bytes[..], b"terminal");
|
||||
assert_eq!(b.sdk_tools_call_result(), 1);
|
||||
assert_eq!(a.sdk_tools_call_result(), 1);
|
||||
}
|
||||
@@ -0,0 +1,385 @@
|
||||
//! #107: real build_app endpoint controls plus a separate SDK structural seam oracle.
|
||||
//! No SDK transport router is used. The structural oracle alone does not prove wire parity.
|
||||
|
||||
use std::{
|
||||
sync::{
|
||||
Arc,
|
||||
atomic::{AtomicUsize, Ordering},
|
||||
},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use axum::{Router, routing::post};
|
||||
use crank_core::{
|
||||
AgentOperationBinding, AgentStatus, AgentVersion, PlatformApiKeyId, ToolSelectionPolicy,
|
||||
};
|
||||
use crank_registry::{
|
||||
CreateAgentDraftVersionRequest, PostgresRegistry, PublishAgentRequest, PublishRequest,
|
||||
};
|
||||
use crank_runtime::{
|
||||
InMemoryCoordinationStateStore, RequestRateLimitConfig, RequestRateLimiter, SecretCrypto,
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{CounterSet, observe, sdk_tools_dispatch_enter, support::*};
|
||||
|
||||
#[path = "rmcp_result_runtime_tests.rs"]
|
||||
mod result_serialization;
|
||||
|
||||
struct Server(tokio::task::JoinHandle<()>, String);
|
||||
|
||||
impl Drop for Server {
|
||||
fn drop(&mut self) {
|
||||
self.0.abort();
|
||||
}
|
||||
}
|
||||
|
||||
async fn serve(app: Router) -> Server {
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let address = listener.local_addr().unwrap();
|
||||
Server(
|
||||
tokio::spawn(async move {
|
||||
axum::serve(listener, app).await.unwrap();
|
||||
}),
|
||||
format!("http://{address}"),
|
||||
)
|
||||
}
|
||||
|
||||
struct Endpoint {
|
||||
server: Server,
|
||||
_upstream: Server,
|
||||
registry: PostgresRegistry,
|
||||
key: String,
|
||||
counters: Arc<CounterSet>,
|
||||
calls: Arc<AtomicUsize>,
|
||||
}
|
||||
|
||||
impl Endpoint {
|
||||
async fn started() -> Self {
|
||||
// First caller owns the process-wide fixture and its atexit cleanup, including RED panics.
|
||||
let _ =
|
||||
crank_test_support::postgres_schema_url_for_task("rmcp_runtime_owner", "t_c559abb1")
|
||||
.await;
|
||||
let registry = test_registry().await;
|
||||
let calls = Arc::new(AtomicUsize::new(0));
|
||||
let upstream = serve(
|
||||
Router::new()
|
||||
.route("/crm/leads", post(result_serialization::upstream))
|
||||
.with_state(calls.clone()),
|
||||
)
|
||||
.await;
|
||||
let operation = test_operation(&upstream.1);
|
||||
registry
|
||||
.create_operation(&workspace_id(), &operation, Some("alice"))
|
||||
.await
|
||||
.unwrap();
|
||||
registry
|
||||
.publish_operation(PublishRequest {
|
||||
workspace_id: &workspace_id(),
|
||||
operation_id: &operation.id,
|
||||
version: 1,
|
||||
published_at: &test_time(),
|
||||
published_by: Some("alice"),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
publish_agent(®istry, &operation).await;
|
||||
let key = create_api_key(®istry).await;
|
||||
let counters = Arc::new(CounterSet::default());
|
||||
let app = crate::build_app(
|
||||
registry.clone(),
|
||||
Duration::ZERO,
|
||||
Some("https://crank.example.com".into()),
|
||||
SecretCrypto::new("test-master-key-00000000000000000000000000000000").unwrap(),
|
||||
crank_runtime::community_with_outbound_policy(
|
||||
crank_runtime::OutboundHttpPolicy::allowing_hosts(["127.0.0.1"]),
|
||||
)
|
||||
.build(),
|
||||
RequestRateLimiter::new(RequestRateLimitConfig::new(10_000, 10_000).unwrap()),
|
||||
Arc::new(InMemoryCoordinationStateStore::default()),
|
||||
Arc::new(crate::session::InMemorySessionStore::default()),
|
||||
Arc::new(crate::auth::CommunityMachineCredentialVerifier),
|
||||
);
|
||||
let app = observe_requests(app, counters.clone(), None).layer(axum::middleware::from_fn({
|
||||
let counters = counters.clone();
|
||||
move |request: axum::extract::Request, next: axum::middleware::Next| {
|
||||
let counters = counters.clone();
|
||||
async move {
|
||||
let response = next.run(request).await;
|
||||
result_serialization::observe_body(response, counters)
|
||||
}
|
||||
}
|
||||
}));
|
||||
let server = serve(app).await;
|
||||
Self {
|
||||
server,
|
||||
_upstream: upstream,
|
||||
registry,
|
||||
key,
|
||||
counters,
|
||||
calls,
|
||||
}
|
||||
}
|
||||
|
||||
async fn post(&self, revision: &str, session: Option<&str>, body: &Value) -> reqwest::Response {
|
||||
self.post_accept(revision, session, body, "application/json")
|
||||
.await
|
||||
}
|
||||
|
||||
async fn post_accept(
|
||||
&self,
|
||||
revision: &str,
|
||||
session: Option<&str>,
|
||||
body: &Value,
|
||||
accept: &str,
|
||||
) -> reqwest::Response {
|
||||
let mut request = reqwest::Client::new()
|
||||
.post(format!(
|
||||
"{}/v1/{WORKSPACE_SLUG}/{AGENT_SLUG}",
|
||||
self.server.1
|
||||
))
|
||||
.bearer_auth(&self.key)
|
||||
// Also guards the legacy JSON-only contract; no SSE parsing fallback here.
|
||||
.header("Accept", accept)
|
||||
.header("x-request-id", "sdk-result-wire")
|
||||
.header(
|
||||
"traceparent",
|
||||
"00-11111111111111111111111111111111-2222222222222222-01",
|
||||
)
|
||||
.header("MCP-Protocol-Version", revision);
|
||||
if let Some(session) = session {
|
||||
request = request.header("MCP-Session-Id", session);
|
||||
}
|
||||
if revision == MODERN_REVISION {
|
||||
request = request.header("Mcp-Method", body["method"].as_str().unwrap());
|
||||
if let Some(name) = body["params"]["name"].as_str() {
|
||||
request = request.header("Mcp-Name", name);
|
||||
}
|
||||
}
|
||||
request.json(body).send().await.unwrap()
|
||||
}
|
||||
|
||||
async fn session(&self, revision: &str) -> Option<String> {
|
||||
if revision == MODERN_REVISION {
|
||||
return None;
|
||||
}
|
||||
let response = self.post(revision, None, &legacy_initialize(1)).await;
|
||||
assert_eq!(response.status(), 200);
|
||||
let session = response.headers()["MCP-Session-Id"]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.to_owned();
|
||||
let body = json_body(response).await;
|
||||
assert_eq!(body["result"]["protocolVersion"], revision);
|
||||
assert!(body["result"]["capabilities"]["tools"].is_object());
|
||||
let response = self
|
||||
.post(revision, Some(&session), &initialized_notification())
|
||||
.await;
|
||||
assert_eq!(response.status(), 202);
|
||||
Some(session)
|
||||
}
|
||||
|
||||
async fn list(&self, revision: &str, session: Option<&str>, expected_name: &str) -> usize {
|
||||
let before = self.counters.sdk_tools_dispatch();
|
||||
let mut body = json!({"jsonrpc":"2.0", "id":10, "method":"tools/list", "params":{}});
|
||||
if revision == MODERN_REVISION {
|
||||
body["params"]["_meta"] = modern_meta();
|
||||
}
|
||||
let calls = self.calls.load(Ordering::SeqCst);
|
||||
let response = self.post(revision, session, &body).await;
|
||||
assert_eq!(response.status(), 200);
|
||||
assert!(
|
||||
response.headers()["content-type"]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.starts_with("application/json")
|
||||
);
|
||||
let body = json_body(response).await;
|
||||
assert_eq!(body["id"], 10);
|
||||
assert_eq!(body["result"]["tools"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(body["result"]["tools"][0]["name"], expected_name);
|
||||
assert!(body["error"].is_null(), "{body}");
|
||||
assert_eq!(
|
||||
self.calls.load(Ordering::SeqCst),
|
||||
calls,
|
||||
"listing must not execute upstream"
|
||||
);
|
||||
self.counters.sdk_tools_dispatch() - before
|
||||
}
|
||||
|
||||
async fn call(&self, revision: &str, session: Option<&str>, name: &str, email: &str) -> usize {
|
||||
let before = self.counters.sdk_tools_dispatch();
|
||||
let arrivals = self.calls.load(Ordering::SeqCst);
|
||||
let mut body = if revision == MODERN_REVISION {
|
||||
modern_tool_call(11, email)
|
||||
} else {
|
||||
legacy_tool_call(11, email)
|
||||
};
|
||||
body["params"]["name"] = json!(name);
|
||||
let response = self.post(revision, session, &body).await;
|
||||
assert_eq!(response.status(), 200);
|
||||
assert!(
|
||||
response.headers()["content-type"]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.starts_with("application/json")
|
||||
);
|
||||
let body = json_body(response).await;
|
||||
assert_eq!(body["id"], 11);
|
||||
assert!(body["error"].is_null(), "{body}");
|
||||
assert_ne!(body["result"]["isError"], true, "{body}");
|
||||
assert_scoped_output(revision, &body, email);
|
||||
if revision == MODERN_REVISION {
|
||||
assert_eq!(body["result"]["resultType"], "complete");
|
||||
}
|
||||
assert_eq!(self.calls.load(Ordering::SeqCst) - arrivals, 1);
|
||||
self.counters.sdk_tools_dispatch() - before
|
||||
}
|
||||
|
||||
async fn publish_renamed_tool(&self) {
|
||||
let now = time::OffsetDateTime::now_utc();
|
||||
let version = AgentVersion {
|
||||
agent_id: agent_id(),
|
||||
version: 2,
|
||||
status: AgentStatus::Draft,
|
||||
instructions: json!({}),
|
||||
tool_selection_policy: ToolSelectionPolicy::default(),
|
||||
created_at: now,
|
||||
};
|
||||
let bindings = [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,
|
||||
}];
|
||||
self.registry
|
||||
.create_agent_draft_version(CreateAgentDraftVersionRequest {
|
||||
workspace_id: &workspace_id(),
|
||||
agent_id: &agent_id(),
|
||||
version: &version,
|
||||
bindings: &bindings,
|
||||
updated_at: &now,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
self.registry
|
||||
.publish_agent(PublishAgentRequest {
|
||||
workspace_id: &workspace_id(),
|
||||
agent_id: &agent_id(),
|
||||
version: 2,
|
||||
published_at: &now,
|
||||
published_by: Some("alice"),
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
async fn endpoint_control(revision: &str) -> [usize; 2] {
|
||||
let h = Endpoint::started().await;
|
||||
let session = h.session(revision).await;
|
||||
let session = session.as_deref();
|
||||
let list_dispatches = h.list(revision, session, TOOL_NAME).await;
|
||||
let call_dispatches = h
|
||||
.call(
|
||||
revision,
|
||||
session,
|
||||
TOOL_NAME,
|
||||
&format!("{revision}@example.test"),
|
||||
)
|
||||
.await;
|
||||
// A fresh publication must be visible without reinitialize or a new endpoint.
|
||||
h.publish_renamed_tool().await;
|
||||
h.list(revision, session, "new_publication_tool").await;
|
||||
h.call(
|
||||
revision,
|
||||
session,
|
||||
"new_publication_tool",
|
||||
"new-publication@example.test",
|
||||
)
|
||||
.await;
|
||||
h.registry
|
||||
.revoke_platform_api_key(
|
||||
&workspace_id(),
|
||||
&PlatformApiKeyId::new("pk_dispatch_observer"),
|
||||
&time::OffsetDateTime::now_utc(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let before_sdk = h.counters.sdk_tools_dispatch();
|
||||
let arrivals = h.calls.load(Ordering::SeqCst);
|
||||
let mut denied = if revision == MODERN_REVISION {
|
||||
modern_tool_call(12, "denied@example.test")
|
||||
} else {
|
||||
legacy_tool_call(12, "denied@example.test")
|
||||
};
|
||||
denied["params"]["name"] = json!("new_publication_tool");
|
||||
assert_eq!(h.post(revision, session, &denied).await.status(), 401);
|
||||
assert_eq!(
|
||||
h.calls.load(Ordering::SeqCst),
|
||||
arrivals,
|
||||
"revoked credential must not execute upstream"
|
||||
);
|
||||
assert_eq!(
|
||||
h.counters.sdk_tools_dispatch(),
|
||||
before_sdk,
|
||||
"revocation must reject before SDK dispatch"
|
||||
);
|
||||
eprintln!(
|
||||
"existing GREEN {revision}: JSON list/call, scoped output, upstream=2, publication refresh, revoked=401/no outbound; SDK list/call deltas={:?}",
|
||||
[list_dispatches, call_dispatches]
|
||||
);
|
||||
[list_dispatches, call_dispatches]
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_runtime_existing_wire_modern() {
|
||||
endpoint_control(MODERN_REVISION).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_runtime_existing_wire_legacy() {
|
||||
endpoint_control(LEGACY_REVISION).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_runtime_sdk_dispatch_modern() {
|
||||
let counts = endpoint_control(MODERN_REVISION).await;
|
||||
assert_eq!(
|
||||
counts,
|
||||
[1, 1],
|
||||
"real endpoint tools/list and tools/call must each enter SDK typed dispatch once (structural seam oracle)"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_runtime_sdk_dispatch_legacy() {
|
||||
let counts = endpoint_control(LEGACY_REVISION).await;
|
||||
assert_eq!(
|
||||
counts,
|
||||
[1, 1],
|
||||
"real endpoint tools/list and tools/call must each enter SDK typed dispatch once (structural seam oracle)"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_runtime_observer_is_request_scoped() {
|
||||
let counters = Arc::new(CounterSet::default());
|
||||
sdk_tools_dispatch_enter();
|
||||
assert_eq!(counters.sdk_tools_dispatch(), 0);
|
||||
observe(counters.clone(), async {
|
||||
sdk_tools_dispatch_enter();
|
||||
})
|
||||
.await;
|
||||
assert_eq!(counters.sdk_tools_dispatch(), 1);
|
||||
let other = Arc::new(CounterSet::default());
|
||||
observe(other.clone(), async {
|
||||
sdk_tools_dispatch_enter();
|
||||
})
|
||||
.await;
|
||||
assert_eq!(other.sdk_tools_dispatch(), 1);
|
||||
assert_eq!(counters.sdk_tools_dispatch(), 1);
|
||||
}
|
||||
@@ -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), поставленный в v0.4.0-rc.15. [Решением владельца 08.11.2026](https://git.itexp.me/bsodfather/crank/issues/107#issuecomment-2463) разрешён первый Tools-срез этапа 2 (#107) в действующем endpoint без смены transport. #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 и остальные защитные ограничения сохраняются.
|
||||
|
||||
## Результат
|
||||
|
||||
@@ -31,6 +31,14 @@
|
||||
|
||||
Подключить SDK к действующему пути и перенести стандартные envelopes, dispatch, lifecycle и transport. Порядок переноса устанавливается по результату первого опыта, без параллельных writers одних MCP-файлов.
|
||||
|
||||
Первый срез #107: `build_app` направляет `tools/list` обеих revisions и `tools/call` через `app/rmcp_dispatch.rs`. Параметры rmcp=3.7.0 (`PaginatedRequestParams`/`CallToolRequestParams`) определяют команду существующего shared Tools service; расширения Crank `limit`/confirmation сохраняются отдельно. Потребитель — штатный MCP HTTP клиент, не изолированный router #106. Текущие admission, свежая identity, lifecycle, era-specific ответы и PostgreSQL sessions остаются у прежнего transport; SDK HTTP transport не подключён. В следующем Tools response-срезе `app/response.rs` строит и сериализует настоящие rmcp `ListToolsResult`/`Tool` и `CallToolResult`/`ContentBlock`; эти builders используют оба HTTP dispatch и общий JSON/SSE terminal, а изолированный `rmcp_tools` переиспользует typed builders. Явная проекция сохраняет revision defaults, pretty text, tool-error contract, `isError` и present-null `structuredContent`; после SDK list serialization сохраняются исходные top-level extensions/optional null и непрозрачные annotations/icons. Штатный producer публикует name/title/description/inputSchema: расширения защищены локальной builder-регрессией, а не объявлены новыми runtime-полями. HTTP-тесты проверяют обе revisions, success/tool errors/InvalidParams, ID/correlation, modern SSE terminal и несколько страниц опубликованного каталога. JSON-RPC envelope/status остаются прежней внешней границей; остальные handlers, transport и lifecycle ещё не перенесены. Полный #107 не завершён; проверки #106 не являются доказательством завершения миграции.
|
||||
|
||||
Следующий Resources-срез #107 подключает `resources/list`, `resources/read` и `resources/templates/list` обеих revisions к тому же `app/rmcp_dispatch.rs`: `PaginatedRequestParams`/`ReadResourceRequestParams` передают cursor/URI прежнему shared Resources service, а Crank `limit` сохраняется отдельно. `app/response.rs` сериализует rmcp `ListResourcesResult`/`Resource`, `ReadResourceResult`/`ResourceContents` и `ListResourceTemplatesResult`/`ResourceTemplate` с прежними revision-specific cache defaults. Минимальная lossless-проекция сохраняет Crank template `parameters`, extensions/optional null и непрозрачные annotations/icons. Штатные producers по-прежнему публикуют прежние поля; builder-регрессия не добавляет runtime-возможностей. Потребитель — действующий `build_app` HTTP JSON/SSE terminal. Реальные HTTP-тесты отдельно подтверждают SDK request/result seam и сохранение wire; существующая Resources-матрица проверяет заполненные templates, exact-version binding, text/JSON/blob, scope/revocation и cursors. Handwritten builders этих трёх результатов заменены; domain/storage/auth, envelopes, transport и lifecycle не меняются. Subscribe/unsubscribe/notifications остаются прежними и не объявляются перенесёнными; остальные handlers и полный #107 ещё не завершены.
|
||||
|
||||
Prompts-срез #107 подключает `prompts/list` и `prompts/get` обеих revisions к `app/rmcp_dispatch.rs`: реальные `PaginatedRequestParams`/`GetPromptRequestParams` передают cursor/name и JSON-значения аргументов прежнему shared Prompts service; Crank `limit` сохраняется отдельно. `app/response.rs` сериализует rmcp `ListPromptsResult`/`Prompt` и `GetPromptResult`/`PromptMessage`/`ContentBlock`, используемые штатным `build_app` HTTP JSON/SSE. Lossless-проекция сохраняет typed argument schemas/defaults, extensions/optional null и существующую роль `system`, которую pinned SDK Role не представляет; она восстанавливается после SDK serialization, не меняя опубликованные message boundaries. Прежний dispatch сохраняет revision-specific result/cache projections и ошибки. HTTP ATDD проверяет wire обеих revisions и реальный SDK request/result seam отдельно; affected Prompts/composition regression — exact binding, archive, typed rendering, pinned static/dynamic Resource content и fail-closed dependency errors. Handwritten list/get builders заменены; domain/storage/auth/envelopes/transport/lifecycle не меняются. Completion, notifications/subscriptions/progress/cancel/logging не объявляются перенесёнными. Полный #107 и feature qualification (UI/full/load/p95) этим срезом не завершены.
|
||||
|
||||
Completion-срез #107 на базе rc.20/rmcp3.9.0 подключает `completion/complete` обеих revisions к тому же request-scoped `app/rmcp_dispatch.rs`: настоящие `CompleteRequestParams`/`Reference`/`ArgumentInfo` передают reference и argument прежнему shared service. SDK context представляет только строки, поэтому исходный Crank JSON context сохраняется отдельно без фильтрации/приведения типов и проходит прежнюю domain validation. `app/response.rs` заменяет handwritten completion builder сериализацией `CompleteResult`/`CompletionInfo`, сохраняя omission `hasMore=false`, точный bounded total либо его отсутствие при partial scan и прежнюю внешнюю modern/legacy result projection. Потребитель — штатный `build_app` MCP HTTP JSON/SSE. Runtime ATDD отдельно наблюдает SDK request/result seam и сохранение Prompt/Resource refs, pinned/archive, populated/empty/bounded результатов, safe refusals/context, correlation/IDs и revoked-key rejection. Domain/storage/auth/envelopes/transport/lifecycle не меняются; signals/logging/subscriptions ещё не перенесены. Это не завершение #107, не external-client/feature qualification и не production deployment.
|
||||
|
||||
Проверяемый результат:
|
||||
|
||||
- Через SDK проходят действующие Tools, Resources, Prompts, completion, уведомления и подписки в применимых revisions, а также progress/cancel и существующая logging policy.
|
||||
|
||||
@@ -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.
|
||||
@@ -0,0 +1,267 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Validate an existing draft release before resuming its image build."""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.parse import quote, urlsplit
|
||||
from urllib.request import Request, build_opener
|
||||
|
||||
_HERE = Path(__file__).resolve().parent
|
||||
_ASSETS_SCRIPT = _HERE / "ci-release-assets.py"
|
||||
_spec = importlib.util.spec_from_file_location("ci_release_assets", _ASSETS_SCRIPT)
|
||||
if _spec is None or _spec.loader is None:
|
||||
raise RuntimeError("Could not load release asset helpers")
|
||||
_assets_module = importlib.util.module_from_spec(_spec)
|
||||
sys.modules[_spec.name] = _assets_module
|
||||
_spec.loader.exec_module(_assets_module)
|
||||
|
||||
PublishError = _assets_module.PublishError
|
||||
_NoRedirect = _assets_module._NoRedirect
|
||||
_assets = _assets_module._assets
|
||||
_inputs = _assets_module._inputs
|
||||
_json_request = _assets_module._json_request
|
||||
|
||||
_COMMIT = re.compile(r"[0-9a-fA-F]{40}\Z")
|
||||
_ARCHIVES = re.compile(r"crank-community-(?:admin-api|mcp-server|ui)-.+\.tar\.gz\Z")
|
||||
_MAX_ASSET_SIZE = 512 * 1024 * 1024
|
||||
_MAX_TOTAL_SIZE = 1024 * 1024 * 1024
|
||||
_REQUIRED_SOURCE_STATUSES = (
|
||||
"CI / Required Checks (push)",
|
||||
"CI / Rust Checks (push)",
|
||||
"CI / UI Checks (push)",
|
||||
)
|
||||
|
||||
|
||||
def _fail(message: str) -> None:
|
||||
raise PublishError(message)
|
||||
|
||||
|
||||
def _git(*args: str) -> str:
|
||||
try:
|
||||
result = subprocess.run(
|
||||
["git", *args], check=False, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.DEVNULL, text=True,
|
||||
)
|
||||
except OSError:
|
||||
_fail("Could not inspect checked out Git history")
|
||||
if result.returncode:
|
||||
_fail("Resume source tag is unavailable or is not based on checked out main")
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def _check_source(tag: str, source_sha: str, env: dict[str, str]) -> None:
|
||||
if env.get("GITHUB_EVENT_NAME") != "workflow_dispatch" or env.get("GITHUB_REF") != "refs/heads/main":
|
||||
_fail("Resume is allowed only for manual dispatches from main")
|
||||
if not _COMMIT.fullmatch(source_sha):
|
||||
_fail("RESUME_SOURCE_SHA must be an exact 40-character commit SHA")
|
||||
tag_sha = _git("rev-parse", "--verify", f"refs/tags/{tag}^{{commit}}")
|
||||
if tag_sha.lower() != source_sha.lower():
|
||||
_fail("Release tag does not point to the requested source commit")
|
||||
try:
|
||||
result = subprocess.run(
|
||||
["git", "merge-base", "--is-ancestor", tag_sha, "HEAD"],
|
||||
check=False, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
|
||||
)
|
||||
except OSError:
|
||||
_fail("Could not verify release source ancestry")
|
||||
if result.returncode:
|
||||
_fail("Release source is not an ancestor of checked out main")
|
||||
|
||||
|
||||
def _api_tag_commit(api: str, tag: str, token: str, opener) -> str:
|
||||
result, status = _json_request(
|
||||
opener, "GET", f"{api}/tags/{quote(tag, safe='')}", token
|
||||
)
|
||||
if status != 200 or not isinstance(result, dict) or result.get("name") != tag:
|
||||
_fail("Gitea did not return the requested tag")
|
||||
commit = result.get("commit")
|
||||
if not isinstance(commit, dict) or not isinstance(commit.get("sha"), str):
|
||||
_fail("Gitea returned a malformed tag commit")
|
||||
return commit["sha"]
|
||||
|
||||
|
||||
def _download(origin: str, item: dict, token: str, opener) -> bytes:
|
||||
url = urlsplit(item["browser_download_url"])
|
||||
trusted = urlsplit(origin)
|
||||
if (
|
||||
url.scheme != "https" or url.netloc != trusted.netloc
|
||||
or url.username or url.password or url.fragment or not url.path.startswith("/")
|
||||
):
|
||||
_fail(f"Release asset {item['name']} has an untrusted download URL")
|
||||
size = item["size"]
|
||||
if size < 0 or size > _MAX_ASSET_SIZE:
|
||||
_fail(f"Release asset {item['name']} exceeds the download size limit")
|
||||
request = Request(item["browser_download_url"], headers={"Authorization": f"token {token}"})
|
||||
chunks: list[bytes] = []
|
||||
total = 0
|
||||
try:
|
||||
with opener.open(request, timeout=30) as response:
|
||||
while True:
|
||||
chunk = response.read(min(1024 * 1024, size + 1 - total))
|
||||
if not chunk:
|
||||
break
|
||||
total += len(chunk)
|
||||
if total > size:
|
||||
_fail(f"Release asset {item['name']} size does not match Gitea metadata")
|
||||
chunks.append(chunk)
|
||||
except PublishError:
|
||||
raise
|
||||
except HTTPError as exc:
|
||||
status = exc.code
|
||||
exc.close()
|
||||
_fail(f"Could not download release asset (HTTP {status})")
|
||||
except (URLError, TimeoutError, OSError):
|
||||
_fail("Could not download release asset or request timed out")
|
||||
if total != size:
|
||||
_fail(f"Release asset {item['name']} size does not match Gitea metadata")
|
||||
return b"".join(chunks)
|
||||
|
||||
|
||||
def _sha_manifest(data: bytes, expected: set[str]) -> dict[str, str]:
|
||||
try:
|
||||
lines = data.decode("utf-8").splitlines()
|
||||
except UnicodeDecodeError:
|
||||
_fail("SHA256SUMS is not valid UTF-8")
|
||||
parsed: dict[str, str] = {}
|
||||
for line in lines:
|
||||
match = re.fullmatch(r"([0-9a-fA-F]{64}) [ *](?:dist/)?([^\s/\\]+)", line)
|
||||
if not match or match.group(2) in parsed:
|
||||
_fail("SHA256SUMS has an invalid or duplicate entry")
|
||||
parsed[match.group(2)] = match.group(1).lower()
|
||||
if set(parsed) != expected:
|
||||
_fail("SHA256SUMS does not cover exactly all release payload assets")
|
||||
return parsed
|
||||
|
||||
|
||||
def _verify_payloads(payload: dict[str, bytes], manifest_data: bytes, tag: str) -> dict[str, str]:
|
||||
archives = sorted(name for name in payload if _ARCHIVES.fullmatch(name))
|
||||
checksums = [name for name in payload if name.endswith("-checksums.txt")]
|
||||
sboms = [name for name in payload if name.endswith("-sbom.spdx.json")]
|
||||
expected_archives = {
|
||||
f"crank-community-admin-api-{tag}.tar.gz",
|
||||
f"crank-community-mcp-server-{tag}.tar.gz",
|
||||
f"crank-community-ui-{tag}.tar.gz",
|
||||
}
|
||||
if (
|
||||
set(archives) != expected_archives
|
||||
or checksums != [f"crank-community-{tag}-checksums.txt"]
|
||||
or sboms != [f"crank-community-{tag}-sbom.spdx.json"]
|
||||
):
|
||||
_fail("Draft release is missing an expected archive, checksums file, or SBOM")
|
||||
if len(payload) != 5:
|
||||
_fail("Draft release contains an unexpected payload asset set")
|
||||
manifest = _sha_manifest(manifest_data, set(payload))
|
||||
hashes = {name: hashlib.sha256(data).hexdigest() for name, data in payload.items()}
|
||||
if any(manifest[name] != digest for name, digest in hashes.items()):
|
||||
_fail("SHA256SUMS does not match a release payload asset")
|
||||
try:
|
||||
checksum_lines = payload[checksums[0]].decode("utf-8").splitlines()
|
||||
except UnicodeDecodeError:
|
||||
_fail("Release checksums file is not valid UTF-8")
|
||||
checksum_entries: dict[str, str] = {}
|
||||
for line in checksum_lines:
|
||||
match = re.fullmatch(r"([0-9a-fA-F]{64}) [ *](?:dist/)?([^\s/\\]+)", line)
|
||||
if not match or match.group(2) in checksum_entries:
|
||||
_fail("Release checksums file has an invalid or duplicate entry")
|
||||
checksum_entries[match.group(2)] = match.group(1).lower()
|
||||
if set(checksum_entries) != set(archives) or any(
|
||||
checksum_entries[name] != hashlib.sha256(payload[name]).hexdigest() for name in archives
|
||||
):
|
||||
_fail("Release checksums file does not match all three release archives")
|
||||
return hashes
|
||||
|
||||
|
||||
def _require_source_ci(status_data: object, status_code: int) -> None:
|
||||
if status_code != 200 or not isinstance(status_data, dict):
|
||||
_fail("Could not read required source CI statuses")
|
||||
statuses = status_data.get("statuses")
|
||||
if not isinstance(statuses, list):
|
||||
_fail("Gitea did not return source CI status records")
|
||||
for context in _REQUIRED_SOURCE_STATUSES:
|
||||
matches = [
|
||||
item for item in statuses
|
||||
if isinstance(item, dict) and item.get("context") == context
|
||||
]
|
||||
if not matches:
|
||||
_fail(f"Required source CI status is missing: {context}")
|
||||
if any(not isinstance(item.get("updated_at"), str) for item in matches):
|
||||
_fail(f"Required source CI status has invalid timestamp: {context}")
|
||||
latest = max(matches, key=lambda item: item["updated_at"])
|
||||
if latest.get("status") != "success":
|
||||
_fail(f"Required source CI status is not successful: {context}")
|
||||
|
||||
|
||||
def verify(env=None, opener=None) -> dict[str, object]:
|
||||
env = os.environ if env is None else env
|
||||
origin, api, tag, token = _inputs(env)
|
||||
source_sha = env.get("RESUME_SOURCE_SHA", "")
|
||||
_check_source(tag, source_sha, env)
|
||||
opener = opener or build_opener(_NoRedirect())
|
||||
|
||||
release, status = _json_request(
|
||||
opener, "GET", f"{api}/releases/tags/{quote(tag, safe='')}", token, allow_404=True
|
||||
)
|
||||
if status == 404 or not isinstance(release, dict):
|
||||
_fail("The requested release does not already exist")
|
||||
release_id = release.get("id")
|
||||
if (
|
||||
release.get("tag_name") != tag or release.get("draft") is not True
|
||||
or not isinstance(release_id, int) or release_id <= 0
|
||||
):
|
||||
_fail("The requested release is not the expected existing draft")
|
||||
if _api_tag_commit(api, tag, token, opener).lower() != source_sha.lower():
|
||||
_fail("Gitea tag does not point to the requested source commit")
|
||||
status_data, status_code = _json_request(
|
||||
opener, "GET", f"{api}/commits/{source_sha}/status", token
|
||||
)
|
||||
_require_source_ci(status_data, status_code)
|
||||
existing = _assets(api, release_id, token, opener)
|
||||
if len(existing) != 6:
|
||||
_fail("Draft release must contain exactly the five expected payloads and SHA256SUMS")
|
||||
sums_names = [name for name in existing if name == "SHA256SUMS"]
|
||||
if len(sums_names) != 1:
|
||||
_fail("Draft release must contain one canonical SHA256SUMS asset")
|
||||
if sum(item["size"] for item in existing.values()) > _MAX_TOTAL_SIZE:
|
||||
_fail("Draft release payload exceeds the total download size limit")
|
||||
payload: dict[str, bytes] = {}
|
||||
for name, item in existing.items():
|
||||
payload[name] = _download(origin, item, token, opener)
|
||||
if "SHA256SUMS" not in payload:
|
||||
_fail("Draft release must contain one canonical SHA256SUMS asset")
|
||||
sums = payload.pop("SHA256SUMS")
|
||||
hashes = _verify_payloads(payload, sums, tag)
|
||||
return {
|
||||
"tag": tag,
|
||||
"release_id": release_id,
|
||||
"source_sha": source_sha.lower(),
|
||||
"assets": hashes,
|
||||
}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
try:
|
||||
result = verify()
|
||||
except PublishError as exc:
|
||||
print(f"Gitea release resume: {exc}", file=sys.stderr)
|
||||
return 1
|
||||
output = os.environ.get("GITHUB_OUTPUT")
|
||||
if not output:
|
||||
print("GITHUB_OUTPUT is unavailable", file=sys.stderr)
|
||||
return 1
|
||||
with open(output, "a", encoding="utf-8") as target:
|
||||
target.write(f"release_id={result['release_id']}\n")
|
||||
target.write(f"source_sha={result['source_sha']}\n")
|
||||
target.write(f"release_tag={result['tag']}\n")
|
||||
print(f"Validated existing draft {result['tag']} (id {result['release_id']}) and source CI")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,84 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Fail-closed detector for release-tooling-only CI changes."""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
_SHA = re.compile(r"[0-9a-fA-F]{40}\Z")
|
||||
_ALLOWED = {
|
||||
".gitea/workflows/release.yml",
|
||||
"scripts/scan-images.sh",
|
||||
"scripts/check-image-scan.py",
|
||||
"scripts/ci-release-assets.py",
|
||||
"scripts/ci-release-resume.py",
|
||||
"tests/unit/test_scan_images.py",
|
||||
"tests/unit/test_check_image_scan.py",
|
||||
"tests/unit/test_ci_release_assets.py",
|
||||
"tests/unit/test_ci_release_resume.py",
|
||||
}
|
||||
_ALLOWED_BYTES = {path.encode("utf-8") for path in _ALLOWED}
|
||||
|
||||
|
||||
def _git(repo: Path, *args: str) -> subprocess.CompletedProcess[bytes] | None:
|
||||
try:
|
||||
return subprocess.run(
|
||||
["git", "-C", str(repo), *args],
|
||||
check=False,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.DEVNULL,
|
||||
)
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
|
||||
def release_tooling_only(
|
||||
repo: Path, event_name: str, before_sha: str, pr_base_sha: str, force_full: str
|
||||
) -> bool:
|
||||
if force_full.lower() != "false" or event_name not in {"push", "pull_request"}:
|
||||
return False
|
||||
raw_base = before_sha if event_name == "push" else pr_base_sha
|
||||
if not _SHA.fullmatch(raw_base):
|
||||
return False
|
||||
available = _git(repo, "cat-file", "-e", f"{raw_base}^{{commit}}")
|
||||
if available is None or available.returncode != 0:
|
||||
return False
|
||||
if event_name == "pull_request":
|
||||
merge_base = _git(repo, "merge-base", "HEAD", raw_base)
|
||||
if merge_base is None or merge_base.returncode != 0:
|
||||
return False
|
||||
raw_base = merge_base.stdout.decode("ascii", errors="ignore").strip()
|
||||
if not _SHA.fullmatch(raw_base):
|
||||
return False
|
||||
diff = _git(repo, "diff", "--no-renames", "--name-only", "-z", raw_base, "HEAD")
|
||||
if diff is None or diff.returncode != 0:
|
||||
return False
|
||||
paths = diff.stdout.split(b"\0")
|
||||
paths = [path for path in paths if path]
|
||||
return bool(paths) and all(path in _ALLOWED_BYTES for path in paths)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
env = os.environ
|
||||
ci_only = release_tooling_only(
|
||||
Path.cwd(),
|
||||
env.get("GITEA_EVENT_NAME", ""),
|
||||
env.get("GITEA_EVENT_BEFORE", ""),
|
||||
env.get("GITEA_PR_BASE_SHA", ""),
|
||||
env.get("FORCE_FULL", ""),
|
||||
)
|
||||
output = env.get("GITHUB_OUTPUT")
|
||||
if not output:
|
||||
print("Release-tooling CI scope unavailable; using full Rust checks.")
|
||||
return 0
|
||||
with open(output, "a", encoding="utf-8") as stream:
|
||||
stream.write(f"ci_only={'true' if ci_only else 'false'}\n")
|
||||
print("Release-tooling-only change detected." if ci_only else "Full Rust checks required.")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -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
|
||||
+39
-7
@@ -1,8 +1,8 @@
|
||||
#!/bin/sh
|
||||
# Scan the built Crank server images with a pinned Trivy and fail closed.
|
||||
#
|
||||
# The wrapper downloads and checksum-verifies one fixed Trivy release, downloads
|
||||
# one fresh vulnerability database, then scans every requested image by its
|
||||
# The wrapper loads or downloads and checksum-verifies one fixed Trivy release,
|
||||
# downloads one fresh vulnerability database, then scans every requested image by its
|
||||
# immutable Docker id with a fully pinned policy. It never trusts a local
|
||||
# trivy.yaml, .trivyignore, VEX file or skip list: --config and --ignorefile
|
||||
# point at /dev/null and every inherited TRIVY_* variable is removed before
|
||||
@@ -14,6 +14,7 @@
|
||||
#
|
||||
# db/metadata.json copy of the actual downloaded Trivy DB metadata
|
||||
# db-download.log database download log
|
||||
# scanner-cache-source.log archive source provenance
|
||||
# scanner.json pinned scanner version and scan policy receipt
|
||||
# <NN-slug>.json raw Trivy JSON report per image
|
||||
# <NN-slug>.scan.log Trivy scan log per image
|
||||
@@ -45,6 +46,12 @@ trivy_version="0.70.0"
|
||||
archive="trivy_${trivy_version}_Linux-64bit.tar.gz"
|
||||
expected_sha256="8b4376d5d6befe5c24d503f10ff136d9e0c49f9127a4279fd110b727929a5aa9"
|
||||
download_url="https://github.com/aquasecurity/trivy/releases/download/v${trivy_version}/${archive}"
|
||||
# Fixed GitHub asset ID for the Trivy 0.70.0 Linux 64-bit release archive.
|
||||
asset_api_url="https://api.github.com/repos/aquasecurity/trivy/releases/assets/398381981"
|
||||
tool_cache_root="${RUNNER_TOOL_CACHE:-/opt/hostedtoolcache}"
|
||||
cached_archive="$tool_cache_root/trivy/$trivy_version/$archive"
|
||||
db_repository_primary="ghcr.io/aquasecurity/trivy-db:2"
|
||||
db_repository_fallback="mirror.gcr.io/aquasec/trivy-db:2"
|
||||
|
||||
output_dir="${CRANK_IMAGE_SCAN_OUTPUT_DIR:-.tmp/image-scan-evidence}"
|
||||
if ! mkdir -p "$output_dir"; then
|
||||
@@ -100,11 +107,34 @@ PY
|
||||
exit 2
|
||||
}
|
||||
|
||||
# Download and checksum-verify the pinned scanner exactly once.
|
||||
if ! curl --fail --silent --show-error --location --max-time 300 \
|
||||
"$download_url" --output "$temp_dir/$archive" \
|
||||
>"$output_dir/scanner-download.log" 2>&1; then
|
||||
fail_all "could not download pinned Trivy ${trivy_version}"
|
||||
# Load the exact-version archive from the runner cache when preinstalled;
|
||||
# otherwise use the bounded network routes. The shared cache is read-only here.
|
||||
cache_source_log="$output_dir/scanner-cache-source.log"
|
||||
: > "$cache_source_log"
|
||||
if [ -f "$cached_archive" ]; then
|
||||
printf 'archive_source=runner-tool-cache\n' > "$cache_source_log"
|
||||
if ! cp "$cached_archive" "$temp_dir/$archive"; then
|
||||
fail_all "could not copy the pinned Trivy archive from runner tool cache"
|
||||
fi
|
||||
else
|
||||
printf 'archive_source=network\n' > "$cache_source_log"
|
||||
if ! curl --fail --silent --show-error --location --max-time 300 \
|
||||
"$download_url" --output "$temp_dir/$archive" \
|
||||
>"$output_dir/scanner-download.log" 2>&1; then
|
||||
rm -f "$temp_dir/$archive"
|
||||
if ! curl --fail --silent --show-error --location --max-time 300 \
|
||||
--header 'Accept: application/octet-stream' \
|
||||
"$asset_api_url" --output "$temp_dir/$archive" \
|
||||
>"$output_dir/scanner-api-download.log" 2>&1; then
|
||||
printf 'network_download=failed\n' >> "$cache_source_log"
|
||||
fail_all "could not download pinned Trivy ${trivy_version} from release URL or GitHub asset API"
|
||||
fi
|
||||
printf 'archive_source=github-release-asset-api\n' > "$cache_source_log"
|
||||
printf 'Downloaded pinned Trivy %s from GitHub release asset API.\n' "$trivy_version" \
|
||||
>>"$output_dir/scanner-api-download.log"
|
||||
else
|
||||
printf 'archive_source=github-release-download\n' > "$cache_source_log"
|
||||
fi
|
||||
fi
|
||||
if ! printf '%s %s\n' "$expected_sha256" "$temp_dir/$archive" \
|
||||
| sha256sum --check --status; then
|
||||
@@ -120,6 +150,8 @@ fi
|
||||
|
||||
# Download one fresh vulnerability database; every scan reuses it read-only.
|
||||
if ! "$trivy_bin" image --config /dev/null --download-db-only --cache-dir "$cache_dir" \
|
||||
--db-repository "$db_repository_primary" \
|
||||
--db-repository "$db_repository_fallback" \
|
||||
--no-progress --skip-version-check \
|
||||
>"$output_dir/db-download.log" 2>&1; then
|
||||
fail_all "could not download the Trivy vulnerability database"
|
||||
|
||||
@@ -0,0 +1,238 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
SCRIPT = ROOT / "scripts" / "ci-release-resume.py"
|
||||
spec = importlib.util.spec_from_file_location("ci_release_resume", SCRIPT)
|
||||
assert spec and spec.loader
|
||||
resume = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(resume)
|
||||
|
||||
|
||||
TAG = "v0.4.0-rc.15"
|
||||
SHA = "29ee01b6efced04b027569fbeed2e865991c8f55"
|
||||
FILES = {
|
||||
f"crank-community-admin-api-{TAG}.tar.gz": b"admin archive",
|
||||
f"crank-community-mcp-server-{TAG}.tar.gz": b"mcp archive",
|
||||
f"crank-community-ui-{TAG}.tar.gz": b"ui archive",
|
||||
f"crank-community-{TAG}-checksums.txt": b"",
|
||||
f"crank-community-{TAG}-sbom.spdx.json": b"{}",
|
||||
}
|
||||
|
||||
|
||||
def payloads():
|
||||
files = dict(FILES)
|
||||
archives = [name for name in files if name.endswith(".tar.gz")]
|
||||
files[f"crank-community-{TAG}-checksums.txt"] = "".join(
|
||||
f"{hashlib.sha256(files[name]).hexdigest()} dist/{name}\n" for name in archives
|
||||
).encode()
|
||||
manifest = "".join(
|
||||
f"{hashlib.sha256(data).hexdigest()} {name}\n" for name, data in files.items()
|
||||
).encode()
|
||||
return files, manifest
|
||||
|
||||
|
||||
class ResumeValidationTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.env = {
|
||||
"GITEA_SERVER_URL": "https://git.itexp.me",
|
||||
"GITEA_REPOSITORY": "bsodfather/crank-community",
|
||||
"GITEA_TOKEN": "test-token",
|
||||
"RELEASE_TAG": TAG,
|
||||
"RESUME_SOURCE_SHA": SHA,
|
||||
"GITHUB_EVENT_NAME": "workflow_dispatch",
|
||||
"GITHUB_REF": "refs/heads/main",
|
||||
}
|
||||
self.files, self.manifest = payloads()
|
||||
self.calls = []
|
||||
|
||||
def api(self, _opener, method, url, token, payload=None, allow_404=False):
|
||||
self.calls.append((method, url, payload))
|
||||
if url.endswith("/releases/tags/" + TAG):
|
||||
return ({"id": 426, "tag_name": TAG, "draft": True}, 200)
|
||||
if url.endswith("/tags/" + TAG):
|
||||
return ({"name": TAG, "commit": {"sha": SHA}}, 200)
|
||||
if url.endswith("/commits/" + SHA + "/status"):
|
||||
contexts = {"CI / Required Checks (push)", "CI / Rust Checks (push)", "CI / UI Checks (push)"}
|
||||
return ({
|
||||
"state": "failure",
|
||||
"statuses": [
|
||||
{"context": context, "status": "success", "updated_at": "2026-11-07T10:00:00Z"}
|
||||
for context in contexts
|
||||
] + [
|
||||
{"context": "Community Release (push)", "status": "failure", "updated_at": "2026-11-07T10:01:00Z"}
|
||||
],
|
||||
}, 200)
|
||||
raise AssertionError(f"Unexpected API URL: {url}")
|
||||
|
||||
def assets(self, _api, release_id, token, opener):
|
||||
self.assertEqual(release_id, 426)
|
||||
result = {}
|
||||
for name, data in {**self.files, "SHA256SUMS": self.manifest}.items():
|
||||
result[name] = {"name": name, "id": len(result) + 1, "size": len(data),
|
||||
"browser_download_url": f"https://git.itexp.me/releases/download/{name}"}
|
||||
return result
|
||||
|
||||
def download(self, origin, item, token, opener):
|
||||
self.assertEqual(origin, "https://git.itexp.me")
|
||||
return self.files.get(item["name"], self.manifest)
|
||||
|
||||
def run_verify(self):
|
||||
with (
|
||||
patch.object(resume, "_inputs", return_value=("https://git.itexp.me", "https://git.itexp.me/api/v1/repos/bsodfather/crank-community", TAG, "test-token")),
|
||||
patch.object(resume, "_check_source") as check_source,
|
||||
patch.object(resume, "_json_request", side_effect=self.api),
|
||||
patch.object(resume, "_assets", side_effect=self.assets),
|
||||
patch.object(resume, "_download", side_effect=self.download),
|
||||
):
|
||||
result = resume.verify(self.env, opener=object())
|
||||
check_source.assert_called_once_with(TAG, SHA, self.env)
|
||||
return result
|
||||
|
||||
def test_valid_draft_is_read_only_and_outputs_source_receipt(self):
|
||||
result = self.run_verify()
|
||||
self.assertEqual(result["release_id"], 426)
|
||||
self.assertEqual(result["source_sha"], SHA)
|
||||
self.assertEqual(set(result["assets"]), set(self.files))
|
||||
self.assertTrue(self.calls)
|
||||
self.assertTrue(all(call[0] == "GET" and call[2] is None for call in self.calls))
|
||||
|
||||
def test_missing_release_rejected(self):
|
||||
with patch.object(resume, "_inputs", return_value=("https://git.itexp.me", "https://api", TAG, "token")), \
|
||||
patch.object(resume, "_check_source"), \
|
||||
patch.object(resume, "_json_request", return_value=(None, 404)):
|
||||
with self.assertRaisesRegex(resume.PublishError, "does not already exist"):
|
||||
resume.verify(self.env, opener=object())
|
||||
|
||||
def test_source_mismatch_rejected_before_api(self):
|
||||
with patch.object(resume, "_inputs", return_value=("https://git.itexp.me", "https://api", TAG, "token")), \
|
||||
patch.object(resume, "_check_source", side_effect=resume.PublishError("tag mismatch")), \
|
||||
patch.object(resume, "_json_request") as request:
|
||||
with self.assertRaisesRegex(resume.PublishError, "tag mismatch"):
|
||||
resume.verify(self.env, opener=object())
|
||||
request.assert_not_called()
|
||||
|
||||
def test_api_tag_commit_mismatch_rejected(self):
|
||||
with patch.object(resume, "_inputs", return_value=("https://git.itexp.me", "https://api", TAG, "token")), \
|
||||
patch.object(resume, "_check_source"), \
|
||||
patch.object(resume, "_json_request", side_effect=self.api), \
|
||||
patch.object(resume, "_api_tag_commit", return_value="0" * 40):
|
||||
with self.assertRaisesRegex(resume.PublishError, "Gitea tag does not point"):
|
||||
resume.verify(self.env, opener=object())
|
||||
|
||||
def test_unexpected_asset_set_rejected_before_download(self):
|
||||
assets = self.assets(None, 426, "token", None)
|
||||
assets["unexpected.txt"] = {
|
||||
"name": "unexpected.txt", "id": 99, "size": 0,
|
||||
"browser_download_url": "https://git.itexp.me/unexpected.txt",
|
||||
}
|
||||
with patch.object(resume, "_inputs", return_value=("https://git.itexp.me", "https://api", TAG, "token")), \
|
||||
patch.object(resume, "_check_source"), \
|
||||
patch.object(resume, "_json_request", side_effect=self.api), \
|
||||
patch.object(resume, "_api_tag_commit", return_value=SHA), \
|
||||
patch.object(resume, "_assets", return_value=assets), \
|
||||
patch.object(resume, "_download") as download:
|
||||
with self.assertRaisesRegex(resume.PublishError, "exactly the five expected"):
|
||||
resume.verify(self.env, opener=object())
|
||||
download.assert_not_called()
|
||||
|
||||
def test_required_source_status_missing_or_failed_is_rejected(self):
|
||||
cases = (
|
||||
{"state": "failure", "statuses": []},
|
||||
{"state": "failure", "statuses": [
|
||||
{"context": "CI / Required Checks (push)", "status": "failure", "updated_at": "2026-11-07T10:00:00Z"},
|
||||
{"context": "CI / Rust Checks (push)", "status": "success", "updated_at": "2026-11-07T10:00:00Z"},
|
||||
{"context": "CI / UI Checks (push)", "status": "success", "updated_at": "2026-11-07T10:00:00Z"},
|
||||
]},
|
||||
{"state": "failure", "statuses": [
|
||||
{"context": "CI / Required Checks (push)", "status": "success", "updated_at": "2026-11-07T09:00:00Z"},
|
||||
{"context": "CI / Required Checks (push)", "status": "failure", "updated_at": "2026-11-07T10:00:00Z"},
|
||||
{"context": "CI / Rust Checks (push)", "status": "success", "updated_at": "2026-11-07T10:00:00Z"},
|
||||
{"context": "CI / UI Checks (push)", "status": "success", "updated_at": "2026-11-07T10:00:00Z"},
|
||||
]},
|
||||
)
|
||||
for status_data in cases:
|
||||
with self.subTest(status_data=status_data):
|
||||
with self.assertRaises(resume.PublishError):
|
||||
resume._require_source_ci(status_data, 200)
|
||||
|
||||
def test_missing_expected_asset_rejected(self):
|
||||
files = dict(self.files)
|
||||
files.pop(f"crank-community-{TAG}-sbom.spdx.json")
|
||||
with self.assertRaisesRegex(resume.PublishError, "missing an expected"):
|
||||
resume._verify_payloads(files, self.manifest, TAG)
|
||||
|
||||
def test_checksum_manifest_rejects_missing_or_bad_payload_entries(self):
|
||||
for manifest in (b"", b"0" * 64 + b" wrong.tar.gz\n"):
|
||||
with self.subTest(manifest=manifest):
|
||||
with self.assertRaises(resume.PublishError):
|
||||
resume._verify_payloads(self.files, manifest, TAG)
|
||||
|
||||
def test_checksum_manifest_rejects_mismatched_archive_checksum(self):
|
||||
files = dict(self.files)
|
||||
checksum_name = f"crank-community-{TAG}-checksums.txt"
|
||||
files[checksum_name] = b"0" * 64 + b" crank-community-admin-api-" + TAG.encode() + b".tar.gz\n"
|
||||
updated_manifest = "".join(
|
||||
f"{hashlib.sha256(data).hexdigest()} {name}\n" for name, data in files.items()
|
||||
).encode()
|
||||
with self.assertRaisesRegex(resume.PublishError, "checksums file"):
|
||||
resume._verify_payloads(files, updated_manifest, TAG)
|
||||
|
||||
def test_download_rejects_untrusted_origin_before_network(self):
|
||||
item = {"name": "payload", "size": 1, "browser_download_url": "https://evil.example/payload"}
|
||||
opener = unittest.mock.Mock()
|
||||
with self.assertRaisesRegex(resume.PublishError, "untrusted download URL"):
|
||||
resume._download("https://git.itexp.me", item, "token", opener)
|
||||
opener.open.assert_not_called()
|
||||
|
||||
def test_download_rejects_redirect_without_following(self):
|
||||
class Redirecting:
|
||||
def open(self, request, timeout):
|
||||
raise resume.PublishError("redirect refused")
|
||||
item = {"name": "payload", "size": 1, "browser_download_url": "https://git.itexp.me/payload"}
|
||||
with self.assertRaisesRegex(resume.PublishError, "redirect refused"):
|
||||
resume._download("https://git.itexp.me", item, "token", Redirecting())
|
||||
|
||||
|
||||
class WorkflowResumeTests(unittest.TestCase):
|
||||
def test_resume_selects_tag_source_and_skips_asset_production(self):
|
||||
workflow = (ROOT / ".gitea/workflows/release.yml").read_text()
|
||||
self.assertIn("resume_tag:", workflow)
|
||||
self.assertIn("resume_source_sha:", workflow)
|
||||
self.assertIn("IMAGE_TAG: ${{ inputs.resume_tag || gitea.ref_name }}", workflow)
|
||||
self.assertIn("python3 scripts/ci-release-resume.py", workflow)
|
||||
self.assertIn("ref: ${{ steps.resume.outputs.release_tag }}", workflow)
|
||||
self.assertIn('test "$(git rev-parse HEAD)" = "$EXPECTED_SOURCE_SHA"', workflow)
|
||||
for step in ("Build release binaries", "Build UI dist", "Package release artifacts", "Generate SBOM"):
|
||||
start = workflow.index(f"- name: {step}")
|
||||
self.assertIn("if: inputs.resume_tag == ''", workflow[start : start + 180])
|
||||
self.assertIn("if: inputs.resume_tag == '' && startsWith(gitea.ref, 'refs/tags/v')", workflow)
|
||||
self.assertIn("if: inputs.resume_tag == ''\n run: |\n ls -lh dist", workflow)
|
||||
|
||||
def test_resume_preserves_updated_scanner_before_old_source_checkout(self):
|
||||
workflow = (ROOT / ".gitea/workflows/release.yml").read_text()
|
||||
pin = workflow.index("- name: Preserve updated image scanner for resume")
|
||||
old_checkout = workflow.index("- name: Checkout validated release source")
|
||||
source_assert = workflow.index("- name: Assert exact release source checkout")
|
||||
image_build = workflow.index("- name: Build and push release images")
|
||||
self.assertLess(pin, old_checkout)
|
||||
self.assertLess(old_checkout, source_assert)
|
||||
self.assertLess(source_assert, image_build)
|
||||
pin_step = workflow[pin:old_checkout]
|
||||
self.assertIn("if: inputs.resume_tag != ''", pin_step)
|
||||
self.assertIn('cp scripts/scan-images.sh "$scanner_dir/scan-images.sh"', pin_step)
|
||||
self.assertIn('cp scripts/check-image-scan.py "$scanner_dir/check-image-scan.py"', pin_step)
|
||||
build_step = workflow[image_build:]
|
||||
self.assertIn("RELEASE_IMAGE_SCANNER: ${{ steps.pin_resume_scanner.outputs.path || 'scripts/scan-images.sh' }}", build_step)
|
||||
self.assertIn('"$RELEASE_IMAGE_SCANNER" \\', build_step)
|
||||
self.assertIn("ref: ${{ steps.resume.outputs.release_tag }}", workflow)
|
||||
self.assertIn('test "$(git rev-parse HEAD)" = "$EXPECTED_SOURCE_SHA"', workflow)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,140 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
SCRIPT = ROOT / "scripts" / "ci-release-tooling-scope.py"
|
||||
spec = importlib.util.spec_from_file_location("ci_release_tooling_scope", SCRIPT)
|
||||
assert spec and spec.loader
|
||||
scope = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(scope)
|
||||
|
||||
WORKFLOW = ROOT / ".gitea/workflows/ci.yml"
|
||||
_FALSE = "false"
|
||||
|
||||
|
||||
class ReleaseToolingScopeTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.repo = Path(self.temp.name)
|
||||
self.git("init", "-q")
|
||||
self.git("config", "user.email", "ci-scope@example.test")
|
||||
self.git("config", "user.name", "CI Scope Test")
|
||||
self.write("src/lib.rs", "pub fn initial() {}\n")
|
||||
self.write("scripts/scan-images.sh", "#!/bin/sh\nexit 0\n")
|
||||
self.write("tests/unit/test_scan_images.py", "# initial\n")
|
||||
self.git("add", ".")
|
||||
self.git("commit", "-qm", "baseline")
|
||||
self.base = self.head()
|
||||
|
||||
def git(self, *args: str) -> str:
|
||||
result = subprocess.run(
|
||||
["git", "-C", str(self.repo), *args],
|
||||
check=True,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
text=True,
|
||||
)
|
||||
return result.stdout.strip()
|
||||
|
||||
def head(self) -> str:
|
||||
return self.git("rev-parse", "HEAD")
|
||||
|
||||
def write(self, relative: str, content: str) -> None:
|
||||
path = self.repo / relative
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(content, encoding="utf-8")
|
||||
|
||||
def commit(self, message: str = "change") -> None:
|
||||
self.git("add", "-A")
|
||||
self.git("commit", "-qm", message)
|
||||
|
||||
def classify(self, event="push", before=None, base=None, force=_FALSE) -> bool:
|
||||
return scope.release_tooling_only(
|
||||
self.repo,
|
||||
event,
|
||||
self.base if before is None else before,
|
||||
self.base if base is None else base,
|
||||
force,
|
||||
)
|
||||
|
||||
def test_release_only_diff_is_safe_for_push_and_pull_request(self):
|
||||
self.write(".gitea/workflows/release.yml", "# release tooling update\n")
|
||||
self.write("scripts/scan-images.sh", "#!/bin/sh\n# scanner update\n")
|
||||
self.commit()
|
||||
self.assertTrue(self.classify("push", before=self.base))
|
||||
self.assertTrue(self.classify("pull_request", base=self.base))
|
||||
|
||||
def test_rust_or_mixed_diff_requires_full_ci(self):
|
||||
self.write("src/lib.rs", "pub fn changed() {}\n")
|
||||
self.commit("Rust change")
|
||||
self.assertFalse(self.classify("push", before=self.base))
|
||||
|
||||
self.write("scripts/scan-images.sh", "#!/bin/sh\n# tooling change\n")
|
||||
self.write("src/lib.rs", "pub fn changed_again() {}\n")
|
||||
self.commit("mixed change")
|
||||
self.assertFalse(self.classify("push", before=self.base))
|
||||
|
||||
def test_rename_from_rust_into_allowlist_is_not_safe(self):
|
||||
(self.repo / ".gitea/workflows").mkdir(parents=True)
|
||||
self.git("mv", "src/lib.rs", ".gitea/workflows/release.yml")
|
||||
self.commit("rename Rust source into release path")
|
||||
self.assertFalse(self.classify("push", before=self.base))
|
||||
|
||||
def test_unavailable_zero_empty_and_missing_bases_require_full_ci(self):
|
||||
self.write("scripts/scan-images.sh", "#!/bin/sh\n# allowed\n")
|
||||
self.commit()
|
||||
self.assertFalse(self.classify("push", before=""))
|
||||
self.assertFalse(self.classify("push", before="0" * 40))
|
||||
self.assertFalse(self.classify("push", before="1" * 40))
|
||||
self.assertFalse(self.classify("push", before=self.head()))
|
||||
self.assertFalse(self.classify("pull_request", base=""))
|
||||
|
||||
def test_manual_feature_and_unknown_force_metadata_require_full_ci(self):
|
||||
self.write("scripts/scan-images.sh", "#!/bin/sh\n# allowed\n")
|
||||
self.commit()
|
||||
self.assertFalse(self.classify("workflow_dispatch", before=self.base))
|
||||
self.assertFalse(self.classify("push", before=self.base, force="true"))
|
||||
self.assertFalse(self.classify("push", before=self.base, force=""))
|
||||
|
||||
def test_non_allowlisted_ci_self_change_requires_full_ci(self):
|
||||
self.write(".gitea/workflows/ci.yml", "# detector workflow change\n")
|
||||
self.commit()
|
||||
self.assertFalse(self.classify("push", before=self.base))
|
||||
|
||||
|
||||
class WorkflowScopeTests(unittest.TestCase):
|
||||
def test_only_four_heavy_rust_steps_are_skippable(self):
|
||||
workflow = WORKFLOW.read_text(encoding="utf-8")
|
||||
self.assertIn("run: python3 scripts/ci-release-tooling-scope.py", workflow)
|
||||
self.assertIn("FORCE_FULL: ${{ inputs.validation_level == 'feature' || contains(gitea.event.pull_request.labels.*.name, 'feature-ready') }}", workflow)
|
||||
conditional = "if: steps.release_tooling.outputs.ci_only != 'true'"
|
||||
for name in (
|
||||
"Check typed runtime configuration contract",
|
||||
"Check canonical migration contract",
|
||||
"Check typed metrics contract",
|
||||
"Run Crank story ATDD",
|
||||
):
|
||||
start = workflow.index(f"- name: {name}")
|
||||
self.assertIn(conditional, workflow[start : start + 180])
|
||||
for name in (
|
||||
"Install Rust toolchain",
|
||||
"Run tooling unit tests",
|
||||
"Check formatting",
|
||||
"Check Rust boundaries",
|
||||
"Check OpenAPI matrix and corpus compatibility versions",
|
||||
):
|
||||
start = workflow.index(f"- name: {name}")
|
||||
self.assertNotIn("if:", workflow[start : start + 160])
|
||||
self.assertIn("name: Rust Checks", workflow)
|
||||
self.assertIn("name: UI Checks", workflow)
|
||||
self.assertIn("name: Required Checks", workflow)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -27,9 +27,18 @@ import os
|
||||
import sys
|
||||
|
||||
args = sys.argv[1:]
|
||||
if os.environ.get("FAKE_CURL_FAIL") == "1":
|
||||
sys.stderr.write("curl: (7) failed to connect\\n")
|
||||
url = next((value for value in args if value.startswith("https://")), "")
|
||||
api_download = url == "https://api.github.com/repos/aquasecurity/trivy/releases/assets/398381981"
|
||||
failed = os.environ.get("FAKE_CURL_FAIL") == "1"
|
||||
failed = failed or (not api_download and os.environ.get("FAKE_CURL_DIRECT_FAIL") == "1")
|
||||
failed = failed or (api_download and os.environ.get("FAKE_CURL_API_FAIL") == "1")
|
||||
if failed:
|
||||
sys.stderr.write("curl: (22) fixture download failure for " + url + "\\n")
|
||||
sys.exit(7)
|
||||
if api_download:
|
||||
if "--header" not in args or args[args.index("--header") + 1] != "Accept: application/octet-stream":
|
||||
sys.stderr.write("curl: missing octet-stream Accept header\\n")
|
||||
sys.exit(2)
|
||||
output = None
|
||||
for index, value in enumerate(args):
|
||||
if value in ("--output", "-o"):
|
||||
@@ -37,7 +46,8 @@ for index, value in enumerate(args):
|
||||
if output is None:
|
||||
sys.stderr.write("curl: missing --output\\n")
|
||||
sys.exit(2)
|
||||
with open(os.environ["FAKE_CURL_ARCHIVE"], "rb") as source:
|
||||
archive_path = os.environ.get("FAKE_CURL_API_ARCHIVE", os.environ["FAKE_CURL_ARCHIVE"]) if api_download else os.environ["FAKE_CURL_ARCHIVE"]
|
||||
with open(archive_path, "rb") as source:
|
||||
payload = source.read()
|
||||
with open(output, "wb") as target:
|
||||
target.write(payload)
|
||||
@@ -176,6 +186,10 @@ class ScanImagesWrapperTests(unittest.TestCase):
|
||||
images=(VULN_TAG, CLEAN_TAG),
|
||||
trivy_fail_id=None,
|
||||
curl_fail=False,
|
||||
curl_direct_fail=False,
|
||||
curl_api_fail=False,
|
||||
api_checksum_mismatch=False,
|
||||
cache_archive=None,
|
||||
extra_env=None,
|
||||
workdir_files=None,
|
||||
run_in_workdir=False,
|
||||
@@ -214,6 +228,13 @@ class ScanImagesWrapperTests(unittest.TestCase):
|
||||
|
||||
archive_path = root / "trivy-fixture.tar.gz"
|
||||
archive_path.write_bytes(fixture_archive)
|
||||
api_archive_path = root / "trivy-api-fixture.tar.gz"
|
||||
api_archive_path.write_bytes(fixture_archive + b"tampered" if api_checksum_mismatch else fixture_archive)
|
||||
tool_cache = root / "runner-tool-cache"
|
||||
if cache_archive is not None:
|
||||
cached_path = tool_cache / "trivy" / "0.70.0" / "trivy_0.70.0_Linux-64bit.tar.gz"
|
||||
cached_path.parent.mkdir(parents=True)
|
||||
cached_path.write_bytes(fixture_archive if cache_archive == "valid" else b"invalid archive")
|
||||
|
||||
reports = root / "reports"
|
||||
reports.mkdir()
|
||||
@@ -246,8 +267,10 @@ class ScanImagesWrapperTests(unittest.TestCase):
|
||||
env.update(
|
||||
{
|
||||
"PATH": f"{bin_dir}:{env['PATH']}",
|
||||
"RUNNER_TOOL_CACHE": str(tool_cache),
|
||||
"CRANK_IMAGE_SCAN_OUTPUT_DIR": str(evidence),
|
||||
"FAKE_CURL_ARCHIVE": str(archive_path),
|
||||
"FAKE_CURL_API_ARCHIVE": str(api_archive_path),
|
||||
"FAKE_IMAGE_MAP": str(image_map),
|
||||
"FAKE_REPORT_DIR": str(reports),
|
||||
"FAKE_DOCKER_LOG": str(docker_log),
|
||||
@@ -258,6 +281,10 @@ class ScanImagesWrapperTests(unittest.TestCase):
|
||||
env["FAKE_TRIVY_FAIL_ID"] = trivy_fail_id
|
||||
if curl_fail:
|
||||
env["FAKE_CURL_FAIL"] = "1"
|
||||
if curl_direct_fail:
|
||||
env["FAKE_CURL_DIRECT_FAIL"] = "1"
|
||||
if curl_api_fail:
|
||||
env["FAKE_CURL_API_FAIL"] = "1"
|
||||
if extra_env:
|
||||
env.update(extra_env)
|
||||
|
||||
@@ -412,6 +439,18 @@ class ScanImagesWrapperTests(unittest.TestCase):
|
||||
self.assertEqual(result.returncode, 2, result.stderr)
|
||||
self.assertEqual(receipt["overall"]["status"], "error")
|
||||
|
||||
def test_database_download_uses_official_priority_and_fallback(self):
|
||||
result, _, _, _, _, trivy_calls = self.run_scan(images=(CLEAN_TAG,))
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
downloads = [call["args"] for call in trivy_calls if "--download-db-only" in call["args"]]
|
||||
self.assertEqual(len(downloads), 1)
|
||||
args = downloads[0]
|
||||
repositories = [args[index + 1] for index, item in enumerate(args) if item == "--db-repository"]
|
||||
self.assertEqual(
|
||||
repositories,
|
||||
["ghcr.io/aquasecurity/trivy-db:2", "mirror.gcr.io/aquasec/trivy-db:2"],
|
||||
)
|
||||
|
||||
def test_rerun_cannot_reuse_an_old_successful_raw_report(self):
|
||||
result, _, evidence, receipt, _, _ = self.run_scan(images=(CLEAN_TAG,), repeat_without_output=True)
|
||||
self.assertEqual(result.returncode, 2, result.stderr)
|
||||
@@ -430,6 +469,68 @@ class ScanImagesWrapperTests(unittest.TestCase):
|
||||
self.assertEqual(docker_calls, [])
|
||||
self.assertEqual(trivy_calls, [])
|
||||
|
||||
def test_pinned_asset_api_fallback_downloads_and_verifies_same_archive(self):
|
||||
result, _, evidence, receipt, _, trivy_calls = self.run_scan(
|
||||
images=(CLEAN_TAG,), curl_direct_fail=True
|
||||
)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(receipt["overall"]["status"], "pass")
|
||||
self.assertIn("fixture download failure", (evidence / "scanner-download.log").read_text())
|
||||
self.assertIn("GitHub release asset API", (evidence / "scanner-api-download.log").read_text())
|
||||
self.assertTrue(any("--download-db-only" in call["args"] for call in trivy_calls))
|
||||
scanner = json.loads((evidence / "scanner.json").read_text(encoding="utf-8"))
|
||||
self.assertEqual(scanner["expected_version"], "0.70.0")
|
||||
|
||||
def test_pinned_asset_api_fallback_failure_fails_closed_with_both_logs(self):
|
||||
result, _, evidence, receipt, _, trivy_calls = self.run_scan(
|
||||
images=(CLEAN_TAG,), curl_direct_fail=True, curl_api_fail=True
|
||||
)
|
||||
self.assertEqual(result.returncode, 2)
|
||||
self.assertEqual(receipt["overall"]["status"], "error")
|
||||
self.assertIn("fixture download failure", (evidence / "scanner-download.log").read_text())
|
||||
self.assertIn("fixture download failure", (evidence / "scanner-api-download.log").read_text())
|
||||
self.assertEqual(trivy_calls, [])
|
||||
|
||||
def test_pinned_asset_api_fallback_checksum_mismatch_never_executes_trivy(self):
|
||||
result, _, evidence, receipt, _, trivy_calls = self.run_scan(
|
||||
images=(CLEAN_TAG,), curl_direct_fail=True, api_checksum_mismatch=True
|
||||
)
|
||||
self.assertEqual(result.returncode, 2)
|
||||
self.assertEqual(receipt["overall"]["status"], "error")
|
||||
self.assertIn("checksum mismatch", result.stderr)
|
||||
self.assertEqual(trivy_calls, [])
|
||||
|
||||
def test_preloaded_pinned_archive_runs_without_network(self):
|
||||
result, root, evidence, receipt, _, trivy_calls = self.run_scan(
|
||||
images=(CLEAN_TAG,), cache_archive="valid", curl_fail=True
|
||||
)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(receipt["overall"]["status"], "pass")
|
||||
self.assertEqual(
|
||||
(evidence / "scanner-cache-source.log").read_text(),
|
||||
"archive_source=runner-tool-cache\n",
|
||||
)
|
||||
self.assertFalse((evidence / "scanner-download.log").exists())
|
||||
self.assertFalse((evidence / "scanner-api-download.log").exists())
|
||||
cached = root / "runner-tool-cache" / "trivy" / "0.70.0" / "trivy_0.70.0_Linux-64bit.tar.gz"
|
||||
self.assertEqual(cached.read_bytes(), (root / "trivy-fixture.tar.gz").read_bytes())
|
||||
self.assertTrue(any("--download-db-only" in call["args"] for call in trivy_calls))
|
||||
|
||||
def test_preloaded_archive_hash_mismatch_fails_before_network_or_execution(self):
|
||||
result, _, evidence, receipt, _, trivy_calls = self.run_scan(
|
||||
images=(CLEAN_TAG,), cache_archive="bad", curl_fail=True
|
||||
)
|
||||
self.assertEqual(result.returncode, 2)
|
||||
self.assertEqual(receipt["overall"]["status"], "error")
|
||||
self.assertIn("checksum mismatch", result.stderr)
|
||||
self.assertEqual(
|
||||
(evidence / "scanner-cache-source.log").read_text(),
|
||||
"archive_source=runner-tool-cache\n",
|
||||
)
|
||||
self.assertFalse((evidence / "scanner-download.log").exists())
|
||||
self.assertFalse((evidence / "scanner-api-download.log").exists())
|
||||
self.assertEqual(trivy_calls, [])
|
||||
|
||||
def test_unknown_image_is_error_and_is_never_scanned(self):
|
||||
missing = "crank/missing:ci"
|
||||
result, _, _, receipt, _, trivy_calls = self.run_scan(images=(missing, CLEAN_TAG))
|
||||
@@ -445,7 +546,8 @@ class ScanImagesWrapperTests(unittest.TestCase):
|
||||
result, _, evidence, receipt, _, _ = self.run_scan(curl_fail=True)
|
||||
self.assertEqual(result.returncode, 2, result.stderr)
|
||||
self.assertEqual(receipt["overall"]["status"], "error")
|
||||
self.assertIn("failed to connect", (evidence / "scanner-download.log").read_text())
|
||||
self.assertIn("fixture download failure", (evidence / "scanner-download.log").read_text())
|
||||
self.assertIn("fixture download failure", (evidence / "scanner-api-download.log").read_text())
|
||||
|
||||
def test_evidence_kept_even_when_gate_is_red(self):
|
||||
_, _, evidence, receipt, _, _ = self.run_scan()
|
||||
|
||||
Reference in new issue
Block a user