Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
49c8af24ed | ||
|
|
a965bc4137 | ||
|
|
47a6e54660 | ||
|
|
206ca784f7 | ||
|
|
a438c1df42 | ||
|
|
aed83268a0 | ||
|
|
12d8a3d490 | ||
|
|
e57ab47c05 | ||
|
|
1baeefe889 | ||
|
|
9567bbf3aa |
No files matched your search
+134
-90
@@ -2,6 +2,15 @@ name: CI
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types: [opened, synchronize, reopened, labeled, unlabeled]
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
validation_level:
|
||||
description: Validation depth for this run
|
||||
type: choice
|
||||
options: [story, feature]
|
||||
default: story
|
||||
required: true
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
@@ -9,6 +18,8 @@ on:
|
||||
env:
|
||||
CARGO_BUILD_JOBS: "2"
|
||||
CARGO_INCREMENTAL: "0"
|
||||
CARGO_PROFILE_DEV_DEBUG: "0"
|
||||
CARGO_PROFILE_TEST_DEBUG: "0"
|
||||
RUST_TEST_THREADS: "2"
|
||||
TESTCONTAINERS_RYUK_DISABLED: "true"
|
||||
|
||||
@@ -19,7 +30,7 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v5
|
||||
uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
@@ -56,12 +67,6 @@ jobs:
|
||||
docker --version
|
||||
docker info
|
||||
|
||||
- name: Install dependency policy tool
|
||||
run: cargo install cargo-deny --version 0.20.2 --locked
|
||||
|
||||
- name: Run tooling unit tests
|
||||
run: python3 -m unittest discover -s tests/unit
|
||||
|
||||
- name: Check typed runtime configuration contract
|
||||
run: |
|
||||
cargo run -p crank-config --bin crank-config-contract -- --check
|
||||
@@ -76,6 +81,9 @@ jobs:
|
||||
cargo run -p crank-metrics --bin crank-metrics-contract -- --check
|
||||
python3 scripts/check-metrics-boundaries.py --root .
|
||||
|
||||
- name: Run tooling unit tests
|
||||
run: python3 -m unittest discover -s tests/unit
|
||||
|
||||
- name: Check Capability Inventory
|
||||
run: |
|
||||
required_args=""
|
||||
@@ -104,14 +112,10 @@ jobs:
|
||||
- name: Check Rust code health
|
||||
run: scripts/check-rust-code-health.sh
|
||||
|
||||
- name: Check dependency licenses and advisories
|
||||
run: cargo deny --locked check advisories bans licenses sources
|
||||
|
||||
- name: Check Rust boundaries
|
||||
run: scripts/check-rust-boundaries.sh
|
||||
|
||||
- name: Run offline OpenAPI support corpus gate
|
||||
run: cargo test -p crank-import --test corpus -- --test-threads=1
|
||||
|
||||
- name: Check OpenAPI matrix and corpus compatibility versions
|
||||
env:
|
||||
@@ -127,80 +131,15 @@ jobs:
|
||||
fi
|
||||
python3 scripts/check-openapi-matrix-compatibility.py --base "$base_ref"
|
||||
|
||||
- name: Save OpenAPI corpus evidence
|
||||
if: always()
|
||||
uses: https://github.com/ChristopherHX/gitea-upload-artifact@81f940d004763f986ba3582c007fd842dd5cb0d7 # v4
|
||||
with:
|
||||
name: openapi-corpus-evidence
|
||||
path: crates/crank-import/target/openapi-corpus/evidence-*.json
|
||||
if-no-files-found: warn
|
||||
|
||||
- name: Run clippy
|
||||
run: cargo clippy --workspace --all-targets --all-features --jobs "$CARGO_BUILD_JOBS" -- -D warnings
|
||||
|
||||
# One event per change: a feature branch is gated by its pull request, so the push event runs
|
||||
# only on `main` (see `on:` above). No cache and no parallel test shards are configured on
|
||||
# purpose: both need a measured runner/isolation check first (team validation policy), and the
|
||||
# workspace suites already isolate shared databases per test process.
|
||||
#
|
||||
# Story events (`pull_request`) run only the packages the diff touches; the full workspace
|
||||
# suite stays the feature/release gate and runs on `main`.
|
||||
- name: Run story tests (affected packages)
|
||||
if: ${{ gitea.event_name == 'pull_request' }}
|
||||
run: |
|
||||
set -eu
|
||||
base="$(git merge-base HEAD origin/main 2>/dev/null || true)"
|
||||
if [ -z "$base" ]; then
|
||||
git fetch --no-tags origin main
|
||||
base="$(git merge-base HEAD FETCH_HEAD)"
|
||||
fi
|
||||
changed="$(git diff --name-only "$base" HEAD)"
|
||||
packages=""
|
||||
workspace=""
|
||||
for path in $changed; do
|
||||
case "$path" in
|
||||
Cargo.toml|Cargo.lock|rust-toolchain.toml|justfile|vendor/*|crates/Cargo.toml|apps/Cargo.toml)
|
||||
workspace="yes"
|
||||
;;
|
||||
crates/*/*)
|
||||
packages="$packages $(printf '%s' "$path" | cut -d/ -f2)"
|
||||
;;
|
||||
apps/admin-api/*)
|
||||
packages="$packages admin-api"
|
||||
;;
|
||||
apps/mcp-server/*)
|
||||
packages="$packages mcp-server"
|
||||
;;
|
||||
esac
|
||||
done
|
||||
if [ -n "$workspace" ]; then
|
||||
echo "shared build input changed: running the whole workspace"
|
||||
cargo test --workspace --all-targets --jobs "$CARGO_BUILD_JOBS" -- --test-threads=1
|
||||
exit 0
|
||||
fi
|
||||
selected=""
|
||||
for package in $(printf '%s\n' $packages | sort -u); do
|
||||
selected="$selected -p $package"
|
||||
done
|
||||
if [ -z "$selected" ]; then
|
||||
echo "no Rust package changed in this diff; the static checks above are the story gate"
|
||||
exit 0
|
||||
fi
|
||||
echo "story packages:$selected"
|
||||
cargo test $selected --all-targets --jobs "$CARGO_BUILD_JOBS" -- --test-threads=1
|
||||
|
||||
- name: Run full workspace tests (feature/release gate)
|
||||
if: ${{ gitea.event_name != 'pull_request' }}
|
||||
run: cargo test --workspace --all-targets --jobs "$CARGO_BUILD_JOBS" -- --test-threads=1
|
||||
|
||||
- name: Run Crank story ATDD
|
||||
run: scripts/ci-story-checks.sh
|
||||
ui:
|
||||
name: UI Checks
|
||||
runs-on: ubuntu-latest
|
||||
needs: rust
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v5
|
||||
uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
|
||||
|
||||
- name: Verify runner toolchain
|
||||
run: |
|
||||
@@ -208,6 +147,7 @@ jobs:
|
||||
npm --version
|
||||
docker --version
|
||||
|
||||
|
||||
- name: Install UI dependencies
|
||||
working-directory: apps/ui
|
||||
run: npm ci
|
||||
@@ -220,10 +160,74 @@ jobs:
|
||||
working-directory: apps/ui
|
||||
run: npm run build
|
||||
|
||||
rust-feature:
|
||||
needs: rust
|
||||
name: Rust Feature Validation
|
||||
if: >-
|
||||
inputs.validation_level == 'feature' ||
|
||||
contains(gitea.event.pull_request.labels.*.name, 'feature-ready')
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: Install Rust toolchain
|
||||
run: |
|
||||
set -eu
|
||||
toolchain="$(sed -n 's/^channel = "\(.*\)"/\1/p' rust-toolchain.toml | head -n1)"
|
||||
if [ -z "$toolchain" ]; then
|
||||
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')"
|
||||
toolchain_dir="${RUSTUP_HOME:-$HOME/.rustup}/toolchains/${toolchain}-${host}"
|
||||
toolchain_bin="$toolchain_dir/bin"
|
||||
if [ ! -x "$toolchain_bin/rustc" ] || [ ! -x "$toolchain_bin/cargo" ]; then
|
||||
echo "Rust $toolchain was not installed at $toolchain_dir." >&2
|
||||
exit 1
|
||||
fi
|
||||
printf '%s\n' "$toolchain_bin" >> "$GITHUB_PATH"
|
||||
"$toolchain_bin/rustc" --version
|
||||
"$toolchain_bin/cargo" --version
|
||||
"$toolchain_bin/rustfmt" --version
|
||||
"$toolchain_bin/cargo-clippy" --version
|
||||
- name: Verify runner toolchain
|
||||
run: |
|
||||
python3 --version
|
||||
rustc --version
|
||||
cargo --version
|
||||
rustfmt --version
|
||||
cargo clippy --version
|
||||
docker --version
|
||||
docker info
|
||||
- name: Install dependency policy tool
|
||||
run: cargo install cargo-deny --version 0.20.2 --locked
|
||||
- name: Check dependency licenses and advisories
|
||||
run: cargo deny --locked check advisories bans licenses sources
|
||||
- name: Run offline OpenAPI support corpus gate
|
||||
run: cargo test -p crank-import --test corpus -- --test-threads=1
|
||||
- name: Save OpenAPI corpus evidence
|
||||
if: always()
|
||||
uses: https://github.com/ChristopherHX/gitea-upload-artifact@81f940d004763f986ba3582c007fd842dd5cb0d7 # v4
|
||||
with:
|
||||
name: openapi-corpus-evidence
|
||||
path: crates/crank-import/target/openapi-corpus/evidence-*.json
|
||||
if-no-files-found: warn
|
||||
- name: Run clippy
|
||||
run: cargo clippy --workspace --all-targets --all-features --jobs "$CARGO_BUILD_JOBS" -- -D warnings
|
||||
- name: Run tests
|
||||
run: cargo test --workspace --all-targets --jobs "$CARGO_BUILD_JOBS" -- --test-threads=1
|
||||
frontend-e2e:
|
||||
needs: [rust, ui]
|
||||
if: >-
|
||||
inputs.validation_level == 'feature' ||
|
||||
contains(gitea.event.pull_request.labels.*.name, 'feature-ready')
|
||||
name: Frontend E2E
|
||||
runs-on: ubuntu-latest
|
||||
needs: ui
|
||||
services:
|
||||
crank-e2e-postgres:
|
||||
image: postgres:16-alpine
|
||||
@@ -246,7 +250,7 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v5
|
||||
uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
|
||||
|
||||
- name: Install Rust toolchain
|
||||
run: |
|
||||
@@ -324,15 +328,16 @@ jobs:
|
||||
find .tmp/ui-e2e/logs -maxdepth 1 -type f -print -exec sed -n '1,220p' {} \; || true
|
||||
|
||||
deployment:
|
||||
needs: [rust, ui]
|
||||
if: >-
|
||||
inputs.validation_level == 'feature' ||
|
||||
contains(gitea.event.pull_request.labels.*.name, 'feature-ready')
|
||||
name: Community Image Smoke
|
||||
runs-on: ubuntu-latest
|
||||
needs:
|
||||
- rust
|
||||
- ui
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v5
|
||||
uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
|
||||
|
||||
- name: Validate Community deployment manifests
|
||||
run: |
|
||||
@@ -447,14 +452,53 @@ jobs:
|
||||
docker compose -f deploy/community/docker-compose.images.yml \
|
||||
--env-file .tmp/community-smoke.env --profile local-db down -v --remove-orphans || true
|
||||
|
||||
required-checks:
|
||||
name: Required Checks
|
||||
runs-on: ubuntu-latest
|
||||
if: always()
|
||||
needs:
|
||||
- rust
|
||||
- ui
|
||||
- deployment
|
||||
- rust-feature
|
||||
- frontend-e2e
|
||||
steps:
|
||||
- name: Require story gates and mode-appropriate feature gates
|
||||
env:
|
||||
FEATURE_VALIDATION: ${{ inputs.validation_level == 'feature' || contains(gitea.event.pull_request.labels.*.name, 'feature-ready') }}
|
||||
RUST_RESULT: ${{ needs.rust.result }}
|
||||
UI_RESULT: ${{ needs.ui.result }}
|
||||
RUST_FEATURE_RESULT: ${{ needs.rust-feature.result }}
|
||||
E2E_RESULT: ${{ needs.frontend-e2e.result }}
|
||||
IMAGE_RESULT: ${{ needs.deployment.result }}
|
||||
run: |
|
||||
set -eu
|
||||
if [ "$RUST_RESULT" != "success" ] || \
|
||||
[ "$UI_RESULT" != "success" ]; then
|
||||
echo "A required story gate did not succeed." >&2
|
||||
exit 1
|
||||
fi
|
||||
if [ "$FEATURE_VALIDATION" = "true" ]; then
|
||||
if [ "$RUST_FEATURE_RESULT" != "success" ] || \
|
||||
[ "$E2E_RESULT" != "success" ] || \
|
||||
[ "$IMAGE_RESULT" != "success" ]; then
|
||||
echo "A required feature gate did not succeed." >&2
|
||||
exit 1
|
||||
fi
|
||||
else
|
||||
if [ "$RUST_FEATURE_RESULT" != "skipped" ] || \
|
||||
[ "$E2E_RESULT" != "skipped" ] || \
|
||||
[ "$IMAGE_RESULT" != "skipped" ]; then
|
||||
echo "A feature-only gate did not skip in story mode." >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
deploy:
|
||||
name: Deploy
|
||||
runs-on: ubuntu-latest
|
||||
needs:
|
||||
- rust
|
||||
- ui
|
||||
- frontend-e2e
|
||||
- deployment
|
||||
- required-checks
|
||||
if: ${{ gitea.event_name == 'push' && gitea.ref == 'refs/heads/main' }}
|
||||
env:
|
||||
REGISTRY: git.itexp.me
|
||||
@@ -466,7 +510,7 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v5
|
||||
uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
|
||||
|
||||
- name: Verify runner toolchain
|
||||
run: |
|
||||
|
||||
@@ -5,6 +5,13 @@ on:
|
||||
tags:
|
||||
- "v*"
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
validation_level:
|
||||
description: Validation depth for this run
|
||||
type: choice
|
||||
options: [story, feature]
|
||||
default: story
|
||||
required: true
|
||||
|
||||
env:
|
||||
REGISTRY: git.itexp.me
|
||||
@@ -17,10 +24,17 @@ env:
|
||||
jobs:
|
||||
release:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
code: read
|
||||
releases: write
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v5
|
||||
uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
|
||||
- name: Clear optional release evidence
|
||||
run: rm -f .tmp/openapi-playwright.json .tmp/openapi-ui-evidence.json
|
||||
|
||||
|
||||
|
||||
- name: Use preinstalled Rust toolchain
|
||||
run: |
|
||||
@@ -53,7 +67,14 @@ jobs:
|
||||
- name: Install dependency policy tool
|
||||
run: cargo install cargo-deny --version 0.20.2 --locked
|
||||
|
||||
- name: Check formatting
|
||||
run: cargo fmt --all --check
|
||||
|
||||
- name: Audit Rust dependencies
|
||||
run: cargo deny --locked check advisories bans licenses sources
|
||||
|
||||
- name: Run tooling unit tests
|
||||
if: inputs.validation_level == 'feature'
|
||||
run: python3 -m unittest discover -s tests/unit
|
||||
|
||||
- name: Check typed runtime configuration contract
|
||||
@@ -93,16 +114,19 @@ jobs:
|
||||
- name: Check Community scope
|
||||
run: scripts/check-community-scope.sh
|
||||
|
||||
- name: Run Crank story ATDD
|
||||
run: scripts/ci-story-checks.sh
|
||||
|
||||
- name: Run release quality gates
|
||||
if: inputs.validation_level == 'feature'
|
||||
run: |
|
||||
cargo fmt --all --check
|
||||
cargo clippy --workspace --all-targets --all-features -- -D warnings
|
||||
cargo test --workspace --all-targets -- --test-threads=1
|
||||
cargo deny --locked check advisories bans licenses sources
|
||||
|
||||
- name: Build release binaries
|
||||
run: cargo build --release -p admin-api -p mcp-server
|
||||
|
||||
|
||||
- name: Install UI dependencies
|
||||
working-directory: apps/ui
|
||||
run: npm ci
|
||||
@@ -116,10 +140,12 @@ jobs:
|
||||
run: npm run build
|
||||
|
||||
- name: Install Playwright browser
|
||||
if: 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'
|
||||
working-directory: apps/ui
|
||||
run: |
|
||||
mkdir -p ../../.tmp
|
||||
@@ -127,6 +153,7 @@ jobs:
|
||||
PLAYWRIGHT_JSON_OUTPUT=../../.tmp/openapi-playwright.json npm run e2e
|
||||
|
||||
- name: Collect sanitized OpenAPI UI release evidence
|
||||
if: inputs.validation_level == 'feature'
|
||||
working-directory: apps/ui
|
||||
run: |
|
||||
trap 'rm -f ../../.tmp/openapi-playwright.json' EXIT
|
||||
@@ -155,22 +182,26 @@ jobs:
|
||||
|
||||
- name: Package release artifacts
|
||||
run: |
|
||||
set -euo pipefail
|
||||
mkdir -p dist/release
|
||||
source_revision="$(git rev-parse HEAD)"
|
||||
evidence_artifact="dist/crank-openapi-ui-evidence-${IMAGE_TAG}-${source_revision}.json"
|
||||
cp target/release/admin-api dist/release/admin-api
|
||||
cp target/release/crank-migrate dist/release/crank-migrate
|
||||
cp target/release/mcp-server dist/release/mcp-server
|
||||
cp .tmp/openapi-ui-evidence.json "$evidence_artifact"
|
||||
tar -C dist/release -czf dist/crank-community-admin-api-${IMAGE_TAG}.tar.gz admin-api crank-migrate
|
||||
tar -C dist/release -czf dist/crank-community-mcp-server-${IMAGE_TAG}.tar.gz mcp-server
|
||||
tar -C apps/ui/dist -czf dist/crank-community-ui-${IMAGE_TAG}.tar.gz .
|
||||
sha256sum \
|
||||
dist/crank-community-admin-api-${IMAGE_TAG}.tar.gz \
|
||||
dist/crank-community-mcp-server-${IMAGE_TAG}.tar.gz \
|
||||
dist/crank-community-ui-${IMAGE_TAG}.tar.gz \
|
||||
"$evidence_artifact" \
|
||||
> dist/crank-community-${IMAGE_TAG}-checksums.txt
|
||||
files=(
|
||||
"dist/crank-community-admin-api-${IMAGE_TAG}.tar.gz"
|
||||
"dist/crank-community-mcp-server-${IMAGE_TAG}.tar.gz"
|
||||
"dist/crank-community-ui-${IMAGE_TAG}.tar.gz"
|
||||
)
|
||||
if [ -f .tmp/openapi-ui-evidence.json ]; then
|
||||
cp .tmp/openapi-ui-evidence.json "$evidence_artifact"
|
||||
files+=("$evidence_artifact")
|
||||
fi
|
||||
sha256sum "${files[@]}" > "dist/crank-community-${IMAGE_TAG}-checksums.txt"
|
||||
|
||||
- name: Generate SBOM
|
||||
run: |
|
||||
@@ -178,6 +209,31 @@ jobs:
|
||||
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')
|
||||
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.
|
||||
GITEA_SERVER_URL: https://git.itexp.me
|
||||
GITEA_REPOSITORY: ${{ gitea.repository }}
|
||||
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
|
||||
RELEASE_TAG: ${{ gitea.ref_name }}
|
||||
SOURCE_REVISION: ${{ gitea.sha }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
assets=(
|
||||
"dist/crank-community-admin-api-${RELEASE_TAG}.tar.gz"
|
||||
"dist/crank-community-mcp-server-${RELEASE_TAG}.tar.gz"
|
||||
"dist/crank-community-ui-${RELEASE_TAG}.tar.gz"
|
||||
"dist/crank-community-${RELEASE_TAG}-checksums.txt"
|
||||
"dist/crank-community-${RELEASE_TAG}-sbom.spdx.json"
|
||||
)
|
||||
evidence="dist/crank-openapi-ui-evidence-${RELEASE_TAG}-${SOURCE_REVISION}.json"
|
||||
if [ -f "$evidence" ]; then
|
||||
assets+=("$evidence")
|
||||
fi
|
||||
python3 scripts/ci-release-assets.py "${assets[@]}"
|
||||
|
||||
- name: Load deployment secrets from OpenBao
|
||||
env:
|
||||
BAO_ADDR: ${{ secrets.BAO_ADDR }}
|
||||
@@ -243,51 +299,3 @@ jobs:
|
||||
- name: Show release bundle summary
|
||||
run: |
|
||||
ls -lh dist
|
||||
|
||||
- name: Write release notes
|
||||
run: |
|
||||
set -eu
|
||||
tag="${{ gitea.ref_name }}"
|
||||
{
|
||||
echo "## Crank Community ${tag}"
|
||||
echo
|
||||
echo "Source commit: \`$(git rev-parse HEAD)\`"
|
||||
echo
|
||||
echo "### Changes"
|
||||
echo
|
||||
git log --oneline -25 | sed 's/^/- /'
|
||||
echo
|
||||
echo "### Artifacts and checksums"
|
||||
echo
|
||||
echo '```'
|
||||
cat "dist/crank-community-${tag}-checksums.txt"
|
||||
echo '```'
|
||||
} > dist/RELEASE-NOTES.md
|
||||
cat dist/RELEASE-NOTES.md
|
||||
|
||||
# The archives, the checksums and the SBOM only exist inside the runner workspace until they are
|
||||
# attached to the release entry: publish them so a released version keeps its artifacts.
|
||||
- name: Publish artifacts to the Gitea release
|
||||
env:
|
||||
RELEASE_TOKEN: ${{ secrets.GITEA_TOKEN }}
|
||||
FALLBACK_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
set -eu
|
||||
tag="${{ gitea.ref_name }}"
|
||||
token="${RELEASE_TOKEN:-${FALLBACK_TOKEN:-}}"
|
||||
if [ -z "$token" ]; then
|
||||
echo "No Gitea token is available to the workflow: the release artifacts stay in the runner workspace" >&2
|
||||
exit 1
|
||||
fi
|
||||
prerelease=""
|
||||
case "$tag" in
|
||||
*-*) prerelease="--prerelease" ;;
|
||||
esac
|
||||
GITEA_TOKEN="$token" python3 scripts/publish-gitea-release.py \
|
||||
--api "${{ gitea.server_url }}/api/v1" \
|
||||
--repo "${{ gitea.repository }}" \
|
||||
--tag "$tag" \
|
||||
--title "Crank Community ${tag}" \
|
||||
--notes-file dist/RELEASE-NOTES.md \
|
||||
--dist dist \
|
||||
$prerelease
|
||||
@@ -7,7 +7,9 @@ mod integration {
|
||||
mod inventory_projection;
|
||||
mod jsonrpc_correlation;
|
||||
mod mcp_completion;
|
||||
mod mcp_logging;
|
||||
mod mcp_prompts;
|
||||
mod mcp_signals;
|
||||
mod request_context;
|
||||
mod revision_matrix;
|
||||
mod static_resources;
|
||||
|
||||
@@ -241,6 +241,11 @@ async fn inventory_projection_sidecar_is_provenance_only_and_names_the_projectio
|
||||
assert_eq!(
|
||||
triples,
|
||||
vec![
|
||||
(
|
||||
"server".to_owned(),
|
||||
"capability".to_owned(),
|
||||
"logging".to_owned()
|
||||
),
|
||||
(
|
||||
"server".to_owned(),
|
||||
"capability".to_owned(),
|
||||
@@ -262,7 +267,7 @@ async fn inventory_projection_sidecar_is_provenance_only_and_names_the_projectio
|
||||
"tools".to_owned()
|
||||
)
|
||||
],
|
||||
"the advertised server capabilities of the current scope are `completions`, `prompts`, `resources` and `tools`"
|
||||
"the advertised server capabilities of the current scope are `logging`, `completions`, `prompts`, `resources` and `tools`"
|
||||
);
|
||||
|
||||
// The sidecar is not the payload: byte comparison is against the frozen file only.
|
||||
|
||||
@@ -0,0 +1,856 @@
|
||||
//! Story 3.18 acceptance tests: safe MCP server logging (AT-3.18-01..03, FR-19).
|
||||
//!
|
||||
//! Oracles: `docs/acceptance-test-plan.md` AT-3.18-01..03, `epics.md` Story 3.18 and the pinned
|
||||
//! `logging`/`notifications/message`/`LoggingLevel` schemas of both supported revisions
|
||||
//! (`2026-07-28` carries the level per request in `_meta`; `2025-11-25` serves `logging/setLevel`).
|
||||
//! Every request travels through the real HTTP endpoint built by `build_test_app` over a real
|
||||
//! PostgreSQL registry; the level is set through the production request path.
|
||||
//!
|
||||
//! The delivered events are observed on the SSE response stream, which is the only carrier the
|
||||
//! pinned transport gives a server notification: a JSON body has no place for one. Where a pending
|
||||
//! notification exists and the client offered `text/event-stream`, the negotiated mode is the stream.
|
||||
//!
|
||||
//! No external MCP client is exercised here: these are local harness results against the pinned wire
|
||||
//! shapes, and the story handoff states that honestly.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use crank_core::PlatformApiKeyScope;
|
||||
use crank_registry::PostgresRegistry;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::common::{
|
||||
agent_mcp_url, build_test_app, create_platform_api_key, initialize_session,
|
||||
publish_agent_with_bindings, spawn_mcp_server, test_registry,
|
||||
};
|
||||
|
||||
const MODERN_REVISION: &str = "2026-07-28";
|
||||
const LEGACY_REVISION: &str = "2025-11-25";
|
||||
const META_PROTOCOL_VERSION: &str = "io.modelcontextprotocol/protocolVersion";
|
||||
const META_LOG_LEVEL: &str = "io.modelcontextprotocol/logLevel";
|
||||
const META_CLIENT_CAPABILITIES: &str = "io.modelcontextprotocol/clientCapabilities";
|
||||
const META_CLIENT_INFO: &str = "io.modelcontextprotocol/clientInfo";
|
||||
|
||||
const AGENT_SLUG: &str = "logging-agent";
|
||||
const OTHER_AGENT_SLUG: &str = "logging-other";
|
||||
|
||||
/// The one safe wire detail of a malformed logging level.
|
||||
const INVALID_LEVEL: &str = "invalid logging level";
|
||||
/// The fixed logger name of a delivered notification.
|
||||
const LOGGER_NAME: &str = "crank-mcp-server";
|
||||
/// A value that must never appear in a delivered notification. It is distinctive on purpose.
|
||||
const CANARY: &str = "crank-canary-9f7620e5-aa41-4b0d";
|
||||
|
||||
struct LoggingEndpoint {
|
||||
client: reqwest::Client,
|
||||
base_url: String,
|
||||
api_key: String,
|
||||
other_api_key: String,
|
||||
registry: PostgresRegistry,
|
||||
}
|
||||
|
||||
impl LoggingEndpoint {
|
||||
fn url(&self, agent_slug: &str) -> String {
|
||||
agent_mcp_url(&self.base_url, agent_slug)
|
||||
}
|
||||
|
||||
/// One request whose response is negotiated as the SSE stream, so a pending notification really
|
||||
/// has a carrier. The body is split into its notifications and the final JSON-RPC response.
|
||||
async fn post_stream(
|
||||
&self,
|
||||
agent_slug: &str,
|
||||
api_key: &str,
|
||||
headers: &[(&str, &str)],
|
||||
payload: Value,
|
||||
) -> StreamReply {
|
||||
let mut request = self
|
||||
.client
|
||||
.post(self.url(agent_slug))
|
||||
.header(reqwest::header::ACCEPT, "text/event-stream")
|
||||
.header(reqwest::header::AUTHORIZATION, format!("Bearer {api_key}"));
|
||||
for (name, value) in headers {
|
||||
request = request.header(*name, *value);
|
||||
}
|
||||
let response = request
|
||||
.json(&payload)
|
||||
.send()
|
||||
.await
|
||||
.expect("the MCP endpoint answers");
|
||||
let status = response.status();
|
||||
let content_type = response
|
||||
.headers()
|
||||
.get(reqwest::header::CONTENT_TYPE)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.unwrap_or_default()
|
||||
.to_owned();
|
||||
let body = response.text().await.expect("the stream body is readable");
|
||||
StreamReply::parse(status, content_type, body)
|
||||
}
|
||||
|
||||
/// One legacy request inside the initialized session of `agent_slug`.
|
||||
async fn legacy_post(
|
||||
&self,
|
||||
agent_slug: &str,
|
||||
api_key: &str,
|
||||
session_id: &str,
|
||||
payload: Value,
|
||||
) -> StreamReply {
|
||||
self.post_stream(
|
||||
agent_slug,
|
||||
api_key,
|
||||
&[
|
||||
("MCP-Protocol-Version", LEGACY_REVISION),
|
||||
("MCP-Session-Id", session_id),
|
||||
],
|
||||
payload,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// One `logging/setLevel` request of the legacy era.
|
||||
async fn set_level(&self, session_id: &str, level: Value) -> StreamReply {
|
||||
self.legacy_post(
|
||||
AGENT_SLUG,
|
||||
&self.api_key,
|
||||
session_id,
|
||||
json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": 41,
|
||||
"method": "logging/setLevel",
|
||||
"params": {"level": level}
|
||||
}),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// One modern request of an arbitrary method with the required per-request identity.
|
||||
async fn modern_stream(&self, method: &str, params: Value) -> StreamReply {
|
||||
let mut params = params;
|
||||
params["_meta"] = json!({
|
||||
META_PROTOCOL_VERSION: MODERN_REVISION,
|
||||
META_CLIENT_CAPABILITIES: {},
|
||||
META_CLIENT_INFO: {"name": "crank-logging-atdd", "version": "0.1.0"}
|
||||
});
|
||||
self.modern_stream_with_params(method, params).await
|
||||
}
|
||||
|
||||
/// The same, with the caller's `params` (including a chosen `_meta`).
|
||||
async fn modern_stream_with_params(&self, method: &str, params: Value) -> StreamReply {
|
||||
self.post_stream(
|
||||
AGENT_SLUG,
|
||||
&self.api_key,
|
||||
&[
|
||||
("MCP-Protocol-Version", MODERN_REVISION),
|
||||
("Mcp-Method", method),
|
||||
],
|
||||
json!({"jsonrpc": "2.0", "id": 51, "method": method, "params": params}),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn legacy_session(&self, agent_slug: &str, api_key: &str) -> String {
|
||||
initialize_session(&self.client, &self.url(agent_slug), api_key).await
|
||||
}
|
||||
}
|
||||
|
||||
struct StreamReply {
|
||||
status: reqwest::StatusCode,
|
||||
content_type: String,
|
||||
/// The JSON-RPC response, which is the last event of the stream.
|
||||
response: Value,
|
||||
/// The `notifications/message` bodies delivered before it.
|
||||
notifications: Vec<Value>,
|
||||
/// The raw body, so a test can search it for a canary value.
|
||||
raw: String,
|
||||
}
|
||||
|
||||
impl StreamReply {
|
||||
/// Parse a reply that may arrive either as an SSE stream (a pending notification needs the
|
||||
/// stream) or as the plain JSON body of a method this era does not serve.
|
||||
fn parse(status: reqwest::StatusCode, content_type: String, body: String) -> Self {
|
||||
let mut messages = Vec::new();
|
||||
for block in body.split("\n\n") {
|
||||
for line in block.lines() {
|
||||
let Some(data) = line.strip_prefix("data:") else {
|
||||
continue;
|
||||
};
|
||||
let data = data.trim_start();
|
||||
if data.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let value: Value = serde_json::from_str(data)
|
||||
.unwrap_or_else(|error| panic!("every stream event is JSON: {data:?} {error}"));
|
||||
messages.push(value);
|
||||
}
|
||||
}
|
||||
if messages.is_empty() {
|
||||
// An era-correct rejection of an unserved method is answered as a plain JSON body: it
|
||||
// never carries a notification, so there is nothing to stream.
|
||||
let response: Value = serde_json::from_str(&body)
|
||||
.unwrap_or_else(|error| panic!("expected a JSON-RPC body, got {body:?}: {error}"));
|
||||
return Self {
|
||||
status,
|
||||
content_type,
|
||||
response,
|
||||
notifications: Vec::new(),
|
||||
raw: body,
|
||||
};
|
||||
}
|
||||
let response = messages
|
||||
.pop()
|
||||
.unwrap_or_else(|| panic!("the stream must end with the JSON-RPC response: {body:?}"));
|
||||
Self {
|
||||
status,
|
||||
content_type,
|
||||
response,
|
||||
notifications: messages,
|
||||
raw: body,
|
||||
}
|
||||
}
|
||||
|
||||
fn result(&self) -> &Value {
|
||||
self.response
|
||||
.get("result")
|
||||
.unwrap_or_else(|| panic!("expected a JSON-RPC result, got {}", self.response))
|
||||
}
|
||||
|
||||
fn error(&self) -> (i64, String) {
|
||||
let code = self
|
||||
.response
|
||||
.pointer("/error/code")
|
||||
.and_then(Value::as_i64)
|
||||
.unwrap_or_else(|| panic!("expected a JSON-RPC error, got {}", self.response));
|
||||
let message = self
|
||||
.response
|
||||
.pointer("/error/message")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default()
|
||||
.to_owned();
|
||||
(code, message)
|
||||
}
|
||||
|
||||
fn assert_stream(&self) {
|
||||
assert_eq!(self.status, reqwest::StatusCode::OK);
|
||||
assert!(
|
||||
self.content_type.starts_with("text/event-stream"),
|
||||
"a streamed answer must carry the SSE content type, got {:?}",
|
||||
self.content_type
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The exact closed body of one delivered event. Nothing else is allowed to be carried.
|
||||
fn expected_notification(level: &str, event: &str, outcome: &str) -> Value {
|
||||
json!({
|
||||
"jsonrpc": "2.0",
|
||||
"method": "notifications/message",
|
||||
"params": {
|
||||
"level": level,
|
||||
"logger": LOGGER_NAME,
|
||||
"data": {"event": event, "outcome": outcome}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async fn logging_endpoint() -> LoggingEndpoint {
|
||||
let registry = test_registry().await;
|
||||
publish_agent_with_bindings(®istry, AGENT_SLUG, Vec::new()).await;
|
||||
publish_agent_with_bindings(®istry, OTHER_AGENT_SLUG, Vec::new()).await;
|
||||
|
||||
let api_key = create_platform_api_key(
|
||||
®istry,
|
||||
AGENT_SLUG,
|
||||
"mcp-logging",
|
||||
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
|
||||
)
|
||||
.await;
|
||||
let other_api_key = create_platform_api_key(
|
||||
®istry,
|
||||
OTHER_AGENT_SLUG,
|
||||
"mcp-logging-other",
|
||||
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
|
||||
)
|
||||
.await;
|
||||
let base_url = spawn_mcp_server(build_test_app(
|
||||
registry.clone(),
|
||||
Duration::from_millis(0),
|
||||
Some("https://crank.example.com".to_owned()),
|
||||
))
|
||||
.await;
|
||||
|
||||
LoggingEndpoint {
|
||||
client: reqwest::Client::new(),
|
||||
base_url,
|
||||
api_key,
|
||||
other_api_key,
|
||||
registry,
|
||||
}
|
||||
}
|
||||
|
||||
/// AT-3.18-01/03: the advertisement equals the implemented surface on both revisions.
|
||||
#[tokio::test]
|
||||
async fn advertisement_declares_the_logging_capability_on_both_revisions() {
|
||||
let endpoint = logging_endpoint().await;
|
||||
|
||||
let discover = endpoint
|
||||
.client
|
||||
.post(endpoint.url(AGENT_SLUG))
|
||||
.header(
|
||||
reqwest::header::ACCEPT,
|
||||
"application/json, text/event-stream",
|
||||
)
|
||||
.header(
|
||||
reqwest::header::AUTHORIZATION,
|
||||
format!("Bearer {}", endpoint.api_key),
|
||||
)
|
||||
.header("MCP-Protocol-Version", MODERN_REVISION)
|
||||
.header("Mcp-Method", "server/discover")
|
||||
.json(&json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": 1,
|
||||
"method": "server/discover",
|
||||
"params": {"_meta": {
|
||||
META_PROTOCOL_VERSION: MODERN_REVISION,
|
||||
META_CLIENT_CAPABILITIES: {},
|
||||
META_CLIENT_INFO: {"name": "crank-logging-atdd", "version": "0.1.0"}
|
||||
}}
|
||||
}))
|
||||
.send()
|
||||
.await
|
||||
.expect("the endpoint answers");
|
||||
let discover: Value = discover.json().await.expect("a JSON body");
|
||||
assert_eq!(
|
||||
discover["result"]["capabilities"]["logging"],
|
||||
json!({}),
|
||||
"the modern advertisement must declare the implemented logging capability: {discover}"
|
||||
);
|
||||
|
||||
let initialize = endpoint
|
||||
.client
|
||||
.post(endpoint.url(AGENT_SLUG))
|
||||
.header(
|
||||
reqwest::header::ACCEPT,
|
||||
"application/json, text/event-stream",
|
||||
)
|
||||
.header(
|
||||
reqwest::header::AUTHORIZATION,
|
||||
format!("Bearer {}", endpoint.api_key),
|
||||
)
|
||||
.json(&json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": 2,
|
||||
"method": "initialize",
|
||||
"params": {"protocolVersion": LEGACY_REVISION, "capabilities": {}}
|
||||
}))
|
||||
.send()
|
||||
.await
|
||||
.expect("the endpoint answers");
|
||||
let initialize: Value = initialize.json().await.expect("a JSON body");
|
||||
assert_eq!(
|
||||
initialize["result"]["capabilities"]["logging"],
|
||||
json!({}),
|
||||
"the legacy advertisement must declare the implemented logging capability: {initialize}"
|
||||
);
|
||||
// Control: a capability this story does not implement is still absent, so the assertion above is
|
||||
// not a blanket "advertise everything" change.
|
||||
assert!(
|
||||
initialize["result"]["capabilities"]
|
||||
.get("io.modelcontextprotocol/tasks")
|
||||
.is_none(),
|
||||
"an unimplemented extension must not appear: {initialize}"
|
||||
);
|
||||
endpoint.registry.ping().await.expect("the registry is up");
|
||||
}
|
||||
|
||||
/// AT-3.18-01: setting a valid legacy level is acknowledged with one safe structured event.
|
||||
#[tokio::test]
|
||||
async fn legacy_set_level_acknowledges_with_a_closed_safe_event() {
|
||||
let endpoint = logging_endpoint().await;
|
||||
let session = endpoint.legacy_session(AGENT_SLUG, &endpoint.api_key).await;
|
||||
|
||||
let reply = endpoint.set_level(&session, json!("debug")).await;
|
||||
reply.assert_stream();
|
||||
assert_eq!(
|
||||
reply.result(),
|
||||
&json!({}),
|
||||
"the pinned `logging/setLevel` result is empty: {}",
|
||||
reply.response
|
||||
);
|
||||
assert_eq!(
|
||||
reply.notifications,
|
||||
vec![
|
||||
expected_notification("notice", "mcp.logging.level_applied", "applied"),
|
||||
expected_notification("info", "mcp.request.served", "ok"),
|
||||
],
|
||||
"the acknowledgment carries the applied level and the served outcome, nothing else"
|
||||
);
|
||||
assert!(
|
||||
reply.raw.len() < 4_096,
|
||||
"one notification is a few hundred bytes, never a payload echo"
|
||||
);
|
||||
}
|
||||
|
||||
/// AT-3.18-01: after the opt-in, a served request delivers its own safe event only.
|
||||
#[tokio::test]
|
||||
async fn legacy_served_request_delivers_only_the_closed_safe_event() {
|
||||
let endpoint = logging_endpoint().await;
|
||||
let session = endpoint.legacy_session(AGENT_SLUG, &endpoint.api_key).await;
|
||||
endpoint.set_level(&session, json!("debug")).await;
|
||||
|
||||
let reply = endpoint
|
||||
.legacy_post(
|
||||
AGENT_SLUG,
|
||||
&endpoint.api_key,
|
||||
&session,
|
||||
json!({"jsonrpc": "2.0", "id": 61, "method": "tools/list", "params": {}}),
|
||||
)
|
||||
.await;
|
||||
reply.assert_stream();
|
||||
assert!(
|
||||
reply.result().get("tools").is_some(),
|
||||
"the business result is unchanged: {}",
|
||||
reply.response
|
||||
);
|
||||
assert_eq!(
|
||||
reply.notifications,
|
||||
vec![expected_notification("info", "mcp.request.served", "ok")],
|
||||
"a served request reports its outcome and nothing about the request"
|
||||
);
|
||||
}
|
||||
|
||||
/// AT-3.18-01 (redaction): a value the request carries can never reach a notification, while the
|
||||
/// positive control proves the same search does find a reflected value elsewhere in the body.
|
||||
#[tokio::test]
|
||||
async fn a_request_value_can_never_reach_a_notification() {
|
||||
let endpoint = logging_endpoint().await;
|
||||
let session = endpoint.legacy_session(AGENT_SLUG, &endpoint.api_key).await;
|
||||
endpoint.set_level(&session, json!("debug")).await;
|
||||
|
||||
let reply = endpoint
|
||||
.legacy_post(
|
||||
AGENT_SLUG,
|
||||
&endpoint.api_key,
|
||||
&session,
|
||||
json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": 62,
|
||||
"method": "tools/call",
|
||||
"params": {
|
||||
"name": CANARY,
|
||||
"arguments": {"secret": CANARY},
|
||||
"_meta": {"progressToken": CANARY}
|
||||
}
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
reply.assert_stream();
|
||||
|
||||
// Positive control: the existing product answer echoes the unknown tool name verbatim, so the
|
||||
// canary is provably present in this very body — a "not found" search here would be meaningless.
|
||||
let (code, message) = reply.error();
|
||||
assert_eq!(code, -32602, "an unknown tool is a safe client error");
|
||||
assert!(
|
||||
message.contains(CANARY),
|
||||
"the positive control must reflect the canary in the error message, got {message:?}"
|
||||
);
|
||||
|
||||
// Positive control on delivery: the event is really delivered and its body is exactly the
|
||||
// closed one for a rejected request, so the canary assertions below cannot pass vacuously.
|
||||
assert_eq!(
|
||||
reply.notifications,
|
||||
vec![expected_notification(
|
||||
"warning",
|
||||
"mcp.request.rejected",
|
||||
"invalid_params"
|
||||
)],
|
||||
"a rejected request must deliver exactly one safe warning event"
|
||||
);
|
||||
|
||||
// The delivered notification is exactly the closed safe body: no canary, no argument value.
|
||||
for notification in &reply.notifications {
|
||||
assert_eq!(
|
||||
notification["params"]["data"]
|
||||
.as_object()
|
||||
.map(|data| {
|
||||
let mut keys: Vec<&str> = data.keys().map(String::as_str).collect();
|
||||
keys.sort_unstable();
|
||||
keys
|
||||
})
|
||||
.unwrap_or_default(),
|
||||
vec!["event", "outcome"],
|
||||
"a notification data object carries exactly the two closed members: {notification}"
|
||||
);
|
||||
assert!(
|
||||
!notification.to_string().contains(CANARY),
|
||||
"a request value must never reach a notification: {notification}"
|
||||
);
|
||||
assert!(
|
||||
notification["params"].get("id").is_none(),
|
||||
"a notification is not a response: {notification}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// AT-3.18-02/03: the modern era opts in per request, and only from the pinned `_meta` key.
|
||||
#[tokio::test]
|
||||
async fn modern_level_is_per_request_and_requires_an_explicit_opt_in() {
|
||||
let endpoint = logging_endpoint().await;
|
||||
|
||||
let opted_in = endpoint
|
||||
.modern_stream_with_params(
|
||||
"tools/list",
|
||||
json!({"_meta": {
|
||||
META_PROTOCOL_VERSION: MODERN_REVISION,
|
||||
META_CLIENT_CAPABILITIES: {},
|
||||
META_CLIENT_INFO: {"name": "crank-logging-atdd", "version": "0.1.0"},
|
||||
META_LOG_LEVEL: "debug"
|
||||
}}),
|
||||
)
|
||||
.await;
|
||||
opted_in.assert_stream();
|
||||
assert!(opted_in.result().get("tools").is_some());
|
||||
assert_eq!(
|
||||
opted_in.notifications,
|
||||
vec![expected_notification("info", "mcp.request.served", "ok")],
|
||||
"a request that opted in receives its safe event"
|
||||
);
|
||||
|
||||
// The pinned modern schema: without the key the server MUST NOT send any notification.
|
||||
let not_opted_in = endpoint.modern_stream("tools/list", json!({})).await;
|
||||
assert_eq!(not_opted_in.status, reqwest::StatusCode::OK);
|
||||
assert!(
|
||||
not_opted_in.result().get("tools").is_some(),
|
||||
"the business answer is unchanged without an opt-in: {}",
|
||||
not_opted_in.response
|
||||
);
|
||||
assert!(
|
||||
not_opted_in.notifications.is_empty(),
|
||||
"no notification without an explicit opt-in, got {:?}",
|
||||
not_opted_in.notifications
|
||||
);
|
||||
|
||||
// An unknown level is treated as "not opted in" rather than as an error of the business request,
|
||||
// and it never widens the accepted vocabulary.
|
||||
let unknown = endpoint
|
||||
.modern_stream_with_params(
|
||||
"tools/list",
|
||||
json!({"_meta": {
|
||||
META_PROTOCOL_VERSION: MODERN_REVISION,
|
||||
META_CLIENT_CAPABILITIES: {},
|
||||
META_CLIENT_INFO: {"name": "crank-logging-atdd", "version": "0.1.0"},
|
||||
META_LOG_LEVEL: "verbose"
|
||||
}}),
|
||||
)
|
||||
.await;
|
||||
assert!(unknown.result().get("tools").is_some());
|
||||
assert!(
|
||||
unknown.notifications.is_empty(),
|
||||
"an unpinned level must not opt in, got {:?}",
|
||||
unknown.notifications
|
||||
);
|
||||
}
|
||||
|
||||
/// AT-3.18-03: the delivered severities follow the ranged level of the legacy session.
|
||||
#[tokio::test]
|
||||
async fn legacy_severity_filter_is_honoured() {
|
||||
let endpoint = logging_endpoint().await;
|
||||
let session = endpoint.legacy_session(AGENT_SLUG, &endpoint.api_key).await;
|
||||
|
||||
// `error` is more severe than both a served request and a rejected one: neither is delivered.
|
||||
endpoint.set_level(&session, json!("error")).await;
|
||||
let served = endpoint
|
||||
.legacy_post(
|
||||
AGENT_SLUG,
|
||||
&endpoint.api_key,
|
||||
&session,
|
||||
json!({"jsonrpc": "2.0", "id": 71, "method": "tools/list", "params": {}}),
|
||||
)
|
||||
.await;
|
||||
assert!(
|
||||
served.notifications.is_empty(),
|
||||
"a served event is below the `error` level, got {:?}",
|
||||
served.notifications
|
||||
);
|
||||
let rejected = endpoint
|
||||
.legacy_post(
|
||||
AGENT_SLUG,
|
||||
&endpoint.api_key,
|
||||
&session,
|
||||
json!({"jsonrpc": "2.0", "id": 72, "method": "prompts/get", "params": {}}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
rejected.error().0,
|
||||
-32602,
|
||||
"a malformed request is a client error"
|
||||
);
|
||||
assert!(
|
||||
rejected.notifications.is_empty(),
|
||||
"a warning event is below the `error` level, got {:?}",
|
||||
rejected.notifications
|
||||
);
|
||||
|
||||
// `warning` admits the rejected event, and still not the served one.
|
||||
endpoint.set_level(&session, json!("warning")).await;
|
||||
let rejected = endpoint
|
||||
.legacy_post(
|
||||
AGENT_SLUG,
|
||||
&endpoint.api_key,
|
||||
&session,
|
||||
json!({"jsonrpc": "2.0", "id": 73, "method": "prompts/get", "params": {}}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
rejected.notifications,
|
||||
vec![expected_notification(
|
||||
"warning",
|
||||
"mcp.request.rejected",
|
||||
"invalid_params"
|
||||
)],
|
||||
"the rejection is delivered at the `warning` level"
|
||||
);
|
||||
let served = endpoint
|
||||
.legacy_post(
|
||||
AGENT_SLUG,
|
||||
&endpoint.api_key,
|
||||
&session,
|
||||
json!({"jsonrpc": "2.0", "id": 74, "method": "tools/list", "params": {}}),
|
||||
)
|
||||
.await;
|
||||
assert!(
|
||||
served.notifications.is_empty(),
|
||||
"an info event is still below the `warning` level, got {:?}",
|
||||
served.notifications
|
||||
);
|
||||
}
|
||||
|
||||
/// AT-3.18-02: a malformed level is a revision-correct safe error with bounded work, and it never
|
||||
/// changes the level of the client or of anybody else.
|
||||
#[tokio::test]
|
||||
async fn a_malformed_level_is_a_safe_error_without_state_change() {
|
||||
let endpoint = logging_endpoint().await;
|
||||
let session = endpoint.legacy_session(AGENT_SLUG, &endpoint.api_key).await;
|
||||
endpoint.set_level(&session, json!("error")).await;
|
||||
|
||||
// A value outside the pinned union, a non-string shape, a missing member and an oversized value
|
||||
// all share one safe detail: the client cannot tell them apart and nothing is echoed back.
|
||||
for level in [
|
||||
json!("verbose"),
|
||||
json!("INFO"),
|
||||
json!(7),
|
||||
json!(null),
|
||||
json!({}),
|
||||
json!("i".repeat(64)),
|
||||
] {
|
||||
let reply = endpoint.set_level(&session, level.clone()).await;
|
||||
assert_eq!(
|
||||
reply.error(),
|
||||
(-32602, INVALID_LEVEL.to_owned()),
|
||||
"a malformed level is one safe invalid-params detail for {level}"
|
||||
);
|
||||
if let Some(text) = level.as_str() {
|
||||
assert!(
|
||||
!reply.raw.contains(text),
|
||||
"the offending value must never be echoed back"
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
reply.notifications.is_empty(),
|
||||
"a rejected level is not an opt-in, got {:?}",
|
||||
reply.notifications
|
||||
);
|
||||
}
|
||||
|
||||
// An oversized value is refused by the fixed bound: the answer stays a short safe detail and the
|
||||
// value is not reflected, which is the observable half of "bounded work".
|
||||
let oversized = "i".repeat(65_536);
|
||||
let reply = endpoint.set_level(&session, json!(oversized)).await;
|
||||
assert_eq!(reply.error(), (-32602, INVALID_LEVEL.to_owned()));
|
||||
assert!(
|
||||
!reply.raw.contains(&oversized),
|
||||
"an oversized level must not be reflected"
|
||||
);
|
||||
assert!(
|
||||
reply.raw.len() < 4_096,
|
||||
"the answer to an oversized level is bounded, got {} bytes",
|
||||
reply.raw.len()
|
||||
);
|
||||
let missing = endpoint
|
||||
.legacy_post(
|
||||
AGENT_SLUG,
|
||||
&endpoint.api_key,
|
||||
&session,
|
||||
json!({"jsonrpc": "2.0", "id": 81, "method": "logging/setLevel", "params": {}}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(missing.error(), (-32602, INVALID_LEVEL.to_owned()));
|
||||
|
||||
// The level of the session is unchanged (`error` was set before the malformed attempts), so a
|
||||
// served request still delivers nothing...
|
||||
let served = endpoint
|
||||
.legacy_post(
|
||||
AGENT_SLUG,
|
||||
&endpoint.api_key,
|
||||
&session,
|
||||
json!({"jsonrpc": "2.0", "id": 82, "method": "tools/list", "params": {}}),
|
||||
)
|
||||
.await;
|
||||
assert!(
|
||||
served.notifications.is_empty(),
|
||||
"a malformed level must not change the active level, got {:?}",
|
||||
served.notifications
|
||||
);
|
||||
// ...and a valid level still works, which proves the assertions above are not vacuous.
|
||||
endpoint.set_level(&session, json!("debug")).await;
|
||||
let served = endpoint
|
||||
.legacy_post(
|
||||
AGENT_SLUG,
|
||||
&endpoint.api_key,
|
||||
&session,
|
||||
json!({"jsonrpc": "2.0", "id": 83, "method": "tools/list", "params": {}}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(served.notifications.len(), 1);
|
||||
}
|
||||
|
||||
/// AT-3.18-02 (era matrix): the modern schema declares no `logging/setLevel`, so the same wire name
|
||||
/// is a method-not-found there and never reaches the legacy service.
|
||||
#[tokio::test]
|
||||
async fn the_modern_era_has_no_set_level_method() {
|
||||
let endpoint = logging_endpoint().await;
|
||||
let reply = endpoint
|
||||
.modern_stream("logging/setLevel", json!({"level": "debug"}))
|
||||
.await;
|
||||
let (code, message) = reply.error();
|
||||
assert_eq!(
|
||||
code, -32601,
|
||||
"the modern revision has no logging/setLevel: {}",
|
||||
reply.response
|
||||
);
|
||||
assert!(
|
||||
!message.contains("debug"),
|
||||
"the rejection must not echo the level: {message:?}"
|
||||
);
|
||||
// And the level was not applied through a wrong-era route: a modern request stays silent.
|
||||
let after = endpoint.modern_stream("tools/list", json!({})).await;
|
||||
assert!(after.notifications.is_empty());
|
||||
}
|
||||
|
||||
/// AT-3.18-01/03: a method this era does not implement is a pinned client error, so the safe event
|
||||
/// of an opted-in client describes a client-side rejection, never an internal server failure.
|
||||
#[tokio::test]
|
||||
async fn an_unknown_method_is_a_rejection_not_an_internal_failure() {
|
||||
let endpoint = logging_endpoint().await;
|
||||
let session = endpoint.legacy_session(AGENT_SLUG, &endpoint.api_key).await;
|
||||
endpoint.set_level(&session, json!("info")).await;
|
||||
|
||||
// `server/discover` is a modern-era method, so the legacy adapter answers it with -32601.
|
||||
let reply = endpoint
|
||||
.legacy_post(
|
||||
AGENT_SLUG,
|
||||
&endpoint.api_key,
|
||||
&session,
|
||||
json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": 71,
|
||||
"method": "server/discover",
|
||||
"params": {}
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
reply.error().0,
|
||||
-32601,
|
||||
"an unimplemented method is a pinned client error: {}",
|
||||
reply.response
|
||||
);
|
||||
assert_eq!(
|
||||
reply.notifications,
|
||||
vec![expected_notification(
|
||||
"warning",
|
||||
"mcp.request.rejected",
|
||||
"invalid_params"
|
||||
)],
|
||||
"a pinned client error must not be reported as an internal failure"
|
||||
);
|
||||
}
|
||||
|
||||
/// AT-3.18-01/03 (independence): a level belongs to one client context, so a second session and a
|
||||
/// second Agent keep their own (or no) level.
|
||||
#[tokio::test]
|
||||
async fn a_level_never_leaks_to_another_client() {
|
||||
let endpoint = logging_endpoint().await;
|
||||
let session = endpoint.legacy_session(AGENT_SLUG, &endpoint.api_key).await;
|
||||
endpoint.set_level(&session, json!("debug")).await;
|
||||
|
||||
// Another initialized session of the same Agent never opted in.
|
||||
let other_session = endpoint.legacy_session(AGENT_SLUG, &endpoint.api_key).await;
|
||||
assert_ne!(
|
||||
session, other_session,
|
||||
"each initialize mints its own session"
|
||||
);
|
||||
let other = endpoint
|
||||
.legacy_post(
|
||||
AGENT_SLUG,
|
||||
&endpoint.api_key,
|
||||
&other_session,
|
||||
json!({"jsonrpc": "2.0", "id": 91, "method": "tools/list", "params": {}}),
|
||||
)
|
||||
.await;
|
||||
assert!(
|
||||
other.notifications.is_empty(),
|
||||
"a session that never opted in must stay silent, got {:?}",
|
||||
other.notifications
|
||||
);
|
||||
assert!(other.result().get("tools").is_some());
|
||||
|
||||
// The opted-in session still receives its own events...
|
||||
let opted_in = endpoint
|
||||
.legacy_post(
|
||||
AGENT_SLUG,
|
||||
&endpoint.api_key,
|
||||
&session,
|
||||
json!({"jsonrpc": "2.0", "id": 92, "method": "tools/list", "params": {}}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(opted_in.notifications.len(), 1);
|
||||
|
||||
// ...and another Agent's session is unaffected by this Agent's level, both before and after it
|
||||
// sets its own.
|
||||
let other_agent_session = endpoint
|
||||
.legacy_session(OTHER_AGENT_SLUG, &endpoint.other_api_key)
|
||||
.await;
|
||||
let other_agent = endpoint
|
||||
.legacy_post(
|
||||
OTHER_AGENT_SLUG,
|
||||
&endpoint.other_api_key,
|
||||
&other_agent_session,
|
||||
json!({"jsonrpc": "2.0", "id": 93, "method": "tools/list", "params": {}}),
|
||||
)
|
||||
.await;
|
||||
assert!(
|
||||
other_agent.notifications.is_empty(),
|
||||
"another Agent must not inherit a level, got {:?}",
|
||||
other_agent.notifications
|
||||
);
|
||||
endpoint
|
||||
.legacy_post(
|
||||
OTHER_AGENT_SLUG,
|
||||
&endpoint.other_api_key,
|
||||
&other_agent_session,
|
||||
json!({"jsonrpc": "2.0", "id": 94, "method": "logging/setLevel", "params": {"level": "error"}}),
|
||||
)
|
||||
.await;
|
||||
let other_agent_error = endpoint
|
||||
.legacy_post(
|
||||
OTHER_AGENT_SLUG,
|
||||
&endpoint.other_api_key,
|
||||
&other_agent_session,
|
||||
json!({"jsonrpc": "2.0", "id": 95, "method": "tools/list", "params": {}}),
|
||||
)
|
||||
.await;
|
||||
assert!(
|
||||
other_agent_error.notifications.is_empty(),
|
||||
"the other Agent's own `error` level admits no served event"
|
||||
);
|
||||
}
|
||||
@@ -23,7 +23,7 @@ async fn advertisement_declares_prompts_on_both_revisions() {
|
||||
let discover = endpoint.modern("server/discover", json!({}), None).await;
|
||||
assert_eq!(
|
||||
discover["result"]["capabilities"]["prompts"],
|
||||
json!({"listChanged": false}),
|
||||
json!({"listChanged": true}),
|
||||
"the modern advertisement must declare the prompts capability: {discover}"
|
||||
);
|
||||
|
||||
@@ -50,7 +50,7 @@ async fn advertisement_declares_prompts_on_both_revisions() {
|
||||
let initialize = json_body(initialize_response).await;
|
||||
assert_eq!(
|
||||
initialize["result"]["capabilities"]["prompts"],
|
||||
json!({"listChanged": false}),
|
||||
json!({"listChanged": true}),
|
||||
"the legacy advertisement must declare the prompts capability: {initialize}"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,730 @@
|
||||
//! Story 3.19 acceptance tests (AT-3.19-01..03, FR-19): committed Resource/Prompt catalog changes
|
||||
//! are announced to a client that asked for the signal of its revision, and the ordinary list
|
||||
//! methods stay authoritative when a notification is lost.
|
||||
//!
|
||||
//! Everything here is the production path: the real loopback MCP endpoint, the real PostgreSQL
|
||||
//! registry, the real immutable artifact store and real commits through the registry API. No stubbed
|
||||
//! route, no faked notification, no seeded notification table.
|
||||
|
||||
#![allow(dead_code)]
|
||||
|
||||
mod scenarios;
|
||||
|
||||
use std::{
|
||||
fs,
|
||||
path::PathBuf,
|
||||
sync::atomic::{AtomicU64, Ordering},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use axum::http::header;
|
||||
use crank_artifacts::ArtifactStore;
|
||||
use crank_core::{
|
||||
Agent, AgentId, AgentStatus, AgentVersion, PlatformApiKeyScope, ToolSelectionPolicy,
|
||||
ids::{PromptId, ResourceId},
|
||||
prompt::{PromptDefinition, PromptSensitivity},
|
||||
};
|
||||
use crank_registry::model::{
|
||||
AgentPromptBinding, CreatePromptDraftRequest, PublishPromptRequest,
|
||||
SaveAgentCatalogConfigRequest,
|
||||
resource::{CreateResourceDraftRequest, PublishResourceVersionRequest},
|
||||
};
|
||||
use crank_registry::{
|
||||
AgentResourceBinding, CreateAgentDraftVersionRequest, CreateAgentRequest, PostgresRegistry,
|
||||
PublishAgentRequest, PublishRequest,
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
use time::OffsetDateTime;
|
||||
|
||||
use super::common::*;
|
||||
|
||||
const MODERN_REVISION: &str = "2026-07-28";
|
||||
const LEGACY_REVISION: &str = "2025-11-25";
|
||||
|
||||
const META_PROTOCOL_VERSION: &str = "io.modelcontextprotocol/protocolVersion";
|
||||
const META_CLIENT_CAPABILITIES: &str = "io.modelcontextprotocol/clientCapabilities";
|
||||
const META_CLIENT_INFO: &str = "io.modelcontextprotocol/clientInfo";
|
||||
|
||||
const RESOURCE_LIST_CHANGED: &str = "notifications/resources/list_changed";
|
||||
const PROMPT_LIST_CHANGED: &str = "notifications/prompts/list_changed";
|
||||
const SUBSCRIPTIONS_ACKNOWLEDGED: &str = "notifications/subscriptions/acknowledged";
|
||||
const SUBSCRIPTION_ID_KEY: &str = "io.modelcontextprotocol/subscriptionId";
|
||||
|
||||
const AGENT_SLUG: &str = "sales-signals";
|
||||
|
||||
static NEXT_ROOT: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
/// Test-owned artifact root (0700), removed on drop.
|
||||
struct TestRoot(PathBuf);
|
||||
|
||||
impl TestRoot {
|
||||
fn new() -> Self {
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"crank-mcp-signals-{}-{}",
|
||||
std::process::id(),
|
||||
NEXT_ROOT.fetch_add(1, Ordering::Relaxed)
|
||||
));
|
||||
fs::create_dir_all(&path).expect("artifact root must be creatable");
|
||||
let mut permissions = fs::metadata(&path).unwrap().permissions();
|
||||
std::os::unix::fs::PermissionsExt::set_mode(&mut permissions, 0o700);
|
||||
fs::set_permissions(&path, permissions).expect("artifact root must be private");
|
||||
Self(path)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TestRoot {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// The published fixture: one Tool, two bound Prompts, one published but initially unbound Resource.
|
||||
struct SignalsEndpoint {
|
||||
client: reqwest::Client,
|
||||
base_url: String,
|
||||
mcp_url: String,
|
||||
api_key: String,
|
||||
registry: PostgresRegistry,
|
||||
artifact_store: ArtifactStore,
|
||||
root: TestRoot,
|
||||
agent_id: AgentId,
|
||||
operation: crank_core::Operation<crank_schema::Schema, crank_mapping::MappingSet>,
|
||||
second_operation: crank_core::Operation<crank_schema::Schema, crank_mapping::MappingSet>,
|
||||
greeting: PromptId,
|
||||
review: PromptId,
|
||||
extra_prompt: PromptId,
|
||||
notice: ResourceId,
|
||||
}
|
||||
|
||||
impl SignalsEndpoint {
|
||||
fn modern_meta() -> Value {
|
||||
json!({
|
||||
META_PROTOCOL_VERSION: MODERN_REVISION,
|
||||
META_CLIENT_CAPABILITIES: {},
|
||||
META_CLIENT_INFO: { "name": "crank-signals-atdd", "version": "0.1.0" }
|
||||
})
|
||||
}
|
||||
|
||||
async fn modern_post(&self, payload: Value) -> reqwest::Response {
|
||||
self.client
|
||||
.post(&self.mcp_url)
|
||||
.header(header::ACCEPT, "application/json, text/event-stream")
|
||||
.header(header::AUTHORIZATION, format!("Bearer {}", self.api_key))
|
||||
.json(&payload)
|
||||
.send()
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// One modern request whose result is a JSON body (never a stream).
|
||||
async fn modern(&self, method: &str, params: Value) -> Value {
|
||||
let mut params = params;
|
||||
params["_meta"] = Self::modern_meta();
|
||||
let response = self
|
||||
.client
|
||||
.post(&self.mcp_url)
|
||||
.header(header::ACCEPT, "application/json")
|
||||
.header(header::AUTHORIZATION, format!("Bearer {}", self.api_key))
|
||||
.header("MCP-Protocol-Version", MODERN_REVISION)
|
||||
.header("Mcp-Method", method)
|
||||
.json(&json!({"jsonrpc": "2.0", "id": 5, "method": method, "params": params}))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
let status = response.status();
|
||||
let body = response.text().await.unwrap();
|
||||
serde_json::from_str(&body).unwrap_or_else(|error| {
|
||||
panic!("expected JSON for {method}, {status} {body:?}: {error}")
|
||||
})
|
||||
}
|
||||
|
||||
/// One modern request that offers both response modes and is expected to answer a JSON body
|
||||
/// (an admission or validation rejection, never a stream).
|
||||
async fn modern_offering_stream(&self, method: &str, params: Value) -> Value {
|
||||
let mut params = params;
|
||||
params["_meta"] = Self::modern_meta();
|
||||
let response = self
|
||||
.client
|
||||
.post(&self.mcp_url)
|
||||
.header(header::ACCEPT, "application/json, text/event-stream")
|
||||
.header(header::AUTHORIZATION, format!("Bearer {}", self.api_key))
|
||||
.header("MCP-Protocol-Version", MODERN_REVISION)
|
||||
.header("Mcp-Method", method)
|
||||
.json(&json!({"jsonrpc": "2.0", "id": 9, "method": method, "params": params}))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), reqwest::StatusCode::OK);
|
||||
let body = response.text().await.unwrap();
|
||||
serde_json::from_str(&body).unwrap_or_else(|error| {
|
||||
panic!("expected a JSON rejection for {method}: {body:?} {error}")
|
||||
})
|
||||
}
|
||||
|
||||
/// One legacy request inside the initialized session of this Agent.
|
||||
async fn legacy(&self, session: &str, method: &str, params: Value) -> Value {
|
||||
let response = self
|
||||
.client
|
||||
.post(&self.mcp_url)
|
||||
.header(header::ACCEPT, "application/json, text/event-stream")
|
||||
.header(header::AUTHORIZATION, format!("Bearer {}", self.api_key))
|
||||
.header("MCP-Protocol-Version", LEGACY_REVISION)
|
||||
.header("MCP-Session-Id", session)
|
||||
.json(&json!({"jsonrpc": "2.0", "id": 6, "method": method, "params": params}))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
let status = response.status();
|
||||
let body = response.text().await.unwrap();
|
||||
serde_json::from_str(&body).unwrap_or_else(|error| {
|
||||
panic!("expected JSON for {method}, {status} {body:?}: {error}")
|
||||
})
|
||||
}
|
||||
|
||||
async fn legacy_session(&self) -> String {
|
||||
initialize_session(&self.client, &self.mcp_url, &self.api_key).await
|
||||
}
|
||||
|
||||
/// The legacy notification stream (`GET`), consumed as an SSE response.
|
||||
async fn legacy_stream(&self, session: &str) -> SseResponse {
|
||||
let response = self
|
||||
.client
|
||||
.get(&self.mcp_url)
|
||||
.header(header::ACCEPT, "text/event-stream")
|
||||
.header(header::AUTHORIZATION, format!("Bearer {}", self.api_key))
|
||||
.header("MCP-Protocol-Version", LEGACY_REVISION)
|
||||
.header("MCP-Session-Id", session)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
SseResponse::assert_open(response).await
|
||||
}
|
||||
|
||||
/// Open the modern `subscriptions/listen` stream with an explicit filter.
|
||||
async fn listen(&self, request_id: Value, filter: Value) -> SseResponse {
|
||||
let params = json!({ "notifications": filter, "_meta": Self::modern_meta() });
|
||||
let response = self
|
||||
.client
|
||||
.post(&self.mcp_url)
|
||||
.header(header::ACCEPT, "text/event-stream")
|
||||
.header(header::AUTHORIZATION, format!("Bearer {}", self.api_key))
|
||||
.header("MCP-Protocol-Version", MODERN_REVISION)
|
||||
.header("Mcp-Method", "subscriptions/listen")
|
||||
.json(&json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": request_id,
|
||||
"method": "subscriptions/listen",
|
||||
"params": params
|
||||
}))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
SseResponse::assert_open(response).await
|
||||
}
|
||||
|
||||
fn agent_version(&self, version: u32) -> AgentVersion {
|
||||
AgentVersion {
|
||||
agent_id: self.agent_id.clone(),
|
||||
version,
|
||||
status: AgentStatus::Draft,
|
||||
instructions: json!({}),
|
||||
tool_selection_policy: ToolSelectionPolicy::default(),
|
||||
created_at: OffsetDateTime::now_utc(),
|
||||
}
|
||||
}
|
||||
|
||||
async fn open_draft(&self, version: u32) {
|
||||
self.registry
|
||||
.create_agent_draft_version(CreateAgentDraftVersionRequest {
|
||||
workspace_id: &test_workspace_id(),
|
||||
agent_id: &self.agent_id,
|
||||
version: &self.agent_version(version),
|
||||
bindings: &[],
|
||||
updated_at: &OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("a new Agent draft version opens");
|
||||
}
|
||||
|
||||
/// Write the exact catalog config of one draft version: Tool bindings, Resource bindings and
|
||||
/// Prompt bindings in the single accepted transition.
|
||||
async fn configure_draft(
|
||||
&self,
|
||||
version: u32,
|
||||
tool_bindings: &[crank_core::AgentOperationBinding],
|
||||
resource_bindings: &[AgentResourceBinding],
|
||||
prompt_bindings: &[AgentPromptBinding],
|
||||
) {
|
||||
self.registry
|
||||
.save_agent_catalog_config_editable_with_prompts(
|
||||
SaveAgentCatalogConfigRequest {
|
||||
workspace_id: &test_workspace_id(),
|
||||
agent_id: &self.agent_id,
|
||||
agent_version: version,
|
||||
bindings: tool_bindings,
|
||||
tool_selection_policy: &ToolSelectionPolicy::default(),
|
||||
resource_bindings,
|
||||
expected_state: None,
|
||||
},
|
||||
prompt_bindings,
|
||||
)
|
||||
.await
|
||||
.expect("the exact catalog config of the draft version saves");
|
||||
}
|
||||
|
||||
async fn publish_version(&self, version: u32) {
|
||||
self.registry
|
||||
.publish_agent(PublishAgentRequest {
|
||||
workspace_id: &test_workspace_id(),
|
||||
agent_id: &self.agent_id,
|
||||
version,
|
||||
published_at: &OffsetDateTime::now_utc(),
|
||||
published_by: Some("alice"),
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.expect("the draft Agent version publishes");
|
||||
}
|
||||
|
||||
fn tool_bindings(&self) -> Vec<crank_core::AgentOperationBinding> {
|
||||
vec![binding_for_operation(&self.operation)]
|
||||
}
|
||||
|
||||
fn both_tool_bindings(&self) -> Vec<crank_core::AgentOperationBinding> {
|
||||
vec![
|
||||
binding_for_operation(&self.operation),
|
||||
binding_for_operation(&self.second_operation),
|
||||
]
|
||||
}
|
||||
|
||||
fn base_prompts(&self) -> Vec<AgentPromptBinding> {
|
||||
vec![
|
||||
AgentPromptBinding {
|
||||
prompt_id: self.greeting.clone(),
|
||||
prompt_version: 1,
|
||||
},
|
||||
AgentPromptBinding {
|
||||
prompt_id: self.review.clone(),
|
||||
prompt_version: 1,
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
fn extended_prompts(&self) -> Vec<AgentPromptBinding> {
|
||||
let mut prompts = self.base_prompts();
|
||||
prompts.push(AgentPromptBinding {
|
||||
prompt_id: self.extra_prompt.clone(),
|
||||
prompt_version: 1,
|
||||
});
|
||||
prompts
|
||||
}
|
||||
|
||||
fn notice_binding(&self) -> AgentResourceBinding {
|
||||
AgentResourceBinding {
|
||||
resource_id: self.notice.clone(),
|
||||
resource_version: 1,
|
||||
}
|
||||
}
|
||||
|
||||
/// The draft version this Agent would open next, so the commit helpers do not depend on the
|
||||
/// order the test calls them in.
|
||||
async fn next_draft_version(&self) -> u32 {
|
||||
self.registry
|
||||
.get_agent_summary(&test_workspace_id(), &self.agent_id)
|
||||
.await
|
||||
.expect("the Agent summary reads")
|
||||
.expect("the fixture Agent exists")
|
||||
.current_draft_version
|
||||
+ 1
|
||||
}
|
||||
|
||||
/// The committed catalog change of AT-3.19-01: one Resource binding and one Prompt binding join
|
||||
/// the published Agent snapshot in a single publication.
|
||||
async fn commit_resource_and_prompt_change(&self) {
|
||||
let version = self.next_draft_version().await;
|
||||
self.open_draft(version).await;
|
||||
self.configure_draft(
|
||||
version,
|
||||
&self.tool_bindings(),
|
||||
&[self.notice_binding()],
|
||||
&self.extended_prompts(),
|
||||
)
|
||||
.await;
|
||||
self.publish_version(version).await;
|
||||
}
|
||||
|
||||
/// A commit that only changes the Tool catalog: the visible Resource/Prompt projection is
|
||||
/// identical, so it must not produce a Resource or Prompt signal.
|
||||
async fn commit_tool_only_change(&self) {
|
||||
let version = self.next_draft_version().await;
|
||||
self.open_draft(version).await;
|
||||
self.configure_draft(
|
||||
version,
|
||||
&self.both_tool_bindings(),
|
||||
&[self.notice_binding()],
|
||||
&self.extended_prompts(),
|
||||
)
|
||||
.await;
|
||||
self.publish_version(version).await;
|
||||
}
|
||||
|
||||
/// A commit that only changes the Resource catalog: the visible Prompt projection is identical,
|
||||
/// so it must produce a Resource signal only.
|
||||
async fn commit_resource_only_change(&self) {
|
||||
let version = self.next_draft_version().await;
|
||||
self.open_draft(version).await;
|
||||
self.configure_draft(
|
||||
version,
|
||||
&self.tool_bindings(),
|
||||
&[self.notice_binding()],
|
||||
&self.base_prompts(),
|
||||
)
|
||||
.await;
|
||||
self.publish_version(version).await;
|
||||
}
|
||||
|
||||
/// A commit that only changes the Prompt catalog: the visible Resource projection is identical,
|
||||
/// so it must produce a Prompt signal only.
|
||||
async fn commit_prompt_only_change(&self) {
|
||||
let version = self.next_draft_version().await;
|
||||
self.open_draft(version).await;
|
||||
self.configure_draft(
|
||||
version,
|
||||
&self.tool_bindings(),
|
||||
&[self.notice_binding()],
|
||||
&self.extended_prompts(),
|
||||
)
|
||||
.await;
|
||||
self.publish_version(version).await;
|
||||
}
|
||||
|
||||
/// A draft-only edit: nothing is published, so no committed catalog state changed.
|
||||
async fn edit_draft_without_publishing(&self) {
|
||||
let version = self.next_draft_version().await;
|
||||
self.open_draft(version).await;
|
||||
self.configure_draft(
|
||||
version,
|
||||
&self.both_tool_bindings(),
|
||||
&[self.notice_binding()],
|
||||
&self.base_prompts(),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
/// A live SSE response, read event by event.
|
||||
struct SseResponse {
|
||||
response: reqwest::Response,
|
||||
buffer: String,
|
||||
}
|
||||
|
||||
impl SseResponse {
|
||||
async fn assert_open(response: reqwest::Response) -> Self {
|
||||
assert_eq!(
|
||||
response.status(),
|
||||
reqwest::StatusCode::OK,
|
||||
"the notification stream must be served"
|
||||
);
|
||||
let content_type = response
|
||||
.headers()
|
||||
.get(header::CONTENT_TYPE)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.unwrap_or_default()
|
||||
.to_owned();
|
||||
assert!(
|
||||
content_type.starts_with("text/event-stream"),
|
||||
"the notification stream must be an SSE response, got {content_type}"
|
||||
);
|
||||
Self {
|
||||
response,
|
||||
buffer: String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The payload of the next `data:` frame, or `None` when nothing arrived within `timeout`.
|
||||
async fn next_data(&mut self, timeout: Duration) -> Option<Value> {
|
||||
loop {
|
||||
if let Some(index) = self.buffer.find("\n\n") {
|
||||
let block: String = self.buffer.drain(..index + 2).collect();
|
||||
for line in block.lines() {
|
||||
if let Some(data) = line.strip_prefix("data:") {
|
||||
return Some(
|
||||
serde_json::from_str(data.trim_start())
|
||||
.unwrap_or_else(|error| panic!("SSE frame must be JSON: {error}")),
|
||||
);
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let chunk = tokio::time::timeout(timeout, self.response.chunk())
|
||||
.await
|
||||
.ok()?
|
||||
.ok()??;
|
||||
self.buffer.push_str(&String::from_utf8_lossy(&chunk));
|
||||
}
|
||||
}
|
||||
|
||||
/// The next frame within the watcher's bound.
|
||||
async fn expect_frame(&mut self, what: &str) -> Value {
|
||||
self.next_data(Duration::from_secs(6))
|
||||
.await
|
||||
.unwrap_or_else(|| panic!("expected {what} on the notification stream"))
|
||||
}
|
||||
|
||||
/// Exactly one safe negative window: no frame within `wait`.
|
||||
async fn expect_silence(&mut self, wait: Duration, what: &str) {
|
||||
if let Some(frame) = self.next_data(wait).await {
|
||||
panic!("expected no {what}, got {frame}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn publish_prompt(registry: &PostgresRegistry, prompt_id: &PromptId, name: &str) -> PromptId {
|
||||
let definition = PromptDefinition::parse(&json!({
|
||||
"name": name,
|
||||
"description": format!("{name} fixture"),
|
||||
"arguments": [],
|
||||
"messages": [{"role": "user", "content": format!("Use {name}.")}]
|
||||
}))
|
||||
.expect("the fixture Prompt definition is valid");
|
||||
let created = registry
|
||||
.create_prompt_draft(CreatePromptDraftRequest {
|
||||
workspace_id: test_workspace_id(),
|
||||
prompt_id: prompt_id.clone(),
|
||||
sensitivity: PromptSensitivity::Internal,
|
||||
definition,
|
||||
created_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("the Prompt Draft is created");
|
||||
registry
|
||||
.publish_prompt_draft(PublishPromptRequest {
|
||||
workspace_id: test_workspace_id(),
|
||||
prompt_id: prompt_id.clone(),
|
||||
expected_updated_at: created.updated_at,
|
||||
published_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("the Prompt version publishes");
|
||||
prompt_id.clone()
|
||||
}
|
||||
|
||||
/// Publish one static Resource through the production 3.6/3.7 registry transition.
|
||||
async fn publish_resource(
|
||||
registry: &PostgresRegistry,
|
||||
store: &ArtifactStore,
|
||||
resource_id: &ResourceId,
|
||||
bytes: &[u8],
|
||||
) {
|
||||
let artifact = store
|
||||
.put_registered(bytes)
|
||||
.expect("the fixture bytes are registered durably");
|
||||
registry
|
||||
.create_resource_draft(CreateResourceDraftRequest {
|
||||
workspace_id: test_workspace_id(),
|
||||
resource_id: resource_id.clone(),
|
||||
uri: format!("crank://resources/{}", resource_id.as_str()),
|
||||
name: resource_id.as_str().to_owned(),
|
||||
description: "Story 3.19 signal fixture".to_owned(),
|
||||
kind: "text".to_owned(),
|
||||
mime_type: "text/plain".to_owned(),
|
||||
sensitivity: "internal".to_owned(),
|
||||
artifact,
|
||||
created_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("the Resource Draft is created");
|
||||
let current = registry
|
||||
.get_resource_draft(test_workspace_id().as_str(), resource_id)
|
||||
.await
|
||||
.expect("the Resource Draft reads");
|
||||
registry
|
||||
.publish_resource_version(PublishResourceVersionRequest {
|
||||
workspace_id: test_workspace_id(),
|
||||
resource_id: resource_id.clone(),
|
||||
expected_updated_at: current.resource.updated_at,
|
||||
expected_version: current.version.version,
|
||||
expected_digest: current.version.digest.clone(),
|
||||
expected_size_bytes: current.version.size_bytes,
|
||||
artifact: store
|
||||
.put_registered(bytes)
|
||||
.expect("the published bytes are registered durably"),
|
||||
published_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("the Resource version publishes");
|
||||
}
|
||||
|
||||
async fn signals_endpoint() -> SignalsEndpoint {
|
||||
let root = TestRoot::new();
|
||||
let artifact_store = ArtifactStore::open(root.0.clone()).expect("the artifact store opens");
|
||||
let registry = test_registry().await;
|
||||
let upstream_base_url = spawn_upstream_server().await;
|
||||
|
||||
let operation = test_operation(&upstream_base_url, "crm_create_lead");
|
||||
registry
|
||||
.create_operation(&test_workspace_id(), &operation, Some("alice"))
|
||||
.await
|
||||
.unwrap();
|
||||
registry
|
||||
.publish_operation(PublishRequest {
|
||||
workspace_id: &test_workspace_id(),
|
||||
operation_id: &operation.id,
|
||||
version: 1,
|
||||
published_at: &OffsetDateTime::now_utc(),
|
||||
published_by: Some("alice"),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let second_operation = test_operation(&upstream_base_url, "crm_create_second");
|
||||
registry
|
||||
.create_operation(&test_workspace_id(), &second_operation, Some("alice"))
|
||||
.await
|
||||
.unwrap();
|
||||
registry
|
||||
.publish_operation(PublishRequest {
|
||||
workspace_id: &test_workspace_id(),
|
||||
operation_id: &second_operation.id,
|
||||
version: 1,
|
||||
published_at: &OffsetDateTime::now_utc(),
|
||||
published_by: Some("alice"),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let greeting = publish_prompt(®istry, &PromptId::new("prm_a_greeting"), "greeting").await;
|
||||
let review = publish_prompt(®istry, &PromptId::new("prm_b_review"), "review").await;
|
||||
let extra_prompt = publish_prompt(®istry, &PromptId::new("prm_c_extra"), "extra").await;
|
||||
let notice = ResourceId::new("res_a_notice");
|
||||
publish_resource(®istry, &artifact_store, ¬ice, b"first notice").await;
|
||||
|
||||
let agent_id = AgentId::new(format!("agent_{AGENT_SLUG}"));
|
||||
let now = OffsetDateTime::now_utc();
|
||||
registry
|
||||
.create_agent(CreateAgentRequest {
|
||||
agent: &Agent {
|
||||
id: agent_id.clone(),
|
||||
workspace_id: test_workspace_id(),
|
||||
slug: AGENT_SLUG.to_owned(),
|
||||
display_name: AGENT_SLUG.to_owned(),
|
||||
description: "Story 3.19 signal fixture".to_owned(),
|
||||
status: AgentStatus::Draft,
|
||||
current_draft_version: 1,
|
||||
latest_published_version: None,
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
published_at: None,
|
||||
},
|
||||
version: &AgentVersion {
|
||||
agent_id: agent_id.clone(),
|
||||
version: 1,
|
||||
status: AgentStatus::Draft,
|
||||
instructions: json!({}),
|
||||
tool_selection_policy: ToolSelectionPolicy::default(),
|
||||
created_at: now,
|
||||
},
|
||||
bindings: &[binding_for_operation(&operation)],
|
||||
})
|
||||
.await
|
||||
.expect("the draft Agent is created");
|
||||
registry
|
||||
.save_agent_catalog_config_editable_with_prompts(
|
||||
SaveAgentCatalogConfigRequest {
|
||||
workspace_id: &test_workspace_id(),
|
||||
agent_id: &agent_id,
|
||||
agent_version: 1,
|
||||
bindings: &[binding_for_operation(&operation)],
|
||||
tool_selection_policy: &ToolSelectionPolicy::default(),
|
||||
resource_bindings: &[],
|
||||
expected_state: None,
|
||||
},
|
||||
&[
|
||||
AgentPromptBinding {
|
||||
prompt_id: greeting.clone(),
|
||||
prompt_version: 1,
|
||||
},
|
||||
AgentPromptBinding {
|
||||
prompt_id: review.clone(),
|
||||
prompt_version: 1,
|
||||
},
|
||||
],
|
||||
)
|
||||
.await
|
||||
.expect("the exact bound Prompt versions are accepted");
|
||||
registry
|
||||
.publish_agent(PublishAgentRequest {
|
||||
workspace_id: &test_workspace_id(),
|
||||
agent_id: &agent_id,
|
||||
version: 1,
|
||||
published_at: &OffsetDateTime::now_utc(),
|
||||
published_by: Some("alice"),
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.expect("the bound Agent publishes");
|
||||
|
||||
let api_key = create_platform_api_key(
|
||||
®istry,
|
||||
AGENT_SLUG,
|
||||
"mcp-signals",
|
||||
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
|
||||
)
|
||||
.await;
|
||||
let base_url = spawn_mcp_server(build_test_app_with_artifacts(
|
||||
registry.clone(),
|
||||
Duration::from_millis(0),
|
||||
None,
|
||||
artifact_store.clone(),
|
||||
))
|
||||
.await;
|
||||
|
||||
SignalsEndpoint {
|
||||
client: reqwest::Client::new(),
|
||||
mcp_url: agent_mcp_url(&base_url, AGENT_SLUG),
|
||||
base_url,
|
||||
api_key,
|
||||
registry,
|
||||
artifact_store,
|
||||
root,
|
||||
agent_id,
|
||||
operation,
|
||||
second_operation,
|
||||
greeting,
|
||||
review,
|
||||
extra_prompt,
|
||||
notice,
|
||||
}
|
||||
}
|
||||
|
||||
fn prompt_names(list: &Value) -> Vec<String> {
|
||||
list["result"]["prompts"]
|
||||
.as_array()
|
||||
.unwrap_or_else(|| panic!("prompts/list must return a page: {list}"))
|
||||
.iter()
|
||||
.map(|prompt| prompt["name"].as_str().unwrap().to_owned())
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn resource_uris(list: &Value) -> Vec<String> {
|
||||
list["result"]["resources"]
|
||||
.as_array()
|
||||
.unwrap_or_else(|| panic!("resources/list must return a page: {list}"))
|
||||
.iter()
|
||||
.map(|resource| resource["uri"].as_str().unwrap().to_owned())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Write a stand file that only the current user may read (credential files live here).
|
||||
fn write_private(path: &PathBuf, contents: &str) {
|
||||
use std::io::Write as _;
|
||||
use std::os::unix::fs::OpenOptionsExt as _;
|
||||
let mut file = fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.truncate(true)
|
||||
.write(true)
|
||||
.mode(0o600)
|
||||
.open(path)
|
||||
.unwrap_or_else(|error| panic!("stand file {path:?} must be writable: {error}"));
|
||||
file.write_all(contents.as_bytes())
|
||||
.expect("the stand file must be written");
|
||||
}
|
||||
@@ -0,0 +1,416 @@
|
||||
//! Story 3.19 acceptance scenarios (AT-3.19-01..03, FR-19) on the harness in the parent module.
|
||||
//!
|
||||
//! Moved out of `mcp_signals.rs` verbatim (code-health split, 1000-line limit); no scenario,
|
||||
//! assertion or fixture changed.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Loopback disposable stand for the AC-3 representative-client evidence. This is deliberately not
|
||||
/// part of the automated ATDD: it publishes the fixture catalog, serves the real MCP endpoint on
|
||||
/// `127.0.0.1`, and then performs one commit per command file so an external MCP client can observe
|
||||
/// the signals on its own stream.
|
||||
///
|
||||
/// Run it explicitly (the credential file is `0600` and never printed):
|
||||
///
|
||||
/// ```text
|
||||
/// MCP_SIGNALS_STAND_DIR=/tmp/crank-signals-stand \
|
||||
/// cargo test -p mcp-server --test integration mcp_signals::scenarios::representative_client_stand \
|
||||
/// -- --ignored --exact --nocapture
|
||||
/// ```
|
||||
///
|
||||
/// Commands (create the file, wait for `<command>.done`): `commit-both`, `commit-prompt`,
|
||||
/// `commit-resource`, `commit-tool`, `draft`, `stop`.
|
||||
#[tokio::test]
|
||||
#[ignore = "manual loopback stand for the representative MCP Inspector client evidence"]
|
||||
async fn representative_client_stand() {
|
||||
let directory = PathBuf::from(
|
||||
std::env::var("MCP_SIGNALS_STAND_DIR")
|
||||
.expect("MCP_SIGNALS_STAND_DIR names the disposable stand directory"),
|
||||
);
|
||||
fs::create_dir_all(&directory).expect("the stand directory is creatable");
|
||||
let endpoint = signals_endpoint().await;
|
||||
write_private(
|
||||
&directory.join("stand.json"),
|
||||
&json!({ "url": endpoint.mcp_url, "token": endpoint.api_key }).to_string(),
|
||||
);
|
||||
println!("stand ready: {}", directory.join("stand.json").display());
|
||||
|
||||
let deadline = tokio::time::Instant::now() + Duration::from_secs(900);
|
||||
while tokio::time::Instant::now() < deadline {
|
||||
for command in [
|
||||
"commit-both",
|
||||
"commit-prompt",
|
||||
"commit-resource",
|
||||
"commit-tool",
|
||||
"draft",
|
||||
"stop",
|
||||
] {
|
||||
let marker = directory.join(command);
|
||||
if !marker.exists() {
|
||||
continue;
|
||||
}
|
||||
fs::remove_file(&marker).expect("the command file is consumed once");
|
||||
if command == "stop" {
|
||||
println!("stand stopped: {command}");
|
||||
return;
|
||||
}
|
||||
match command {
|
||||
"commit-both" => endpoint.commit_resource_and_prompt_change().await,
|
||||
"commit-prompt" => endpoint.commit_prompt_only_change().await,
|
||||
"commit-resource" => endpoint.commit_resource_only_change().await,
|
||||
"commit-tool" => endpoint.commit_tool_only_change().await,
|
||||
_ => endpoint.edit_draft_without_publishing().await,
|
||||
}
|
||||
write_private(&directory.join(format!("{command}.done")), "done");
|
||||
println!("stand committed: {command}");
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// AT-3.19-01 (legacy): an open notification stream receives the Resource and Prompt list-change
|
||||
/// notifications only after the catalog commit, and `resources/list` / `prompts/list` serve the new
|
||||
/// state afterwards.
|
||||
#[tokio::test]
|
||||
async fn legacy_stream_announces_a_committed_catalog_change_after_the_commit() {
|
||||
let endpoint = signals_endpoint().await;
|
||||
let session = endpoint.legacy_session().await;
|
||||
|
||||
let mut stream = endpoint.legacy_stream(&session).await;
|
||||
// The watcher takes its baseline before it can report anything; let it settle before the commit.
|
||||
tokio::time::sleep(Duration::from_millis(1_500)).await;
|
||||
stream
|
||||
.expect_silence(Duration::from_millis(1_200), "signal before any commit")
|
||||
.await;
|
||||
|
||||
// A draft-only edit is not a commit: nothing is announced.
|
||||
endpoint.edit_draft_without_publishing().await;
|
||||
stream
|
||||
.expect_silence(Duration::from_millis(2_500), "signal for a draft-only edit")
|
||||
.await;
|
||||
|
||||
endpoint.commit_resource_and_prompt_change().await;
|
||||
|
||||
let mut methods = Vec::new();
|
||||
for _ in 0..2 {
|
||||
let frame = stream
|
||||
.expect_frame("the committed list-change signals")
|
||||
.await;
|
||||
assert_eq!(frame["jsonrpc"], json!("2.0"));
|
||||
assert!(
|
||||
frame.get("params").is_none(),
|
||||
"a legacy list-change notification carries no parameters: {frame}"
|
||||
);
|
||||
methods.push(frame["method"].as_str().unwrap().to_owned());
|
||||
}
|
||||
methods.sort();
|
||||
assert_eq!(
|
||||
methods,
|
||||
vec![
|
||||
PROMPT_LIST_CHANGED.to_owned(),
|
||||
RESOURCE_LIST_CHANGED.to_owned()
|
||||
],
|
||||
"one signal per changed catalog type"
|
||||
);
|
||||
|
||||
// The ordinary list methods are authoritative for the same committed state.
|
||||
let prompts = endpoint.legacy(&session, "prompts/list", json!({})).await;
|
||||
assert!(
|
||||
prompt_names(&prompts).contains(&"extra".to_owned()),
|
||||
"prompts/list must serve the newly bound Prompt: {prompts}"
|
||||
);
|
||||
let resources = endpoint.legacy(&session, "resources/list", json!({})).await;
|
||||
assert!(
|
||||
resource_uris(&resources)
|
||||
.iter()
|
||||
.any(|uri| uri == &format!("crank://resources/{}", endpoint.notice.as_str())),
|
||||
"resources/list must serve the newly bound Resource: {resources}"
|
||||
);
|
||||
|
||||
// A Tool-only commit keeps the Resource/Prompt projection: no further signal.
|
||||
endpoint.commit_tool_only_change().await;
|
||||
stream
|
||||
.expect_silence(
|
||||
Duration::from_millis(2_500),
|
||||
"signal for a Tool-only commit",
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
/// AT-3.19-01/03 (modern): `subscriptions/listen` acknowledges the honoured filter with the request
|
||||
/// id, then delivers coalesced list-change notifications carrying the subscription id.
|
||||
#[tokio::test]
|
||||
async fn modern_listen_stream_acknowledges_then_announces_coalesced_changes() {
|
||||
let endpoint = signals_endpoint().await;
|
||||
let mut stream = endpoint
|
||||
.listen(
|
||||
json!(41),
|
||||
json!({
|
||||
"resourcesListChanged": true,
|
||||
"promptsListChanged": true,
|
||||
"toolsListChanged": true,
|
||||
"resourceSubscriptions": ["crank://resources/res_a_notice"]
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
|
||||
let acknowledgement = stream.expect_frame("the acknowledgment").await;
|
||||
assert_eq!(acknowledgement["method"], SUBSCRIPTIONS_ACKNOWLEDGED);
|
||||
assert_eq!(
|
||||
acknowledgement["params"]["_meta"][SUBSCRIPTION_ID_KEY],
|
||||
json!(41)
|
||||
);
|
||||
assert_eq!(
|
||||
acknowledgement["params"]["notifications"],
|
||||
json!({ "promptsListChanged": true, "resourcesListChanged": true }),
|
||||
"only the implemented list-change types are acknowledged: {acknowledgement}"
|
||||
);
|
||||
|
||||
tokio::time::sleep(Duration::from_millis(1_500)).await;
|
||||
|
||||
// Two commits in quick succession coalesce into one signal per changed type.
|
||||
endpoint.commit_resource_and_prompt_change().await;
|
||||
endpoint.commit_tool_only_change().await;
|
||||
|
||||
let mut methods = Vec::new();
|
||||
for _ in 0..2 {
|
||||
let frame = stream
|
||||
.expect_frame("the coalesced list-change signal")
|
||||
.await;
|
||||
assert_eq!(frame["params"]["_meta"][SUBSCRIPTION_ID_KEY], json!(41));
|
||||
methods.push(frame["method"].as_str().unwrap().to_owned());
|
||||
}
|
||||
methods.sort();
|
||||
assert_eq!(
|
||||
methods,
|
||||
vec![
|
||||
PROMPT_LIST_CHANGED.to_owned(),
|
||||
RESOURCE_LIST_CHANGED.to_owned()
|
||||
]
|
||||
);
|
||||
stream
|
||||
.expect_silence(
|
||||
Duration::from_millis(2_500),
|
||||
"a duplicate or unrequested signal",
|
||||
)
|
||||
.await;
|
||||
|
||||
// A client that missed every notification still recovers the authoritative catalog.
|
||||
let prompts = endpoint.modern("prompts/list", json!({})).await;
|
||||
assert!(
|
||||
prompt_names(&prompts).contains(&"extra".to_owned()),
|
||||
"{prompts}"
|
||||
);
|
||||
}
|
||||
|
||||
/// AT-3.19-01/03 (modern): the acknowledged filter is the delivery contract. A prompts-only stream
|
||||
/// stays silent for a Resource-only commit, delivers exactly one Prompt frame with the subscription
|
||||
/// id for a Prompt commit, and never delivers an unrequested type.
|
||||
#[tokio::test]
|
||||
async fn modern_listen_delivers_only_the_negotiated_signal_types() {
|
||||
let endpoint = signals_endpoint().await;
|
||||
let mut stream = endpoint
|
||||
.listen(
|
||||
json!("prompts-only"),
|
||||
json!({
|
||||
"promptsListChanged": true,
|
||||
"toolsListChanged": true,
|
||||
"resourceSubscriptions": ["crank://resources/res_a_notice"]
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
|
||||
let acknowledgement = stream.expect_frame("the acknowledgment").await;
|
||||
assert_eq!(acknowledgement["method"], SUBSCRIPTIONS_ACKNOWLEDGED);
|
||||
assert_eq!(
|
||||
acknowledgement["params"]["_meta"][SUBSCRIPTION_ID_KEY],
|
||||
json!("prompts-only")
|
||||
);
|
||||
assert_eq!(
|
||||
acknowledgement["params"]["notifications"],
|
||||
json!({ "promptsListChanged": true }),
|
||||
"only the implemented and requested type is acknowledged: {acknowledgement}"
|
||||
);
|
||||
|
||||
// The watcher takes its baseline before it can report anything.
|
||||
tokio::time::sleep(Duration::from_millis(1_500)).await;
|
||||
|
||||
// A Resource-only commit is outside the negotiated filter: a server that ignored the filter would
|
||||
// emit a Resource frame here.
|
||||
endpoint.commit_resource_only_change().await;
|
||||
stream
|
||||
.expect_silence(
|
||||
Duration::from_millis(2_500),
|
||||
"signal for a Resource-only commit on a prompts-only stream",
|
||||
)
|
||||
.await;
|
||||
|
||||
// A Prompt-only commit is inside it: exactly one frame, correlated by the subscription id.
|
||||
endpoint.commit_prompt_only_change().await;
|
||||
let frame = stream
|
||||
.expect_frame("the negotiated Prompt list-change signal")
|
||||
.await;
|
||||
assert_eq!(frame["method"], PROMPT_LIST_CHANGED);
|
||||
assert_eq!(
|
||||
frame["params"]["_meta"][SUBSCRIPTION_ID_KEY],
|
||||
json!("prompts-only")
|
||||
);
|
||||
|
||||
// Neither `toolsListChanged` nor `resourceSubscriptions` were honoured, so nothing else follows.
|
||||
stream
|
||||
.expect_silence(
|
||||
Duration::from_millis(2_500),
|
||||
"a duplicate, Tools or URI-content signal",
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
/// AT-3.19-03: the unsupported URI-content subscription surface is never acknowledged, and the
|
||||
/// legacy revision has no `subscriptions/listen` request at all.
|
||||
#[tokio::test]
|
||||
async fn unsupported_subscription_surfaces_are_refused_rather_than_faked() {
|
||||
let endpoint = signals_endpoint().await;
|
||||
|
||||
for method in ["resources/subscribe", "resources/unsubscribe"] {
|
||||
let reply = endpoint
|
||||
.modern(method, json!({ "uri": "crank://resources/res_a_notice" }))
|
||||
.await;
|
||||
assert_eq!(
|
||||
reply["error"]["code"],
|
||||
json!(-32601),
|
||||
"{method} must stay unimplemented: {reply}"
|
||||
);
|
||||
}
|
||||
|
||||
// The legacy revision opens its notification stream with GET only.
|
||||
let session = endpoint.legacy_session().await;
|
||||
let legacy_listen = endpoint
|
||||
.legacy(
|
||||
&session,
|
||||
"subscriptions/listen",
|
||||
json!({ "notifications": {} }),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
legacy_listen["error"]["code"],
|
||||
json!(-32601),
|
||||
"subscriptions/listen is a modern-only request: {legacy_listen}"
|
||||
);
|
||||
|
||||
// A malformed filter is a bounded invalid-params answer with no echoed value.
|
||||
let malformed = endpoint
|
||||
.modern_offering_stream(
|
||||
"subscriptions/listen",
|
||||
json!({ "notifications": ["promptsListChanged"] }),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(malformed["error"]["code"], json!(-32602));
|
||||
assert_eq!(
|
||||
malformed["error"]["message"],
|
||||
json!("invalid subscriptions/listen notification filter")
|
||||
);
|
||||
|
||||
// Without an SSE-capable client the stream cannot be served at all.
|
||||
let without_sse = endpoint
|
||||
.client
|
||||
.post(&endpoint.mcp_url)
|
||||
.header(header::ACCEPT, "application/json")
|
||||
.header(
|
||||
header::AUTHORIZATION,
|
||||
format!("Bearer {}", endpoint.api_key),
|
||||
)
|
||||
.header("MCP-Protocol-Version", MODERN_REVISION)
|
||||
.header("Mcp-Method", "subscriptions/listen")
|
||||
.json(&json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": 42,
|
||||
"method": "subscriptions/listen",
|
||||
"params": {
|
||||
"notifications": { "promptsListChanged": true },
|
||||
"_meta": SignalsEndpoint::modern_meta()
|
||||
}
|
||||
}))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(without_sse.status(), reqwest::StatusCode::NOT_ACCEPTABLE);
|
||||
}
|
||||
|
||||
/// AT-3.19-02: a missed notification never loses committed state — a legacy client re-initializes
|
||||
/// (the retired session is a safe `404`) and reads the authoritative catalog, while the modern
|
||||
/// stateless client recovers through `server/discover` and the list methods.
|
||||
#[tokio::test]
|
||||
async fn a_lost_notification_is_recovered_through_the_authoritative_methods() {
|
||||
let endpoint = signals_endpoint().await;
|
||||
|
||||
// Modern recovery: the commit happens with no stream open at all.
|
||||
endpoint.commit_resource_and_prompt_change().await;
|
||||
let discover = endpoint.modern("server/discover", json!({})).await;
|
||||
assert_eq!(
|
||||
discover["result"]["capabilities"]["prompts"]["listChanged"],
|
||||
json!(true)
|
||||
);
|
||||
assert_eq!(
|
||||
discover["result"]["capabilities"]["resources"]["listChanged"],
|
||||
json!(true)
|
||||
);
|
||||
let resources = endpoint.modern("resources/list", json!({})).await;
|
||||
assert!(
|
||||
resource_uris(&resources)
|
||||
.iter()
|
||||
.any(|uri| uri == &format!("crank://resources/{}", endpoint.notice.as_str())),
|
||||
"the committed Resource is served to a client that missed the signal: {resources}"
|
||||
);
|
||||
|
||||
// Legacy recovery: the negotiated session can be dropped, and the revision-correct answer is a
|
||||
// safe `404` that makes the client re-initialize instead of resuming a stale stream.
|
||||
let session = endpoint.legacy_session().await;
|
||||
let mut stream = endpoint.legacy_stream(&session).await;
|
||||
tokio::time::sleep(Duration::from_millis(1_500)).await;
|
||||
|
||||
let deleted = endpoint
|
||||
.client
|
||||
.delete(&endpoint.mcp_url)
|
||||
.header(
|
||||
header::AUTHORIZATION,
|
||||
format!("Bearer {}", endpoint.api_key),
|
||||
)
|
||||
.header("MCP-Protocol-Version", LEGACY_REVISION)
|
||||
.header("MCP-Session-Id", &session)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(deleted.status(), reqwest::StatusCode::NO_CONTENT);
|
||||
stream
|
||||
.expect_silence(
|
||||
Duration::from_millis(2_500),
|
||||
"a signal on the retired session",
|
||||
)
|
||||
.await;
|
||||
|
||||
let stale_get = endpoint
|
||||
.client
|
||||
.get(&endpoint.mcp_url)
|
||||
.header(header::ACCEPT, "text/event-stream")
|
||||
.header(
|
||||
header::AUTHORIZATION,
|
||||
format!("Bearer {}", endpoint.api_key),
|
||||
)
|
||||
.header("MCP-Protocol-Version", LEGACY_REVISION)
|
||||
.header("MCP-Session-Id", &session)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
stale_get.status(),
|
||||
reqwest::StatusCode::NOT_FOUND,
|
||||
"a retired session is never resumed"
|
||||
);
|
||||
|
||||
let fresh = endpoint.legacy_session().await;
|
||||
let prompts = endpoint.legacy(&fresh, "prompts/list", json!({})).await;
|
||||
assert!(
|
||||
prompt_names(&prompts).contains(&"extra".to_owned()),
|
||||
"re-initialization serves the authoritative catalog: {prompts}"
|
||||
);
|
||||
}
|
||||
@@ -114,8 +114,8 @@ fn now_rfc3339() -> String {
|
||||
.unwrap_or_else(|error| format!("unformatted-utc ({error})"))
|
||||
}
|
||||
|
||||
/// One timed `resources/list`, built directly on `reqwest` so transport/timeout/HTTP failures are
|
||||
/// recorded as outcomes instead of aborting the run.
|
||||
/// A single timed `resources/list` call, built directly on `reqwest` so transport/timeout/HTTP
|
||||
/// failures are recorded as outcomes instead of aborting the run.
|
||||
async fn timed_list(
|
||||
endpoint: &ResourceEndpoint,
|
||||
revision: &'static str,
|
||||
|
||||
+94
-25
@@ -1,18 +1,56 @@
|
||||
use super::*;
|
||||
use std::process::Command;
|
||||
use std::{
|
||||
env,
|
||||
io::{Read, Write},
|
||||
net::{TcpListener, TcpStream, ToSocketAddrs},
|
||||
process::Command,
|
||||
thread,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
pub(super) struct TestValkey(String);
|
||||
|
||||
impl TestValkey {
|
||||
pub(super) fn start() -> (Self, u16) {
|
||||
let output = Command::new("docker")
|
||||
.args([
|
||||
"run",
|
||||
"--detach",
|
||||
"--publish",
|
||||
"127.0.0.1::6379",
|
||||
"valkey/valkey:8-alpine",
|
||||
])
|
||||
let in_docker_job = if std::path::Path::new("/.dockerenv").exists() {
|
||||
let hostname = env::var("HOSTNAME").unwrap_or_default();
|
||||
assert!(
|
||||
matches!(hostname.len(), 12 | 64)
|
||||
&& hostname.bytes().all(|byte| byte.is_ascii_hexdigit()),
|
||||
"Docker job hostname must be a full 12- or 64-character container ID"
|
||||
);
|
||||
Some(hostname)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let port = if in_docker_job.is_some() {
|
||||
let listener = TcpListener::bind(("127.0.0.1", 0))
|
||||
.expect("test-owned Valkey loopback port must be available");
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
drop(listener);
|
||||
Some(port)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let mut docker = Command::new("docker");
|
||||
docker.args([
|
||||
"run",
|
||||
"--detach",
|
||||
"--label",
|
||||
"crank.test.fixture=static-resources-valkey",
|
||||
]);
|
||||
if let (Some(hostname), Some(port)) = (&in_docker_job, port) {
|
||||
docker
|
||||
.arg("--network")
|
||||
.arg(format!("container:{hostname}"))
|
||||
.arg("valkey/valkey:8-alpine")
|
||||
.args(["valkey-server", "--port", &port.to_string()]);
|
||||
} else {
|
||||
docker.args(["--publish", "127.0.0.1::6379", "valkey/valkey:8-alpine"]);
|
||||
}
|
||||
let output = docker
|
||||
.output()
|
||||
.expect("Docker CLI must start the test-owned Valkey container");
|
||||
assert!(
|
||||
@@ -25,22 +63,29 @@ impl TestValkey {
|
||||
.trim()
|
||||
.to_owned();
|
||||
let valkey = Self(id);
|
||||
let port_output = Command::new("docker")
|
||||
.args(["port", &valkey.0, "6379/tcp"])
|
||||
.output()
|
||||
.expect("Docker CLI must report the test-owned port");
|
||||
assert!(
|
||||
port_output.status.success(),
|
||||
"test-owned Valkey port must be available"
|
||||
);
|
||||
let address = String::from_utf8(port_output.stdout).expect("Docker port must be UTF-8");
|
||||
let port = address
|
||||
.trim()
|
||||
.rsplit(':')
|
||||
.next()
|
||||
.unwrap()
|
||||
.parse()
|
||||
.expect("Docker mapped port must be numeric");
|
||||
let port = match port {
|
||||
Some(port) => port,
|
||||
None => {
|
||||
let port_output = Command::new("docker")
|
||||
.args(["port", &valkey.0, "6379/tcp"])
|
||||
.output()
|
||||
.expect("Docker CLI must report the test-owned port");
|
||||
assert!(
|
||||
port_output.status.success(),
|
||||
"test-owned Valkey port must be available"
|
||||
);
|
||||
let address =
|
||||
String::from_utf8(port_output.stdout).expect("Docker port must be UTF-8");
|
||||
address
|
||||
.trim()
|
||||
.rsplit(':')
|
||||
.next()
|
||||
.unwrap()
|
||||
.parse()
|
||||
.expect("Docker mapped port must be numeric")
|
||||
}
|
||||
};
|
||||
wait_for_valkey(port);
|
||||
(valkey, port)
|
||||
}
|
||||
|
||||
@@ -53,6 +98,30 @@ impl TestValkey {
|
||||
}
|
||||
}
|
||||
|
||||
fn wait_for_valkey(port: u16) {
|
||||
let address = ("127.0.0.1", port)
|
||||
.to_socket_addrs()
|
||||
.expect("test-owned Valkey loopback address must resolve")
|
||||
.next()
|
||||
.unwrap();
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
while Instant::now() < deadline {
|
||||
if let Ok(mut stream) = TcpStream::connect_timeout(&address, Duration::from_millis(250)) {
|
||||
let _ = stream.set_read_timeout(Some(Duration::from_millis(250)));
|
||||
let _ = stream.set_write_timeout(Some(Duration::from_millis(250)));
|
||||
let mut reply = [0_u8; 7];
|
||||
if stream.write_all(b"*1\r\n$4\r\nPING\r\n").is_ok()
|
||||
&& stream.read_exact(&mut reply).is_ok()
|
||||
&& &reply == b"+PONG\r\n"
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
thread::sleep(Duration::from_millis(100));
|
||||
}
|
||||
panic!("test-owned Valkey did not answer PING on 127.0.0.1:{port} within 10 seconds");
|
||||
}
|
||||
|
||||
impl Drop for TestValkey {
|
||||
fn drop(&mut self) {
|
||||
let _ = Command::new("docker").args(["rm", "-f", &self.0]).output();
|
||||
|
||||
+1
-1
@@ -10,7 +10,7 @@ COPY crank-community.png ./crank-community.png
|
||||
|
||||
RUN npm run build
|
||||
|
||||
FROM nginx:1.30.4-alpine3.24-slim
|
||||
FROM nginx:1.30.6-alpine3.24-slim
|
||||
|
||||
RUN apk add --no-cache --upgrade \
|
||||
'pcre2>=10.49-r0' \
|
||||
|
||||
@@ -49,6 +49,7 @@ mod approvals;
|
||||
mod auth_resolution;
|
||||
mod dispatch;
|
||||
mod endpoint;
|
||||
mod legacy_dispatch;
|
||||
|
||||
use self::approvals::{
|
||||
approve_request, deny_request, get_approval_request, list_pending_approvals,
|
||||
@@ -82,6 +83,12 @@ pub(super) struct AppState {
|
||||
session_slots: Arc<Semaphore>,
|
||||
pub(super) credential_verifier: SharedMachineCredentialVerifier,
|
||||
allowed_origins: AllowedOrigins,
|
||||
/// Story 3.18: the bounded in-memory `logging/setLevel` opt-in of the legacy sessions. It is a
|
||||
/// client-scoped level, never a process-global one, and it needs no schema migration.
|
||||
pub(super) logging_levels: Arc<crate::protocol::LogLevelStore>,
|
||||
/// Story 3.19: the bounded table of the legacy session that currently owns the notification
|
||||
/// stream, so one session never broadcasts the same list-change signal into two streams.
|
||||
pub(super) signal_streams: Arc<crate::protocol::StreamRegistry>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
@@ -248,6 +255,8 @@ fn build_app_inner(
|
||||
session_slots: Arc::new(Semaphore::new(max_concurrent_sessions)),
|
||||
credential_verifier,
|
||||
allowed_origins: AllowedOrigins::new(public_base_url),
|
||||
logging_levels: Arc::new(crate::protocol::LogLevelStore::new()),
|
||||
signal_streams: Arc::new(crate::protocol::StreamRegistry::new()),
|
||||
});
|
||||
if start_background_workers {
|
||||
spawn_approval_recovery(Arc::clone(&state));
|
||||
|
||||
@@ -23,7 +23,9 @@ use crate::{
|
||||
},
|
||||
session::SessionState,
|
||||
tool_error::execution_locale,
|
||||
transport::{ResponseMode, json_response, session_id_from_headers, transport_response},
|
||||
transport::{
|
||||
ResponseMode, json_response, session_id_from_headers, sse_response, transport_response,
|
||||
},
|
||||
};
|
||||
use axum::{
|
||||
http::{HeaderMap, StatusCode},
|
||||
@@ -67,6 +69,12 @@ pub(super) async fn handle_modern_request(
|
||||
.as_deref()
|
||||
.unwrap_or(crate::jsonrpc::MODERN_PROTOCOL_VERSION);
|
||||
|
||||
// Story 3.18: the modern revision carries the log level of this request in
|
||||
// `_meta["io.modelcontextprotocol/logLevel"]` (SEP-2577); the former `logging/setLevel` request
|
||||
// does not exist here. Absent, non-string or unknown values mean "not opted in", so no
|
||||
// `notifications/message` is emitted for this request.
|
||||
crate::protocol::set_active_level(crate::protocol::modern_request_level(message));
|
||||
|
||||
// A notification carries no `id`. It is acknowledged before the request-only header rules: the
|
||||
// mandatory `Mcp-Method`/`Mcp-Name` pair applies to requests, not to notifications (protocol era
|
||||
// matrix row 18). The envelope, identity and mixed-carrier checks — and authentication — have
|
||||
@@ -652,6 +660,80 @@ pub(super) async fn handle_modern_request(
|
||||
}
|
||||
}
|
||||
}
|
||||
// Story 3.19: the modern long-lived notification stream. The response is itself the SSE
|
||||
// stream that stays open, so it is built here instead of going through the one-shot
|
||||
// response helpers: the acknowledgment is its first frame, then the coalesced list-change
|
||||
// signals, and closing the HTTP stream ends the producer.
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::SubscriptionsListen,
|
||||
..
|
||||
} => {
|
||||
// A notification stream is an SSE body by construction: a client that did not offer
|
||||
// `text/event-stream` could not receive it.
|
||||
if !crate::transport::accepts_event_stream(headers) {
|
||||
return StatusCode::NOT_ACCEPTABLE.into_response();
|
||||
}
|
||||
let filter: crate::protocol::ListenParams =
|
||||
match serde_json::from_value(params(message)) {
|
||||
Ok(filter) => filter,
|
||||
Err(_) => {
|
||||
return transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(
|
||||
request_id(message),
|
||||
-32602,
|
||||
crate::protocol::INVALID_LISTEN_FILTER,
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(version),
|
||||
);
|
||||
}
|
||||
};
|
||||
let accepted = match filter.notifications.accepted() {
|
||||
crate::protocol::FilterOutcome::Accepted(accepted) => accepted,
|
||||
crate::protocol::FilterOutcome::Invalid(detail) => {
|
||||
return transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(request_id(message), -32602, detail),
|
||||
response_mode,
|
||||
None,
|
||||
Some(version),
|
||||
);
|
||||
}
|
||||
};
|
||||
// The subscription id is the JSON-RPC id of this request; a value whose encoding is not
|
||||
// bounded cannot be a frame identity carrier and is refused before the stream opens.
|
||||
let Some(subscription_id) = crate::protocol::subscription_id(&request_id(message))
|
||||
else {
|
||||
return transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(request_id(message), -32600, "invalid JSON-RPC message"),
|
||||
response_mode,
|
||||
None,
|
||||
Some(version),
|
||||
);
|
||||
};
|
||||
let Ok(permit) = super::metrics::ActiveStreamGuard::try_acquire(&state.session_slots)
|
||||
else {
|
||||
return StatusCode::TOO_MANY_REQUESTS.into_response();
|
||||
};
|
||||
let acknowledged = crate::protocol::acknowledged_frame(&subscription_id, accepted);
|
||||
let receiver = crate::protocol::spawn_signal_watch(
|
||||
Arc::clone(state),
|
||||
crate::protocol::Watch {
|
||||
workspace_slug: path.workspace_slug.clone(),
|
||||
agent_slug: path.agent_slug.clone(),
|
||||
signals: accepted,
|
||||
wire: crate::protocol::Wire::Modern(subscription_id),
|
||||
legacy_stream: None,
|
||||
deadline: None,
|
||||
},
|
||||
);
|
||||
let stream = crate::protocol::frames_stream(vec![acknowledged], receiver, permit);
|
||||
|
||||
sse_response(StatusCode::OK, stream, None, Some(version))
|
||||
}
|
||||
// The standard Prompt requests are registered capabilities now; any other
|
||||
// unregistered/wrong-era method goes straight to the era-correct unsupported answer.
|
||||
_ => crate::protocol::modern_method_not_found_response(message),
|
||||
|
||||
@@ -3,55 +3,37 @@
|
||||
//!
|
||||
//! Moved verbatim out of `app.rs` (Story 3.6, kanban t_987bf309); `mcp_post_response` is reached from
|
||||
//! `build_app_inner` via `mcp_post`, hence `pub(super)`. No behaviour changed.
|
||||
//!
|
||||
//! The legacy-era dispatch itself lives in `super::legacy_dispatch` (Story 3.18 code-health, kanban
|
||||
//! t_d1b45ddc) to keep this transport entry file inside the 1000-line limit.
|
||||
|
||||
use super::metrics::{ActiveStreamGuard, McpRequestMetrics};
|
||||
use super::request::ToolCallParams;
|
||||
use super::response::take_confirmation_token;
|
||||
use super::stages::{enforce_traced_rate_limit, require_traced_machine_access};
|
||||
use crate::{
|
||||
jsonrpc::{
|
||||
LEGACY_PROTOCOL_VERSION, is_notification, is_request, jsonrpc_error, jsonrpc_result,
|
||||
method_name, params, request_id,
|
||||
},
|
||||
jsonrpc::{jsonrpc_error, method_name, request_id},
|
||||
protocol::{
|
||||
CompletionCommand, CompletionOutcome, ContinuationSupport, DispatchDecision, EnvelopeKind,
|
||||
Kind, MethodHandler, PromptGetCommand, PromptsCommand, PromptsListCommand, PromptsOutcome,
|
||||
RequestEra, ResourceReadCommand, ResourcesCommand, ResourcesListCommand, ResourcesOutcome,
|
||||
ServiceContext, ToolCallCommand, ToolsCommand, ToolsListCommand, ToolsOutcome,
|
||||
ambiguous_session_carrier_response, handle_completion_command, handle_prompts_command,
|
||||
handle_resources_command, handle_tools_command, resolve_request_identity,
|
||||
EnvelopeKind, RequestEra, ambiguous_session_carrier_response, resolve_request_identity,
|
||||
},
|
||||
rate_limit::{rate_limited_jsonrpc_response, rate_limited_status_response},
|
||||
request_context::RequestContext,
|
||||
tool_error::execution_locale,
|
||||
transport::{
|
||||
negotiate_post_response_mode, session_id_from_headers, sse_response, transport_response,
|
||||
validate_get_accept_header, validate_origin, validate_session_protocol_version,
|
||||
with_request_id_header,
|
||||
accepts_event_stream, negotiate_post_response_mode, session_id_from_headers, sse_response,
|
||||
transport_response, validate_get_accept_header, validate_origin,
|
||||
validate_session_protocol_version, with_request_id_header,
|
||||
},
|
||||
};
|
||||
use axum::{
|
||||
Json,
|
||||
extract::{Extension, Path, State, rejection::JsonRejection},
|
||||
http::{HeaderMap, StatusCode},
|
||||
response::{IntoResponse, Response, sse::Event},
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
use crank_core::{CorrelationContext, PlatformApiKeyScope};
|
||||
use futures_util::stream;
|
||||
use serde_json::{Value, json};
|
||||
use std::{convert::Infallible, sync::Arc, time::Duration};
|
||||
use serde_json::Value;
|
||||
use std::{sync::Arc, time::Duration, time::Instant};
|
||||
use tracing::info;
|
||||
|
||||
use super::dispatch::{
|
||||
handle_initialize, handle_initialized_notification, handle_modern_request,
|
||||
require_initialized_session,
|
||||
};
|
||||
use super::response::{
|
||||
completion_result, internal_jsonrpc_error, prompt_arguments_error_response, prompt_get_result,
|
||||
prompts_list_result, resource_error_response, resource_read_result,
|
||||
resource_templates_list_result, resources_list_result, tool_command_response,
|
||||
tools_list_result,
|
||||
};
|
||||
use super::dispatch::handle_modern_request;
|
||||
use super::{AgentRoutePath, AppState, TRANSPORT_SESSION_TTL_MS};
|
||||
pub(super) async fn mcp_get(
|
||||
Path(path): Path<AgentRoutePath>,
|
||||
@@ -120,11 +102,32 @@ pub(super) async fn mcp_get(
|
||||
return StatusCode::TOO_MANY_REQUESTS.into_response();
|
||||
};
|
||||
|
||||
let stream = stream::unfold(permit, |permit| async move {
|
||||
tokio::time::sleep(Duration::from_millis(TRANSPORT_SESSION_TTL_MS)).await;
|
||||
drop(permit);
|
||||
None::<(Result<Event, Infallible>, _)>
|
||||
});
|
||||
// Story 3.19: the pinned legacy transport forbids broadcasting one JSON-RPC message across the
|
||||
// SSE streams of a session, so exactly one admitted `GET` receives the Resource/Prompt
|
||||
// list-change signals. A newer `GET` takes them over and the older stream simply ends; a
|
||||
// `DELETE` retires the producer, so a stale generation never writes into a reconnect.
|
||||
let Some(generation) = state.signal_streams.admit(&session_id) else {
|
||||
// The bounded owner table is contended: refuse this admission instead of waiting.
|
||||
return StatusCode::TOO_MANY_REQUESTS.into_response();
|
||||
};
|
||||
let receiver = crate::protocol::spawn_signal_watch(
|
||||
Arc::clone(&state),
|
||||
crate::protocol::Watch {
|
||||
workspace_slug: path.workspace_slug.clone(),
|
||||
agent_slug: path.agent_slug.clone(),
|
||||
signals: crate::protocol::Signals::BOTH,
|
||||
wire: crate::protocol::Wire::Legacy,
|
||||
legacy_stream: Some((
|
||||
Arc::clone(&state.signal_streams),
|
||||
session_id.clone(),
|
||||
generation,
|
||||
)),
|
||||
deadline: Some(Instant::now() + Duration::from_millis(TRANSPORT_SESSION_TTL_MS)),
|
||||
},
|
||||
);
|
||||
// The stream permit lives in the response stream: a client that closes the SSE connection ends
|
||||
// the producer and releases the slot, and no signal is queued for a reader that is gone.
|
||||
let stream = crate::protocol::frames_stream(Vec::new(), receiver, permit);
|
||||
|
||||
sse_response(
|
||||
StatusCode::OK,
|
||||
@@ -177,6 +180,7 @@ pub(super) async fn mcp_delete(
|
||||
|
||||
match state.sessions.delete(&session_id).await {
|
||||
Ok(true) => {
|
||||
state.signal_streams.retire(&session_id);
|
||||
state.session_metrics.refresh();
|
||||
StatusCode::NO_CONTENT.into_response()
|
||||
}
|
||||
@@ -224,8 +228,14 @@ pub(super) async fn mcp_post(
|
||||
"mcp request received"
|
||||
);
|
||||
|
||||
let response =
|
||||
mcp_post_response(&path, state, &headers, &message, &transport_correlation).await;
|
||||
let response = crate::protocol::logging_scope(mcp_post_response(
|
||||
&path,
|
||||
state,
|
||||
&headers,
|
||||
&message,
|
||||
&transport_correlation,
|
||||
))
|
||||
.await;
|
||||
request_metrics.complete(&response);
|
||||
with_request_id_header(response, &transport_request_id)
|
||||
}
|
||||
@@ -250,6 +260,13 @@ async fn mcp_post_response(
|
||||
Ok(mode) => mode,
|
||||
Err(status) => return status.into_response(),
|
||||
};
|
||||
// Story 3.18: a server notification is delivered only on the SSE stream, so the logging
|
||||
// projection records whether this request offered it. This is an admission fact of the same
|
||||
// `Accept` header the mode above was negotiated from.
|
||||
if accepts_event_stream(headers) {
|
||||
crate::protocol::set_sse_acceptable();
|
||||
}
|
||||
|
||||
// A conflicting duplicate session carrier is an ambiguous identity: it must not be resolved to
|
||||
// one of its values. The carrier itself cannot tell which era the request belongs to, so the
|
||||
// diagnostic is read from the non-ambiguous part of the request (matrix row 17) — a consumer of
|
||||
@@ -327,6 +344,17 @@ async fn mcp_post_response(
|
||||
}
|
||||
}
|
||||
|
||||
// Story 3.18: the legacy logging opt-in belongs to this session, so it is read before dispatch.
|
||||
// A session that never sent `logging/setLevel` has no level, which is what the pinned schema
|
||||
// describes as "not opted in" (no notification is delivered).
|
||||
if matches!(identity.era, RequestEra::Legacy) {
|
||||
crate::protocol::set_active_level(
|
||||
request_session_id
|
||||
.as_deref()
|
||||
.and_then(|session_id| state.logging_levels.get(session_id)),
|
||||
);
|
||||
}
|
||||
|
||||
let required_scope = match method_name(message) {
|
||||
Some("tools/call") => PlatformApiKeyScope::Write,
|
||||
_ => PlatformApiKeyScope::Read,
|
||||
@@ -358,625 +386,17 @@ async fn mcp_post_response(
|
||||
#[cfg(test)]
|
||||
crate::app::dispatch_observer::era_legacy_enter();
|
||||
|
||||
// R5/F5: the owning registration decides *which handler* serves this method in the request's
|
||||
// revision. The adapter holds no method list of its own — the method-to-handler mapping lives in
|
||||
// `protocol::registry` and is read through `dispatch_decision`, so a newly registered method
|
||||
// really reaches its handler and removing a descriptor removes the dispatch.
|
||||
let registration_revision = protocol_version
|
||||
.as_deref()
|
||||
.unwrap_or(LEGACY_PROTOCOL_VERSION);
|
||||
let dispatch = crate::protocol::dispatch_decision(
|
||||
method_name(message).unwrap_or_default(),
|
||||
registration_revision,
|
||||
);
|
||||
match dispatch {
|
||||
// G2: the *registered kind* of the matched method, not the envelope shape, decides which
|
||||
// legacy lifecycle action runs. `initialize` is a request and `notifications/initialized` is a
|
||||
// notification: the two share one handler but are not interchangeable, so an `initialize`
|
||||
// notification may not initialize an existing session and a `notifications/initialized`
|
||||
// request may not create one.
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::Lifecycle,
|
||||
kind: Kind::Method,
|
||||
} if is_request(message) => handle_initialize(state, path, message, response_mode).await,
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::Lifecycle,
|
||||
kind: Kind::Notification,
|
||||
} if is_notification(message) => {
|
||||
handle_initialized_notification(state, path, headers).await
|
||||
}
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::Ping,
|
||||
..
|
||||
} if is_request(message) => {
|
||||
let session = match require_initialized_session(&state, path, headers, message).await {
|
||||
Ok(session) => session,
|
||||
Err(response) => return response,
|
||||
};
|
||||
|
||||
transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
json!({ "protocolVersion": session.protocol_version }),
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
)
|
||||
}
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::ToolList,
|
||||
..
|
||||
} if is_request(message) => {
|
||||
let session = match require_initialized_session(&state, path, headers, message).await {
|
||||
Ok(session) => session,
|
||||
Err(response) => return response,
|
||||
};
|
||||
|
||||
// The adapter parses the wire form and maps the neutral outcome back; the shared Tools
|
||||
// service never sees the envelope, the response mode or the protocol revision.
|
||||
let list_command: ToolsListCommand = match serde_json::from_value(params(message)) {
|
||||
Ok(value) => value,
|
||||
Err(_) => {
|
||||
return transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(request_id(message), -32602, "invalid tools/list parameters"),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
);
|
||||
}
|
||||
};
|
||||
let outcome = handle_tools_command(
|
||||
&state,
|
||||
ServiceContext {
|
||||
workspace_slug: &session.workspace_slug,
|
||||
agent_slug: &session.agent_slug,
|
||||
credential: &credential,
|
||||
correlation: transport_correlation,
|
||||
continuation: ContinuationSupport::from_supported(session.supports_elicitation),
|
||||
locale: execution_locale(message),
|
||||
},
|
||||
ToolsCommand::List(list_command),
|
||||
)
|
||||
.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::InvalidParams(message_text) => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(request_id(message), -32602, message_text),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
),
|
||||
ToolsOutcome::CatalogUnavailable => {
|
||||
internal_jsonrpc_error(message, "published catalog is unavailable")
|
||||
}
|
||||
// A list command never produces a call outcome; it is answered with the adapter's
|
||||
// internal error instead of being silently ignored.
|
||||
ToolsOutcome::Call(_) => internal_jsonrpc_error(
|
||||
message,
|
||||
"unexpected shared tools outcome for a tools/list",
|
||||
),
|
||||
}
|
||||
}
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::ToolCall,
|
||||
..
|
||||
} if is_request(message) => {
|
||||
let session = match require_initialized_session(&state, path, headers, message).await {
|
||||
Ok(session) => session,
|
||||
Err(response) => return response,
|
||||
};
|
||||
let tool_call_params: ToolCallParams = match serde_json::from_value(params(message)) {
|
||||
Ok(value) => value,
|
||||
Err(_) => {
|
||||
return transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(request_id(message), -32602, "invalid tool call parameters"),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
// The adapter owns the wire form: it parses the call parameters, removes the reserved
|
||||
// confirmation marker and the shared Tools service never sees the envelope, the
|
||||
// response mode or the protocol revision (spec section 6.2).
|
||||
let mut arguments = tool_call_params.arguments.unwrap_or_else(|| json!({}));
|
||||
let confirmation_token = take_confirmation_token(&mut arguments);
|
||||
let outcome = handle_tools_command(
|
||||
&state,
|
||||
ServiceContext {
|
||||
workspace_slug: &session.workspace_slug,
|
||||
agent_slug: &session.agent_slug,
|
||||
credential: &credential,
|
||||
correlation: transport_correlation,
|
||||
continuation: ContinuationSupport::from_supported(session.supports_elicitation),
|
||||
locale: execution_locale(message),
|
||||
},
|
||||
ToolsCommand::Call(ToolCallCommand {
|
||||
tool_name: tool_call_params.name,
|
||||
arguments,
|
||||
confirmation_token,
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
tool_command_response(
|
||||
message,
|
||||
response_mode,
|
||||
&session.protocol_version,
|
||||
transport_correlation,
|
||||
outcome,
|
||||
)
|
||||
}
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::ResourceList,
|
||||
..
|
||||
} if is_request(message) => {
|
||||
let session = match require_initialized_session(&state, path, headers, message).await {
|
||||
Ok(session) => session,
|
||||
Err(response) => return response,
|
||||
};
|
||||
let list_command: ResourcesListCommand = match serde_json::from_value(params(message)) {
|
||||
Ok(value) => value,
|
||||
Err(_) => {
|
||||
return transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(
|
||||
request_id(message),
|
||||
-32602,
|
||||
"invalid resources/list parameters",
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
);
|
||||
}
|
||||
};
|
||||
let outcome = handle_resources_command(
|
||||
&state,
|
||||
ServiceContext {
|
||||
workspace_slug: &session.workspace_slug,
|
||||
agent_slug: &session.agent_slug,
|
||||
credential: &credential,
|
||||
correlation: transport_correlation,
|
||||
continuation: ContinuationSupport::from_supported(session.supports_elicitation),
|
||||
locale: execution_locale(message),
|
||||
},
|
||||
&session.protocol_version,
|
||||
ResourcesCommand::List(list_command),
|
||||
)
|
||||
.await;
|
||||
match outcome {
|
||||
ResourcesOutcome::Listed {
|
||||
resources,
|
||||
next_cursor,
|
||||
} => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
resources_list_result(resources, next_cursor),
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
),
|
||||
ResourcesOutcome::InvalidParams(detail) => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(request_id(message), -32602, detail),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
),
|
||||
_ => internal_jsonrpc_error(message, "published resources are unavailable"),
|
||||
}
|
||||
}
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::ResourceRead,
|
||||
..
|
||||
} if is_request(message) => {
|
||||
let session = match require_initialized_session(&state, path, headers, message).await {
|
||||
Ok(session) => session,
|
||||
Err(response) => return response,
|
||||
};
|
||||
let read_command: ResourceReadCommand = match serde_json::from_value(params(message)) {
|
||||
Ok(value) => value,
|
||||
Err(_) => {
|
||||
return transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(
|
||||
request_id(message),
|
||||
-32602,
|
||||
"invalid resources/read parameters",
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
);
|
||||
}
|
||||
};
|
||||
let outcome = handle_resources_command(
|
||||
&state,
|
||||
ServiceContext {
|
||||
workspace_slug: &session.workspace_slug,
|
||||
agent_slug: &session.agent_slug,
|
||||
credential: &credential,
|
||||
correlation: transport_correlation,
|
||||
continuation: ContinuationSupport::from_supported(session.supports_elicitation),
|
||||
locale: execution_locale(message),
|
||||
},
|
||||
&session.protocol_version,
|
||||
ResourcesCommand::Read(read_command),
|
||||
)
|
||||
.await;
|
||||
match outcome {
|
||||
ResourcesOutcome::Read { contents } => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(request_id(message), resource_read_result(contents)),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
),
|
||||
ResourcesOutcome::NotAvailable => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(
|
||||
request_id(message),
|
||||
-32602,
|
||||
"the requested resource is not available",
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
),
|
||||
ResourcesOutcome::InvalidParams(detail) => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(request_id(message), -32602, detail),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
),
|
||||
ResourcesOutcome::ExecutionError(contract) => resource_error_response(
|
||||
message,
|
||||
response_mode,
|
||||
&session.protocol_version,
|
||||
contract,
|
||||
),
|
||||
_ => internal_jsonrpc_error(message, "published resources are unavailable"),
|
||||
}
|
||||
}
|
||||
// Story 3.11: the shared service returns exact bound Published templates; the legacy adapter
|
||||
// retains its earlier result shape and still requires the initialized session.
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::ResourceTemplateList,
|
||||
..
|
||||
} if is_request(message) => {
|
||||
let session = match require_initialized_session(&state, path, headers, message).await {
|
||||
Ok(session) => session,
|
||||
Err(response) => return response,
|
||||
};
|
||||
|
||||
let command: ResourcesListCommand = match serde_json::from_value(params(message)) {
|
||||
Ok(command) => command,
|
||||
Err(_) => {
|
||||
return transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(
|
||||
request_id(message),
|
||||
-32602,
|
||||
"invalid resources/templates/list parameters",
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
);
|
||||
}
|
||||
};
|
||||
let (templates, next_cursor) = match crate::protocol::list_resource_templates(
|
||||
&state,
|
||||
&path.workspace_slug,
|
||||
&path.agent_slug,
|
||||
&session.protocol_version,
|
||||
command,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(page) => page,
|
||||
Err(crate::protocol::ResourceTemplatesListError::InvalidCursor) => {
|
||||
return transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(
|
||||
request_id(message),
|
||||
-32602,
|
||||
"invalid resources/templates/list cursor",
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
);
|
||||
}
|
||||
Err(crate::protocol::ResourceTemplatesListError::Unavailable) => {
|
||||
return internal_jsonrpc_error(message, "published templates are unavailable");
|
||||
}
|
||||
};
|
||||
transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
resource_templates_list_result(templates, next_cursor),
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
)
|
||||
}
|
||||
// Story 3.14: `prompts/list` / `prompts/get` of the initialized legacy session, served from
|
||||
// the same exact bound Published Prompt Versions as the modern era.
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::PromptList,
|
||||
..
|
||||
} if is_request(message) => {
|
||||
let session = match require_initialized_session(&state, path, headers, message).await {
|
||||
Ok(session) => session,
|
||||
Err(response) => return response,
|
||||
};
|
||||
let command: PromptsListCommand = match serde_json::from_value(params(message)) {
|
||||
Ok(command) => command,
|
||||
Err(_) => {
|
||||
return transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(
|
||||
request_id(message),
|
||||
-32602,
|
||||
"invalid prompts/list parameters",
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
);
|
||||
}
|
||||
};
|
||||
let outcome = handle_prompts_command(
|
||||
&state,
|
||||
ServiceContext {
|
||||
workspace_slug: &session.workspace_slug,
|
||||
agent_slug: &session.agent_slug,
|
||||
credential: &credential,
|
||||
correlation: transport_correlation,
|
||||
continuation: ContinuationSupport::from_supported(session.supports_elicitation),
|
||||
locale: execution_locale(message),
|
||||
},
|
||||
&session.protocol_version,
|
||||
PromptsCommand::List(command),
|
||||
)
|
||||
.await;
|
||||
match outcome {
|
||||
PromptsOutcome::Listed {
|
||||
prompts,
|
||||
next_cursor,
|
||||
} => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
prompts_list_result(prompts, next_cursor),
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
),
|
||||
PromptsOutcome::InvalidParams(detail) => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(request_id(message), -32602, detail),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
),
|
||||
_ => internal_jsonrpc_error(message, "published prompts are unavailable"),
|
||||
}
|
||||
}
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::PromptGet,
|
||||
..
|
||||
} if is_request(message) => {
|
||||
let session = match require_initialized_session(&state, path, headers, message).await {
|
||||
Ok(session) => session,
|
||||
Err(response) => return response,
|
||||
};
|
||||
let command: PromptGetCommand = match serde_json::from_value(params(message)) {
|
||||
Ok(command) => command,
|
||||
Err(_) => {
|
||||
return transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(
|
||||
request_id(message),
|
||||
-32602,
|
||||
"invalid prompts/get parameters",
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
);
|
||||
}
|
||||
};
|
||||
let outcome = handle_prompts_command(
|
||||
&state,
|
||||
ServiceContext {
|
||||
workspace_slug: &session.workspace_slug,
|
||||
agent_slug: &session.agent_slug,
|
||||
credential: &credential,
|
||||
correlation: transport_correlation,
|
||||
continuation: ContinuationSupport::from_supported(session.supports_elicitation),
|
||||
locale: execution_locale(message),
|
||||
},
|
||||
&session.protocol_version,
|
||||
PromptsCommand::Get(command),
|
||||
)
|
||||
.await;
|
||||
match outcome {
|
||||
PromptsOutcome::Got {
|
||||
description,
|
||||
messages,
|
||||
} => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
prompt_get_result(description, messages),
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
),
|
||||
PromptsOutcome::NotAvailable => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(
|
||||
request_id(message),
|
||||
-32602,
|
||||
"the requested prompt is not available",
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
),
|
||||
PromptsOutcome::ArgumentsRejected { reason, argument } => {
|
||||
prompt_arguments_error_response(
|
||||
message,
|
||||
response_mode,
|
||||
&session.protocol_version,
|
||||
reason,
|
||||
argument,
|
||||
)
|
||||
}
|
||||
PromptsOutcome::DependencyUnavailable { position } => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(
|
||||
request_id(message),
|
||||
-32603,
|
||||
format!("the pinned dependency at dependencies[{position}] is unavailable"),
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
),
|
||||
PromptsOutcome::InvalidParams(detail) => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(request_id(message), -32602, detail),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
),
|
||||
_ => internal_jsonrpc_error(message, "published prompts are unavailable"),
|
||||
}
|
||||
}
|
||||
// Story 3.17: `completion/complete` of the initialized legacy session. The shared service is
|
||||
// the same one the modern era uses; only the result envelope differs (no `resultType`).
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::Completion,
|
||||
..
|
||||
} if is_request(message) => {
|
||||
let session = match require_initialized_session(&state, path, headers, message).await {
|
||||
Ok(session) => session,
|
||||
Err(response) => return response,
|
||||
};
|
||||
let command: CompletionCommand = match serde_json::from_value(params(message)) {
|
||||
Ok(command) => command,
|
||||
Err(_) => {
|
||||
return transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(
|
||||
request_id(message),
|
||||
-32602,
|
||||
"invalid completion/complete parameters",
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
);
|
||||
}
|
||||
};
|
||||
let outcome = handle_completion_command(
|
||||
&state,
|
||||
ServiceContext {
|
||||
workspace_slug: &session.workspace_slug,
|
||||
agent_slug: &session.agent_slug,
|
||||
credential: &credential,
|
||||
correlation: transport_correlation,
|
||||
continuation: ContinuationSupport::from_supported(session.supports_elicitation),
|
||||
locale: execution_locale(message),
|
||||
},
|
||||
&session.protocol_version,
|
||||
command,
|
||||
)
|
||||
.await;
|
||||
match outcome {
|
||||
CompletionOutcome::Completed {
|
||||
values,
|
||||
total,
|
||||
has_more,
|
||||
} => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
completion_result(values, total, has_more),
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
),
|
||||
CompletionOutcome::InvalidParams(detail) => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(request_id(message), -32602, detail),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
),
|
||||
CompletionOutcome::NotAvailable => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(
|
||||
request_id(message),
|
||||
-32602,
|
||||
"the completion reference is not available",
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
),
|
||||
CompletionOutcome::CatalogUnavailable => {
|
||||
internal_jsonrpc_error(message, "published completion sources are unavailable")
|
||||
}
|
||||
}
|
||||
}
|
||||
// A notification whose method the registration does not map to this adapter's handlers is
|
||||
// acknowledged without being dispatched, exactly as before.
|
||||
_ if is_notification(message) => StatusCode::ACCEPTED.into_response(),
|
||||
// Every remaining decision (unregistered, wrong era, or a handler this adapter does not
|
||||
// serve) is a method-level rejection: no handler, no service entry, no outbound call.
|
||||
_ => match method_name(message) {
|
||||
Some(method) => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(
|
||||
request_id(message),
|
||||
-32601,
|
||||
format!("method {method} is not supported"),
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
protocol_version.as_deref(),
|
||||
),
|
||||
None => transport_response(
|
||||
StatusCode::BAD_REQUEST,
|
||||
jsonrpc_error(Value::Null, -32600, "invalid JSON-RPC message"),
|
||||
response_mode,
|
||||
None,
|
||||
protocol_version.as_deref(),
|
||||
),
|
||||
},
|
||||
}
|
||||
// R5/F5: the owning registration decides which handler serves this method in the request's
|
||||
// revision; that legacy dispatch lives in `super::legacy_dispatch`.
|
||||
super::legacy_dispatch::handle_legacy_request(
|
||||
state,
|
||||
path,
|
||||
headers,
|
||||
message,
|
||||
response_mode,
|
||||
&identity,
|
||||
&credential,
|
||||
transport_correlation,
|
||||
)
|
||||
.await
|
||||
}
|
||||
@@ -0,0 +1,731 @@
|
||||
//! Legacy-era JSON-RPC dispatch: the registered method-to-handler mapping, the
|
||||
//! initialized-session guard and every legacy envelope the transport endpoint answers.
|
||||
//!
|
||||
//! Moved verbatim out of `app/endpoint.rs` (Story 3.18 code-health, kanban t_d1b45ddc) so the
|
||||
//! transport entry file stays inside the 1000-line limit; the entry point is `pub(super)`.
|
||||
//! No behaviour changed.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::{
|
||||
http::{HeaderMap, StatusCode},
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
use crank_core::CorrelationContext;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::dispatch::{
|
||||
handle_initialize, handle_initialized_notification, require_initialized_session,
|
||||
};
|
||||
use super::request::ToolCallParams;
|
||||
use super::response::{
|
||||
completion_result, internal_jsonrpc_error, prompt_arguments_error_response, prompt_get_result,
|
||||
prompts_list_result, resource_error_response, resource_read_result,
|
||||
resource_templates_list_result, resources_list_result, take_confirmation_token,
|
||||
tool_command_response, tools_list_result,
|
||||
};
|
||||
use super::{AgentRoutePath, AppState};
|
||||
use crate::{
|
||||
auth::VerifiedMachineCredential,
|
||||
jsonrpc::{
|
||||
LEGACY_PROTOCOL_VERSION, is_notification, is_request, jsonrpc_error, jsonrpc_result,
|
||||
method_name, params, request_id,
|
||||
},
|
||||
protocol::{
|
||||
CompletionCommand, CompletionOutcome, ContinuationSupport, DispatchDecision,
|
||||
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,
|
||||
},
|
||||
tool_error::execution_locale,
|
||||
transport::{ResponseMode, transport_response},
|
||||
};
|
||||
|
||||
// The transport invariants of one request travel together here; a parameter struct would only
|
||||
// duplicate them (the same shape every other dispatch entry point in this crate uses).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) async fn handle_legacy_request(
|
||||
state: Arc<AppState>,
|
||||
path: &AgentRoutePath,
|
||||
headers: &HeaderMap,
|
||||
message: &Value,
|
||||
response_mode: ResponseMode,
|
||||
identity: &RequestIdentity,
|
||||
credential: &VerifiedMachineCredential,
|
||||
transport_correlation: &CorrelationContext,
|
||||
) -> Response {
|
||||
let protocol_version = identity.version.as_deref();
|
||||
|
||||
// R5/F5: the owning registration decides *which handler* serves this method in the request's
|
||||
// revision. The adapter holds no method list of its own — the method-to-handler mapping lives in
|
||||
// `protocol::registry` and is read through `dispatch_decision`, so a newly registered method
|
||||
// really reaches its handler and removing a descriptor removes the dispatch.
|
||||
let registration_revision = protocol_version.unwrap_or(LEGACY_PROTOCOL_VERSION);
|
||||
let dispatch = crate::protocol::dispatch_decision(
|
||||
method_name(message).unwrap_or_default(),
|
||||
registration_revision,
|
||||
);
|
||||
match dispatch {
|
||||
// G2: the *registered kind* of the matched method, not the envelope shape, decides which
|
||||
// legacy lifecycle action runs. `initialize` is a request and `notifications/initialized` is a
|
||||
// notification: the two share one handler but are not interchangeable, so an `initialize`
|
||||
// notification may not initialize an existing session and a `notifications/initialized`
|
||||
// request may not create one.
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::Lifecycle,
|
||||
kind: Kind::Method,
|
||||
} if is_request(message) => handle_initialize(state, path, message, response_mode).await,
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::Lifecycle,
|
||||
kind: Kind::Notification,
|
||||
} if is_notification(message) => {
|
||||
handle_initialized_notification(state, path, headers).await
|
||||
}
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::Ping,
|
||||
..
|
||||
} if is_request(message) => {
|
||||
let session = match require_initialized_session(&state, path, headers, message).await {
|
||||
Ok(session) => session,
|
||||
Err(response) => return response,
|
||||
};
|
||||
|
||||
transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
json!({ "protocolVersion": session.protocol_version }),
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
)
|
||||
}
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::ToolList,
|
||||
..
|
||||
} if is_request(message) => {
|
||||
let session = match require_initialized_session(&state, path, headers, message).await {
|
||||
Ok(session) => session,
|
||||
Err(response) => return response,
|
||||
};
|
||||
|
||||
// The adapter parses the wire form and maps the neutral outcome back; the shared Tools
|
||||
// service never sees the envelope, the response mode or the protocol revision.
|
||||
let list_command: ToolsListCommand = match serde_json::from_value(params(message)) {
|
||||
Ok(value) => value,
|
||||
Err(_) => {
|
||||
return transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(request_id(message), -32602, "invalid tools/list parameters"),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
);
|
||||
}
|
||||
};
|
||||
let outcome = handle_tools_command(
|
||||
&state,
|
||||
ServiceContext {
|
||||
workspace_slug: &session.workspace_slug,
|
||||
agent_slug: &session.agent_slug,
|
||||
credential,
|
||||
correlation: transport_correlation,
|
||||
continuation: ContinuationSupport::from_supported(session.supports_elicitation),
|
||||
locale: execution_locale(message),
|
||||
},
|
||||
ToolsCommand::List(list_command),
|
||||
)
|
||||
.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::InvalidParams(message_text) => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(request_id(message), -32602, message_text),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
),
|
||||
ToolsOutcome::CatalogUnavailable => {
|
||||
internal_jsonrpc_error(message, "published catalog is unavailable")
|
||||
}
|
||||
// A list command never produces a call outcome; it is answered with the adapter's
|
||||
// internal error instead of being silently ignored.
|
||||
ToolsOutcome::Call(_) => internal_jsonrpc_error(
|
||||
message,
|
||||
"unexpected shared tools outcome for a tools/list",
|
||||
),
|
||||
}
|
||||
}
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::ToolCall,
|
||||
..
|
||||
} if is_request(message) => {
|
||||
let session = match require_initialized_session(&state, path, headers, message).await {
|
||||
Ok(session) => session,
|
||||
Err(response) => return response,
|
||||
};
|
||||
let tool_call_params: ToolCallParams = match serde_json::from_value(params(message)) {
|
||||
Ok(value) => value,
|
||||
Err(_) => {
|
||||
return transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(request_id(message), -32602, "invalid tool call parameters"),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
// The adapter owns the wire form: it parses the call parameters, removes the reserved
|
||||
// confirmation marker and the shared Tools service never sees the envelope, the
|
||||
// response mode or the protocol revision (spec section 6.2).
|
||||
let mut arguments = tool_call_params.arguments.unwrap_or_else(|| json!({}));
|
||||
let confirmation_token = take_confirmation_token(&mut arguments);
|
||||
let outcome = handle_tools_command(
|
||||
&state,
|
||||
ServiceContext {
|
||||
workspace_slug: &session.workspace_slug,
|
||||
agent_slug: &session.agent_slug,
|
||||
credential,
|
||||
correlation: transport_correlation,
|
||||
continuation: ContinuationSupport::from_supported(session.supports_elicitation),
|
||||
locale: execution_locale(message),
|
||||
},
|
||||
ToolsCommand::Call(ToolCallCommand {
|
||||
tool_name: tool_call_params.name,
|
||||
arguments,
|
||||
confirmation_token,
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
tool_command_response(
|
||||
message,
|
||||
response_mode,
|
||||
&session.protocol_version,
|
||||
transport_correlation,
|
||||
outcome,
|
||||
)
|
||||
}
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::ResourceList,
|
||||
..
|
||||
} if is_request(message) => {
|
||||
let session = match require_initialized_session(&state, path, headers, message).await {
|
||||
Ok(session) => session,
|
||||
Err(response) => return response,
|
||||
};
|
||||
let list_command: ResourcesListCommand = match serde_json::from_value(params(message)) {
|
||||
Ok(value) => value,
|
||||
Err(_) => {
|
||||
return transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(
|
||||
request_id(message),
|
||||
-32602,
|
||||
"invalid resources/list parameters",
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
);
|
||||
}
|
||||
};
|
||||
let outcome = handle_resources_command(
|
||||
&state,
|
||||
ServiceContext {
|
||||
workspace_slug: &session.workspace_slug,
|
||||
agent_slug: &session.agent_slug,
|
||||
credential,
|
||||
correlation: transport_correlation,
|
||||
continuation: ContinuationSupport::from_supported(session.supports_elicitation),
|
||||
locale: execution_locale(message),
|
||||
},
|
||||
&session.protocol_version,
|
||||
ResourcesCommand::List(list_command),
|
||||
)
|
||||
.await;
|
||||
match outcome {
|
||||
ResourcesOutcome::Listed {
|
||||
resources,
|
||||
next_cursor,
|
||||
} => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
resources_list_result(resources, next_cursor),
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
),
|
||||
ResourcesOutcome::InvalidParams(detail) => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(request_id(message), -32602, detail),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
),
|
||||
_ => internal_jsonrpc_error(message, "published resources are unavailable"),
|
||||
}
|
||||
}
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::ResourceRead,
|
||||
..
|
||||
} if is_request(message) => {
|
||||
let session = match require_initialized_session(&state, path, headers, message).await {
|
||||
Ok(session) => session,
|
||||
Err(response) => return response,
|
||||
};
|
||||
let read_command: ResourceReadCommand = match serde_json::from_value(params(message)) {
|
||||
Ok(value) => value,
|
||||
Err(_) => {
|
||||
return transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(
|
||||
request_id(message),
|
||||
-32602,
|
||||
"invalid resources/read parameters",
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
);
|
||||
}
|
||||
};
|
||||
let outcome = handle_resources_command(
|
||||
&state,
|
||||
ServiceContext {
|
||||
workspace_slug: &session.workspace_slug,
|
||||
agent_slug: &session.agent_slug,
|
||||
credential,
|
||||
correlation: transport_correlation,
|
||||
continuation: ContinuationSupport::from_supported(session.supports_elicitation),
|
||||
locale: execution_locale(message),
|
||||
},
|
||||
&session.protocol_version,
|
||||
ResourcesCommand::Read(read_command),
|
||||
)
|
||||
.await;
|
||||
match outcome {
|
||||
ResourcesOutcome::Read { contents } => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(request_id(message), resource_read_result(contents)),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
),
|
||||
ResourcesOutcome::NotAvailable => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(
|
||||
request_id(message),
|
||||
-32602,
|
||||
"the requested resource is not available",
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
),
|
||||
ResourcesOutcome::InvalidParams(detail) => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(request_id(message), -32602, detail),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
),
|
||||
ResourcesOutcome::ExecutionError(contract) => resource_error_response(
|
||||
message,
|
||||
response_mode,
|
||||
&session.protocol_version,
|
||||
contract,
|
||||
),
|
||||
_ => internal_jsonrpc_error(message, "published resources are unavailable"),
|
||||
}
|
||||
}
|
||||
// Story 3.11: the shared service returns exact bound Published templates; the legacy adapter
|
||||
// retains its earlier result shape and still requires the initialized session.
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::ResourceTemplateList,
|
||||
..
|
||||
} if is_request(message) => {
|
||||
let session = match require_initialized_session(&state, path, headers, message).await {
|
||||
Ok(session) => session,
|
||||
Err(response) => return response,
|
||||
};
|
||||
|
||||
let command: ResourcesListCommand = match serde_json::from_value(params(message)) {
|
||||
Ok(command) => command,
|
||||
Err(_) => {
|
||||
return transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(
|
||||
request_id(message),
|
||||
-32602,
|
||||
"invalid resources/templates/list parameters",
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
);
|
||||
}
|
||||
};
|
||||
let (templates, next_cursor) = match crate::protocol::list_resource_templates(
|
||||
&state,
|
||||
&path.workspace_slug,
|
||||
&path.agent_slug,
|
||||
&session.protocol_version,
|
||||
command,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(page) => page,
|
||||
Err(crate::protocol::ResourceTemplatesListError::InvalidCursor) => {
|
||||
return transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(
|
||||
request_id(message),
|
||||
-32602,
|
||||
"invalid resources/templates/list cursor",
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
);
|
||||
}
|
||||
Err(crate::protocol::ResourceTemplatesListError::Unavailable) => {
|
||||
return internal_jsonrpc_error(message, "published templates are unavailable");
|
||||
}
|
||||
};
|
||||
transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
resource_templates_list_result(templates, next_cursor),
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
)
|
||||
}
|
||||
// Story 3.14: `prompts/list` / `prompts/get` of the initialized legacy session, served from
|
||||
// the same exact bound Published Prompt Versions as the modern era.
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::PromptList,
|
||||
..
|
||||
} if is_request(message) => {
|
||||
let session = match require_initialized_session(&state, path, headers, message).await {
|
||||
Ok(session) => session,
|
||||
Err(response) => return response,
|
||||
};
|
||||
let command: PromptsListCommand = match serde_json::from_value(params(message)) {
|
||||
Ok(command) => command,
|
||||
Err(_) => {
|
||||
return transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(
|
||||
request_id(message),
|
||||
-32602,
|
||||
"invalid prompts/list parameters",
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
);
|
||||
}
|
||||
};
|
||||
let outcome = handle_prompts_command(
|
||||
&state,
|
||||
ServiceContext {
|
||||
workspace_slug: &session.workspace_slug,
|
||||
agent_slug: &session.agent_slug,
|
||||
credential,
|
||||
correlation: transport_correlation,
|
||||
continuation: ContinuationSupport::from_supported(session.supports_elicitation),
|
||||
locale: execution_locale(message),
|
||||
},
|
||||
&session.protocol_version,
|
||||
PromptsCommand::List(command),
|
||||
)
|
||||
.await;
|
||||
match outcome {
|
||||
PromptsOutcome::Listed {
|
||||
prompts,
|
||||
next_cursor,
|
||||
} => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
prompts_list_result(prompts, next_cursor),
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
),
|
||||
PromptsOutcome::InvalidParams(detail) => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(request_id(message), -32602, detail),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
),
|
||||
_ => internal_jsonrpc_error(message, "published prompts are unavailable"),
|
||||
}
|
||||
}
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::PromptGet,
|
||||
..
|
||||
} if is_request(message) => {
|
||||
let session = match require_initialized_session(&state, path, headers, message).await {
|
||||
Ok(session) => session,
|
||||
Err(response) => return response,
|
||||
};
|
||||
let command: PromptGetCommand = match serde_json::from_value(params(message)) {
|
||||
Ok(command) => command,
|
||||
Err(_) => {
|
||||
return transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(
|
||||
request_id(message),
|
||||
-32602,
|
||||
"invalid prompts/get parameters",
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
);
|
||||
}
|
||||
};
|
||||
let outcome = handle_prompts_command(
|
||||
&state,
|
||||
ServiceContext {
|
||||
workspace_slug: &session.workspace_slug,
|
||||
agent_slug: &session.agent_slug,
|
||||
credential,
|
||||
correlation: transport_correlation,
|
||||
continuation: ContinuationSupport::from_supported(session.supports_elicitation),
|
||||
locale: execution_locale(message),
|
||||
},
|
||||
&session.protocol_version,
|
||||
PromptsCommand::Get(command),
|
||||
)
|
||||
.await;
|
||||
match outcome {
|
||||
PromptsOutcome::Got {
|
||||
description,
|
||||
messages,
|
||||
} => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
prompt_get_result(description, messages),
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
),
|
||||
PromptsOutcome::NotAvailable => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(
|
||||
request_id(message),
|
||||
-32602,
|
||||
"the requested prompt is not available",
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
),
|
||||
PromptsOutcome::ArgumentsRejected { reason, argument } => {
|
||||
prompt_arguments_error_response(
|
||||
message,
|
||||
response_mode,
|
||||
&session.protocol_version,
|
||||
reason,
|
||||
argument,
|
||||
)
|
||||
}
|
||||
PromptsOutcome::DependencyUnavailable { position } => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(
|
||||
request_id(message),
|
||||
-32603,
|
||||
format!("the pinned dependency at dependencies[{position}] is unavailable"),
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
),
|
||||
PromptsOutcome::InvalidParams(detail) => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(request_id(message), -32602, detail),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
),
|
||||
_ => internal_jsonrpc_error(message, "published prompts are unavailable"),
|
||||
}
|
||||
}
|
||||
// Story 3.17: `completion/complete` of the initialized legacy session. The shared service is
|
||||
// the same one the modern era uses; only the result envelope differs (no `resultType`).
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::Completion,
|
||||
..
|
||||
} if is_request(message) => {
|
||||
let session = match require_initialized_session(&state, path, headers, message).await {
|
||||
Ok(session) => session,
|
||||
Err(response) => return response,
|
||||
};
|
||||
let command: CompletionCommand = match serde_json::from_value(params(message)) {
|
||||
Ok(command) => command,
|
||||
Err(_) => {
|
||||
return transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(
|
||||
request_id(message),
|
||||
-32602,
|
||||
"invalid completion/complete parameters",
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
);
|
||||
}
|
||||
};
|
||||
let outcome = handle_completion_command(
|
||||
&state,
|
||||
ServiceContext {
|
||||
workspace_slug: &session.workspace_slug,
|
||||
agent_slug: &session.agent_slug,
|
||||
credential,
|
||||
correlation: transport_correlation,
|
||||
continuation: ContinuationSupport::from_supported(session.supports_elicitation),
|
||||
locale: execution_locale(message),
|
||||
},
|
||||
&session.protocol_version,
|
||||
command,
|
||||
)
|
||||
.await;
|
||||
match outcome {
|
||||
CompletionOutcome::Completed {
|
||||
values,
|
||||
total,
|
||||
has_more,
|
||||
} => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
completion_result(values, total, has_more),
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
),
|
||||
CompletionOutcome::InvalidParams(detail) => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(request_id(message), -32602, detail),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
),
|
||||
CompletionOutcome::NotAvailable => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(
|
||||
request_id(message),
|
||||
-32602,
|
||||
"the completion reference is not available",
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
),
|
||||
CompletionOutcome::CatalogUnavailable => {
|
||||
internal_jsonrpc_error(message, "published completion sources are unavailable")
|
||||
}
|
||||
}
|
||||
}
|
||||
// Story 3.18: the pinned legacy `logging/setLevel`. The level belongs to the initialized
|
||||
// session of this request, so setting it can never change another client's level. The request
|
||||
// answers an empty result; the acknowledgment event is filtered by the level it just set.
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::LoggingSetLevel,
|
||||
..
|
||||
} if is_request(message) => {
|
||||
let session = match require_initialized_session(&state, path, headers, message).await {
|
||||
Ok(session) => session,
|
||||
Err(response) => return response,
|
||||
};
|
||||
let command: SetLevelCommand = match serde_json::from_value(params(message)) {
|
||||
Ok(command) => command,
|
||||
// A non-string, missing or otherwise unparsable level shares the one safe detail of a
|
||||
// value outside the pinned union: nothing the client sent is echoed back.
|
||||
Err(_) => {
|
||||
return transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(request_id(message), -32602, INVALID_LEVEL),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
);
|
||||
}
|
||||
};
|
||||
match handle_logging_command(&state.logging_levels, &session.id, command) {
|
||||
LoggingOutcome::Applied(level) => {
|
||||
crate::protocol::set_active_level(Some(level));
|
||||
crate::protocol::note(
|
||||
crate::protocol::LogLevel::Notice,
|
||||
EVENT_LEVEL_APPLIED,
|
||||
"applied",
|
||||
);
|
||||
transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(request_id(message), json!({})),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
)
|
||||
}
|
||||
LoggingOutcome::InvalidParams(detail) => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(request_id(message), -32602, detail),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
),
|
||||
}
|
||||
}
|
||||
// A notification whose method the registration does not map to this adapter's handlers is
|
||||
// acknowledged without being dispatched, exactly as before.
|
||||
_ if is_notification(message) => StatusCode::ACCEPTED.into_response(),
|
||||
// Every remaining decision (unregistered, wrong era, or a handler this adapter does not
|
||||
// serve) is a method-level rejection: no handler, no service entry, no outbound call.
|
||||
_ => match method_name(message) {
|
||||
Some(method) => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(
|
||||
request_id(message),
|
||||
-32601,
|
||||
format!("method {method} is not supported"),
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
protocol_version,
|
||||
),
|
||||
None => transport_response(
|
||||
StatusCode::BAD_REQUEST,
|
||||
jsonrpc_error(Value::Null, -32600, "invalid JSON-RPC message"),
|
||||
response_mode,
|
||||
None,
|
||||
protocol_version,
|
||||
),
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -121,3 +121,53 @@ impl ActiveStreamGuard {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crank_metrics::McpMethod;
|
||||
use serde_json::json;
|
||||
|
||||
use super::normalized_mcp_method;
|
||||
|
||||
/// AT-3.18-02: the metric label of the logging request is a member of the closed label enum, so
|
||||
/// neither the level nor any other client-supplied identifier can reach the label space. There is
|
||||
/// no mapping from a request value to a label anywhere in this file.
|
||||
#[test]
|
||||
fn a_logging_request_can_only_produce_a_fixed_metric_label() {
|
||||
for level in [
|
||||
json!("debug"),
|
||||
json!("verbose"),
|
||||
json!("crank-canary-9f7620e5-aa41-4b0d"),
|
||||
json!(7),
|
||||
json!(null),
|
||||
] {
|
||||
let message = json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": 1,
|
||||
"method": "logging/setLevel",
|
||||
"params": {"level": level}
|
||||
});
|
||||
assert_eq!(
|
||||
normalized_mcp_method(&message),
|
||||
McpMethod::Unsupported,
|
||||
"the method label is a fixed enum member, never the request value"
|
||||
);
|
||||
}
|
||||
assert_eq!(McpMethod::Unsupported.as_str(), "unsupported");
|
||||
// Every label value of the enum is a pinned literal, so the label domain cannot be widened by
|
||||
// a request at all.
|
||||
assert!(
|
||||
McpMethod::VALUES.iter().all(|value| value
|
||||
.chars()
|
||||
.all(|character| character.is_ascii_lowercase() || character == '_')),
|
||||
"every method label is a fixed lowercase literal: {:?}",
|
||||
McpMethod::VALUES
|
||||
);
|
||||
|
||||
// A malformed envelope has its own fixed label as well.
|
||||
assert_eq!(
|
||||
normalized_mcp_method(&json!({"level": "debug"})),
|
||||
McpMethod::Invalid
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,9 @@ pub const CURRENT_PROTOCOL_VERSION: &str = LEGACY_PROTOCOL_VERSION;
|
||||
pub const META_PROTOCOL_VERSION_KEY: &str = "io.modelcontextprotocol/protocolVersion";
|
||||
pub const META_CLIENT_CAPABILITIES_KEY: &str = "io.modelcontextprotocol/clientCapabilities";
|
||||
pub const META_CLIENT_INFO_KEY: &str = "io.modelcontextprotocol/clientInfo";
|
||||
/// `_meta` key of the per-request log level (Story 3.18). SEP-2577 replaces the former
|
||||
/// `logging/setLevel` request of the legacy era with this per-request opt-in.
|
||||
pub const META_LOG_LEVEL_KEY: &str = "io.modelcontextprotocol/logLevel";
|
||||
|
||||
/// Result `_meta` key carrying the self-reported server identity (pinned `DiscoverResult`).
|
||||
pub const META_SERVER_INFO_KEY: &str = "io.modelcontextprotocol/serverInfo";
|
||||
|
||||
@@ -0,0 +1,338 @@
|
||||
//! Story 3.18: safe MCP server logging (FR-19).
|
||||
//!
|
||||
//! Scope of this module is the server side of the pinned `logging` capability of the two approved
|
||||
//! revisions, and nothing else:
|
||||
//!
|
||||
//! * `2025-11-25` (legacy session era) declares `logging/setLevel` as a client request with one
|
||||
//! `level` of the pinned `LoggingLevel` union, and `logging?: object` in `ServerCapabilities`.
|
||||
//! The request sets the severity a client wants to receive for its own session.
|
||||
//! * `2026-07-28` (modern stateless era) has no `logging/setLevel` method at all: SEP-2577 replaces
|
||||
//! it with the per-request `_meta["io.modelcontextprotocol/logLevel"]`, and the schema says that
|
||||
//! when that key is absent "the server MUST NOT send any notifications/message notifications for
|
||||
//! this request". The `logging` capability and `notifications/message` themselves stay in the
|
||||
//! pinned schema as deprecated for at least twelve months.
|
||||
//!
|
||||
//! The answer of this story is therefore the narrow one the contract offers: an opt-in level that
|
||||
//! belongs to the current negotiated client context (one legacy session, or one modern request —
|
||||
//! never a process-global level shared by every agent), and `notifications/message` events that are
|
||||
//! built **only** from the closed safe vocabulary below.
|
||||
//!
|
||||
//! Redaction is structural, not a filter: no request payload, credential, internal error cause,
|
||||
//! Prompt/Resource/Tool name, URI, argument value or any other user-supplied value is ever accepted
|
||||
//! by this module, so none of them can reach the wire. A `notifications/message` body is exactly
|
||||
//! `{"level": <severity of the event>, "logger": "crank-mcp-server", "data": {"event": <closed name>,
|
||||
//! "outcome": <closed label>}}` — every member of it is a `&'static str` from this file.
|
||||
//!
|
||||
//! Bounds (issue requirement: bounded frequency/queues/bytes, logging never blocks execution and
|
||||
//! never replaces the audit trail):
|
||||
//! * at most one event per response is recorded, and at most [`MAX_PENDING_NOTIFICATIONS`] are
|
||||
//! drained into one response — a fixed, per-response frequency bound;
|
||||
//! * every event has a fixed size and no variable input, so the byte bound follows from the count
|
||||
//! bound without a separate accounting path;
|
||||
//! * recording is a bounded in-memory push that drops the event when the buffer is full, the active
|
||||
//! level is unset, or the task has no request scope. No I/O, no lock acquisition that can wait, and
|
||||
//! no error path: logging can never fail or slow down the request it describes.
|
||||
//! * the legacy opt-in table is a bounded in-memory map read/written with `try_lock` only.
|
||||
|
||||
use std::{
|
||||
cell::RefCell,
|
||||
collections::HashMap,
|
||||
future::Future,
|
||||
sync::{Mutex, MutexGuard},
|
||||
};
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
use tokio::task_local;
|
||||
|
||||
/// The pinned `LoggingLevel` union: RFC 5424 severities, ordered from the most verbose to the most
|
||||
/// severe. The ordering is the filtering contract — a client is sent the events at or above its
|
||||
/// level.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub(crate) enum LogLevel {
|
||||
Debug,
|
||||
Info,
|
||||
Notice,
|
||||
Warning,
|
||||
Error,
|
||||
Critical,
|
||||
Alert,
|
||||
Emergency,
|
||||
}
|
||||
|
||||
impl LogLevel {
|
||||
/// The exact wire literal of this level.
|
||||
pub(crate) const fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Debug => "debug",
|
||||
Self::Info => "info",
|
||||
Self::Notice => "notice",
|
||||
Self::Warning => "warning",
|
||||
Self::Error => "error",
|
||||
Self::Critical => "critical",
|
||||
Self::Alert => "alert",
|
||||
Self::Emergency => "emergency",
|
||||
}
|
||||
}
|
||||
|
||||
/// Exact parse of the eight pinned literals.
|
||||
///
|
||||
/// Nothing is coerced: no case folding, no aliases (`warn`), no numeric severities. A value that
|
||||
/// is not one of the pinned strings is malformed, which is what the pinned `LoggingLevel` type
|
||||
/// says and what `InvalidParamsError` is for.
|
||||
pub(crate) fn parse(value: &str) -> Option<Self> {
|
||||
match value {
|
||||
"debug" => Some(Self::Debug),
|
||||
"info" => Some(Self::Info),
|
||||
"notice" => Some(Self::Notice),
|
||||
"warning" => Some(Self::Warning),
|
||||
"error" => Some(Self::Error),
|
||||
"critical" => Some(Self::Critical),
|
||||
"alert" => Some(Self::Alert),
|
||||
"emergency" => Some(Self::Emergency),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Bound of `params.level` before it is compared: the longest pinned literal is nine bytes, so a
|
||||
/// value beyond this cannot be a level and must not be scanned further.
|
||||
pub(crate) const MAX_LEVEL_BYTES: usize = 16;
|
||||
|
||||
/// The one safe detail of a malformed `logging/setLevel`: it never echoes the offending value, so an
|
||||
/// oversized or hostile value cannot be reflected back or widened into an error payload.
|
||||
pub(crate) const INVALID_LEVEL: &str = "invalid logging level";
|
||||
|
||||
/// Notifications drained into one response (frequency bound).
|
||||
pub(crate) const MAX_PENDING_NOTIFICATIONS: usize = 4;
|
||||
|
||||
/// Bound of the in-memory legacy opt-in table (memory bound; see [`LogLevelStore`]).
|
||||
pub(crate) const MAX_TRACKED_SESSIONS: usize = 1_024;
|
||||
|
||||
/// The fixed logger name carried by every notification. It is a server constant, never a
|
||||
/// client-supplied or catalog-supplied value.
|
||||
const LOGGER_NAME: &str = "crank-mcp-server";
|
||||
|
||||
/// Closed safe vocabulary: the server served the request.
|
||||
pub(crate) const EVENT_SERVED: &str = "mcp.request.served";
|
||||
/// Closed safe vocabulary: the request was rejected as invalid before any service work.
|
||||
pub(crate) const EVENT_REJECTED: &str = "mcp.request.rejected";
|
||||
/// Closed safe vocabulary: the request failed on the server side.
|
||||
pub(crate) const EVENT_FAILED: &str = "mcp.request.failed";
|
||||
/// Closed safe vocabulary: this client set its logging level.
|
||||
pub(crate) const EVENT_LEVEL_APPLIED: &str = "mcp.logging.level_applied";
|
||||
|
||||
/// The `params` of one `logging/setLevel` request as the legacy adapter parses it from the wire form.
|
||||
///
|
||||
/// Only the single pinned member exists here: an unknown member is ignored by serde, and a `level`
|
||||
/// that is not a string is a deserialization error, which the adapter answers with the same safe
|
||||
/// [`INVALID_LEVEL`] detail instead of a serde diagnostic.
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub(crate) struct SetLevelCommand {
|
||||
pub(crate) level: String,
|
||||
}
|
||||
|
||||
impl SetLevelCommand {
|
||||
/// The bounded input contract of AC2: the level is length-bounded and compared exactly, so a
|
||||
/// malformed or oversized value is refused with bounded work and one safe detail.
|
||||
pub(crate) fn validate(&self) -> Result<LogLevel, &'static str> {
|
||||
if self.level.is_empty() || self.level.len() > MAX_LEVEL_BYTES {
|
||||
return Err(INVALID_LEVEL);
|
||||
}
|
||||
LogLevel::parse(&self.level).ok_or(INVALID_LEVEL)
|
||||
}
|
||||
}
|
||||
|
||||
/// A neutral outcome of the shared `logging/setLevel` service.
|
||||
pub(crate) enum LoggingOutcome {
|
||||
/// The level of this client context was accepted.
|
||||
Applied(LogLevel),
|
||||
/// Malformed or oversized level: one safe detail, no echoed input.
|
||||
InvalidParams(&'static str),
|
||||
}
|
||||
|
||||
/// One recorded event of the closed vocabulary.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
struct SafeEvent {
|
||||
level: LogLevel,
|
||||
event: &'static str,
|
||||
outcome: &'static str,
|
||||
}
|
||||
|
||||
/// The request-scoped logging state: the level this client opted in to, whether the client offered
|
||||
/// the SSE response mode that is the only carrier of a server notification, and the bounded events
|
||||
/// this response will carry.
|
||||
#[derive(Default)]
|
||||
struct RequestLog {
|
||||
active: Option<LogLevel>,
|
||||
sse_acceptable: bool,
|
||||
pending: Vec<SafeEvent>,
|
||||
}
|
||||
|
||||
task_local! {
|
||||
/// Per-request logging scope. Installed by the HTTP entry point of the MCP endpoint, so two
|
||||
/// concurrently served requests never share a level or a buffer. Code outside such a scope
|
||||
/// (unit tests, background workers) sees a no-op.
|
||||
static REQUEST_LOG: RefCell<RequestLog>;
|
||||
}
|
||||
|
||||
/// Run one request inside its own logging scope.
|
||||
pub(crate) async fn scoped<F: Future>(future: F) -> F::Output {
|
||||
REQUEST_LOG
|
||||
.scope(RefCell::new(RequestLog::default()), future)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Activate (or clear) the level of the current client context. Outside a scope this is a no-op.
|
||||
pub(crate) fn set_active_level(level: Option<LogLevel>) {
|
||||
let _ = REQUEST_LOG.try_with(|log| {
|
||||
if let Ok(mut log) = log.try_borrow_mut() {
|
||||
log.active = level;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Remember that this request offered `text/event-stream`, the only carrier of a notification.
|
||||
pub(crate) fn set_sse_acceptable() {
|
||||
let _ = REQUEST_LOG.try_with(|log| {
|
||||
if let Ok(mut log) = log.try_borrow_mut() {
|
||||
log.sse_acceptable = true;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Record one event of the closed vocabulary for the level this client opted in to.
|
||||
///
|
||||
/// Everything below the active level, every event without an active level (the client did not opt
|
||||
/// in), and every event beyond the fixed buffer bound is dropped silently: the caller never branches
|
||||
/// on logging.
|
||||
pub(crate) fn note(level: LogLevel, event: &'static str, outcome: &'static str) {
|
||||
let _ = REQUEST_LOG.try_with(|log| {
|
||||
let Ok(mut log) = log.try_borrow_mut() else {
|
||||
return;
|
||||
};
|
||||
let Some(active) = log.active else {
|
||||
return;
|
||||
};
|
||||
if level < active || log.pending.len() >= MAX_PENDING_NOTIFICATIONS {
|
||||
return;
|
||||
}
|
||||
log.pending.push(SafeEvent {
|
||||
level,
|
||||
event,
|
||||
outcome,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// The pending events as wire `notifications/message` bodies, and whether this request can carry
|
||||
/// them at all. Draining is the last step of the response projection, so a notification can never be
|
||||
/// delivered twice or survive into another request.
|
||||
pub(crate) fn take_notifications() -> Vec<Value> {
|
||||
REQUEST_LOG
|
||||
.try_with(|log| {
|
||||
let Ok(mut log) = log.try_borrow_mut() else {
|
||||
return Vec::new();
|
||||
};
|
||||
if !log.sse_acceptable {
|
||||
// A JSON body has no place for a server notification: the event is not delivered
|
||||
// instead of being smuggled into the result object.
|
||||
log.pending.clear();
|
||||
return Vec::new();
|
||||
}
|
||||
std::mem::take(&mut log.pending)
|
||||
.into_iter()
|
||||
.map(|event| {
|
||||
json!({
|
||||
"jsonrpc": "2.0",
|
||||
"method": "notifications/message",
|
||||
"params": {
|
||||
"level": event.level.as_str(),
|
||||
"logger": LOGGER_NAME,
|
||||
"data": {
|
||||
"event": event.event,
|
||||
"outcome": event.outcome,
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The per-session opt-in of the legacy era.
|
||||
///
|
||||
/// The login belongs to the session the client negotiated, so a level set by one agent's client can
|
||||
/// never apply to another. It is deliberately **in-memory only**: persisting it would need a schema
|
||||
/// migration of the transport session store, and the deprecated capability does not justify that.
|
||||
///
|
||||
/// shortcut: the table is per process — a level set on one replica is not seen by another replica
|
||||
/// serving the same session, and a restart clears it; upgrade to the session store if a durable or
|
||||
/// cross-replica level is ever required.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct LogLevelStore {
|
||||
levels: Mutex<HashMap<String, LogLevel>>,
|
||||
}
|
||||
|
||||
impl LogLevelStore {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Store the level of one session. Never waits and never fails: on lock contention the update is
|
||||
/// skipped rather than blocking the request.
|
||||
pub(crate) fn set(&self, session_id: &str, level: LogLevel) {
|
||||
let Some(mut levels) = self.lock() else {
|
||||
return;
|
||||
};
|
||||
if levels.len() >= MAX_TRACKED_SESSIONS && !levels.contains_key(session_id) {
|
||||
// Bounded table: the oldest opt-ins are dropped instead of growing without a limit. A
|
||||
// dropped client simply stops receiving notifications until it sets its level again.
|
||||
levels.clear();
|
||||
}
|
||||
levels.insert(session_id.to_owned(), level);
|
||||
}
|
||||
|
||||
/// The level of one session, if this process still remembers it.
|
||||
pub(crate) fn get(&self, session_id: &str) -> Option<LogLevel> {
|
||||
self.lock()?.get(session_id).copied()
|
||||
}
|
||||
|
||||
fn lock(&self) -> Option<MutexGuard<'_, HashMap<String, LogLevel>>> {
|
||||
self.levels.try_lock().ok()
|
||||
}
|
||||
}
|
||||
|
||||
/// Serve one `logging/setLevel` request of the legacy era (AC1/AC2).
|
||||
///
|
||||
/// The command has already been parsed from the wire form, so this function only validates and
|
||||
/// records; it never reads the registry, the catalog or any stored value.
|
||||
pub(crate) fn handle_logging_command(
|
||||
store: &LogLevelStore,
|
||||
session_id: &str,
|
||||
command: SetLevelCommand,
|
||||
) -> LoggingOutcome {
|
||||
match command.validate() {
|
||||
Ok(level) => {
|
||||
store.set(session_id, level);
|
||||
LoggingOutcome::Applied(level)
|
||||
}
|
||||
Err(detail) => LoggingOutcome::InvalidParams(detail),
|
||||
}
|
||||
}
|
||||
|
||||
/// The level a modern request asked for in `_meta`.
|
||||
///
|
||||
/// The pinned schema says the server must not send `notifications/message` for a request that does
|
||||
/// not carry the key, so an absent, non-string or unknown value is simply "not opted in": it is not
|
||||
/// an error of the business request and never widens the accepted vocabulary.
|
||||
pub(crate) fn modern_request_level(message: &Value) -> Option<LogLevel> {
|
||||
let meta = crate::jsonrpc::params(message).get("_meta")?.clone();
|
||||
let value = meta.get(crate::jsonrpc::META_LOG_LEVEL_KEY)?.as_str()?;
|
||||
LogLevel::parse(value)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "logging_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,316 @@
|
||||
//! Unit contract of Story 3.18: the pinned level vocabulary, the bounded input contract of
|
||||
//! `logging/setLevel`, the request-scoped bounded event buffer and the closed safe notification
|
||||
//! shape.
|
||||
|
||||
use serde_json::json;
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Parse one `logging/setLevel` params object and validate its level, or `None` when the shape itself
|
||||
/// is malformed (which the adapter answers with the same safe detail).
|
||||
fn validate(level: &str) -> Option<Result<LogLevel, &'static str>> {
|
||||
let command: SetLevelCommand = serde_json::from_value(json!({ "level": level })).ok()?;
|
||||
Some(command.validate())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_pinned_level_is_accepted_exactly_once_and_in_severity_order() {
|
||||
// The pinned `LoggingLevel` union of both revisions, most verbose first.
|
||||
let pinned = [
|
||||
("debug", LogLevel::Debug),
|
||||
("info", LogLevel::Info),
|
||||
("notice", LogLevel::Notice),
|
||||
("warning", LogLevel::Warning),
|
||||
("error", LogLevel::Error),
|
||||
("critical", LogLevel::Critical),
|
||||
("alert", LogLevel::Alert),
|
||||
("emergency", LogLevel::Emergency),
|
||||
];
|
||||
for (index, (literal, expected)) in pinned.iter().enumerate() {
|
||||
assert_eq!(
|
||||
LogLevel::parse(literal),
|
||||
Some(*expected),
|
||||
"{literal} is a pinned level"
|
||||
);
|
||||
assert_eq!(
|
||||
expected.as_str(),
|
||||
*literal,
|
||||
"the wire literal of a level is exactly the pinned string"
|
||||
);
|
||||
assert_eq!(
|
||||
*expected as usize, index,
|
||||
"the severity ordering of {literal} must follow the RFC 5424 order"
|
||||
);
|
||||
assert_eq!(
|
||||
validate(literal),
|
||||
Some(Ok(*expected)),
|
||||
"{literal} must be accepted through the wire shape too"
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
pinned.windows(2).all(|pair| pair[0].1 < pair[1].1),
|
||||
"severity must be strictly increasing so the filter is `event >= level`"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_outside_the_pinned_union_is_a_level() {
|
||||
for value in [
|
||||
"",
|
||||
"warn",
|
||||
"WARN",
|
||||
"Info",
|
||||
"information",
|
||||
" debug",
|
||||
"debug ",
|
||||
"0",
|
||||
"7",
|
||||
"emergency!",
|
||||
"debug\u{0}",
|
||||
"информация",
|
||||
] {
|
||||
assert_eq!(
|
||||
LogLevel::parse(value),
|
||||
None,
|
||||
"{value:?} is not one of the pinned literals and must never be coerced into one"
|
||||
);
|
||||
assert_eq!(
|
||||
validate(value),
|
||||
Some(Err(INVALID_LEVEL)),
|
||||
"a value outside the union is a bounded invalid-params detail, got {value:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_level_shapes_share_one_safe_detail() {
|
||||
// A `level` the schema types as a string, sent as something else: a deserialization error that the
|
||||
// adapter answers with the same safe detail. It never echoes what the client sent.
|
||||
for value in [json!(7), json!(1.5), json!(0)] {
|
||||
assert!(
|
||||
serde_json::from_value::<SetLevelCommand>(json!({ "level": value })).is_err(),
|
||||
"a numeric level is not a pinned LoggingLevel"
|
||||
);
|
||||
}
|
||||
for value in [json!(null), json!({}), json!(["info"]), json!(true)] {
|
||||
assert!(
|
||||
serde_json::from_value::<SetLevelCommand>(json!({ "level": value })).is_err(),
|
||||
"a non-string level is not a pinned LoggingLevel"
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
serde_json::from_value::<SetLevelCommand>(json!({})).is_err(),
|
||||
"the pinned request requires `level`"
|
||||
);
|
||||
// Control: the same safe detail is what an unknown string produces, so both malformed shapes are
|
||||
// indistinguishable on the wire and neither discloses what was sent.
|
||||
assert_eq!(validate("verbose"), Some(Err(INVALID_LEVEL)));
|
||||
assert!(
|
||||
INVALID_LEVEL.len() < 64,
|
||||
"the detail stays a fixed short text"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_oversized_level_is_refused_before_any_comparison() {
|
||||
let oversized = "i".repeat(MAX_LEVEL_BYTES + 1);
|
||||
assert_eq!(validate(&oversized), Some(Err(INVALID_LEVEL)));
|
||||
// Positive control: the bound is not so tight that a pinned literal is refused.
|
||||
assert_eq!(validate("emergency"), Some(Ok(LogLevel::Emergency)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_session_opt_in_is_per_session_and_bounded() {
|
||||
let store = LogLevelStore::new();
|
||||
store.set("session-a", LogLevel::Error);
|
||||
store.set("session-b", LogLevel::Debug);
|
||||
assert_eq!(store.get("session-a"), Some(LogLevel::Error));
|
||||
assert_eq!(store.get("session-b"), Some(LogLevel::Debug));
|
||||
assert_eq!(
|
||||
store.get("session-c"),
|
||||
None,
|
||||
"a session that never opted in must not inherit another session's level"
|
||||
);
|
||||
|
||||
// The table stays bounded: filling it past the cap drops the previous opt-ins instead of growing.
|
||||
for index in 0..MAX_TRACKED_SESSIONS {
|
||||
store.set(&format!("filler-{index}"), LogLevel::Info);
|
||||
}
|
||||
store.set("session-after-cap", LogLevel::Alert);
|
||||
assert_eq!(store.get("session-after-cap"), Some(LogLevel::Alert));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_event_is_delivered_only_at_or_above_the_opted_in_level() {
|
||||
// One closed-vocabulary event per severity, recorded inside a request scope that offered SSE.
|
||||
for (active, expected) in [
|
||||
(LogLevel::Debug, 4usize),
|
||||
(LogLevel::Info, 4),
|
||||
(LogLevel::Notice, 3),
|
||||
(LogLevel::Warning, 2),
|
||||
(LogLevel::Error, 1),
|
||||
(LogLevel::Critical, 0),
|
||||
(LogLevel::Alert, 0),
|
||||
(LogLevel::Emergency, 0),
|
||||
] {
|
||||
let delivered = scoped(async move {
|
||||
set_active_level(Some(active));
|
||||
set_sse_acceptable();
|
||||
note(LogLevel::Info, EVENT_SERVED, "ok");
|
||||
note(LogLevel::Notice, EVENT_LEVEL_APPLIED, "applied");
|
||||
note(LogLevel::Warning, EVENT_REJECTED, "invalid_params");
|
||||
note(LogLevel::Error, EVENT_FAILED, "internal");
|
||||
take_notifications()
|
||||
})
|
||||
.await;
|
||||
assert_eq!(
|
||||
delivered.len(),
|
||||
expected,
|
||||
"level {} must deliver exactly the events at or above it",
|
||||
active.as_str()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn without_an_opt_in_nothing_is_even_recorded() {
|
||||
// Outside a scope (no request, e.g. a background worker): a no-op.
|
||||
note(LogLevel::Info, EVENT_SERVED, "ok");
|
||||
assert!(take_notifications().is_empty());
|
||||
|
||||
// Inside a scope without an opted-in level.
|
||||
let no_level = scoped(async {
|
||||
set_sse_acceptable();
|
||||
note(LogLevel::Error, EVENT_FAILED, "internal");
|
||||
take_notifications()
|
||||
})
|
||||
.await;
|
||||
assert!(
|
||||
no_level.is_empty(),
|
||||
"the pinned modern schema forbids notifications for a client that did not opt in"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_level_is_present_but_the_client_offered_no_stream() {
|
||||
let delivered = scoped(async {
|
||||
set_active_level(Some(LogLevel::Debug));
|
||||
note(LogLevel::Error, EVENT_FAILED, "internal");
|
||||
take_notifications()
|
||||
})
|
||||
.await;
|
||||
assert!(
|
||||
delivered.is_empty(),
|
||||
"a JSON body has no carrier for notifications/message; the event is dropped, not smuggled in"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_buffer_is_bounded_and_drains_once() {
|
||||
let (first, second) = scoped(async {
|
||||
set_active_level(Some(LogLevel::Debug));
|
||||
set_sse_acceptable();
|
||||
for _ in 0..(MAX_PENDING_NOTIFICATIONS * 4) {
|
||||
note(LogLevel::Info, EVENT_SERVED, "ok");
|
||||
}
|
||||
let first = take_notifications();
|
||||
let second = take_notifications();
|
||||
(first, second)
|
||||
})
|
||||
.await;
|
||||
assert_eq!(
|
||||
first.len(),
|
||||
MAX_PENDING_NOTIFICATIONS,
|
||||
"the per-response frequency bound"
|
||||
);
|
||||
assert!(
|
||||
second.is_empty(),
|
||||
"a delivered event must not survive into a later response"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_notification_body_is_exactly_the_closed_safe_shape() {
|
||||
let delivered = scoped(async {
|
||||
set_active_level(Some(LogLevel::Debug));
|
||||
set_sse_acceptable();
|
||||
note(LogLevel::Warning, EVENT_REJECTED, "invalid_params");
|
||||
take_notifications()
|
||||
})
|
||||
.await;
|
||||
assert_eq!(
|
||||
delivered,
|
||||
vec![json!({
|
||||
"jsonrpc": "2.0",
|
||||
"method": "notifications/message",
|
||||
"params": {
|
||||
"level": "warning",
|
||||
"logger": "crank-mcp-server",
|
||||
"data": {"event": "mcp.request.rejected", "outcome": "invalid_params"}
|
||||
}
|
||||
})],
|
||||
"`params` carries only the severity, the fixed logger name and the closed data object"
|
||||
);
|
||||
// A notification has no `id`, so it can never be mistaken for a response.
|
||||
assert!(delivered[0].get("id").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_modern_level_is_read_from_the_pinned_meta_key_only() {
|
||||
let modern = |meta: Value| json!({"jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": {"_meta": meta}});
|
||||
assert_eq!(
|
||||
modern_request_level(&modern(
|
||||
json!({ "io.modelcontextprotocol/logLevel": "error" })
|
||||
)),
|
||||
Some(LogLevel::Error)
|
||||
);
|
||||
// Not opted in: an absent key, a non-string value and an unknown literal are all "no level".
|
||||
assert_eq!(modern_request_level(&modern(json!({}))), None);
|
||||
assert_eq!(
|
||||
modern_request_level(&modern(json!({ "io.modelcontextprotocol/logLevel": 7 }))),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
modern_request_level(&modern(
|
||||
json!({ "io.modelcontextprotocol/logLevel": "verbose" })
|
||||
)),
|
||||
None
|
||||
);
|
||||
// A level under another key is not the pinned carrier.
|
||||
assert_eq!(
|
||||
modern_request_level(&modern(json!({ "logLevel": "error" }))),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
modern_request_level(&json!({"jsonrpc": "2.0", "id": 1, "method": "tools/list"})),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_command_records_the_level_of_its_own_session_only() {
|
||||
let store = LogLevelStore::new();
|
||||
store.set("other-session", LogLevel::Debug);
|
||||
let command: SetLevelCommand =
|
||||
serde_json::from_value(json!({ "level": "critical" })).expect("a pinned level parses");
|
||||
let outcome = handle_logging_command(&store, "this-session", command);
|
||||
assert!(matches!(
|
||||
outcome,
|
||||
LoggingOutcome::Applied(LogLevel::Critical)
|
||||
));
|
||||
assert_eq!(store.get("this-session"), Some(LogLevel::Critical));
|
||||
assert_eq!(
|
||||
store.get("other-session"),
|
||||
Some(LogLevel::Debug),
|
||||
"setting one session's level must never change another client's level"
|
||||
);
|
||||
|
||||
// A malformed level changes nothing.
|
||||
let malformed: SetLevelCommand =
|
||||
serde_json::from_value(json!({ "level": "verbose" })).expect("the shape parses");
|
||||
assert!(matches!(
|
||||
handle_logging_command(&store, "this-session", malformed),
|
||||
LoggingOutcome::InvalidParams(INVALID_LEVEL)
|
||||
));
|
||||
assert_eq!(store.get("this-session"), Some(LogLevel::Critical));
|
||||
}
|
||||
@@ -26,15 +26,22 @@ use crate::transport::{json_response, protocol_version_from_headers, singleton_h
|
||||
|
||||
mod command;
|
||||
mod completion;
|
||||
mod logging;
|
||||
mod prompts;
|
||||
mod registry;
|
||||
mod resources;
|
||||
mod signals;
|
||||
|
||||
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 logging::{
|
||||
EVENT_FAILED, EVENT_LEVEL_APPLIED, EVENT_REJECTED, EVENT_SERVED, INVALID_LEVEL, LogLevel,
|
||||
LogLevelStore, LoggingOutcome, SetLevelCommand, handle_logging_command, modern_request_level,
|
||||
note, scoped as logging_scope, set_active_level, set_sse_acceptable, take_notifications,
|
||||
};
|
||||
pub(crate) use prompts::{
|
||||
PromptGetCommand, PromptsCommand, PromptsListCommand, PromptsOutcome, handle_prompts_command,
|
||||
};
|
||||
@@ -42,6 +49,10 @@ pub(crate) use resources::{
|
||||
ResourceReadCommand, ResourceTemplatesListError, ResourcesCommand, ResourcesListCommand,
|
||||
ResourcesOutcome, handle_resources_command, list_resource_templates,
|
||||
};
|
||||
pub(crate) use signals::{
|
||||
FilterOutcome, INVALID_LISTEN_FILTER, ListenParams, Signals, StreamRegistry, Watch, Wire,
|
||||
acknowledged_frame, frames_stream, spawn as spawn_signal_watch, subscription_id,
|
||||
};
|
||||
|
||||
/// Resolved era of an incoming POST request.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
|
||||
@@ -22,6 +22,20 @@ pub(crate) enum CapabilityId {
|
||||
Prompts,
|
||||
/// Bounded argument completion for bound Published Prompts and Resource templates (Story 3.17).
|
||||
Completions,
|
||||
/// `subscriptions/listen` of the modern revision: a *client-sent* request that opens the
|
||||
/// notification stream (Story 3.19). It is a dispatch-only registration without an advertisement
|
||||
/// fragment because the pinned modern schema has no server `subscriptions` capability object;
|
||||
/// there is no such method in the legacy revision at all.
|
||||
Subscriptions,
|
||||
/// `logging` server capability: safe structured `notifications/message` events of the negotiated
|
||||
/// client context (Story 3.18). Advertised in both revisions; the pinned modern revision carries
|
||||
/// the level per request in `_meta` and marks the capability deprecated (SEP-2577).
|
||||
Logging,
|
||||
/// `logging/setLevel` as the *legacy* client request that sets a session level. It is a
|
||||
/// dispatch-only registration without an advertisement fragment because the pinned modern
|
||||
/// revision has no such method: there the per-request `_meta` key replaces it, so the same wire
|
||||
/// name is a wrong-era request and must never be served.
|
||||
LoggingSetLevel,
|
||||
Ping,
|
||||
Discovery,
|
||||
LegacyLifecycle,
|
||||
@@ -81,6 +95,13 @@ pub(crate) enum MethodHandler {
|
||||
/// `completion/complete`: bounded suggestions from the typed schema of one exact bound Prompt
|
||||
/// argument or one exact bound Resource template parameter (Story 3.17).
|
||||
Completion,
|
||||
/// `subscriptions/listen`: open the long-lived modern notification stream and deliver the
|
||||
/// Resource/Prompt list-change signals the client opted in to (Story 3.19).
|
||||
SubscriptionsListen,
|
||||
/// `logging/setLevel`: validate the pinned level and record it for this legacy session, so the
|
||||
/// adapter can deliver safe structured `notifications/message` events of that context
|
||||
/// (Story 3.18). The handler never widens the accepted vocabulary and never echoes the input.
|
||||
LoggingSetLevel,
|
||||
Ping,
|
||||
Discover,
|
||||
Lifecycle,
|
||||
@@ -358,7 +379,9 @@ pub(crate) const CAPABILITY_DESCRIPTORS: &[CapabilityIdDescriptor] = &[
|
||||
extension: None,
|
||||
deprecated: None,
|
||||
sub_features: FeatureSet(&["subscribe", "listChanged"]),
|
||||
advertised: Some(("resources", &[("subscribe", false), ("listChanged", false)])),
|
||||
// Story 3.19: the server really emits `notifications/resources/list_changed`; URI-content
|
||||
// subscriptions (`subscribe`) remain unimplemented and are still advertised as false.
|
||||
advertised: Some(("resources", &[("subscribe", false), ("listChanged", true)])),
|
||||
revisions: MODERN_AND_LEGACY,
|
||||
},
|
||||
CapabilityIdDescriptor {
|
||||
@@ -368,7 +391,8 @@ pub(crate) const CAPABILITY_DESCRIPTORS: &[CapabilityIdDescriptor] = &[
|
||||
extension: None,
|
||||
deprecated: None,
|
||||
sub_features: FeatureSet(&["listChanged"]),
|
||||
advertised: Some(("prompts", &[("listChanged", false)])),
|
||||
// Story 3.19: the server really emits `notifications/prompts/list_changed`.
|
||||
advertised: Some(("prompts", &[("listChanged", true)])),
|
||||
revisions: MODERN_AND_LEGACY,
|
||||
},
|
||||
CapabilityIdDescriptor {
|
||||
@@ -382,6 +406,46 @@ pub(crate) const CAPABILITY_DESCRIPTORS: &[CapabilityIdDescriptor] = &[
|
||||
advertised: Some(("completions", &[])),
|
||||
revisions: MODERN_AND_LEGACY,
|
||||
},
|
||||
CapabilityIdDescriptor {
|
||||
// Story 3.18: the standard `logging` declaration of both approved revisions. The pinned
|
||||
// modern revision marks it deprecated (SEP-2577) but keeps it in the schema for at least
|
||||
// twelve months, and `notifications/message` remains the only log channel there; the legacy
|
||||
// revision additionally serves `logging/setLevel`.
|
||||
id: CapabilityId::Logging,
|
||||
roster: Roster::Server,
|
||||
kind: Kind::Capability,
|
||||
extension: None,
|
||||
deprecated: None,
|
||||
// The pinned schema declares `logging` as an open object with no named sub-features.
|
||||
sub_features: FeatureSet(&[]),
|
||||
advertised: Some(("logging", &[])),
|
||||
revisions: MODERN_AND_LEGACY,
|
||||
},
|
||||
CapabilityIdDescriptor {
|
||||
// Dispatch-only registration of the legacy `logging/setLevel` request: it is a client
|
||||
// request, not an advertised server capability, and it does not exist in the modern schema.
|
||||
id: CapabilityId::LoggingSetLevel,
|
||||
roster: Roster::Server,
|
||||
kind: Kind::Method,
|
||||
extension: None,
|
||||
deprecated: None,
|
||||
sub_features: FeatureSet(&[]),
|
||||
advertised: None,
|
||||
revisions: LEGACY_ONLY,
|
||||
},
|
||||
CapabilityIdDescriptor {
|
||||
// Story 3.19: dispatch-only registration of the modern `subscriptions/listen` request. The
|
||||
// client sends it; the pinned modern schema declares no server `subscriptions` capability
|
||||
// object, so it carries no advertisement fragment. The legacy revision has no such method.
|
||||
id: CapabilityId::Subscriptions,
|
||||
roster: Roster::Client,
|
||||
kind: Kind::Method,
|
||||
extension: None,
|
||||
deprecated: None,
|
||||
sub_features: FeatureSet(&[]),
|
||||
advertised: None,
|
||||
revisions: MODERN_ONLY,
|
||||
},
|
||||
CapabilityIdDescriptor {
|
||||
id: CapabilityId::Ping,
|
||||
roster: Roster::Server,
|
||||
@@ -486,6 +550,27 @@ pub(crate) const METHOD_DESCRIPTORS: &[MethodDescriptor] = &[
|
||||
required_headers: HEADERS_METHOD_ONLY,
|
||||
handler: MethodHandler::Completion,
|
||||
},
|
||||
MethodDescriptor {
|
||||
// Story 3.18: the legacy client request that sets the log level of its session. It declares
|
||||
// the level, not a server-side name, so only the method header applies; the pinned modern
|
||||
// revision has no such method at all (per-request `_meta` replaces it).
|
||||
name: "logging/setLevel",
|
||||
capability: CapabilityId::LoggingSetLevel,
|
||||
kind: Kind::Method,
|
||||
required_headers: HEADERS_METHOD_ONLY,
|
||||
handler: MethodHandler::LoggingSetLevel,
|
||||
},
|
||||
MethodDescriptor {
|
||||
// Story 3.19: the modern long-lived notification stream. It declares the notification filter
|
||||
// in its params, not a server-side name, so only the method header applies. The legacy
|
||||
// revision opens its notification stream with `GET` instead, so this name is a wrong-era
|
||||
// request there and must never be served.
|
||||
name: "subscriptions/listen",
|
||||
capability: CapabilityId::Subscriptions,
|
||||
kind: Kind::Method,
|
||||
required_headers: HEADERS_METHOD_ONLY,
|
||||
handler: MethodHandler::SubscriptionsListen,
|
||||
},
|
||||
MethodDescriptor {
|
||||
name: "ping",
|
||||
capability: CapabilityId::Ping,
|
||||
|
||||
@@ -36,8 +36,9 @@ fn static_registration_is_unique_and_advertises_only_the_registered_capability()
|
||||
registry.advertised_capabilities(revision),
|
||||
json!({
|
||||
"completions": {},
|
||||
"prompts": {"listChanged": false},
|
||||
"resources": {"listChanged": false, "subscribe": false},
|
||||
"logging": {},
|
||||
"prompts": {"listChanged": true},
|
||||
"resources": {"listChanged": true, "subscribe": false},
|
||||
"tools": {"listChanged": false}
|
||||
}),
|
||||
"the registered advertisement must be the same reviewed object in {revision}"
|
||||
@@ -46,8 +47,9 @@ fn static_registration_is_unique_and_advertises_only_the_registered_capability()
|
||||
advertised_server_capabilities(revision),
|
||||
json!({
|
||||
"completions": {},
|
||||
"prompts": {"listChanged": false},
|
||||
"resources": {"listChanged": false, "subscribe": false},
|
||||
"logging": {},
|
||||
"prompts": {"listChanged": true},
|
||||
"resources": {"listChanged": true, "subscribe": false},
|
||||
"tools": {"listChanged": false}
|
||||
}),
|
||||
"the production advertisement entry point must serve {revision}"
|
||||
@@ -259,8 +261,9 @@ fn an_inert_test_descriptor_changes_both_projections_and_is_never_registered_in_
|
||||
without.advertised_capabilities(MODERN_PROTOCOL_VERSION),
|
||||
json!({
|
||||
"completions": {},
|
||||
"prompts": {"listChanged": false},
|
||||
"resources": {"listChanged": false, "subscribe": false},
|
||||
"logging": {},
|
||||
"prompts": {"listChanged": true},
|
||||
"resources": {"listChanged": true, "subscribe": false},
|
||||
"tools": {"listChanged": false}
|
||||
})
|
||||
);
|
||||
@@ -269,8 +272,9 @@ fn an_inert_test_descriptor_changes_both_projections_and_is_never_registered_in_
|
||||
json!({
|
||||
"inert_test_capability": {"enabled": true},
|
||||
"completions": {},
|
||||
"prompts": {"listChanged": false},
|
||||
"resources": {"listChanged": false, "subscribe": false},
|
||||
"logging": {},
|
||||
"prompts": {"listChanged": true},
|
||||
"resources": {"listChanged": true, "subscribe": false},
|
||||
"tools": {"listChanged": false}
|
||||
})
|
||||
);
|
||||
@@ -279,8 +283,9 @@ fn an_inert_test_descriptor_changes_both_projections_and_is_never_registered_in_
|
||||
json!({
|
||||
"inert_test_capability": {"enabled": true},
|
||||
"completions": {},
|
||||
"prompts": {"listChanged": false},
|
||||
"resources": {"listChanged": false, "subscribe": false},
|
||||
"logging": {},
|
||||
"prompts": {"listChanged": true},
|
||||
"resources": {"listChanged": true, "subscribe": false},
|
||||
"tools": {"listChanged": false}
|
||||
})
|
||||
);
|
||||
@@ -462,8 +467,9 @@ fn a_single_era_descriptor_never_leaks_into_the_other_era_advertisement() {
|
||||
other_era_advertisement,
|
||||
json!({
|
||||
"completions": {},
|
||||
"prompts": {"listChanged": false},
|
||||
"resources": {"listChanged": false, "subscribe": false},
|
||||
"logging": {},
|
||||
"prompts": {"listChanged": true},
|
||||
"resources": {"listChanged": true, "subscribe": false},
|
||||
"tools": {"listChanged": false}
|
||||
}),
|
||||
"the other era advertisement stays the reviewed object"
|
||||
@@ -654,6 +660,56 @@ fn story317_completion_is_advertised_and_dispatchable_in_both_revisions() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn story318_logging_is_advertised_on_both_revisions_and_set_level_is_legacy_only() {
|
||||
let registry = production_registry();
|
||||
for revision in [MODERN_PROTOCOL_VERSION, LEGACY_PROTOCOL_VERSION] {
|
||||
assert!(
|
||||
registry.advertise_for(CapabilityId::Logging, revision),
|
||||
"the implemented logging surface must be advertised in {revision}"
|
||||
);
|
||||
assert_eq!(
|
||||
registry.advertised_capabilities(revision)["logging"],
|
||||
json!({}),
|
||||
"the pinned advertisement is an empty `logging` object in {revision}"
|
||||
);
|
||||
}
|
||||
|
||||
// `logging/setLevel` is a legacy request only: the pinned modern revision replaces it with the
|
||||
// per-request `_meta` log level, so the modern era must never serve it.
|
||||
assert_eq!(
|
||||
registry.dispatch_decision("logging/setLevel", LEGACY_PROTOCOL_VERSION),
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::LoggingSetLevel,
|
||||
kind: Kind::Method,
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
registry.dispatch_decision("logging/setLevel", MODERN_PROTOCOL_VERSION),
|
||||
DispatchDecision::WrongEra {
|
||||
handler: MethodHandler::LoggingSetLevel,
|
||||
kind: Kind::Method,
|
||||
},
|
||||
"a method the modern schema does not declare must never reach a handler there"
|
||||
);
|
||||
let descriptor = METHOD_DESCRIPTORS
|
||||
.iter()
|
||||
.find(|descriptor| descriptor.name == "logging/setLevel")
|
||||
.expect("logging/setLevel is a registered method");
|
||||
assert_eq!(
|
||||
descriptor.required_headers.0,
|
||||
&["Mcp-Method"],
|
||||
"the request declares a level, not a server-side name"
|
||||
);
|
||||
assert!(
|
||||
CAPABILITY_DESCRIPTORS
|
||||
.iter()
|
||||
.filter(|descriptor| descriptor.id == CapabilityId::LoggingSetLevel)
|
||||
.all(|descriptor| descriptor.advertised.is_none()),
|
||||
"the client request must never be advertised as a server capability"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adding_and_removing_a_method_descriptor_changes_the_dispatch_decision() {
|
||||
// The inert capability owns one inert method. With the method descriptor registered the
|
||||
@@ -702,8 +758,9 @@ fn adding_and_removing_a_method_descriptor_changes_the_dispatch_decision() {
|
||||
json!({
|
||||
"inert_test_capability": {"enabled": true},
|
||||
"completions": {},
|
||||
"prompts": {"listChanged": false},
|
||||
"resources": {"listChanged": false, "subscribe": false},
|
||||
"logging": {},
|
||||
"prompts": {"listChanged": true},
|
||||
"resources": {"listChanged": true, "subscribe": false},
|
||||
"tools": {"listChanged": false}
|
||||
})
|
||||
);
|
||||
|
||||
@@ -0,0 +1,482 @@
|
||||
//! Story 3.19: Resource and Prompt list-change signals (FR-19).
|
||||
//!
|
||||
//! The positive result of the story is that a client which asked for the list-change signal of its
|
||||
//! revision learns that the *committed* Resource or Prompt catalog changed, and that the ordinary
|
||||
//! `resources/list`, `resources/read`, `resources/templates/list`, `prompts/list` and `prompts/get`
|
||||
//! stay authoritative for a client that misses the notification.
|
||||
//!
|
||||
//! Shape of the chosen seam (ARC decision, kanban t_c12863fb): a **stream-local watcher**. One open
|
||||
//! notification stream owns one bounded periodic read of the published Agent catalog the stream is
|
||||
//! scoped to; a change of the visible Resource/Prompt binding projection produces the revision's
|
||||
//! list-change notification. There is no post-commit hook, no cross-process bus and no durable
|
||||
//! queue: the committed catalog is the source of truth, so a signal can never be produced before its
|
||||
//! commit, and a failed read can never roll the commit back — it only skips that tick and stays
|
||||
//! observable in tracing.
|
||||
//!
|
||||
//! Bounds (issue requirement: bounded queues/frequency/bytes):
|
||||
//! * one in-flight read per stream, one fixed poll interval, a read timeout and skipped ticks;
|
||||
//! * at most one frame per change type per tick, so a burst coalesces by the latest observed
|
||||
//! revision instead of queueing every intermediate commit;
|
||||
//! * the queue is a fixed-capacity channel; a slow reader drops the newest frame instead of blocking
|
||||
//! the producer or growing memory, and recovers through the authoritative list methods;
|
||||
//! * every frame has a fixed shape — a closed method name plus the request id of the subscription —
|
||||
//! so the byte bound follows from the id bound ([`MAX_SUBSCRIPTION_ID_BYTES`]).
|
||||
//!
|
||||
//! Scope boundary: this module serves list-change signals only. URI-content subscriptions
|
||||
//! (`resources/subscribe` / `notifications/resources/updated`) stay unimplemented and are never
|
||||
//! acknowledged or emitted here.
|
||||
|
||||
use std::{
|
||||
collections::{HashMap, VecDeque},
|
||||
future::Future,
|
||||
pin::Pin,
|
||||
sync::{
|
||||
Arc, Mutex, MutexGuard,
|
||||
atomic::{AtomicU64, Ordering},
|
||||
},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use axum::response::sse::Event;
|
||||
use crank_registry::PublishedAgentCatalog;
|
||||
use futures_util::stream;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Map, Value, json};
|
||||
use tokio::sync::mpsc;
|
||||
use tracing::warn;
|
||||
|
||||
use crate::app::AppState;
|
||||
|
||||
/// The pinned key that correlates every message of one subscription stream with its
|
||||
/// `subscriptions/listen` request id.
|
||||
pub(crate) const SUBSCRIPTION_ID_KEY: &str = "io.modelcontextprotocol/subscriptionId";
|
||||
|
||||
/// `notifications/resources/list_changed` (both approved revisions).
|
||||
pub(crate) const RESOURCE_LIST_CHANGED: &str = "notifications/resources/list_changed";
|
||||
/// `notifications/prompts/list_changed` (both approved revisions).
|
||||
pub(crate) const PROMPT_LIST_CHANGED: &str = "notifications/prompts/list_changed";
|
||||
/// `notifications/subscriptions/acknowledged` (modern revision only).
|
||||
pub(crate) const SUBSCRIPTIONS_ACKNOWLEDGED: &str = "notifications/subscriptions/acknowledged";
|
||||
|
||||
/// Engineering default of the watcher tick. It is not a measured latency SLO: the story only needs
|
||||
/// "after commit", and the client always keeps the authoritative list methods for recovery.
|
||||
pub(crate) const POLL_INTERVAL: Duration = Duration::from_secs(1);
|
||||
/// Upper bound of one watcher read. A read that exceeds it is a skipped tick, exactly like a failed
|
||||
/// read: no signal, no rollback, one safe tracing event.
|
||||
pub(crate) const READ_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
/// Frames a slow reader may fall behind before the newest frame is dropped (`coalescing`).
|
||||
pub(crate) const SIGNAL_QUEUE_CAPACITY: usize = 4;
|
||||
/// Bound of the encoded `subscriptions/listen` id carried by every frame of one stream.
|
||||
pub(crate) const MAX_SUBSCRIPTION_ID_BYTES: usize = 64;
|
||||
/// Bound of the legacy session stream table (memory bound; see [`StreamRegistry`]).
|
||||
pub(crate) const MAX_TRACKED_STREAMS: usize = 1_024;
|
||||
/// Bound of the URIs a modern filter may name. The server does not implement URI subscriptions, so
|
||||
/// this many names is already far more than a well-behaved client asks for.
|
||||
pub(crate) const MAX_FILTER_URIS: usize = 32;
|
||||
/// Bound of one URI in the modern filter: longer values are rejected without being echoed back.
|
||||
pub(crate) const MAX_FILTER_URI_BYTES: usize = 2_048;
|
||||
|
||||
/// The one safe detail of a malformed or oversized `subscriptions/listen` filter.
|
||||
pub(crate) const INVALID_LISTEN_FILTER: &str = "invalid subscriptions/listen notification filter";
|
||||
|
||||
/// The two list-change signal types this server implements.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub(crate) struct Signals {
|
||||
pub(crate) resources: bool,
|
||||
pub(crate) prompts: bool,
|
||||
}
|
||||
|
||||
impl Signals {
|
||||
/// Both types: the legacy revision defines no client opt-in, so its stream carries both.
|
||||
pub(crate) const BOTH: Self = Self {
|
||||
resources: true,
|
||||
prompts: true,
|
||||
};
|
||||
|
||||
#[cfg_attr(not(test), allow(dead_code))] // read by the unit oracle of the projection
|
||||
pub(crate) fn any(self) -> bool {
|
||||
self.resources || self.prompts
|
||||
}
|
||||
|
||||
fn intersect(self, other: Self) -> Self {
|
||||
Self {
|
||||
resources: self.resources && other.resources,
|
||||
prompts: self.prompts && other.prompts,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The pinned modern `SubscriptionFilter`, as far as this server reads it.
|
||||
///
|
||||
/// Unknown members are ignored and a malformed shape is a deserialization error, so a client cannot
|
||||
/// reach the watcher with anything but the reviewed field set.
|
||||
#[derive(Debug, Default, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(crate) struct ListenFilter {
|
||||
#[serde(default)]
|
||||
/// `toolsListChanged` is not implemented in this scope and is therefore never acknowledged.
|
||||
#[allow(dead_code)]
|
||||
tools_list_changed: bool,
|
||||
#[serde(default)]
|
||||
prompts_list_changed: bool,
|
||||
#[serde(default)]
|
||||
resources_list_changed: bool,
|
||||
#[serde(default)]
|
||||
resource_subscriptions: Vec<String>,
|
||||
}
|
||||
|
||||
/// The pinned `SubscriptionsListenRequestParams`: the notification filter is a required member.
|
||||
///
|
||||
/// Only the reviewed member is read; `_meta` and any other member of the request params is not part
|
||||
/// of this contract.
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub(crate) struct ListenParams {
|
||||
pub(crate) notifications: ListenFilter,
|
||||
}
|
||||
|
||||
/// The bounded input contract of a `subscriptions/listen` filter.
|
||||
pub(crate) enum FilterOutcome {
|
||||
/// The list-change subset this server honours for the stream.
|
||||
Accepted(Signals),
|
||||
/// One safe detail: no URI, name or value the client sent is echoed back.
|
||||
Invalid(&'static str),
|
||||
}
|
||||
|
||||
impl ListenFilter {
|
||||
/// Validate the bounded inputs and keep only the honoured types.
|
||||
///
|
||||
/// `toolsListChanged` and `resourceSubscriptions` are not implemented in the current scope, which
|
||||
/// is what the acknowledgment reports: they are simply not honoured, and the pinned schema
|
||||
/// forbids the server from sending a type it did not agree to.
|
||||
pub(crate) fn accepted(&self) -> FilterOutcome {
|
||||
if self.resource_subscriptions.len() > MAX_FILTER_URIS
|
||||
|| self
|
||||
.resource_subscriptions
|
||||
.iter()
|
||||
.any(|uri| uri.len() > MAX_FILTER_URI_BYTES)
|
||||
{
|
||||
return FilterOutcome::Invalid(INVALID_LISTEN_FILTER);
|
||||
}
|
||||
FilterOutcome::Accepted(Signals {
|
||||
resources: self.resources_list_changed,
|
||||
prompts: self.prompts_list_changed,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The `notifications` object of the acknowledgment: exactly the subset that will be delivered.
|
||||
fn acknowledged_filter_wire(accepted: Signals) -> Value {
|
||||
let mut filter = Map::new();
|
||||
if accepted.prompts {
|
||||
filter.insert("promptsListChanged".to_owned(), Value::Bool(true));
|
||||
}
|
||||
if accepted.resources {
|
||||
filter.insert("resourcesListChanged".to_owned(), Value::Bool(true));
|
||||
}
|
||||
Value::Object(filter)
|
||||
}
|
||||
|
||||
/// The exact bound Resource/Prompt projection of one published Agent catalog.
|
||||
///
|
||||
/// The projection is derived from the same committed catalog read that already feeds
|
||||
/// `resources/list`, `resources/templates/list`, `prompts/list` and `prompts/get`: the exact Resource
|
||||
/// and Prompt bindings of the published Agent snapshot, in deterministic binding order.
|
||||
/// `catalog_revision` alone is *not* the comparison key — a commit that only changes Tools must not
|
||||
/// produce a Resource/Prompt signal — so the two binding vectors are compared on their own.
|
||||
///
|
||||
/// shortcut: a Resource revocation invalidates a bound publication without a new Agent snapshot, so
|
||||
/// it does not change this projection and produces no list-change signal; the revocation gate at
|
||||
/// read time (Story 3.8) still fails closed, and a faithful revocation signal needs a bounded
|
||||
/// registry read that the current scope does not have.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub(crate) struct CatalogFingerprint {
|
||||
resources: Vec<(String, u32)>,
|
||||
prompts: Vec<(String, u32)>,
|
||||
}
|
||||
|
||||
impl CatalogFingerprint {
|
||||
pub(crate) fn of(catalog: &PublishedAgentCatalog) -> Self {
|
||||
let mut resources = catalog
|
||||
.resources
|
||||
.iter()
|
||||
.map(|binding| {
|
||||
(
|
||||
binding.resource_id.as_str().to_owned(),
|
||||
binding.resource_version,
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let mut prompts = catalog
|
||||
.prompts
|
||||
.iter()
|
||||
.map(|binding| {
|
||||
(
|
||||
binding.prompt_id.as_str().to_owned(),
|
||||
binding.prompt_version,
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
resources.sort();
|
||||
prompts.sort();
|
||||
Self { resources, prompts }
|
||||
}
|
||||
|
||||
/// The list-change types whose visible binding projection differs between `previous` and `self`.
|
||||
pub(crate) fn changes_since(&self, previous: &Self) -> Signals {
|
||||
Signals {
|
||||
resources: self.resources != previous.resources,
|
||||
prompts: self.prompts != previous.prompts,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The wire contract of one stream.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) enum Wire {
|
||||
/// `2025-11-25`: a bare server notification without parameters.
|
||||
Legacy,
|
||||
/// `2026-07-28`: every message carries the subscription id of its `subscriptions/listen` request.
|
||||
Modern(Value),
|
||||
}
|
||||
|
||||
impl Wire {
|
||||
fn signal_frames(&self, signals: Signals) -> Vec<String> {
|
||||
let mut frames = Vec::with_capacity(2);
|
||||
for (changed, method) in [
|
||||
(signals.resources, RESOURCE_LIST_CHANGED),
|
||||
(signals.prompts, PROMPT_LIST_CHANGED),
|
||||
] {
|
||||
if !changed {
|
||||
continue;
|
||||
}
|
||||
let frame = match self {
|
||||
Wire::Legacy => json!({ "jsonrpc": "2.0", "method": method }),
|
||||
Wire::Modern(subscription_id) => json!({
|
||||
"jsonrpc": "2.0",
|
||||
"method": method,
|
||||
"params": { "_meta": { SUBSCRIPTION_ID_KEY: subscription_id } }
|
||||
}),
|
||||
};
|
||||
frames.push(frame.to_string());
|
||||
}
|
||||
frames
|
||||
}
|
||||
}
|
||||
|
||||
/// The first modern frame: the accepted subset, before any list-change notification of the stream.
|
||||
pub(crate) fn acknowledged_frame(subscription_id: &Value, accepted: Signals) -> String {
|
||||
json!({
|
||||
"jsonrpc": "2.0",
|
||||
"method": SUBSCRIPTIONS_ACKNOWLEDGED,
|
||||
"params": {
|
||||
"_meta": { SUBSCRIPTION_ID_KEY: subscription_id },
|
||||
"notifications": acknowledged_filter_wire(accepted),
|
||||
}
|
||||
})
|
||||
.to_string()
|
||||
}
|
||||
|
||||
/// The subscription id of a `subscriptions/listen` request, or `None` when its encoding is not a
|
||||
/// bounded identity carrier.
|
||||
pub(crate) fn subscription_id(request_id: &Value) -> Option<Value> {
|
||||
let encoded = request_id.to_string();
|
||||
(encoded.len() <= MAX_SUBSCRIPTION_ID_BYTES).then(|| request_id.clone())
|
||||
}
|
||||
|
||||
/// Bounded table of the legacy session that currently owns the notification stream.
|
||||
///
|
||||
/// The pinned legacy transport forbids broadcasting one message across several SSE streams of the
|
||||
/// same session, and the community scope keeps exactly one producer per session: the newest admitted
|
||||
/// `GET` takes the signals over and the older stream ends. A retired stream (session `DELETE`) or a
|
||||
/// superseded generation never writes into a reconnect.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct StreamRegistry {
|
||||
next_generation: AtomicU64,
|
||||
owners: Mutex<HashMap<String, u64>>,
|
||||
}
|
||||
|
||||
impl StreamRegistry {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Admit the notification stream of one session and return its generation.
|
||||
pub(crate) fn admit(&self, session_id: &str) -> Option<u64> {
|
||||
let generation = self.next_generation.fetch_add(1, Ordering::Relaxed) + 1;
|
||||
let mut owners = self.lock()?;
|
||||
if owners.len() >= MAX_TRACKED_STREAMS && !owners.contains_key(session_id) {
|
||||
// Bounded table: forget the whole owner set instead of growing without a limit. Each
|
||||
// running producer still holds its own generation, so the worst case is a stream that
|
||||
// can no longer be told apart from a newer one — never unbounded memory.
|
||||
owners.clear();
|
||||
}
|
||||
owners.insert(session_id.to_owned(), generation);
|
||||
Some(generation)
|
||||
}
|
||||
|
||||
/// Whether `generation` still owns the stream of `session_id`.
|
||||
pub(crate) fn is_current(&self, session_id: &str, generation: u64) -> bool {
|
||||
self.lock()
|
||||
.and_then(|owners| owners.get(session_id).copied())
|
||||
.is_some_and(|current| current == generation)
|
||||
}
|
||||
|
||||
/// Stop the producer of one session (`DELETE`, or a session that no longer exists).
|
||||
pub(crate) fn retire(&self, session_id: &str) {
|
||||
if let Some(mut owners) = self.lock() {
|
||||
owners.remove(session_id);
|
||||
}
|
||||
}
|
||||
|
||||
fn lock(&self) -> Option<MutexGuard<'_, HashMap<String, u64>>> {
|
||||
self.owners.try_lock().ok()
|
||||
}
|
||||
}
|
||||
|
||||
/// Everything one watcher needs.
|
||||
pub(crate) struct Watch {
|
||||
pub(crate) workspace_slug: String,
|
||||
pub(crate) agent_slug: String,
|
||||
/// The signal types this stream may deliver.
|
||||
pub(crate) signals: Signals,
|
||||
pub(crate) wire: Wire,
|
||||
/// The legacy session lease: the producer stops when the stream is superseded or retired.
|
||||
pub(crate) legacy_stream: Option<(Arc<StreamRegistry>, String, u64)>,
|
||||
/// Lifetime bound inherited from the legacy transport session TTL.
|
||||
pub(crate) deadline: Option<Instant>,
|
||||
}
|
||||
|
||||
/// One committed-catalog read of a watcher tick.
|
||||
///
|
||||
/// The reader is a closure so the failure path is driveable in a unit oracle without a live
|
||||
/// registry: production passes [`read`] over the shared [`AppState`], and the oracle passes a
|
||||
/// scripted sequence.
|
||||
pub(crate) type ReadFuture =
|
||||
Pin<Box<dyn Future<Output = Result<CatalogFingerprint, ReadError>> + Send>>;
|
||||
/// A source of committed-catalog reads. One call per tick.
|
||||
pub(crate) type Reader = Box<dyn FnMut() -> ReadFuture + Send>;
|
||||
|
||||
/// Start the stream-local watcher and return the bounded frame queue of the response stream.
|
||||
///
|
||||
/// The first read is the baseline taken **before** the acknowledgment is written; it is never reset
|
||||
/// afterwards, so a publication between the baseline and the acknowledgment is still delivered.
|
||||
pub(crate) fn spawn(state: Arc<AppState>, watch: Watch) -> mpsc::Receiver<String> {
|
||||
let scope = (watch.workspace_slug.clone(), watch.agent_slug.clone());
|
||||
let reader: Reader = Box::new(move || {
|
||||
let state = Arc::clone(&state);
|
||||
let scope = scope.clone();
|
||||
Box::pin(async move { read(&state, &scope).await })
|
||||
});
|
||||
let (sender, receiver) = mpsc::channel(SIGNAL_QUEUE_CAPACITY);
|
||||
tokio::spawn(run(watch, sender, reader));
|
||||
receiver
|
||||
}
|
||||
|
||||
async fn run(watch: Watch, sender: mpsc::Sender<String>, mut read: Reader) {
|
||||
let mut baseline = match read().await {
|
||||
Ok(fingerprint) => Some(fingerprint),
|
||||
Err(ReadError::Gone) => return,
|
||||
Err(ReadError::Retry) => {
|
||||
observe_failure();
|
||||
None
|
||||
}
|
||||
};
|
||||
|
||||
loop {
|
||||
if !still_owned(&watch) || sender.is_closed() {
|
||||
return;
|
||||
}
|
||||
if watch
|
||||
.deadline
|
||||
.is_some_and(|deadline| Instant::now() >= deadline)
|
||||
{
|
||||
return;
|
||||
}
|
||||
tokio::time::sleep(POLL_INTERVAL).await;
|
||||
if !still_owned(&watch) {
|
||||
return;
|
||||
}
|
||||
|
||||
match read().await {
|
||||
Ok(fingerprint) => {
|
||||
if let Some(previous) = baseline.as_ref() {
|
||||
let changes = fingerprint.changes_since(previous).intersect(watch.signals);
|
||||
for frame in watch.wire.signal_frames(changes) {
|
||||
// A slow reader coalesces: the newest frame is dropped instead of blocking
|
||||
// the producer or growing a queue, and the client recovers through the
|
||||
// authoritative list methods.
|
||||
let _ = sender.try_send(frame);
|
||||
}
|
||||
}
|
||||
baseline = Some(fingerprint);
|
||||
}
|
||||
// The Agent is no longer published: fail closed by ending the stream instead of serving a
|
||||
// catalog nobody may read any more.
|
||||
Err(ReadError::Gone) => return,
|
||||
// The committed catalog is untouched: the failure is observable and this tick is skipped.
|
||||
Err(_) => observe_failure(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) enum ReadError {
|
||||
/// The published Agent behind this stream is gone: the producer ends.
|
||||
Gone,
|
||||
/// The catalog could not be read this tick: skip it, keep the committed state.
|
||||
Retry,
|
||||
}
|
||||
|
||||
fn still_owned(watch: &Watch) -> bool {
|
||||
match &watch.legacy_stream {
|
||||
Some((registry, session_id, generation)) => registry.is_current(session_id, *generation),
|
||||
None => true,
|
||||
}
|
||||
}
|
||||
|
||||
async fn read(state: &AppState, scope: &(String, String)) -> Result<CatalogFingerprint, ReadError> {
|
||||
let catalog = tokio::time::timeout(READ_TIMEOUT, state.catalog.get_catalog(&scope.0, &scope.1))
|
||||
.await
|
||||
.map_err(|_| ReadError::Retry)?
|
||||
.map_err(|error| match error {
|
||||
crank_registry::RegistryError::PublishedAgentNotFound { .. } => ReadError::Gone,
|
||||
_ => ReadError::Retry,
|
||||
})?;
|
||||
Ok(CatalogFingerprint::of(&catalog))
|
||||
}
|
||||
|
||||
/// One safe, closed-vocabulary observation of a skipped tick: no URI, Agent name, credential or raw
|
||||
/// error text is read here.
|
||||
fn observe_failure() {
|
||||
warn!(
|
||||
name: "mcp.signals.read_failed",
|
||||
error_category = "catalog",
|
||||
"catalog change signal read failed"
|
||||
);
|
||||
}
|
||||
|
||||
/// The bounded SSE body of one signal stream: the leading frames (acknowledgment), then the queue,
|
||||
/// ending when the producer ends. The caller's stream permit lives in `guard` and is released when
|
||||
/// the response stream is dropped.
|
||||
pub(crate) fn frames_stream<G: Send + 'static>(
|
||||
first: Vec<String>,
|
||||
receiver: mpsc::Receiver<String>,
|
||||
guard: G,
|
||||
) -> impl stream::Stream<Item = Result<Event, std::convert::Infallible>> {
|
||||
let pending: VecDeque<String> = first.into();
|
||||
stream::unfold(
|
||||
(pending, receiver, guard),
|
||||
|(mut pending, mut receiver, guard)| async move {
|
||||
loop {
|
||||
if let Some(frame) = pending.pop_front() {
|
||||
return Some((Ok(Event::default().data(frame)), (pending, receiver, guard)));
|
||||
}
|
||||
let frame = receiver.recv().await?;
|
||||
pending.push_back(frame);
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "signals_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,411 @@
|
||||
//! Unit oracles of the Story 3.19 signal seam: the catalog projection, the bounded filter, the exact
|
||||
//! wire frames of both approved revisions and the bounded legacy stream ownership.
|
||||
|
||||
use std::{
|
||||
io,
|
||||
sync::{Arc, Mutex},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use crank_core::ToolSelectionPolicy;
|
||||
use crank_core::ids::{PromptId, ResourceId};
|
||||
use crank_registry::PublishedAgentCatalog;
|
||||
use crank_registry::model::{AgentPromptBinding, AgentResourceBinding};
|
||||
use serde_json::{Value, json};
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
use super::{
|
||||
CatalogFingerprint, FilterOutcome, INVALID_LISTEN_FILTER, ListenFilter, MAX_FILTER_URIS,
|
||||
MAX_SUBSCRIPTION_ID_BYTES, PROMPT_LIST_CHANGED, RESOURCE_LIST_CHANGED, ReadError, Reader,
|
||||
SIGNAL_QUEUE_CAPACITY, SUBSCRIPTION_ID_KEY, SUBSCRIPTIONS_ACKNOWLEDGED, Signals,
|
||||
StreamRegistry, Watch, Wire, acknowledged_frame, run, subscription_id,
|
||||
};
|
||||
|
||||
fn catalog(
|
||||
resources: &[(&str, u32)],
|
||||
prompts: &[(&str, u32)],
|
||||
catalog_revision: &str,
|
||||
) -> PublishedAgentCatalog {
|
||||
PublishedAgentCatalog {
|
||||
agent_version: 1,
|
||||
catalog_revision: catalog_revision.to_owned(),
|
||||
tool_selection_policy: ToolSelectionPolicy::default(),
|
||||
tools: Vec::new(),
|
||||
resources: resources
|
||||
.iter()
|
||||
.map(|(id, version)| AgentResourceBinding {
|
||||
resource_id: ResourceId::new(*id),
|
||||
resource_version: *version,
|
||||
})
|
||||
.collect(),
|
||||
prompts: prompts
|
||||
.iter()
|
||||
.map(|(id, version)| AgentPromptBinding {
|
||||
prompt_id: PromptId::new(*id),
|
||||
prompt_version: *version,
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_committed_resource_binding_is_a_resource_change_only() {
|
||||
let before = CatalogFingerprint::of(&catalog(&[("res_a", 1)], &[("prm_a", 1)], "rev-1"));
|
||||
let after = CatalogFingerprint::of(&catalog(
|
||||
&[("res_a", 1), ("res_b", 1)],
|
||||
&[("prm_a", 1)],
|
||||
"rev-2",
|
||||
));
|
||||
|
||||
assert_eq!(
|
||||
after.changes_since(&before),
|
||||
Signals {
|
||||
resources: true,
|
||||
prompts: false
|
||||
}
|
||||
);
|
||||
assert!(!before.changes_since(&after).prompts);
|
||||
assert_eq!(
|
||||
before.changes_since(&after),
|
||||
Signals {
|
||||
resources: true,
|
||||
prompts: false
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_committed_prompt_binding_is_a_prompt_change_only() {
|
||||
let before = CatalogFingerprint::of(&catalog(&[], &[("prm_a", 1)], "rev-1"));
|
||||
let after = CatalogFingerprint::of(&catalog(&[], &[("prm_a", 1), ("prm_b", 2)], "rev-2"));
|
||||
|
||||
assert_eq!(
|
||||
after.changes_since(&before),
|
||||
Signals {
|
||||
resources: false,
|
||||
prompts: true
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pinned_version_bump_is_a_change_even_when_the_binding_names_are_stable() {
|
||||
let before = CatalogFingerprint::of(&catalog(&[("res_a", 1)], &[("prm_a", 1)], "rev-1"));
|
||||
let after = CatalogFingerprint::of(&catalog(&[("res_a", 2)], &[("prm_a", 1)], "rev-1"));
|
||||
|
||||
assert_eq!(
|
||||
after.changes_since(&before),
|
||||
Signals {
|
||||
resources: true,
|
||||
prompts: false
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tool_only_catalog_commit_is_silent() {
|
||||
// `catalog_revision` moved, but the visible Resource/Prompt projection did not: a Tool-only
|
||||
// commit must not produce a Resource or Prompt list-change signal.
|
||||
let before = CatalogFingerprint::of(&catalog(&[("res_a", 1)], &[("prm_a", 1)], "rev-1"));
|
||||
let after = CatalogFingerprint::of(&catalog(&[("res_a", 1)], &[("prm_a", 1)], "rev-2"));
|
||||
|
||||
assert!(!after.changes_since(&before).any());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_projection_is_order_independent_and_has_no_duplicate_growth() {
|
||||
let forward = CatalogFingerprint::of(&catalog(
|
||||
&[("res_a", 1), ("res_b", 2)],
|
||||
&[("prm_a", 1), ("prm_b", 2)],
|
||||
"rev-1",
|
||||
));
|
||||
let reversed = CatalogFingerprint::of(&catalog(
|
||||
&[("res_b", 2), ("res_a", 1)],
|
||||
&[("prm_b", 2), ("prm_a", 1)],
|
||||
"rev-1",
|
||||
));
|
||||
|
||||
assert!(!reversed.changes_since(&forward).any());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_legacy_frames_carry_a_closed_method_name_and_no_parameters() {
|
||||
let frames = Wire::Legacy.signal_frames(Signals::BOTH);
|
||||
|
||||
assert_eq!(
|
||||
frames,
|
||||
vec![
|
||||
json!({"jsonrpc": "2.0", "method": RESOURCE_LIST_CHANGED}).to_string(),
|
||||
json!({"jsonrpc": "2.0", "method": PROMPT_LIST_CHANGED}).to_string(),
|
||||
]
|
||||
);
|
||||
// No URI, name or payload of a changed object is part of a list-change notification.
|
||||
assert!(frames.iter().all(|frame| !frame.contains("uri")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_modern_frames_carry_the_subscription_id_of_their_listen_request() {
|
||||
let id = json!(41);
|
||||
let frames = Wire::Modern(id.clone()).signal_frames(Signals::BOTH);
|
||||
|
||||
assert_eq!(
|
||||
frames,
|
||||
vec![
|
||||
json!({
|
||||
"jsonrpc": "2.0",
|
||||
"method": RESOURCE_LIST_CHANGED,
|
||||
"params": { "_meta": { SUBSCRIPTION_ID_KEY: 41 } }
|
||||
})
|
||||
.to_string(),
|
||||
json!({
|
||||
"jsonrpc": "2.0",
|
||||
"method": PROMPT_LIST_CHANGED,
|
||||
"params": { "_meta": { SUBSCRIPTION_ID_KEY: 41 } }
|
||||
})
|
||||
.to_string(),
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::from_str::<Value>(&frames[0]).unwrap()["params"]["_meta"][SUBSCRIPTION_ID_KEY],
|
||||
id
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_requested_and_honoured_types_are_encoded() {
|
||||
let frames = Wire::Modern(json!(1)).signal_frames(Signals {
|
||||
resources: false,
|
||||
prompts: true,
|
||||
});
|
||||
|
||||
assert_eq!(frames.len(), 1);
|
||||
assert!(frames[0].contains(PROMPT_LIST_CHANGED));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_acknowledgment_reports_exactly_the_honoured_subset() {
|
||||
let frame: Value = serde_json::from_str(&acknowledged_frame(
|
||||
&json!(7),
|
||||
Signals {
|
||||
resources: true,
|
||||
prompts: false,
|
||||
},
|
||||
))
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(frame["method"], SUBSCRIPTIONS_ACKNOWLEDGED);
|
||||
assert_eq!(frame["params"]["_meta"][SUBSCRIPTION_ID_KEY], json!(7));
|
||||
assert_eq!(
|
||||
frame["params"]["notifications"],
|
||||
json!({ "resourcesListChanged": true })
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_honoured_subset_is_an_empty_filter_object() {
|
||||
let frame: Value =
|
||||
serde_json::from_str(&acknowledged_frame(&json!("sub-1"), Signals::default())).unwrap();
|
||||
|
||||
assert_eq!(frame["params"]["notifications"], json!({}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_filter_keeps_only_the_implemented_list_change_types() {
|
||||
let filter: ListenFilter = serde_json::from_value(json!({
|
||||
"toolsListChanged": true,
|
||||
"promptsListChanged": true,
|
||||
"resourcesListChanged": false,
|
||||
"resourceSubscriptions": ["file:///project/config.json"]
|
||||
}))
|
||||
.unwrap();
|
||||
|
||||
match filter.accepted() {
|
||||
FilterOutcome::Accepted(signals) => assert_eq!(
|
||||
signals,
|
||||
Signals {
|
||||
resources: false,
|
||||
prompts: true
|
||||
}
|
||||
),
|
||||
FilterOutcome::Invalid(detail) => panic!("a bounded filter must be accepted: {detail}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_absent_filter_field_means_not_subscribed() {
|
||||
let filter: ListenFilter = serde_json::from_value(json!({})).unwrap();
|
||||
|
||||
match filter.accepted() {
|
||||
FilterOutcome::Accepted(signals) => assert!(!signals.any()),
|
||||
FilterOutcome::Invalid(detail) => panic!("an empty filter must be accepted: {detail}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_oversized_uri_filter_is_refused_without_echoing_it() {
|
||||
let filter: ListenFilter = serde_json::from_value(json!({
|
||||
"resourceSubscriptions": (0..=MAX_FILTER_URIS)
|
||||
.map(|index| format!("file:///resource-{index}"))
|
||||
.collect::<Vec<_>>()
|
||||
}))
|
||||
.unwrap();
|
||||
|
||||
match filter.accepted() {
|
||||
FilterOutcome::Invalid(detail) => assert_eq!(detail, INVALID_LISTEN_FILTER),
|
||||
FilterOutcome::Accepted(_) => panic!("an oversized filter must be refused"),
|
||||
}
|
||||
|
||||
let oversized: ListenFilter = serde_json::from_value(json!({
|
||||
"resourceSubscriptions": ["u".repeat(super::MAX_FILTER_URI_BYTES + 1)]
|
||||
}))
|
||||
.unwrap();
|
||||
assert!(matches!(
|
||||
oversized.accepted(),
|
||||
FilterOutcome::Invalid(INVALID_LISTEN_FILTER)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_non_object_filter_is_a_deserialization_error() {
|
||||
assert!(serde_json::from_value::<ListenFilter>(json!(["toolsListChanged"])).is_err());
|
||||
assert!(serde_json::from_value::<ListenFilter>(json!({"promptsListChanged": "yes"})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_subscription_id_is_bound_by_its_encoded_size() {
|
||||
assert_eq!(subscription_id(&json!(1)), Some(json!(1)));
|
||||
assert_eq!(subscription_id(&json!("sub-1")), Some(json!("sub-1")));
|
||||
assert_eq!(
|
||||
subscription_id(&json!("x".repeat(MAX_SUBSCRIPTION_ID_BYTES))),
|
||||
None,
|
||||
"an id longer than the frame bound must not be used as a subscription id"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_newer_legacy_stream_supersedes_the_previous_one() {
|
||||
let streams = StreamRegistry::new();
|
||||
let first = streams.admit("session-1").unwrap();
|
||||
let second = streams.admit("session-1").unwrap();
|
||||
|
||||
assert!(!streams.is_current("session-1", first));
|
||||
assert!(streams.is_current("session-1", second));
|
||||
// Another session is unaffected.
|
||||
let other = streams.admit("session-2").unwrap();
|
||||
assert!(streams.is_current("session-2", other));
|
||||
|
||||
streams.retire("session-1");
|
||||
assert!(!streams.is_current("session-1", second));
|
||||
assert!(streams.is_current("session-2", other));
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
struct SharedLogWriter {
|
||||
buffer: Arc<Mutex<Vec<u8>>>,
|
||||
}
|
||||
|
||||
impl SharedLogWriter {
|
||||
fn output(&self) -> String {
|
||||
String::from_utf8(self.buffer.lock().unwrap().clone()).unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for SharedLogWriter {
|
||||
type Writer = SharedLogGuard;
|
||||
|
||||
fn make_writer(&'a self) -> Self::Writer {
|
||||
SharedLogGuard {
|
||||
buffer: Arc::clone(&self.buffer),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct SharedLogGuard {
|
||||
buffer: Arc<Mutex<Vec<u8>>>,
|
||||
}
|
||||
|
||||
impl io::Write for SharedLogGuard {
|
||||
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
|
||||
self.buffer.lock().unwrap().extend_from_slice(bytes);
|
||||
Ok(bytes.len())
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// AC-2: a failed committed-catalog read is observable and loses nothing — the tick is skipped (no
|
||||
/// fabricated signal, no write path that could roll the catalog back) while the baseline survives, so
|
||||
/// the next successful read still reports the change of the committed catalog.
|
||||
#[tokio::test]
|
||||
async fn a_failed_catalog_read_is_observable_and_loses_no_committed_change() {
|
||||
let writer = SharedLogWriter::default();
|
||||
let subscriber = crank_observability::build_subscriber(
|
||||
crank_observability::ObservabilityConfig::new(
|
||||
crank_observability::ServiceIdentity::try_new("mcp-server", "test", "test").unwrap(),
|
||||
"info",
|
||||
crank_observability::RedactionLimits::default(),
|
||||
),
|
||||
writer.clone(),
|
||||
)
|
||||
.unwrap();
|
||||
let dispatch = tracing::Dispatch::new(subscriber);
|
||||
let _guard = tracing::dispatcher::set_default(&dispatch);
|
||||
|
||||
let baseline = CatalogFingerprint::of(&catalog(&[], &[("prm_a", 1)], "rev-1"));
|
||||
let committed = CatalogFingerprint::of(&catalog(&[], &[("prm_a", 1), ("prm_b", 1)], "rev-2"));
|
||||
let script = Arc::new(Mutex::new(
|
||||
vec![Ok(baseline), Err(ReadError::Retry), Ok(committed)].into_iter(),
|
||||
));
|
||||
let reader: Reader = Box::new(move || {
|
||||
let next = script
|
||||
.lock()
|
||||
.unwrap()
|
||||
.next()
|
||||
.unwrap_or(Err(ReadError::Retry));
|
||||
Box::pin(async move { next })
|
||||
});
|
||||
|
||||
let (sender, mut receiver) = mpsc::channel(SIGNAL_QUEUE_CAPACITY);
|
||||
tokio::spawn(run(
|
||||
Watch {
|
||||
workspace_slug: "workspace-canary".to_owned(),
|
||||
agent_slug: "agent-canary".to_owned(),
|
||||
signals: Signals::BOTH,
|
||||
wire: Wire::Legacy,
|
||||
legacy_stream: None,
|
||||
deadline: Some(Instant::now() + Duration::from_millis(2_100)),
|
||||
},
|
||||
sender,
|
||||
reader,
|
||||
));
|
||||
|
||||
let mut frames = Vec::new();
|
||||
while let Some(frame) = receiver.recv().await {
|
||||
frames.push(frame);
|
||||
}
|
||||
|
||||
// The failed tick produced no frame; the committed change of the next successful read did.
|
||||
assert_eq!(
|
||||
frames,
|
||||
vec![json!({"jsonrpc": "2.0", "method": PROMPT_LIST_CHANGED}).to_string()]
|
||||
);
|
||||
|
||||
let output = writer.output();
|
||||
let failures: Vec<Value> = output
|
||||
.lines()
|
||||
.filter_map(|line| serde_json::from_str::<Value>(line).ok())
|
||||
.filter(|event| event["event"] == "mcp.signals.read_failed")
|
||||
.collect();
|
||||
assert!(
|
||||
!failures.is_empty(),
|
||||
"a skipped tick must be observable: {output}"
|
||||
);
|
||||
for event in &failures {
|
||||
assert_eq!(event["fields"]["error_category"], "catalog");
|
||||
}
|
||||
// Closed vocabulary: no workspace, Agent, URI or raw database text is read into the event.
|
||||
assert!(!output.contains("workspace-canary"));
|
||||
assert!(!output.contains("agent-canary"));
|
||||
}
|
||||
@@ -116,6 +116,19 @@ fn accepted_media_types(headers: &HeaderMap) -> Option<Vec<String>> {
|
||||
)
|
||||
}
|
||||
|
||||
/// Whether this request offered `text/event-stream`.
|
||||
///
|
||||
/// Story 3.18: the SSE response stream is the only carrier of a server `notifications/message`, so
|
||||
/// the logging projection asks this before it promises a notification. It is the same admission rule
|
||||
/// the response-mode negotiation already applies, not a second interpretation of the header.
|
||||
pub(super) fn accepts_event_stream(headers: &HeaderMap) -> bool {
|
||||
accepted_media_types(headers).is_some_and(|media_types| {
|
||||
media_types
|
||||
.iter()
|
||||
.any(|media_type| media_type == "text/event-stream")
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn negotiate_post_response_mode(
|
||||
headers: &HeaderMap,
|
||||
) -> Result<ResponseMode, StatusCode> {
|
||||
@@ -266,8 +279,26 @@ pub(super) fn transport_response(
|
||||
protocol_version: Option<&str>,
|
||||
) -> Response {
|
||||
let outcome = payload_outcome(&payload);
|
||||
// Story 3.18: this is the single projection point of the adapter's own safe structured event.
|
||||
// The severity is derived from the already-decided outcome of the payload, so no request payload,
|
||||
// credential, error cause or user value is read here.
|
||||
note_logging_outcome(&payload);
|
||||
let notifications = crate::protocol::take_notifications();
|
||||
// A pending `notifications/message` has no carrier in a JSON body. When the client offered both
|
||||
// media types and opted in to logging, the negotiated mode is the SSE stream, so the notification
|
||||
// precedes the response instead of being silently dropped.
|
||||
let response_mode = if notifications.is_empty() {
|
||||
response_mode
|
||||
} else {
|
||||
ResponseMode::Sse
|
||||
};
|
||||
if status == StatusCode::OK && matches!(response_mode, ResponseMode::Sse) {
|
||||
let stream = stream::iter([Ok(Event::default().data(payload.to_string()))]);
|
||||
let mut messages = Vec::with_capacity(notifications.len() + 1);
|
||||
for notification in notifications {
|
||||
messages.push(Ok(Event::default().data(notification.to_string())));
|
||||
}
|
||||
messages.push(Ok(Event::default().data(payload.to_string())));
|
||||
let stream = stream::iter(messages);
|
||||
|
||||
let mut response = sse_response(status, stream, session_id, protocol_version);
|
||||
if let Some(outcome) = outcome {
|
||||
@@ -279,6 +310,33 @@ pub(super) fn transport_response(
|
||||
json_response(status, payload, session_id, protocol_version)
|
||||
}
|
||||
|
||||
/// Record the closed safe event of one response: served, rejected as invalid, failed, or a tool-level
|
||||
/// error. Every label is a fixed string of the closed vocabulary; nothing from the payload or the
|
||||
/// request is copied into it.
|
||||
fn note_logging_outcome(payload: &Value) {
|
||||
use crate::protocol::{EVENT_FAILED, EVENT_REJECTED, EVENT_SERVED, LogLevel, note};
|
||||
if payload.get("error").is_some() {
|
||||
match payload.pointer("/error/code").and_then(Value::as_i64) {
|
||||
// The pinned client-error codes: a malformed request, a method that this era does not
|
||||
// implement, and invalid params. The client can correct all three, so they are a
|
||||
// rejection rather than a server failure; the closed label stays the one client-error
|
||||
// label of the vocabulary instead of growing a new one.
|
||||
Some(-32602..=-32600) => note(LogLevel::Warning, EVENT_REJECTED, "invalid_params"),
|
||||
_ => note(LogLevel::Error, EVENT_FAILED, "internal"),
|
||||
}
|
||||
return;
|
||||
}
|
||||
if payload
|
||||
.pointer("/result/isError")
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(false)
|
||||
{
|
||||
note(LogLevel::Warning, EVENT_REJECTED, "tool_error");
|
||||
return;
|
||||
}
|
||||
note(LogLevel::Info, EVENT_SERVED, "ok");
|
||||
}
|
||||
|
||||
fn payload_outcome(payload: &Value) -> Option<McpOutcome> {
|
||||
if payload.get("error").is_some() {
|
||||
return Some(McpOutcome::JsonRpcError);
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
{
|
||||
"kind": "inventory",
|
||||
"path": "docs/capability-inventory.json",
|
||||
"sha256": "96589e25b7a3247f633fba2b031910e2ed4355d9ce8d29c7641638217800de0d"
|
||||
"sha256": "10ca3538aa1b6b25868f80e19932c7ef918398c4817c52bc1aae52f18c31522b"
|
||||
},
|
||||
{
|
||||
"kind": "required_surfaces",
|
||||
|
||||
@@ -884,26 +884,28 @@
|
||||
"surface": "experimental"
|
||||
},
|
||||
{
|
||||
"advertised": null,
|
||||
"advertised": {
|
||||
"logging": {}
|
||||
},
|
||||
"applicability": "stable",
|
||||
"evidence_target": "logging",
|
||||
"fallback": "capability not advertised, request not dispatched",
|
||||
"kind": "capability",
|
||||
"open_subfeatures": false,
|
||||
"owner": "story 3.18",
|
||||
"owner": "community-release",
|
||||
"per_revision": {
|
||||
"2026-07-28": {
|
||||
"applicability": "deprecated"
|
||||
}
|
||||
},
|
||||
"reason": "safe MCP server logging is owned by story 3.18 (FR-19); the capability is deprecated in the pinned 2026-07-28 revision and remains present in the legacy revision",
|
||||
"reason": "safe MCP server logging is implemented (Story 3.18, FR-19); the capability is deprecated in the pinned 2026-07-28 revision, where the per-request `_meta` log level replaces logging/setLevel, and present in the legacy revision, where logging/setLevel is served",
|
||||
"requirement": "FR-19",
|
||||
"revisions": [
|
||||
"2026-07-28",
|
||||
"2025-11-25"
|
||||
],
|
||||
"role": "server",
|
||||
"status": "deferred",
|
||||
"status": "supported",
|
||||
"subfeatures": [],
|
||||
"surface": "logging"
|
||||
},
|
||||
@@ -930,7 +932,7 @@
|
||||
{
|
||||
"advertised": {
|
||||
"prompts": {
|
||||
"listChanged": false
|
||||
"listChanged": true
|
||||
}
|
||||
},
|
||||
"applicability": "stable",
|
||||
@@ -939,6 +941,7 @@
|
||||
"kind": "capability",
|
||||
"open_subfeatures": false,
|
||||
"owner": "community-release",
|
||||
"reason": "the adapter emits `notifications/prompts/list_changed` from the committed published Prompt bindings of the Agent snapshot since Story 3.19",
|
||||
"requirement": "FR-17",
|
||||
"revisions": [
|
||||
"2026-07-28",
|
||||
@@ -954,7 +957,7 @@
|
||||
{
|
||||
"advertised": {
|
||||
"resources": {
|
||||
"listChanged": false,
|
||||
"listChanged": true,
|
||||
"subscribe": false
|
||||
}
|
||||
},
|
||||
@@ -964,6 +967,7 @@
|
||||
"kind": "capability",
|
||||
"open_subfeatures": false,
|
||||
"owner": "community-release",
|
||||
"reason": "the adapter emits `notifications/resources/list_changed` from the committed published Resource bindings of the Agent snapshot since Story 3.19; URI-content subscriptions remain unimplemented",
|
||||
"requirement": "FR-15",
|
||||
"revisions": [
|
||||
"2026-07-28",
|
||||
@@ -1366,14 +1370,14 @@
|
||||
"fallback": "capability not advertised, request not dispatched",
|
||||
"kind": "method",
|
||||
"open_subfeatures": false,
|
||||
"owner": "story 3.18",
|
||||
"reason": "safe MCP server logging is owned by story 3.18 (FR-19); the pinned modern revision replaces this method with a per-request log level",
|
||||
"owner": "community-release",
|
||||
"reason": "served in the legacy revision by Story 3.18 (FR-19): the level is validated against the pinned LoggingLevel union and recorded for the client session; the pinned modern revision replaces this method with the per-request `_meta` log level, so the same wire name is a wrong-era request there",
|
||||
"requirement": "FR-19",
|
||||
"revisions": [
|
||||
"2025-11-25"
|
||||
],
|
||||
"role": "client",
|
||||
"status": "deferred",
|
||||
"status": "supported",
|
||||
"subfeatures": [],
|
||||
"surface": "logging/setLevel"
|
||||
},
|
||||
@@ -1436,13 +1440,13 @@
|
||||
"kind": "method",
|
||||
"open_subfeatures": false,
|
||||
"owner": "community-release",
|
||||
"reason": "the community scope serves no subscription stream, so the modern listen request is not served",
|
||||
"reason": "served since Story 3.19 (FR-19) as the modern long-lived notification stream; the acknowledged filter carries only the implemented Resource/Prompt list-change types",
|
||||
"requirement": "FR-13",
|
||||
"revisions": [
|
||||
"2026-07-28"
|
||||
],
|
||||
"role": "client",
|
||||
"status": "not_applicable",
|
||||
"status": "supported",
|
||||
"subfeatures": [],
|
||||
"surface": "subscriptions/listen"
|
||||
},
|
||||
@@ -1611,15 +1615,15 @@
|
||||
"fallback": "capability not advertised, request not dispatched",
|
||||
"kind": "notification",
|
||||
"open_subfeatures": false,
|
||||
"owner": "story 3.19",
|
||||
"reason": "Resource and Prompt change signals are owned by story 3.19",
|
||||
"owner": "community-release",
|
||||
"reason": "emitted since Story 3.19 (FR-19) from the committed published Resource bindings of the Agent snapshot; carries no parameters, so no URI, name or content is disclosed",
|
||||
"requirement": "FR-19",
|
||||
"revisions": [
|
||||
"2026-07-28",
|
||||
"2025-11-25"
|
||||
],
|
||||
"role": "server",
|
||||
"status": "deferred",
|
||||
"status": "supported",
|
||||
"subfeatures": [],
|
||||
"surface": "notifications/resources/list_changed"
|
||||
},
|
||||
@@ -1630,15 +1634,15 @@
|
||||
"fallback": "capability not advertised, request not dispatched",
|
||||
"kind": "notification",
|
||||
"open_subfeatures": false,
|
||||
"owner": "story 3.19",
|
||||
"reason": "Resource and Prompt change signals are owned by story 3.19",
|
||||
"owner": "community-release",
|
||||
"reason": "emitted since Story 3.19 (FR-19) from the committed published Prompt bindings of the Agent snapshot; carries no parameters, so no Prompt name or content is disclosed",
|
||||
"requirement": "FR-19",
|
||||
"revisions": [
|
||||
"2026-07-28",
|
||||
"2025-11-25"
|
||||
],
|
||||
"role": "server",
|
||||
"status": "deferred",
|
||||
"status": "supported",
|
||||
"subfeatures": [],
|
||||
"surface": "notifications/prompts/list_changed"
|
||||
},
|
||||
@@ -1692,20 +1696,20 @@
|
||||
"fallback": "capability not advertised, request not dispatched",
|
||||
"kind": "notification",
|
||||
"open_subfeatures": false,
|
||||
"owner": "story 3.18",
|
||||
"owner": "community-release",
|
||||
"per_revision": {
|
||||
"2026-07-28": {
|
||||
"applicability": "deprecated"
|
||||
}
|
||||
},
|
||||
"reason": "safe MCP server logging is owned by story 3.18 (FR-19); the notification is deprecated in the pinned 2026-07-28 revision, where a request opts in per request",
|
||||
"reason": "emitted by the adapter since Story 3.18 (FR-19) from a closed safe vocabulary only; still declared (deprecated) in the pinned 2026-07-28 revision, where a request opts in through `_meta`",
|
||||
"requirement": "FR-19",
|
||||
"revisions": [
|
||||
"2026-07-28",
|
||||
"2025-11-25"
|
||||
],
|
||||
"role": "server",
|
||||
"status": "deferred",
|
||||
"status": "supported",
|
||||
"subfeatures": [],
|
||||
"surface": "notifications/message"
|
||||
},
|
||||
@@ -1717,13 +1721,13 @@
|
||||
"kind": "notification",
|
||||
"open_subfeatures": false,
|
||||
"owner": "community-release",
|
||||
"reason": "the community scope serves no subscription stream",
|
||||
"reason": "sent since Story 3.19 (FR-19) as the first frame of a `subscriptions/listen` stream, carrying the request id as the subscription id and the honoured filter subset",
|
||||
"requirement": "FR-13",
|
||||
"revisions": [
|
||||
"2026-07-28"
|
||||
],
|
||||
"role": "server",
|
||||
"status": "not_applicable",
|
||||
"status": "supported",
|
||||
"subfeatures": [],
|
||||
"surface": "notifications/subscriptions/acknowledged"
|
||||
},
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
# Проверки в CI
|
||||
|
||||
## Уровни
|
||||
|
||||
Обычная story запускает быстрые статические и контрактные проверки затронутого
|
||||
проекта плюс один явный ATDD-вход `scripts/ci-story-checks.sh`. Скрипт содержит
|
||||
короткие команды для принятого восстановительного scope и завершается ошибкой,
|
||||
если команда падает или не выбрала ни одного теста. Story CI не запускает полный
|
||||
Rust workspace, полный pytest, browser E2E, образный smoke или feature matrix.
|
||||
|
||||
Полная проверка фичи запускается при ручном `workflow_dispatch` с
|
||||
`validation_level: feature` или PR с меткой `feature-ready`. Снятие метки,
|
||||
обычный push и обычный PR возвращают CI к уровню story. Стабильный обязательный
|
||||
контекст слияния — `CI / Required Checks`; он всегда проверяет базовые jobs, а
|
||||
feature jobs должны быть `skipped` для story и `success` для feature. Пустой или
|
||||
неизвестный результат считается ошибкой.
|
||||
|
||||
У Crank и FreeHub полный Rust clippy/workspace test и тяжёлые feature/security
|
||||
проверки выполняются только на feature. UI build и быстрые UI unit tests остаются
|
||||
на story, Playwright E2E — на feature. Crank image build/scan/compose smoke — на
|
||||
feature; фактический Deploy остаётся отдельным push-main job со своими build,
|
||||
scan, health и требованием успешного SHA. Тег релиза по умолчанию запускает story
|
||||
ATDD, сборку бинарных/UI артефактов, security audit и image scan. Полный release
|
||||
clippy/workspace/E2E доступен через ручной dispatch с `validation_level: feature`;
|
||||
отчёт evidence прикладывается только если такой E2E был выполнен. FreeHub
|
||||
production CD сохраняет свой exact-SHA CI guard и собственные build/health
|
||||
проверки.
|
||||
|
||||
У Torranslate story запускает один Python 3.14 и принятый целевой pytest файл;
|
||||
feature запускает существующий Python 3.13/3.14 quality matrix и Docker Compose
|
||||
smoke. Никакие workflow этого проекта не меняют Seerr, VPN/DNS или production.
|
||||
|
||||
## Поддержка ATDD-команд
|
||||
|
||||
Перед поставкой Dev и QA обновляют `scripts/ci-story-checks.sh` под story,
|
||||
которая действительно поставляется. DevOps проверяет, что тот же проверяемый
|
||||
коммит содержит актуальную команду. Начальные команды в этих скриптах относятся
|
||||
к принятому recovery scope Crank 3.17, FreeHub 2.13 и Torranslate Phase0 sidecar;
|
||||
они **не подтверждают**, что текущие 3.18, 2.14 или 1.19 уже проверены. Если
|
||||
story требует security или contract regression, добавьте её точечно в тот же
|
||||
вход и зафиксируйте основание в AC/handoff. Не добавляйте динамический selector,
|
||||
список фильтров или общий тестовый framework.
|
||||
|
||||
## Стоимость и доказательства
|
||||
|
||||
Cargo registry/git и npm dependency caches уменьшают повторную загрузку
|
||||
зависимостей. `target` не кешируется: холодная компиляция остаётся затратой и
|
||||
не измерена этим изменением. Не заявляйте экономию времени до сравнения реальных
|
||||
логов. Полный workspace/pytest и feature smoke назначаются для готовой фичи или
|
||||
явного feature dispatch, а не каждой story.
|
||||
Executable
+285
@@ -0,0 +1,285 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Publish immutable Crank release assets to Gitea, safely supporting retries."""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.parse import quote, urlencode, urlsplit
|
||||
from urllib.request import HTTPRedirectHandler, Request, build_opener
|
||||
|
||||
_REPO = re.compile(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+\Z")
|
||||
_TAG = re.compile(r"v[A-Za-z0-9._+-]+\Z")
|
||||
|
||||
|
||||
|
||||
class PublishError(Exception):
|
||||
"""Sanitized release publication failure safe to show in CI logs."""
|
||||
|
||||
|
||||
class _NoRedirect(HTTPRedirectHandler):
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
raise PublishError(
|
||||
f"Gitea API redirected (HTTP {code}); refusing to forward credentials"
|
||||
)
|
||||
|
||||
|
||||
def _inputs(env):
|
||||
raw_base = env.get("GITEA_SERVER_URL", "")
|
||||
parts = urlsplit(raw_base)
|
||||
if (
|
||||
parts.scheme != "https"
|
||||
or not parts.hostname
|
||||
or parts.username
|
||||
or parts.password
|
||||
or parts.query
|
||||
or parts.fragment
|
||||
or parts.path not in ("", "/")
|
||||
):
|
||||
raise PublishError("GITEA_SERVER_URL must be the trusted HTTPS Gitea origin")
|
||||
repo = env.get("GITEA_REPOSITORY", "")
|
||||
if not _REPO.fullmatch(repo):
|
||||
raise PublishError("GITEA_REPOSITORY must be owner/repository")
|
||||
tag = env.get("RELEASE_TAG", "")
|
||||
if not _TAG.fullmatch(tag):
|
||||
raise PublishError("RELEASE_TAG is not a supported version tag")
|
||||
token = env.get("GITEA_TOKEN", "")
|
||||
if (
|
||||
not token
|
||||
or len(token) > 4096
|
||||
or any(ord(char) < 32 or ord(char) == 127 for char in token)
|
||||
):
|
||||
raise PublishError("GITEA_TOKEN is unavailable or has invalid format")
|
||||
origin = f"{parts.scheme}://{parts.netloc}"
|
||||
owner, name = repo.split("/", 1)
|
||||
api = f"{origin}/api/v1/repos/{quote(owner, safe='')}/{quote(name, safe='')}"
|
||||
return origin, api, tag, token
|
||||
|
||||
|
||||
def _json_request(opener, method, url, token, payload=None, allow_404=False):
|
||||
body = None if payload is None else json.dumps(payload).encode("utf-8")
|
||||
headers = {"Authorization": f"token {token}", "Accept": "application/json"}
|
||||
if body is not None:
|
||||
headers["Content-Type"] = "application/json"
|
||||
request = Request(url, data=body, headers=headers, method=method)
|
||||
try:
|
||||
with opener.open(request, timeout=20) as response:
|
||||
return json.loads(response.read()), response.status
|
||||
except PublishError:
|
||||
raise
|
||||
except HTTPError as exc:
|
||||
status = exc.code
|
||||
exc.close()
|
||||
if allow_404 and status == 404:
|
||||
return None, 404
|
||||
raise PublishError(f"Gitea release API request failed (HTTP {status})") from None
|
||||
except (URLError, TimeoutError, OSError):
|
||||
raise PublishError("Gitea release API request failed or timed out") from None
|
||||
except (json.JSONDecodeError, UnicodeDecodeError):
|
||||
raise PublishError("Gitea returned invalid release API data") from None
|
||||
|
||||
|
||||
def _release_id(api, tag, token, opener):
|
||||
tag_path = f"{api}/releases/tags/{quote(tag, safe='')}"
|
||||
release, status = _json_request(opener, "GET", tag_path, token, allow_404=True)
|
||||
if status == 404:
|
||||
release, status = _json_request(
|
||||
opener,
|
||||
"POST",
|
||||
f"{api}/releases",
|
||||
token,
|
||||
payload={
|
||||
"tag_name": tag,
|
||||
"name": f"Crank Community {tag}",
|
||||
"body": "Checksums, evidence, and SBOM are attached to this release.",
|
||||
},
|
||||
)
|
||||
if status not in (200, 201) or not isinstance(release, dict):
|
||||
raise PublishError("Gitea did not return a release record")
|
||||
if release.get("tag_name") != tag:
|
||||
raise PublishError("Gitea returned a release for a different tag")
|
||||
release_id = release.get("id")
|
||||
if not isinstance(release_id, int) or release_id <= 0:
|
||||
raise PublishError("Gitea returned an invalid release identifier")
|
||||
return release_id
|
||||
|
||||
|
||||
def _assets(api, release_id, token, opener):
|
||||
collected = {}
|
||||
page_size = 50
|
||||
max_pages = 20
|
||||
for page_num in range(1, max_pages + 1):
|
||||
url = f"{api}/releases/{release_id}/assets?{urlencode({'page': page_num, 'limit': page_size})}"
|
||||
result, status = _json_request(opener, "GET", url, token)
|
||||
if status != 200 or not isinstance(result, list):
|
||||
raise PublishError("Gitea returned invalid release asset data")
|
||||
for item in result:
|
||||
if (
|
||||
not isinstance(item, dict)
|
||||
or not isinstance(item.get("name"), str)
|
||||
or not isinstance(item.get("id"), int)
|
||||
or not isinstance(item.get("size"), int)
|
||||
or not isinstance(item.get("browser_download_url"), str)
|
||||
):
|
||||
raise PublishError("Gitea returned a malformed release asset")
|
||||
if item["name"] in collected:
|
||||
raise PublishError(
|
||||
f"Gitea returned duplicate release asset name {item['name']}"
|
||||
)
|
||||
collected[item["name"]] = item
|
||||
if len(result) < page_size:
|
||||
return collected
|
||||
raise PublishError("Gitea release asset history exceeded the pagination limit")
|
||||
|
||||
|
||||
def _same_bytes(origin, attachment, local_path, token, opener):
|
||||
download = urlsplit(attachment["browser_download_url"])
|
||||
trusted = urlsplit(origin)
|
||||
if (
|
||||
download.scheme != "https"
|
||||
or download.netloc != trusted.netloc
|
||||
or download.username
|
||||
or download.password
|
||||
or download.fragment
|
||||
):
|
||||
raise PublishError(
|
||||
f"Existing asset {attachment['name']} has an untrusted download URL; refusing to replace it"
|
||||
)
|
||||
expected_size = local_path.stat().st_size
|
||||
if attachment["size"] != expected_size:
|
||||
return False
|
||||
request = Request(
|
||||
attachment["browser_download_url"],
|
||||
headers={"Authorization": f"token {token}"},
|
||||
)
|
||||
try:
|
||||
with opener.open(request, timeout=30) as response:
|
||||
digest = hashlib.sha256()
|
||||
total = 0
|
||||
while True:
|
||||
chunk = response.read(1024 * 1024)
|
||||
if not chunk:
|
||||
break
|
||||
total += len(chunk)
|
||||
if total > expected_size:
|
||||
return False
|
||||
digest.update(chunk)
|
||||
except PublishError:
|
||||
raise
|
||||
except HTTPError as exc:
|
||||
status = exc.code
|
||||
exc.close()
|
||||
if 300 <= status < 400:
|
||||
raise PublishError(
|
||||
f"Existing asset {attachment['name']} redirects; refusing to forward credentials"
|
||||
) from None
|
||||
raise PublishError(
|
||||
f"Could not compare existing release asset (HTTP {status})"
|
||||
) from None
|
||||
except (URLError, TimeoutError, OSError):
|
||||
raise PublishError("Could not download existing release asset for comparison") from None
|
||||
return total == expected_size and digest.digest() == _hash_file(local_path)
|
||||
|
||||
|
||||
def _hash_file(path):
|
||||
digest = hashlib.sha256()
|
||||
with path.open("rb") as source:
|
||||
for chunk in iter(lambda: source.read(1024 * 1024), b""):
|
||||
digest.update(chunk)
|
||||
return digest.digest()
|
||||
|
||||
|
||||
def _curl_config(token):
|
||||
escaped = token.replace("\\", "\\\\").replace('"', '\\"')
|
||||
config = tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", delete=False)
|
||||
try:
|
||||
config.write(f'header = "Authorization: token {escaped}"\n')
|
||||
config.flush()
|
||||
os.chmod(config.name, 0o600)
|
||||
return config.name
|
||||
finally:
|
||||
config.close()
|
||||
|
||||
|
||||
def _upload(api, release_id, path, token):
|
||||
name = path.name
|
||||
url = f"{api}/releases/{release_id}/assets?{urlencode({'name': name})}"
|
||||
auth_config = _curl_config(token)
|
||||
try:
|
||||
result = subprocess.run(
|
||||
[
|
||||
"curl",
|
||||
"--fail",
|
||||
"--silent",
|
||||
"--show-error",
|
||||
"--max-time",
|
||||
"180",
|
||||
"--config",
|
||||
auth_config,
|
||||
"-F",
|
||||
f"attachment=@{path}",
|
||||
url,
|
||||
],
|
||||
check=False,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
text=True,
|
||||
)
|
||||
except OSError:
|
||||
raise PublishError("curl is unavailable for release asset upload") from None
|
||||
finally:
|
||||
Path(auth_config).unlink(missing_ok=True)
|
||||
if result.returncode != 0:
|
||||
raise PublishError(f"Gitea rejected release asset {name} (curl exit {result.returncode})")
|
||||
|
||||
|
||||
def publish(env=None, assets=None, opener=None, upload=_upload):
|
||||
env = os.environ if env is None else env
|
||||
origin, api, tag, token = _inputs(env)
|
||||
if not assets:
|
||||
raise PublishError("No release assets were provided")
|
||||
paths = [Path(item) for item in assets]
|
||||
if any(not path.is_file() for path in paths):
|
||||
raise PublishError("A requested release asset file is missing")
|
||||
names = [path.name for path in paths]
|
||||
if len(names) != len(set(names)):
|
||||
raise PublishError("Release asset names must be unique")
|
||||
opener = opener or build_opener(_NoRedirect())
|
||||
release_id = _release_id(api, tag, token, opener)
|
||||
existing = _assets(api, release_id, token, opener)
|
||||
published = []
|
||||
for path in paths:
|
||||
attachment = existing.get(path.name)
|
||||
if attachment is not None:
|
||||
if not _same_bytes(origin, attachment, path, token, opener):
|
||||
raise PublishError(
|
||||
f"Release asset {path.name} already exists with different bytes; immutable asset left unchanged"
|
||||
)
|
||||
published.append((path.name, "already present with matching bytes"))
|
||||
continue
|
||||
upload(api, release_id, path, token)
|
||||
published.append((path.name, "uploaded"))
|
||||
return {"tag": tag, "release_id": release_id, "assets": published}
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
argv = sys.argv[1:] if argv is None else argv
|
||||
try:
|
||||
result = publish(assets=argv)
|
||||
except PublishError as exc:
|
||||
print(f"Gitea release assets: {exc}", file=sys.stderr)
|
||||
return 1
|
||||
print(f"Gitea release {result['tag']} (id {result['release_id']}):")
|
||||
for name, state in result["assets"]:
|
||||
print(f"{state}: {name}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Executable
+47
@@ -0,0 +1,47 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
active_log=""
|
||||
cleanup() {
|
||||
if [[ -n "$active_log" ]]; then
|
||||
rm -f -- "$active_log"
|
||||
fi
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
run_atdd() {
|
||||
local description="$1"
|
||||
shift
|
||||
active_log="$(mktemp)"
|
||||
if cargo test "$@" >"$active_log" 2>&1; then
|
||||
if ! grep -Eq '^test result: ok\. [1-9][0-9]* passed' "$active_log"; then
|
||||
cat "$active_log" >&2
|
||||
printf 'ATDD command selected zero passing tests: %s\n' "$description" >&2
|
||||
return 1
|
||||
fi
|
||||
grep '^test result:' "$active_log"
|
||||
rm -f -- "$active_log"
|
||||
active_log=""
|
||||
return 0
|
||||
fi
|
||||
cat "$active_log" >&2
|
||||
printf 'ATDD command failed: %s\n' "$description" >&2
|
||||
return 1
|
||||
}
|
||||
|
||||
# Keep Story 3.16 prompt ATDD with Story 3.17 completion and its bound-template regression.
|
||||
run_atdd "MCP prompt composition" -p mcp-server --test integration mcp_prompts::composition -- --test-threads=1
|
||||
run_atdd "MCP completion" -p mcp-server --test integration mcp_completion -- --test-threads=1
|
||||
run_atdd "bound template resources/list regression" -p mcp-server --test integration static_resources::list::list_stays_available_when_a_published_template_is_bound -- --test-threads=1
|
||||
|
||||
# Story 3.18: safe structured logging — the closed level vocabulary, the endpoint ATDD, and the
|
||||
# capability projection the `logging` surface changes.
|
||||
run_atdd "MCP log level vocabulary" -p crank-community-mcp --lib protocol::logging -- --test-threads=1
|
||||
run_atdd "MCP safe logging" -p mcp-server --test integration mcp_logging -- --test-threads=1
|
||||
run_atdd "capability inventory projection" -p mcp-server --test integration inventory_projection -- --test-threads=1
|
||||
|
||||
# Story 3.19 (FR-19): a committed Resource/Prompt catalog change is announced to the client that
|
||||
# asked for the signal, in both revisions, and the authoritative list methods stay the recovery path.
|
||||
# The advertisement projection is already covered by the `inventory_projection` entry above.
|
||||
run_atdd "Resource/Prompt change signals" -p mcp-server --test integration mcp_signals -- --test-threads=1
|
||||
run_atdd "change signal wire oracles" -p crank-community-mcp --lib protocol::signals -- --test-threads=1
|
||||
+1
-1
@@ -1 +1 @@
|
||||
{"completions":{},"prompts":{"listChanged":false},"resources":{"listChanged":false,"subscribe":false},"tools":{"listChanged":false}}
|
||||
{"completions":{},"logging":{},"prompts":{"listChanged":true},"resources":{"listChanged":true,"subscribe":false},"tools":{"listChanged":false}}
|
||||
+6
-1
@@ -1,9 +1,14 @@
|
||||
{
|
||||
"revision": "2025-11-25",
|
||||
"inventory_path": "docs/capability-inventory.json",
|
||||
"inventory_sha256": "96589e25b7a3247f633fba2b031910e2ed4355d9ce8d29c7641638217800de0d",
|
||||
"inventory_sha256": "10ca3538aa1b6b25868f80e19932c7ef918398c4817c52bc1aae52f18c31522b",
|
||||
"rule": "remaining-ac-spec.md#5-server-only-projection-rules-1-4",
|
||||
"projection_inputs": [
|
||||
{
|
||||
"role": "server",
|
||||
"kind": "capability",
|
||||
"surface": "logging"
|
||||
},
|
||||
{
|
||||
"role": "server",
|
||||
"kind": "capability",
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
{"completions":{},"prompts":{"listChanged":false},"resources":{"listChanged":false,"subscribe":false},"tools":{"listChanged":false}}
|
||||
{"completions":{},"logging":{},"prompts":{"listChanged":true},"resources":{"listChanged":true,"subscribe":false},"tools":{"listChanged":false}}
|
||||
+6
-1
@@ -1,9 +1,14 @@
|
||||
{
|
||||
"revision": "2026-07-28",
|
||||
"inventory_path": "docs/capability-inventory.json",
|
||||
"inventory_sha256": "96589e25b7a3247f633fba2b031910e2ed4355d9ce8d29c7641638217800de0d",
|
||||
"inventory_sha256": "10ca3538aa1b6b25868f80e19932c7ef918398c4817c52bc1aae52f18c31522b",
|
||||
"rule": "remaining-ac-spec.md#5-server-only-projection-rules-1-4",
|
||||
"projection_inputs": [
|
||||
{
|
||||
"role": "server",
|
||||
"kind": "capability",
|
||||
"surface": "logging"
|
||||
},
|
||||
{
|
||||
"role": "server",
|
||||
"kind": "capability",
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
{
|
||||
"oracle": "crank-current-scope-advertised-capabilities",
|
||||
"note": "Independent expected projection of the capability descriptor the CURRENT scope is allowed to advertise: advertisement equals what is implemented. Later capabilities are deferred and must not appear until their owning story implements them. This is a scoped projection, not the official MCP capability list.",
|
||||
"expected_keys": ["completions", "prompts", "resources", "tools"],
|
||||
"note": "Independent expected projection of the capability descriptor the CURRENT scope is allowed to advertise: advertisement equals what is implemented. Later capabilities are deferred and must not appear until their owning story implements them. This is a scoped projection, not the official MCP capability list. Story 3.19 implements the Resource/Prompt list-change signals, so both listChanged leaves are advertised; URI-content subscriptions stay unimplemented.",
|
||||
"expected_keys": ["completions", "logging", "prompts", "resources", "tools"],
|
||||
"expected_descriptor": {
|
||||
"completions": {},
|
||||
"logging": {},
|
||||
"prompts": {
|
||||
"listChanged": false
|
||||
"listChanged": true
|
||||
},
|
||||
"resources": {
|
||||
"listChanged": false,
|
||||
"listChanged": true,
|
||||
"subscribe": false
|
||||
},
|
||||
"tools": {
|
||||
@@ -17,8 +18,7 @@
|
||||
},
|
||||
"must_not_be_advertised": ["experimental", "extensions"],
|
||||
"deferred_with_owner": {
|
||||
"change_signals": "story 3.19 (FR-19)",
|
||||
"io.modelcontextprotocol/tasks": "story 4.7",
|
||||
"logging": "story 3.18 (FR-19)"
|
||||
"resource_content_subscriptions": "story 3.19 scope boundary (URI-content subscriptions deferred)",
|
||||
"io.modelcontextprotocol/tasks": "story 4.7"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import tempfile
|
||||
import unittest
|
||||
from importlib.util import module_from_spec, spec_from_file_location
|
||||
from pathlib import Path
|
||||
from urllib.error import HTTPError
|
||||
|
||||
_MODULE_SPEC = spec_from_file_location(
|
||||
"ci_release_assets",
|
||||
Path(__file__).parents[2] / "scripts" / "ci-release-assets.py",
|
||||
)
|
||||
release_assets = module_from_spec(_MODULE_SPEC)
|
||||
_MODULE_SPEC.loader.exec_module(release_assets)
|
||||
|
||||
BASE = {
|
||||
"GITEA_SERVER_URL": "https://git.example.test",
|
||||
"GITEA_REPOSITORY": "team/project",
|
||||
"RELEASE_TAG": "v1.2.3",
|
||||
"GITEA_TOKEN": "gta_test-token",
|
||||
}
|
||||
API = "https://git.example.test/api/v1/repos/team/project"
|
||||
|
||||
|
||||
class Response:
|
||||
def __init__(self, payload=None, body=b"", status=200):
|
||||
self.payload = payload
|
||||
self.body = body
|
||||
self.status = status
|
||||
self.offset = 0
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *_args):
|
||||
return False
|
||||
|
||||
def read(self, size=-1):
|
||||
if self.payload is not None:
|
||||
body = json.dumps(self.payload).encode()
|
||||
else:
|
||||
body = self.body
|
||||
if size < 0:
|
||||
chunk = body[self.offset :]
|
||||
self.offset = len(body)
|
||||
return chunk
|
||||
chunk = body[self.offset : self.offset + size]
|
||||
self.offset += len(chunk)
|
||||
return chunk
|
||||
|
||||
|
||||
class Opener:
|
||||
def __init__(self, results):
|
||||
self.results = list(results)
|
||||
self.requests = []
|
||||
|
||||
def open(self, request, timeout):
|
||||
self.requests.append((request, timeout))
|
||||
if not self.results:
|
||||
raise AssertionError(f"unexpected HTTP request: {request.full_url}")
|
||||
expected_method, expected_fragment, result = self.results.pop(0)
|
||||
self_method = request.get_method()
|
||||
if self_method != expected_method or expected_fragment not in request.full_url:
|
||||
raise AssertionError(
|
||||
f"unexpected request {self_method} {request.full_url}; "
|
||||
f"expected {expected_method} containing {expected_fragment}"
|
||||
)
|
||||
if isinstance(result, BaseException):
|
||||
raise result
|
||||
return result
|
||||
|
||||
|
||||
def api_error(status):
|
||||
return HTTPError("https://git.example.test/api", status, "error", {}, None)
|
||||
|
||||
|
||||
def release_record():
|
||||
return {"id": 17, "tag_name": "v1.2.3"}
|
||||
|
||||
|
||||
def asset_record(name, content, url="https://git.example.test/download/file"):
|
||||
return {"id": 8, "name": name, "size": len(content), "browser_download_url": url}
|
||||
|
||||
|
||||
class ReleaseAssetsTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.path = Path(self.temp.name) / "bundle.tar.gz"
|
||||
self.path.write_bytes(b"expected release bytes")
|
||||
self.uploads = []
|
||||
|
||||
def tearDown(self):
|
||||
self.temp.cleanup()
|
||||
|
||||
def upload(self, api, release_id, path, token):
|
||||
self.uploads.append((api, release_id, path.name, token))
|
||||
|
||||
def test_creates_release_and_uploads_missing_asset(self):
|
||||
opener = Opener(
|
||||
[
|
||||
("GET", "/releases/tags/v1.2.3", api_error(404)),
|
||||
("POST", "/releases", Response(payload=release_record(), status=201)),
|
||||
("GET", "/releases/17/assets", Response(payload=[])),
|
||||
]
|
||||
)
|
||||
result = release_assets.publish(BASE, [str(self.path)], opener, self.upload)
|
||||
self.assertEqual(result["release_id"], 17)
|
||||
self.assertEqual(result["assets"], [("bundle.tar.gz", "uploaded")])
|
||||
self.assertEqual(len(self.uploads), 1)
|
||||
self.assertEqual(opener.requests[1][0].get_method(), "POST")
|
||||
self.assertEqual(opener.requests[1][0].get_header("Authorization"), "token gta_test-token")
|
||||
|
||||
def test_rerun_reuses_tag_release_and_skips_matching_asset_bytes(self):
|
||||
expected = self.path.read_bytes()
|
||||
opener = Opener(
|
||||
[
|
||||
("GET", "/releases/tags/v1.2.3", Response(payload=release_record())),
|
||||
(
|
||||
"GET",
|
||||
"/releases/17/assets",
|
||||
Response(payload=[asset_record(self.path.name, expected)]),
|
||||
),
|
||||
("GET", "/download/file", Response(body=expected)),
|
||||
]
|
||||
)
|
||||
result = release_assets.publish(BASE, [str(self.path)], opener, self.upload)
|
||||
self.assertEqual(result["assets"], [("bundle.tar.gz", "already present with matching bytes")])
|
||||
self.assertEqual(self.uploads, [])
|
||||
self.assertEqual([request.get_method() for request, _ in opener.requests], ["GET", "GET", "GET"])
|
||||
|
||||
def test_partial_retry_skips_matching_asset_and_uploads_only_missing_asset(self):
|
||||
second = Path(self.temp.name) / "checksums.txt"
|
||||
second.write_bytes(b"checksums")
|
||||
opener = Opener(
|
||||
[
|
||||
("GET", "/releases/tags/v1.2.3", Response(payload=release_record())),
|
||||
(
|
||||
"GET",
|
||||
"/releases/17/assets",
|
||||
Response(payload=[asset_record(self.path.name, self.path.read_bytes())]),
|
||||
),
|
||||
("GET", "/download/file", Response(body=self.path.read_bytes())),
|
||||
]
|
||||
)
|
||||
result = release_assets.publish(
|
||||
BASE, [str(self.path), str(second)], opener, self.upload
|
||||
)
|
||||
self.assertEqual(
|
||||
result["assets"],
|
||||
[
|
||||
("bundle.tar.gz", "already present with matching bytes"),
|
||||
("checksums.txt", "uploaded"),
|
||||
],
|
||||
)
|
||||
self.assertEqual(len(self.uploads), 1)
|
||||
self.assertEqual(self.uploads[0][2], "checksums.txt")
|
||||
|
||||
def test_different_existing_asset_is_not_overwritten(self):
|
||||
opener = Opener(
|
||||
[
|
||||
("GET", "/releases/tags/v1.2.3", Response(payload=release_record())),
|
||||
(
|
||||
"GET",
|
||||
"/releases/17/assets",
|
||||
Response(payload=[asset_record(self.path.name, b"x" * self.path.stat().st_size)]),
|
||||
),
|
||||
("GET", "/download/file", Response(body=b"x" * self.path.stat().st_size)),
|
||||
]
|
||||
)
|
||||
with self.assertRaisesRegex(release_assets.PublishError, "different bytes"):
|
||||
release_assets.publish(BASE, [str(self.path)], opener, self.upload)
|
||||
self.assertEqual(self.uploads, [])
|
||||
|
||||
def test_untrusted_existing_asset_url_is_rejected(self):
|
||||
opener = Opener(
|
||||
[
|
||||
("GET", "/releases/tags/v1.2.3", Response(payload=release_record())),
|
||||
(
|
||||
"GET",
|
||||
"/releases/17/assets",
|
||||
Response(
|
||||
payload=[
|
||||
asset_record(
|
||||
self.path.name,
|
||||
self.path.read_bytes(),
|
||||
"https://evil.example/download",
|
||||
)
|
||||
]
|
||||
),
|
||||
),
|
||||
]
|
||||
)
|
||||
with self.assertRaisesRegex(release_assets.PublishError, "untrusted download URL"):
|
||||
release_assets.publish(BASE, [str(self.path)], opener, self.upload)
|
||||
self.assertEqual(self.uploads, [])
|
||||
self.assertEqual(len(opener.requests), 2)
|
||||
|
||||
def test_same_size_different_bytes_fail(self):
|
||||
opener = Opener(
|
||||
[
|
||||
("GET", "/releases/tags/v1.2.3", Response(payload=release_record())),
|
||||
(
|
||||
"GET",
|
||||
"/releases/17/assets",
|
||||
Response(payload=[asset_record(self.path.name, b"x" * self.path.stat().st_size)]),
|
||||
),
|
||||
("GET", "/download/file", Response(body=b"x" * self.path.stat().st_size)),
|
||||
]
|
||||
)
|
||||
with self.assertRaisesRegex(release_assets.PublishError, "different bytes"):
|
||||
release_assets.publish(BASE, [str(self.path)], opener, self.upload)
|
||||
|
||||
def test_redirected_asset_download_fails_without_forwarding_token(self):
|
||||
redirect = HTTPError(
|
||||
"https://git.example.test/download/file",
|
||||
302,
|
||||
"Found",
|
||||
{"Location": "https://evil.example/file"},
|
||||
None,
|
||||
)
|
||||
opener = Opener(
|
||||
[
|
||||
("GET", "/releases/tags/v1.2.3", Response(payload=release_record())),
|
||||
(
|
||||
"GET",
|
||||
"/releases/17/assets",
|
||||
Response(payload=[asset_record(self.path.name, self.path.read_bytes())]),
|
||||
),
|
||||
("GET", "/download/file", redirect),
|
||||
]
|
||||
)
|
||||
with self.assertRaisesRegex(release_assets.PublishError, "redirects"):
|
||||
release_assets.publish(BASE, [str(self.path)], opener, self.upload)
|
||||
download_request = opener.requests[-1][0]
|
||||
self.assertEqual(download_request.get_header("Authorization"), "token gta_test-token")
|
||||
self.assertEqual(self.uploads, [])
|
||||
|
||||
def test_invalid_token_header_characters_are_rejected(self):
|
||||
with self.assertRaisesRegex(release_assets.PublishError, "invalid format"):
|
||||
release_assets.publish({**BASE, "GITEA_TOKEN": "bad\ntoken"}, [str(self.path)], Opener([]), self.upload)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -47,13 +47,14 @@ EXPECTED_FROZEN = (
|
||||
b'{"resources":{"listChanged":false,"subscribe":false},"tools":{"listChanged":false}}'
|
||||
)
|
||||
EXPECTED_SHA256 = "e38c795fc28fee74168cb045427df55d882f8f7ace206af5c9a3ca4df5892c9a"
|
||||
# The canonical inventory implements the completions/prompts/resources/tools surfaces, so the committed
|
||||
# oracle and the canonical projection carry exactly those four; the logging surface is still deferred
|
||||
# to its owning story and must not appear in the advertisement.
|
||||
# The canonical inventory also implements the logging surface (Story 3.18, FR-19) and the
|
||||
# Resource/Prompt list-change signals (Story 3.19, FR-19), so the committed oracle and the canonical
|
||||
# projection carry `logging` next to `completions`/`prompts`/`resources`/`tools`, and both
|
||||
# `listChanged` leaves are now implemented.
|
||||
COMMITTED_FROZEN = (
|
||||
b'{"completions":{},"prompts":{"listChanged":false},"resources":{"listChanged":false,"subscribe":false},"tools":{"listChanged":false}}'
|
||||
b'{"completions":{},"logging":{},"prompts":{"listChanged":true},"resources":{"listChanged":true,"subscribe":false},"tools":{"listChanged":false}}'
|
||||
)
|
||||
COMMITTED_SHA256 = "08c29e3df2bd8ffc58c1ec172714cc06031c5b279ef042940a8591940aca91fe"
|
||||
COMMITTED_SHA256 = "b90b59f32e2e5c43e829b96339b99a52852bc04f48a2ca0ce7e971affa3a878e"
|
||||
|
||||
|
||||
class AdvertisedCapabilitiesProjectionTests(unittest.TestCase):
|
||||
@@ -294,6 +295,7 @@ class AdvertisedCapabilitiesProjectionTests(unittest.TestCase):
|
||||
),
|
||||
[
|
||||
("server", "capability", "completions"),
|
||||
("server", "capability", "logging"),
|
||||
("server", "capability", "prompts"),
|
||||
("server", "capability", "resources"),
|
||||
("server", "capability", "tools"),
|
||||
@@ -332,6 +334,7 @@ class CommittedFrozenOracleTests(unittest.TestCase):
|
||||
),
|
||||
[
|
||||
("server", "capability", "completions"),
|
||||
("server", "capability", "logging"),
|
||||
("server", "capability", "prompts"),
|
||||
("server", "capability", "resources"),
|
||||
("server", "capability", "tools"),
|
||||
|
||||
@@ -1276,9 +1276,9 @@ class Story31FoundationProjectionBoundaryTests(unittest.TestCase):
|
||||
"""
|
||||
|
||||
EXPECTED_FROZEN = (
|
||||
b'{"completions":{},"prompts":{"listChanged":false},"resources":{"listChanged":false,"subscribe":false},"tools":{"listChanged":false}}'
|
||||
b'{"completions":{},"logging":{},"prompts":{"listChanged":true},"resources":{"listChanged":true,"subscribe":false},"tools":{"listChanged":false}}'
|
||||
)
|
||||
EXPECTED_FROZEN_SHA256 = "08c29e3df2bd8ffc58c1ec172714cc06031c5b279ef042940a8591940aca91fe"
|
||||
EXPECTED_FROZEN_SHA256 = "b90b59f32e2e5c43e829b96339b99a52852bc04f48a2ca0ce7e971affa3a878e"
|
||||
|
||||
def test_control_committed_frozen_oracle_is_the_canonical_projection(self) -> None:
|
||||
"""Positive control (existing GREEN, AT-13): the committed frozen bytes are canonical."""
|
||||
|
||||
Reference in new issue
Block a user