From a5c506b642c0f40b90bce0189cd15ae46adf2f5f Mon Sep 17 00:00:00 2001 From: tercel Date: Fri, 27 Nov 2026 11:11:57 +0800 Subject: [PATCH 01/36] chore(release): prepare Surfaces previews for Core alpha.1 Signed-off-by: tercel --- .github/workflows/core-candidate.yml | 368 +++++++++ a2a/conformance/README.md | 2 + .../fixtures/event_subscriber.json | 56 ++ a2a/docs/features/openapi-backend.md | 41 +- a2a/python/CHANGELOG.md | 6 + a2a/python/README.md | 31 + a2a/python/pyproject.toml | 8 +- a2a/python/src/apcore_a2a/__init__.py | 3 + a2a/python/src/apcore_a2a/event_subscriber.py | 68 ++ a2a/python/src/apcore_a2a/openapi_backend.py | 22 +- a2a/python/src/apcore_a2a/server/executor.py | 388 ++++++---- a2a/python/src/apcore_a2a/server/factory.py | 110 ++- .../conformance/test_event_subscriber.py | 170 +++++ a2a/python/tests/server/test_executor.py | 251 ++++++- .../tests/server/test_server_factory.py | 312 +++++++- .../tests/test_openapi_effective_backend.py | 18 + a2a/rust/CHANGELOG.md | 6 + a2a/rust/Cargo.toml | 6 +- a2a/rust/README.md | 27 + a2a/rust/src/event_subscriber.rs | 238 ++++++ a2a/rust/src/lib.rs | 2 + a2a/rust/src/openapi_backend.rs | 34 +- a2a/rust/src/server/executor.rs | 46 +- a2a/rust/src/server/factory.rs | 2 +- a2a/rust/src/server/handlers.rs | 462 ++++++++---- a2a/rust/tests/conformance.rs | 22 +- .../tests/event_subscriber_conformance.rs | 251 +++++++ a2a/rust/tests/integration.rs | 278 ++++++- a2a/rust/tests/openapi_backend_conformance.rs | 54 ++ a2a/rust/tests/store_failures.rs | 122 +++ a2a/typescript/CHANGELOG.md | 6 + a2a/typescript/README.md | 43 ++ a2a/typescript/package.json | 6 +- a2a/typescript/pnpm-lock.yaml | 12 +- a2a/typescript/src/event-subscriber.ts | 107 +++ a2a/typescript/src/index.ts | 4 + a2a/typescript/src/openapi-backend.ts | 35 +- a2a/typescript/src/server/executor.ts | 111 +-- .../conformance/event-subscriber.test.ts | 173 +++++ .../tests/effective-openapi-backend.test.ts | 47 ++ a2a/typescript/tests/server/executor.test.ts | 89 ++- a2a/typescript/tests/server/factory.test.ts | 47 ++ cli/conformance/README.md | 2 + .../fixtures/structured_flags.json | 39 + cli/python/CHANGELOG.md | 6 + cli/python/README.md | 8 + cli/python/pyproject.toml | 6 +- cli/python/src/apcore_cli/cli.py | 94 ++- cli/python/src/apcore_cli/discovery.py | 17 +- cli/python/src/apcore_cli/schema_parser.py | 56 +- .../conformance/test_structured_flags.py | 113 +++ cli/python/tests/test_strict_stream.py | 150 ++++ cli/rust/CHANGELOG.md | 6 + cli/rust/Cargo.lock | 14 +- cli/rust/Cargo.toml | 6 +- cli/rust/README.md | 17 +- cli/rust/src/cli.rs | 184 ++++- cli/rust/src/ref_resolver.rs | 17 +- cli/rust/src/schema_parser.rs | 35 +- .../tests/conformance_structured_flags.rs | 206 +++++ cli/rust/tests/test_cli.rs | 190 +++++ cli/typescript/CHANGELOG.md | 6 + cli/typescript/README.md | 14 + cli/typescript/package.json | 10 +- cli/typescript/pnpm-lock.yaml | 24 +- cli/typescript/src/cli.ts | 2 + cli/typescript/src/discovery.ts | 17 +- cli/typescript/src/error-output.ts | 5 +- cli/typescript/src/main.ts | 73 +- cli/typescript/src/schema-parser.ts | 30 +- cli/typescript/src/strict-stream.ts | 89 +++ .../acl-argument-scoped-approval.test.ts | 17 +- cli/typescript/tests/acl-governance.test.ts | 14 +- cli/typescript/tests/strict-stream.test.ts | 133 ++++ cli/typescript/tests/structured-flags.test.ts | 93 +++ mcp/conformance/fixtures/openapi_backend.json | 67 ++ mcp/docs/features/openapi-backend.md | 26 +- mcp/python/CHANGELOG.md | 6 + mcp/python/pyproject.toml | 8 +- mcp/python/src/apcore_mcp/auth/middleware.py | 6 +- mcp/python/src/apcore_mcp/openapi_backend.py | 26 +- mcp/python/src/apcore_mcp/server/factory.py | 36 +- mcp/python/src/apcore_mcp/server/router.py | 216 ++++-- mcp/python/src/apcore_mcp/server/transport.py | 172 +++-- .../tests/server/test_request_cancellation.py | 269 +++++++ .../server/test_router_stream_completion.py | 227 ++++++ mcp/python/tests/server/test_transport.py | 25 - mcp/python/tests/test_async_serve.py | 38 +- mcp/python/tests/test_logging.py | 30 +- .../tests/test_openapi_backend_conformance.py | 2 + .../tests/test_openapi_effective_backend.py | 18 + mcp/rust/CHANGELOG.md | 6 + mcp/rust/Cargo.toml | 6 +- mcp/rust/README.md | 18 +- mcp/rust/docs/features/transport.md | 16 +- mcp/rust/src/apcore_mcp.rs | 228 +++++- mcp/rust/src/openapi_backend.rs | 48 +- mcp/rust/src/server/router.rs | 456 +++++++---- mcp/rust/src/server/session.rs | 4 + mcp/rust/src/server/transport.rs | 705 ++++++++++++++++-- mcp/rust/tests/openapi_backend_conformance.rs | 5 + .../tests/openapi_backend_option_plumbing.rs | 56 +- mcp/typescript/CHANGELOG.md | 6 + mcp/typescript/README.md | 11 + mcp/typescript/package.json | 6 +- mcp/typescript/pnpm-lock.yaml | 12 +- mcp/typescript/src/openapi-backend.ts | 31 +- mcp/typescript/src/server/router.ts | 171 +++-- mcp/typescript/src/types.ts | 22 + mcp/typescript/tests/cli.test.ts | 22 +- mcp/typescript/tests/config-bus.test.ts | 3 +- .../tests/effective-openapi-backend.test.ts | 47 ++ .../tests/openapi-backend-conformance.test.ts | 4 + .../tests/server/request-cancellation.test.ts | 62 ++ .../tests/server/stream-completion.test.ts | 149 ++++ .../tests/server/test-router-stream.test.ts | 3 +- scripts/verify-rust-core-candidate.py | 99 +++ toolkit/docs/features/output-writers.md | 2 + toolkit/python/CHANGELOG.md | 6 + toolkit/python/README.md | 33 + toolkit/python/pyproject.toml | 4 +- toolkit/python/src/apcore_toolkit/__init__.py | 2 + .../python/src/apcore_toolkit/output/types.py | 3 +- .../src/apcore_toolkit/prometheus_server.py | 83 +++ toolkit/python/tests/test_conformance.py | 28 +- .../python/tests/test_prometheus_server.py | 132 ++++ toolkit/rust/CHANGELOG.md | 6 + toolkit/rust/CLAUDE.md | 8 +- toolkit/rust/Cargo.lock | 51 +- toolkit/rust/Cargo.toml | 22 +- toolkit/rust/README.md | 33 + toolkit/rust/src/lib.rs | 4 + toolkit/rust/src/prometheus_server.rs | 218 ++++++ toolkit/rust/tests/annotation_conformance.rs | 49 +- toolkit/rust/tests/prometheus_server.rs | 145 ++++ toolkit/typescript/CHANGELOG.md | 6 + toolkit/typescript/README.md | 34 + toolkit/typescript/package.json | 4 +- toolkit/typescript/pnpm-lock.yaml | 2 +- toolkit/typescript/src/index.ts | 3 + .../src/output/http-proxy-writer.ts | 7 +- toolkit/typescript/src/prometheus-server.ts | 55 ++ toolkit/typescript/tests/conformance.test.ts | 41 +- .../openapi-effective-parameters.test.ts | 4 +- .../tests/prometheus-server.test.ts | 203 +++++ 145 files changed, 9133 insertions(+), 1200 deletions(-) create mode 100644 .github/workflows/core-candidate.yml create mode 100644 a2a/conformance/fixtures/event_subscriber.json create mode 100644 a2a/python/src/apcore_a2a/event_subscriber.py create mode 100644 a2a/python/tests/conformance/test_event_subscriber.py create mode 100644 a2a/rust/src/event_subscriber.rs create mode 100644 a2a/rust/tests/event_subscriber_conformance.rs create mode 100644 a2a/typescript/src/event-subscriber.ts create mode 100644 a2a/typescript/tests/conformance/event-subscriber.test.ts create mode 100644 cli/conformance/fixtures/structured_flags.json create mode 100644 cli/python/tests/conformance/test_structured_flags.py create mode 100644 cli/python/tests/test_strict_stream.py create mode 100644 cli/rust/tests/conformance_structured_flags.rs create mode 100644 cli/typescript/src/strict-stream.ts create mode 100644 cli/typescript/tests/strict-stream.test.ts create mode 100644 cli/typescript/tests/structured-flags.test.ts create mode 100644 mcp/python/tests/server/test_request_cancellation.py create mode 100644 mcp/python/tests/server/test_router_stream_completion.py create mode 100644 mcp/typescript/tests/server/request-cancellation.test.ts create mode 100644 mcp/typescript/tests/server/stream-completion.test.ts create mode 100644 scripts/verify-rust-core-candidate.py create mode 100644 toolkit/python/src/apcore_toolkit/prometheus_server.py create mode 100644 toolkit/python/tests/test_prometheus_server.py create mode 100644 toolkit/rust/src/prometheus_server.rs create mode 100644 toolkit/rust/tests/prometheus_server.rs create mode 100644 toolkit/typescript/src/prometheus-server.ts create mode 100644 toolkit/typescript/tests/prometheus-server.test.ts diff --git a/.github/workflows/core-candidate.yml b/.github/workflows/core-candidate.yml new file mode 100644 index 00000000..38614fbc --- /dev/null +++ b/.github/workflows/core-candidate.yml @@ -0,0 +1,368 @@ +name: Core candidate compatibility + +on: + workflow_dispatch: + inputs: + core_run_id: + description: Successful APCore Core distribution verification run ID + required: true + type: string + rust_sha256: + description: Expected SHA-256 of the Rust candidate crate, when supplied + required: false + type: string + python_sha256: + description: Expected SHA-256 of the Python wheel, when supplied + required: false + type: string + npm_sha256: + description: Expected SHA-256 of the Node tarball, when supplied + required: false + type: string + +permissions: + contents: read + +jobs: + verify-source: + runs-on: ubuntu-latest + outputs: + head_sha: ${{ steps.source.outputs.head_sha }} + steps: + - name: Verify the upstream package run + id: source + shell: bash + env: + CORE_RUN_ID: ${{ inputs.core_run_id }} + GH_TOKEN: ${{ secrets.APCORE_ARTIFACT_READ_TOKEN }} + run: | + if [[ ! "$CORE_RUN_ID" =~ ^[0-9]+$ ]]; then + echo "core_run_id must be a numeric APCore workflow run ID." >&2 + exit 1 + fi + if [[ -z "$GH_TOKEN" ]]; then + echo "Set APCORE_ARTIFACT_READ_TOKEN with Actions read access to aiperceivable/apcore." >&2 + exit 1 + fi + run=$(gh api "repos/aiperceivable/apcore/actions/runs/$CORE_RUN_ID") + if ! head_sha=$(jq -er ' + select( + .conclusion == "success" and + .path == ".github/workflows/packages.yml" and + .head_repository.full_name == "aiperceivable/apcore" and + (.event == "push" or .event == "workflow_dispatch") + ) | .head_sha | select(test("^[0-9a-f]{40}$")) + ' <<< "$run"); then + echo "Choose a successful push or manual Core distribution verification run from aiperceivable/apcore." >&2 + exit 1 + fi + printf 'head_sha=%s\n' "$head_sha" >> "$GITHUB_OUTPUT" + printf 'APCore package run %s at %s\n' "$CORE_RUN_ID" "$head_sha" + + python: + name: Python / ${{ matrix.component }} / ${{ matrix.core }} + needs: verify-source + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + component: [toolkit, mcp, a2a, cli] + core: [minimum, candidate] + defaults: + run: + working-directory: ${{ matrix.component }}/python + env: + CORE_MODE: ${{ matrix.core }} + COMPONENT: ${{ matrix.component }} + CORE_HEAD_SHA: ${{ needs.verify-source.outputs.head_sha }} + APCORE_A2A_REQUIRE_RELIABLE_DELIVERY: ${{ matrix.core == 'candidate' && '1' || '0' }} + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 + with: + persist-credentials: false + - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 + with: + python-version: '3.12' + - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + if: matrix.core == 'candidate' + with: + repository: aiperceivable/apcore + run-id: ${{ inputs.core_run_id }} + github-token: ${{ secrets.APCORE_ARTIFACT_READ_TOKEN }} + name: core-python-distributions + path: ${{ runner.temp }}/apcore-wheel + - name: Install and verify the selected Core and local Toolkit + shell: bash + env: + EXPECTED_SHA256: ${{ inputs.python_sha256 }} + run: | + core="apcore==0.33.0" + if [[ "$CORE_MODE" == candidate ]]; then + shopt -s nullglob + wheels=("$RUNNER_TEMP"/apcore-wheel/apcore-*.whl) + if (( ${#wheels[@]} != 1 )); then + echo "Expected exactly one APCore wheel." >&2 + exit 1 + fi + core="${wheels[0]}" + digest=$(sha256sum "$core" | cut -d ' ' -f 1) + printf 'APCore %s wheel SHA-256 %s %s\n' "$CORE_HEAD_SHA" "$digest" "$core" + expected=$(printf '%s' "$EXPECTED_SHA256" | tr '[:upper:]' '[:lower:]') + if [[ -n "$expected" && "$digest" != "$expected" ]]; then + echo "The APCore wheel SHA-256 differs from the expected digest." >&2 + exit 1 + fi + fi + args=(-e '.[dev]') + if [[ "$COMPONENT" != toolkit ]]; then + args+=(-e "$GITHUB_WORKSPACE/toolkit/python[http-proxy]") + fi + if [[ "$COMPONENT" == a2a ]]; then + args+=(aiohttp) + fi + if [[ -f constraints.txt ]]; then + args+=(-c constraints.txt) + fi + python -m pip install "$core" "${args[@]}" + python -m pip check + CORE_INSTALL="$core" python - <<'PY' + import json + import os + from importlib.metadata import distribution, version + from pathlib import Path + + import apcore + import apcore_toolkit + from apcore import APCore, Executor + from apcore.events import CircuitBreakerWrapper + + installed = distribution("apcore") + core_path = Path(apcore.__file__).resolve() + toolkit_path = Path(apcore_toolkit.__file__).resolve() + toolkit_expected = Path(os.environ["GITHUB_WORKSPACE"]) / "toolkit/python/src/apcore_toolkit/__init__.py" + print(f"apcore {installed.version} {core_path}") + print(f"apcore-toolkit {version('apcore-toolkit')} {toolkit_path}") + assert core_path == installed.locate_file("apcore/__init__.py").resolve() + assert toolkit_path == toolkit_expected.resolve() + if os.environ["CORE_MODE"] == "candidate": + assert installed.version == "1.0.0a1" + origin = json.loads(installed.read_text("direct_url.json") or "{}") + assert origin.get("url") == Path(os.environ["CORE_INSTALL"]).resolve().as_uri() + assert callable(getattr(Executor, "stream_with_completion", None)) + assert callable(getattr(APCore, "stream_with_completion", None)) + assert hasattr(CircuitBreakerWrapper, "retry") + else: + assert installed.version == "0.33.0" + PY + - run: ruff check src/ tests/ + - run: python -m pytest + - name: Build and install the MCP wheel for the Golden Path + if: matrix.component == 'mcp' && matrix.core == 'candidate' + run: | + python -m pip install build + python -m build --wheel --outdir "$RUNNER_TEMP/surface-wheel" + python -m pip install --force-reinstall --no-deps "$RUNNER_TEMP"/surface-wheel/*.whl + python -m pip check + - name: Check out the verified Core source + if: matrix.component == 'mcp' && matrix.core == 'candidate' + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 + with: + repository: aiperceivable/apcore + ref: ${{ needs.verify-source.outputs.head_sha }} + path: core-source + persist-credentials: false + - name: Verify the Python Golden Path with the installed packages + if: matrix.component == 'mcp' && matrix.core == 'candidate' + working-directory: core-source/examples/python/golden-path + run: python verify.py + + typescript: + name: TypeScript / ${{ matrix.component }} / ${{ matrix.core }} + needs: verify-source + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + component: [toolkit, mcp, a2a, cli] + core: [minimum, candidate] + defaults: + run: + working-directory: ${{ matrix.component }}/typescript + env: + CORE_MODE: ${{ matrix.core }} + COMPONENT: ${{ matrix.component }} + CORE_HEAD_SHA: ${{ needs.verify-source.outputs.head_sha }} + APCORE_A2A_REQUIRE_RELIABLE_DELIVERY: ${{ matrix.core == 'candidate' && '1' || '0' }} + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 + with: + persist-credentials: false + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 + with: + node-version: '22' + - uses: pnpm/action-setup@b906affcce14559ad1aafd4ab0e942779e9f58b1 # v4 + with: + version: '10.30.1' + - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + if: matrix.core == 'candidate' + with: + repository: aiperceivable/apcore + run-id: ${{ inputs.core_run_id }} + github-token: ${{ secrets.APCORE_ARTIFACT_READ_TOKEN }} + name: core-npm-distribution + path: ${{ runner.temp }}/apcore-npm + - name: Build with the selected Core and local Toolkit + shell: bash + env: + EXPECTED_SHA256: ${{ inputs.npm_sha256 }} + run: | + toolkit="$GITHUB_WORKSPACE/toolkit/typescript" + roots=("$PWD") + if [[ "$COMPONENT" == toolkit ]]; then + pnpm install --frozen-lockfile + else + pnpm --dir "$toolkit" install --frozen-lockfile + # The release lock refers to the registry package. Test the candidate + # sources before that package is published by using a local override. + TOOLKIT="$toolkit" node --input-type=module <<'JS' + import { readFileSync, writeFileSync } from 'node:fs'; + + const file = 'package.json'; + const manifest = JSON.parse(readFileSync(file, 'utf8')); + manifest.pnpm ??= {}; + manifest.pnpm.overrides ??= {}; + manifest.pnpm.overrides['apcore-toolkit'] = 'link:' + process.env.TOOLKIT; + writeFileSync(file, JSON.stringify(manifest, null, 2) + '\n'); + JS + pnpm install --no-frozen-lockfile + roots+=("$toolkit") + fi + core_package="apcore-js@0.33.0" + if [[ "$CORE_MODE" == candidate ]]; then + shopt -s nullglob + archives=("$RUNNER_TEMP"/apcore-npm/apcore-js-*.tgz) + if (( ${#archives[@]} != 1 )); then + echo "Expected exactly one APCore npm archive." >&2 + exit 1 + fi + archive="${archives[0]}" + digest=$(sha256sum "$archive" | cut -d ' ' -f 1) + printf 'APCore %s npm SHA-256 %s %s\n' "$CORE_HEAD_SHA" "$digest" "$archive" + expected=$(printf '%s' "$EXPECTED_SHA256" | tr '[:upper:]' '[:lower:]') + if [[ -n "$expected" && "$digest" != "$expected" ]]; then + echo "The APCore npm SHA-256 differs from the expected digest." >&2 + exit 1 + fi + core_package="$archive" + fi + installed=$(mktemp -d) + npm install --prefix "$installed" --ignore-scripts --no-save --no-package-lock --no-audit --no-fund "$core_package" + core_root="$installed/node_modules/apcore-js" + for root in "${roots[@]}"; do + rm -f "$root/node_modules/apcore-js" + ln -s "$core_root" "$root/node_modules/apcore-js" + done + if [[ "$COMPONENT" != toolkit ]]; then + pnpm --dir "$toolkit" build + fi + pnpm build + for root in "${roots[@]}"; do + ( + cd "$root" + CORE_ROOT="$core_root" TOOLKIT_ROOT="$toolkit" node --input-type=module <<'JS' + import assert from 'node:assert/strict'; + import { readFileSync, realpathSync } from 'node:fs'; + import { resolve, sep } from 'node:path'; + import { fileURLToPath } from 'node:url'; + import { APCore, Executor } from 'apcore-js'; + + const core = realpathSync('./node_modules/apcore-js'); + const coreEntry = realpathSync(fileURLToPath(import.meta.resolve('apcore-js'))); + const toolkitEntry = realpathSync(fileURLToPath(import.meta.resolve('apcore-toolkit'))); + const coreVersion = JSON.parse(readFileSync(resolve(core, 'package.json'), 'utf8')).version; + const toolkitVersion = JSON.parse(readFileSync(resolve(process.env.TOOLKIT_ROOT, 'package.json'), 'utf8')).version; + console.log(`apcore-js ${coreVersion} ${coreEntry}`); + console.log(`apcore-toolkit ${toolkitVersion} ${toolkitEntry}`); + assert.equal(core, realpathSync(process.env.CORE_ROOT)); + assert.ok(coreEntry.startsWith(core + sep)); + assert.equal(toolkitEntry, realpathSync(resolve(process.env.TOOLKIT_ROOT, 'dist/index.js'))); + if (process.env.CORE_MODE === 'candidate') { + assert.equal(coreVersion, '1.0.0-alpha.1'); + assert.equal(typeof Executor.prototype.streamWithCompletion, 'function'); + assert.equal(typeof APCore.prototype.streamWithCompletion, 'function'); + } else { + assert.equal(coreVersion, '0.33.0'); + } + JS + ) + done + - run: pnpm lint + if: matrix.component != 'toolkit' + - run: pnpm typecheck + - run: pnpm test + + rust: + name: Rust / ${{ matrix.component }} / ${{ matrix.core }} + needs: verify-source + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + component: [toolkit, mcp, a2a, cli] + core: [minimum, candidate] + # For C2-required packages, the first alpha is both the minimum and + # the current candidate. The candidate entry covers both. + exclude: + - component: mcp + core: minimum + - component: cli + core: minimum + env: + CORE_MODE: ${{ matrix.core }} + COMPONENT: ${{ matrix.component }} + APCORE_A2A_REQUIRE_RELIABLE_DELIVERY: ${{ matrix.core == 'candidate' && '1' || '0' }} + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 + with: + persist-credentials: false + - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 + with: + python-version: '3.12' + - uses: dtolnay/rust-toolchain@df2a88e9fe4098bad09cb42c3dec7187f15861fc + with: + toolchain: stable + - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + if: matrix.core == 'candidate' + with: + repository: aiperceivable/apcore + run-id: ${{ inputs.core_run_id }} + github-token: ${{ secrets.APCORE_ARTIFACT_READ_TOKEN }} + name: core-rust-distribution + path: ${{ runner.temp }}/apcore-crate + - name: Verify resolution and run real Executor tests + shell: bash + env: + EXPECTED_SHA256: ${{ inputs.rust_sha256 }} + run: | + if [[ "$CORE_MODE" == minimum ]]; then + python scripts/verify-rust-core-candidate.py "$COMPONENT" 0.33.0 + exit 0 + fi + shopt -s nullglob + crates=("$RUNNER_TEMP"/apcore-crate/apcore-*.crate) + if (( ${#crates[@]} != 1 )); then + echo "Expected exactly one APCore crate." >&2 + exit 1 + fi + crate="${crates[0]}" + version="${crate##*/apcore-}" + version="${version%.crate}" + if [[ "$version" != 1.0.0-alpha.1 ]]; then + echo "Expected the alpha.1 Core crate." >&2 + exit 1 + fi + if [[ "$CORE_MODE" == candidate && -n "$EXPECTED_SHA256" ]]; then + digest=$(sha256sum "$crate" | cut -d ' ' -f 1) + [[ "$digest" == "${EXPECTED_SHA256,,}" ]] + fi + python scripts/verify-rust-core-candidate.py "$COMPONENT" "$version" --archive "$crate" diff --git a/a2a/conformance/README.md b/a2a/conformance/README.md index 0711024c..bd7a3a3a 100644 --- a/a2a/conformance/README.md +++ b/a2a/conformance/README.md @@ -48,6 +48,8 @@ every SDK's conformance runner. | `fixtures/part_conversion.json` | A-PART | A2A `Part` ⇄ module input/output conversion | | `fixtures/openapi_backend.json` | A-OAS | OpenAPI backend (feature F-12), contract 2.0 (apcore-toolkit >= 0.13.0): registered IDs are the scanner's own, illegal IDs skipped with a warning, the empty-description repair and its report, the path-typed `spec` key, the unapproved-write warning, the collision preflight, public-card exposure | +The separate [event subscriber fixture](fixtures/event_subscriber.json) checks the opt-in A2A event POST transport through the Core subscriber factory and a local HTTP receiver. The cases cover configuration, single delivery, headers, retries, timeouts, circuit breaking, dead letters and filter delegation. + ### JSON-RPC Error Code Table | Code | A2A meaning | apcore source exception | diff --git a/a2a/conformance/fixtures/event_subscriber.json b/a2a/conformance/fixtures/event_subscriber.json new file mode 100644 index 00000000..33a55c25 --- /dev/null +++ b/a2a/conformance/fixtures/event_subscriber.json @@ -0,0 +1,56 @@ +{ + "description": "A2A event delivery through the Core subscriber factory", + "contract_version": "1.0", + "event": { + "event_type": "example.updated", + "module_id": "example.module", + "timestamp": "2026-01-01T00:00:00+00:00", + "severity": "info", + "data": { "value": 42 } + }, + "test_cases": [ + { + "id": "bearer_success", + "subscriber": { "type": "a2a", "auth": "test-token" }, + "status": 204, + "expected": { "requests": 1, "authorization": "Bearer test-token", "skill_id": "apevo.event_receiver", "dead_letters": 0, "circuit_opened": 0 } + }, + { + "id": "headers_permanent_failure", + "subscriber": { "type": "a2a", "auth": { "Authorization": "Basic test", "X-Source": "test" }, "skill_id": "example.receiver" }, + "status": 403, + "expected": { "requests": 1, "authorization": "Basic test", "source": "test", "skill_id": "example.receiver", "dead_letters": 0, "circuit_opened": 0 } + }, + { + "id": "transient_failure", + "subscriber": { "type": "a2a", "retry": { "max_attempts": 2, "initial_backoff_ms": 1 } }, + "status": 503, + "expected": { "requests": 2, "skill_id": "apevo.event_receiver", "dead_letters": 1, "circuit_opened": 0 } + }, + { + "id": "circuit_breaker", + "subscriber": { "type": "a2a", "retry": { "max_attempts": 3, "initial_backoff_ms": 1 }, "circuit_breaker": { "open_threshold": 1 } }, + "status": 503, + "expected": { "requests": 1, "skill_id": "apevo.event_receiver", "dead_letters": 1, "circuit_opened": 1 } + }, + { + "id": "timeout", + "subscriber": { "type": "a2a", "timeout_ms": 200, "retry": { "max_attempts": 1 } }, + "status": 204, + "delay_ms": 900, + "expected": { "requests": 1, "skill_id": "apevo.event_receiver", "dead_letters": 1, "circuit_opened": 0 } + }, + { + "id": "filtered_out", + "subscriber": { "type": "filter", "delegate_type": "a2a", "include_events": ["other.*"] }, + "status": 204, + "expected": { "requests": 0, "dead_letters": 0, "circuit_opened": 0 } + }, + { + "id": "filter_delegates_once", + "subscriber": { "type": "filter", "delegate_type": "a2a", "include_events": ["example.*"] }, + "status": 204, + "expected": { "requests": 1, "skill_id": "apevo.event_receiver", "dead_letters": 0, "circuit_opened": 0 } + } + ] +} diff --git a/a2a/docs/features/openapi-backend.md b/a2a/docs/features/openapi-backend.md index ce9ca755..4a941ccd 100644 --- a/a2a/docs/features/openapi-backend.md +++ b/a2a/docs/features/openapi-backend.md @@ -152,13 +152,9 @@ and the `derive_module_id` / `transform_module` hooks — so a `prefix` of `Pet- 4. One skipped operation MUST NOT fail the scan; sibling operations still register. !!! note "Why skip, when the registry would refuse it anyway" - Handed to `HTTPProxyRegistryWriter`, an illegal ID is rejected by apcore's registry, so the - module never registers either way. But it surfaces as a per-module write-failure **ERROR** - rather than as a report naming the segment and the remedy, and — worse — it is still in the - set every later diagnostic reads: FR-OAS-003's report counts it, FR-OAS-005 warns about a write - operation that will never be on the card, and the zero-modules warning stays silent for a - document none of whose operations registered. Skipping first keeps every diagnostic about the - modules that are actually served. + The scanner can report the specific invalid segment and the remedy before the registry + rejects it. Skipping at that stage lets the bridge accurately report how many modules will + register, which descriptions it synthesized, and which write operations will be served. **Collisions created by the naming rule are the scanner's to resolve.** `listPets` and `list-pets` are two distinct operations to OpenAPI and one module ID to apcore (`list_pets`). The toolkit @@ -619,16 +615,17 @@ Builds a `Registry` from an OpenAPI document. | No usable `base_url` | `ValueError` naming both the document and the config key | | Derived `module_id` collides with a module already in the registry | `ValueError` naming **every** colliding ID, sorted and deduplicated, before anything is written — reporting only the first forces one restart per collision | | A selected operation cannot be forwarded | Backend construction fails before registration, naming the operation and reason | +| A selected operation fails to register | Backend construction fails, naming each failed or absent module and its diagnostic | -Two failures are deliberately **not** errors: a module whose emitted ID apcore's registry would -reject is skipped with a WARNING (FR-OAS-002), and a per-module write failure is logged at ERROR -while the remaining modules still register. Neither leaves the registry partially populated with respect to the *set* the -preflight approved. +A module with an unprojectable ID is skipped with a WARNING (FR-OAS-002) before determining +which modules must register. The bridge checks each selected ID against the writer results +and the registry. TypeScript waits for pending host registration promises. ### Returns -A populated `Registry`. Never a partially-populated one: the collision preflight and every -validation run before the first `write`. +A populated `Registry` on success. A registration failure can occur after some selected modules +have been written. Assemble in a startup-owned registry and publish it only after backend +construction succeeds. ### Properties @@ -639,8 +636,8 @@ validation run before the first `write`. - **Emits**, in this order, before returning: the FR-OAS-002 illegal-ID skip WARNINGs, the scanner's per-module warnings for every module that will register (a skipped module's own toolkit legality warning is not repeated beside its skip line), a zero-modules-produced WARNING, the FR-OAS-003 - description-fallback INFO line, per-module write-failure ERRORs (non-fatal), and the FR-OAS-005 - unapproved-write WARNING. + description-fallback INFO line, and the FR-OAS-005 unapproved-write WARNING after registration + succeeds. - **Every registered module ID is apcore-legal**, and every registered module carries a non-empty description. These two invariants are what FR-OAS-002 and FR-OAS-003 exist to hold, and they are the reason the backend cannot be a thin `scan`-then-`write` call. @@ -649,14 +646,8 @@ validation run before the first `write`. ## Canonical diagnostic text -The six report sites emit at levels that are already normative and identical across the three -SDKs. Their **text** drifted, and a cross-language audit found five of the six carrying -different facts rather than different phrasing — Python's drop message (now the FR-OAS-002 skip -message) named no remedy, its collision error did not say the registry was untouched, and its no-`base_url` error -did not say what breaks. Each of those is a fact the operator needs and one binding withheld. - -The table fixes what each message must **contain**. Wording may differ where a language must -name its own API; the listed facts may not go missing. +The three SDKs report at the same levels and include the facts listed below. Each SDK uses +its own public API names in diagnostic messages. | Site | Level | MUST contain | |---|---|---| @@ -664,16 +655,16 @@ name its own API; the listed facts may not go missing. | Per-module scanner warning | `warn` | the module ID and the scanner's own text, unmodified | | Zero modules produced | `warn` | that the Agent Card will have no skills | | Description synthesis (FR-OAS-003) | `info` | the count, the denominator (modules `scan` returned), and every affected ID **as emitted** — after normalisation and deduplication | -| Per-module write failure | `error` | the module ID and the writer's `verification_error` | | Unapproved writes (FR-OAS-005) | `warn` | the count; the methods; the public Agent Card **and its path**; the three remedies | -And for the three fatal errors: +Fatal errors contain the following details: | Error | MUST contain | |---|---| | ID collision (FR-OAS-006) | every colliding ID, sorted and deduplicated; **"Nothing was registered."**; and the `prefix` remedy | | No `base_url` | that the document has no usable absolute `servers[0].url`, **that every proxied call would otherwise resolve against an unknown host**, and the config key to set | | Missing `prefix` in a mixed deployment | the key `prefix`, and why — a derived ID can collide with a project module ID | +| Incomplete registration | each failed or absent module ID and the available registration error | !!! note "Why the required-pattern fragment is in the skip message" An operator reading *"the derived module ID has a segment (`2fa`) apcore's registry cannot diff --git a/a2a/python/CHANGELOG.md b/a2a/python/CHANGELOG.md index dd6fb1ff..310f1f1e 100644 --- a/a2a/python/CHANGELOG.md +++ b/a2a/python/CHANGELOG.md @@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [0.8.8a1] - Unreleased + +### Added + +- Provide an opt-in A2A event subscriber for migration from Core. Preserve a single terminal task state under cancellation or backpressure and reject incomplete OpenAPI registration. + ## [0.8.7] - 2026-11-20 ### Changed diff --git a/a2a/python/README.md b/a2a/python/README.md index 73cf174e..b154f215 100644 --- a/a2a/python/README.md +++ b/a2a/python/README.md @@ -178,6 +178,37 @@ serve(registry, auth=auth) ## For Developers: API Reference +### A2A event subscriptions + +Call `register_a2a_subscriber()` during application startup, before creating the +APCore client. Existing `sys_modules.events.subscribers` entries with +`type: a2a` then use the adapter's HTTP transport. The same factory resolves +`delegate_type: a2a` in a filter. + +```python +from apcore import APCore, Config +from apcore_a2a import register_a2a_subscriber + +register_a2a_subscriber() +client = APCore(config=Config.discover()) +try: + # Use the client with the application's configured subscribers. + pass +finally: + client.close() +``` + +The transport uses `httpx` and sends one delivery attempt to the configured +`platform_url`. APCore applies retry, circuit breaker and dead-letter policy. +Core 0.33.0's configuration-driven circuit breaker records failures without +forwarding them to the retry and dead-letter pipeline. Use a Core release with +that forwarding enabled when those guarantees are required. + +The factory change applies to future APCore clients in the process. To restore +the built-in transport, remove the registration call and restart with the same +subscriber configuration. The built-in transport requires the optional +`apcore[events]` extra. + ### `serve()` Blocking call — starts uvicorn and serves until SIGINT/SIGTERM. diff --git a/a2a/python/pyproject.toml b/a2a/python/pyproject.toml index 52d42dc1..a493bda9 100644 --- a/a2a/python/pyproject.toml +++ b/a2a/python/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "apcore-a2a" -version = "0.8.7" +version = "0.8.8a1" description = "Automatic A2A Protocol Adapter for apcore Module Registry" readme = "README.md" license = "Apache-2.0" @@ -26,8 +26,8 @@ classifiers = [ "Framework :: AsyncIO", ] dependencies = [ - "apcore>=0.33.0", - "apcore-toolkit>=0.15.0", + "apcore>=0.33.0,<=1.0.0a1", + "apcore-toolkit==0.15.1a1", "a2a-sdk[http-server]>=1.0.0", "starlette>=0.40.0", "uvicorn>=0.30.0", @@ -39,7 +39,7 @@ dependencies = [ # The OpenAPI backend fetches a spec over http(s) and registers each operation as # an HTTP proxy, both of which live behind apcore-toolkit's own extra. openapi = [ - "apcore-toolkit[http-proxy]>=0.15.0", + "apcore-toolkit[http-proxy]==0.15.1a1", ] dev = [ "pytest>=7.0", diff --git a/a2a/python/src/apcore_a2a/__init__.py b/a2a/python/src/apcore_a2a/__init__.py index 7c03ded1..2d517609 100644 --- a/a2a/python/src/apcore_a2a/__init__.py +++ b/a2a/python/src/apcore_a2a/__init__.py @@ -6,6 +6,7 @@ from apcore_a2a.adapters import AgentCardBuilder, ErrorMapper, PartConverter, SchemaConverter, SkillMapper from apcore_a2a.auth import Authenticator, AuthMiddleware, ClaimMapping, JWTAuthenticator, auth_identity_var from apcore_a2a.client import A2AClient +from apcore_a2a.event_subscriber import A2AEventSubscriber, register_a2a_subscriber from apcore_a2a.openapi_backend import openapi_backend from apcore_a2a.server import A2AServerFactory, ApCoreAgentExecutor @@ -18,6 +19,8 @@ "serve", "async_serve", "A2AClient", + "A2AEventSubscriber", + "register_a2a_subscriber", "__version__", # Auth "Authenticator", diff --git a/a2a/python/src/apcore_a2a/event_subscriber.py b/a2a/python/src/apcore_a2a/event_subscriber.py new file mode 100644 index 00000000..c91f979a --- /dev/null +++ b/a2a/python/src/apcore_a2a/event_subscriber.py @@ -0,0 +1,68 @@ +"""Opt-in A2A transport for APCore's event emitter.""" + +from __future__ import annotations + +import asyncio +import logging +from dataclasses import asdict +from typing import Any + +import httpx +from apcore import ApCoreEvent, EventRetryConfig, register_subscriber_type + +_logger = logging.getLogger(__name__) + + +class A2AEventSubscriber: + """Deliver one HTTP attempt. APCore controls retry and dead letters.""" + + subscriber_type = "a2a" + + def __init__( + self, + platform_url: str, + auth: str | dict[str, str] | None = None, + timeout_ms: int = 5000, + skill_id: str = "apevo.event_receiver", + *, + retry: EventRetryConfig | dict[str, int | float] | None = None, + subscriber_id: str | None = None, + ) -> None: + self._platform_url = platform_url + self._timeout_s = timeout_ms / 1000 if timeout_ms > 0 else None + self._skill_id = skill_id + self._headers = {"Content-Type": "application/json"} + if isinstance(auth, str): + self._headers["Authorization"] = f"Bearer {auth}" + elif isinstance(auth, dict): + self._headers.update(auth) + self.retry = retry + self.subscriber_id = subscriber_id + + async def on_event(self, event: ApCoreEvent) -> None: + payload = {"skillId": self._skill_id, "event": asdict(event)} + async with ( + asyncio.timeout(self._timeout_s), + httpx.AsyncClient(timeout=None, follow_redirects=True, trust_env=False) as client, + client.stream("POST", self._platform_url, json=payload, headers=self._headers) as response, + ): + if response.status_code >= 500: + raise RuntimeError(f"A2A event delivery failed with HTTP {response.status_code}") + if response.status_code >= 400: + _logger.warning("A2A event %s rejected with HTTP %d", event.event_type, response.status_code) + + +def _from_config(config: dict[str, Any]) -> A2AEventSubscriber: + return A2AEventSubscriber( + platform_url=config["platform_url"], + auth=config.get("auth"), + timeout_ms=config.get("timeout_ms", 5000), + skill_id=config.get("skill_id", "apevo.event_receiver"), + retry=config.get("retry"), + subscriber_id=config.get("id"), + ) + + +def register_a2a_subscriber() -> None: + """Select the A2A transport for future `type: a2a` config entries.""" + register_subscriber_type("a2a", _from_config) diff --git a/a2a/python/src/apcore_a2a/openapi_backend.py b/a2a/python/src/apcore_a2a/openapi_backend.py index 83ac9e32..9f99044c 100644 --- a/a2a/python/src/apcore_a2a/openapi_backend.py +++ b/a2a/python/src/apcore_a2a/openapi_backend.py @@ -405,9 +405,8 @@ def openapi_backend( target = registry if registry is not None else Registry() - # Full-set preflight before the first write. Toolkit writers report per-module - # WriteResults and never abort, so without this a duplicate would arrive as a - # failed WriteResult, get logged and skipped, and leave a partial registry. + # Check the full set before writing so a collision leaves the registry + # untouched and the host can report every colliding ID. existing = set(_registry_ids(target)) collisions = sorted({str(m.module_id) for m in modules} & existing) if collisions: @@ -431,13 +430,16 @@ def openapi_backend( base_url=resolved_base, auth_header_factory=auth_header_factory, ) - for result in writer.write(modules, target): - if getattr(result, "verification_error", None): - logger.error( - "apcore-a2a: %s failed to register as an HTTP proxy: %s", - result.module_id, - result.verification_error, - ) + results = {result.module_id: result for result in writer.write(modules, target)} + failures = [] + for module in modules: + result = results.get(module.module_id) + if result is not None and result.verified and target.get(module.module_id) is not None: + continue + detail = result.verification_error if result is not None else None + failures.append(f"{module.module_id}: {detail or 'module not registered'}") + if failures: + raise ValueError("OpenAPI registration incomplete: " + "; ".join(failures)) _warn_unapproved_writes( modules, diff --git a/a2a/python/src/apcore_a2a/server/executor.py b/a2a/python/src/apcore_a2a/server/executor.py index eec45778..335a22a8 100644 --- a/a2a/python/src/apcore_a2a/server/executor.py +++ b/a2a/python/src/apcore_a2a/server/executor.py @@ -6,12 +6,14 @@ import inspect import logging import time -from collections.abc import Callable +from collections.abc import Awaitable, Callable +from dataclasses import dataclass, field from datetime import UTC, datetime -from typing import Any +from typing import Any, TypeVar from uuid import uuid4 from a2a.server.agent_execution import AgentExecutor, RequestContext +from a2a.server.context import ServerCallContext from a2a.server.events.event_queue_v2 import EventQueue from a2a.types import ( Artifact, @@ -31,6 +33,23 @@ from apcore_a2a.auth.middleware import auth_identity_var logger = logging.getLogger(__name__) +_Result = TypeVar("_Result") +_TaskKey = tuple[str, str, str] +_TERMINAL_STATES = { + TaskState.TASK_STATE_COMPLETED, + TaskState.TASK_STATE_FAILED, + TaskState.TASK_STATE_CANCELED, + TaskState.TASK_STATE_REJECTED, +} + + +@dataclass +class _TaskExecution: + stopped: asyncio.Event = field(default_factory=asyncio.Event) + token: Any = None + work: asyncio.Future[Any] | None = None + terminal: TaskStatus | None = None + terminal_offer_finished: asyncio.Event = field(default_factory=asyncio.Event) def _make_timestamp() -> Timestamp: @@ -55,6 +74,11 @@ def _text_message(text: str) -> Message: ) +def _owner(context: ServerCallContext | None) -> str: + name = getattr(getattr(context, "user", None), "user_name", "") + return name if isinstance(name, str) else "" + + class ApCoreAgentExecutor(AgentExecutor): """Bridges apcore executor to a2a-sdk's AgentExecutor interface.""" @@ -66,6 +90,9 @@ def __init__( registry: Any = None, execution_timeout: int = 300, on_state_change: Callable[[str, str], None] | None = None, + *, + track_terminal_status: bool = False, + load_task: Callable[[str, Any], Awaitable[Task | None]] | None = None, ) -> None: self._executor = executor self._part_converter = part_converter @@ -75,8 +102,11 @@ def __init__( self._on_state_change = on_state_change # Cache inspect.signature results keyed by stable method qualified name self._context_accepts_cache: dict[str, bool] = {} - # P0-B: per-task CancelToken map - self._cancel_tokens: dict[str, Any] = {} + self._running: dict[_TaskKey, _TaskExecution] = {} + self._track_terminal_status = track_terminal_status + self._load_task = load_task + self._pending_terminal: dict[_TaskKey, TaskStatus] = {} + self._cleaning_up: set[asyncio.Future[Any]] = set() def _notify(self, old_state: str, new_state: str) -> None: if self._on_state_change is not None: @@ -86,6 +116,45 @@ def _notify(self, old_state: str, new_state: str) -> None: logger.debug("on_state_change callback raised", exc_info=True) async def execute(self, context: RequestContext, event_queue: EventQueue) -> None: + key = self._task_key(context) + run = _TaskExecution() + self._running[key] = run + try: + await self._execute(context, event_queue, run) + if run.terminal is not None: + # The SDK closes the transport queue when execute() returns. + # A concurrent cancel must finish offering its winning status + # before that closure can discard it. + await run.terminal_offer_finished.wait() + finally: + if self._running.get(key) is run: + self._running.pop(key) + + @staticmethod + def _task_key(context: RequestContext) -> _TaskKey: + return context.task_id, context.context_id or context.task_id, _owner(context.call_context) + + def project_terminal_status(self, task: Task, context: ServerCallContext | None = None) -> Task: + """Report a claimed terminal while the transport drains its event queue.""" + status = self._pending_terminal.get((task.id, task.context_id, _owner(context))) + if ( + status is None + or status.state == TaskState.TASK_STATE_COMPLETED + or task.status.state in _TERMINAL_STATES + ): + return task + projected = Task() + projected.CopyFrom(task) + projected.status.CopyFrom(status) + return projected + + def observe_task_saved(self, task: Task, context: ServerCallContext | None = None) -> None: + """Retire the projection only when the SDK has persisted that status.""" + key = (task.id, task.context_id, _owner(context)) + if task.status == self._pending_terminal.get(key): + self._pending_terminal.pop(key) + + async def _execute(self, context: RequestContext, event_queue: EventQueue, run: _TaskExecution) -> None: # a2a-sdk 1.0: Establish the Task in the store before any TaskStatusUpdateEvent context_id = context.context_id or context.task_id initial_task = Task( @@ -94,6 +163,8 @@ async def execute(self, context: RequestContext, event_queue: EventQueue) -> Non status=_make_status(TaskState.TASK_STATE_SUBMITTED), ) await event_queue.enqueue_event(initial_task) + if run.stopped.is_set(): + return # 1. Get skill_id from message metadata # metadata is a protobuf Struct; convert to dict for .get() access @@ -147,8 +218,7 @@ async def execute(self, context: RequestContext, event_queue: EventQueue) -> Non from apcore import CancelToken, Context # type: ignore[import] token = CancelToken() - if context.task_id: - self._cancel_tokens[context.task_id] = token + run.token = token # Map the A2A execution_timeout onto apcore's first-class # global_deadline (0.22.0). apcore enforces it cooperatively at # pipeline Step 8 AND between streaming chunks (executor.stream), @@ -176,6 +246,7 @@ async def execute(self, context: RequestContext, event_queue: EventQueue) -> Non # 5. Execute — streaming if available, single otherwise (P0-A) self._notify("submitted", "working") + stopped = run.stopped try: stream_fn = getattr(self._executor, "stream", None) # Stream selection is based on the executor's stream method alone, @@ -189,37 +260,40 @@ async def execute(self, context: RequestContext, event_queue: EventQueue) -> Non ) if _can_stream: - await self._execute_streaming(context, event_queue, skill_id, inputs, apcore_ctx, context_id) - else: - output = await self._execute_single(skill_id, inputs, apcore_ctx) - # Publish artifact + completed event - artifact = self._part_converter.output_to_parts(output, context.task_id) - await event_queue.enqueue_event( - TaskArtifactUpdateEvent( - task_id=context.task_id, - context_id=context_id, - artifact=artifact, - append=False, - last_chunk=True, - ) + await self._run_with_timeout( + self._execute_streaming(context, event_queue, skill_id, inputs, apcore_ctx, context_id, stopped), + context.task_id, + run, ) - await event_queue.enqueue_event( - TaskStatusUpdateEvent( - task_id=context.task_id, - context_id=context_id, - status=_make_status(TaskState.TASK_STATE_COMPLETED), - ) + else: + await self._run_with_timeout( + self._send_single(context, event_queue, skill_id, inputs, apcore_ctx, stopped), + context.task_id, + run, ) - self._notify("working", "completed") + if run.terminal is not None: + return + await self._publish_status(context, event_queue, TaskState.TASK_STATE_COMPLETED) + self._notify("working", "completed") except asyncio.CancelledError: + if run.terminal is not None and run.terminal.state == TaskState.TASK_STATE_CANCELED: + return raise # let a2a-sdk handle asyncio cancellation except TimeoutError: + if run.terminal is not None: + return + if token is not None: + token.cancel() self._notify("working", "failed") await self._fail(context, event_queue, "Execution timed out") except Exception as exc: + if run.terminal is not None: + return code = getattr(exc, "code", None) if code == "MODULE_TIMEOUT": # apcore enforced global_deadline (streaming or cooperative step) + if token is not None: + token.cancel() self._notify("working", "failed") await self._fail(context, event_queue, "Execution timed out") elif code == "EXECUTION_CANCELLED": @@ -246,8 +320,6 @@ async def execute(self, context: RequestContext, event_queue: EventQueue) -> Non logger.exception("Execution failed for task %s skill %s", context.task_id, skill_id) self._notify("working", "failed") await self._fail(context, event_queue, self._failure_text(exc)) - finally: - self._cancel_tokens.pop(context.task_id, None) async def _execute_streaming( self, @@ -257,18 +329,11 @@ async def _execute_streaming( inputs: Any, apcore_ctx: Any, context_id: str, + stopped: asyncio.Event, ) -> None: - """Stream chunks from executor.stream(), emitting TaskArtifactUpdateEvents. - - Bound the whole streaming loop by a host-side wall-clock budget - (execution_timeout) in addition to apcore's cooperative global_deadline. - A monotonic deadline is computed once; each chunk fetch is wrapped with - asyncio.wait_for(remaining). On timeout we stop the loop and emit a failed - status, matching the Rust SDK's stream_channel tokio timeout. - """ + """Stream artifacts. The task owner publishes the terminal status.""" artifact_id = f"art-{context.task_id or str(uuid4())}" chunk_index = 0 - deadline = time.monotonic() + self._execution_timeout # Mirror TS's `apcoreCtx ? ...with ctx : ...without ctx`: only pass the # apcore context when present, so the degraded no-binding state still # streams instead of erroring on a None positional argument. @@ -277,30 +342,41 @@ async def _execute_streaming( if apcore_ctx is not None else self._executor.stream(skill_id, inputs) ) + if inspect.isawaitable(stream): + stream = await stream iterator = stream.__aiter__() - while True: - remaining = deadline - time.monotonic() - if remaining <= 0: - await self._fail_stream_timeout(context, event_queue) - return - try: - chunk = await asyncio.wait_for(iterator.__anext__(), timeout=remaining) - except StopAsyncIteration: - break - except TimeoutError: - await self._fail_stream_timeout(context, event_queue) - return - parts = self._part_converter.output_to_parts(chunk, context.task_id).parts - await event_queue.enqueue_event( - TaskArtifactUpdateEvent( - task_id=context.task_id, - context_id=context_id, - artifact=Artifact(artifact_id=artifact_id, parts=parts), - append=(chunk_index > 0), - last_chunk=False, + token = getattr(apcore_ctx, "cancel_token", None) + + def stopping() -> bool: + return stopped.is_set() or (token is not None and token.is_cancelled) + + exhausted = False + try: + async for chunk in iterator: + # A producer may catch CancelledError and yield another chunk. + if stopping(): + return + parts = self._part_converter.output_to_parts(chunk, context.task_id).parts + await event_queue.enqueue_event( + TaskArtifactUpdateEvent( + task_id=context.task_id, + context_id=context_id, + artifact=Artifact(artifact_id=artifact_id, parts=parts), + append=(chunk_index > 0), + last_chunk=False, + ) ) - ) - chunk_index += 1 + chunk_index += 1 + exhausted = True + finally: + if not exhausted and (close := getattr(iterator, "aclose", None)) is not None: + try: + await close() + except Exception: + logger.warning("Stream cleanup failed for task %s", context.task_id, exc_info=True) + + if stopping(): + return # Emit last_chunk=True to signal stream end await event_queue.enqueue_event( TaskArtifactUpdateEvent( @@ -311,31 +387,44 @@ async def _execute_streaming( last_chunk=True, ) ) - await event_queue.enqueue_event( - TaskStatusUpdateEvent( - task_id=context.task_id, - context_id=context_id, - status=_make_status(TaskState.TASK_STATE_COMPLETED), - ) - ) - self._notify("working", "completed") - async def _fail_stream_timeout(self, context: RequestContext, event_queue: EventQueue) -> None: - """Emit a failed status when the streaming wall-clock budget is exceeded. + async def _run_with_timeout( + self, + operation: Awaitable[_Result], + task_id: str, + run: _TaskExecution, + ) -> _Result: + """Bound the whole operation. Its cancellation cleanup runs separately.""" + work = run.work = asyncio.ensure_future(operation) + try: + done, _ = await asyncio.wait({work}, timeout=self._execution_timeout) + except asyncio.CancelledError: + run.stopped.set() + self._stop_work(work, run.token, task_id) + raise + if work not in done: + run.stopped.set() + self._stop_work(work, run.token, task_id) + raise TimeoutError + return work.result() + + def _stop_work(self, work: asyncio.Future[Any], token: Any, task_id: str) -> None: + if work in self._cleaning_up: + return + if token is not None: + token.cancel() + self._cleaning_up.add(work) - Mirrors the MODULE_TIMEOUT handling in execute(): the host-side budget - bounds the whole streaming loop, matching Rust's stream_channel timeout. - """ - logger.warning( - "Streaming execution timed out after %ss for task %s", - self._execution_timeout, - context.task_id, - ) - self._notify("working", "failed") - await self._fail(context, event_queue, "Execution timed out") + def finished(task: asyncio.Future[Any]) -> None: + self._cleaning_up.discard(task) + if not task.cancelled() and (error := task.exception()) is not None: + logger.warning("Execution cleanup failed for task %s", task_id, exc_info=error) + + work.add_done_callback(finished) + work.cancel() async def _execute_single(self, skill_id: str, inputs: Any, apcore_ctx: Any) -> Any: - """Single call_async() execution with timeout.""" + """Single call_async() execution.""" call_async = self._executor.call_async cache_key = getattr(call_async, "__qualname__", repr(call_async)) accepts_ctx = self._context_accepts_cache.get(cache_key) @@ -347,39 +436,94 @@ async def _execute_single(self, skill_id: str, inputs: Any, apcore_ctx: Any) -> if (apcore_ctx is not None and accepts_ctx) else call_async(skill_id, inputs) ) - return await asyncio.wait_for(coro, timeout=self._execution_timeout) + return await coro - async def cancel(self, context: RequestContext, event_queue: EventQueue) -> None: - # P0-B: Signal cooperative cancellation BEFORE emitting the canceled status - token = self._cancel_tokens.pop(context.task_id, None) - if token is not None: - token.cancel() - context_id = context.context_id or context.task_id + async def _send_single( + self, + context: RequestContext, + event_queue: EventQueue, + skill_id: str, + inputs: Any, + apcore_ctx: Any, + stopped: asyncio.Event, + ) -> None: + output = await self._execute_single(skill_id, inputs, apcore_ctx) + if stopped.is_set(): + return await event_queue.enqueue_event( - TaskStatusUpdateEvent( + TaskArtifactUpdateEvent( task_id=context.task_id, - context_id=context_id, - status=_make_status( - TaskState.TASK_STATE_CANCELED, - _text_message("Canceled by client"), - ), + context_id=context.context_id or context.task_id, + artifact=self._part_converter.output_to_parts(output, context.task_id), + last_chunk=True, ) ) + + async def cancel(self, context: RequestContext, event_queue: EventQueue) -> None: + # The SDK may have read a nonterminal snapshot before the status was + # persisted and our in-process claim retired. Recheck the authorized + # store for those late cancellations. + key = self._task_key(context) + if key not in self._running and self._load_task is not None: + current = await self._load_task(context.task_id, context.call_context) + if current is not None and current.status.state in _TERMINAL_STATES: + return + if not await self._publish_status( + context, event_queue, TaskState.TASK_STATE_CANCELED, "Canceled by client", stop_work=True + ): + # The SDK treats executor.cancel() exceptions as agent failures. + # Let it consume the already-claimed outcome and classify the + # cancellation at the RPC boundary instead. + run = self._running.get(key) + if run is not None and run.terminal is not None: + await run.terminal_offer_finished.wait() + return self._notify("working", "canceled") async def _emit_canceled(self, context: RequestContext, event_queue: EventQueue, message: str) -> None: """Emit CANCELED status (for cooperative cancellation via CancelToken).""" - context_id = context.context_id or context.task_id - await event_queue.enqueue_event( - TaskStatusUpdateEvent( - task_id=context.task_id, - context_id=context_id, - status=_make_status( - TaskState.TASK_STATE_CANCELED, - _text_message(message), - ), - ) - ) + await self._publish_status(context, event_queue, TaskState.TASK_STATE_CANCELED, message) + + async def _publish_status( + self, + context: RequestContext, + event_queue: EventQueue, + state: int, + message: str | None = None, + *, + stop_work: bool = False, + ) -> bool: + key = self._task_key(context) + run = self._running.get(key) + if key in self._pending_terminal or (run is not None and run.terminal is not None): + return False + status = _make_status(state, _text_message(message) if message is not None else None) + if state in _TERMINAL_STATES: + if self._track_terminal_status: + self._pending_terminal[key] = status + if run is not None: + run.terminal = status + if stop_work and run is not None: + run.stopped.set() + if run.work is not None and not run.work.done(): + self._stop_work(run.work, run.token, context.task_id) + elif run.token is not None: + run.token.cancel() + event = TaskStatusUpdateEvent(task_id=key[0], context_id=key[1], status=status) + if run is None or run.terminal is not status: + await event_queue.enqueue_event(event) + return True + # A transport may cancel the producer first. Once this attempt has + # claimed the outcome, preserve its terminal event through teardown. + offer = asyncio.create_task(event_queue.enqueue_event(event)) + try: + await asyncio.shield(offer) + except asyncio.CancelledError: + await offer + raise + finally: + run.terminal_offer_finished.set() + return True def _failure_text(self, error: Exception) -> str: """Caller-facing text for a FAILED task status. @@ -424,41 +568,11 @@ def _failure_text(self, error: Exception) -> str: return message async def _fail(self, context: RequestContext, event_queue: EventQueue, message: str) -> None: - context_id = context.context_id or context.task_id - await event_queue.enqueue_event( - TaskStatusUpdateEvent( - task_id=context.task_id, - context_id=context_id, - status=_make_status( - TaskState.TASK_STATE_FAILED, - _text_message(message), - ), - ) - ) + await self._publish_status(context, event_queue, TaskState.TASK_STATE_FAILED, message) async def _reject(self, context: RequestContext, event_queue: EventQueue, message: str) -> None: """Emit REJECTED status for a governance refusal (srs FR-ERR-012).""" - context_id = context.context_id or context.task_id - await event_queue.enqueue_event( - TaskStatusUpdateEvent( - task_id=context.task_id, - context_id=context_id, - status=_make_status( - TaskState.TASK_STATE_REJECTED, - _text_message(message), - ), - ) - ) + await self._publish_status(context, event_queue, TaskState.TASK_STATE_REJECTED, message) async def _input_required(self, context: RequestContext, event_queue: EventQueue, message: str) -> None: - context_id = context.context_id or context.task_id - await event_queue.enqueue_event( - TaskStatusUpdateEvent( - task_id=context.task_id, - context_id=context_id, - status=_make_status( - TaskState.TASK_STATE_INPUT_REQUIRED, - _text_message(message), - ), - ) - ) + await self._publish_status(context, event_queue, TaskState.TASK_STATE_INPUT_REQUIRED, message) diff --git a/a2a/python/src/apcore_a2a/server/factory.py b/a2a/python/src/apcore_a2a/server/factory.py index 5771cd66..cee2496f 100644 --- a/a2a/python/src/apcore_a2a/server/factory.py +++ b/a2a/python/src/apcore_a2a/server/factory.py @@ -7,15 +7,26 @@ import time import warnings from dataclasses import dataclass -from typing import Any +from typing import TYPE_CHECKING, Any +from a2a.server.context import ServerCallContext from a2a.server.request_handlers import DefaultRequestHandler from a2a.server.routes import create_agent_card_routes, create_jsonrpc_routes, create_rest_routes from a2a.server.tasks.inmemory_push_notification_config_store import ( InMemoryPushNotificationConfigStore, ) from a2a.server.tasks.inmemory_task_store import InMemoryTaskStore as A2ATaskStore -from a2a.types import AgentCapabilities, AgentCard +from a2a.types import ( + AgentCapabilities, + AgentCard, + CancelTaskRequest, + GetTaskRequest, + ListTasksRequest, + ListTasksResponse, + Task, + TaskState, +) +from a2a.utils.errors import TaskNotCancelableError from apcore.error_formatter import ErrorFormatterRegistry from starlette.applications import Starlette from starlette.middleware import Middleware @@ -41,9 +52,75 @@ ) from apcore_a2a.server.executor import ApCoreAgentExecutor +if TYPE_CHECKING: + from a2a.server.cluster.task_store import StoredTask + from a2a.server.cluster.version import TaskVersion + from a2a.server.events import Event + +try: + from a2a.server.cluster.task_store import VersionedTaskStore as _SDKVersionedTaskStore +except ImportError: + + class _SDKVersionedTaskStore: + """Placeholder for SDK releases without versioned stores.""" + + logger = logging.getLogger(__name__) +class _ObservedTaskStore: + """Observe durable acknowledgments while preserving the supplied store's context.""" + + def __init__(self, store: Any, executor: ApCoreAgentExecutor) -> None: + self._store = store + self._executor = executor + + def __getattr__(self, name: str) -> Any: + return getattr(self._store, name) + + async def save(self, task: Task, context: ServerCallContext) -> None: + await self._store.save(task, context) + self._executor.observe_task_saved(task, context) + + +class _ObservedVersionedTaskStore(_ObservedTaskStore, _SDKVersionedTaskStore): + async def save( + self, + task: Task, + *, + event: Event | None, + prev: Task | None, + prev_version: TaskVersion, + context: ServerCallContext, + ) -> TaskVersion: + version = await self._store.save(task, event=event, prev=prev, prev_version=prev_version, context=context) + self._executor.observe_task_saved(task, context) + return version + + async def get(self, task_id: str, context: ServerCallContext) -> StoredTask | None: + return await self._store.get(task_id, context) + + async def list(self, params: ListTasksRequest, context: ServerCallContext) -> ListTasksResponse: + return await self._store.list(params, context) + + async def delete(self, task_id: str, context: ServerCallContext) -> None: + await self._store.delete(task_id, context) + + +class _TerminalAwareRequestHandler(DefaultRequestHandler): + async def on_get_task(self, params: GetTaskRequest, context: ServerCallContext) -> Task | None: + task = await super().on_get_task(params, context) + if task is not None: + task = self.agent_executor.project_terminal_status(task, context) + return task + + async def on_cancel_task(self, params: CancelTaskRequest, context: ServerCallContext) -> Task | None: + task = await super().on_cancel_task(params, context) + if task is not None and task.status.state != TaskState.TASK_STATE_CANCELED: + raise TaskNotCancelableError(message="Task already has a terminal outcome") + return task + + @dataclass class _MetricsState: """Simple in-process counters for the A2A ``/metrics`` endpoint. @@ -255,6 +332,14 @@ def create( ``OwnerResolver``; a third-party store must do the same. Upstream states the requirement as a SHOULD on the ``TaskStore`` contract, so it cannot be enforced here. + + While the SDK drains a backpressured event queue, authenticated + ``GetTask`` requests can see a pending unsuccessful outcome in this + server process. Successful completion becomes visible once the store + persists it, and ``ListTasks`` reflects persisted results. The SDK + continues draining after a stream disconnect. A store write failure + remains an SDK persistence error. Until the store acknowledges the + terminal write, the pending outcome exists only in this process. """ # C3: cancel_on_disconnect is not used by DefaultRequestHandler; warn when False if not cancel_on_disconnect: @@ -372,6 +457,13 @@ def create( # Build ApCoreAgentExecutor — C1: wire state-transition callback when metrics enabled on_state_change_cb = metrics_state.on_state_transition if metrics else None + sdk_task_store = task_store if task_store is not None else A2ATaskStore() + self._task_store = sdk_task_store + + async def load_task(task_id: str, context: ServerCallContext) -> Task | None: + stored = await sdk_task_store.get(task_id, context) + return stored.task if stored is not None and isinstance(sdk_task_store, _SDKVersionedTaskStore) else stored + apcore_executor = ApCoreAgentExecutor( executor, self._part_converter, @@ -379,6 +471,8 @@ def create( registry, execution_timeout, on_state_change=on_state_change_cb, + track_terminal_status=True, + load_task=load_task, ) # P1-A: wire apcore observability middleware into the executor. @@ -397,10 +491,6 @@ def create( except Exception: logger.debug("Could not add observability middleware", exc_info=True) - # Build task store - sdk_task_store = task_store if task_store is not None else A2ATaskStore() - self._task_store = sdk_task_store - # Build push config store push_config_store = InMemoryPushNotificationConfigStore() if push_notifications else None @@ -423,9 +513,13 @@ async def extended_card_modifier( # type: ignore[misc] return build_extended_card(card, executor, _identity_of(context)) # Build DefaultRequestHandler (a2a-sdk 1.0: agent_card is required 3rd arg) - handler = DefaultRequestHandler( + handler = _TerminalAwareRequestHandler( agent_executor=apcore_executor, - task_store=sdk_task_store, + task_store=( + _ObservedVersionedTaskStore(sdk_task_store, apcore_executor) + if isinstance(sdk_task_store, _SDKVersionedTaskStore) + else _ObservedTaskStore(sdk_task_store, apcore_executor) + ), agent_card=agent_card, push_config_store=push_config_store, extended_agent_card=extended_card, diff --git a/a2a/python/tests/conformance/test_event_subscriber.py b/a2a/python/tests/conformance/test_event_subscriber.py new file mode 100644 index 00000000..19f04656 --- /dev/null +++ b/a2a/python/tests/conformance/test_event_subscriber.py @@ -0,0 +1,170 @@ +"""Check the alternate A2A subscriber through real configuration and HTTP.""" + +from __future__ import annotations + +import json +import time +from collections.abc import Iterator +from contextlib import closing, contextmanager +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from threading import Thread +from typing import Any +from unittest.mock import patch + +import pytest +from apcore import APCore, ApCoreEvent, Config, EventEmitter, EventRetryConfig, reset_subscriber_registry +from apcore.events import A2ASubscriber as CoreA2ASubscriber +from apcore.events import CircuitBreakerWrapper, create_subscriber_from_config + +from apcore_a2a import A2AEventSubscriber, register_a2a_subscriber + +_FIXTURE = json.loads((Path(__file__).resolve().parents[3] / "conformance/fixtures/event_subscriber.json").read_text()) +_DELIVERY_EVENTS = ("apcore.event.delivery_failed", "apcore.subscriber.circuit_opened") +_LEGACY_FAILURE_COUNTS = { + "transient_failure": {"requests": 1, "dead_letters": 0}, + "circuit_breaker": {"requests": 1, "dead_letters": 0}, + "timeout": {"requests": 1, "dead_letters": 0}, +} + + +class _DiagnosticSink: + def __init__(self, event_pattern: str, events: list[ApCoreEvent]) -> None: + self.event_pattern = event_pattern + self._events = events + + async def on_event(self, event: ApCoreEvent) -> None: + self._events.append(event) + + +@pytest.fixture(autouse=True) +def _isolate_subscriber_registry() -> Iterator[None]: + reset_subscriber_registry() + try: + yield + finally: + reset_subscriber_registry() + + +@contextmanager +def _receiver( + status: int = 204, delay_ms: int = 0 +) -> Iterator[tuple[str, list[tuple[dict[str, str], dict[str, Any]]]]]: + received: list[tuple[dict[str, str], dict[str, Any]]] = [] + + class Receiver(BaseHTTPRequestHandler): + def do_POST(self) -> None: # noqa: N802 + body = json.loads(self.rfile.read(int(self.headers["Content-Length"]))) + headers = {key.lower(): value for key, value in self.headers.items()} + received.append((headers, body)) + if delay_ms: + time.sleep(delay_ms / 1000) + self.send_response(status) + self.end_headers() + + def log_message(self, format: str, *args: object) -> None: + pass + + with ThreadingHTTPServer(("127.0.0.1", 0), Receiver) as server: + server.daemon_threads = False + worker = Thread(target=server.serve_forever, kwargs={"poll_interval": 0.01}) + worker.start() + try: + yield f"http://127.0.0.1:{server.server_port}/receive", received + finally: + server.shutdown() + worker.join(timeout=3) + + +def _emit_from_config(path: Path, subscriber: dict[str, Any]) -> list[ApCoreEvent]: + path.write_text( + "version: '1.0.0'\nproject: {name: fixture}\n" + "sys_modules:\n enabled: true\n events:\n enabled: true\n" + f" subscribers: {json.dumps([subscriber])}\n" + ) + events: list[ApCoreEvent] = [] + with closing(APCore(config=Config.load(str(path)))) as core: + assert core.events is not None + for name in _DELIVERY_EVENTS: + core.events.subscribe(_DiagnosticSink(name, events)) + core.events.emit(ApCoreEvent(**_FIXTURE["event"])) + core.events.flush() + core.events.flush() + return events + + +@pytest.mark.parametrize("case", _FIXTURE["test_cases"], ids=lambda case: case["id"]) +def test_event_subscriber_from_config(case: dict[str, Any], tmp_path: Path) -> None: + with _receiver(case["status"], case.get("delay_ms", 0)) as (url, received): + subscriber = dict(case["subscriber"]) + if subscriber["type"] == "filter": + subscriber["delegate_config"] = {"platform_url": url} + else: + subscriber.update(platform_url=url, id="configured-a2a") + + register_a2a_subscriber() + register_a2a_subscriber() + with patch("apcore.events.subscribers.aiohttp", None): + events = _emit_from_config(tmp_path / "apcore.yaml", subscriber) + + expected = case["expected"] + if not hasattr(CircuitBreakerWrapper, "retry"): + # The released minimum's Config wrapper counts failures for its + # circuit without forwarding them to the emitter's retry loop. + expected = {**expected, **_LEGACY_FAILURE_COUNTS.get(case["id"], {})} + assert len(received) == expected["requests"] + for headers, body in received: + assert headers.get("content-type") == "application/json" + assert headers.get("authorization") == expected.get("authorization") + assert headers.get("x-source") == expected.get("source") + assert body == {"skillId": expected["skill_id"], "event": _FIXTURE["event"]} + event_types = [event.event_type for event in events] + assert event_types.count("apcore.event.delivery_failed") == expected["dead_letters"] + assert event_types.count("apcore.subscriber.circuit_opened") == expected["circuit_opened"] + for event in events: + assert event.data["subscriber_id"] == "configured-a2a" + + +def test_subscriber_factory_switch_is_opt_in_and_reversible() -> None: + config = {"type": "a2a", "platform_url": "https://example.com/receive"} + assert isinstance(create_subscriber_from_config(config), CoreA2ASubscriber) + register_a2a_subscriber() + assert isinstance(create_subscriber_from_config(config), A2AEventSubscriber) + reset_subscriber_registry() + assert isinstance(create_subscriber_from_config(config), CoreA2ASubscriber) + + +def test_legacy_config_restored_after_reset(tmp_path: Path) -> None: + pytest.importorskip("aiohttp", reason="the legacy Core transport uses the optional events extra") + with _receiver() as (url, received): + config_path = tmp_path / "apcore.yaml" + subscriber = {"type": "a2a", "platform_url": url, "auth": "test-token"} + register_a2a_subscriber() + assert _emit_from_config(config_path, subscriber) == [] + assert len(received) == 1 + + reset_subscriber_registry() + assert _emit_from_config(config_path, subscriber) == [] + assert len(received) == 2 + assert received[0][0]["authorization"] == received[1][0]["authorization"] == "Bearer test-token" + assert received[0][1] == received[1][1] + + +async def test_zero_timeout_leaves_delivery_to_the_event_bus() -> None: + with _receiver() as (url, received): + subscriber = A2AEventSubscriber(url, timeout_ms=0) + await subscriber.on_event(ApCoreEvent(**_FIXTURE["event"])) + assert len(received) == 1 + + +def test_transport_exposes_failure_to_event_emitter() -> None: + with _receiver(status=503) as (url, received): + subscriber = A2AEventSubscriber(url, retry=EventRetryConfig(max_attempts=2, initial_backoff_ms=1)) + emitter = EventEmitter() + try: + emitter.subscribe(subscriber) + emitter.emit(ApCoreEvent(**_FIXTURE["event"])) + emitter.flush() + finally: + emitter.shutdown() + assert len(received) == 2 diff --git a/a2a/python/tests/server/test_executor.py b/a2a/python/tests/server/test_executor.py index 059c5317..38495b35 100644 --- a/a2a/python/tests/server/test_executor.py +++ b/a2a/python/tests/server/test_executor.py @@ -7,14 +7,16 @@ from unittest.mock import AsyncMock, MagicMock import pytest -from a2a.server.events import EventQueue +from a2a.server.context import ServerCallContext +from a2a.server.events.event_queue import EventQueueLegacy as EventQueue from a2a.server.events.in_memory_queue_manager import InMemoryQueueManager -from a2a.types import Message, Part, Role, TaskState +from a2a.types import Message, Part, Role, Task, TaskArtifactUpdateEvent, TaskState, TaskStatusUpdateEvent from apcore.errors import ErrorCodes, ModuleError from apcore_a2a.adapters.errors import ErrorMapper from apcore_a2a.adapters.parts import PartConverter from apcore_a2a.adapters.schema import SchemaConverter +from apcore_a2a.server.context import IdentityUser from apcore_a2a.server.executor import ApCoreAgentExecutor # --------------------------------------------------------------------------- @@ -56,6 +58,251 @@ async def _make_queue() -> EventQueue: return await mgr.get("task-1") +@pytest.mark.parametrize("partial", [False, True]) +async def test_stream_timeout_finishes_before_producer_cleanup(partial, caplog): + cleanup_started = asyncio.Event() + release_cleanup = asyncio.Event() + producer_closed = asyncio.Event() + cancellation_seen = [] + + class SlowExecutor: + async def stream(self, module_id, inputs, context): + try: + if partial: + yield {"value": "partial"} + try: + await asyncio.Future() + except asyncio.CancelledError: + cancellation_seen.append(context.cancel_token.is_cancelled) + cleanup_started.set() + await release_cleanup.wait() + yield {"value": "late"} + finally: + producer_closed.set() + raise RuntimeError("generator cleanup failed") + + agent = ApCoreAgentExecutor( + SlowExecutor(), + PartConverter(SchemaConverter()), + ErrorMapper(), + execution_timeout=0.03, + ) + queue = await _make_queue() + running = asyncio.create_task(agent.execute(_make_context(), queue)) + try: + await asyncio.wait_for(cleanup_started.wait(), timeout=1) + done, _ = await asyncio.wait({running}, timeout=0.5) + assert running in done, "the task terminal must not wait for generator cleanup" + await running + assert not producer_closed.is_set() + finally: + release_cleanup.set() + await asyncio.wait_for(running, timeout=1) + await asyncio.wait_for(producer_closed.wait(), timeout=1) + + events = await _drain_queue(queue) + updates = [event for event in events if isinstance(event, TaskStatusUpdateEvent)] + assert [event.status.state for event in updates] == [TaskState.TASK_STATE_FAILED] + assert updates[0].status.message.parts[0].text == "Execution timed out" + artifacts = [event for event in events if isinstance(event, TaskArtifactUpdateEvent)] + assert len(artifacts) == int(partial) + assert all(not event.last_chunk for event in artifacts) + assert cancellation_seen == [True] + assert "Stream cleanup failed for task task-1" in caplog.text + + +async def test_client_cancel_wins_over_late_stream_completion(): + started = asyncio.Event() + resume = asyncio.Event() + + class SlowExecutor: + async def stream(self, module_id, inputs, context): + started.set() + await resume.wait() + yield {"value": "late"} + + agent = ApCoreAgentExecutor(SlowExecutor(), PartConverter(SchemaConverter()), ErrorMapper()) + queue = await _make_queue() + ctx = _make_context() + running = asyncio.create_task(agent.execute(ctx, queue)) + try: + await asyncio.wait_for(started.wait(), timeout=1) + await agent.cancel(ctx, queue) + finally: + resume.set() + await asyncio.wait_for(running, timeout=1) + + events = await _drain_queue(queue) + updates = [event.status.state for event in events if isinstance(event, TaskStatusUpdateEvent)] + assert updates == [TaskState.TASK_STATE_CANCELED] + assert all(not isinstance(event, TaskArtifactUpdateEvent) for event in events) + + +async def _read_event(queue): + event = await asyncio.wait_for(queue.dequeue_event(), 1) + queue.task_done() + return event + + +async def test_timeout_is_queryable_while_artifacts_block_the_sdk_queue(monkeypatch): + timed_out = asyncio.Event() + queue = EventQueue(max_queue_size=1) + enqueue = queue.enqueue_event + + async def observe_enqueue(event): + if isinstance(event, TaskStatusUpdateEvent): + timed_out.set() + await enqueue(event) + + monkeypatch.setattr(queue, "enqueue_event", observe_enqueue) + + class Producer: + async def stream(self, module_id, inputs, context): + for value in range(20): + yield {"value": value} + + agent = ApCoreAgentExecutor( + Producer(), PartConverter(SchemaConverter()), ErrorMapper(), execution_timeout=0.05, track_terminal_status=True + ) + context = _make_context() + owner = ServerCallContext(user=IdentityUser(MagicMock(id="owner"))) + other = ServerCallContext(user=IdentityUser(MagicMock(id="other"))) + context.call_context = owner + running = asyncio.create_task(agent.execute(context, queue)) + submitted = await _read_event(queue) + try: + await asyncio.wait_for(timed_out.wait(), 1) + assert queue.queue.full() + projected = agent.project_terminal_status(submitted, owner) + assert projected.status.state == TaskState.TASK_STATE_FAILED + assert submitted.status.state == TaskState.TASK_STATE_SUBMITTED + assert agent.project_terminal_status(submitted, other) is submitted + await _read_event(queue) + terminal = await _read_event(queue) + assert terminal.status.state == TaskState.TASK_STATE_FAILED + await asyncio.wait_for(running, 1) + persisted = Task(id=submitted.id, context_id=submitted.context_id, status=terminal.status) + agent.observe_task_saved(persisted, other) + assert agent.project_terminal_status(submitted, owner).status == persisted.status + agent.observe_task_saved(persisted, owner) + assert agent.project_terminal_status(submitted, owner) is submitted + finally: + running.cancel() + await asyncio.gather(running, return_exceptions=True) + await queue.close(immediate=True) + + +async def test_cancel_cannot_replace_completed_status_waiting_to_be_enqueued(monkeypatch): + completed = asyncio.Event() + queue = EventQueue(max_queue_size=1) + enqueue = queue.enqueue_event + + async def observe_enqueue(event): + if isinstance(event, TaskStatusUpdateEvent) and event.status.state == TaskState.TASK_STATE_COMPLETED: + completed.set() + await enqueue(event) + + monkeypatch.setattr(queue, "enqueue_event", observe_enqueue) + + class Producer: + async def stream(self, module_id, inputs, context): + yield {"value": 1} + + agent = ApCoreAgentExecutor(Producer(), PartConverter(SchemaConverter()), ErrorMapper()) + context = _make_context() + running = asyncio.create_task(agent.execute(context, queue)) + cancel = None + try: + await _read_event(queue) + await _read_event(queue) + await asyncio.wait_for(completed.wait(), 1) + cancel = asyncio.create_task(agent.cancel(context, queue)) + await _read_event(queue) + await asyncio.wait_for(cancel, 1) + terminal = await _read_event(queue) + assert terminal.status.state == TaskState.TASK_STATE_COMPLETED + await asyncio.wait_for(running, 1) + assert queue.queue.empty() + finally: + running.cancel() + if cancel is not None: + cancel.cancel() + await asyncio.gather(running, *([cancel] if cancel is not None else []), return_exceptions=True) + await queue.close(immediate=True) + + +async def test_stale_cancel_cannot_replace_a_terminal_status_already_saved(): + context = _make_context() + load_task = AsyncMock( + return_value=Task( + id=context.task_id, + context_id=context.context_id, + status={"state": TaskState.TASK_STATE_COMPLETED}, + ) + ) + agent = ApCoreAgentExecutor( + MagicMock(), PartConverter(SchemaConverter()), ErrorMapper(), load_task=load_task + ) + queue = EventQueue(max_queue_size=1) + try: + await agent.cancel(context, queue) + load_task.assert_awaited_once_with(context.task_id, context.call_context) + assert queue.queue.empty() + finally: + await queue.close(immediate=True) + + +async def test_cancel_event_survives_queue_shutdown_when_artifacts_block_the_queue(monkeypatch): + parked, cancel_offered, closing = asyncio.Event(), asyncio.Event(), asyncio.Event() + queue = EventQueue(max_queue_size=1) + enqueue = queue.enqueue_event + + async def observe_enqueue(event): + if isinstance(event, TaskStatusUpdateEvent) and event.status.state == TaskState.TASK_STATE_CANCELED: + cancel_offered.set() + await enqueue(event) + + monkeypatch.setattr(queue, "enqueue_event", observe_enqueue) + + class Producer: + async def stream(self, module_id, inputs, context): + yield {"value": 1} + parked.set() + await asyncio.Future() + + agent = ApCoreAgentExecutor(Producer(), PartConverter(SchemaConverter()), ErrorMapper()) + context = _make_context() + + async def run_until_closed(): + await agent.execute(context, queue) + closing.set() + await queue.close() + + running = asyncio.create_task(run_until_closed()) + cancel = None + try: + await _read_event(queue) + await asyncio.wait_for(parked.wait(), 1) + assert queue.queue.full() + cancel = asyncio.create_task(agent.cancel(context, queue)) + await asyncio.wait_for(cancel_offered.wait(), 1) + # The SDK must not begin shutting down the queue while cancel is + # blocked on offering the one terminal event. + with pytest.raises(TimeoutError): + await asyncio.wait_for(closing.wait(), 0.05) + assert isinstance(await _read_event(queue), TaskArtifactUpdateEvent) + await asyncio.wait_for(cancel, 1) + terminal = await _read_event(queue) + assert terminal.status.state == TaskState.TASK_STATE_CANCELED + await asyncio.wait_for(running, 1) + finally: + running.cancel() + if cancel is not None: + cancel.cancel() + await asyncio.gather(running, *([cancel] if cancel is not None else []), return_exceptions=True) + await queue.close(immediate=True) + + @pytest.fixture def mock_registry(): reg = MagicMock() diff --git a/a2a/python/tests/server/test_server_factory.py b/a2a/python/tests/server/test_server_factory.py index cafd1dfe..78fd92a1 100644 --- a/a2a/python/tests/server/test_server_factory.py +++ b/a2a/python/tests/server/test_server_factory.py @@ -1,13 +1,25 @@ """Tests for A2AServerFactory.""" +import asyncio +import json from unittest.mock import AsyncMock, MagicMock +import httpx import pytest -from a2a.types import AgentCard +from a2a.server.context import ServerCallContext +from a2a.server.events.event_queue_v2 import EventQueueSource +from a2a.types import AgentCard, CancelTaskRequest, SendMessageRequest, Task, TaskState, TaskStatusUpdateEvent +from a2a.utils.errors import TaskNotCancelableError +from apcore import Executor, Registry +from pydantic import BaseModel from starlette.applications import Starlette from starlette.testclient import TestClient -from apcore_a2a.server.factory import A2AServerFactory +from apcore_a2a.adapters.errors import ErrorMapper +from apcore_a2a.adapters.parts import PartConverter +from apcore_a2a.adapters.schema import SchemaConverter +from apcore_a2a.server.executor import ApCoreAgentExecutor +from apcore_a2a.server.factory import A2AServerFactory, A2ATaskStore, _ObservedTaskStore, _TerminalAwareRequestHandler @pytest.fixture @@ -90,8 +102,6 @@ def test_app_has_jsonrpc_route(mock_registry, mock_executor): url="http://x", ) client = TestClient(app) - import json - # `ListTasks` is the A2A 1.0 name, and needs the version header: a request # without it is treated as v0.3 (spec 3.6.2), which has no listing method. # Asserting the result, not just HTTP 200 — a JSON-RPC error is also a 200, @@ -108,6 +118,300 @@ def test_app_has_jsonrpc_route(mock_registry, mock_executor): assert isinstance(payload["result"]["tasks"], list) +async def test_stream_timeout_is_queryable_through_the_actual_a2a_routes(): + class Input(BaseModel): + pass + + class Output(BaseModel): + value: str + + class Stall: + description = "Emit a partial artifact, then stall" + input_schema = Input + output_schema = Output + + async def execute(self, inputs, context): + raise AssertionError("the native stream must run") + + async def stream(self, inputs, context): + yield {"value": "partial"} + await asyncio.Future() + + registry = Registry() + registry.register("test.stall", Stall()) + app, _ = A2AServerFactory().create( + registry, Executor(registry), name="agent", description="d", version="1", + url="http://test", execution_timeout=0.1, + ) + request = { + "jsonrpc": "2.0", "id": 1, "method": "SendStreamingMessage", + "params": {"message": { + "messageId": "stall", "role": "ROLE_USER", "parts": [{"data": {}}], + "metadata": {"skillId": "test.stall"}, + }}, + } + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=app), base_url="http://test", headers={"A2A-Version": "1.0"}, + ) as client: + response = await asyncio.wait_for(client.post("/", json=request), timeout=2) + assert response.status_code == 200 + frames = [json.loads(line[5:])["result"] for line in response.text.splitlines() if line.startswith("data:")] + artifacts = [event["artifactUpdate"] for event in frames if "artifactUpdate" in event] + assert len(artifacts) == 1 and not artifacts[0].get("lastChunk", False) + statuses = [event["statusUpdate"] for event in frames if "statusUpdate" in event] + assert [update["status"]["state"] for update in statuses] == ["TASK_STATE_FAILED"] + terminal = statuses[0] + assert terminal["status"]["message"]["parts"][0]["text"] == "Execution timed out" + result = await client.post("/", json={ + "jsonrpc": "2.0", "id": 2, "method": "GetTask", "params": {"id": terminal["taskId"]}, + }) + assert result.json()["result"]["status"] == terminal["status"] + + +@pytest.mark.parametrize("versioned_store", [False, True]) +async def test_get_task_reports_the_terminal_before_a_slow_sse_reader_drains(versioned_store): + first_task, allow_send, stopped = asyncio.Event(), asyncio.Event(), asyncio.Event() + task_id = "" + + class FastProducer: + description = "Fill the artifact queue while a client pauses its SSE read" + input_schema = {"type": "object"} + output_schema = {"type": "object"} + + async def execute(self, inputs, context): + raise AssertionError("the native stream must run") + + async def stream(self, inputs, context): + try: + for index in range(10_000): + yield {"index": index} + finally: + stopped.set() + + registry = Registry() + registry.register("test.backpressure", FastProducer()) + store = None + if versioned_store: + cluster = pytest.importorskip("a2a.server.cluster.task_store") + store = cluster.LegacyTaskStoreAdapter(A2ATaskStore()) + app, _ = A2AServerFactory().create( + registry, + Executor(registry), + name="agent", + description="description", + version="1", + url="http://test", + task_store=store, + execution_timeout=0.25, + ) + + async def hold_first_sse_event(scope, receive, send): + async def slow_send(event): + nonlocal task_id + body = event.get("body", b"") + if not task_id and event["type"] == "http.response.body" and body.startswith(b"data:"): + task_id = json.loads(body.splitlines()[0][5:])["result"]["task"]["id"] + first_task.set() + await allow_send.wait() + await send(event) + + await app(scope, receive, slow_send) + + headers = {"A2A-Version": "1.0"} + async with ( + httpx.AsyncClient(transport=httpx.ASGITransport(app=hold_first_sse_event), base_url="http://test") as stream, + httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as status, + ): + streaming = asyncio.create_task( + stream.post( + "/", + headers=headers, + json={ + "jsonrpc": "2.0", + "id": 1, + "method": "SendStreamingMessage", + "params": { + "message": { + "messageId": "blocked-reader", + "role": "ROLE_USER", + "parts": [{"data": {}}], + "metadata": {"skillId": "test.backpressure"}, + } + }, + }, + ) + ) + try: + await asyncio.wait_for(first_task.wait(), 2) + await asyncio.wait_for(stopped.wait(), 2) + query = {"jsonrpc": "2.0", "id": 2, "method": "GetTask", "params": {"id": task_id}} + result = await status.post("/", headers=headers, json=query) + assert result.json()["result"]["status"]["state"] == "TASK_STATE_FAILED" + assert not streaming.done() + finally: + allow_send.set() + response = await asyncio.wait_for(streaming, 3) + frames = [json.loads(line[5:])["result"] for line in response.text.splitlines() if line.startswith("data:")] + statuses = [event["statusUpdate"]["status"] for event in frames if "statusUpdate" in event] + assert [item["state"] for item in statuses] == ["TASK_STATE_FAILED"] + persisted = await status.post("/", headers=headers, json=query) + assert persisted.json()["result"]["status"] == statuses[0] + + +async def test_disconnected_stream_persists_the_terminal_and_retires_the_projection(): + class Producer: + async def stream(self, module_id, inputs, context): + yield {"value": "partial"} + await asyncio.Future() + + class ObservedStore(A2ATaskStore): + def __init__(self): + super().__init__() + self.terminal_saved = asyncio.Event() + + async def save(self, task, context): + await super().save(task, context) + if task.status.state == TaskState.TASK_STATE_FAILED: + self.terminal_saved.set() + + store = ObservedStore() + agent = ApCoreAgentExecutor( + Producer(), + PartConverter(SchemaConverter()), + ErrorMapper(), + execution_timeout=0.05, + track_terminal_status=True, + ) + handler = _TerminalAwareRequestHandler( + agent_executor=agent, + task_store=_ObservedTaskStore(store, agent), + agent_card=AgentCard(name="test", capabilities={"streaming": True}), + ) + context = ServerCallContext() + request = SendMessageRequest( + message={ + "message_id": "disconnect", + "role": "ROLE_USER", + "parts": [{"text": "test"}], + "metadata": {"skillId": "test.disconnect"}, + }, + ) + stream = handler.on_message_send_stream(request, context) + try: + submitted = await asyncio.wait_for(anext(stream), 1) + assert isinstance(submitted, Task) + assert submitted.status.state == TaskState.TASK_STATE_SUBMITTED + finally: + await stream.aclose() + await asyncio.wait_for(store.terminal_saved.wait(), 2) + persisted = await store.get(submitted.id, context) + assert persisted.status.state == TaskState.TASK_STATE_FAILED + assert agent.project_terminal_status(submitted, context) is submitted + + +async def test_cancel_reports_one_matching_terminal_to_both_rpc_and_stream(): + class Producer: + async def stream(self, module_id, inputs, context): + yield {"value": "partial"} + await asyncio.Future() + + store = A2ATaskStore() + agent = ApCoreAgentExecutor( + Producer(), PartConverter(SchemaConverter()), ErrorMapper(), track_terminal_status=True, + ) + handler = _TerminalAwareRequestHandler( + agent_executor=agent, + task_store=_ObservedTaskStore(store, agent), + agent_card=AgentCard(name="test", capabilities={"streaming": True}), + ) + context = ServerCallContext() + request = SendMessageRequest( + message={ + "message_id": "cancel", + "role": "ROLE_USER", + "parts": [{"text": "test"}], + "metadata": {"skillId": "test.cancel"}, + }, + ) + stream = handler.on_message_send_stream(request, context) + submitted = await asyncio.wait_for(anext(stream), 1) + assert isinstance(submitted, Task) + cancel = asyncio.create_task(handler.on_cancel_task(CancelTaskRequest(id=submitted.id), context)) + try: + async with asyncio.timeout(2): + statuses = [event.status async for event in stream if isinstance(event, TaskStatusUpdateEvent)] + canceled = await cancel + assert [status.state for status in statuses] == [TaskState.TASK_STATE_CANCELED] + assert statuses[0] == canceled.status + finally: + cancel.cancel() + await asyncio.gather(cancel, return_exceptions=True) + await stream.aclose() + + +async def test_sdk_cancel_cannot_rewrite_a_completed_terminal_waiting_on_its_queue(monkeypatch): + offered, release, cancel_entered = asyncio.Event(), asyncio.Event(), asyncio.Event() + enqueue = EventQueueSource.enqueue_event + + async def delay_completion(queue, event): + if isinstance(event, TaskStatusUpdateEvent) and event.status.state == TaskState.TASK_STATE_COMPLETED: + offered.set() + await release.wait() + await enqueue(queue, event) + + monkeypatch.setattr(EventQueueSource, "enqueue_event", delay_completion) + + class Producer: + async def stream(self, module_id, inputs, context): + yield {"value": "complete"} + + store = A2ATaskStore() + agent = ApCoreAgentExecutor( + Producer(), PartConverter(SchemaConverter()), ErrorMapper(), track_terminal_status=True + ) + cancel = agent.cancel + + async def observe_cancel(*args): + cancel_entered.set() + await cancel(*args) + + monkeypatch.setattr(agent, "cancel", observe_cancel) + handler = _TerminalAwareRequestHandler( + agent_executor=agent, + task_store=_ObservedTaskStore(store, agent), + agent_card=AgentCard(name="test", capabilities={"streaming": True}), + ) + context = ServerCallContext() + request = SendMessageRequest( + message={ + "message_id": "complete", + "role": "ROLE_USER", + "parts": [{"text": "test"}], + "metadata": {"skillId": "test.complete"}, + }, + ) + stream = handler.on_message_send_stream(request, context) + submitted = await asyncio.wait_for(anext(stream), 1) + assert isinstance(submitted, Task) + await asyncio.wait_for(offered.wait(), 1) + assert agent.project_terminal_status(submitted, context) is submitted + response = asyncio.create_task(handler.on_cancel_task(CancelTaskRequest(id=submitted.id), context)) + try: + await asyncio.wait_for(cancel_entered.wait(), 1) + release.set() + async with asyncio.timeout(2): + statuses = [event.status async for event in stream if isinstance(event, TaskStatusUpdateEvent)] + with pytest.raises(TaskNotCancelableError): + await asyncio.wait_for(response, 1) + assert [status.state for status in statuses] == [TaskState.TASK_STATE_COMPLETED] + assert (await store.get(submitted.id, context)).status == statuses[0] + finally: + release.set() + response.cancel() + await asyncio.gather(response, return_exceptions=True) + await stream.aclose() + + def test_agent_card_has_skills(mock_registry, mock_executor, simple_descriptor): factory = A2AServerFactory() _, card = factory.create( diff --git a/a2a/python/tests/test_openapi_effective_backend.py b/a2a/python/tests/test_openapi_effective_backend.py index bf5e4712..65af5ca8 100644 --- a/a2a/python/tests/test_openapi_effective_backend.py +++ b/a2a/python/tests/test_openapi_effective_backend.py @@ -62,3 +62,21 @@ async def call() -> None: assert [(request.method, request.url.raw_path) for request in requests] == [ ("GET", b"/items/one%2Ftwo"), ] + + +def test_backend_refuses_to_start_when_registry_rejects_a_scanned_module() -> None: + class RejectUpdate: + def validate(self, module: object) -> list[str]: + return ["rejected by host rule"] if getattr(module, "description", None) == "Update item" else [] + + registry = Registry() + registry.set_validator(RejectUpdate()) + document = { + **_DOCUMENT, + "paths": { + "/items": {"get": {"operationId": "listItems", "summary": "List items"}}, + "/updates": {"post": {"operationId": "updateItem", "summary": "Update item"}}, + }, + } + with pytest.raises(ValueError, match=r"update_item.*rejected by host rule"): + openapi_backend(document, registry=registry, acknowledge_unapproved_writes=True) diff --git a/a2a/rust/CHANGELOG.md b/a2a/rust/CHANGELOG.md index 4b09e4b4..801a322a 100644 --- a/a2a/rust/CHANGELOG.md +++ b/a2a/rust/CHANGELOG.md @@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [0.8.7-alpha.1] - Unreleased + +### Added + +- Provide an opt-in A2A event subscriber for migration from Core. Preserve a single terminal task state under cancellation or backpressure and reject incomplete OpenAPI registration. + ## [0.8.6] - 2026-11-20 ### Fixed diff --git a/a2a/rust/Cargo.toml b/a2a/rust/Cargo.toml index 1c196f55..aecd1c36 100644 --- a/a2a/rust/Cargo.toml +++ b/a2a/rust/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "apcore-a2a" -version = "0.8.6" +version = "0.8.7-alpha.1" edition = "2021" rust-version = "1.86" description = "A2A protocol adapter for apcore — expose apcore modules as A2A agents" @@ -27,12 +27,12 @@ default = [] openapi = ["apcore-toolkit/http-proxy"] [dependencies] -apcore = ">=0.33.0" +apcore = ">=0.33.0, <=1.0.0-alpha.1" # `default-features = false` so `http-proxy` — a *default* feature of the # toolkit — is reached through this crate's `openapi` feature instead of being # enabled unconditionally. The unconditional import (`deep_resolve_refs`) is # outside that feature. -apcore-toolkit = { version = ">=0.15.0", default-features = false } +apcore-toolkit = { version = "=0.15.1-alpha.1", default-features = false } tokio = { version = "1", features = ["full"] } serde = { version = "1", features = ["derive"] } serde_json = "1" diff --git a/a2a/rust/README.md b/a2a/rust/README.md index 7c222c41..860a918e 100644 --- a/a2a/rust/README.md +++ b/a2a/rust/README.md @@ -161,6 +161,33 @@ let auth = JWTAuthenticator::new("your-secret-key") --- +### Deliver Core events over A2A + +Register the optional transport before creating the Core client that loads your +subscriber configuration: + +```rust +use apcore::{APCore, ModuleError}; +use apcore_a2a::register_a2a_subscriber; + +fn load_core() -> Result { + register_a2a_subscriber(); + APCore::from_path("apcore.yaml") +} +``` + +This selects the transport for subsequently created `type: a2a` subscribers, +including `filter` entries whose `delegate_type` is `a2a`. `platform_url`, +`auth`, `skill_id`, `timeout_ms`, and `retry` use the existing configuration +layout. Core manages retries, circuit breaking, and dead letters. Configured +retry and dead-letter delivery requires a Core release whose circuit wrapper +reports failed attempts to the emitter. The A2A transport uses this crate's +existing HTTP client dependency and works without Core's `events` feature. + +To restore Core's built-in transport, restart the process without the registration +call and enable Core's `events` feature for built-in HTTP delivery. Subscribers +created before registration retain the transport selected at creation time. + ## Architecture | A2A Concept | apcore Mapping | diff --git a/a2a/rust/src/event_subscriber.rs b/a2a/rust/src/event_subscriber.rs new file mode 100644 index 00000000..7ca19a7a --- /dev/null +++ b/a2a/rust/src/event_subscriber.rs @@ -0,0 +1,238 @@ +//! Opt-in A2A HTTP transport for the Core event emitter. + +use std::fmt; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::OnceLock; +use std::time::Duration; + +use apcore::{ + register_subscriber_type, ApCoreEvent, ErrorCode, EventRetryConfig, EventSubscriber, + ModuleError, +}; +use reqwest::header::{HeaderMap, HeaderName, HeaderValue, AUTHORIZATION}; +use serde_json::{json, Value}; + +const DEFAULT_SKILL_ID: &str = "apevo.event_receiver"; +const DEFAULT_TIMEOUT_MS: u64 = 5_000; +static NEXT_ID: AtomicU64 = AtomicU64::new(0); + +/// Sends one A2A HTTP event delivery attempt. The APCore emitter controls retries. +#[derive(Clone)] +pub struct A2AEventSubscriber { + id: String, + platform_url: String, + headers: HeaderMap, + timeout_ms: u64, + skill_id: String, + retry: EventRetryConfig, +} + +impl A2AEventSubscriber { + /// Create a subscriber with the default timeout and receiver skill. + pub fn new(platform_url: impl Into) -> Self { + let number = NEXT_ID.fetch_add(1, Ordering::Relaxed); + Self { + id: format!("a2a-{number}"), + platform_url: platform_url.into(), + headers: HeaderMap::new(), + timeout_ms: DEFAULT_TIMEOUT_MS, + skill_id: DEFAULT_SKILL_ID.into(), + retry: EventRetryConfig::default(), + } + } + + /// Set the headers to merge into the delivery request. + #[must_use] + pub fn with_headers(mut self, headers: HeaderMap) -> Self { + self.headers = headers; + self + } + + /// Set the subscriber ID exposed to the event emitter. + #[must_use] + pub fn with_id(mut self, id: impl Into) -> Self { + self.id = id.into(); + self + } + + /// Set the per-attempt request timeout in milliseconds. + #[must_use] + pub fn with_timeout_ms(mut self, timeout_ms: u64) -> Self { + self.timeout_ms = timeout_ms; + self + } + + /// Set the A2A receiver skill included in the payload. + #[must_use] + pub fn with_skill_id(mut self, skill_id: impl Into) -> Self { + self.skill_id = skill_id.into(); + self + } + + /// Set the Core emitter's retry configuration for this subscriber. + #[must_use] + pub fn with_retry(mut self, retry: EventRetryConfig) -> Self { + self.retry = retry; + self + } +} + +impl fmt::Debug for A2AEventSubscriber { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_struct("A2AEventSubscriber") + .field("id", &self.id) + .field("timeout_ms", &self.timeout_ms) + .field("skill_id", &self.skill_id) + .field("retry", &self.retry) + .finish_non_exhaustive() + } +} + +#[async_trait::async_trait] +impl EventSubscriber for A2AEventSubscriber { + fn subscriber_id(&self) -> &str { + &self.id + } + + fn subscriber_type(&self) -> &'static str { + "a2a" + } + + fn retry(&self) -> EventRetryConfig { + self.retry + } + + async fn on_event(&self, event: &ApCoreEvent) -> Result<(), ModuleError> { + let payload = json!({ + "skillId": self.skill_id, + "event": { + "event_type": event.event_type, + "module_id": event.module_id, + "timestamp": event.timestamp, + "severity": event.severity, + "data": event.data, + } + }); + let response = http_client()? + .post(&self.platform_url) + .timeout(Duration::from_millis(self.timeout_ms)) + .headers(self.headers.clone()) + .json(&payload) + .send() + .await + .map_err(|error| { + let message = if error.is_timeout() { + "A2A event delivery timed out" + } else { + "A2A event delivery failed" + }; + ModuleError::new(ErrorCode::GeneralInternalError, message) + })?; + let status = response.status(); + if status.is_server_error() { + return Err(ModuleError::new( + ErrorCode::GeneralInternalError, + format!("A2A event delivery failed with HTTP {}", status.as_u16()), + )); + } + if status.is_client_error() { + tracing::warn!(status = status.as_u16(), event_type = %event.event_type, "A2A event rejected"); + } + Ok(()) + } +} + +/// Select the A2A transport for future `type: a2a` configuration entries. +/// Existing subscriptions are owned by their original emitter. +pub fn register_a2a_subscriber() { + register_subscriber_type("a2a", Box::new(from_config)); +} + +#[allow(clippy::result_large_err)] // The Core factory contract uses ModuleError. +fn from_config(config: &Value) -> Result, ModuleError> { + let url = config["platform_url"] + .as_str() + .filter(|url| !url.trim().is_empty()) + .ok_or_else(|| { + ModuleError::new(ErrorCode::ConfigInvalid, "a2a: 'platform_url' is required") + })?; + let timeout_ms = config["timeout_ms"].as_u64().unwrap_or(DEFAULT_TIMEOUT_MS); + let skill_id = config["skill_id"].as_str().unwrap_or(DEFAULT_SKILL_ID); + let mut subscriber = A2AEventSubscriber::new(url) + .with_headers(auth_headers(&config["auth"])?) + .with_skill_id(skill_id) + .with_timeout_ms(timeout_ms) + .with_retry(retry_config(&config["retry"])); + if let Some(id) = config["id"].as_str() { + subscriber = subscriber.with_id(id); + } + Ok(Box::new(subscriber)) +} + +#[allow(clippy::result_large_err)] // Invalid authentication is a Core configuration error. +fn auth_headers(value: &Value) -> Result { + let invalid = || { + ModuleError::new( + ErrorCode::ConfigInvalid, + "a2a: invalid authentication header", + ) + }; + let mut headers = HeaderMap::new(); + match value { + Value::String(token) => { + let mut header = + HeaderValue::from_str(&format!("Bearer {token}")).map_err(|_| invalid())?; + header.set_sensitive(true); + headers.insert(AUTHORIZATION, header); + } + Value::Object(values) => { + for (name, value) in values { + if let Some(value) = value.as_str() { + let name = HeaderName::from_bytes(name.as_bytes()).map_err(|_| invalid())?; + let mut header = HeaderValue::from_str(value).map_err(|_| invalid())?; + if name == AUTHORIZATION { + header.set_sensitive(true); + } + headers.insert(name, header); + } + } + } + _ => {} + } + Ok(headers) +} + +fn retry_config(value: &Value) -> EventRetryConfig { + let defaults = EventRetryConfig::default(); + EventRetryConfig { + max_attempts: value["max_attempts"] + .as_u64() + .and_then(|value| u32::try_from(value).ok()) + .unwrap_or(defaults.max_attempts), + initial_backoff_ms: value["initial_backoff_ms"] + .as_u64() + .unwrap_or(defaults.initial_backoff_ms), + max_backoff_ms: value["max_backoff_ms"] + .as_u64() + .unwrap_or(defaults.max_backoff_ms), + backoff_multiplier: value["backoff_multiplier"] + .as_f64() + .unwrap_or(defaults.backoff_multiplier), + } +} + +#[allow(clippy::result_large_err)] // The subscriber returns ModuleError to the emitter. +fn http_client() -> Result<&'static reqwest::Client, ModuleError> { + static CLIENT: OnceLock = OnceLock::new(); + if let Some(client) = CLIENT.get() { + return Ok(client); + } + let client = reqwest::Client::builder().no_proxy().build().map_err(|_| { + ModuleError::new( + ErrorCode::GeneralInternalError, + "A2A HTTP client initialization failed", + ) + })?; + Ok(CLIENT.get_or_init(|| client)) +} diff --git a/a2a/rust/src/lib.rs b/a2a/rust/src/lib.rs index edab5ba4..a693c7c3 100644 --- a/a2a/rust/src/lib.rs +++ b/a2a/rust/src/lib.rs @@ -7,6 +7,7 @@ pub mod apcore_a2a; pub mod auth; pub mod cli; pub mod client; +pub mod event_subscriber; pub mod explorer; #[cfg(feature = "openapi")] pub mod openapi_backend; @@ -52,6 +53,7 @@ pub use crate::adapters::{ // Re-exports: client pub use crate::client::{A2AClient, A2AClientError, AgentCardFetcher, ClientResult}; +pub use crate::event_subscriber::{register_a2a_subscriber, A2AEventSubscriber}; // Re-exports: OpenAPI backend (feature `openapi`) #[cfg(feature = "openapi")] diff --git a/a2a/rust/src/openapi_backend.rs b/a2a/rust/src/openapi_backend.rs index bf3e5ae7..0a80b1a1 100644 --- a/a2a/rust/src/openapi_backend.rs +++ b/a2a/rust/src/openapi_backend.rs @@ -549,10 +549,7 @@ pub async fn openapi_backend( } // --- Collision preflight, over the FULL set, before the first write ------ - // Toolkit writers report per-module `WriteResult`s and never abort, so - // without this a duplicate arrives as a failed WriteResult, gets logged and - // skipped, and leaves a partial registry: a skill the document advertises, - // absent from the card, with one log line as the only notice. + // A collision leaves the registry untouched and reports every colliding ID. let existing = registry.list(None, None, Some(&["public", "hidden"])); let mut collisions: Vec = modules .iter() @@ -601,13 +598,30 @@ pub async fn openapi_backend( ) .map_err(|e| APCoreA2AError::Config(format!("apcore-a2a.openapi: {e}")))?; - for result in writer.write(&modules, ®istry) { - if let Some(error) = result.verification_error { - tracing::error!( - "apcore-a2a: {} failed to register as an HTTP proxy: {error}", - result.module_id - ); + let results: HashMap<_, _> = writer + .write(&modules, ®istry) + .into_iter() + .map(|result| (result.module_id.clone(), result)) + .collect(); + let mut failures = Vec::new(); + for module in &modules { + let id = &module.module_id; + let result = results.get(id); + if result.is_some_and(|result| result.verified) + && registry.get(id).is_ok_and(|module| module.is_some()) + { + continue; } + let detail = result + .and_then(|result| result.verification_error.as_deref()) + .unwrap_or("module not registered"); + failures.push(format!("{id}: {detail}")); + } + if !failures.is_empty() { + return Err(APCoreA2AError::Config(format!( + "OpenAPI registration incomplete: {}", + failures.join("; ") + ))); } warn_unapproved_writes( diff --git a/a2a/rust/src/server/executor.rs b/a2a/rust/src/server/executor.rs index fdebba4a..64bc40a9 100644 --- a/a2a/rust/src/server/executor.rs +++ b/a2a/rust/src/server/executor.rs @@ -69,6 +69,10 @@ impl ApCoreAgentExecutor { &self.part_converter } + pub(crate) fn execution_timeout(&self) -> Duration { + Duration::from_secs(self.execution_timeout_secs) + } + /// The apcore ACL backing this executor, if one is configured. Lets the /// Agent Card advertise only the skills a caller is allowed to invoke. pub fn acl(&self) -> Option> { @@ -188,14 +192,17 @@ impl ApCoreAgentExecutor { identity: Option, cancel_token: CancelToken, ) -> Result { - let ctx = self.build_context(identity, cancel_token); + let ctx = self.build_context(identity, cancel_token.clone()); let fut = self.executor.call(module_id, inputs, Some(&ctx), None); - match tokio::time::timeout(Duration::from_secs(self.execution_timeout_secs), fut).await { + match tokio::time::timeout(self.execution_timeout(), fut).await { Ok(result) => result, - Err(_) => Err(ModuleError::new( - ErrorCode::ModuleTimeout, - "Execution timed out", - )), + Err(_) => { + cancel_token.cancel(); + Err(ModuleError::new( + ErrorCode::ModuleTimeout, + "Execution timed out", + )) + } } } @@ -214,9 +221,10 @@ impl ApCoreAgentExecutor { cancel_token: CancelToken, ) -> ReceiverStream> { let executor = self.executor.clone(); - let ctx = self.build_context(identity, cancel_token); - let (tx, rx) = mpsc::channel::>(16); - let timeout = Duration::from_secs(self.execution_timeout_secs); + let ctx = self.build_context(identity, cancel_token.clone()); + let (tx, rx) = mpsc::channel::>(17); + let timeout_slot = tx.clone().try_reserve_owned().ok(); + let timeout = self.execution_timeout(); tokio::spawn(async move { // A hard host-side timeout bounds the *entire* stream lifetime, in @@ -234,15 +242,17 @@ impl ApCoreAgentExecutor { } } }; - if tokio::time::timeout(timeout, drive).await.is_err() { - // Total budget elapsed: surface a timeout chunk so the handler - // emits a failed "Execution timed out" status (Python/TS parity). - let _ = tx - .send(Err(ModuleError::new( - ErrorCode::ModuleTimeout, - "Execution timed out", - ))) - .await; + tokio::select! { + biased; + _ = tx.closed() => cancel_token.cancel(), + result = tokio::time::timeout(timeout, drive) => { + if result.is_err() { + cancel_token.cancel(); + if let Some(slot) = timeout_slot { + slot.send(Err(ModuleError::new(ErrorCode::ModuleTimeout, "Execution timed out"))); + } + } + } } }); diff --git a/a2a/rust/src/server/factory.rs b/a2a/rust/src/server/factory.rs index 866c40f5..ba7784f1 100644 --- a/a2a/rust/src/server/factory.rs +++ b/a2a/rust/src/server/factory.rs @@ -241,7 +241,7 @@ impl A2AServerFactory { agent_card: public_card_value, extended_card, explorer_card, - cancel_tokens: Arc::new(Mutex::new(HashMap::new())), + running_tasks: Arc::new(Mutex::new(HashMap::new())), push_config_store, http: reqwest::Client::new(), }; diff --git a/a2a/rust/src/server/handlers.rs b/a2a/rust/src/server/handlers.rs index c1ecaaca..b091c6db 100644 --- a/a2a/rust/src/server/handlers.rs +++ b/a2a/rust/src/server/handlers.rs @@ -23,7 +23,7 @@ use axum::{ Json, }; use serde_json::{json, Value}; -use tokio::sync::mpsc; +use tokio::sync::{mpsc, watch}; use tokio_stream::wrappers::ReceiverStream; use tokio_stream::StreamExt; use uuid::Uuid; @@ -64,7 +64,7 @@ pub struct AppState { /// Filtered per caller like the extended card: the Explorer sits behind the /// auth middleware whenever one is configured. pub(crate) explorer_card: Arc, - pub(crate) cancel_tokens: Arc>>, + pub(crate) running_tasks: Arc>>>, /// Per-task push-notification webhook configs /// (`tasks/pushNotificationConfig/*`), scoped to their owner by the store. pub(crate) push_config_store: Arc, @@ -715,7 +715,7 @@ async fn fail_task( context_id: &str, ctx: &CallContext, message: impl Into, -) -> Value { +) -> Result { let status = TaskStatus::with_message(TaskState::Failed, Message::agent_text(message)); let task = Task { id: task_id.to_string(), @@ -725,7 +725,7 @@ async fn fail_task( history: vec![], }; let task_json = serde_json::to_value(&task).unwrap(); - save_task(state, task_id, task_json.clone(), ctx).await; + save_task(state, task_id, task_json.clone(), ctx).await?; notify_push( state, task_id, @@ -737,7 +737,7 @@ async fn fail_task( }), ) .await; - task_json + Ok(task_json) } /// Emit a task-level failure as an SSE stream (SUBMITTED then terminal FAILED), @@ -759,7 +759,11 @@ async fn failed_task_stream( artifacts: vec![], history: vec![], }; - save_task(state, &task_id, serde_json::to_value(&task).unwrap(), ctx).await; + if let Err((code, message)) = + save_task(state, &task_id, serde_json::to_value(&task).unwrap(), ctx).await + { + return Json(rpc_error(&id, code, &message)).into_response(); + } let terminal = StreamEvent::StatusUpdate(TaskStatusUpdateEvent { task_id: task_id.clone(), context_id: context_id.clone(), @@ -805,25 +809,24 @@ async fn handle_send( task_id, context_id, message, - }) => return Ok(fail_task(state, &task_id, &context_id, ctx, message).await), + }) => return fail_task(state, &task_id, &context_id, ctx, message).await, }; // Reject unknown skills with a FAILED task (Python/TS parity). if !state.skill_ids.contains(&skill_id) { - return Ok(fail_task( + return fail_task( state, &task_id, &context_id, ctx, format!("Skill not found: {skill_id}"), ) - .await); + .await; } let mut task = submitted_task(&task_id, &context_id); - let cancel = CancelToken::new(); - register_cancel(state, &task_id, cancel.clone()); + let execution = register_execution(state, &task_id); // Unregister the cancel token on every exit path (success, error, panic); // a Drop guard mirrors handle_stream and avoids leaking the token. let _cancel_guard = CancelGuard { @@ -831,13 +834,20 @@ async fn handle_send( task_id: task_id.clone(), }; - save_task(state, &task_id, serde_json::to_value(&task).unwrap(), ctx).await; + save_task(state, &task_id, serde_json::to_value(&task).unwrap(), ctx).await?; let result = state .executor - .call(&skill_id, inputs, identity, cancel) + .call(&skill_id, inputs, identity, execution.token.clone()) .await; + let terminal = execution.terminal.lock().await; + if execution.canceled_status().is_some() { + return read_task(state, &task_id, ctx) + .await? + .ok_or((CODE_TASK_NOT_FOUND, "Task not found".to_string())); + } + match result { Ok(output) => { let artifact = state @@ -852,11 +862,8 @@ async fn handle_send( } } let task_json = serde_json::to_value(&task).unwrap(); - state - .task_store - .save(&task_id, task_json.clone(), ctx) - .await - .map_err(|e| store_failure(&format!("task store write for {task_id}"), e))?; + save_task(state, &task_id, task_json.clone(), ctx).await?; + drop(terminal); // Deliver the terminal status to any registered webhook. notify_push( @@ -893,15 +900,19 @@ async fn handle_stream( }) => return failed_task_stream(state, task_id, context_id, ctx, id, message).await, }; - let cancel = CancelToken::new(); - register_cancel(state, &task_id, cancel.clone()); + let execution = register_execution(state, &task_id); - let (tx, rx) = mpsc::channel::(16); + // Reserve capacity for the terminal status and successful end marker. + // Artifact backpressure must not block either after the decision is made. + let (tx, rx) = mpsc::channel::(18); + let terminal_slot = tx.clone().try_reserve_owned().ok(); + let marker_slot = tx.clone().try_reserve_owned().ok(); let state2 = state.clone(); // The spawned task outlives this call, so it needs an owned context to // scope its own stores writes and webhook lookup. let ctx2 = ctx.clone(); let skill_known = state.skill_ids.contains(&skill_id); + let started = tokio::time::Instant::now(); tokio::spawn(async move { // Unregister the cancel token on every exit path (success, error, panic). @@ -909,20 +920,33 @@ async fn handle_stream( state: state2.clone(), task_id: task_id.clone(), }; - let send = |ev: StreamEvent| { - let tx = tx.clone(); - async move { - let _ = tx.send(ev).await; + let mut task = submitted_task(&task_id, &context_id); + if skill_known { + task.status = TaskStatus::new(TaskState::Working); + if let Err(error) = save_task( + &state2, + &task_id, + serde_json::to_value(&task).unwrap(), + &ctx2, + ) + .await + { + publish_stream_storage_error(terminal_slot, &id, error); + return; } - }; + } // submitted → working - send(StreamEvent::StatusUpdate(TaskStatusUpdateEvent { - task_id: task_id.clone(), - context_id: context_id.clone(), - status: TaskStatus::new(TaskState::Submitted), - })) - .await; + let _ = tx + .send(sse_event( + &id, + &StreamEvent::StatusUpdate(TaskStatusUpdateEvent { + task_id: task_id.clone(), + context_id: context_id.clone(), + status: TaskStatus::new(TaskState::Submitted), + }), + )) + .await; // Reject unknown skills with a terminal FAILED status (Python/TS parity). if !skill_known { @@ -937,115 +961,177 @@ async fn handle_stream( artifacts: vec![], history: vec![], }; - save_task( + if let Err(error) = save_task( &state2, &task_id, serde_json::to_value(&task).unwrap(), &ctx2, ) - .await; + .await + { + publish_stream_storage_error(terminal_slot, &id, error); + return; + } let terminal_event = StreamEvent::StatusUpdate(TaskStatusUpdateEvent { task_id: task_id.clone(), context_id: context_id.clone(), status, }); + if let Some(slot) = terminal_slot { + slot.send(sse_event(&id, &terminal_event)); + } + drop(marker_slot); + drop(tx); notify_push(&state2, &task_id, &ctx2, &terminal_event).await; - send(terminal_event).await; return; } - send(StreamEvent::StatusUpdate(TaskStatusUpdateEvent { - task_id: task_id.clone(), - context_id: context_id.clone(), - status: TaskStatus::new(TaskState::Working), - })) - .await; + let _ = tx + .send(sse_event( + &id, + &StreamEvent::StatusUpdate(TaskStatusUpdateEvent { + task_id: task_id.clone(), + context_id: context_id.clone(), + status: task.status.clone(), + }), + )) + .await; - let mut chunks = state2 + let remaining = state2 .executor - .stream_channel(skill_id, inputs, identity, cancel); - let mut idx: usize = 0; - let mut error: Option = None; - - while let Some(item) = chunks.next().await { - match item { - Ok(chunk) => { - // task_id is always a fresh uuid here, so the artifact id is - // stable (`art-{task_id}`) across chunks. - let artifact = state2 - .executor - .part_converter() - .output_to_parts(&chunk, &task_id); - send(StreamEvent::ArtifactUpdate(TaskArtifactUpdateEvent { - task_id: task_id.clone(), - context_id: context_id.clone(), - artifact, - append: idx > 0, - last_chunk: false, - })) - .await; - idx += 1; + .execution_timeout() + .saturating_sub(started.elapsed()); + let forward = async { + if remaining.is_zero() { + return Err(Box::new(ModuleError::new( + ErrorCode::ModuleTimeout, + "Execution timed out", + ))); + } + let chunks = + state2 + .executor + .stream_channel(skill_id, inputs, identity, execution.token.clone()); + forward_artifacts(&state2, &task, chunks, &tx, &id).await + }; + let mut canceled = execution.client_canceled.subscribe(); + let (status, append_marker) = tokio::select! { + biased; + _ = canceled.wait_for(Option::is_some) => (canceled_by_client(), None), + _ = tx.closed() => { + execution.token.cancel(); + (TaskStatus::with_message(TaskState::Canceled, Message::agent_text("Client disconnected")), None) + } + result = tokio::time::timeout(remaining, forward) => match result { + Ok(Ok(append)) => (TaskStatus::new(TaskState::Completed), Some(append)), + Ok(Err(error)) => (error_to_status(&error, state2.executor.disclose_refusal_reason()), None), + Err(_) => { + execution.token.cancel(); + (TaskStatus::with_message(TaskState::Failed, Message::agent_text("Execution timed out")), None) } - Err(e) => { - error = Some(e); - break; + }, + }; + // Serialize the terminal store write with tasks/cancel. The accepted + // cancel path already persisted the status and owns push delivery. + let notify = { + let _terminal = execution.terminal.lock().await; + if let Some(canceled) = execution.canceled_status() { + task.status = canceled; + false + } else { + task.status = status; + if let Err(error) = save_task( + &state2, + &task_id, + serde_json::to_value(&task).unwrap(), + &ctx2, + ) + .await + { + publish_stream_storage_error(terminal_slot, &id, error); + return; } + true } - } - - // On successful completion, emit a terminal empty-artifact marker - // (last_chunk=true, art-{task_id}) before the COMPLETED status — required - // by the A2A streaming contract (streaming.md "Final chunk: lastChunk=True") - // and matching Python/TS. Errors skip the marker and go straight to FAILED. - if error.is_none() { - send(StreamEvent::ArtifactUpdate(TaskArtifactUpdateEvent { - task_id: task_id.clone(), - context_id: context_id.clone(), - artifact: Artifact::new(format!("art-{task_id}"), vec![]), - append: idx > 0, - last_chunk: true, - })) - .await; - } - - let final_status = match &error { - None => TaskStatus::new(TaskState::Completed), - Some(e) => error_to_status(e, state2.executor.disclose_refusal_reason()), }; - // Persist terminal task. - let task = Task { - id: task_id.clone(), - context_id: context_id.clone(), - status: final_status.clone(), - artifacts: vec![], - history: vec![], - }; - save_task( - &state2, - &task_id, - serde_json::to_value(&task).unwrap(), - &ctx2, - ) - .await; + // A client cancel that beat the terminal store write suppresses the + // successful marker just as it suppresses the completed status. + if let (true, Some(append), Some(slot)) = (notify, append_marker, marker_slot) { + slot.send(sse_event( + &id, + &StreamEvent::ArtifactUpdate(TaskArtifactUpdateEvent { + task_id: task_id.clone(), + context_id: context_id.clone(), + artifact: Artifact::new(format!("art-{task_id}"), vec![]), + append, + last_chunk: true, + }), + )); + } let terminal_event = StreamEvent::StatusUpdate(TaskStatusUpdateEvent { task_id: task_id.clone(), - context_id: context_id.clone(), - status: final_status, + context_id, + status: task.status, }); - // Deliver the terminal status to any registered webhook. - notify_push(&state2, &task_id, &ctx2, &terminal_event).await; - send(terminal_event).await; + if let Some(slot) = terminal_slot { + slot.send(sse_event(&id, &terminal_event)); + } + drop(tx); + if notify { + notify_push(&state2, &task_id, &ctx2, &terminal_event).await; + } // `_cancel_guard` unregisters the cancel token on drop (all exit paths). }); - let event_stream = - ReceiverStream::new(rx).map(move |ev| Ok::(sse_event(&id, &ev))); + let event_stream = ReceiverStream::new(rx).map(Ok::); Sse::new(event_stream) .keep_alive(KeepAlive::default()) .into_response() } +fn publish_stream_storage_error( + slot: Option>, + id: &Value, + error: (i32, String), +) { + if let Some(slot) = slot { + slot.send(Event::default().data(rpc_error(id, error.0, &error.1).to_string())); + } +} + +/// Forward artifacts within the same host budget, including slow SSE writes. +async fn forward_artifacts( + state: &AppState, + task: &Task, + mut chunks: ReceiverStream>, + tx: &mpsc::Sender, + id: &Value, +) -> Result> { + let mut append = false; + while let Some(item) = chunks.next().await { + let chunk = item.map_err(Box::new)?; + let artifact = state + .executor + .part_converter() + .output_to_parts(&chunk, &task.id); + let _ = tx + .send(sse_event( + id, + &StreamEvent::ArtifactUpdate(TaskArtifactUpdateEvent { + task_id: task.id.clone(), + context_id: task.context_id.clone(), + artifact, + append, + last_chunk: false, + }), + )) + .await; + append = true; + } + Ok(append) +} + /// `tasks/get` — return a stored task by id, if the caller owns it. async fn handle_get( state: &AppState, @@ -1060,11 +1146,9 @@ async fn handle_get( // `ctx.owner()`. Masked as "not found" rather than "forbidden", matching // how ACL denials are reported (srs FR-ERR-003): a caller must not learn // that another principal's task id exists. - match state.task_store.get(task_id, ctx).await { - Ok(Some(task)) => Ok(task), - Ok(None) => Err((CODE_TASK_NOT_FOUND, "Task not found".to_string())), - Err(e) => Err(store_failure(&format!("task store read for {task_id}"), e)), - } + read_task(state, task_id, ctx) + .await? + .ok_or((CODE_TASK_NOT_FOUND, "Task not found".to_string())) } /// `ListTasks` — return the calling principal's tasks. @@ -1104,13 +1188,17 @@ async fn handle_cancel( "Missing required parameter: id".to_string(), ))?; + let execution = state.running_tasks.lock().unwrap().get(task_id).cloned(); + let terminal = match &execution { + Some(execution) => Some(execution.terminal.lock().await), + None => None, + }; + // Another principal's task reads back as absent, so it is reported as // missing rather than as forbidden. - let stored = match state.task_store.get(task_id, ctx).await { - Ok(Some(stored)) => stored, - Ok(None) => return Err((CODE_TASK_NOT_FOUND, "Task not found".to_string())), - Err(e) => return Err(store_failure(&format!("task store read for {task_id}"), e)), - }; + let stored = read_task(state, task_id, ctx) + .await? + .ok_or((CODE_TASK_NOT_FOUND, "Task not found".to_string()))?; // A task whose stored JSON cannot be read back is unusable, not cancelable. let mut task: Task = serde_json::from_value(stored) @@ -1127,28 +1215,21 @@ async fn handle_cancel( )); } - if let Some(token) = state.cancel_tokens.lock().unwrap().remove(task_id) { - token.cancel(); - } - // Update in place: artifacts and history a non-terminal task already // accumulated belong to it and survive the cancellation. - task.status = TaskStatus::with_message( - TaskState::Canceled, - Message::agent_text("Canceled by client"), - ); + task.status = canceled_by_client(); let context_id = task.context_id.clone(); let task_json = serde_json::to_value(&task).unwrap(); - // Cancelling *is* this write, so unlike the send/stream paths a failure - // here is not "work happened but could not be recorded" — it is the - // operation failing. Answering CANCELED anyway would leave the caller - // believing a task is cancelled while the store still reads WORKING. The - // cancel token is already signalled, so retrying is the right response. - state - .task_store - .save(task_id, task_json.clone(), ctx) - .await - .map_err(|e| store_failure(&format!("task store write for {task_id}"), e))?; + // Persist the accepted cancellation before waking the worker. The store + // write is serialized with local execution's competing terminal write. + save_task(state, task_id, task_json.clone(), ctx).await?; + if let Some(execution) = &execution { + execution + .client_canceled + .send_replace(Some(task.status.clone())); + execution.token.cancel(); + } + drop(terminal); // Deliver the terminal CANCELED status to any registered webhook. notify_push( @@ -1257,13 +1338,16 @@ async fn handle_push_delete( /// Deliver an event to a task's registered webhook (if any), retrying with /// exponential backoff. Fire-and-forget: spawned so it never blocks the caller. async fn notify_push(state: &AppState, task_id: &str, ctx: &CallContext, event: &StreamEvent) { - let cfg = match state.push_config_store.get(task_id, ctx).await { + let cfg = match store_operation( + state, + &format!("push config store read for {task_id}"), + state.push_config_store.get(task_id, ctx), + ) + .await + { Ok(Some(c)) => c, Ok(None) => return, - Err(e) => { - tracing::warn!("push config store read failed for {task_id}: {e}"); - return; - } + Err(_) => return, }; let url = match cfg.get("url").and_then(Value::as_str) { Some(u) => u.to_string(), @@ -1311,30 +1395,82 @@ fn store_failure(what: &str, e: StoreError) -> (i32, String) { (CODE_INTERNAL_ERROR, "Internal server error".to_string()) } -/// Persist a task, logging rather than propagating a store failure. -/// -/// Every call site here has already run the task to a known state, so a failed -/// write cannot change what is returned to the caller — turning it into a -/// JSON-RPC error would report "failed" for work that actually succeeded. It -/// must not stay silent either: previously each of these was a bare `let _ =`, -/// so a store outage produced tasks that `message/send` reported as COMPLETED -/// and `tasks/get` then reported as missing, with nothing logged in between. -async fn save_task(state: &AppState, task_id: &str, task: Value, ctx: &CallContext) { - if let Err(e) = state.task_store.save(task_id, task, ctx).await { - tracing::warn!("task store write failed for {task_id}: {e}"); +async fn store_operation( + state: &AppState, + operation: &str, + future: impl std::future::Future>, +) -> Result { + // Each store operation has a bounded budget of its own. A failed or timed-out + // execution still needs a chance to durably record its terminal state. + match tokio::time::timeout(state.executor.execution_timeout(), future).await { + Ok(Ok(value)) => Ok(value), + Ok(Err(error)) => Err(store_failure(operation, error)), + Err(_) => Err(store_failure( + operation, + StoreError::backend_msg("operation timed out"), + )), } } -fn register_cancel(state: &AppState, task_id: &str, token: CancelToken) { +async fn save_task( + state: &AppState, + task_id: &str, + task: Value, + ctx: &CallContext, +) -> Result<(), (i32, String)> { + store_operation( + state, + &format!("task store write for {task_id}"), + state.task_store.save(task_id, task, ctx), + ) + .await +} + +async fn read_task( + state: &AppState, + task_id: &str, + ctx: &CallContext, +) -> Result, (i32, String)> { + store_operation( + state, + &format!("task store read for {task_id}"), + state.task_store.get(task_id, ctx), + ) + .await +} + +fn canceled_by_client() -> TaskStatus { + TaskStatus::with_message( + TaskState::Canceled, + Message::agent_text("Canceled by client"), + ) +} + +pub(crate) struct TaskExecution { + token: CancelToken, + client_canceled: watch::Sender>, + terminal: tokio::sync::Mutex<()>, +} + +impl TaskExecution { + fn canceled_status(&self) -> Option { + self.client_canceled.borrow().clone() + } +} + +fn register_execution(state: &AppState, task_id: &str) -> Arc { + let (client_canceled, _) = watch::channel(None); + let execution = Arc::new(TaskExecution { + token: CancelToken::new(), + client_canceled, + terminal: tokio::sync::Mutex::new(()), + }); state - .cancel_tokens + .running_tasks .lock() .unwrap() - .insert(task_id.to_string(), token); -} - -fn unregister_cancel(state: &AppState, task_id: &str) { - state.cancel_tokens.lock().unwrap().remove(task_id); + .insert(task_id.to_string(), execution.clone()); + execution } /// Drop guard that unregisters a task's cancel token on all exit paths @@ -1346,7 +1482,11 @@ struct CancelGuard { impl Drop for CancelGuard { fn drop(&mut self) { - unregister_cancel(&self.state, &self.task_id); + self.state + .running_tasks + .lock() + .unwrap() + .remove(&self.task_id); } } diff --git a/a2a/rust/tests/conformance.rs b/a2a/rust/tests/conformance.rs index 65da2a41..37821c52 100644 --- a/a2a/rust/tests/conformance.rs +++ b/a2a/rust/tests/conformance.rs @@ -248,14 +248,12 @@ async fn collect_sse(router: axum::Router, body: Value) -> Vec { /// Every fixture in the spec repo that this crate claims to drive. /// -/// All but one are driven by this file. `openapi_backend.json` is driven by -/// `tests/openapi_backend_conformance.rs`, because the whole backend sits behind -/// the `openapi` cargo feature and its driver has to be gated with it — but the -/// guard below still refuses to let the *file* go undriven, and the second -/// assertion below refuses to let the driver go missing. +/// External drivers are listed separately so the guard checks that their +/// test binaries exist as well as the fixtures themselves. const DRIVEN_FIXTURES: &[&str] = &[ "agent_card.json", "error_mapping.json", + "event_subscriber.json", "jwt_claim_coercion.json", // Driven by tests/openapi_backend_conformance.rs (feature `openapi`). "openapi_backend.json", @@ -268,10 +266,16 @@ const DRIVEN_FIXTURES: &[&str] = &[ /// /// Listing a name in `DRIVEN_FIXTURES` is a claim; for a fixture this file does /// not itself load, the claim is checked by requiring the driver to exist. -const EXTERNAL_DRIVERS: &[(&str, &str)] = &[( - "openapi_backend.json", - "tests/openapi_backend_conformance.rs", -)]; +const EXTERNAL_DRIVERS: &[(&str, &str)] = &[ + ( + "event_subscriber.json", + "tests/event_subscriber_conformance.rs", + ), + ( + "openapi_backend.json", + "tests/openapi_backend_conformance.rs", + ), +]; #[test] fn every_spec_fixture_has_a_driver() { diff --git a/a2a/rust/tests/event_subscriber_conformance.rs b/a2a/rust/tests/event_subscriber_conformance.rs new file mode 100644 index 00000000..2a7e6ee8 --- /dev/null +++ b/a2a/rust/tests/event_subscriber_conformance.rs @@ -0,0 +1,251 @@ +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use apcore::{ + create_subscriber, reset_subscriber_registry, APCore, ApCoreEvent, Config, EventSubscriber, + ModuleError, +}; +use apcore_a2a::{register_a2a_subscriber, A2AEventSubscriber}; +use axum::{extract::State, http::HeaderMap, http::StatusCode, routing::post, Json, Router}; +use serde::Deserialize; +use serde_json::{json, Value}; +use tokio::net::TcpListener; + +const DEAD_LETTER: &str = "apcore.event.delivery_failed"; +const CIRCUIT_OPENED: &str = "apcore.subscriber.circuit_opened"; + +#[derive(Deserialize)] +struct Fixture { + event: ApCoreEvent, + test_cases: Vec, +} + +#[derive(Deserialize)] +struct FixtureCase { + id: String, + subscriber: Value, + status: u16, + #[serde(default)] + delay_ms: u64, + expected: Expected, +} + +#[derive(Deserialize)] +struct Expected { + requests: usize, + authorization: Option, + source: Option, + skill_id: Option, + dead_letters: usize, + circuit_opened: usize, +} + +#[derive(Debug)] +struct DiagnosticRecorder { + event_type: &'static str, + events: Arc>>, +} + +#[async_trait::async_trait] +impl EventSubscriber for DiagnosticRecorder { + fn event_pattern(&self) -> &str { + self.event_type + } + + async fn on_event(&self, event: &ApCoreEvent) -> Result<(), ModuleError> { + self.events.lock().unwrap().push(event.clone()); + Ok(()) + } +} + +struct ReceiverState { + requests: Mutex>, + status: StatusCode, + delay_ms: u64, +} + +async fn record_request( + State(state): State>, + headers: HeaderMap, + Json(payload): Json, +) -> StatusCode { + state.requests.lock().unwrap().push((headers, payload)); + if state.delay_ms > 0 { + tokio::time::sleep(Duration::from_millis(state.delay_ms)).await; + } + state.status +} + +async fn emit_from_config(subscriber: &Value, event: &ApCoreEvent) -> Vec { + let project = tempfile::tempdir().unwrap(); + let path = project.path().join("apcore.yaml"); + std::fs::write( + &path, + format!( + "version: '1.0.0'\nproject: {{name: event-test}}\nextensions: {{auto_discover: false}}\n\ + sys_modules:\n enabled: true\n events:\n enabled: true\n subscribers: [{}]\n", + serde_json::to_string(subscriber).unwrap() + ), + ) + .unwrap(); + let client = APCore::with_config(Config::load(&path).unwrap()); + let events = client.events().expect("configured event bus"); + let captured = Arc::new(Mutex::new(Vec::new())); + for event_type in [DEAD_LETTER, CIRCUIT_OPENED] { + events.subscribe(Box::new(DiagnosticRecorder { + event_type, + events: Arc::clone(&captured), + })); + } + events.emit(event).await; + tokio::time::timeout(Duration::from_secs(5), async { + events.flush(0).await.unwrap(); + // A failed delivery can queue a circuit lifecycle event during flush. + events.flush(0).await.unwrap(); + }) + .await + .expect("event delivery settles"); + let diagnostics = captured.lock().unwrap().clone(); + diagnostics +} + +async fn run_case(case: &FixtureCase, event: &ApCoreEvent) { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}/receive", listener.local_addr().unwrap()); + let state = Arc::new(ReceiverState { + requests: Mutex::new(Vec::new()), + status: StatusCode::from_u16(case.status).unwrap(), + delay_ms: case.delay_ms, + }); + let app = Router::new() + .route("/receive", post(record_request)) + .with_state(Arc::clone(&state)); + let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + let mut subscriber = case.subscriber.clone(); + if subscriber["type"] == "filter" { + subscriber["delegate_config"] = json!({ "platform_url": url }); + } else { + subscriber["id"] = json!("configured-a2a"); + subscriber["platform_url"] = json!(url); + } + + register_a2a_subscriber(); + register_a2a_subscriber(); + let diagnostics = emit_from_config(&subscriber, event).await; + assert_eq!( + diagnostics + .iter() + .filter(|event| event.event_type == DEAD_LETTER) + .count(), + case.expected.dead_letters, + "{}: {diagnostics:?}", + case.id + ); + assert_eq!( + diagnostics + .iter() + .filter(|event| event.event_type == CIRCUIT_OPENED) + .count(), + case.expected.circuit_opened, + "{}: {diagnostics:?}", + case.id + ); + for diagnostic in diagnostics { + assert_eq!(diagnostic.data["subscriber_type"], "a2a", "{}", case.id); + assert_eq!( + diagnostic.data["subscriber_id"], "configured-a2a", + "{}", + case.id + ); + } + { + let requests = state.requests.lock().unwrap(); + assert_eq!(requests.len(), case.expected.requests, "{}", case.id); + for (headers, payload) in requests.iter() { + let header = |name: &str| headers.get(name).map(|value| value.to_str().unwrap()); + assert_eq!( + header("content-type"), + Some("application/json"), + "{}", + case.id + ); + assert_eq!( + header("authorization"), + case.expected.authorization.as_deref(), + "{}", + case.id + ); + assert_eq!( + header("x-source"), + case.expected.source.as_deref(), + "{}", + case.id + ); + assert_eq!( + payload, + &json!({"skillId": case.expected.skill_id, "event": event}), + "{}", + case.id + ); + } + } + + if case.id == "bearer_success" + && std::env::var("APCORE_A2A_VERIFY_LEGACY_HTTP") + .ok() + .as_deref() + == Some("1") + { + reset_subscriber_registry(); + assert!(emit_from_config(&subscriber, event).await.is_empty()); + let requests = state.requests.lock().unwrap(); + assert_eq!(requests.len(), 2); + assert_eq!( + requests[0].0["authorization"], + requests[1].0["authorization"] + ); + assert_eq!(requests[0].1, requests[1].1); + } + server.abort(); + let _ = server.await; +} + +struct RestoreBuiltins; + +impl Drop for RestoreBuiltins { + fn drop(&mut self) { + reset_subscriber_registry(); + } +} + +#[tokio::test] +async fn a2a_subscription_is_opt_in_and_uses_core_configured_delivery() { + let fixture: Fixture = serde_json::from_str(include_str!( + "../../conformance/fixtures/event_subscriber.json" + )) + .unwrap(); + reset_subscriber_registry(); + let _restore = RestoreBuiltins; + let config = json!({"type":"a2a", "platform_url":"https://example.com/receive"}); + assert!(format!("{:?}", create_subscriber(&config).unwrap()).starts_with("A2ASubscriber")); + assert_eq!( + A2AEventSubscriber::new("https://example.com/receive").subscriber_type(), + "a2a" + ); + register_a2a_subscriber(); + assert!(format!("{:?}", create_subscriber(&config).unwrap()).starts_with("A2AEventSubscriber")); + + let minimum_without_delivery = apcore::VERSION == "0.33.0" + && std::env::var("APCORE_A2A_REQUIRE_RELIABLE_DELIVERY") + .ok() + .as_deref() + != Some("1"); + for case in &fixture.test_cases { + if minimum_without_delivery && case.expected.dead_letters > 0 { + continue; + } + run_case(case, &fixture.event).await; + } + reset_subscriber_registry(); + assert!(format!("{:?}", create_subscriber(&config).unwrap()).starts_with("A2ASubscriber")); +} diff --git a/a2a/rust/tests/integration.rs b/a2a/rust/tests/integration.rs index 110c9d90..f8e3ef62 100644 --- a/a2a/rust/tests/integration.rs +++ b/a2a/rust/tests/integration.rs @@ -5,18 +5,294 @@ //! task execution against a real apcore `Registry` holding an echo module. use std::sync::Arc; +use std::time::Duration; use apcore::context::Context; use apcore::errors::{ErrorCode, ModuleError}; -use apcore::module::Module; +use apcore::module::{ChunkStream, Module}; use apcore::registry::registry::Registry; use apcore_a2a::{build_app, APCoreA2AConfig, BackendSource}; use async_trait::async_trait; use axum::body::{to_bytes, Body}; use axum::http::{Request, StatusCode}; +use futures_util::StreamExt; use serde_json::{json, Value}; use tower::ServiceExt; +struct StallingStream { + chunks: usize, + started: Arc, + closed: Arc, +} + +struct NotifyOnDrop(Arc); + +impl Drop for NotifyOnDrop { + fn drop(&mut self) { + self.0.notify_one(); + } +} + +#[async_trait] +impl Module for StallingStream { + fn input_schema(&self) -> Value { + json!({ "type": "object" }) + } + + fn output_schema(&self) -> Value { + json!({ "type": "object" }) + } + + fn description(&self) -> &str { + "Yields a chosen number of chunks and then stalls" + } + + async fn execute(&self, _: Value, _: &Context) -> Result { + panic!("the native streaming module must not run execute") + } + + fn stream(&self, _: Value, _: &Context) -> Option { + let chunks = self.chunks; + let started = self.started.clone(); + let closed = self.closed.clone(); + Some(Box::pin(async_stream::stream! { + let _closed = NotifyOnDrop(closed); + started.notify_one(); + for index in 0..chunks { + yield Ok(json!({ "chunk": index })); + } + std::future::pending::<()>().await; + })) + } +} + +async fn stalling_server( + chunks: usize, + timeout_secs: u64, +) -> ( + axum::Router, + Arc, + Arc, +) { + let started = Arc::new(tokio::sync::Notify::new()); + let closed = Arc::new(tokio::sync::Notify::new()); + let registry = Registry::new(); + registry + .register_module( + "test.stall", + Box::new(StallingStream { + chunks, + started: started.clone(), + closed: closed.clone(), + }), + ) + .expect("register stalling stream"); + let config = APCoreA2AConfig { + execution_timeout: timeout_secs, + ..Default::default() + }; + let (router, _) = build_app(BackendSource::Registry(Arc::new(registry)), config) + .await + .unwrap(); + (router, started, closed) +} + +async fn open_stalling_stream(router: axum::Router) -> (String, axum::body::BodyDataStream) { + let req = Request::builder() + .method("POST") + .uri("/") + .header("content-type", "application/json") + .body(Body::from( + json!({ + "jsonrpc": "2.0", "id": 1, "method": "message/stream", + "params": { + "message": {"messageId": "stall", "role": "ROLE_USER", "parts": [{"data": {}}]}, + "metadata": {"skillId": "test.stall"} + } + }) + .to_string(), + )) + .unwrap(); + let response = router.oneshot(req).await.unwrap(); + let mut stream = response.into_body().into_data_stream(); + let first = tokio::time::timeout(Duration::from_secs(2), stream.next()) + .await + .unwrap() + .unwrap() + .unwrap(); + let event = sse_frame(&first); + let id = event["statusUpdate"]["taskId"] + .as_str() + .unwrap() + .to_string(); + (id, stream) +} + +fn sse_frame(bytes: &[u8]) -> Value { + let text = std::str::from_utf8(bytes).unwrap(); + let line = text + .lines() + .find_map(|line| line.strip_prefix("data:")) + .unwrap(); + serde_json::from_str::(line.trim()).unwrap()["result"].clone() +} + +async fn remaining_stream_events(mut stream: axum::body::BodyDataStream) -> Vec { + tokio::time::timeout(Duration::from_secs(3), async { + let mut events = Vec::new(); + while let Some(bytes) = stream.next().await { + events.push(sse_frame(&bytes.unwrap())); + } + events + }) + .await + .expect("stream must terminate") +} + +#[tokio::test] +async fn stalled_stream_timeout_persists_despite_sse_backpressure() { + let (router, started, closed) = stalling_server(1000, 1).await; + let (id, stream) = open_stalling_stream(router.clone()).await; + tokio::time::timeout(Duration::from_secs(2), started.notified()) + .await + .unwrap(); + + // Leave the response body unread. The module will fill both bounded queues. + // tasks/get must observe FAILED by the deadline even though SSE cannot drain. + let task = tokio::time::timeout(Duration::from_secs(3), async { + loop { + let (_, task) = post_rpc( + router.clone(), + json!({ + "jsonrpc": "2.0", "id": 2, "method": "tasks/get", "params": {"id": id} + }), + ) + .await; + if task["result"]["status"]["state"] == "TASK_STATE_FAILED" { + break task; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("timeout state must be visible without draining the SSE body"); + assert_eq!( + task["result"]["status"]["message"]["parts"][0]["text"], + "Execution timed out" + ); + tokio::time::timeout(Duration::from_secs(2), closed.notified()) + .await + .unwrap(); + let events = remaining_stream_events(stream).await; + let terminal: Vec<_> = events + .iter() + .filter_map(|event| event["statusUpdate"]["status"]["state"].as_str()) + .filter(|state| *state != "TASK_STATE_WORKING") + .collect(); + assert_eq!(terminal, ["TASK_STATE_FAILED"]); + assert_eq!( + events.last().unwrap()["statusUpdate"]["status"]["state"], + "TASK_STATE_FAILED" + ); + assert!(events + .iter() + .all(|event| event["artifactUpdate"]["lastChunk"] != true)); +} + +#[tokio::test] +async fn disconnected_stalled_stream_drops_the_producer_before_deadline() { + let (router, started, closed) = stalling_server(0, 30).await; + let (id, stream) = open_stalling_stream(router.clone()).await; + tokio::time::timeout(Duration::from_secs(2), started.notified()) + .await + .unwrap(); + drop(stream); + tokio::time::timeout(Duration::from_secs(2), closed.notified()) + .await + .expect("disconnect must drop the producer promptly"); + + let (_, task) = post_rpc( + router, + json!({ + "jsonrpc": "2.0", "id": 2, "method": "tasks/get", "params": {"id": id} + }), + ) + .await; + assert_eq!(task["result"]["status"]["state"], "TASK_STATE_CANCELED"); +} + +#[tokio::test] +async fn stalled_stream_timeout_terminates_before_or_after_first_artifact() { + for chunk_count in [0, 1] { + let (router, _, closed) = stalling_server(chunk_count, 1).await; + let (id, stream) = open_stalling_stream(router.clone()).await; + let events = remaining_stream_events(stream).await; + tokio::time::timeout(Duration::from_secs(2), closed.notified()) + .await + .expect("timed out producer must be dropped"); + let artifacts: Vec<_> = events + .iter() + .filter_map(|event| event.get("artifactUpdate")) + .collect(); + assert_eq!(artifacts.len(), chunk_count); + assert!(artifacts.iter().all(|event| event["lastChunk"] == false)); + assert_eq!( + events.last().unwrap()["statusUpdate"]["status"]["state"], + "TASK_STATE_FAILED" + ); + let (_, task) = post_rpc( + router, + json!({ + "jsonrpc": "2.0", "id": 2, "method": "tasks/get", "params": {"id": id} + }), + ) + .await; + assert_eq!(task["result"]["status"]["state"], "TASK_STATE_FAILED"); + } +} + +#[tokio::test] +async fn client_cancel_persists_one_terminal_before_a_stalled_stream_deadline() { + let (router, started, closed) = stalling_server(0, 30).await; + let (id, stream) = open_stalling_stream(router.clone()).await; + tokio::time::timeout(Duration::from_secs(2), started.notified()) + .await + .unwrap(); + let (_, canceled) = post_rpc( + router.clone(), + json!({ + "jsonrpc": "2.0", "id": 2, "method": "tasks/cancel", "params": {"id": id} + }), + ) + .await; + assert_eq!(canceled["result"]["status"]["state"], "TASK_STATE_CANCELED"); + tokio::time::timeout(Duration::from_secs(2), closed.notified()) + .await + .unwrap(); + + let events = remaining_stream_events(stream).await; + let statuses: Vec<_> = events + .iter() + .filter_map(|event| event["statusUpdate"]["status"]["state"].as_str()) + .collect(); + assert_eq!(statuses, ["TASK_STATE_WORKING", "TASK_STATE_CANCELED"]); + assert_eq!( + events.last().unwrap()["statusUpdate"]["status"], + canceled["result"]["status"] + ); + assert!(events + .iter() + .all(|event| event.get("artifactUpdate").is_none())); + let (_, task) = post_rpc( + router, + json!({ + "jsonrpc": "2.0", "id": 3, "method": "tasks/get", "params": {"id": id} + }), + ) + .await; + assert_eq!(task["result"]["status"], canceled["result"]["status"]); +} + /// Minimal echo module: returns its inputs unchanged. struct EchoModule; diff --git a/a2a/rust/tests/openapi_backend_conformance.rs b/a2a/rust/tests/openapi_backend_conformance.rs index 62d80df0..7f42ffa9 100644 --- a/a2a/rust/tests/openapi_backend_conformance.rs +++ b/a2a/rust/tests/openapi_backend_conformance.rs @@ -1188,3 +1188,57 @@ async fn test_effective_openapi_registration_preflights_and_forwards_selected_op "GET /items/red%2Fblue?tag=red&tag=blue HTTP/1.1\r\n" ); } + +#[tokio::test] +async fn test_backend_refuses_startup_when_a_host_validator_rejects_a_scanned_module() { + use apcore::module::{Module, ValidationResult}; + use apcore::registry::registry::{ModuleDescriptor, ModuleValidator}; + use apcore::ValidationErrorDetail; + + struct RejectUpdate; + + impl ModuleValidator for RejectUpdate { + fn validate( + &self, + _module: &dyn Module, + descriptor: Option<&ModuleDescriptor>, + ) -> ValidationResult { + let mut result = ValidationResult::default(); + result.valid = + !descriptor.is_some_and(|descriptor| descriptor.module_id == "update_item"); + if !result.valid { + result.errors = vec![ValidationErrorDetail::message_only("rejected by host rule")]; + } + result + } + } + + let registry = Arc::new(Registry::new()); + registry.set_validator(Box::new(RejectUpdate)); + let document = json!({ + "openapi": "3.1.0", + "info": {"title": "Inventory", "version": "1"}, + "paths": { + "/items": {"get": {"operationId": "list_items", "summary": "List items", + "responses": {"200": {"description": "OK"}}}}, + "/updates": {"post": {"operationId": "update_item", "summary": "Update item", + "responses": {"200": {"description": "OK"}}}} + } + }); + let message = openapi_backend( + &document, + registry, + OpenAPIBackendOptions { + base_url: Some("http://127.0.0.1:1".to_string()), + acknowledge_unapproved_writes: true, + ..OpenAPIBackendOptions::new() + }, + ) + .await + .expect_err("incomplete assembly must not start") + .to_string(); + assert!( + message.contains("update_item") && message.contains("rejected by host rule"), + "{message}", + ); +} diff --git a/a2a/rust/tests/store_failures.rs b/a2a/rust/tests/store_failures.rs index a08b8e1f..08cd9e08 100644 --- a/a2a/rust/tests/store_failures.rs +++ b/a2a/rust/tests/store_failures.rs @@ -224,6 +224,128 @@ async fn post(router: axum::Router, body: Value) -> Value { serde_json::from_slice(&bytes).unwrap() } +#[derive(Clone, Copy, PartialEq, Eq)] +enum StreamWriteFault { + InitialTimeout, + TerminalTimeout, + TerminalRejected, +} + +struct StreamFaultStore { + inner: InMemoryTaskStore, + fault: StreamWriteFault, +} + +#[async_trait] +impl TaskStore for StreamFaultStore { + async fn save(&self, id: &str, task: Value, ctx: &CallContext) -> Result<(), StoreError> { + let completed = task["status"]["state"] == "TASK_STATE_COMPLETED"; + match self.fault { + StreamWriteFault::InitialTimeout => std::future::pending().await, + StreamWriteFault::TerminalTimeout if completed => std::future::pending().await, + StreamWriteFault::TerminalRejected if completed => { + Err(StoreError::backend_msg("terminal write rejected")) + } + _ => self.inner.save(id, task, ctx).await, + } + } + + async fn get(&self, id: &str, ctx: &CallContext) -> Result, StoreError> { + self.inner.get(id, ctx).await + } + + async fn delete(&self, id: &str, ctx: &CallContext) -> Result<(), StoreError> { + self.inner.delete(id, ctx).await + } + + async fn list(&self, params: &ListParams, ctx: &CallContext) -> Result, StoreError> { + self.inner.list(params, ctx).await + } +} + +#[tokio::test] +async fn stream_does_not_publish_unconfirmed_terminal_state_or_wait_forever_on_storage() { + for fault in [ + StreamWriteFault::TerminalRejected, + StreamWriteFault::InitialTimeout, + StreamWriteFault::TerminalTimeout, + ] { + let registry = Arc::new(Registry::new()); + registry + .register_module("test.echo", Box::new(EchoModule)) + .unwrap(); + let executor = Arc::new(apcore::Executor::new( + registry.clone(), + apcore::Config::default(), + )); + let agent = Arc::new(apcore_a2a::ApCoreAgentExecutor::new( + executor, + apcore_a2a::PartConverter::new(apcore_a2a::SchemaConverter::new()), + 1, + )); + let options = apcore_a2a::CreateOptions::new( + agent, + "fixture", + "fixture", + "0.0.0", + "http://localhost", + ) + .with_task_store(Arc::new(StreamFaultStore { + inner: InMemoryTaskStore::new(), + fault, + })); + let (app, _) = apcore_a2a::A2AServerFactory::new().create(®istry, options); + let request = Request::post("/") + .header("content-type", "application/json") + .body(Body::from(json!({ + "jsonrpc": "2.0", "id": "stream", "method": "message/stream", + "params": { + "message": { "messageId": "m1", "role": "ROLE_USER", "parts": [{"data": {}}] }, + "metadata": {"skillId": "test.echo"} + } + }).to_string())).unwrap(); + let reply = app.clone().oneshot(request).await.unwrap(); + let bytes = tokio::time::timeout( + std::time::Duration::from_millis(1500), + to_bytes(reply.into_body(), usize::MAX), + ) + .await + .expect("storage failure must finish the stream") + .unwrap(); + let events: Vec = std::str::from_utf8(&bytes) + .unwrap() + .lines() + .filter_map(|line| line.strip_prefix("data: ")) + .map(|line| serde_json::from_str(line).unwrap()) + .collect(); + assert_eq!( + events.last().unwrap()["error"]["code"], + INTERNAL_ERROR, + "{events:?}" + ); + assert_eq!(events.last().unwrap()["id"], "stream"); + assert!(events + .iter() + .all(|event| event["result"]["statusUpdate"]["status"]["state"] + != "TASK_STATE_COMPLETED")); + assert!(events + .iter() + .all(|event| event["result"]["artifactUpdate"]["lastChunk"] != true)); + if fault != StreamWriteFault::InitialTimeout { + let id = events + .iter() + .find_map(|e| e["result"]["statusUpdate"]["taskId"].as_str()) + .unwrap(); + let current = post( + app, + json!({"jsonrpc":"2.0", "id":"get", "method":"tasks/get", "params":{"id":id}}), + ) + .await; + assert_eq!(current["result"]["status"]["state"], "TASK_STATE_WORKING"); + } + } +} + /// Submit a task while both stores are healthy and return its id. async fn seed_task(h: &Harness) -> String { let sent = post( diff --git a/a2a/typescript/CHANGELOG.md b/a2a/typescript/CHANGELOG.md index 3ce8e6a6..00cac093 100644 --- a/a2a/typescript/CHANGELOG.md +++ b/a2a/typescript/CHANGELOG.md @@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [0.8.9-alpha.1] - Unreleased + +### Added + +- Provide an opt-in A2A event subscriber for migration from Core. Preserve a single terminal task state under cancellation or backpressure and reject incomplete OpenAPI registration. + ## [0.8.8] - 2026-11-20 ### Changed diff --git a/a2a/typescript/README.md b/a2a/typescript/README.md index 127d72fd..21e74fbc 100644 --- a/a2a/typescript/README.md +++ b/a2a/typescript/README.md @@ -187,6 +187,49 @@ for await (const event of client.streamMessage(message, { contextId: "ctx-1" })) client.close(); ``` +### Deliver APCore events to an A2A receiver + +Call `registerA2ASubscriber()` during startup before constructing any APCore +client that should use the A2A transport. The existing `type: a2a` configuration +selects one subscriber, including when used as a filter delegate. Importing +the adapter leaves the built-in Core registration in place. + +```typescript +import { APCore, Config, createEvent } from "apcore-js"; +import { registerA2ASubscriber } from "apcore-a2a"; + +registerA2ASubscriber(); +const core = new APCore({ config: Config.load("apcore.yaml") }); +core.events?.emit(createEvent("example.updated", "example.module", "info", { value: 42 })); +await core.events?.flush(); +``` + +```yaml +version: "1.0.0" +project: + name: example +sys_modules: + enabled: true + events: + enabled: true + subscribers: + - type: a2a + platform_url: https://events.example.com/receive + skill_id: example.event_receiver + timeout_ms: 5000 + retry: + max_attempts: 3 +``` + +An omitted `skill_id` defaults to `apevo.event_receiver`. A string `auth` +sends a bearer token, and a header map supplies custom headers. The transport +uses Node's fetch and sends one POST per attempt. APCore owns filter rules, +retry, circuit breakers, and dead-letter delivery. Configured retries and +dead-letter reporting require a Core build that propagates delivery failures +through the circuit breaker. Core 0.33.0 keeps its existing configured event +handling. To return to the built-in transport, omit the registration call +when restarting your application. + ### Add authentication ```typescript diff --git a/a2a/typescript/package.json b/a2a/typescript/package.json index f87c2dbb..fe4963e8 100644 --- a/a2a/typescript/package.json +++ b/a2a/typescript/package.json @@ -1,6 +1,6 @@ { "name": "apcore-a2a", - "version": "0.8.8", + "version": "0.8.9-alpha.1", "packageManager": "pnpm@10.30.1", "description": "Automatic A2A Protocol Adapter for apcore Module Registry", "type": "module", @@ -33,8 +33,8 @@ }, "dependencies": { "@a2a-js/sdk": ">=1.0.1", - "apcore-js": ">=0.33.0", - "apcore-toolkit": ">=0.15.0", + "apcore-js": ">=0.33.0 <1.0.0 || 1.0.0-alpha.1", + "apcore-toolkit": "0.15.1-alpha.1", "express": "^5.1.0", "jsonwebtoken": "^9.0.3", "uuid": "^13.0.2" diff --git a/a2a/typescript/pnpm-lock.yaml b/a2a/typescript/pnpm-lock.yaml index 447ad9c2..8856574a 100644 --- a/a2a/typescript/pnpm-lock.yaml +++ b/a2a/typescript/pnpm-lock.yaml @@ -12,11 +12,11 @@ importers: specifier: '>=1.0.1' version: 1.0.1(express@5.2.1) apcore-js: - specifier: '>=0.33.0' + specifier: '>=0.33.0 <1.0.0 || 1.0.0-alpha.1' version: 0.33.0 apcore-toolkit: - specifier: '>=0.15.0' - version: 0.15.0(@sinclair/typebox@0.34.48) + specifier: 0.15.1-alpha.1 + version: 0.15.1-alpha.1(@sinclair/typebox@0.34.48) express: specifier: ^5.1.0 version: 5.2.1 @@ -660,8 +660,8 @@ packages: resolution: {integrity: sha512-+0UPovkB37qKy9kUwZmgSK6an+RqOUy+XOU9sEAauXStmQYIWmPBV7ACymQ9nwPI4RVAKiWbU4upMIqrCitxoQ==} engines: {node: '>=20.0.0'} - apcore-toolkit@0.15.0: - resolution: {integrity: sha512-PAF0NvA1TRUlS1uHyUwjfe/c7OqttgxxAyMkwcijvQqh45UhUx5V49I6LPrJpHSq1dvkY6komnEO5FeCi/CjqQ==} + apcore-toolkit@0.15.1-alpha.1: + resolution: {integrity: sha512-e8E9gtYAKLeBkpdIQisey4LogMdTR+qffL5PD5U0TyLiVl2v90xSBVXfHof3FkJWMj0/MKRqjlyzBk750xmt+w==} engines: {node: '>=20.10.0'} peerDependencies: '@sinclair/typebox': '>=0.31.0' @@ -1952,7 +1952,7 @@ snapshots: js-yaml: 4.3.2 uuid: 11.1.1 - apcore-toolkit@0.15.0(@sinclair/typebox@0.34.48): + apcore-toolkit@0.15.1-alpha.1(@sinclair/typebox@0.34.48): dependencies: '@sinclair/typebox': 0.34.48 ajv: 8.20.0 diff --git a/a2a/typescript/src/event-subscriber.ts b/a2a/typescript/src/event-subscriber.ts new file mode 100644 index 00000000..80fcd5c6 --- /dev/null +++ b/a2a/typescript/src/event-subscriber.ts @@ -0,0 +1,107 @@ +import { registerSubscriberType } from "apcore-js"; +import type { ApCoreEvent, EventRetryConfig, EventSubscriber } from "apcore-js"; + +export interface A2AEventSubscriberOptions { + readonly timeoutMs?: number; + readonly skillId?: string; + readonly id?: string; + readonly retry?: EventRetryConfig; +} + +type AuthHeaders = string | Record; + +let nextSubscriberId = 0; + +/** Deliver one A2A HTTP attempt for the Core event emitter. */ +export class A2AEventSubscriber implements EventSubscriber { + readonly subscriberType = "a2a"; + readonly subscriberId: string; + readonly retry?: EventRetryConfig; + private readonly headers = new Headers({ "Content-Type": "application/json" }); + private readonly timeoutMs: number; + private readonly skillId: string; + + constructor( + private readonly platformUrl: string, + auth?: AuthHeaders, + options: A2AEventSubscriberOptions = {}, + ) { + this.subscriberId = options.id ?? `a2a-${nextSubscriberId++}`; + this.retry = options.retry; + this.timeoutMs = options.timeoutMs ?? 5000; + this.skillId = options.skillId ?? "apevo.event_receiver"; + if (typeof auth === "string") { + this.headers.set("Authorization", `Bearer ${auth}`); + } else if (auth) { + for (const [name, value] of Object.entries(auth)) { + if (typeof value === "string") this.headers.set(name, value); + } + } + } + + async onEvent(event: ApCoreEvent): Promise { + const body = JSON.stringify({ + skillId: this.skillId, + event: { + event_type: event.eventType, + module_id: event.moduleId, + timestamp: event.timestamp, + severity: event.severity, + data: event.data, + }, + }); + const controller = new AbortController(); + const timeout = setTimeout(() => controller.abort(), this.timeoutMs); + try { + const response = await fetch(this.platformUrl, { + method: "POST", + headers: this.headers, + body, + signal: controller.signal, + }).catch(() => { + const message = controller.signal.aborted + ? "A2A event delivery timed out" + : "A2A event delivery failed"; + throw new Error(message); + }); + // Delivery has no response body contract. Release it without delaying + // the status result or interfering with Core's retry decision. + void response.body?.cancel().catch(() => undefined); + if (response.status >= 500) { + throw new Error(`A2A event delivery failed with HTTP ${response.status}`); + } + if (response.status >= 400) { + console.warn("[apcore:a2a]", `Event ${event.eventType} rejected with HTTP ${response.status}`); + } + } finally { + clearTimeout(timeout); + } + } +} + +function retryFromConfig(value: unknown): EventRetryConfig | undefined { + if (typeof value !== "object" || value === null || Array.isArray(value)) return undefined; + const raw = value as Record; + const retry: EventRetryConfig = {}; + if (typeof raw.max_attempts === "number") retry.maxAttempts = raw.max_attempts; + if (typeof raw.initial_backoff_ms === "number") retry.initialBackoffMs = raw.initial_backoff_ms; + if (typeof raw.max_backoff_ms === "number") retry.maxBackoffMs = raw.max_backoff_ms; + if (typeof raw.backoff_multiplier === "number") retry.backoffMultiplier = raw.backoff_multiplier; + return retry; +} + +/** Select this transport for future `type: a2a` entries, including filter delegates. */ +export function registerA2ASubscriber(): void { + registerSubscriberType("a2a", config => { + const { platform_url: url, auth, id, timeout_ms: timeoutMs, skill_id: skillId, retry } = config; + if (typeof url !== "string" || url.length === 0) { + throw new Error('a2a subscriber requires a non-empty "platform_url" string field'); + } + return new A2AEventSubscriber(url, auth as AuthHeaders | undefined, { + id: typeof id === "string" ? id : undefined, + timeoutMs: typeof timeoutMs === "number" ? timeoutMs : undefined, + skillId: typeof skillId === "string" ? skillId : undefined, + retry: retryFromConfig(retry), + }); + }); +} diff --git a/a2a/typescript/src/index.ts b/a2a/typescript/src/index.ts index 19a540cc..0783bd93 100644 --- a/a2a/typescript/src/index.ts +++ b/a2a/typescript/src/index.ts @@ -18,6 +18,10 @@ export { TaskNotFoundError, } from "./client/index.js"; +// Events +export { A2AEventSubscriber, registerA2ASubscriber } from "./event-subscriber.js"; +export type { A2AEventSubscriberOptions } from "./event-subscriber.js"; + // Auth export type { Authenticator, ClaimMapping } from "./auth/index.js"; export { JWTAuthenticator } from "./auth/index.js"; diff --git a/a2a/typescript/src/openapi-backend.ts b/a2a/typescript/src/openapi-backend.ts index a11b649e..94b36d0a 100644 --- a/a2a/typescript/src/openapi-backend.ts +++ b/a2a/typescript/src/openapi-backend.ts @@ -525,11 +525,8 @@ export async function openapiBackend( } // --- 4. Collision preflight ----------------------------------------------- - // Full-set, before the first write. Toolkit writers report per-module - // WriteResults and never abort, so without this a duplicate would arrive as a - // failed WriteResult, get logged and skipped, and leave a partial registry: a - // skill the document advertises, absent from the card, with one log line as - // the only notice. + // Check the full set before writing so a collision leaves the registry + // untouched and the host can report every colliding ID. const target = options.registry ?? new Registry(); const existing = new Set(registryIds(target)); const collisions = [ @@ -559,13 +556,27 @@ export async function openapiBackend( baseUrl, authHeaderFactory: options.authHeaderFactory, }); - for (const result of writer.write([...modules], target)) { - if (result.verificationError) { - log.error( - `apcore-a2a: ${result.moduleId} failed to register as an HTTP proxy: ` + - result.verificationError, - ); - } + // Keep the Toolkit writer's synchronous WriteResult contract while waiting + // for APCore's async host validators before publishing the backend. + const pending: Promise[] = []; + const asyncFailures = new Map(); + const writes = await writer.write([...modules], { + register(moduleId, module) { + pending.push(Promise.resolve(target.register(moduleId, module)).catch((error: unknown) => { + asyncFailures.set(moduleId, error instanceof Error ? error.message : String(error)); + })); + }, + }); + await Promise.all(pending); + const results = new Map(writes.map(result => [result.moduleId, result])); + const failures = modules.flatMap(({ moduleId }) => { + const result = results.get(moduleId); + const error = asyncFailures.get(moduleId); + if (result?.verified && error === undefined && target.get(moduleId) != null) return []; + return [`${moduleId}: ${result?.verificationError ?? error ?? "module not registered"}`]; + }); + if (failures.length > 0) { + throw new Error(`OpenAPI registration incomplete: ${failures.join("; ")}`); } warnUnapprovedWrites(modules, { diff --git a/a2a/typescript/src/server/executor.ts b/a2a/typescript/src/server/executor.ts index 6c09912e..3654f038 100644 --- a/a2a/typescript/src/server/executor.ts +++ b/a2a/typescript/src/server/executor.ts @@ -1,4 +1,5 @@ import { v4 as uuidv4 } from "uuid"; +import type { CancelToken } from "apcore-js"; import { Artifact, Part, Role, TaskState } from "@a2a-js/sdk"; import type { Message, TaskStatus } from "@a2a-js/sdk"; import { @@ -119,7 +120,7 @@ export class ApCoreAgentExecutor implements AgentExecutor { private executionTimeoutMs: number; private onStateChange?: (oldState: string, newState: string) => void; // P0-B: CancelToken map keyed by taskId - private cancelTokens = new Map(); + private cancelTokens = new Map(); private errorMapper: ErrorMapper; constructor(opts: ApCoreAgentExecutorOptions) { @@ -209,11 +210,12 @@ export class ApCoreAgentExecutor implements AgentExecutor { // 5. Build apcore context with identity and CancelToken (P0-B) const identity = getAuthIdentity(); + let token: CancelToken | undefined; let apcoreCtx: unknown = undefined; try { - const { Context, CancelToken } = await import("apcore-js"); + const { Context, CancelToken: CoreCancelToken } = await import("apcore-js"); // P0-B: create a CancelToken per task and store it - const token = new CancelToken(); + token = new CoreCancelToken(); this.cancelTokens.set(context.taskId, token); // Map the A2A executionTimeout onto apcore's global_deadline so apcore // can stop cooperatively between streaming chunks / pipeline steps. @@ -246,19 +248,15 @@ export class ApCoreAgentExecutor implements AgentExecutor { try { if (canStream) { - // P0-A: Streaming path. The timeout is enforced cooperatively by - // apcore's global_deadline (seeded above) between chunks/steps and - // surfaces as MODULE_TIMEOUT, so we do NOT wrap the stream in a second - // withTimeout (matches the Python binding, which relies on - // global_deadline rather than asyncio.wait_for on the streaming path). - await this.executeStreaming(context, eventBus, skillId, inputObj, apcoreCtx); + await this.executeStreaming(context, eventBus, skillId, inputObj, apcoreCtx, token?.signal); } else { // Non-streaming path (callAsync) let output: Record; const coro = apcoreCtx ? this.executor.callAsync(skillId, inputObj, apcoreCtx) : this.executor.callAsync(skillId, inputObj); - output = await withTimeout(coro, this.executionTimeoutMs); + output = await withTimeout(coro, this.executionTimeoutMs, token?.signal); + if (token?.signal.aborted) return; // 8. Publish artifact + completed const artifact = this.partConverter.outputToParts(output, context.taskId); @@ -277,7 +275,10 @@ export class ApCoreAgentExecutor implements AgentExecutor { this.publishCompleted(context, eventBus); } } catch (e: unknown) { + // cancelTask owns the CANCELED event after explicitly signaling the token. + if (token?.signal.aborted) return; if (e instanceof TimeoutError) { + token?.cancel(); this.notify("working", "failed"); this.publishFailed(context, eventBus, "Execution timed out"); return; @@ -285,6 +286,7 @@ export class ApCoreAgentExecutor implements AgentExecutor { const code = (e as { code?: string }).code; if (code === "MODULE_TIMEOUT") { // apcore enforced global_deadline (streaming or cooperative step) + token?.cancel(); this.notify("working", "failed"); this.publishFailed(context, eventBus, "Execution timed out"); return; @@ -334,6 +336,7 @@ export class ApCoreAgentExecutor implements AgentExecutor { moduleId: string, inputs: Record, apcoreCtx: unknown, + signal?: AbortSignal, ): Promise { const contextId = context.contextId || context.taskId; const artifactId = `art-${context.taskId}`; @@ -348,48 +351,43 @@ export class ApCoreAgentExecutor implements AgentExecutor { ? streamFn.call(this.executor, moduleId, inputs, apcoreCtx) : streamFn.call(this.executor, moduleId, inputs); - // A-D-13: bound the entire streaming loop by a host-side wall-clock budget. - // apcore's cooperative global_deadline only stops well-behaved modules - // between chunks; this Promise.race guarantees the loop terminates even if - // the generator stalls (matches Rust's stream_channel tokio timeout). The - // deadline spans the whole stream, not just a single chunk. - const deadline = Date.now() + this.executionTimeoutMs; + // The host uses a monotonic total budget even if the producer ignores + // apcore's cooperative deadline. + const deadline = performance.now() + this.executionTimeoutMs; const iterator = gen[Symbol.asyncIterator](); - for (;;) { - const remaining = deadline - Date.now(); - if (remaining <= 0) { - await iterator.return?.(undefined); - throw new TimeoutError(); - } - let next: IteratorResult>; - try { - next = await withTimeout(iterator.next(), remaining); - } catch (e) { - if (e instanceof TimeoutError) { - // Signal the underlying generator to stop iterating. - await iterator.return?.(undefined); + let exhausted = false; + try { + for (;;) { + if (signal?.aborted) return; + const remaining = deadline - performance.now(); + if (remaining <= 0) throw new TimeoutError(); + const next = await withTimeout(iterator.next(), remaining, signal); + if (signal?.aborted) return; + if (next.done) { + exhausted = true; + break; } - throw e; + const artifact = this.partConverter.outputToParts(next.value, context.taskId); + eventBus.publish( + AgentEvent.artifactUpdate({ + taskId: context.taskId, + contextId, + artifact: { ...artifact, artifactId }, + append: chunkIndex > 0, + lastChunk: false, + metadata: undefined, + }), + ); + chunkIndex++; + } + } finally { + if (!exhausted) { + // AsyncGenerator.return() queues behind any pending next(). A late + // value or cleanup failure must never change the task's terminal state. + void Promise.resolve().then(() => iterator.return?.(undefined)).catch((error: unknown) => { + console.warn(`[apcore-a2a] Stream cleanup failed for task ${context.taskId}`, error); + }); } - if (next.done) break; - const chunk = next.value; - - const artifact = this.partConverter.outputToParts(chunk, context.taskId); - // Override artifactId to be consistent across chunks - const chunkArtifact: Artifact = { ...artifact, artifactId }; - - eventBus.publish( - AgentEvent.artifactUpdate({ - taskId: context.taskId, - contextId, - artifact: chunkArtifact, - append: chunkIndex > 0, - lastChunk: false, - metadata: undefined, - }), - ); - - chunkIndex++; } // Signal end of stream with lastChunk: true @@ -404,7 +402,7 @@ export class ApCoreAgentExecutor implements AgentExecutor { }), ); - this.publishCompleted(context, eventBus); + if (!signal?.aborted) this.publishCompleted(context, eventBus); } async cancelTask(taskId: string, eventBus: ExecutionEventBus): Promise { @@ -514,10 +512,17 @@ class TimeoutError extends Error { } } -function withTimeout(promise: Promise, ms: number): Promise { +function withTimeout(promise: Promise, ms: number, signal?: AbortSignal): Promise { let timer: ReturnType; - const timeout = new Promise((_, reject) => { + let onAbort: () => void; + const interruption = new Promise((_, reject) => { + onAbort = () => reject(new Error("Execution cancelled")); timer = setTimeout(() => reject(new TimeoutError()), ms); + if (signal?.aborted) onAbort(); + else signal?.addEventListener("abort", onAbort, { once: true }); + }); + return Promise.race([promise, interruption]).finally(() => { + clearTimeout(timer); + signal?.removeEventListener("abort", onAbort); }); - return Promise.race([promise, timeout]).finally(() => clearTimeout(timer)); } diff --git a/a2a/typescript/tests/conformance/event-subscriber.test.ts b/a2a/typescript/tests/conformance/event-subscriber.test.ts new file mode 100644 index 00000000..56c7cf48 --- /dev/null +++ b/a2a/typescript/tests/conformance/event-subscriber.test.ts @@ -0,0 +1,173 @@ +import { + APCore, A2ASubscriber, Config, VERSION, createSubscriberFromConfig, resetSubscriberRegistry, +} from "apcore-js"; +import type { ApCoreEvent, EventEmitter } from "apcore-js"; +import { once } from "node:events"; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { createServer } from "node:http"; +import type { IncomingHttpHeaders } from "node:http"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; +import { A2AEventSubscriber, registerA2ASubscriber } from "../../src/index.js"; + +interface FixtureCase { + id: string; + subscriber: Record; + status: number; + delay_ms?: number; + expected: { + requests: number; + authorization?: string; + source?: string; + skill_id?: string; + dead_letters: number; + circuit_opened: number; + }; +} + +interface FixtureEvent { + event_type: string; + module_id: string | null; + timestamp: string; + severity: string; + data: Record; +} + +interface RecordedRequest { + method?: string; + path?: string; + headers: IncomingHttpHeaders; + body: unknown; +} + +const fixture = JSON.parse(readFileSync( + new URL("../../../conformance/fixtures/event_subscriber.json", import.meta.url), "utf8", +)) as { event: FixtureEvent; test_cases: FixtureCase[] }; +// The published minimum suppresses failures from configured subscribers +// inside CircuitBreakerWrapper. Candidate jobs can require all cases even +// when checking their installation, so a stale minimum cannot pass them. +const legacyCoreFloor = VERSION === "0.33.0" && process.env.APCORE_A2A_REQUIRE_RELIABLE_DELIVERY !== "1"; + +function createEmitter(configFile: string, receiverUrl: string, test: FixtureCase): EventEmitter { + const subscriber = test.subscriber.type === "filter" + ? { ...test.subscriber, delegate_config: { platform_url: receiverUrl } } + : { ...test.subscriber, platform_url: receiverUrl }; + writeFileSync(configFile, [ + 'version: "1.0.0"', + "project: {name: fixture}", + "sys_modules:", + " enabled: true", + " events:", + " enabled: true", + ` subscribers: ${JSON.stringify([subscriber])}`, + ].join("\n")); + const app = new APCore({ config: Config.load(configFile), failOnError: true }); + if (!app.events) throw new Error("Configured event bus is unavailable"); + return app.events; +} + +function expectRequest(recorded: RecordedRequest, expected: FixtureCase["expected"]): void { + expect(recorded.method).toBe("POST"); + expect(recorded.path).toBe("/receive"); + expect(recorded.headers["content-type"]).toBe("application/json"); + expect(recorded.headers.authorization).toBe(expected.authorization); + expect(recorded.headers["x-source"]).toBe(expected.source); + expect(recorded.body).toEqual({ skillId: expected.skill_id, event: fixture.event }); +} + +describe("configured A2A event subscriber", () => { + const verifyDelivery = async (test: FixtureCase): Promise => { + const requests: RecordedRequest[] = []; + const diagnostics: ApCoreEvent[] = []; + const server = createServer((request, response) => { + const chunks: Buffer[] = []; + request.on("data", (chunk: Buffer) => { chunks.push(chunk); }); + request.once("end", () => { + requests.push({ + method: request.method, + path: request.url, + headers: request.headers, + body: JSON.parse(Buffer.concat(chunks).toString()), + }); + const respond = () => { response.writeHead(test.status).end(); }; + if (test.delay_ms === undefined) { + respond(); + } else { + const timer = setTimeout(respond, test.delay_ms); + response.once("close", () => { clearTimeout(timer); }); + } + }); + }); + const scratch = mkdtempSync(join(tmpdir(), "apcore-a2a-event-")); + resetSubscriberRegistry(); + try { + const listening = once(server, "listening"); + server.listen(0, "127.0.0.1"); + await listening; + const bound = server.address(); + if (!bound || typeof bound === "string") throw new Error("Receiver TCP address is unavailable"); + const url = `http://127.0.0.1:${bound.port}/receive`; + const configFile = join(scratch, "apcore.yaml"); + const event: ApCoreEvent = { + eventType: fixture.event.event_type, + moduleId: fixture.event.module_id, + timestamp: fixture.event.timestamp, + severity: fixture.event.severity, + data: fixture.event.data, + }; + + const config = { type: "a2a", platform_url: url }; + expect(createSubscriberFromConfig(config)).toBeInstanceOf(A2ASubscriber); + registerA2ASubscriber(); + expect(createSubscriberFromConfig(config)).toBeInstanceOf(A2AEventSubscriber); + const emitter = createEmitter(configFile, url, test); + try { + for (const eventPattern of ["apcore.event.delivery_failed", "apcore.subscriber.circuit_opened"]) { + emitter.subscribe({ eventPattern, onEvent: received => { diagnostics.push(received); } }); + } + emitter.emit(event); + await emitter.flush(); + } finally { + await emitter.shutdown(); + } + + expect(requests).toHaveLength(test.expected.requests); + for (const request of requests) expectRequest(request, test.expected); + const deadLetters = diagnostics.filter(item => item.eventType === "apcore.event.delivery_failed"); + const circuits = diagnostics.filter(item => item.eventType === "apcore.subscriber.circuit_opened"); + expect(deadLetters).toHaveLength(test.expected.dead_letters); + expect(circuits).toHaveLength(test.expected.circuit_opened); + for (const diagnostic of [...deadLetters, ...circuits]) { + expect(diagnostic.data).toMatchObject({ subscriber_type: "a2a", subscriber_id: expect.stringMatching(/^a2a-\d+$/) }); + } + + if (test.id === "bearer_success") { + resetSubscriberRegistry(); + expect(createSubscriberFromConfig(config)).toBeInstanceOf(A2ASubscriber); + const legacy = createEmitter(configFile, url, test); + try { + legacy.emit(event); + await legacy.flush(); + } finally { + await legacy.shutdown(); + } + expect(requests).toHaveLength(2); + expectRequest(requests[1], test.expected); + } + } finally { + resetSubscriberRegistry(); + if (server.listening) { + const closed = once(server, "close"); + server.close(); + server.closeAllConnections(); + await closed; + } + rmSync(scratch, { recursive: true, force: true }); + } + }; + + for (const test of fixture.test_cases) { + it.skipIf(legacyCoreFloor && test.expected.dead_letters > 0)(test.id, () => verifyDelivery(test)); + } +}); diff --git a/a2a/typescript/tests/effective-openapi-backend.test.ts b/a2a/typescript/tests/effective-openapi-backend.test.ts index ca56ce36..eea2bc1f 100644 --- a/a2a/typescript/tests/effective-openapi-backend.test.ts +++ b/a2a/typescript/tests/effective-openapi-backend.test.ts @@ -61,3 +61,50 @@ it("forwards inherited referenced values after filtering an unsupported operatio })); } }); + + +const registrationDocument = { + ...document, + paths: { + "/items": { get: { operationId: "list_items", summary: "List items", responses: response } }, + "/updates": { post: { operationId: "update_item", summary: "Update item", responses: response } }, + }, +}; + +it("refuses startup when a host validator rejects a scanned module", async () => { + const registry = new Registry(); + registry.setValidator({ + validate: module => + (module as { description: string }).description === "Update item" ? ["rejected by host rule"] : [], + }); + await expect(openapiBackend(registrationDocument, { + registry, + baseUrl: "http://127.0.0.1:1", + acknowledgeUnapprovedWrites: true, + })).rejects.toThrow(/update_item.*rejected by host rule/s); +}); + + +it("waits for asynchronous host validation before publishing the backend", async () => { + const registry = new Registry(); + registry.setValidator({ validate: async () => [] }); + await expect(openapiBackend(registrationDocument, { + registry, + baseUrl: "http://127.0.0.1:1", + acknowledgeUnapprovedWrites: true, + })).resolves.toBe(registry); + expect(registry.list()).toEqual(["list_items", "update_item"]); +}); + +it("refuses publication when asynchronous host validation rejects", async () => { + const registry = new Registry(); + registry.setValidator({ + validate: async module => + (module as { description: string }).description === "Update item" ? ["rejected asynchronously"] : [], + }); + await expect(openapiBackend(registrationDocument, { + registry, + baseUrl: "http://127.0.0.1:1", + acknowledgeUnapprovedWrites: true, + })).rejects.toThrow(/update_item.*rejected asynchronously/s); +}); diff --git a/a2a/typescript/tests/server/executor.test.ts b/a2a/typescript/tests/server/executor.test.ts index 7ef51582..fa3d5c40 100644 --- a/a2a/typescript/tests/server/executor.test.ts +++ b/a2a/typescript/tests/server/executor.test.ts @@ -1,7 +1,7 @@ import { describe, it, expect, vi, beforeEach } from "vitest"; import { Context, ErrorCodes, ModuleError } from "apcore-js"; import { Part, TaskState } from "@a2a-js/sdk"; -import type { ExecutionEventBus, AgentExecutionEvent } from "@a2a-js/sdk/server"; +import type { ExecutionEventBus, AgentExecutionEvent, RequestContext } from "@a2a-js/sdk/server"; import { ApCoreAgentExecutor } from "../../src/server/executor.js"; import { PartConverter } from "../../src/adapters/parts.js"; @@ -60,6 +60,12 @@ function makeExecutor(result: Record = { result: "ok" }) { }; } +function deferred() { + let resolve!: () => void; + const promise = new Promise((done) => { resolve = done; }); + return { promise, resolve }; +} + describe("ApCoreAgentExecutor", () => { let partConverter: PartConverter; @@ -160,6 +166,87 @@ describe("ApCoreAgentExecutor", () => { expect(statusText(event)).toContain("timed out"); }); + it.each([false, true])("finishes a stalled stream before iterator cleanup (partial=%s)", async (partial) => { + const producer = deferred(); + const closing = deferred(); + const stalled = deferred(); + const cleanupWarning = vi.spyOn(console, "warn").mockImplementation(() => {}); + let cancellationSeen: boolean | undefined; + const executor = { + callAsync: vi.fn(), + async *stream(_moduleId: string, _inputs: Record, context: Context) { + try { + if (partial) yield { value: "partial" }; + stalled.resolve(); + await producer.promise; + cancellationSeen = context.cancelToken?.isCancelled; + yield { value: "late" }; + } finally { + closing.resolve(); + throw new Error("generator cleanup failed"); + } + }, + }; + const agent = new ApCoreAgentExecutor({ executor, partConverter, executionTimeout: 0.03 }); + const bus = makeEventBus(); + const execution = agent.execute(makeContext({ skillId: "test" }) as unknown as RequestContext, bus); + try { + await stalled.promise; + await vi.waitFor(() => { + expect((bus.events.at(-1) as AgentExecutionEvent).kind).toBe("statusUpdate"); + }, { timeout: 500 }); + await execution; + producer.resolve(); + await closing.promise; + const updates = (bus.events as AgentExecutionEvent[]).filter((event) => event.kind === "statusUpdate"); + expect(updates.map((event) => event.data.status.state)).toEqual([TaskState.TASK_STATE_FAILED]); + expect(statusText(updates[0].data)).toBe("Execution timed out"); + const artifacts = (bus.events as AgentExecutionEvent[]).filter((event) => event.kind === "artifactUpdate"); + expect(artifacts.map((event) => event.data.lastChunk)).toEqual(partial ? [false] : []); + expect(cancellationSeen).toBe(true); + await vi.waitFor(() => expect(cleanupWarning).toHaveBeenCalledWith( + expect.stringContaining("Stream cleanup failed"), + expect.objectContaining({ message: "generator cleanup failed" }), + )); + } finally { + producer.resolve(); + await execution; + cleanupWarning.mockRestore(); + } + }); + + it("publishes only CANCELED when the client cancels a stalled stream", async () => { + const stalled = deferred(); + const resume = deferred(); + const closed = deferred(); + const executor = { + callAsync: vi.fn(), + async *stream() { + try { + stalled.resolve(); + await resume.promise; + yield { value: "late" }; + } finally { + closed.resolve(); + } + }, + }; + const agent = new ApCoreAgentExecutor({ executor, partConverter, executionTimeout: 4 }); + const bus = makeEventBus(); + const task = agent.execute(makeContext({ skillId: "test" }) as unknown as RequestContext, bus); + try { + await stalled.promise; + await agent.cancelTask("task-1", bus); + await task; + } finally { + resume.resolve(); + await closed.promise; + } + const updates = (bus.events as AgentExecutionEvent[]).filter((event) => event.kind === "statusUpdate"); + expect(updates.map((event) => event.data.status.state)).toEqual([TaskState.TASK_STATE_CANCELED]); + expect(bus.events).toHaveLength(2); + }, 2_000); + it("passes globalDeadline to Context.create as epoch seconds, not ms-since-epoch via data", async () => { // apcore-js >= 0.31.0 (spec D-99/D-100/D-101): `BuiltinContextCreation` // reads only the first-class `Context.globalDeadline` field (epoch diff --git a/a2a/typescript/tests/server/factory.test.ts b/a2a/typescript/tests/server/factory.test.ts index 995a01d2..4c9dea39 100644 --- a/a2a/typescript/tests/server/factory.test.ts +++ b/a2a/typescript/tests/server/factory.test.ts @@ -1,4 +1,6 @@ import { describe, it, expect, vi, beforeEach } from "vitest"; +import { Executor, Registry as CoreRegistry } from "apcore-js"; +import { Type } from "@sinclair/typebox"; import request from "supertest"; import { A2AServerFactory } from "../../src/server/factory.js"; import type { Registry } from "../../src/adapters/agent-card.js"; @@ -50,6 +52,51 @@ describe("A2AServerFactory", () => { }); }); + it("persists a real APCore stream timeout and exposes it via GetTask", async () => { + let release!: () => void; + const stalled = new Promise((resume) => { release = resume; }); + const registry = new CoreRegistry(); + registry.register("test.stall", { + description: "Yields an artifact then stalls", + inputSchema: Type.Object({}), + outputSchema: Type.Object({ value: Type.String() }), + execute() { throw new Error("native stream must run"); }, + async *stream() { + yield { value: "partial" }; + await stalled; + yield { value: "late" }; + }, + }); + expect(registry.list()).toContain("test.stall"); + const { app } = new A2AServerFactory().create( + registry as unknown as Registry, new Executor({ registry }), { ...baseOpts, executionTimeout: 0.1 }, + ); + try { + const streamed = await request(app).post("/").set("A2A-Version", "1.0").send({ + jsonrpc: "2.0", id: 1, method: "SendStreamingMessage", + params: { message: { + messageId: "stall", role: "ROLE_USER", parts: [{ data: {} }], metadata: { skillId: "test.stall" }, + } }, + }).timeout({ deadline: 2000 }); + expect(streamed.status).toBe(200); + const frames = streamed.text.split("\n").filter((line: string) => line.startsWith("data:")) + .map((line: string) => JSON.parse(line.slice(5)).result); + const artifacts = frames.flatMap((frame) => frame.artifactUpdate ? [frame.artifactUpdate] : []); + expect(artifacts).toHaveLength(1); + expect(artifacts[0].lastChunk ?? false).toBe(false); + const statuses = frames.flatMap((frame) => frame.statusUpdate ? [frame.statusUpdate] : []); + expect(statuses.map((update) => update.status.state)).toEqual(["TASK_STATE_FAILED"]); + const terminal = statuses[0]; + expect(terminal.status.message.parts[0].text).toBe("Execution timed out"); + const queried = await request(app).post("/").set("A2A-Version", "1.0").send({ + jsonrpc: "2.0", id: 2, method: "GetTask", params: { id: terminal.taskId }, + }); + expect(queried.body.result.status).toEqual(terminal.status); + } finally { + release(); + } + }); + describe("agent card endpoint", () => { it("serves the A2A 1.0 primary endpoint /.well-known/agent-card.json", async () => { const factory = new A2AServerFactory(); diff --git a/cli/conformance/README.md b/cli/conformance/README.md index a51923f1..252dfe92 100644 --- a/cli/conformance/README.md +++ b/cli/conformance/README.md @@ -35,6 +35,8 @@ Each entry in `test_cases` is an object with the following fields: --- +[Structured flags](fixtures/structured_flags.json) runs against the generated command and a real Executor. It checks typed input, exit 45 on malformed JSON or a schema mismatch, and the number of module calls. + ## Algorithm C01 **Algorithm C01** is the CLI argument and output parity algorithm. It is the normative specification that all SDK implementations must conform to. diff --git a/cli/conformance/fixtures/structured_flags.json b/cli/conformance/fixtures/structured_flags.json new file mode 100644 index 00000000..71b8f6ba --- /dev/null +++ b/cli/conformance/fixtures/structured_flags.json @@ -0,0 +1,39 @@ +{ + "description": "Generated object and array options decode JSON before schema validation and execution", + "schema": { + "type": "object", + "properties": { + "filters": { "type": "object" }, + "labels": { "type": "array", "items": { "type": "string" } }, + "note": { "type": "string" } + }, + "required": ["filters", "labels"] + }, + "test_cases": [ + { + "id": "objects_and_arrays", + "args": ["--filters", "{\"active\":true,\"limit\":3}", "--labels", "[\"a\",\"b\"]", "--note", "{\"literal\":true}"], + "expected": { "exit_code": 0, "calls": 1, "input": { "filters": { "active": true, "limit": 3 }, "labels": ["a", "b"], "note": "{\"literal\":true}" } } + }, + { + "id": "empty_collections", + "args": ["--filters", "{}", "--labels", "[]"], + "expected": { "exit_code": 0, "calls": 1, "input": { "filters": {}, "labels": [] } } + }, + { + "id": "malformed_object", + "args": ["--filters", "{", "--labels", "[]"], + "expected": { "exit_code": 45, "calls": 0 } + }, + { + "id": "wrong_container_type", + "args": ["--filters", "[]", "--labels", "[]"], + "expected": { "exit_code": 45, "calls": 0 } + }, + { + "id": "wrong_array_items", + "args": ["--filters", "{}", "--labels", "[17]"], + "expected": { "exit_code": 45, "calls": 0 } + } + ] +} diff --git a/cli/python/CHANGELOG.md b/cli/python/CHANGELOG.md index e05d3815..15b4f567 100644 --- a/cli/python/CHANGELOG.md +++ b/cli/python/CHANGELOG.md @@ -5,6 +5,12 @@ All notable changes to apcore-cli (Python SDK) will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [0.14.2a1] - Unreleased + +### Fixed + +- Accept structured arguments and enforce strict stream completion on supported in-process execution paths. + ## [0.14.1] - 2026-11-20 ### Added diff --git a/cli/python/README.md b/cli/python/README.md index 59f7eb30..67ebb348 100644 --- a/cli/python/README.md +++ b/cli/python/README.md @@ -306,6 +306,14 @@ apcore-cli --extensions-dir ./extensions apcli list apcore-cli --extensions-dir ./extensions math add --a 5 --b 10 ``` +For a generated command, pass object and array flags as quoted JSON. A flag +value overrides the corresponding property from `--input`. Invalid JSON or +values that fail schema validation exit with code `45` before execution. + +```bash +apcore-cli report create --filters '{"active":true}' --labels '["weekly","ops"]' +``` + ### STDIN piping (Unix pipes) ```bash diff --git a/cli/python/pyproject.toml b/cli/python/pyproject.toml index 296ee33c..58ce7567 100644 --- a/cli/python/pyproject.toml +++ b/cli/python/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "apcore-cli" -version = "0.14.1" +version = "0.14.2a1" description = "Terminal adapter for apcore — execute AI-Perceivable modules from the command line" readme = "README.md" license = "Apache-2.0" @@ -26,8 +26,8 @@ classifiers = [ "Environment :: Console", ] dependencies = [ - "apcore>=0.33.0", - "apcore-toolkit[http-proxy]>=0.15.0", + "apcore>=0.33.0,<=1.0.0a1", + "apcore-toolkit[http-proxy]==0.15.1a1", "click>=8.1", "jsonschema>=4.20", "rich>=13.0", diff --git a/cli/python/src/apcore_cli/cli.py b/cli/python/src/apcore_cli/cli.py index 7195bedd..ea790b3e 100644 --- a/cli/python/src/apcore_cli/cli.py +++ b/cli/python/src/apcore_cli/cli.py @@ -2,17 +2,21 @@ from __future__ import annotations +import asyncio +import inspect import json import logging import re import sys import time from collections.abc import Callable, Mapping +from contextlib import aclosing from pathlib import Path from typing import TYPE_CHECKING, Any import click import jsonschema +from apcore import ModuleError from apcore_cli.acl_loader import cli_context as _cli_acl_context from apcore_cli.acl_loader import enforce_acl_for_unguarded_path as _enforce_acl_for_unguarded_path @@ -47,7 +51,7 @@ UnresolvableRefError, resolve_refs, ) -from apcore_cli.schema_parser import reconvert_enum_values, schema_to_click_options +from apcore_cli.schema_parser import extract_structured_flags, reconvert_enum_values, schema_to_click_options # Re-exported: get_audit_logger/set_audit_logger live in security.audit (not # defined here) so that acl_loader.py — which cli.py imports above — can also @@ -542,6 +546,56 @@ def _check_sandbox_options(*, sandbox: bool, trace: bool, strategy: str | None, raise InvalidCliInputError("--sandbox cannot be combined with --trace, --stream, or --strategy.") +def _strict_stream_opener( + executor: Any, + *, + strict_stream: bool, + sandbox: bool, + trace: bool, + strategy: str | None, + dry_run: bool, +) -> Callable[..., Any] | None: + if not strict_stream or dry_run: + return None + if sandbox or trace or strategy is not None: + raise InvalidCliInputError("--strict-stream cannot be combined with --sandbox, --trace, or --strategy.") + opener = ( + getattr(executor, "stream_with_completion", None) + if inspect.getattr_static(executor, "stream_with_completion", None) is not None + else None + ) + if not callable(opener): + raise InvalidCliInputError("--strict-stream requires an executor with stream completion support.") + return opener + + +def _run_strict_stream( + opener: Callable[..., Any], module_id: str, inputs: dict[str, Any], *, print_result: bool +) -> dict[str, Any]: + """Emit each JSONL chunk and return only after successful completion.""" + + async def run() -> dict[str, Any]: + async with aclosing(opener(module_id, inputs, _cli_acl_context())) as execution: + async for chunk in execution.chunks: + if print_result: + click.echo(json.dumps(chunk, default=str)) + sys.stdout.flush() + completion = await execution.completion() + output = completion.output + if completion.reason != "completed" or not isinstance(output, dict): + raise ModuleError(completion.error_code or "MODULE_EXECUTE_ERROR", "Stream did not complete") + allowed_skips = {"not_configured", "no_match", "strategy_skipped"} + for outcome, code, message in ( + (completion.output_validation, "SCHEMA_VALIDATION_ERROR", "Stream output validation failed"), + (completion.middleware_after, "MODULE_EXECUTE_ERROR", "Stream after-middleware failed"), + ): + if outcome.status != "passed" and not (outcome.status == "skipped" and outcome.reason in allowed_skips): + raise ModuleError(code, message) + return output + + return asyncio.run(run()) + + def build_module_command( module_def: ModuleDescriptor, executor: Executor, @@ -659,6 +713,7 @@ def callback(**kwargs: Any) -> None: dry_run = kwargs.pop("dry_run", False) trace_flag = kwargs.pop("trace", False) stream_flag = kwargs.pop("stream", False) + strict_stream = kwargs.pop("strict_stream", False) strategy_name = kwargs.pop("strategy", None) approval_timeout = kwargs.pop("approval_timeout", None) or 60 approval_token = kwargs.pop("approval_token", None) @@ -667,11 +722,20 @@ def callback(**kwargs: Any) -> None: preflight_exit_code = None audit_start = time.monotonic() try: + strict_opener = _strict_stream_opener( + executor, + strict_stream=strict_stream, + sandbox=sandbox_flag, + trace=trace_flag, + strategy=strategy_name, + dry_run=dry_run, + ) _check_sandbox_options( sandbox=sandbox_flag, trace=trace_flag, strategy=strategy_name, stream=stream_flag, dry_run=dry_run ) - # 1. Collect and merge input (STDIN + CLI flags) - merged = _read_module_input(stdin_input, kwargs, large_input) + # 1. Decode explicit structured flags, then merge with JSON input. + structured, structured_defaults = extract_structured_flags(kwargs, schema_options) + merged = {**structured_defaults, **_read_module_input(stdin_input, kwargs, large_input), **structured} # 2. Reconvert enum values to original types merged = reconvert_enum_values(merged, schema_options) @@ -756,10 +820,18 @@ def callback(**kwargs: Any) -> None: # 5. Execute (optionally sandboxed) + if strict_opener is not None: + result = _run_strict_stream(strict_opener, module_id, merged, print_result=print_result) + if on_result is not None: + on_result(result, module_id) + audit_logger = get_audit_logger() + if audit_logger is not None: + duration_ms = int((time.monotonic() - audit_start) * 1000) + audit_logger.log_execution(module_id, merged, "success", 0, duration_ms) + return + # -- Streaming execution -- if stream_flag: - import asyncio - # Streaming always outputs JSONL; --format table is ignored (spec §3.6.2) if output_format == "table": logger.warning("Streaming mode always outputs JSONL; --format table is ignored.") @@ -940,7 +1012,7 @@ async def _do_stream() -> None: on_error=on_error, exit_codes=exit_codes, exit=exit, - error_stream=error_stream, + error_stream="stderr" if strict_stream else error_stream, ) finally: if preflight_exit_code is not None: @@ -1043,6 +1115,15 @@ async def _do_stream() -> None: hidden=_hide, ) ) + cmd.params.append( + click.Option( + ["--strict-stream"], + is_flag=True, + default=False, + help="Stream JSONL and require successful pipeline completion.", + hidden=_hide, + ) + ) cmd.params.append( click.Option( ["--strategy"], @@ -1082,6 +1163,7 @@ async def _do_stream() -> None: "dry_run", "trace", "stream", + "strict_stream", "strategy", "approval_timeout", "approval_token", diff --git a/cli/python/src/apcore_cli/discovery.py b/cli/python/src/apcore_cli/discovery.py index e4d83c90..81d2dfbd 100644 --- a/cli/python/src/apcore_cli/discovery.py +++ b/cli/python/src/apcore_cli/discovery.py @@ -29,6 +29,8 @@ _check_sandbox_options, _first_failed_exit_code, _read_module_input, + _run_strict_stream, + _strict_stream_opener, collect_input, format_preflight_result, validate_module_id, @@ -355,6 +357,9 @@ def register_exec_command( @click.option("--trace", is_flag=True, default=False, help="Enable pipeline trace output.") @click.option("--dry-run", "dry_run", is_flag=True, default=False, help="Validate inputs without executing.") @click.option("--stream", is_flag=True, default=False, help="Stream output as JSONL.") + @click.option( + "--strict-stream", is_flag=True, default=False, help="Stream JSONL and require successful completion." + ) def exec_cmd( module_id: str, output_format: str | None, @@ -367,6 +372,7 @@ def exec_cmd( trace: bool, dry_run: bool, stream: bool, + strict_stream: bool, ) -> None: """Execute a module by ID with JSON input.""" import time @@ -376,6 +382,9 @@ def exec_cmd( merged: dict[str, Any] = {} audit_start = time.monotonic() try: + strict_opener = _strict_stream_opener( + executor, strict_stream=strict_stream, sandbox=sandbox, trace=trace, strategy=strategy, dry_run=dry_run + ) _check_sandbox_options(sandbox=sandbox, trace=trace, strategy=strategy, stream=stream, dry_run=dry_run) _assert_valid_module_id(module_id) @@ -431,7 +440,9 @@ def exec_cmd( format_preflight_result(preflight, output_format) return - if (trace or strategy) and hasattr(executor, "call_with_trace"): + if strict_opener is not None: + result = _run_strict_stream(strict_opener, module_id, merged, print_result=print_result) + elif (trace or strategy) and hasattr(executor, "call_with_trace"): warn_if_acl_bypassed(strategy) acl_context = cli_context() if acl_context is not None: @@ -451,7 +462,7 @@ def exec_cmd( result = Sandbox(enabled=sandbox).execute(module_id, merged, executor, cli_context()) # Format output FIRST (canonical order: format → audit on success) - if print_result: + if print_result and strict_opener is None: format_exec_result(result, resolve_format(output_format), fields) if on_result is not None: on_result(result, module_id) @@ -474,7 +485,7 @@ def exec_cmd( on_error=on_error, exit_codes=exit_codes, exit=exit, - error_stream=error_stream, + error_stream="stderr" if strict_stream else error_stream, ) _ = exec_cmd diff --git a/cli/python/src/apcore_cli/schema_parser.py b/cli/python/src/apcore_cli/schema_parser.py index 3d205c31..3054686d 100644 --- a/cli/python/src/apcore_cli/schema_parser.py +++ b/cli/python/src/apcore_cli/schema_parser.py @@ -2,17 +2,22 @@ from __future__ import annotations +import json import logging -from typing import Any +from copy import deepcopy +from typing import Any, NoReturn import click +from click.core import ParameterSource from apcore_cli.exit import exit_with +from apcore_cli.security.sandbox import SchemaValidationError logger = logging.getLogger("apcore_cli.schema_parser") # Sentinel for boolean flag marker _BOOLEAN_FLAG = object() +_JSON_CONTAINER_TYPES = {"object", "array"} # Property names that collide with built-in CLI options — schema_to_click_options # rejects these early so the error surfaces at schema-parse time, not at invocation. @@ -106,6 +111,20 @@ def _map_type(prop_name: str, prop_schema: dict) -> Any: return result +def _is_structured_option(prop_schema: dict[str, Any]) -> bool: + """Detect a container-shaped option while keeping mixed scalar unions as text.""" + schema_type = prop_schema.get("type") + if isinstance(schema_type, str): + return schema_type in _JSON_CONTAINER_TYPES + if isinstance(schema_type, list): + types = {value for value in schema_type if isinstance(value, str) and value != "null"} + return bool(types) and types <= _JSON_CONTAINER_TYPES + branches = [ + branch for branch in prop_schema.get("anyOf", []) if isinstance(branch, dict) and branch.get("type") != "null" + ] + return bool(branches) and all(_is_structured_option(branch) for branch in branches) + + def _extract_help(prop_schema: dict, max_length: int = 1000) -> str | None: """Extract help text from schema property, preferring x-llm-description.""" text = prop_schema.get("x-llm-description") @@ -196,6 +215,10 @@ def schema_to_click_options(schema: dict, max_help_length: int = 1000) -> list[c help=help_text, show_default=True, ) + elif _is_structured_option(prop_schema): + # Keep native schema defaults intact and let the module callback + # decode user input via its existing schema error/exit handling. + option = click.Option([flag_name], type=click.UNPROCESSED, metavar="JSON", default=default, help=help_text) elif "enum" in prop_schema and click_type is not _BOOLEAN_FLAG: enum_values = prop_schema["enum"] if not enum_values: @@ -235,6 +258,37 @@ def schema_to_click_options(schema: dict, max_help_length: int = 1000) -> list[c return options +def _reject_json_constant(constant: str) -> NoReturn: + raise ValueError(f"Invalid JSON constant: {constant}") + + +def extract_structured_flags( + values: dict[str, Any], options: list[click.Option] +) -> tuple[dict[str, Any], dict[str, Any]]: + """Pop structured options and return their decoded values and native defaults.""" + context = click.get_current_context(silent=True) + explicit: dict[str, Any] = {} + defaults: dict[str, Any] = {} + for option in options: + name = option.name + if option.type is not click.UNPROCESSED or name is None: + continue + value = values.pop(name, None) + if value is None: + continue + source = context.get_parameter_source(name) if context is not None else None + if source in (ParameterSource.DEFAULT, ParameterSource.DEFAULT_MAP): + defaults[name] = deepcopy(value) + continue + try: + explicit[name] = ( + json.loads(value, parse_constant=_reject_json_constant) if isinstance(value, str) else value + ) + except (ValueError, RecursionError) as error: + raise SchemaValidationError(f"Option '{option.opts[0]}' must contain valid JSON.") from error + return explicit, defaults + + def reconvert_enum_values(kwargs: dict[str, Any], options: list[click.Option]) -> dict[str, Any]: """Reconvert enum values from string back to their original types.""" result = dict(kwargs) diff --git a/cli/python/tests/conformance/test_structured_flags.py b/cli/python/tests/conformance/test_structured_flags.py new file mode 100644 index 00000000..7c46a18a --- /dev/null +++ b/cli/python/tests/conformance/test_structured_flags.py @@ -0,0 +1,113 @@ +"""Generated CLI options use JSON containers before invoking the Executor.""" + +from __future__ import annotations + +import json +from copy import deepcopy +from pathlib import Path +from typing import Any + +import click +import pytest +from apcore import Context, Executor, Registry +from click.testing import CliRunner + +from apcore_cli.cli import build_module_command +from apcore_cli.exit_codes import EXIT_SCHEMA_VALIDATION_ERROR + +_FIXTURE = json.loads( + (Path(__file__).resolve().parents[3] / "conformance/fixtures/structured_flags.json").read_text(encoding="utf-8") +) + + +class _CaptureModule: + description = "Capture the inputs received by the module" + output_schema = {"type": "object"} + + def __init__(self, input_schema: dict[str, Any]) -> None: + self.input_schema = input_schema + self.calls: list[dict[str, Any]] = [] + + def execute(self, inputs: dict[str, Any], context: Context) -> dict[str, Any]: + self.calls.append(inputs) + return inputs + + +def _command(schema: dict[str, Any]) -> tuple[click.Command, _CaptureModule]: + module = _CaptureModule(schema) + registry = Registry() + registry.register("test.structured_flags", module) + descriptor = registry.get_definition("test.structured_flags") + assert descriptor is not None + return build_module_command(descriptor, Executor(registry)), module + + +@pytest.mark.parametrize("case", _FIXTURE["test_cases"], ids=lambda case: case["id"]) +def test_shared_structured_flag_contract(case: dict[str, Any]) -> None: + command, module = _command(_FIXTURE["schema"]) + result = CliRunner().invoke(command, case["args"]) + expected = case["expected"] + assert result.exit_code == expected["exit_code"], result.output + assert len(module.calls) == expected["calls"] + if expected["calls"]: + assert module.calls == [expected["input"]] + else: + assert result.stderr + + +@pytest.mark.parametrize("source", ["stdin", "file"]) +def test_structured_flags_override_input_without_reparsing_it(tmp_path: Path, source: str) -> None: + schema = deepcopy(_FIXTURE["schema"]) + schema["properties"]["labels"]["default"] = ["default"] + command, module = _command(schema) + inline = json.dumps({"filters": {"from_input": True}, "labels": ["inline"], "note": "[]"}) + path = tmp_path / "payload.json" + path.write_text(inline, encoding="utf-8") + result = CliRunner().invoke( + command, + ["--input", "-" if source == "stdin" else str(path), "--filters", '{"from_flag":true}'], + input=inline if source == "stdin" else None, + ) + assert result.exit_code == 0, result.output + assert module.calls == [{"filters": {"from_flag": True}, "labels": ["inline"], "note": "[]"}] + + +def test_structured_schema_defaults_stay_native() -> None: + schema = deepcopy(_FIXTURE["schema"]) + schema["properties"]["filters"]["default"] = {"enabled": True} + schema["properties"]["labels"]["default"] = ["default"] + command, module = _command(schema) + result = CliRunner().invoke(command, []) + assert result.exit_code == 0, result.output + assert module.calls == [{"filters": {"enabled": True}, "labels": ["default"]}] + + +def test_input_strings_are_not_decoded_as_structured_flags() -> None: + command, module = _command(_FIXTURE["schema"]) + result = CliRunner().invoke(command, ["--input", "-"], input='{"filters":"{}","labels":[]}') + assert result.exit_code == EXIT_SCHEMA_VALIDATION_ERROR, result.output + assert module.calls == [] + + +def test_non_json_literals_fail_before_execution() -> None: + command, module = _command(_FIXTURE["schema"]) + result = CliRunner().invoke(command, ["--filters", '{"value": NaN}', "--labels", "[]"]) + assert result.exit_code == EXIT_SCHEMA_VALIDATION_ERROR, result.output + assert module.calls == [] + + +def test_nullable_and_enum_container_flags_use_the_schema_validator() -> None: + schema = deepcopy(_FIXTURE["schema"]) + schema["properties"]["filters"] = {"type": ["object", "null"]} + schema["properties"]["labels"]["enum"] = [["allowed"]] + command, module = _command(schema) + accepted = CliRunner().invoke(command, ["--filters", "{}", "--labels", '["allowed"]']) + nullable = CliRunner().invoke(command, ["--filters", "null", "--labels", '["allowed"]']) + rejected = CliRunner().invoke(command, ["--filters", "{}", "--labels", '["other"]']) + assert accepted.exit_code == 0, accepted.output + assert nullable.exit_code == 0, nullable.output + assert rejected.exit_code == EXIT_SCHEMA_VALIDATION_ERROR, rejected.output + assert module.calls == [ + {"filters": {}, "labels": ["allowed"]}, + {"filters": None, "labels": ["allowed"]}, + ] diff --git a/cli/python/tests/test_strict_stream.py b/cli/python/tests/test_strict_stream.py new file mode 100644 index 00000000..e79494d9 --- /dev/null +++ b/cli/python/tests/test_strict_stream.py @@ -0,0 +1,150 @@ +"""JSONL, diagnostics and audit with a real completion-capable Executor.""" + +from __future__ import annotations + +import json +from collections.abc import AsyncIterator, Iterator +from pathlib import Path +from typing import Any + +import click +import pytest +from apcore import Context, Executor, ModuleAnnotations, ModuleExecuteError, Registry +from apcore.middleware import Middleware +from click.testing import CliRunner +from pydantic import BaseModel + +from apcore_cli.cli import build_module_command +from apcore_cli.discovery import register_exec_command +from apcore_cli.exit_codes import EXIT_INVALID_INPUT, EXIT_SCHEMA_VALIDATION_ERROR +from apcore_cli.security.audit import AuditLogger, get_audit_logger, set_audit_logger + +_HAS_COMPLETION = callable(getattr(Executor, "stream_with_completion", None)) + + +class _Input(BaseModel): + pass + + +class _Output(BaseModel): + value: int + + +class _Module: + annotations = ModuleAnnotations(streaming=True) + description = "Return two partial outputs" + input_schema = _Input + output_schema = _Output + + def __init__(self, last_value: object) -> None: + self.last_value = last_value + self.entries = 0 + + async def execute(self, inputs: dict[str, Any], context: Context) -> dict[str, Any]: + self.entries += 1 + return {"value": self.last_value} + + async def stream(self, inputs: dict[str, Any], context: Context) -> AsyncIterator[dict[str, Any]]: + self.entries += 1 + yield {"value": 1} + yield {"value": self.last_value} + + +@pytest.fixture +def audit_log(tmp_path: Path) -> Iterator[Path]: + file = tmp_path / "audit.jsonl" + previous = get_audit_logger() + set_audit_logger(AuditLogger(file)) + try: + yield file + finally: + set_audit_logger(previous) + + +def _setup( + module: _Module, *, generic: bool = False, legacy: bool = False, middleware: Middleware | None = None +) -> tuple[click.Command, list[str]]: + class LegacyExecutor(Executor): + stream_with_completion = None # type: ignore[assignment] + + registry = Registry() + registry.register("test.stream", module) + executor = LegacyExecutor(registry) if legacy else Executor(registry) + if middleware is not None: + executor.use(middleware) + if generic: + group = click.Group("apcli") + register_exec_command(group, registry, executor) + return group, ["exec", "test.stream", "--input", "{}"] + descriptor = registry.get_definition("test.stream") + assert descriptor is not None + return build_module_command(descriptor, executor), [] + + +@pytest.mark.parametrize("generic", [False, True]) +@pytest.mark.parametrize("value", [2, "not an integer"]) +@pytest.mark.skipif(not _HAS_COMPLETION, reason="run with the A2 wheel for the completion path") +def test_strict_jsonl_exit_and_audit_follow_completion(audit_log: Path, generic: bool, value: object) -> None: + module = _Module(value) + cli, args = _setup(module, generic=generic) + result = CliRunner().invoke(cli, [*args, "--strict-stream"]) + assert [json.loads(line) for line in result.stdout.splitlines()] == [{"value": 1}, {"value": value}] + records = [json.loads(line) for line in audit_log.read_text().splitlines()] + assert len(records) == 1 + if value == 2: + assert result.exit_code == 0, result.output + assert records[0]["status"] == "success" + assert result.stderr == "" + else: + assert result.exit_code == EXIT_SCHEMA_VALIDATION_ERROR, result.output + assert records[0]["status"] == "error" + assert "validation" in result.stderr.lower() + assert records[0]["exit_code"] == result.exit_code + assert module.entries == 1 + + +@pytest.mark.parametrize("generic", [False, True]) +def test_old_core_refuses_strict_before_invocation(generic: bool) -> None: + module = _Module(2) + cli, args = _setup(module, generic=generic, legacy=True) + result = CliRunner().invoke(cli, [*args, "--strict-stream"]) + assert result.exit_code == EXIT_INVALID_INPUT + assert "completion" in result.stderr + assert result.stdout == "" + assert module.entries == 0 + + +def test_legacy_stream_preserves_emitted_lines_and_old_terminal_behavior(audit_log: Path) -> None: + module = _Module("not an integer") + cli, args = _setup(module) + result = CliRunner().invoke(cli, [*args, "--stream"]) + assert result.exit_code == 0, result.output + assert [json.loads(line) for line in result.stdout.splitlines()] == [{"value": 1}, {"value": "not an integer"}] + assert json.loads(audit_log.read_text())["status"] == "success" + assert module.entries == 1 + + +@pytest.mark.parametrize("unsupported", [["--sandbox"], ["--trace"], ["--strategy", "standard"]]) +def test_strict_rejects_modes_without_completion_before_execution(unsupported: list[str]) -> None: + module = _Module(2) + cli, args = _setup(module) + result = CliRunner().invoke(cli, [*args, "--strict-stream", *unsupported]) + assert result.exit_code == EXIT_INVALID_INPUT + assert "cannot be combined" in result.stderr + assert module.entries == 0 + + +@pytest.mark.skipif(not _HAS_COMPLETION, reason="run with the A2 wheel for the completion path") +def test_after_hook_failure_preserves_chunks_but_records_audit_error(audit_log: Path) -> None: + class FailingAfter(Middleware): + def after(self, module_id: str, inputs: dict[str, Any], output: dict[str, Any], context: Context) -> None: + raise ModuleExecuteError(module_id, "private diagnostic") + + module = _Module(2) + cli, args = _setup(module, middleware=FailingAfter()) + result = CliRunner().invoke(cli, [*args, "--strict-stream"]) + assert result.exit_code == 1, result.output + assert [json.loads(line) for line in result.stdout.splitlines()] == [{"value": 1}, {"value": 2}] + assert "after-middleware" in result.stderr + assert json.loads(audit_log.read_text())["status"] == "error" + assert module.entries == 1 diff --git a/cli/rust/CHANGELOG.md b/cli/rust/CHANGELOG.md index eda643ec..69b2a080 100644 --- a/cli/rust/CHANGELOG.md +++ b/cli/rust/CHANGELOG.md @@ -3,6 +3,12 @@ All notable changes to this project will be documented in this file. Format: [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). +## [0.14.2-alpha.1] - Unreleased + +### Fixed + +- Accept structured arguments and enforce strict stream completion on supported in-process execution paths. + ## [0.14.1] - Unreleased ### Added diff --git a/cli/rust/Cargo.lock b/cli/rust/Cargo.lock index 6bae3f37..2949548b 100644 --- a/cli/rust/Cargo.lock +++ b/cli/rust/Cargo.lock @@ -133,9 +133,9 @@ checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" [[package]] name = "apcore" -version = "0.33.0" +version = "1.0.0-alpha.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23f7c4d184641deb06d4140cfc058c8f73f6ea57b6e0948b37a9335cb0dc83af" +checksum = "2344e07dc37e34b8a93d8ff66d757587a2ca5adea5ca5cbd204af8d0ff836884" dependencies = [ "async-stream", "async-trait", @@ -161,7 +161,7 @@ dependencies = [ [[package]] name = "apcore-cli" -version = "0.14.1" +version = "0.14.2-alpha.1" dependencies = [ "aes-gcm", "anyhow", @@ -197,9 +197,9 @@ dependencies = [ [[package]] name = "apcore-toolkit" -version = "0.15.0" +version = "0.15.1-alpha.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a76301238650b9b7dc78b084b672f20f812d5f69b95a91a5510f9d9d5ee851e0" +checksum = "44a190df138e3edc4e21738c8d07f76eb17aab761afb76226e61a08643147dc9" dependencies = [ "apcore", "async-trait", @@ -244,9 +244,9 @@ dependencies = [ [[package]] name = "async-executor" -version = "1.14.0" +version = "1.14.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c96bf972d85afc50bf5ab8fe2d54d1586b4e0b46c97c50a0c9e71e2f7bcd812a" +checksum = "f426a31126c735126297bc5ea7a521263c9faff4f63ca415267ee625651c4f37" dependencies = [ "async-task", "concurrent-queue", diff --git a/cli/rust/Cargo.toml b/cli/rust/Cargo.toml index 59026d56..7c2a5854 100644 --- a/cli/rust/Cargo.toml +++ b/cli/rust/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "apcore-cli" -version = "0.14.1" +version = "0.14.2-alpha.1" edition = "2021" description = "Command-line interface for apcore modules" license = "Apache-2.0" @@ -21,7 +21,7 @@ name = "apcore_cli" path = "src/lib.rs" [dependencies] -apcore = ">=0.30.0" +apcore = "=1.0.0-alpha.1" async-trait = "0.1" clap = { version = "4", features = ["derive", "env", "string"] } serde = { version = "1", features = ["derive"] } @@ -48,7 +48,7 @@ chrono = { version = "0.4", features = ["serde"] } tempfile = "3" nix = { version = "0.30", features = ["user"] } libc = "0.2" -apcore-toolkit = { version = ">=0.15.0", features = ["http-proxy"] } +apcore-toolkit = { version = "=0.15.1-alpha.1", features = ["http-proxy"] } [features] # ADR-07 is fully landed as of 0.10.0 (6.2 fix): apcore-toolkit is a hard diff --git a/cli/rust/README.md b/cli/rust/README.md index 17b9f1bb..86663d70 100644 --- a/cli/rust/README.md +++ b/cli/rust/README.md @@ -48,7 +48,7 @@ Terminal adapter for apcore. Execute AI-Perceivable modules from the command lin cargo install apcore-cli ``` -Build with current stable Rust (`apcore` requires Rust 1.86+, and the checked-in lockfile includes dependencies requiring Rust 1.88+), `apcore >= 0.32.3`, and `apcore-toolkit >= 0.14.1` with the `http-proxy` feature (a required runtime dependency). +Build with current stable Rust (`apcore` requires Rust 1.86+, and the checked-in lockfile includes dependencies requiring Rust 1.88+), `apcore = 1.0.0-alpha.1`, and `apcore-toolkit = 0.15.1-alpha.1` with `http-proxy`. Registry-based installation requires a compatible APCore release on crates.io. When testing a locally unpacked prerelease, resolve both this crate and Toolkit against the same unpacked APCore package and confirm with `cargo metadata`. > **Note:** `apcore-toolkit-rust` 0.7.0 enables `serde_json/preserve_order`. This transitively affects all `serde_json::Map` iteration in your dependency tree — code that relied on alphabetical key ordering must re-sort explicitly. @@ -122,6 +122,13 @@ result. Preflight and streaming calls return `Ok(None)` on success. Failures return `Err(exit_code)`. A non-streaming module requested with `--stream` falls back to buffered execution and returns its result. +`--strict-stream` emits JSONL and reports success only after APCore confirms +successful completion of each applicable output-validation and after-middleware +step. With a non-streaming in-process module it emits the unary result as one +JSONL record. A late failure exits nonzero and records a failure in the audit log even if stdout +already contains chunks. Filesystem scripts and `--sandbox` are unsupported +in strict mode. `--strict-stream` also conflicts with `--dry-run` and `--trace`. + To inject host-level input, choose the failure stream, or observe failures, use `dispatch_module_with_options`: @@ -259,7 +266,7 @@ apcore-cli ships with 13 built-in subcommands, all reachable under the reserved | Command | Description | Source | |---------|-------------|--------| -| `exec ` | Execute a module by ID (supports `--input`, `--yes`, `--format`, `--sandbox`, `--dry-run`, `--trace`, `--stream`, `--strategy`, `--fields`, `--approval-timeout`, `--approval-token`) | `cli` | +| `exec ` | Execute a module by ID (supports `--input`, `--yes`, `--format`, `--sandbox`, `--dry-run`, `--trace`, `--stream`, `--strict-stream`, `--strategy`, `--fields`, `--approval-timeout`, `--approval-token`) | `cli` | | `list` | List available modules with filtering (`--tag`, `--search`, `--status`, `--annotation`, `--sort`, `--reverse`, `--deprecated`, `--deps`) | `discovery` | | `describe ` | Show full module metadata, schemas, and annotations | `discovery` | | `validate ` | Run preflight schema / approval / dependency validation without executing | `validate` | @@ -303,12 +310,18 @@ When executing a module (e.g. `apcore-cli math.add` or `apcore-cli exec math.add | `--dry-run` | Run preflight checks without executing (FE-11, routed through the `validate` module) | | `--trace` | Emit a pipeline execution trace | | `--stream` | Stream results line-by-line instead of buffering | +| `--strict-stream` | Stream JSONL and use APCore completion for exit status and audit | | `--strategy ` | Override execution strategy (`standard`, `internal`, `testing`, `performance`, `minimal`) | | `--fields ` | Select output fields via dot-path notation | | `--approval-timeout ` | Override approval prompt timeout (default: 60) | | `--approval-token ` | Provide a pre-obtained approval token to skip the interactive prompt | Schema-generated flags (e.g. `--a`, `--b`) are added automatically from the module's `input_schema`. +Object and array flags accept JSON, for example `--filters '{"active":true}'` +and `--labels '["a","b"]'`. Malformed JSON or a value that fails schema +validation exits with code 45 before module execution. An explicit structured +flag takes precedence over `--input`, and structured schema defaults fill +fields neither source supplied. **Enhanced `list` flags (v0.6.0):** `--search `, `--status `, `--annotation `, `--sort `, `--reverse`, `--deprecated` (include deprecated modules), `--deps` (show dependency graph). diff --git a/cli/rust/src/cli.rs b/cli/rust/src/cli.rs index 1a5e3fce..a81407af 100644 --- a/cli/rust/src/cli.rs +++ b/cli/rust/src/cli.rs @@ -341,6 +341,14 @@ pub fn add_dispatch_flags(cmd: clap::Command) -> clap::Command { ) .hide(hide), ) + .arg( + Arg::new("strict-stream") + .long("strict-stream") + .action(ArgAction::SetTrue) + .conflicts_with_all(["sandbox", "dry-run", "trace"]) + .help("Stream JSONL and require successful Core completion before exiting.") + .hide(hide), + ) .arg( Arg::new("strategy") .long("strategy") @@ -426,6 +434,7 @@ const RESERVED_FLAG_NAMES: &[&str] = &[ "sandbox", "strategy", "stream", + "strict-stream", "trace", "yes", ]; @@ -436,7 +445,7 @@ const RESERVED_FLAG_NAMES: &[&str] = &[ /// * its `name` set to `module_def.name` /// * its `about` derived from the module descriptor (empty if unavailable) /// * the built-in dispatch flags (`--input`, `--yes`/`-y`, `--large-input`, -/// `--format`, `--sandbox`, `--dry-run`, `--trace`, `--stream`, `--strategy`, +/// `--format`, `--sandbox`, `--dry-run`, `--trace`, `--stream`, `--strict-stream`, `--strategy`, /// `--fields`, `--approval-timeout`, `--approval-token`) /// * schema-derived flags from `schema_to_clap_args` /// @@ -1055,47 +1064,76 @@ pub fn reconcile_bool_pairs( result } -/// Extract schema-derived CLI kwargs from `ArgMatches` for a given module. -/// -/// Iterates schema properties and extracts string values from clap matches. -/// Boolean pairs are handled separately via `reconcile_bool_pairs`. +#[derive(Default)] +struct CliInputs { + kwargs: HashMap, + structured_flags: HashMap, + structured_defaults: HashMap, +} + +/// Read schema-derived flags and keep explicit structured values separate from defaults. fn extract_cli_kwargs( matches: &clap::ArgMatches, module_def: &apcore::registry::registry::ModuleDescriptor, -) -> HashMap { - use crate::schema_parser::schema_to_clap_args; +) -> Result { + use crate::schema_parser::{is_structured_option, schema_to_clap_args}; - let schema_args = match schema_to_clap_args(&module_def.input_schema, None) { - Ok(sa) => sa, - Err(_) => return HashMap::new(), + let resolved = crate::ref_resolver::resolve_refs( + &module_def.input_schema, + crate::ref_resolver::MAX_REF_DEPTH, + &module_def.module_id, + ) + .ok(); + let schema = resolved.as_ref().unwrap_or(&module_def.input_schema); + let Ok(schema_args) = schema_to_clap_args(schema, None) else { + return Ok(CliInputs::default()); }; - let mut kwargs: HashMap = HashMap::new(); - - // Extract non-boolean schema args as strings (or Null if absent). + let mut inputs = CliInputs::default(); for arg in &schema_args.args { - let id = arg.get_id().as_str().to_string(); + let id = arg.get_id().as_str(); // Skip the no- counterparts of boolean args. if id.starts_with("no-") { continue; } // Use try_get_one to avoid panicking when the arg doesn't exist // in ArgMatches (e.g. exec subcommand doesn't have schema-derived flags). - if let Ok(Some(val)) = matches.try_get_one::(&id) { - kwargs.insert(id, Value::String(val.clone())); - } else if let Ok(Some(val)) = matches.try_get_one::(&id) { - kwargs.insert(id, Value::String(val.to_string_lossy().to_string())); - } else { - kwargs.insert(id, Value::Null); + if let Ok(Some(value)) = matches.try_get_one::(id) { + let property = &schema["properties"][id]; + if is_structured_option(property) { + if matches.value_source(id) == Some(clap::parser::ValueSource::DefaultValue) { + if let Some(default) = property.get("default") { + inputs + .structured_defaults + .insert(id.to_owned(), default.clone()); + } + } else { + let value = serde_json::from_str(value).map_err(|_| { + format!( + "Option '--{}' must contain valid JSON.", + arg.get_long().unwrap_or(id) + ) + })?; + inputs.structured_flags.insert(id.to_owned(), value); + } + } else { + inputs + .kwargs + .insert(id.to_owned(), Value::String(value.clone())); + } + } else if let Ok(Some(value)) = matches.try_get_one::(id) { + inputs.kwargs.insert( + id.to_owned(), + Value::String(value.to_string_lossy().to_string()), + ); } } - // Reconcile boolean pairs. - let bool_vals = reconcile_bool_pairs(matches, &schema_args.bool_pairs); - kwargs.extend(bool_vals); - - // Apply enum type reconversion. - crate::schema_parser::reconvert_enum_values(kwargs, &schema_args) + inputs + .kwargs + .extend(reconcile_bool_pairs(matches, &schema_args.bool_pairs)); + inputs.kwargs = crate::schema_parser::reconvert_enum_values(inputs.kwargs, &schema_args); + Ok(inputs) } /// Execute a script-based module by spawning the executable as a subprocess. @@ -1171,6 +1209,39 @@ fn validate_sandbox_flags( Ok(()) } +fn strict_stream_error(completion: &apcore::StreamCompletion) -> Option<&str> { + use apcore::{StreamEndReason, StreamSkipReason, StreamStepOutcome}; + + let failed = |step| { + matches!( + step, + StreamStepOutcome::Failed { .. } + | StreamStepOutcome::Skipped { + reason: StreamSkipReason::NotReached + } + ) + }; + match completion.reason { + StreamEndReason::Completed if failed(completion.output_validation) => { + Some("SCHEMA_VALIDATION_ERROR") + } + StreamEndReason::Completed + if failed(completion.middleware_after) || completion.output.is_none() => + { + Some("MODULE_EXECUTE_ERROR") + } + StreamEndReason::Completed => None, + StreamEndReason::Cancelled | StreamEndReason::ConsumerClosed => Some("EXECUTION_CANCELLED"), + StreamEndReason::TimedOut => Some("MODULE_TIMEOUT"), + StreamEndReason::Failed => Some( + completion + .error_code + .as_deref() + .unwrap_or("MODULE_EXECUTE_ERROR"), + ), + } +} + /// Execute a module and exit the process with the corresponding CLI exit code. /// /// Use [`dispatch_module_with_result`] when the caller needs to keep running. @@ -1453,7 +1524,8 @@ async fn run_module_dispatch( let fields_flag = matches.get_one::("fields").cloned(); let dry_run = matches.get_flag("dry-run"); let trace_flag = matches.get_flag("trace"); - let stream_flag = matches.get_flag("stream"); + let strict_stream = matches.get_flag("strict-stream"); + let stream_flag = strict_stream || matches.get_flag("stream"); let strategy_name = matches.get_one::("strategy").cloned(); let approval_timeout_arg = matches.get_one::("approval-timeout").cloned(); let approval_token = matches.get_one::("approval-token").cloned(); @@ -1473,15 +1545,21 @@ async fn run_module_dispatch( // presents `@external`. let cli_ctx = crate::acl_cmd::identity_context(); - // 4. Build CLI kwargs from schema-derived flags (stub: empty map). - let cli_kwargs = extract_cli_kwargs(matches, &module_def); + // 4. Decode schema-derived flags before validation and module execution. + let cli_inputs = extract_cli_kwargs(matches, &module_def).map_err(|message| { + errors.fail( + EXIT_SCHEMA_VALIDATION_ERROR, + "SCHEMA_VALIDATION_ERROR", + message, + ) + })?; // 5. Collect and merge input (exit 2 on errors). let input = match stdin_flag { Some(source) if source.trim_start().starts_with(['{', '[']) => { - collect_input_from_reader(Some("-"), cli_kwargs, large_input, source.as_bytes()) + collect_input_from_reader(Some("-"), cli_inputs.kwargs, large_input, source.as_bytes()) } - _ => collect_input(stdin_flag, cli_kwargs, large_input), + _ => collect_input(stdin_flag, cli_inputs.kwargs, large_input), }; let mut merged = match input { Ok(m) => m, @@ -1503,6 +1581,11 @@ async fn run_module_dispatch( } }; + for (name, value) in cli_inputs.structured_defaults { + merged.entry(name).or_insert(value); + } + merged.extend(cli_inputs.structured_flags); + // 5b. Host-injected input (program-level flags, envelope fields). Merged // before validation so the values are validated like any other input. if let Some(extra) = &options.extra_input { @@ -1586,6 +1669,9 @@ async fn run_module_dispatch( .get() .and_then(|map| map.get(module_id)) .cloned(); + if strict_stream && (script_executable.is_some() || use_sandbox) { + return Err(errors.invalid_input("--strict-stream requires in-process Core execution.")); + } // 6.5 FE-14 section 4.10: gate every execution path that does not carry // the attached ACL. @@ -1708,25 +1794,40 @@ async fn run_module_dispatch( .as_ref() .is_some_and(|annotations| annotations.streaming); - if stream_flag && !standalone && !supports_streaming { + if stream_flag && !strict_stream && !standalone && !supports_streaming { eprintln!( "Warning: Module '{module_id}' does not declare streaming support. Falling back to standard execution." ); } - if stream_flag && (standalone || supports_streaming) { + if stream_flag && (standalone || supports_streaming || strict_stream) { // Streaming always outputs JSONL; --format table is ignored (spec 3.6.2). if format_flag.as_deref() == Some("table") { eprintln!("Warning: Streaming mode always outputs JSONL; --format table is ignored."); } let start = std::time::Instant::now(); - if supports_streaming { - let mut chunks = - apcore_executor.stream(module_id, input_value.clone(), cli_ctx.as_ref(), None); + if supports_streaming || strict_stream { + let (mut chunks, completion) = if strict_stream { + let (chunks, completion) = apcore_executor.stream_with_completion( + module_id, + input_value.clone(), + cli_ctx.as_ref(), + None, + ); + (Box::pin(chunks) as _, Some(completion)) + } else { + ( + apcore_executor.stream(module_id, input_value.clone(), cli_ctx.as_ref(), None), + None, + ) + }; loop { let chunk = tokio::select! { chunk = std::future::poll_fn(|cx| chunks.as_mut().poll_next(cx)) => chunk, _ = &mut cancel => { + if strict_stream { + audit_error(module_id, &input_value, EXIT_SIGINT, start.elapsed().as_millis() as u64); + } eprintln!("Execution cancelled."); return Err(EXIT_SIGINT); } @@ -1742,6 +1843,17 @@ async fn run_module_dispatch( } None => { let duration_ms = start.elapsed().as_millis() as u64; + if let Some(completion) = completion { + let outcome = completion.await; + if let Some(code) = strict_stream_error(&outcome) { + return Err(errors.report( + map_apcore_error_to_exit_code(code), + &format!("Streaming completion failed ({code})."), + Some(&serde_json::json!({"code": code})), + Some((&input_value, duration_ms)), + )); + } + } audit_success(module_id, &input_value, duration_ms); return Ok(None); } diff --git a/cli/rust/src/ref_resolver.rs b/cli/rust/src/ref_resolver.rs index 7a2732b2..eed01a9a 100644 --- a/cli/rust/src/ref_resolver.rs +++ b/cli/rust/src/ref_resolver.rs @@ -211,7 +211,11 @@ fn resolve_node( })?; visiting.insert(ref_path.clone()); - let result = resolve_node(def, defs, depth + 1, max_depth, visiting, module_id)?; + let mut result = resolve_node(def, defs, depth + 1, max_depth, visiting, module_id)?; + // A default attached to the reference site configures that CLI flag. + if let (Some(default), Some(resolved)) = (obj.get("default"), result.as_object_mut()) { + resolved.insert("default".into(), default.clone()); + } // Keep ref_path in visiting for the duration of this chain to detect cycles. // It remains in visiting intentionally — siblings go through a fresh chain // because we only remove entries when unwinding past the insertion point. @@ -244,6 +248,14 @@ fn resolve_node( .cloned() .unwrap_or_default(); + let mut types = resolved_branches + .iter() + .filter_map(|branch| branch.get("type")); + let container_type = types + .next() + .filter(|kind| matches!(kind.as_str(), Some("object" | "array"))) + .filter(|kind| types.all(|other| other == *kind)) + .cloned(); let merged = merge_allof(&parent_required, resolved_branches); let merged_map = match merged { Value::Object(m) => m, @@ -270,6 +282,9 @@ fn resolve_node( result_map.insert(k.clone(), v.clone()); } } + if let Some(container_type) = container_type { + result_map.entry("type").or_insert(container_type); + } return Ok(Value::Object(result_map)); } diff --git a/cli/rust/src/schema_parser.rs b/cli/rust/src/schema_parser.rs index 04361c5a..9641b374 100644 --- a/cli/rust/src/schema_parser.rs +++ b/cli/rust/src/schema_parser.rs @@ -26,6 +26,7 @@ pub const RESERVED_PROPERTY_NAMES: &[&str] = &[ "dry_run", "trace", "stream", + "strict_stream", "strategy", "approval_timeout", "approval_token", @@ -144,6 +145,24 @@ pub fn extract_help_with_limit(prop_schema: &Value, max_len: usize) -> Option bool { + let is_container = |kind| matches!(kind, "object" | "array"); + match prop_schema.get("type") { + Some(Value::String(kind)) => is_container(kind), + Some(Value::Array(kinds)) => { + kinds + .iter() + .any(|kind| kind.as_str().is_some_and(is_container)) + && kinds.iter().all(|kind| match kind.as_str() { + Some("null") => true, + Some(kind) => is_container(kind), + None => false, + }) + } + _ => false, + } +} + /// Map a single schema property to a clap::Arg. /// /// Returns an error only for flag collisions (detected at schema_to_clap_args level). @@ -153,16 +172,18 @@ pub fn map_type(prop_name: &str, prop_schema: &Value) -> Result. Type coercion to JSON - // numbers/booleans happens in reconvert_enum_values and collect_input. + // Keep argument values available to the dispatcher as strings, except + // for file paths and boolean pairs handled by their own parsers. let arg = match schema_type { Some("integer") | Some("number") => arg, Some("string") if is_file_property(prop_name, prop_schema) => { arg.value_parser(clap::value_parser!(PathBuf)) } - Some("string") | Some("object") | Some("array") => arg, + Some("string") => arg, Some(unknown) => { warn!( "Unknown schema type '{}' for property '{}', defaulting to string.", @@ -331,7 +352,11 @@ pub fn schema_to_clap_args_with_limit( } // Enum handling: properties with an "enum" array (and type != "boolean"). - if let Some(enum_values) = prop_schema.get("enum").and_then(|v| v.as_array()) { + if let Some(enum_values) = prop_schema + .get("enum") + .and_then(|v| v.as_array()) + .filter(|_| !is_structured_option(prop_schema)) + { if enum_values.is_empty() { warn!( "Empty enum for property '{}', falling through to plain string arg.", diff --git a/cli/rust/tests/conformance_structured_flags.rs b/cli/rust/tests/conformance_structured_flags.rs new file mode 100644 index 00000000..dcc93251 --- /dev/null +++ b/cli/rust/tests/conformance_structured_flags.rs @@ -0,0 +1,206 @@ +use std::path::PathBuf; +use std::sync::{ + atomic::{AtomicUsize, Ordering}, + Arc, +}; + +use apcore::{Config, Context, Executor, Module, ModuleError, Registry}; +use apcore_cli::discovery::{ApCoreRegistryProvider, RegistryProvider}; +use apcore_cli::{ + build_module_command, dispatch_module_with_options, DispatchOptions, ErrorStream, +}; +use serde::Deserialize; +use serde_json::{json, Value}; + +const MODULE: &str = "fixture.echo"; + +#[derive(Deserialize)] +struct Fixture { + schema: Value, + test_cases: Vec, +} + +#[derive(Deserialize)] +struct Case { + id: String, + args: Vec, + expected: Expected, +} + +#[derive(Deserialize)] +struct Expected { + exit_code: i32, + calls: usize, + input: Option, +} + +struct Echo { + schema: Value, + calls: Arc, +} + +#[async_trait::async_trait] +impl Module for Echo { + fn input_schema(&self) -> Value { + self.schema.clone() + } + + fn output_schema(&self) -> Value { + json!({"type": "object"}) + } + + fn description(&self) -> &'static str { + "Echo the arguments received from the generated CLI command" + } + + async fn execute( + &self, + inputs: Value, + _context: &Context, + ) -> Result { + self.calls.fetch_add(1, Ordering::SeqCst); + Ok(inputs) + } +} + +async fn run_case(schema: &Value, args: &[String], id: &str, expected: &Expected) { + let calls = Arc::new(AtomicUsize::new(0)); + let registry = || { + let registry = Registry::new(); + registry + .register_module( + MODULE, + Box::new(Echo { + schema: schema.clone(), + calls: Arc::clone(&calls), + }), + ) + .unwrap(); + registry + }; + let provider = ApCoreRegistryProvider::new(registry()); + let executor = Executor::new(registry(), Config::default()); + let descriptor = provider.get_module_descriptor(MODULE).unwrap(); + let matches = build_module_command(&descriptor) + .unwrap() + .try_get_matches_from(std::iter::once(MODULE).chain(args.iter().map(String::as_str))) + .unwrap(); + let observed = Arc::new(std::sync::Mutex::new(Vec::new())); + let options = DispatchOptions { + print_result: false, + error_stream: ErrorStream::Custom(Arc::new({ + let observed = Arc::clone(&observed); + move |message| observed.lock().unwrap().push(message.to_owned()) + })), + ..DispatchOptions::default() + }; + let result = + dispatch_module_with_options(MODULE, &matches, &provider, &executor, &options).await; + let errors = observed.lock().unwrap(); + assert_eq!( + calls.load(Ordering::SeqCst), + expected.calls, + "{id}: {result:?} {errors:?}" + ); + if expected.exit_code == 0 { + assert_eq!(result, Ok(expected.input.clone()), "{id}: {errors:?}"); + assert!(errors.is_empty(), "{id}: {errors:?}"); + } else { + assert_eq!(result, Err(expected.exit_code), "{id}: {errors:?}"); + assert!( + errors + .iter() + .any(|error| error.contains("SCHEMA_VALIDATION_ERROR")), + "{id}: {errors:?}" + ); + } +} + +#[tokio::test] +async fn generated_commands_decode_structured_flags_from_shared_fixture() { + let root = std::env::var_os("APCORE_CLI_SPEC_REPO") + .map(PathBuf::from) + .unwrap_or_else(|| PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("..")); + let path = root.join("conformance/fixtures/structured_flags.json"); + let source = std::fs::read(&path).unwrap_or_else(|error| { + panic!("read fixture {}: {error}", path.display()); + }); + let fixture: Fixture = serde_json::from_slice(&source).expect("parse structured flag fixture"); + for case in fixture.test_cases { + run_case(&fixture.schema, &case.args, &case.id, &case.expected).await; + } +} + +#[tokio::test] +async fn structured_defaults_follow_json_input_and_explicit_flag_precedence() { + let schema = json!({ + "type": "object", + "properties": { + "filters": {"$ref": "#/$defs/Filters"}, + "labels": {"type": "array", "items": {"type": "string"}, "default": ["schema"]}, + }, + "$defs": {"Filters": {"type": "object", "default": {"source": "schema"}}}, + "required": ["filters", "labels"], + }); + let json_input = [ + "--input", + r#"{"filters":{"source":"input"},"labels":["input"]}"#, + ]; + for (id, args, output) in [ + ( + "native defaults", + vec![], + json!({"filters": {"source": "schema"}, "labels": ["schema"]}), + ), + ( + "input before defaults", + json_input.to_vec(), + json!({"filters": {"source": "input"}, "labels": ["input"]}), + ), + ( + "flags before input", + [&json_input[..], &["--filters", r#"{"source":"flag"}"#]].concat(), + json!({"filters": {"source": "flag"}, "labels": ["input"]}), + ), + ] { + let args: Vec = args.into_iter().map(str::to_owned).collect(); + run_case( + &schema, + &args, + id, + &Expected { + exit_code: 0, + calls: 1, + input: Some(output), + }, + ) + .await; + } +} + +#[tokio::test] +async fn composition_and_reference_siblings_keep_container_flags_typed() { + let schema = json!({ + "type": "object", + "properties": { + "filters": {"allOf": [{"$ref": "#/$defs/Filters"}]}, + "labels": {"$ref": "#/$defs/Labels", "default": ["adjacent"]}, + }, + "$defs": { + "Filters": {"type": "object"}, + "Labels": {"type": "array", "items": {"type": "string"}}, + }, + "required": ["filters", "labels"], + }); + run_case( + &schema, + &["--filters".into(), "{\"active\":true}".into()], + "composed container and adjacent default", + &Expected { + exit_code: 0, + calls: 1, + input: Some(json!({"filters": {"active": true}, "labels": ["adjacent"]})), + }, + ) + .await; +} diff --git a/cli/rust/tests/test_cli.rs b/cli/rust/tests/test_cli.rs index 4aa446d0..03b1de3c 100644 --- a/cli/rust/tests/test_cli.rs +++ b/cli/rust/tests/test_cli.rs @@ -382,6 +382,196 @@ fn status_registry(streaming: bool) -> apcore::Registry { registry } +struct StrictStreamModule { + mode: String, + calls: std::sync::Arc, +} + +#[async_trait::async_trait] +impl apcore::Module for StrictStreamModule { + fn input_schema(&self) -> Value { + json!({"type": "object"}) + } + + fn output_schema(&self) -> Value { + json!({"type": "object", "required": ["value"], "properties": {"value": {"type": "integer"}}}) + } + + fn description(&self) -> &'static str { + "Provide chunks for strict completion" + } + + fn annotations(&self) -> apcore::ModuleAnnotations { + apcore::ModuleAnnotations { + streaming: self.mode != "fallback", + ..Default::default() + } + } + + async fn execute( + &self, + _inputs: Value, + _ctx: &apcore::Context, + ) -> Result { + assert_eq!(self.mode, "fallback"); + self.calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + Ok(json!({"value": 9})) + } + + fn as_streaming(&self) -> Option<&dyn apcore::StreamingModule> { + (self.mode != "fallback").then_some(self) + } + + fn stream(&self, inputs: Value, ctx: &apcore::Context) -> Option { + self.as_streaming() + .map(|module| module.stream_typed(inputs, ctx)) + } +} + +impl apcore::StreamingModule for StrictStreamModule { + fn stream_typed(&self, _inputs: Value, _ctx: &apcore::Context) -> apcore::ChunkStream { + self.calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + let value = if matches!(self.mode.as_str(), "validation" | "legacy_validation") { + json!("invalid") + } else { + json!(9) + }; + Box::pin(futures_util::stream::iter([Ok(json!({"value": value}))])) + } +} + +#[tokio::test] +async fn strict_stream_retains_jsonl_and_audits_only_the_completed_outcome() { + use apcore_cli::cli::{exec_command, set_audit_logger, set_executables}; + use apcore_cli::discovery::ApCoreRegistryProvider; + use apcore_cli::dispatch_module_with_result; + use apcore_cli::security::AuditLogger; + use std::sync::{ + atomic::{AtomicUsize, Ordering}, + Arc, + }; + + const CHILD_MODE: &str = "APCORE_CLI_TEST_STRICT_STREAM"; + const AUDIT_PATH: &str = "APCORE_CLI_TEST_AUDIT_PATH"; + const MODULE: &str = "test.strict_stream"; + if let Ok(mode) = std::env::var(CHILD_MODE) { + let calls = Arc::new(AtomicUsize::new(0)); + let registry = || { + let registry = apcore::Registry::new(); + registry + .register_module( + MODULE, + Box::new(StrictStreamModule { + mode: mode.clone(), + calls: Arc::clone(&calls), + }), + ) + .unwrap(); + registry + }; + let provider = ApCoreRegistryProvider::new(registry()); + let executor = apcore::Executor::new(registry(), apcore::Config::default()); + set_audit_logger(Some(AuditLogger::new(Some( + std::env::var(AUDIT_PATH).unwrap().into(), + )))); + if mode == "after" { + executor + .use_middleware(Box::new(apcore::middleware::adapters::AfterAdapter::new( + "fail_after", + |_, _, _, _| async { + Err(apcore::ModuleError::new( + apcore::ErrorCode::ModuleExecuteError, + "after failure", + )) + }, + ))) + .unwrap(); + } + if mode == "script" { + set_executables(HashMap::from([( + MODULE.to_string(), + "/not-a-test-program".into(), + )])); + } + let stream_flag = if mode == "legacy_validation" { + "--stream" + } else { + "--strict-stream" + }; + let matches = exec_command().get_matches_from(["exec", MODULE, stream_flag]); + let result = + dispatch_module_with_result(MODULE, &matches, &provider, &executor, true).await; + assert_eq!(calls.load(Ordering::SeqCst), usize::from(mode != "script")); + std::process::exit(result.err().unwrap_or(0)); + } + + let work = tempfile::tempdir().unwrap(); + for (mode, expected_exit, expected_value, expected_error) in [ + ("fallback", 0, Some(json!(9)), ""), + ("native", 0, Some(json!(9)), ""), + ("legacy_validation", 0, Some(json!("invalid")), ""), + ( + "validation", + 45, + Some(json!("invalid")), + "SCHEMA_VALIDATION_ERROR", + ), + ("after", 1, Some(json!(9)), "MODULE_EXECUTE_ERROR"), + ("script", 2, None, "requires in-process Core execution"), + ] { + let audit_path = work.path().join(format!("{mode}.jsonl")); + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "strict_stream_retains_jsonl_and_audits_only_the_completed_outcome", + "--nocapture", + ]) + .env(CHILD_MODE, mode) + .env(AUDIT_PATH, &audit_path) + .output() + .unwrap(); + let stderr = String::from_utf8_lossy(&output.stderr); + assert_eq!( + output.status.code(), + Some(expected_exit), + "{mode}: {stderr}" + ); + let objects: Vec = String::from_utf8_lossy(&output.stdout) + .lines() + .filter_map(|line| serde_json::from_str(line).ok()) + .collect(); + assert_eq!( + objects, + expected_value + .map(|value| json!({"value": value})) + .into_iter() + .collect::>() + ); + if mode == "script" { + assert!(stderr.contains(expected_error)); + assert!(!audit_path.exists()); + continue; + } + if expected_exit == 0 { + assert!(stderr.is_empty(), "{stderr}"); + } else { + assert!(stderr.contains(expected_error), "{stderr}"); + } + let audit = std::fs::read_to_string(&audit_path).unwrap(); + assert_eq!(audit.lines().count(), 1); + let audit: Value = serde_json::from_str(audit.trim()).unwrap(); + assert_eq!( + audit["status"], + if expected_exit == 0 { + "success" + } else { + "error" + } + ); + assert_eq!(audit["exit_code"], expected_exit); + } +} + #[tokio::test] async fn embedded_dispatch_returns_raw_result() { use apcore_cli::cli::exec_command; diff --git a/cli/typescript/CHANGELOG.md b/cli/typescript/CHANGELOG.md index 1b8612bb..7de9f8e7 100644 --- a/cli/typescript/CHANGELOG.md +++ b/cli/typescript/CHANGELOG.md @@ -5,6 +5,12 @@ All notable changes to apcore-cli (TypeScript SDK) will be documented in this fi The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [0.14.2-alpha.1] - Unreleased + +### Fixed + +- Accept structured arguments and enforce strict stream completion on supported in-process execution paths. + ## [0.14.1] - 2026-11-20 ### Added diff --git a/cli/typescript/README.md b/cli/typescript/README.md index 4f83774a..c02af91a 100644 --- a/cli/typescript/README.md +++ b/cli/typescript/README.md @@ -322,12 +322,26 @@ When executing a module (e.g. `apcore-cli math.add`), these built-in options are | `--dry-run` | Run preflight checks (schema, ACL, approval) without executing (FE-11) | | `--trace` | Emit execution pipeline trace (strategy, hooks, middleware timings) | | `--stream` | Stream results line-by-line for stream-capable modules | +| `--strict-stream` | Write JSONL and require a successful completion receipt | | `--strategy ` | Override execution strategy: `standard`, `internal`, `testing`, `performance`, or `minimal` | | `--fields ` | Select output fields via dot-path notation (e.g. `result.sum,meta.duration`) | | `--approval-timeout ` | Override approval timeout (default `60`) | | `--approval-token ` | Provide a pre-obtained approval token (bypasses interactive prompt) | Schema-generated flags (e.g. `--a`, `--b`) are added automatically from the module's `input_schema`. +Pass object and array values as quoted JSON, such as `--filters '{"active":true}'` +or `--labels '["a","b"]'`. The command decodes them before validation and +execution. Invalid JSON and values of the wrong schema type exit with code 45. +String options keep the literal text supplied on the command line. + +`--strict-stream` is available on generated module commands and `apcli exec`. +It writes provisional chunks as JSONL. A zero exit code and a successful audit +entry require the executor to finish with a canonical output and for output +validation and after middleware to pass or be skipped by execution policy. +On failure, the command reports the error on stderr and keeps any JSONL already +written. An executor without streaming completion support rejects the option +before invocation. The option requires in-process execution and cannot be +combined with `--sandbox`, `--trace`, or `--strategy`. #### `list` command flags (v0.6.0) diff --git a/cli/typescript/package.json b/cli/typescript/package.json index a75feed1..e4e3396d 100644 --- a/cli/typescript/package.json +++ b/cli/typescript/package.json @@ -1,6 +1,6 @@ { "name": "apcore-cli", - "version": "0.14.1", + "version": "0.14.2-alpha.1", "description": "CLI wrapper for the apcore core SDK — exposes apcore modules as CLI commands", "type": "module", "main": "./dist/index.js", @@ -30,8 +30,8 @@ "node": ">=20.0.0" }, "peerDependencies": { - "apcore-js": ">=0.33.0", - "apcore-toolkit": ">=0.15.0" + "apcore-js": ">=0.33.0 <1.0.0 || 1.0.0-alpha.1", + "apcore-toolkit": "0.15.1-alpha.1" }, "dependencies": { "@sinclair/typebox": "^0.34.0", @@ -47,8 +47,8 @@ "@typescript-eslint/eslint-plugin": "^8.59.0", "@typescript-eslint/parser": "^8.59.0", "@vitest/coverage-v8": "^5.1.0", - "apcore-js": "^0.32.3 || ^0.33.0", - "apcore-toolkit": ">=0.15.0", + "apcore-js": "^0.33.0 || 1.0.0-alpha.1", + "apcore-toolkit": "0.15.1-alpha.1", "apdev-js": "^0.2.4", "eslint": "^10.2.1", "tsup": "^8.0.0", diff --git a/cli/typescript/pnpm-lock.yaml b/cli/typescript/pnpm-lock.yaml index b7402c2d..0141cb2b 100644 --- a/cli/typescript/pnpm-lock.yaml +++ b/cli/typescript/pnpm-lock.yaml @@ -34,11 +34,11 @@ importers: specifier: ^5.1.0 version: 5.1.0(vitest@5.1.0) apcore-js: - specifier: ^0.32.3 || ^0.33.0 - version: 0.32.3 + specifier: ^0.33.0 || 1.0.0-alpha.1 + version: 0.33.0 apcore-toolkit: - specifier: '>=0.15.0' - version: 0.15.0(@sinclair/typebox@0.34.48) + specifier: 0.15.1-alpha.1 + version: 0.15.1-alpha.1(@sinclair/typebox@0.34.48) apdev-js: specifier: ^0.2.4 version: 0.2.4(typescript@5.9.3) @@ -731,16 +731,12 @@ packages: any-promise@1.3.0: resolution: {integrity: sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A==} - apcore-js@0.32.3: - resolution: {integrity: sha512-kmIDULt35c4vv9fxopnUomDi2Vvb9TzX4JdO9xfv6+XAE62OxuH4a6cvIQCuu62A5ESsIiwa2evhNX+PbPyqtA==} - engines: {node: '>=20.0.0'} - apcore-js@0.33.0: resolution: {integrity: sha512-+0UPovkB37qKy9kUwZmgSK6an+RqOUy+XOU9sEAauXStmQYIWmPBV7ACymQ9nwPI4RVAKiWbU4upMIqrCitxoQ==} engines: {node: '>=20.0.0'} - apcore-toolkit@0.15.0: - resolution: {integrity: sha512-PAF0NvA1TRUlS1uHyUwjfe/c7OqttgxxAyMkwcijvQqh45UhUx5V49I6LPrJpHSq1dvkY6komnEO5FeCi/CjqQ==} + apcore-toolkit@0.15.1-alpha.1: + resolution: {integrity: sha512-e8E9gtYAKLeBkpdIQisey4LogMdTR+qffL5PD5U0TyLiVl2v90xSBVXfHof3FkJWMj0/MKRqjlyzBk750xmt+w==} engines: {node: '>=20.10.0'} peerDependencies: '@sinclair/typebox': '>=0.31.0' @@ -1943,19 +1939,13 @@ snapshots: any-promise@1.3.0: {} - apcore-js@0.32.3: - dependencies: - '@sinclair/typebox': 0.34.48 - js-yaml: 4.3.2 - uuid: 11.1.1 - apcore-js@0.33.0: dependencies: '@sinclair/typebox': 0.34.48 js-yaml: 4.3.2 uuid: 11.1.1 - apcore-toolkit@0.15.0(@sinclair/typebox@0.34.48): + apcore-toolkit@0.15.1-alpha.1(@sinclair/typebox@0.34.48): dependencies: '@sinclair/typebox': 0.34.48 ajv: 8.20.0 diff --git a/cli/typescript/src/cli.ts b/cli/typescript/src/cli.ts index 94fbecc9..49a64c63 100644 --- a/cli/typescript/src/cli.ts +++ b/cli/typescript/src/cli.ts @@ -126,6 +126,8 @@ export interface Executor { callWithTrace?(moduleId: string, input: Record, options?: { strategy?: string }): Promise<[unknown, PipelineTrace]>; /** Stream execution — async iterator of chunks. */ stream?(moduleId: string, input: Record): AsyncIterable; + /** Optional Core API used by --strict-stream. */ + streamWithCompletion?(moduleId: string, input: Record, context?: unknown): import("./strict-stream.js").StreamExecution; /** * Describe the executor's currently-set strategy. Returns StrategyInfo * (apcore-js >= 0.18.0). Takes no arguments — to introspect a different diff --git a/cli/typescript/src/discovery.ts b/cli/typescript/src/discovery.ts index 86d19e17..5ee71fe7 100644 --- a/cli/typescript/src/discovery.ts +++ b/cli/typescript/src/discovery.ts @@ -33,6 +33,7 @@ import { } from "./acl-loader.js"; import { getAuditLogger } from "./security/audit.js"; import { sortModulesByUsage } from "./system-usage.js"; +import { executeStrictStream, validateStrictStreamOptions } from "./strict-stream.js"; const TAG_PATTERN = /^[a-z][a-z0-9_-]*$/; @@ -283,6 +284,7 @@ export function registerExecCommand( .option("--trace", "Enable pipeline trace output.", false) .option("--dry-run", "Validate inputs without executing the module.", false) .option("--stream", "Stream output as JSONL instead of buffering.", false) + .option("--strict-stream", "Stream JSONL and require a successful completion receipt.", false) .action(async ( moduleId: string, opts: { @@ -296,12 +298,16 @@ export function registerExecCommand( trace: boolean; dryRun: boolean; stream: boolean; + strictStream: boolean; }, ) => { let merged: Record = {}; const startTime = performance.now(); try { - if (!opts.dryRun) validateSandboxOptions(opts.sandbox, opts.trace, opts.stream, opts.strategy); + if (!opts.dryRun) { + validateSandboxOptions(opts.sandbox, opts.trace, opts.stream, opts.strategy); + if (opts.strictStream) validateStrictStreamOptions(executor, opts.sandbox, opts.trace, opts.strategy); + } assertValidModuleId(moduleId); const moduleDef = registry.getDefinition(moduleId); @@ -352,6 +358,11 @@ export function registerExecCommand( return; } + if (opts.strictStream) { + await executeStrictStream(executor, moduleId, merged, startTime); + return; + } + let result: unknown; // D11-011: --trace alone (no --strategy) must also route through // callWithTrace, matching Python discovery.py:382. Previously the @@ -380,7 +391,7 @@ export function registerExecCommand( auditLogger.logExecution(moduleId, merged, "success", 0, durationMs); } } catch (err: unknown) { - const failure = resolveModuleError(err, moduleId, resultOptions.exitCodes); + const failure = resolveModuleError(err, moduleId, resultOptions.exitCodes, opts.strictStream); const durationMs = Math.round(performance.now() - startTime); try { const auditLogger = getAuditLogger(); @@ -390,7 +401,7 @@ export function registerExecCommand( } catch { // Ignore audit failures during error handling } - await reportModuleError(failure, resultOptions, opts.format); + await reportModuleError(failure, opts.strictStream ? { ...resultOptions, errorStream: "stderr" } : resultOptions, opts.format); } }); apcliGroup.addCommand(execCmd); diff --git a/cli/typescript/src/error-output.ts b/cli/typescript/src/error-output.ts index 48a4f2fe..0f5801f5 100644 --- a/cli/typescript/src/error-output.ts +++ b/cli/typescript/src/error-output.ts @@ -33,13 +33,16 @@ export function resolveModuleError( error: unknown, moduleId: string, exitCodes: ModuleResultOptions["exitCodes"], + requireNonZero = false, ): ModuleErrorContext { const value = error as { code?: unknown } | null; const code = typeof value?.code === "string" ? value.code : null; const mapped = code !== null && exitCodes && Object.hasOwn(exitCodes, code) ? exitCodes[code] : undefined; - return { error, code, moduleId, exitCode: mapped ?? exitCodeForError(error) }; + const usableOverride = mapped !== undefined && + (!requireNonZero || (Number.isInteger(mapped) && mapped > 0 && mapped <= 255)); + return { error, code, moduleId, exitCode: usableOverride ? mapped : exitCodeForError(error) }; } export async function reportModuleError( diff --git a/cli/typescript/src/main.ts b/cli/typescript/src/main.ts index 6ada7bad..0fb38ee4 100644 --- a/cli/typescript/src/main.ts +++ b/cli/typescript/src/main.ts @@ -43,6 +43,7 @@ import { import { registerPipelineCommand } from "./strategy.js"; import { registerAclCommand } from "./acl-cmd.js"; import { registerOpenapiCommand } from "./openapi-cmd.js"; +import { executeStrictStream, validateStrictStreamOptions } from "./strict-stream.js"; import { assertDelegatedAccess, buildCliContext, @@ -215,6 +216,8 @@ export interface OptionConfig { enumOriginalTypes?: Record; /** Parser function for Commander (e.g. parseInt, parseFloat). */ parseArg?: (value: string) => unknown; + /** Decode an explicit structured option in the module command's error boundary. */ + parseStructuredArg?: (value: string) => unknown; } // --------------------------------------------------------------------------- @@ -1102,7 +1105,7 @@ export function main(progName?: string): void { /** * Build a Commander Command for a single apcore module. * - * Includes all 11 FE-11 options: --dry-run, --trace, --stream, --strategy, + * Includes --dry-run, --trace, --stream, --strict-stream, --strategy, * --approval-timeout, --approval-token, --fields, and enhanced --format choices. */ export function buildModuleCommand( @@ -1163,6 +1166,7 @@ export function buildModuleCommand( const traceOpt = new Option("--trace", "Show execution pipeline trace with per-step timing after the result.").default(false); // F6: --stream const streamOpt = new Option("--stream", "Stream module output as JSONL (one JSON object per line, flushed immediately).").default(false); + const strictStreamOpt = new Option("--strict-stream", "Stream JSONL and require a successful completion receipt.").default(false); // F8: --strategy const strategyOpt = new Option("--strategy ", "Execution pipeline strategy: standard (default), internal, testing, performance.") .choices(["standard", "internal", "testing", "performance", "minimal"]); @@ -1179,6 +1183,7 @@ export function buildModuleCommand( dryRunOpt.hideHelp(); traceOpt.hideHelp(); streamOpt.hideHelp(); + strictStreamOpt.hideHelp(); strategyOpt.hideHelp(); approvalTimeoutOpt.hideHelp(); approvalTokenOpt.hideHelp(); @@ -1193,6 +1198,7 @@ export function buildModuleCommand( cmd.addOption(dryRunOpt); cmd.addOption(traceOpt); cmd.addOption(streamOpt); + cmd.addOption(strictStreamOpt); cmd.addOption(strategyOpt); cmd.addOption(approvalTimeoutOpt); cmd.addOption(approvalTokenOpt); @@ -1212,25 +1218,19 @@ export function buildModuleCommand( cmd.addHelpText("after", "\n" + footerParts.join("\n") + "\n"); } - // Schema-generated options + // Commander gives each flag its camelCase option key. Preserve the + // original schema property name separately for the module input. + const schemaFlags: [OptionConfig, string][] = []; for (const opt of schemaOptions) { + const flagBase = opt.name.replace(/_/g, "-"); + const option = new Option(opt.isBooleanFlag ? `--${flagBase}` : opt.flags, opt.description) + .default(opt.defaultValue); + if (opt.parseArg) option.argParser(opt.parseArg); + cmd.addOption(option); + schemaFlags.push([opt, option.attributeName()]); if (opt.isBooleanFlag) { - // Commander does not parse the combined "--flag, --no-flag" spec the - // way Python click does — it ends up storing `false` for both forms. - // Register the affirmative form (carrying the schema default and help - // text) and a hidden `--no-` companion; commander auto-routes - // both to the same camelCase attribute and applies negation correctly. - const flagBase = opt.name.replace(/_/g, "-"); - cmd.addOption( - new Option(`--${flagBase}`, opt.description).default( - opt.defaultValue as boolean, - ), - ); + // Commander needs a separate negative option for the same attribute. cmd.addOption(new Option(`--no-${flagBase}`).hideHelp()); - } else if (opt.parseArg) { - cmd.option(opt.flags, opt.description, opt.parseArg, opt.defaultValue); - } else { - cmd.option(opt.flags, opt.description, opt.defaultValue as string | boolean | undefined); } } @@ -1246,6 +1246,7 @@ export function buildModuleCommand( const dryRun = options.dryRun as boolean; const traceFlag = options.trace as boolean; const streamFlag = options.stream as boolean; + const strictStreamFlag = options.strictStream as boolean; const strategyName = resolveStringOption(options.strategy, process.env.APCORE_CLI_STRATEGY); const approvalTimeout = resolveIntOption( options.approvalTimeout as number | undefined, @@ -1254,29 +1255,24 @@ export function buildModuleCommand( ); const approvalToken = options.approvalToken as string | undefined; - // Build schema kwargs from parsed options. Commander stores parsed flag - // values under camelCase keys (e.g. `--has-solution` -> `hasSolution`), - // but downstream module code keys off the original schema property names - // (snake_case) to match Python click and Rust clap behavior. Drive the - // mapping from schemaOptions so each value is written back under its - // original propName. - const schemaKwargs: Record = {}; - for (const opt of schemaOptions) { - const commanderKey = opt.name.replace(/_([a-z0-9])/g, (_, c: string) => c.toUpperCase()); - if (commanderKey in options) { - schemaKwargs[opt.name] = options[commanderKey]; - } else if (opt.name in options) { - schemaKwargs[opt.name] = options[opt.name]; - } - } - let merged: Record = {}; let preflightExitCode: number | undefined; const startTime = performance.now(); try { - if (!dryRun) validateSandboxOptions(sandboxEnabled, traceFlag, streamFlag, strategyName); + if (!dryRun) { + validateSandboxOptions(sandboxEnabled, traceFlag, streamFlag, strategyName); + if (strictStreamFlag) validateStrictStreamOptions(executor, sandboxEnabled, traceFlag, strategyName); + } // 1. Collect and merge input + const schemaKwargs: Record = {}; + for (const [opt, key] of schemaFlags) { + if (!Object.hasOwn(options, key)) continue; + const value = options[key]; + schemaKwargs[opt.name] = opt.parseStructuredArg && typeof value === "string" && cmd.getOptionValueSource(key) === "cli" + ? opt.parseStructuredArg(value) + : value; + } merged = await readModuleInput(stdinFlag, schemaKwargs, largeInput); // 2. Reconvert enum values @@ -1355,6 +1351,11 @@ export function buildModuleCommand( // 5. Execute with timing + if (strictStreamFlag) { + await executeStrictStream(executor, moduleId, merged, startTime); + return; + } + // -- Streaming execution (F6) -- if (streamFlag) { // Streaming always outputs JSONL; --format table is ignored (spec §3.6.2) @@ -1489,7 +1490,7 @@ export function buildModuleCommand( auditLogger.logExecution(moduleId, merged, "success", 0, durationMs); } } catch (err: unknown) { - const failure = resolveModuleError(err, moduleId, resultOptions.exitCodes); + const failure = resolveModuleError(err, moduleId, resultOptions.exitCodes, strictStreamFlag); const durationMs = Math.round(performance.now() - startTime); // Audit log (error) with real elapsed duration_ms @@ -1503,7 +1504,7 @@ export function buildModuleCommand( // Ignore audit failures during error handling } - await reportModuleError(failure, resultOptions, outputFormat); + await reportModuleError(failure, strictStreamFlag ? { ...resultOptions, errorStream: "stderr" } : resultOptions, outputFormat); } finally { // A preflight already wrote its result. Keep the host's exit outside // the dispatch catch so an exception from it is never reported again. diff --git a/cli/typescript/src/schema-parser.ts b/cli/typescript/src/schema-parser.ts index 8cfbc82c..e3788c58 100644 --- a/cli/typescript/src/schema-parser.ts +++ b/cli/typescript/src/schema-parser.ts @@ -5,7 +5,7 @@ */ import type { OptionConfig } from "./main.js"; -import { EXIT_CODES } from "./errors.js"; +import { EXIT_CODES, SchemaValidationError } from "./errors.js"; import { exitWith } from "./exit.js"; import { warn as logWarn } from "./logger.js"; @@ -77,6 +77,20 @@ export function extractHelp(propSchema: Record, maxLength = 100 return text; } +function parseStructuredValue(value: string, flag: string, type: "object" | "array"): unknown { + let decoded: unknown; + try { + decoded = JSON.parse(value); + } catch { + throw new SchemaValidationError(`${flag} must contain valid JSON.`); + } + const matches = type === "array" + ? Array.isArray(decoded) + : typeof decoded === "object" && decoded !== null && !Array.isArray(decoded); + if (!matches) throw new SchemaValidationError(`${flag} must be a JSON ${type}.`); + return decoded; +} + // --------------------------------------------------------------------------- // schemaToCliOptions // --------------------------------------------------------------------------- @@ -84,7 +98,7 @@ export function extractHelp(propSchema: Record, maxLength = 100 /** Reserved CLI option names that cannot be used by schema properties. */ const RESERVED_NAMES = new Set([ "input", "yes", "large_input", "format", "fields", "sandbox", - "all_options", "dry_run", "trace", "stream", "strategy", + "all_options", "dry_run", "trace", "stream", "strict_stream", "strategy", "approval_timeout", "approval_token", ]); @@ -151,7 +165,17 @@ export function schemaToCliOptions( : helpBase ?? ""; const defaultValue = propSchema.default as unknown; - if (typeResult === BOOLEAN_FLAG) { + const structuredType = propSchema.type; + if (structuredType === "object" || structuredType === "array") { + options.push({ + name: propName, + flags: `${flagName} `, + description: helpText, + defaultValue, + required: isRequired, + parseStructuredArg: value => parseStructuredValue(value, flagName, structuredType), + }); + } else if (typeResult === BOOLEAN_FLAG) { // Boolean flag pair: --flag/--no-flag const flagBase = propName.replace(/_/g, "-"); // Cross-SDK parity (D11-005): Rust schema_parser.rs:272 also tracks diff --git a/cli/typescript/src/strict-stream.ts b/cli/typescript/src/strict-stream.ts new file mode 100644 index 00000000..6e986722 --- /dev/null +++ b/cli/typescript/src/strict-stream.ts @@ -0,0 +1,89 @@ +import { ErrorCodes } from "apcore-js"; +import { buildCliContext } from "./acl-loader.js"; +import type { Executor } from "./cli.js"; +import { InvalidCliInputError, ModuleExecutionError, SchemaValidationError } from "./errors.js"; +import { getAuditLogger } from "./security/audit.js"; + +interface StepOutcome { + readonly status: string; + readonly reason?: string; +} + +interface StreamCompletion { + readonly reason: string; + readonly output: Record | null; + readonly outputValidation: StepOutcome; + readonly middlewareAfter: StepOutcome; + readonly errorCode: string | null; +} + +export interface StreamExecution { + readonly chunks: AsyncIterable; + readonly completion: Promise; + close(): Promise; +} + +const coreErrorCodes: ReadonlySet = new Set(Object.values(ErrorCodes)); + +export function validateStrictStreamOptions( + executor: Executor, + sandbox: boolean, + trace: boolean, + strategy?: string, +): void { + if (sandbox || trace || strategy) { + throw new InvalidCliInputError("--strict-stream cannot be combined with --sandbox, --trace, or --strategy."); + } + if (typeof executor.streamWithCompletion !== "function") { + throw new InvalidCliInputError("Strict streaming requires an Executor with stream completion support."); + } +} + +function stepSucceeded(step: StepOutcome): boolean { + return step.status === "passed" || (step.status === "skipped" && + (step.reason === "not_configured" || step.reason === "no_match" || step.reason === "strategy_skipped")); +} + +function completionError(receipt: StreamCompletion): Error | null { + if (receipt.reason === "completed" && receipt.output !== null && + stepSucceeded(receipt.outputValidation) && stepSucceeded(receipt.middlewareAfter)) return null; + if (receipt.errorCode !== null && coreErrorCodes.has(receipt.errorCode)) { + return Object.assign(new Error("Streaming invocation did not complete successfully"), { code: receipt.errorCode }); + } + if (receipt.reason === "completed" && !stepSucceeded(receipt.outputValidation)) { + return new SchemaValidationError("Streaming output validation did not complete successfully"); + } + return new ModuleExecutionError("Streaming invocation did not complete successfully"); +} + +export async function executeStrictStream( + executor: Executor, + moduleId: string, + input: Record, + startTime: number, +): Promise { + const stream = executor.streamWithCompletion?.(moduleId, input, buildCliContext()); + if (!stream) { + throw new InvalidCliInputError("Strict streaming requires an Executor with stream completion support."); + } + let writeOrIterationFailed = false; + try { + for await (const chunk of stream.chunks) { + const line = JSON.stringify(chunk) + "\n"; + // The failure path can exit the process immediately. Flush each line + // before advancing so already-emitted JSONL survives a piped exit. + await new Promise((resolve, reject) => { + process.stdout.write(line, error => error ? reject(error) : resolve()); + }); + } + } catch { + writeOrIterationFailed = true; + // The receipt keeps the canonical failure without exposing the iterator's + // exception details. Close also stops the invocation if output failed. + await stream.close(); + } + const failure = completionError(await stream.completion); + if (failure) throw failure; + if (writeOrIterationFailed) throw new ModuleExecutionError("Streaming output failed"); + getAuditLogger()?.logExecution(moduleId, input, "success", 0, Math.round(performance.now() - startTime)); +} diff --git a/cli/typescript/tests/acl-argument-scoped-approval.test.ts b/cli/typescript/tests/acl-argument-scoped-approval.test.ts index 757d52a5..71b456e5 100644 --- a/cli/typescript/tests/acl-argument-scoped-approval.test.ts +++ b/cli/typescript/tests/acl-argument-scoped-approval.test.ts @@ -32,15 +32,20 @@ import { CliApprovalHandler } from "../src/approval.js"; * discriminating — a call that merely succeeds proves nothing, since a gate * that never fired would also let it through. */ -function appWithArgumentScopedRule(autoApprove: boolean) { +async function appWithArgumentScopedRule(autoApprove: boolean) { const app = new APCore(); - app.registry.register("git.push", { + await app.registry.register("git.push", { moduleId: "git.push", + description: "Push the test branch", annotations: { requiresApproval: false }, inputSchema: { type: "object", properties: { remote: { type: "string" }, force: { type: "boolean" } }, }, + outputSchema: { + type: "object", + properties: { pushed: { type: "boolean" }, force: { type: "boolean" } }, + }, execute: async (input: Record) => ({ pushed: true, force: input.force === true, @@ -72,7 +77,7 @@ function appWithArgumentScopedRule(autoApprove: boolean) { describe("ACL argument-scoped approval reaches CliApprovalHandler", () => { it("runs an ungated call without consulting the handler", async () => { - const executor = appWithArgumentScopedRule(/*autoApprove*/ true); + const executor = await appWithArgumentScopedRule(/*autoApprove*/ true); await expect( executor.call("git.push", { remote: "origin" }), @@ -80,7 +85,7 @@ describe("ACL argument-scoped approval reaches CliApprovalHandler", () => { }); it("routes an ACL-gated call through the handler and runs it", async () => { - const executor = appWithArgumentScopedRule(/*autoApprove*/ true); + const executor = await appWithArgumentScopedRule(/*autoApprove*/ true); await expect( executor.call("git.push", { remote: "origin", force: true }), @@ -89,7 +94,7 @@ describe("ACL argument-scoped approval reaches CliApprovalHandler", () => { it("reports the governance-effective requirement from validate()", async () => { // §7.9.5: the union is what `apcli validate` and `--dry-run` forward. - const executor = appWithArgumentScopedRule(/*autoApprove*/ true); + const executor = await appWithArgumentScopedRule(/*autoApprove*/ true); const plain = await executor.validate("git.push", { remote: "origin" }); const forced = await executor.validate("git.push", { @@ -110,7 +115,7 @@ describe("ACL argument-scoped approval reaches CliApprovalHandler", () => { // and lets the test assert the stronger property directly — that the gate // *consulted a handler at all*, and for which call. const seen: string[] = []; - const executor = appWithArgumentScopedRule(/*autoApprove*/ true); + const executor = await appWithArgumentScopedRule(/*autoApprove*/ true); executor.setApprovalHandler({ async requestApproval(request: { moduleId: string; arguments: Record }) { seen.push(`${request.moduleId}(${Object.keys(request.arguments).sort().join(",")})`); diff --git a/cli/typescript/tests/acl-governance.test.ts b/cli/typescript/tests/acl-governance.test.ts index fea2bac1..12d8a0ea 100644 --- a/cli/typescript/tests/acl-governance.test.ts +++ b/cli/typescript/tests/acl-governance.test.ts @@ -822,11 +822,13 @@ describe("apcli acl status (FE-14 §4.7)", () => { describe("an attached ACL makes existing surfaces live (FE-14 §4.9)", () => { /** Real APCore holding `db.migrate` behind a deny rule. */ - function deniedApp() { + async function deniedApp() { const app = new APCore(); - app.registry.register("db.migrate", { + await app.registry.register("db.migrate", { moduleId: "db.migrate", + description: "Migrate the test database", inputSchema: { type: "object", properties: {} }, + outputSchema: { type: "object", properties: { migrated: { type: "boolean" } } }, execute: async () => ({ migrated: true }), // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any); @@ -844,7 +846,7 @@ describe("an attached ACL makes existing surfaces live (FE-14 §4.9)", () => { } it("T-ACL-22: a denied call raises ACL_DENIED, which the CLI maps to exit 77", async () => { - const executor = deniedApp(); + const executor = await deniedApp(); let caught: unknown; try { await executor.call("db.migrate", {}); @@ -858,7 +860,7 @@ describe("an attached ACL makes existing surfaces live (FE-14 §4.9)", () => { it("T-ACL-23: preflight reports the acl check as failed, and 77 is the first failed code", async () => { const { firstFailedExitCode } = await import("../src/output.js"); - const executor = deniedApp(); + const executor = await deniedApp(); const preflight = await executor.validate("db.migrate", {}); expect(preflight.valid).toBe(false); const aclCheck = preflight.checks.find( @@ -943,9 +945,11 @@ rules: // case above would be proving nothing about the ACL. attach(SANDBOX_ACL); const app = new APCore(); - app.registry.register("ops.control", { + await app.registry.register("ops.control", { moduleId: "ops.control", + description: "Run the test control operation", inputSchema: { type: "object", properties: {} }, + outputSchema: { type: "object", properties: { ran: { type: "boolean" } } }, execute: async () => ({ ran: true }), // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any); diff --git a/cli/typescript/tests/strict-stream.test.ts b/cli/typescript/tests/strict-stream.test.ts new file mode 100644 index 00000000..fcd159c4 --- /dev/null +++ b/cli/typescript/tests/strict-stream.test.ts @@ -0,0 +1,133 @@ +import { mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { Executor, Registry, STREAMING_MARKER, createAnnotations } from "apcore-js"; +import { describe, expect, it, vi } from "vitest"; +import { buildModuleCommand, createCli } from "../src/main.js"; +import { AuditLogger, getAuditLogger, setAuditLogger } from "../src/security/audit.js"; + +const moduleId = "test.completion"; +const hasCompletion = "streamWithCompletion" in Executor.prototype; + +type Failure = "validation" | "after" | null; + +async function setup(entry: "generated" | "generic", failure: Failure = null, exitCodes?: Record) { + let calls = 0; + let streams = 0; + const registry = new Registry(); + await registry.register(moduleId, { + description: "Stream one module invocation", + annotations: createAnnotations({ streaming: true }), + [STREAMING_MARKER]: true, + inputSchema: { type: "object" }, + outputSchema: { type: "object", ...(failure === "validation" ? { required: ["absent"] } : {}) }, + execute: () => { calls++; return { result: "atomic" }; }, + async *stream() { streams++; yield { result: "chunk" }; }, + } as never); + const executor = Executor.fromRegistry(registry); + if (failure === "after") executor.useAfter(() => { throw new Error("private-after-cause"); }); + const exit = vi.fn(); + const previousLogger = getAuditLogger(); + const descriptor = registry.getDefinition(moduleId); + if (!descriptor) throw new Error("The streaming test module is not registered"); + const command = entry === "generated" + ? buildModuleCommand(descriptor, executor, 1000, undefined, undefined, { exit, exitCodes }) + : createCli({ registry, executor, exit, exitCodes }); + const auditDirectory = mkdtempSync(join(tmpdir(), "apcore-cli-strict-")); + const auditFile = join(auditDirectory, "audit.jsonl"); + setAuditLogger(new AuditLogger(auditFile)); + let stdoutFlushed = 0; + const stdout = vi.spyOn(process.stdout, "write").mockImplementation((_chunk, encoding, callback) => { + const done = typeof encoding === "function" ? encoding : callback; + if (done) setImmediate(() => { + stdoutFlushed++; + done(); + }); + return true; + }); + const stderr = vi.spyOn(process.stderr, "write").mockImplementation(() => true); + vi.spyOn(console, "warn").mockImplementation(() => undefined); + const prefix = entry === "generic" ? ["apcli", "exec", moduleId] : []; + return { + run: (flags: string[]) => command.parseAsync([...prefix, ...flags], { from: "user" }), + counts: () => ({ calls, streams }), exit, + stdout: () => stdout.mock.calls.map(([chunk]) => String(chunk)).join(""), + stdoutFlushed: () => stdoutFlushed, + stderr: () => stderr.mock.calls.map(([chunk]) => String(chunk)).join(""), + audit: () => readFileSync(auditFile, "utf8").trim().split("\n").map((line) => JSON.parse(line)), + close() { + setAuditLogger(previousLogger); + rmSync(auditDirectory, { recursive: true, force: true }); + vi.restoreAllMocks(); + }, + }; +} + +describe.each(["generated", "generic"] as const)("strict streaming via %s commands", (entry) => { + it("selects the supported path before execution", async () => { + const app = await setup(entry); + try { + await app.run(["--strict-stream"]); + if (hasCompletion) { + expect(app.stdout()).toBe('{"result":"chunk"}\n'); + expect(app.stdoutFlushed()).toBe(1); + expect(app.exit).not.toHaveBeenCalled(); + expect(app.audit()).toMatchObject([{ status: "success", exit_code: 0 }]); + expect(app.counts()).toEqual({ calls: 0, streams: 1 }); + } else { + expect(app.stdout()).toBe(""); + expect(app.stderr()).toMatch(/strict streaming.*requires/i); + expect(app.exit).toHaveBeenCalledWith(2); + expect(app.audit()).toMatchObject([{ status: "error", exit_code: 2 }]); + expect(app.counts()).toEqual({ calls: 0, streams: 0 }); + } + } finally { app.close(); } + }); + + it.skipIf(!hasCompletion).each([["validation", 45], ["after", 1]] as const)( + "keeps emitted JSONL and fails the audit on a %s error", async (failure, exitCode) => { + const app = await setup(entry, failure); + try { + await app.run(["--strict-stream"]); + expect(app.stdout()).toBe('{"result":"chunk"}\n'); + expect(app.stdoutFlushed()).toBe(1); + expect(app.stderr()).toContain("Streaming"); + expect(app.stderr()).not.toContain("private-after-cause"); + expect(app.exit).toHaveBeenCalledWith(exitCode); + expect(app.audit()).toMatchObject([{ status: "error", exit_code: exitCode }]); + expect(app.counts()).toEqual({ calls: 0, streams: 1 }); + } finally { app.close(); } + }, + ); + + it.skipIf(!hasCompletion)("does not apply a host's zero exit code to a strict failure", async () => { + const app = await setup(entry, "after", { MODULE_EXECUTE_ERROR: 0 }); + try { + await app.run(["--strict-stream"]); + expect(app.exit).toHaveBeenCalledWith(1); + expect(app.audit()).toMatchObject([{ status: "error", exit_code: 1 }]); + } finally { app.close(); } + }); + + it("rejects sandbox delegation without starting any invocation", async () => { + const app = await setup(entry); + try { + await app.run(["--sandbox", "--strict-stream"]); + expect(app.stdout()).toBe(""); + expect(app.stderr()).toContain("--sandbox"); + expect(app.exit).toHaveBeenCalledWith(2); + expect(app.counts()).toEqual({ calls: 0, streams: 0 }); + } finally { app.close(); } + }); +}); + +it("keeps the legacy stream completion and audit behavior", async () => { + const app = await setup("generated", "after"); + try { + await app.run(["--stream"]); + expect(app.stdout()).toBe('{"result":"chunk"}\n'); + expect(app.exit).not.toHaveBeenCalled(); + expect(app.audit()).toMatchObject([{ status: "success", exit_code: 0 }]); + expect(app.counts()).toEqual({ calls: 0, streams: 1 }); + } finally { app.close(); } +}); diff --git a/cli/typescript/tests/structured-flags.test.ts b/cli/typescript/tests/structured-flags.test.ts new file mode 100644 index 00000000..5eda9e88 --- /dev/null +++ b/cli/typescript/tests/structured-flags.test.ts @@ -0,0 +1,93 @@ +import { readFileSync } from "node:fs"; +import { Executor, Registry } from "apcore-js"; +import { describe, expect, it, vi } from "vitest"; +import { buildModuleCommand } from "../src/main.js"; + +interface FixtureCase { + id: string; + args: string[]; + expected: { exit_code: number; calls: number; input?: Record }; +} + +const fixture = JSON.parse(readFileSync( + new URL("../../conformance/fixtures/structured_flags.json", import.meta.url), "utf8", +)) as { + schema: { type: string; properties: Record>; required: string[] }; + test_cases: FixtureCase[]; +}; + +async function invoke(args: string[], inputSchema = fixture.schema) { + const moduleId = "test.structured"; + const inputs: Record[] = []; + const registry = new Registry(); + await registry.register(moduleId, { + description: "Accept JSON data from generated command options", + inputSchema, + outputSchema: { type: "object" }, + execute(input: Record) { + inputs.push(input); + return {}; + }, + } as never); + const descriptor = registry.getDefinition(moduleId); + if (!descriptor) throw new Error("The structured test module is not registered"); + const executor = Executor.fromRegistry(registry); + const validate = vi.spyOn(executor, "validate"); + const exit = vi.fn(); + const cmd = buildModuleCommand(descriptor, executor, 1000, undefined, undefined, { exit, printResult: false }); + const stdout = vi.spyOn(process.stdout, "write").mockImplementation(() => true); + const stderr = vi.spyOn(process.stderr, "write").mockImplementation(() => true); + try { + await cmd.parseAsync(args, { from: "user" }); + return { + inputs, + preflightInputs: validate.mock.calls.map(([, input]) => input), + exitCode: exit.mock.lastCall?.[0] ?? 0, + diagnostics: stderr.mock.calls.map(([chunk]) => String(chunk)).join(""), + }; + } finally { + validate.mockRestore(); + stdout.mockRestore(); + stderr.mockRestore(); + } +} + +describe("structured generated flags", () => { + it.each(fixture.test_cases)("$id", async ({ args, expected }) => { + const result = await invoke(args); + expect(result.exitCode).toBe(expected.exit_code); + expect(result.inputs).toHaveLength(expected.calls); + if (expected.input) expect(result.inputs[0]).toEqual(expected.input); + }); + + it("passes the decoded values into preflight without running the module", async () => { + const sample = fixture.test_cases.find(test => test.id === "objects_and_arrays"); + if (!sample?.expected.input) throw new Error("Expected input case missing"); + const result = await invoke(["--dry-run", ...sample.args]); + expect(result.exitCode).toBe(0); + expect(result.preflightInputs).toEqual([sample.expected.input]); + expect(result.inputs).toEqual([]); + }); + + it("rejects malformed structured arguments before preflight is called", async () => { + const result = await invoke(["--dry-run", "--filters", "{", "--labels", "[]"]); + expect(result.exitCode).toBe(45); + expect(result.preflightInputs).toEqual([]); + expect(result.inputs).toEqual([]); + expect(result.diagnostics).toContain("--filters"); + }); + + it("uses schema defaults as typed values", async () => { + const schemaWithDefaults = { + ...fixture.schema, + properties: { + ...fixture.schema.properties, + filters: { ...fixture.schema.properties.filters, default: { active: true } }, + labels: { ...fixture.schema.properties.labels, default: ["default"] }, + }, + }; + const result = await invoke([], schemaWithDefaults); + expect(result.exitCode).toBe(0); + expect(result.inputs).toEqual([{ filters: { active: true }, labels: ["default"] }]); + }); +}); diff --git a/mcp/conformance/fixtures/openapi_backend.json b/mcp/conformance/fixtures/openapi_backend.json index 0a8078db..1e46078b 100644 --- a/mcp/conformance/fixtures/openapi_backend.json +++ b/mcp/conformance/fixtures/openapi_backend.json @@ -57,12 +57,79 @@ "expected_modules": [ { "module_id": "list_pets", + "description": "GET /pets", "mcp_tool_name": "list_pets", "openai_function_name": "list_pets" } ], "expected_skipped": [] }, + { + "id": "registered_proxy_description_falls_back_only_when_blank", + "description": "Blank scanner descriptions use the effective method and path. The fallback counts Unicode characters. Supplied descriptions survive registration.", + "document": { + "openapi": "3.0.3", + "info": { + "title": "Proxy descriptions", + "version": "1.0.0" + }, + "servers": [ + { + "url": "https://api.example.com" + } + ], + "paths": { + "/blank": { + "get": { + "operationId": "getBlank", + "summary": " \t\u0085\u2028", + "responses": { + "200": { + "description": "ok" + } + } + } + }, + "/described": { + "get": { + "operationId": "getDescribed", + "summary": "List listed items.", + "responses": { + "200": { + "description": "ok" + } + } + } + }, + "/🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀": { + "head": { + "operationId": "getLong", + "responses": { + "200": { + "description": "ok" + } + } + } + } + } + }, + "options": {}, + "expected_modules": [ + { + "module_id": "get_blank", + "description": "GET /blank" + }, + { + "module_id": "get_described", + "description": "List listed items." + }, + { + "module_id": "get_long", + "description": "HEAD /🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀" + } + ], + "expected_skipped": [] + }, { "id": "path_derived_id_dash_normalized_for_openai", "description": "A path-derived ID the scanner emits already legal is registered as it is; the MCP tool name keeps its dots verbatim and the OpenAI function name replaces them with dashes. Underscores are untouched on both surfaces.", diff --git a/mcp/docs/features/openapi-backend.md b/mcp/docs/features/openapi-backend.md index 52c16242..b98d6976 100644 --- a/mcp/docs/features/openapi-backend.md +++ b/mcp/docs/features/openapi-backend.md @@ -65,8 +65,11 @@ load_spec(url|path) → OpenAPIScanner.scan() → HTTPProxyRegistryWriter.write( already-parsed document), `OpenAPIScanner.scan`, and `HTTPProxyRegistryWriter.write`, in that order, and returns the registry. Any behaviour difference between the three bridges that is not a difference in the toolkit is a defect. The bridge registers the module IDs the scanner emits as - they are; the one policy it adds is to [skip a module whose emitted ID apcore's registry would - still refuse](#module_id-tool-name), with a WARNING, rather than hand it to the writer. + they are. It logs a warning and [skips modules whose IDs apcore would refuse](#module_id-tool-name). + Before writing a proxy module, the bridge supplies a missing or blank description from the + effective HTTP method and path, such as `GET /pets`. The generated description occupies one + line, has at most 200 Unicode characters, and leaves the description supplied by the scan + or its hooks intact when it contains text. 2. **Surface what the scan found.** Every `ScannedModule.warnings` entry and every failed `WriteResult` MUST reach the operator at startup — WARNING for a scan warning, ERROR for a write failure — naming the module ID. A spec with an unresolvable `$ref` produces a tool with an empty @@ -188,9 +191,8 @@ operation whose derived ID collides with a discovered extension module fails the **A prefix reduces the probability of a collision; it does not eliminate one.** Nothing stops an extensions directory from already containing a `petstore.*` module, and a duplicate reaches the writer as a **failed `WriteResult`**, not an exception — the toolkit's writers report per-module -outcomes rather than aborting. Under the "log at ERROR and keep going" rule below, that would leave -the server running with a **partial registry**: some operations served, one silently absent, and a -tool the agent was told about missing from `tools/list`. +outcomes for the batch. The bridge checks collisions before writing so it can identify every +affected ID and leave the registry untouched. Two requirements, and they are not the same mechanism: @@ -211,16 +213,12 @@ Two requirements, and they are not the same mechanism: |---|---|---| | Derived ID collides with a module already in the registry | Preflight, before any write | **Fatal**, atomic, all colliding IDs named. Nothing registers | | Two operations in **one document** derive the same ID | Inside the scanner | Renamed `_2`, `_3`, … with a warning on the module. Never reaches the preflight | - | One module's schema or proxy construction fails | `WriteResult` | ERROR logged naming the module; the rest still register | + | A selected operation fails to register | Writer results and registry lookup | **Fatal**, names every failed or absent module | - The distinction is whether the deployment is **coherent**. A colliding ID means the operator's - two sources disagree about what a name means, and there is no correct answer for the bridge to - pick — serving either one silently is a worse outcome than refusing. A module that fails to - build is a defect in one operation, and dropping it costs one tool. - - This is a **bridge** decision, not a writer behaviour: apcore-toolkit's writers return - per-module `WriteResult`s by contract and do not distinguish these cases, so the escalation has - to happen here. + The bridge checks each selected ID against the writer results and the registry before returning + a backend. The TypeScript bridge waits for pending host registration promises. Successful + writes may already be present when a later registration fails. Assemble in a startup-owned + registry and publish it only after backend construction succeeds. --- diff --git a/mcp/python/CHANGELOG.md b/mcp/python/CHANGELOG.md index d3951327..5be7d62b 100644 --- a/mcp/python/CHANGELOG.md +++ b/mcp/python/CHANGELOG.md @@ -6,6 +6,12 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [0.23.5a1] - Unreleased + +### Fixed + +- Route inbound cancellation to the active request, derive terminal stream results from Core when available, and fail startup when OpenAPI tools fail to register. + ## [0.23.4] - 2026-11-20 ### Changed diff --git a/mcp/python/pyproject.toml b/mcp/python/pyproject.toml index 71b87052..443d0d3b 100644 --- a/mcp/python/pyproject.toml +++ b/mcp/python/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "apcore-mcp" -version = "0.23.4" +version = "0.23.5a1" description = "Automatic MCP Server & OpenAI Tools Bridge for apcore" readme = "README.md" license = "Apache-2.0" @@ -25,7 +25,7 @@ classifiers = [ "Topic :: Scientific/Engineering :: Artificial Intelligence", ] dependencies = [ - "apcore>=0.33.0", + "apcore>=0.33.0,<=1.0.0a1", "mcp>=1.26,<2.0", "jsonschema>=4.20,<5", "referencing>=0.30,<1", @@ -51,7 +51,7 @@ markdown = [ # entry point raises with an actionable install message instead of returning # None. openapi = [ - "apcore-toolkit[http-proxy]>=0.15.0", + "apcore-toolkit[http-proxy]==0.15.1a1", ] dev = [ @@ -61,7 +61,7 @@ dev = [ "mypy>=1.0", "ruff>=0.1", "apdev[dev]>=0.2.3", - "apcore-toolkit[http-proxy]>=0.15.0", + "apcore-toolkit[http-proxy]==0.15.1a1", ] [project.scripts] diff --git a/mcp/python/src/apcore_mcp/auth/middleware.py b/mcp/python/src/apcore_mcp/auth/middleware.py index 18fc4989..56e90a86 100644 --- a/mcp/python/src/apcore_mcp/auth/middleware.py +++ b/mcp/python/src/apcore_mcp/auth/middleware.py @@ -14,6 +14,8 @@ logger = logging.getLogger(__name__) # Bridge between ASGI middleware and MCP handler +_REQUEST_IDENTITY_KEY = "apcore_mcp.auth_identity" + auth_identity_var: ContextVar[Identity | None] = ContextVar("auth_identity", default=None) @@ -81,7 +83,7 @@ async def __call__(self, scope: dict[str, Any], receive: Any, send: Any) -> None ) token = auth_identity_var.set(identity) try: - await self._app(scope, receive, send) + await self._app({**scope, _REQUEST_IDENTITY_KEY: identity}, receive, send) finally: auth_identity_var.reset(token) return @@ -96,7 +98,7 @@ async def __call__(self, scope: dict[str, Any], receive: Any, send: Any) -> None token = auth_identity_var.set(identity) try: - await self._app(scope, receive, send) + await self._app({**scope, _REQUEST_IDENTITY_KEY: identity}, receive, send) finally: auth_identity_var.reset(token) diff --git a/mcp/python/src/apcore_mcp/openapi_backend.py b/mcp/python/src/apcore_mcp/openapi_backend.py index 076f6c8d..cb471dd3 100644 --- a/mcp/python/src/apcore_mcp/openapi_backend.py +++ b/mcp/python/src/apcore_mcp/openapi_backend.py @@ -17,6 +17,7 @@ import re import warnings from collections.abc import Callable +from copy import copy from pathlib import Path from typing import Any @@ -295,13 +296,24 @@ def openapi_backend( base_url=effective_base_url, auth_header_factory=auth_header_factory, ) - for result in writer.write(modules, target): - if getattr(result, "verification_error", None): - logger.error( - "OpenAPI module %s failed to register: %s", - getattr(result, "module_id", "?"), - result.verification_error, - ) + proxy_modules = [] + for module in modules: + if not module.description.strip(): + method, path = toolkit.read_proxy_route(module, default_method="GET") + description = " ".join(f"{method.upper()} {path or '/'}".split())[:200] + module = copy(module) + module.description = description + proxy_modules.append(module) + results = {result.module_id: result for result in writer.write(proxy_modules, target)} + failures = [] + for module in modules: + result = results.get(module.module_id) + if result is not None and result.verified and target.get(module.module_id) is not None: + continue + detail = result.verification_error if result is not None else None + failures.append(f"{module.module_id}: {detail or 'module not registered'}") + if failures: + raise ValueError("OpenAPI registration incomplete: " + "; ".join(failures)) if not acknowledge_unapproved_writes: _warn_if_writes_have_no_approval_path(modules, target) diff --git a/mcp/python/src/apcore_mcp/server/factory.py b/mcp/python/src/apcore_mcp/server/factory.py index 0cbb12bf..bf500e04 100644 --- a/mcp/python/src/apcore_mcp/server/factory.py +++ b/mcp/python/src/apcore_mcp/server/factory.py @@ -2,6 +2,7 @@ from __future__ import annotations +import asyncio import json import logging import math @@ -10,7 +11,9 @@ from typing import Any from urllib.parse import parse_qs, unquote +import anyio import jsonschema # type: ignore[import-untyped] # MCP supplies jsonschema without its optional typing stubs. +from apcore import CancelToken, Identity from apcore.schema.exporter import SchemaExporter from apcore.schema.types import SchemaDefinition from mcp import types as mcp_types @@ -24,7 +27,7 @@ import apcore_mcp.markdown as _markdown from apcore_mcp.adapters.annotations import AnnotationMapper -from apcore_mcp.auth.middleware import auth_identity_var +from apcore_mcp.auth.middleware import _REQUEST_IDENTITY_KEY, auth_identity_var from apcore_mcp.server.approval_bridge import ApprovalBridge from apcore_mcp.server.async_task_bridge import RESERVED_PREFIX, AsyncTaskBridge from apcore_mcp.server.transport import _protocol_source_var, transport_session_var @@ -113,6 +116,17 @@ def is_readonly_system_module(module_id: str) -> bool: _PROTOCOL_SPEC_VERSION = "1.30.0" +def _request_identity() -> Identity | None: + from mcp.server.lowlevel.server import request_ctx + + ctx = request_ctx.get(None) + scope = getattr(ctx.request, "scope", None) if ctx is not None else None + if isinstance(scope, dict) and _REQUEST_IDENTITY_KEY in scope: + identity = scope[_REQUEST_IDENTITY_KEY] + return identity if isinstance(identity, Identity) else None + return auth_identity_var.get() + + def _supports_structured_output() -> bool: """Read protocol state from the MCP session or trusted HTTP request.""" from mcp.server.lowlevel.server import request_ctx @@ -545,7 +559,7 @@ async def handle_call_tool(name: str, arguments: dict[str, Any]) -> mcp_types.Ca extra["_meta"] = meta_dump # Bridge authenticated identity from ASGI middleware - identity = auth_identity_var.get() + identity = _request_identity() if identity is not None: extra["identity"] = identity @@ -615,7 +629,21 @@ async def send_notification(notification: dict[str, Any]) -> None: content = [{"type": "text", "text": info["message"]}] is_error = True else: - content, is_error, _trace_id = await router.handle_call(name, arguments or {}, extra=extra) + # The SDK cancels the request coroutine for its own session and + # JSON-RPC request ID. Signal the linked APCore invocation + # before letting that cancellation interrupt its cleanup. + token = CancelToken() + extra["_transport_cancel_token"] = token + extra["call_id"] = f"mcp:{id(ctx.session)}:{ctx.request_id!r}" + call = asyncio.create_task(router.handle_call(name, arguments or {}, extra=extra)) + try: + content, is_error, _trace_id = await asyncio.shield(call) + except asyncio.CancelledError: + token.cancel() + call.cancel() + with anyio.CancelScope(shield=True): + await asyncio.gather(call, return_exceptions=True) + raise # A direct CallToolResult preserves error status and text metadata. text_contents: list[mcp_types.TextContent] = [] @@ -784,7 +812,7 @@ async def _read_system_resource( raise ValueError(f"Resource not found: {uri_str}") extra: dict[str, Any] = {} - identity = auth_identity_var.get() + identity = _request_identity() if identity is not None: extra["identity"] = identity diff --git a/mcp/python/src/apcore_mcp/server/router.py b/mcp/python/src/apcore_mcp/server/router.py index 6a809a96..456d162c 100644 --- a/mcp/python/src/apcore_mcp/server/router.py +++ b/mcp/python/src/apcore_mcp/server/router.py @@ -9,9 +9,10 @@ import uuid from collections import OrderedDict from collections.abc import Callable, Coroutine +from contextlib import aclosing from typing import Any -from apcore import CancelToken, Context +from apcore import APCore, CancelToken, Context, Executor, ModuleError, StreamingModule from apcore.trace_context import TraceContext, TraceParent from apcore_mcp.adapters.errors import ErrorMapper @@ -25,6 +26,7 @@ # in FIFO order. Tombstones for unknown call_ids accumulate here, so # without an eviction cap a long-running server would leak memory. _CANCEL_TOKENS_MAX = 4096 +_POLICY_SKIPS = {"not_configured", "no_match", "strategy_skipped"} def _deep_merge(base: dict[str, Any], overlay: dict[str, Any], depth: int = 0) -> dict[str, Any]: @@ -53,11 +55,10 @@ class ExecutionRouter: ``(content, is_error, trace_id)`` tuple that the MCP factory can pass directly to ``CallToolResult``. - When the executor also exposes an async ``stream()`` method **and** - the caller provides a ``progress_token`` + ``send_notification`` - callback via the *extra* dict, the router iterates the async - generator and forwards each chunk as a ``notifications/progress`` - message, accumulating chunks via recursive deep merge. + Completion-capable executors supply the canonical stream result for + streaming modules even without a progress token. Progress callbacks + receive redacted chunks. Older Core executors use one ordinary call. + Custom duck-typed executors may still provide a legacy chunk stream. Args: executor: An apcore Executor instance (duck-typed -- must expose @@ -85,6 +86,8 @@ def __init__( descriptor_lookup: Callable[[str], Any] | None = None, ) -> None: self._executor = executor + self._core_backend = isinstance(executor, (Executor, APCore)) + self._trace_executor = executor.executor if isinstance(executor, APCore) else executor self._error_mapper = ErrorMapper() self._validate_inputs = validate_inputs self._output_formatter = output_formatter @@ -108,8 +111,8 @@ def __init__( # [B-002] Per-server `call_id -> CancelToken` map. Populated on # tool-call entry by handle_call(); consulted by cancel(call_id). - # The transport layer forwards inbound MCP `notifications/cancelled` - # to `router.cancel(call_id, reason)` which sets the token. + # MCP request cancellation also signals the token passed by the + # server factory; direct router clients can use cancel(call_id). # # OrderedDict gives us FIFO-evicted bounded growth: when the map # exceeds _CANCEL_TOKENS_MAX entries (active + tombstones), the @@ -124,6 +127,11 @@ def __init__( # so we avoid a broad TypeError catch on every call. self._call_async_accepts_context = self._check_accepts_context(executor.call_async) self._stream_accepts_context = self._check_accepts_context(getattr(executor, "stream", None)) + self._open_completed_stream = ( + getattr(executor, "stream_with_completion", None) + if inspect.getattr_static(executor, "stream_with_completion", None) is not None + else None + ) def _resolve_builtin_formatter(self, format_name: str) -> Callable[[Any], str]: """Resolve a built-in formatter name to a callable. @@ -159,15 +167,17 @@ def _builtin_formatter(result: Any) -> str: return _builtin_formatter - def _maybe_redact(self, tool_name: str, result: Any) -> Any: + def _maybe_redact(self, tool_name: str, result: Any, output_schema: dict[str, Any] | None = None) -> Any: """Apply output redaction if enabled and an output_schema exists for the tool. Uses ``apcore.redact_sensitive()`` to strip sensitive fields. - Fails open: if redaction raises, the original result is returned. + Explicit version projections propagate redaction errors as tool errors. """ if not self._redact_output: return result - output_schema = self._output_schema_map.get(tool_name) + selected_version = output_schema is not None + if not selected_version: + output_schema = self._output_schema_map.get(tool_name) if output_schema is None: return result try: @@ -175,9 +185,22 @@ def _maybe_redact(self, tool_name: str, result: Any) -> Any: return redact_sensitive(result, output_schema) except Exception: + if selected_version: + raise ModuleError("MODULE_EXECUTE_ERROR", "Output redaction failed") from None logger.warning("redact_sensitive failed for %s, returning unredacted output", tool_name, exc_info=True) return result + def _output_projection( + self, tool_name: str, version_hint: str | None + ) -> tuple[str | None, dict[str, Any] | None]: + if not self._redact_output or not self._core_backend or version_hint is None: + return version_hint, None + definition = self._executor.registry.get_definition(tool_name, version_hint) + if definition is None: + raise ModuleError("MODULE_NOT_FOUND", f"Module '{tool_name}' not found") + # Resolve a range once, so execution and projection use the same registration. + return definition.version, definition.output_schema + def _format_result(self, result: Any) -> str: """Format an execution result into text for LLM consumption. @@ -284,14 +307,8 @@ async def handle_call( """ logger.debug("Executing tool call: %s", tool_name) - # [B-002] [A-D-210] Register a CancelToken FIRST — before any - # dispatch (async-bridge, meta-tool, or executor) — so that an - # inbound MCP `notifications/cancelled` (forwarded by the transport - # into `router.cancel(call_id, reason)`) cooperatively cancels - # in-flight work regardless of which dispatch path the call takes. - # Pre-fix this lived AFTER async-bridge dispatch, leaving bridge - # submits invisible to cancel. TS (router.ts:369) and Rust - # (router.rs:755) register the guard first. + # Register before dispatching so direct router and wire callers + # both signal the execution token rather than the result transport. # # The call_id is sourced from `extras.call_id`, # `_meta.progressToken`, or generated. Removed in `finally`. @@ -308,7 +325,8 @@ async def handle_call( call_id = str(pt) if call_id is None: call_id = uuid.uuid4().hex - cancel_token = CancelToken() + transport_token = extra.get("_transport_cancel_token") if extra is not None else None + cancel_token = transport_token if isinstance(transport_token, CancelToken) else CancelToken() with self._cancel_lock: # Tombstone case: cancel arrived before the token was # registered (race). When `_cancel_tokens[call_id]` is already @@ -522,21 +540,22 @@ async def _elicit_callback( raw = apcore_meta.get("version") if isinstance(raw, str): version_hint = raw - # Source #3: descriptor default fallback - if version_hint is None: + # Source #3: descriptor default fallback. Read the same descriptor + # to route annotated streaming modules without progress metadata. + descriptor = None + if version_hint is None or callable(self._open_completed_stream): registry = getattr(self._executor, "registry", None) - if registry is not None: - get_def = getattr(registry, "get_definition", None) - if callable(get_def): - try: - descriptor = get_def(tool_name) - except Exception: # noqa: BLE001 # defensive — registry may raise - descriptor = None - if descriptor is not None: - meta_attr = getattr(descriptor, "metadata", None) or {} - raw = meta_attr.get("version_hint") if isinstance(meta_attr, dict) else None - if isinstance(raw, str): - version_hint = raw + get_def = self._descriptor_lookup or getattr(registry, "get_definition", None) + if callable(get_def): + try: + descriptor = get_def(tool_name) + except Exception: # noqa: BLE001 # defensive — registry may raise + descriptor = None + if descriptor is not None and version_hint is None: + meta_attr = getattr(descriptor, "metadata", None) or {} + raw = meta_attr.get("version_hint") if isinstance(meta_attr, dict) else None + if isinstance(raw, str): + version_hint = raw # Pre-execution validation if self._validate_inputs: @@ -565,10 +584,24 @@ async def _elicit_callback( error_info = self._error_mapper.to_mcp_error(error) return ([{"type": "text", "text": error_info["message"]}], True, None) - # Streaming path: executor has stream() AND we have both helpers - can_stream = hasattr(self._executor, "stream") and progress_token is not None and send_notification is not None + has_progress = progress_token is not None and send_notification is not None + if callable(self._open_completed_stream): + native_stream = getattr(getattr(descriptor, "annotations", None), "streaming", False) is True + if not has_progress and self._core_backend: + try: + native_stream = isinstance(self._executor.registry.get(tool_name, version_hint), StreamingModule) + except ModuleError: + # Leave unknown or incompatible versions to the pipeline's normal error path. + native_stream = False + if has_progress or native_stream: + return await self._handle_completed_stream( + tool_name, arguments, progress_token, send_notification, context, version_hint + ) - if can_stream: + # Raw chunk executors predate the completion API. Keep the public + # embedding behavior for them, but don't merge an older Core's output + # locally or retry an already-started call. + if not self._core_backend and hasattr(self._executor, "stream") and has_progress: return await self._handle_stream( tool_name, arguments, @@ -630,8 +663,7 @@ def cancel(self, call_id: str, reason: str | None = None) -> bool: Returns True when a token was found and cancelled; False when the call_id was unknown (tombstone recorded). - Wired by transport-level handlers parsing inbound MCP - ``notifications/cancelled`` messages. + Wire requests use the MCP SDK's request-scoped cancellation. """ with self._cancel_lock: existing = self._cancel_tokens.get(call_id) @@ -705,13 +737,11 @@ async def _handle_call_async( ) -> tuple[list[dict[str, Any]], bool, str | None]: """Non-streaming execution via executor.call_async().""" try: - if self._trace: - # TODO(apcore>=0.19): plumb version_hint through call_async_with_trace - # (current signature only accepts strategy). - if self._call_async_accepts_context: - result, pipeline_trace = await self._executor.call_async_with_trace(tool_name, arguments, context) - else: - result, pipeline_trace = await self._executor.call_async_with_trace(tool_name, arguments) + version_hint, output_schema = self._output_projection(tool_name, version_hint) + call_kwargs = {"version_hint": version_hint} if version_hint is not None else {} + call_args = (tool_name, arguments, context) if self._call_async_accepts_context else (tool_name, arguments) + if self._trace and (version_hint is None or self._core_backend): + result, pipeline_trace = await self._trace_executor.call_async_with_trace(*call_args, **call_kwargs) trace_dict = { "strategy_name": pipeline_trace.strategy_name, "total_duration_ms": pipeline_trace.total_duration_ms, @@ -726,15 +756,9 @@ async def _handle_call_async( ], } else: - call_kwargs: dict[str, Any] = {} - if version_hint is not None: - call_kwargs["version_hint"] = version_hint - if self._call_async_accepts_context: - result = await self._executor.call_async(tool_name, arguments, context, **call_kwargs) - else: - result = await self._executor.call_async(tool_name, arguments, **call_kwargs) + result = await self._executor.call_async(*call_args, **call_kwargs) trace_dict = None - result = self._maybe_redact(tool_name, result) + result = self._maybe_redact(tool_name, result, output_schema) text_output = self._format_result(result) content: list[dict[str, Any]] = [{"type": "text", "text": text_output}] self._attach_traceparent(content, context) @@ -749,6 +773,73 @@ async def _handle_call_async( self._attach_traceparent(error_content, context) return (error_content, True, context.trace_id if context is not None else None) + async def _handle_completed_stream( + self, + tool_name: str, + arguments: dict[str, Any], + progress_token: str | int | None, + send_notification: Callable[[dict[str, Any]], Coroutine[Any, Any, None]] | None, + context: Context, + version_hint: str | None, + ) -> tuple[list[dict[str, Any]], bool, str | None]: + """Stream progress and take final output from the same execution.""" + try: + version_hint, output_schema = self._output_projection(tool_name, version_hint) + kwargs = {"version_hint": version_hint} if version_hint is not None else {} + async with aclosing(self._open_completed_stream(tool_name, arguments, context, **kwargs)) as execution: + index = 0 + async for chunk in execution.chunks: + index += 1 + if progress_token is not None and send_notification is not None: + await self._send_chunk( + tool_name, chunk, index, progress_token, send_notification, output_schema + ) + completion = await execution.completion() + result = self._require_completed_output(completion) + formatted = self._format_result(self._maybe_redact(tool_name, result, output_schema)) + content: list[dict[str, Any]] = [{"type": "text", "text": formatted}] + self._attach_traceparent(content, context) + return content, False, context.trace_id + except Exception as error: + info = self._error_mapper.to_mcp_error(error) + failure: list[dict[str, Any]] = [{"type": "text", "text": self._build_error_text(info)}] + self._attach_traceparent(failure, context) + return failure, True, context.trace_id + + @staticmethod + def _require_completed_output(completion: Any) -> dict[str, Any]: + output = completion.output + if completion.reason != "completed" or not isinstance(output, dict): + raise ModuleError(completion.error_code or "MODULE_EXECUTE_ERROR", "Stream did not complete") + for outcome, code in ( + (completion.output_validation, "SCHEMA_VALIDATION_ERROR"), + (completion.middleware_after, "MODULE_EXECUTE_ERROR"), + ): + if outcome.status != "passed" and not (outcome.status == "skipped" and outcome.reason in _POLICY_SKIPS): + raise ModuleError(code, "Stream post-processing failed") + return output + + async def _send_chunk( + self, + tool_name: str, + chunk: dict[str, Any], + index: int, + progress_token: str | int, + send_notification: Callable[[dict[str, Any]], Coroutine[Any, Any, None]], + output_schema: dict[str, Any] | None = None, + ) -> None: + await send_notification( + { + "method": "notifications/progress", + "params": { + "progressToken": progress_token, + "progress": index, + "total": None, + "message": json.dumps(self._maybe_redact(tool_name, chunk, output_schema), default=str), + }, + } + ) + async def _handle_stream( self, tool_name: str, @@ -761,7 +852,7 @@ async def _handle_stream( """Streaming execution via executor.stream(). Iterates the async generator, sends each chunk as a - ``notifications/progress`` message, accumulates via shallow + ``notifications/progress`` message, accumulates via recursive merge, and returns the final accumulated result. """ # TODO(apcore>=0.19): streaming traces pending — Executor.stream() @@ -782,20 +873,7 @@ async def _handle_stream( async for chunk in stream_iter: if not isinstance(chunk, dict): raise TypeError(f"stream chunk must be dict, got {type(chunk).__name__}: {chunk!r}") - # Redact each chunk before sending so sensitive fields never reach - # the client via progress notifications, even before final accumulation. - safe_chunk = self._maybe_redact(tool_name, chunk) - # Send progress notification for this chunk - notification: dict[str, Any] = { - "method": "notifications/progress", - "params": { - "progressToken": progress_token, - "progress": chunk_index + 1, - "total": None, - "message": json.dumps(safe_chunk, default=str), - }, - } - await send_notification(notification) + await self._send_chunk(tool_name, chunk, chunk_index + 1, progress_token, send_notification) # Deep merge into accumulated result (depth-capped at 32) accumulated = _deep_merge(accumulated, chunk) diff --git a/mcp/python/src/apcore_mcp/server/transport.py b/mcp/python/src/apcore_mcp/server/transport.py index 1d288c79..ce4f2056 100644 --- a/mcp/python/src/apcore_mcp/server/transport.py +++ b/mcp/python/src/apcore_mcp/server/transport.py @@ -8,6 +8,8 @@ import uuid from collections.abc import AsyncIterator from contextvars import ContextVar +from dataclasses import dataclass +from functools import partial from typing import Any, Protocol, runtime_checkable import anyio @@ -16,12 +18,15 @@ from mcp.server.models import InitializationOptions from mcp.server.sse import SseServerTransport from mcp.server.stdio import stdio_server -from mcp.server.streamable_http import StreamableHTTPServerTransport +from mcp.server.streamable_http_manager import StreamableHTTPSessionManager from starlette.applications import Starlette +from starlette.datastructures import Headers from starlette.responses import JSONResponse, Response from starlette.routing import Mount, Route +from starlette.types import Message, Receive, Scope, Send from apcore_mcp._stdio import stdio_output +from apcore_mcp.auth.middleware import auth_identity_var logger = logging.getLogger(__name__) @@ -56,6 +61,85 @@ class MetricsExporter(Protocol): def export_prometheus(self) -> str: ... +@dataclass +class _HTTPSessionOpening: + principal: tuple[str, str] | None + session_id: str | None = None + closed: bool = False + + +class _ScopedHTTPServer(Server): + """Delegate each SDK-managed HTTP session through transport cleanup.""" + + def __init__(self, manager: TransportManager, server: Server, init_options: InitializationOptions) -> None: + self._manager = manager + self._server = server + self._init_options = init_options + self._opening: ContextVar[_HTTPSessionOpening | None] = ContextVar("mcp_http_opening", default=None) + self._owners: dict[str, _HTTPSessionOpening] = {} + + async def handle_request( + self, sessions: StreamableHTTPSessionManager, scope: Scope, receive: Receive, send: Send + ) -> None: + identity = auth_identity_var.get() + principal = (identity.type, identity.id) if identity is not None else None + session_id = Headers(scope=scope).get("mcp-session-id") + if session_id is not None: + opening = self._owners.get(session_id) + if opening is None or opening.principal != principal: + response = JSONResponse( + {"jsonrpc": "2.0", "id": "server-error", "error": {"code": -32600, "message": "Session not found"}}, + status_code=404, + ) + await response(scope, receive, send) + return + await sessions.handle_request(scope, receive, send) + return + + if scope.get("method") != "POST": + await sessions.handle_request(scope, receive, send) + return + + opening = _HTTPSessionOpening(principal) + + async def bind_session(message: Message) -> None: + if message["type"] == "http.response.start" and message["status"] == 200 and not opening.closed: + issued = Headers(raw=message.get("headers", [])).get("mcp-session-id") + if issued is not None: + opening.session_id = issued + self._owners[issued] = opening + await send(message) + + # AnyIO copies this context when the SDK starts the session. Bind the + # SDK-issued ID before exposing it, then retire it with the session. + state = self._opening.set(opening) + try: + await sessions.handle_request(scope, receive, bind_session) + finally: + self._opening.reset(state) + + def create_initialization_options(self, *args: Any, **kwargs: Any) -> InitializationOptions: + return self._init_options + + async def run( + self, read_stream: Any, write_stream: Any, initialization_options: InitializationOptions, **kwargs: Any + ) -> None: + # The session task inherits the initializing request's context. Each + # HTTP call reads its own verified identity from its request scope. + opening = self._opening.get() + auth_state = auth_identity_var.set(None) + try: + await self._manager._run_scoped( + self._server, read_stream, write_stream, initialization_options, uuid.uuid4().hex, True + ) + finally: + auth_identity_var.reset(auth_state) + if opening is not None: + opening.closed = True + if opening.session_id is not None: + self._owners.pop(opening.session_id, None) + + class TransportManager: """Manages MCP server transport lifecycle.""" @@ -195,39 +279,30 @@ async def build_streamable_http_app( uvicorn.Config(combined, host="0.0.0.0", port=8000) ).serve() """ - session_id = uuid.uuid4().hex - transport = StreamableHTTPServerTransport( - mcp_session_id=session_id, - ) + scoped_server = _ScopedHTTPServer(self, server, init_options) + sessions = StreamableHTTPSessionManager(scoped_server) - async with transport.connect() as (read_stream, write_stream): + async def _health(request: Any) -> JSONResponse: + return JSONResponse(self._build_health_response()) + + async def _metrics(request: Any) -> Response: + return self._build_metrics_response() - async def _health(request: Any) -> JSONResponse: - return JSONResponse(self._build_health_response()) + routes: list[Route | Mount] = [ + Route("/health", endpoint=_health, methods=["GET"]), + Route("/metrics", endpoint=_metrics, methods=["GET"]), + ] + if extra_routes: + routes.extend(extra_routes) + routes.append(Mount("/mcp", app=partial(scoped_server.handle_request, sessions))) - async def _metrics(request: Any) -> Response: - return self._build_metrics_response() + app: Any = Starlette(routes=routes) + if middleware: + for mw_cls, mw_kwargs in middleware: + app = mw_cls(app, **mw_kwargs) - routes: list[Route | Mount] = [ - Route("/health", endpoint=_health, methods=["GET"]), - Route("/metrics", endpoint=_metrics, methods=["GET"]), - ] - if extra_routes: - routes.extend(extra_routes) - routes.append(Mount("/mcp", app=transport.handle_request)) - - app: Any = Starlette(routes=routes) - if middleware: - for mw_cls, mw_kwargs in middleware: - app = mw_cls(app, **mw_kwargs) - - # [TM-4] Bracket the protocol session so ``transport_session_var`` - # is populated for async-task submissions and so the configured - # AsyncTaskBridge mass-cancels session-bound tasks on teardown. - async with anyio.create_task_group() as tg: - tg.start_soon(self._run_scoped, server, read_stream, write_stream, init_options, session_id, True) - yield app - tg.cancel_scope.cancel() + async with sessions.run(): + yield app async def run_stdio( self, @@ -257,40 +332,11 @@ async def run_streamable_http( self._validate_host_port(host, port) logger.info("Starting streamable-http transport on %s:%d", host, port) - session_id = uuid.uuid4().hex - transport = StreamableHTTPServerTransport( - mcp_session_id=session_id, - ) - - async with transport.connect() as (read_stream, write_stream): - - async def _health(request: Any) -> JSONResponse: - return JSONResponse(self._build_health_response()) - - async def _metrics(request: Any) -> Response: - return self._build_metrics_response() - - routes: list[Route | Mount] = [ - Route("/health", endpoint=_health, methods=["GET"]), - Route("/metrics", endpoint=_metrics, methods=["GET"]), - ] - if extra_routes: - routes.extend(extra_routes) - routes.append(Mount("/mcp", app=transport.handle_request)) - - app: Any = Starlette(routes=routes) - if middleware: - for mw_cls, mw_kwargs in middleware: - app = mw_cls(app, **mw_kwargs) - + async with self.build_streamable_http_app( + server, init_options, extra_routes=extra_routes, middleware=middleware + ) as app: config = uvicorn.Config(app, host=host, port=port, log_level="info") - uv_server = uvicorn.Server(config) - - # Run both the MCP server and HTTP server concurrently. [TM-4] The - # MCP protocol session is bracketed by ``_scoped_session``. - async with anyio.create_task_group() as tg: - tg.start_soon(self._run_scoped, server, read_stream, write_stream, init_options, session_id, True) - tg.start_soon(uv_server.serve) + await uvicorn.Server(config).serve() async def run_sse( self, diff --git a/mcp/python/tests/server/test_request_cancellation.py b/mcp/python/tests/server/test_request_cancellation.py new file mode 100644 index 00000000..7aa1201a --- /dev/null +++ b/mcp/python/tests/server/test_request_cancellation.py @@ -0,0 +1,269 @@ +"""MCP wire cancellation reaches the target invocation's apcore token.""" + +from __future__ import annotations + +import asyncio +import json +from typing import Any + +import anyio +import httpx +from apcore import Context, Executor, Identity, Registry +from mcp import types +from mcp.shared.message import SessionMessage +from pydantic import BaseModel + +from apcore_mcp.auth.middleware import AuthMiddleware +from apcore_mcp.server.factory import MCPServerFactory +from apcore_mcp.server.router import ExecutionRouter +from apcore_mcp.server.transport import TransportManager, transport_session_var + + +class _Inputs(BaseModel): + name: str + + +class _Outputs(BaseModel): + name: str + + +class _GatedModule: + input_schema = _Inputs + output_schema = _Outputs + description = "Await the test gate and record the invocation token at exit" + + def __init__(self) -> None: + self.entered = asyncio.Queue[str]() + self.exited = asyncio.Queue[tuple[str, bool]]() + self.release = asyncio.Event() + self.sessions: dict[str, str | None] = {} + + async def execute(self, inputs: dict[str, Any], context: Context) -> dict[str, str]: + name = inputs["name"] + assert context.cancel_token is not None + self.sessions[name] = transport_session_var.get() + await self.entered.put(name) + try: + while not self.release.is_set(): + context.cancel_token.check() + await asyncio.sleep(0.01) + return {"name": name} + finally: + self.exited.put_nowait((name, context.cancel_token.is_cancelled)) + + +async def test_wire_cancel_marks_only_the_target_module_token() -> None: + module = _GatedModule() + registry = Registry() + registry.register("test.gated", module) + factory = MCPServerFactory() + server = factory.create_server() + factory.register_handlers(server, factory.build_tools(registry), ExecutionRouter(Executor(registry=registry))) + init = factory.build_init_options(server, "test", "1") + send_client, read_server = anyio.create_memory_object_stream(10) + send_server, read_client = anyio.create_memory_object_stream(10) + + async def send(message: dict[str, Any]) -> None: + await send_client.send(SessionMessage(types.JSONRPCMessage.model_validate({"jsonrpc": "2.0", **message}))) + + with anyio.fail_after(5): + async with anyio.create_task_group() as group: + group.start_soon(TransportManager()._run_scoped, server, read_server, send_server, init, "test") + await send( + { + "id": 1, + "method": "initialize", + "params": { + "protocolVersion": "2025-11-25", + "capabilities": {}, + "clientInfo": {"name": "test", "version": "1"}, + }, + } + ) + assert (await read_client.receive()).message.root.id == 1 + await send({"method": "notifications/initialized"}) + for request_id, name in [(2, "target"), (3, "peer")]: + await send( + { + "id": request_id, + "method": "tools/call", + "params": {"name": "test.gated", "arguments": {"name": name}}, + } + ) + assert {await module.entered.get(), await module.entered.get()} == {"target", "peer"} + + await send({"method": "notifications/cancelled", "params": {"requestId": 2}}) + try: + assert await module.exited.get() == ("target", True) + finally: + module.release.set() + assert await module.exited.get() == ("peer", False) + + while True: + response = (await read_client.receive()).message.root + if response.id == 3: + assert isinstance(response, types.JSONRPCResponse) + assert not response.result["isError"] + assert json.loads(response.result["content"][0]["text"]) == {"name": "peer"} + break + group.cancel_scope.cancel() + + +async def test_http_sessions_isolate_same_request_id_and_cancel_tasks_on_close() -> None: + class RecordingBridge: + def __init__(self) -> None: + self.closed = asyncio.Queue[str]() + + async def cancel_session_tasks(self, session_key: str) -> int: + await self.closed.put(session_key) + return 0 + + module = _GatedModule() + registry = Registry() + registry.register("test.gated", module) + factory = MCPServerFactory() + server = factory.create_server() + factory.register_handlers(server, factory.build_tools(registry), ExecutionRouter(Executor(registry=registry))) + manager = TransportManager() + bridge = RecordingBridge() + manager.set_async_task_bridge(bridge) + + headers = {"Accept": "application/json, text/event-stream", "MCP-Protocol-Version": "2025-06-18"} + init_message = { + "jsonrpc": "2.0", + "id": 1, + "method": "initialize", + "params": { + "protocolVersion": "2025-06-18", + "capabilities": {}, + "clientInfo": {"name": "test", "version": "1"}, + }, + } + with anyio.fail_after(5): + async with ( + manager.build_streamable_http_app(server, factory.build_init_options(server, "test", "1")) as app, + httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client, + ): + first = await client.post("/mcp/", headers=headers, json=init_message) + second = await client.post("/mcp/", headers=headers, json=init_message) + first.raise_for_status() + second.raise_for_status() + first_headers = {**headers, "Mcp-Session-Id": first.headers["mcp-session-id"]} + second_headers = {**headers, "Mcp-Session-Id": second.headers["mcp-session-id"]} + assert first_headers["Mcp-Session-Id"] != second_headers["Mcp-Session-Id"] + for session_headers in (first_headers, second_headers): + response = await client.post( + "/mcp/", headers=session_headers, json={"jsonrpc": "2.0", "method": "notifications/initialized"} + ) + assert response.status_code == 202 + + async def call(session_headers: dict[str, str], name: str) -> httpx.Response: + return await client.post( + "/mcp/", + headers=session_headers, + json={ + "jsonrpc": "2.0", + "id": 2, + "method": "tools/call", + "params": {"name": "test.gated", "arguments": {"name": name}}, + }, + ) + + first_call = asyncio.create_task(call(first_headers, "target")) + second_call = asyncio.create_task(call(second_headers, "peer")) + try: + assert {await module.entered.get(), await module.entered.get()} == {"target", "peer"} + response = await client.post( + "/mcp/", + headers=first_headers, + json={ + "jsonrpc": "2.0", + "method": "notifications/cancelled", + "params": {"requestId": 2}, + }, + ) + assert response.status_code == 202 + assert await module.exited.get() == ("target", True) + finally: + module.release.set() + await asyncio.gather(first_call, second_call) + + assert first_call.result().status_code == 200 + assert "peer" in second_call.result().text + assert await module.exited.get() == ("peer", False) + assert module.sessions["target"] != module.sessions["peer"] + assert None not in module.sessions.values() + removed = await client.delete("/mcp/", headers=first_headers) + assert removed.status_code == 200 + assert await bridge.closed.get() == module.sessions["target"] + assert bridge.closed.empty() + + +async def test_authenticated_http_session_rejects_other_principals_before_dispatch() -> None: + class HeaderAuthenticator: + def authenticate(self, headers: dict[str, str]) -> Identity | None: + name = headers.get("authorization") + return Identity(id=name) if name in {"alice", "bob"} else None + + module = _GatedModule() + registry = Registry() + registry.register("test.gated", module) + factory = MCPServerFactory() + server = factory.create_server() + factory.register_handlers(server, factory.build_tools(registry), ExecutionRouter(Executor(registry=registry))) + manager = TransportManager() + headers = {"Accept": "application/json, text/event-stream", "MCP-Protocol-Version": "2025-06-18"} + init_message = { + "jsonrpc": "2.0", + "id": 1, + "method": "initialize", + "params": { + "protocolVersion": "2025-06-18", + "capabilities": {}, + "clientInfo": {"name": "test", "version": "1"}, + }, + } + middleware = [(AuthMiddleware, {"authenticator": HeaderAuthenticator()})] + with anyio.fail_after(5): + async with ( + manager.build_streamable_http_app( + server, factory.build_init_options(server, "test", "1"), middleware=middleware + ) as app, + httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client, + ): + alice = {**headers, "Authorization": "alice"} + initialized = await client.post("/mcp/", headers=alice, json=init_message) + initialized.raise_for_status() + alice["Mcp-Session-Id"] = initialized.headers["mcp-session-id"] + bob = {**alice, "Authorization": "bob"} + notification = await client.post( + "/mcp/", headers=alice, json={"jsonrpc": "2.0", "method": "notifications/initialized"} + ) + assert notification.status_code == 202 + + target = asyncio.create_task( + client.post( + "/mcp/", + headers=alice, + json={ + "jsonrpc": "2.0", + "id": 2, + "method": "tools/call", + "params": {"name": "test.gated", "arguments": {"name": "target"}}, + }, + ) + ) + try: + assert await module.entered.get() == "target" + cancel = {"jsonrpc": "2.0", "method": "notifications/cancelled", "params": {"requestId": 2}} + assert (await client.post("/mcp/", headers=bob, json=cancel)).status_code == 404 + assert (await client.delete("/mcp/", headers=bob)).status_code == 404 + assert module.exited.empty() + assert (await client.post("/mcp/", headers=alice, json=cancel)).status_code == 202 + assert await module.exited.get() == ("target", True) + finally: + module.release.set() + await target + + assert (await client.delete("/mcp/", headers=alice)).status_code == 200 + assert (await client.post("/mcp/", headers=alice, json=cancel)).status_code == 404 diff --git a/mcp/python/tests/server/test_router_stream_completion.py b/mcp/python/tests/server/test_router_stream_completion.py new file mode 100644 index 00000000..70c6c3ec --- /dev/null +++ b/mcp/python/tests/server/test_router_stream_completion.py @@ -0,0 +1,227 @@ +"""Real Executor acceptance for the MCP stream result boundary.""" + +from __future__ import annotations + +import json +from collections.abc import AsyncIterator +from contextlib import closing +from typing import Any + +import anyio +import pytest +from apcore import REDACTED_VALUE, APCore, Config, Context, Executor, ModuleAnnotations, ModuleExecuteError, Registry +from apcore.builtin_steps import BuiltinOutputValidation +from apcore.middleware import Middleware +from mcp import ClientSession +from pydantic import BaseModel + +from apcore_mcp import APCoreMCP +from apcore_mcp.server.factory import MCPServerFactory +from apcore_mcp.server.router import ExecutionRouter +from apcore_mcp.server.transport import TransportManager + +_HAS_COMPLETION = callable(getattr(Executor, "stream_with_completion", None)) + + +class _Inputs(BaseModel): + pass + + +class _Output(BaseModel): + value: int + nested: dict[str, Any] + parts: list[int] + secret: str + + +class _StreamingTool: + annotations = ModuleAnnotations(streaming=True) + description = "Return two partial objects" + input_schema = _Inputs + output_schema = _Output + + def __init__(self, *, invalid: bool = False) -> None: + self.invalid = invalid + self.stream_calls = 0 + self.execute_calls = 0 + + async def execute(self, inputs: dict[str, Any], context: Context) -> dict[str, Any]: + self.execute_calls += 1 + return {"value": 100, "nested": {}, "parts": [], "secret": "hidden"} + + async def stream(self, inputs: dict[str, Any], context: Context) -> AsyncIterator[dict[str, Any]]: + self.stream_calls += 1 + yield {"nested": {"level": {"left": True}}, "parts": [1], "secret": "hidden"} + yield {"nested": {"level": {"right": True}}, "parts": [2], "value": "invalid" if self.invalid else 2} + + +def _setup( + tool: _StreamingTool, executor_type: type[Executor] = Executor +) -> tuple[Registry, Executor, ExecutionRouter]: + registry = Registry() + registry.register("test.stream", tool) + executor = executor_type(registry, config=Config({"stream": {"max_merge_depth": 1}})) + router = ExecutionRouter( + executor, output_schema_map={"test.stream": {"properties": {"secret": {"x-sensitive": True}}}} + ) + return registry, executor, router + + +@pytest.mark.parametrize(("send_progress", "annotated"), [(True, True), (False, True), (False, False)]) +@pytest.mark.skipif(not _HAS_COMPLETION, reason="run with the A2 wheel for the completion path") +async def test_real_mcp_final_result_uses_core_snapshot(send_progress: bool, annotated: bool) -> None: + tool = _StreamingTool() + if not annotated: + tool.annotations = ModuleAnnotations() + registry, _, router = _setup(tool) + factory = MCPServerFactory() + server = factory.create_server() + factory.register_handlers(server, factory.build_tools(registry), router) + init = factory.build_init_options(server, "test", "1") + send_client, read_server = anyio.create_memory_object_stream(10) + send_server, read_client = anyio.create_memory_object_stream(10) + messages: list[dict[str, Any]] = [] + + async def progress(_count: float, _total: float | None, text: str | None) -> None: + assert text is not None + messages.append(json.loads(text)) + + with anyio.fail_after(5): + async with anyio.create_task_group() as group: + group.start_soon(TransportManager()._run_scoped, server, read_server, send_server, init, "test") + async with ClientSession(read_client, send_client) as session: + await session.initialize() + result = await session.call_tool( + "test.stream", {}, progress_callback=progress if send_progress else None + ) + group.cancel_scope.cancel() + + assert not result.isError + assert json.loads(result.content[0].text) == { + "value": 2, + "nested": {"level": {"right": True}}, + "parts": [2], + "secret": REDACTED_VALUE, + } + assert len(messages) == (2 if send_progress else 0) + if send_progress: + assert messages[0]["secret"] == REDACTED_VALUE + assert (tool.stream_calls, tool.execute_calls) == (1, 0) + + +@pytest.mark.parametrize("ignored", [False, True]) +@pytest.mark.skipif(not _HAS_COMPLETION, reason="run with the A2 wheel for the completion path") +async def test_late_validation_failure_is_a_tool_error_even_if_ignored(ignored: bool) -> None: + tool = _StreamingTool(invalid=True) + _, executor, router = _setup(tool) + if ignored: + validation = BuiltinOutputValidation() + validation.ignore_errors = True + executor.current_strategy.configure_step("output_validation", validation) + + content, is_error, _ = await router.handle_call("test.stream", {}) + assert is_error + assert "validation" in content[0]["text"].lower() + assert "hidden" not in content[0]["text"] + assert (tool.stream_calls, tool.execute_calls) == (1, 0) + + +@pytest.mark.skipif(not _HAS_COMPLETION, reason="run with the A2 wheel for the completion path") +async def test_failed_after_hook_prevents_mcp_success() -> None: + class FailedAfter(Middleware): + def after(self, module_id: str, inputs: dict[str, Any], output: dict[str, Any], context: Context) -> None: + raise ModuleExecuteError(module_id, "private diagnostic") + + tool = _StreamingTool() + _, executor, router = _setup(tool) + executor.use(FailedAfter()) + content, is_error, _ = await router.handle_call("test.stream", {}) + assert is_error + assert "private diagnostic" not in content[0]["text"] + assert (tool.stream_calls, tool.execute_calls) == (1, 0) + + +async def test_old_core_selects_atomic_call_before_streaming() -> None: + class LegacyExecutor(Executor): + stream_with_completion = None # type: ignore[assignment] + + tool = _StreamingTool() + _, _, router = _setup(tool, LegacyExecutor) + + async def send_notification(_notification: dict[str, Any]) -> None: + pytest.fail("ordinary execution must not emit a chunk notification") + + content, is_error, _ = await router.handle_call( + "test.stream", {}, {"progress_token": 0, "send_notification": send_notification} + ) + assert not is_error + assert json.loads(content[0]["text"])["value"] == 100 + assert (tool.stream_calls, tool.execute_calls) == (0, 1) + + +async def test_core_facade_routes_streams_by_completion_capability() -> None: + tool = _StreamingTool() + tool.annotations = ModuleAnnotations() + registry = Registry() + registry.register("test.stream", tool) + with closing(APCore(registry=registry)) as client: + router = ExecutionRouter(client) + if _HAS_COMPLETION: + content, failed, _ = await router.handle_call("test.stream", {}) + assert not failed + assert json.loads(content[0]["text"])["value"] == 2 + assert (tool.stream_calls, tool.execute_calls) == (1, 0) + else: + async def unexpected_progress(notification: dict[str, Any]) -> None: + pytest.fail("ordinary execution cannot publish native chunks") + + content, failed, _ = await router.handle_call( + "test.stream", {}, {"progress_token": 0, "send_notification": unexpected_progress} + ) + assert not failed + assert json.loads(content[0]["text"])["value"] == 100 + assert (tool.stream_calls, tool.execute_calls) == (0, 1) + + +@pytest.mark.parametrize(("progress", "trace"), [(False, False), (True, False), (False, True)]) +async def test_registered_version_controls_output_projection(progress: bool, trace: bool) -> None: + class Versioned: + description = "Return a synthetic field with version-dependent visibility" + input_schema = {"type": "object"} + + def __init__(self, sensitive: bool) -> None: + self.output_schema = { + "type": "object", + "properties": {"label": {"type": "string", "x-sensitive": sensitive}}, + } + + async def execute(self, inputs: dict[str, Any], context: Context) -> dict[str, Any]: + return {"label": "synthetic"} + + async def stream(self, inputs: dict[str, Any], context: Context) -> AsyncIterator[dict[str, Any]]: + yield {"label": "synthetic"} + + registry = Registry() + registry.register("fixture.versioned", Versioned(True), version="1.0.0") + registry.register("fixture.versioned", Versioned(False), version="2.0.0") + if trace: + class UnaryExecutor(Executor): + stream_with_completion = None # type: ignore[assignment] + + router = ExecutionRouter(UnaryExecutor(registry), redact_output=True, trace=True) + else: + _, router, _, _, _ = APCoreMCP(registry, redact_output=True)._build_server_components() + messages: list[dict[str, Any]] = [] + + async def notify(notification: dict[str, Any]) -> None: + messages.append(json.loads(notification["params"]["message"])) + + extra: dict[str, Any] = {"_meta": {"apcore": {"version": "^1.0.0"}}} + if progress: + extra.update(progress_token=0, send_notification=notify) + content, failed, _ = await router.handle_call("fixture.versioned", {}, extra) + assert not failed + assert json.loads(content[0]["text"]) == {"label": REDACTED_VALUE} + assert messages == ([{"label": REDACTED_VALUE}] if progress and _HAS_COMPLETION else []) + if trace: + assert json.loads(content[-1]["text"])["strategy_name"] == "standard" diff --git a/mcp/python/tests/server/test_transport.py b/mcp/python/tests/server/test_transport.py index f486d0df..80edbb24 100644 --- a/mcp/python/tests/server/test_transport.py +++ b/mcp/python/tests/server/test_transport.py @@ -323,31 +323,6 @@ async def test_run_scoped_cancels_session_on_exit(self) -> None: bridge.cancel_session_tasks.assert_awaited_once_with("sess-cancel") - @pytest.mark.asyncio - async def test_build_streamable_http_app_brackets_session(self) -> None: - """build_streamable_http_app must run the server via _run_scoped so the - session is cancelled when the app context exits (client disconnect).""" - from unittest.mock import patch - - tm = TransportManager() - bridge = MagicMock() - bridge.cancel_session_tasks = AsyncMock(return_value=0) - tm.set_async_task_bridge(bridge) - - server = make_mock_server() - init_options = make_mock_init_options() - - with patch.object(tm, "_run_scoped", new=AsyncMock()) as mock_scoped: - async with tm.build_streamable_http_app(server, init_options): - pass - - # The protocol session is run through _run_scoped, not bare server.run. - mock_scoped.assert_awaited_once() - # A concrete session id (the transport's mcp_session_id) is passed. - assert isinstance(mock_scoped.await_args.args[-2], str) - assert mock_scoped.await_args.args[-1] is True - assert mock_scoped.await_args.args[-1] - @pytest.mark.asyncio async def test_run_stdio_uses_scoped_session(self) -> None: """run_stdio must drive the server through _run_scoped.""" diff --git a/mcp/python/tests/test_async_serve.py b/mcp/python/tests/test_async_serve.py index 41460b81..13b38258 100644 --- a/mcp/python/tests/test_async_serve.py +++ b/mcp/python/tests/test_async_serve.py @@ -2,7 +2,7 @@ from __future__ import annotations -from unittest.mock import AsyncMock, MagicMock, patch +from unittest.mock import AsyncMock, MagicMock import pytest from starlette.applications import Starlette @@ -98,24 +98,8 @@ async def test_bad_explorer_prefix_raises(self) -> None: class TestAsyncServeApp: - @patch("apcore_mcp.server.transport.StreamableHTTPServerTransport") - async def test_yields_starlette_app(self, mock_transport_cls: MagicMock) -> None: - """async_serve yields a Starlette ASGI application.""" - # Mock the transport so we don't actually start MCP protocol - mock_transport = MagicMock() - mock_transport_cls.return_value = mock_transport - - mock_read = MagicMock() - mock_write = MagicMock() - - # connect() returns an async context manager yielding (read, write) - mock_cm = AsyncMock() - mock_cm.__aenter__ = AsyncMock(return_value=(mock_read, mock_write)) - mock_cm.__aexit__ = AsyncMock(return_value=False) - mock_transport.connect.return_value = mock_cm - - mock_transport.handle_request = AsyncMock() - + async def test_yields_starlette_app(self) -> None: + """Start the application with its SDK session manager.""" registry = _make_registry() async with async_serve(registry, name="test-mcp") as app: @@ -136,22 +120,10 @@ async def test_is_async_context_manager(self) -> None: class TestBuildStreamableHttpApp: - @patch("apcore_mcp.server.transport.StreamableHTTPServerTransport") - async def test_yields_starlette_app(self, mock_transport_cls: MagicMock) -> None: + async def test_yields_starlette_app(self) -> None: + """Start the application with its SDK session manager.""" from apcore_mcp.server.transport import TransportManager - mock_transport = MagicMock() - mock_transport_cls.return_value = mock_transport - - mock_read = MagicMock() - mock_write = MagicMock() - - mock_cm = AsyncMock() - mock_cm.__aenter__ = AsyncMock(return_value=(mock_read, mock_write)) - mock_cm.__aexit__ = AsyncMock(return_value=False) - mock_transport.connect.return_value = mock_cm - mock_transport.handle_request = AsyncMock() - server = MagicMock(spec=["run"]) server.run = AsyncMock() init_options = MagicMock() diff --git a/mcp/python/tests/test_logging.py b/mcp/python/tests/test_logging.py index 42011d9d..5ec09645 100644 --- a/mcp/python/tests/test_logging.py +++ b/mcp/python/tests/test_logging.py @@ -198,9 +198,9 @@ def test_all_loggers_start_with_apcore_mcp(self): factory.logger, transport.logger, ]: - assert mod_logger.name.startswith( - "apcore_mcp" - ), f"Logger {mod_logger.name!r} does not start with 'apcore_mcp'" + assert mod_logger.name.startswith("apcore_mcp"), ( + f"Logger {mod_logger.name!r} does not start with 'apcore_mcp'" + ) # =========================================================================== @@ -300,31 +300,9 @@ async def test_streamable_http_logs_startup(self, caplog): with ( caplog.at_level(logging.INFO, logger="apcore_mcp.server.transport"), - patch("apcore_mcp.server.transport.StreamableHTTPServerTransport") as mock_transport_cls, patch("apcore_mcp.server.transport.uvicorn") as mock_uvicorn, - patch("apcore_mcp.server.transport.anyio") as mock_anyio, ): - mock_transport = mock_transport_cls.return_value - mock_read = MagicMock() - mock_write = MagicMock() - mock_ctx = MagicMock() - mock_ctx.__aenter__ = AsyncMock(return_value=(mock_read, mock_write)) - mock_ctx.__aexit__ = AsyncMock(return_value=False) - mock_transport.connect.return_value = mock_ctx - mock_transport.handle_request = MagicMock() - - mock_uv_server = MagicMock() - mock_uv_server.serve = AsyncMock() - mock_uvicorn.Config.return_value = MagicMock() - mock_uvicorn.Server.return_value = mock_uv_server - - # Make the task group a no-op that doesn't start tasks - mock_tg = MagicMock() - mock_tg.start_soon = MagicMock() - mock_tg_ctx = MagicMock() - mock_tg_ctx.__aenter__ = AsyncMock(return_value=mock_tg) - mock_tg_ctx.__aexit__ = AsyncMock(return_value=False) - mock_anyio.create_task_group.return_value = mock_tg_ctx + mock_uvicorn.Server.return_value.serve = AsyncMock() await tm.run_streamable_http( mock_server, diff --git a/mcp/python/tests/test_openapi_backend_conformance.py b/mcp/python/tests/test_openapi_backend_conformance.py index 75440019..e5a45bef 100644 --- a/mcp/python/tests/test_openapi_backend_conformance.py +++ b/mcp/python/tests/test_openapi_backend_conformance.py @@ -56,6 +56,8 @@ def test_conformance_modules(case: dict, caplog): for want in expected: mid = want["module_id"] descriptor = descriptors[mid] + if "description" in want: + assert descriptor.description == want["description"] # The MCP tool name is the module ID verbatim; OpenAI is dash-normalized. if "mcp_tool_name" in want: diff --git a/mcp/python/tests/test_openapi_effective_backend.py b/mcp/python/tests/test_openapi_effective_backend.py index 1a39a132..3c94eda9 100644 --- a/mcp/python/tests/test_openapi_effective_backend.py +++ b/mcp/python/tests/test_openapi_effective_backend.py @@ -70,3 +70,21 @@ def test_openapi_requires_toolkit_with_the_shared_preflight(monkeypatch: pytest. monkeypatch.delattr(apcore_toolkit, "validate_effective_proxy_modules") with pytest.raises(RuntimeError, match=r"apcore-toolkit >= 0\.15\.0.*apcore-mcp\[openapi\]"): openapi_backend(_DOCUMENT) + + +def test_backend_refuses_to_start_when_registry_rejects_a_scanned_module() -> None: + class RejectUpdate: + def validate(self, module: object) -> list[str]: + return ["rejected by host rule"] if getattr(module, "description", None) == "Update item" else [] + + registry = Registry() + registry.set_validator(RejectUpdate()) + document = { + **_DOCUMENT, + "paths": { + "/items": {"get": {"operationId": "listItems", "summary": "List items"}}, + "/updates": {"post": {"operationId": "updateItem", "summary": "Update item"}}, + }, + } + with pytest.raises(ValueError, match=r"update_item.*rejected by host rule"): + openapi_backend(document, registry=registry, acknowledge_unapproved_writes=True) diff --git a/mcp/rust/CHANGELOG.md b/mcp/rust/CHANGELOG.md index 305a6fd8..01e21369 100644 --- a/mcp/rust/CHANGELOG.md +++ b/mcp/rust/CHANGELOG.md @@ -6,6 +6,12 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [0.23.5-alpha.1] - Unreleased + +### Fixed + +- Route inbound cancellation to the active request, derive terminal stream results from Core when available, and fail startup when OpenAPI tools fail to register. + ## [0.23.4] - 2026-11-20 ### Fixed diff --git a/mcp/rust/Cargo.toml b/mcp/rust/Cargo.toml index a7a3155e..d6c3f7b6 100644 --- a/mcp/rust/Cargo.toml +++ b/mcp/rust/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "apcore-mcp" -version = "0.23.4" +version = "0.23.5-alpha.1" edition = "2021" description = "MCP bridge for apcore — expose apcore modules as MCP tools" license = "Apache-2.0" @@ -21,8 +21,8 @@ all-features = true rustdoc-args = ["--cfg", "docsrs"] [dependencies] -apcore = ">=0.33.0" -apcore-toolkit = ">=0.15.0" +apcore = "=1.0.0-alpha.1" +apcore-toolkit = "=0.15.1-alpha.1" mcp-embedded-ui = "0.5" tokio = { version = "1", features = ["full"] } serde = { version = "1", features = ["derive"] } diff --git a/mcp/rust/README.md b/mcp/rust/README.md index cd62f06c..b60e6609 100644 --- a/mcp/rust/README.md +++ b/mcp/rust/README.md @@ -60,13 +60,17 @@ cargo add apcore-mcp cargo install apcore-mcp ``` -Requires Rust 1.86+ and `apcore >= 0.32.3` + `apcore-toolkit >= 0.14.1`. The OpenAPI backend registers the module IDs emitted by `OpenAPIScanner`; toolkit 0.13 introduced the required Canonical ID normalization. - -Complete stdio shutdown draining of core invocations after timeout/cancellation -requires `apcore >= 0.32.3`. The `0.32.2` compatibility fallback preserves stdout -isolation and bridge-owned callback/sweep cleanup, but cannot join late core -module execution. See [stdio stdout ownership](docs/features/transport.md#stdio-stdout-ownership) -for the process and platform boundaries. +Requires Rust 1.86+, `apcore = 1.0.0-alpha.1` and `apcore-toolkit = 0.15.1-alpha.1`. +Registry-based installation requires a compatible APCore release on crates.io. +When testing a locally unpacked prerelease, resolve both this crate and Toolkit against +the same unpacked APCore package and confirm with `cargo metadata`. + +Streaming tools backed by APCore use the runtime's final merged output and +completion status for the MCP response. A client with a progress token gets +redacted chunks on stdio and SSE, while streamable HTTP returns the final +result. Output validation or after-middleware failure produces an MCP error +result even if chunks were already delivered. See [stdio stdout ownership](docs/features/transport.md#stdio-stdout-ownership) +for process and platform boundaries. ## Quick Start diff --git a/mcp/rust/docs/features/transport.md b/mcp/rust/docs/features/transport.md index fa70d734..4d5c81f2 100644 --- a/mcp/rust/docs/features/transport.md +++ b/mcp/rust/docs/features/transport.md @@ -114,7 +114,7 @@ The server supports `2024-11-05`, `2025-03-26` and `2025-06-18`. An initialize request for one of these receives the same version. Newer or unknown requests receive `2025-06-18`, allowing the client to decide whether it supports that version. Stdio and SSE remember the negotiated version on each live session, with -state removed on disconnect. Stateless HTTP uses the request's +state removed on disconnect. Streamable HTTP uses the request's `MCP-Protocol-Version` header, defaults to `2025-03-26` when it is absent, and returns HTTP 400 for present malformed or unsupported versions on POST, GET, and DELETE. Python and TypeScript delegate version negotiation to their native @@ -122,9 +122,17 @@ MCP SDKs, which support additional revisions; the Rust supported set remains `2024-11-05`, `2025-03-26` and `2025-06-18`. A different supported fallback is valid when the requested revision is not implemented. -Transport-injected protocol and session metadata cannot be supplied by the -client. HTTP never accepts a caller-supplied session identity or acquires -elicitation support from a forged metadata object. +Transport-injected protocol and session metadata comes from the connection. +Streamable HTTP assigns an opaque session ID on initialization. Cancellation +uses the issued session ID from the HTTP header and preserves the authenticated +owner of the session. A deleted or evicted session returns HTTP 404. Clients +without an initialized session can still use stateless calls. HTTP sessions +scope inbound cancellation without enabling elicitation. + +Inbound `notifications/cancelled` reaches only the active tool call with the +same JSON-RPC request ID and session. Numeric and string IDs are distinct. +The router forwards the signal to the Core invocation token. SSE cancellation +can reach a call while all normal dispatch slots are occupied. - [ ] Preserve the legacy response format on old connections and headerless HTTP requests - [ ] Negotiate structured results independently for each live stdio/SSE session diff --git a/mcp/rust/src/apcore_mcp.rs b/mcp/rust/src/apcore_mcp.rs index 225922a4..b38d6b9b 100644 --- a/mcp/rust/src/apcore_mcp.rs +++ b/mcp/rust/src/apcore_mcp.rs @@ -20,7 +20,7 @@ use crate::converters::openai::OpenAIConverter; use crate::explorer::{create_explorer_mount, ExplorerConfig, ToolInfo}; use crate::server::factory::MCPServerFactory; use crate::server::listener::RegistryListener; -use crate::server::router::{ExecutionRouter, ExecutorError, OutputFormatter}; +use crate::server::router::{CompletedStream, ExecutionRouter, ExecutorError, OutputFormatter}; use crate::server::server::{MCPServer, ServerHandler}; use crate::server::transport::{MetricsExporter, TransportManager}; use crate::server::types::{InitializationOptions, Tool}; @@ -267,6 +267,33 @@ impl crate::server::router::Executor for ApcoreExecutorAdapter { }) } + fn stream_with_completion<'a>( + &'a self, + module_id: &str, + inputs: &Value, + context: &apcore::Context, + version_hint: Option<&str>, + ) -> Option> { + use tokio_stream::StreamExt; + + let module = self.inner.registry().get(module_id).ok()??; + module.as_streaming()?; + let (chunks, completion) = self.inner.stream_with_completion( + module_id, + inputs.clone(), + Some(context), + version_hint, + ); + let chunks = chunks.map(|item| { + item.map_err(|error| ExecutorError::Execution { + code: error.code.wire_str(), + message: error.to_string(), + details: None, + }) + }); + Some((Box::pin(chunks), completion)) + } + async fn call_with_trace( &self, module_id: &str, @@ -2626,6 +2653,205 @@ mod tests { } } + struct CompletionFixture { + entries: Arc, + } + + #[async_trait::async_trait] + impl apcore::Module for CompletionFixture { + fn input_schema(&self) -> Value { + json!({"type": "object"}) + } + + fn output_schema(&self) -> Value { + json!({"type": "object", "required": ["value"], "properties": { + "value": {"type": "integer"}, + "secret": {"type": "string", "x-sensitive": true} + }}) + } + + fn description(&self) -> &'static str { + "Return tracked chunks with a canonical aggregate" + } + + async fn execute( + &self, + _inputs: Value, + _ctx: &apcore::Context, + ) -> Result { + panic!("native streaming must not be retried by unary execution") + } + + fn as_streaming(&self) -> Option<&dyn apcore::StreamingModule> { + Some(self) + } + + fn stream( + &self, + inputs: Value, + ctx: &apcore::Context, + ) -> Option { + Some(apcore::StreamingModule::stream_typed(self, inputs, ctx)) + } + } + + impl apcore::StreamingModule for CompletionFixture { + fn stream_typed( + &self, + inputs: Value, + _ctx: &apcore::Context, + ) -> apcore::ChunkStream { + self.entries + .fetch_add(1, std::sync::atomic::Ordering::SeqCst); + if inputs["panic"] == true { + return Box::pin(futures::stream::poll_fn(|_| { + panic!("simulated native producer panic") + })); + } + let value = if inputs["invalid"] == true { + json!("invalid") + } else { + json!(9) + }; + Box::pin(tokio_stream::iter([ + Ok( + json!({"outer": {"inner": {"left": 1}}, "parts": [1], "secret": "progress-canary"}), + ), + Ok(json!({"outer": {"inner": {"right": 2}}, "parts": [2], "value": value})), + ])) + } + } + + #[tokio::test] + async fn mcp_wire_uses_core_completion_for_progress_and_atomic_results() { + use crate::server::transport::TransportManager; + use std::sync::atomic::{AtomicUsize, Ordering}; + use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; + + let entries = Arc::new(AtomicUsize::new(0)); + let registry = Registry::new(); + registry + .register_module( + "demo.completion", + Box::new(CompletionFixture { + entries: Arc::clone(&entries), + }), + ) + .unwrap(); + assert!(!registry + .get_definition("demo.completion") + .unwrap() + .unwrap() + .annotations + .is_some_and(|annotations| annotations.streaming)); + let mut config = Config::default(); + config.set("stream.max_merge_depth", json!(1)); + let executor = Executor::new(registry, config); + executor + .use_middleware(Box::new(apcore::middleware::adapters::AfterAdapter::new( + "test_completion_after", + |_, inputs: Value, output: Value, _| async move { + assert_eq!(output["outer"]["inner"], json!({"right": 2})); + if inputs["after_failure"] == true { + Err(apcore::ModuleError::new( + apcore::ErrorCode::ModuleExecuteError, + "after failure", + )) + } else { + Ok(None) + } + }, + ))) + .unwrap(); + let mcp = APCoreMCP::builder() + .backend(BackendSource::Executor(Arc::new(executor))) + .redact_output(true) + .build() + .unwrap(); + let (server, _, _, options, _, _) = mcp.build_server_components().unwrap(); + let handler = ServerHandler::from_server(&server, options).unwrap(); + let (client, server) = tokio::io::duplex(8192); + let (read, mut write) = tokio::io::split(client); + let mut lines = BufReader::new(read).lines(); + let (r, w) = tokio::io::split(server); + let task = tokio::spawn(async move { + TransportManager::new(None) + .run_stdio_with_io(r, w, &handler) + .await + .unwrap(); + }); + let decode = |line: String| serde_json::from_str::(&line).unwrap(); + let deadline = std::time::Duration::from_secs(3); + + for (id, progress, error) in [ + (1, true, None), + (2, false, None), + (3, true, Some("SCHEMA_VALIDATION_ERROR")), + (4, true, Some("MODULE_EXECUTE_ERROR")), + (5, false, Some("executor panicked")), + (6, false, None), + ] { + let mut request = json!({ + "jsonrpc": "2.0", "id": id, "method": "tools/call", "params": { + "name": "demo.completion", "arguments": { + "invalid": error == Some("SCHEMA_VALIDATION_ERROR"), + "after_failure": error == Some("MODULE_EXECUTE_ERROR"), + "panic": error == Some("executor panicked"), + } + } + }); + if progress { + request["params"]["_meta"] = json!({"progressToken": "tracked"}); + } + write + .write_all(format!("{request}\n").as_bytes()) + .await + .unwrap(); + + if progress { + for index in 1..=2 { + let progress = decode( + tokio::time::timeout(deadline, lines.next_line()) + .await + .unwrap() + .unwrap() + .unwrap(), + ); + assert_eq!(progress["jsonrpc"], "2.0"); + assert_eq!(progress["method"], "notifications/progress"); + assert_eq!(progress["params"]["progressToken"], "tracked"); + assert_eq!(progress["params"]["progress"], index); + assert!(!progress.to_string().contains("progress-canary")); + } + } + let reply = decode( + tokio::time::timeout(deadline, lines.next_line()) + .await + .unwrap() + .unwrap() + .unwrap(), + ); + assert_eq!(reply["id"], id); + assert_eq!(reply["result"]["isError"], error.is_some()); + let content = reply["result"]["content"][0]["text"].as_str().unwrap(); + if let Some(code) = error { + assert!(content.contains(code)); + assert!(reply["result"].get("structuredContent").is_none()); + } else { + assert_eq!( + serde_json::from_str::(content).unwrap(), + json!({ + "outer": {"inner": {"right": 2}}, "parts": [2], "value": 9, + "secret": apcore::REDACTED_VALUE, + }) + ); + } + assert_eq!(entries.load(Ordering::SeqCst), usize::try_from(id).unwrap()); + } + write.shutdown().await.unwrap(); + tokio::time::timeout(deadline, task).await.unwrap().unwrap(); + } + /// Create a test registry with the given modules. fn make_test_registry(modules: Vec<(&str, &str, Vec)>) -> Registry { let registry = Registry::new(); diff --git a/mcp/rust/src/openapi_backend.rs b/mcp/rust/src/openapi_backend.rs index 789ce250..b7f8c7db 100644 --- a/mcp/rust/src/openapi_backend.rs +++ b/mcp/rust/src/openapi_backend.rs @@ -18,7 +18,9 @@ use std::sync::Arc; use apcore::Registry; use apcore_toolkit::openapi_scanner::{OpenAPIScanner, ScanOptions}; -use apcore_toolkit::output::http_proxy_writer::HTTPProxyRegistryWriter; +use apcore_toolkit::output::http_proxy_writer::{ + http_proxy_route_metadata, HTTPProxyRegistryWriter, +}; use apcore_toolkit::types::ScannedModule; use apcore_toolkit::validate_effective_proxy_modules; use serde_json::Value; @@ -497,14 +499,48 @@ pub async fn openapi_backend( HTTPProxyRegistryWriter::new(base_url, options.auth_header_factory, PROXY_TIMEOUT_SECS) .map_err(|e| APCoreMCPError::Config(format!("mcp.openapi: {e}")))?; - for result in writer.write(&modules, ®istry) { - if let Some(err) = result.verification_error { - tracing::error!( - "OpenAPI module {} failed to register: {err}", - result.module_id + for module in &mut modules { + if module.description.trim().is_empty() { + let (method, path) = http_proxy_route_metadata(module); + let route = format!( + "{} {}", + method.unwrap_or("GET").to_ascii_uppercase(), + path.unwrap_or("/") ); + module.description = route + .split_whitespace() + .collect::>() + .join(" ") + .chars() + .take(200) + .collect(); } } + let results: HashMap<_, _> = writer + .write(&modules, ®istry) + .into_iter() + .map(|result| (result.module_id.clone(), result)) + .collect(); + let mut failures = Vec::new(); + for module in &modules { + let id = &module.module_id; + let result = results.get(id); + if result.is_some_and(|result| result.verified) + && registry.get(id).is_ok_and(|module| module.is_some()) + { + continue; + } + let detail = result + .and_then(|result| result.verification_error.as_deref()) + .unwrap_or("module not registered"); + failures.push(format!("{id}: {detail}")); + } + if !failures.is_empty() { + return Err(APCoreMCPError::Config(format!( + "OpenAPI registration incomplete: {}", + failures.join("; ") + ))); + } if !options.acknowledge_unapproved_writes { warn_if_writes_have_no_approval_path(&modules); diff --git a/mcp/rust/src/server/router.rs b/mcp/rust/src/server/router.rs index 0564660d..2bb6f361 100644 --- a/mcp/rust/src/server/router.rs +++ b/mcp/rust/src/server/router.rs @@ -16,7 +16,9 @@ use serde_json::{json, Value}; use tokio_stream::Stream; use apcore::trace_context::{TraceContext, TraceParent}; -use apcore::CancelToken; +use apcore::{ + CancelToken, StreamCompletionHandle, StreamEndReason, StreamSkipReason, StreamStepOutcome, +}; use crate::auth::middleware::AUTH_IDENTITY; use crate::helpers::{ElicitResult, MCP_ELICIT_CALL_ID_KEY, MCP_ELICIT_KEY, MCP_PROGRESS_KEY}; @@ -24,9 +26,18 @@ use crate::server::approval_bridge::ApprovalBridge; use crate::server::async_task_bridge::AsyncTaskBridge; use crate::server::elicit_registry::ElicitGuard; use crate::server::session::SessionRegistry; +use crate::server::transport::WIRE_CALL_CANCEL; /// A boxed stream of result chunks from a streaming executor. -pub type StreamResult = Pin> + Send>>; +pub type StreamResult = StreamChunks<'static>; + +/// A chunk stream that can borrow its executor. +pub type StreamChunks<'a> = Pin> + Send + 'a>>; + +/// Chunks and separate completion for the same execution. +pub type CompletedStream<'a> = (StreamChunks<'a>, StreamCompletionHandle); + +type StreamOutcome = (Vec, bool, Option); // --------------------------------------------------------------------------- // Task 1: Executor trait @@ -119,6 +130,18 @@ pub trait Executor: Send + Sync { None } + /// Open one tracked invocation, or return `None` before execution when + /// completion metadata is unavailable for the module. + fn stream_with_completion<'a>( + &'a self, + _module_id: &str, + _inputs: &Value, + _context: &apcore::Context, + _version_hint: Option<&str>, + ) -> Option> { + None + } + /// Validate inputs for a module, or `None` if the executor does /// not support pre-execution validation. fn validate( @@ -658,8 +681,8 @@ impl ExecutionRouter { /// /// Returns `true` when an active token was found and cancelled; /// `false` when the `call_id` was unknown (tombstone recorded). - /// Wired by transport-level handlers parsing inbound MCP - /// `notifications/cancelled` messages. + /// For programmatic router calls. Wire-level cancellation uses the + /// active JSON-RPC request ID and transport session. pub fn cancel_call(&self, call_id: &str, _reason: Option<&str>) -> bool { let mut guard = self.cancel_tokens.lock().unwrap_or_else(|p| p.into_inner()); if let Some(token) = guard.get(call_id) { @@ -679,7 +702,11 @@ impl ExecutionRouter { /// same cancellation state (`Arc` inside apcore::CancelToken) /// as the one held in the map, so `cancel_call` flips both. [B-002] fn _cancel_guard(&self, call_id: &str) -> (CancelGuard, CancelToken) { - let token = std::sync::Arc::new(CancelToken::new()); + let token = Arc::new( + WIRE_CALL_CANCEL + .try_with(CancelToken::child) + .unwrap_or_default(), + ); let mut guard = self.cancel_tokens.lock().unwrap_or_else(|p| p.into_inner()); // Tombstone race: if a tombstone was recorded earlier via // cancel_call, propagate the cancelled state to the new token. @@ -1136,30 +1163,15 @@ impl ExecutionRouter { } } - // Select execution path: try streaming if both prerequisites present; - // handle_stream will fall back to non-streaming if executor doesn't - // support streaming. - if let (Some(ref pt), Some(ref sn)) = (progress_token, send_notification) { - self.handle_stream( - tool_name, - arguments, - pt, - sn, - Some(&context_value), - version_hint.as_deref(), - Some(&apcore_ctx), - ) - .await - } else { - self.handle_call_async_with_hint( - tool_name, - arguments, - Some(&context_value), - version_hint.as_deref(), - Some(&apcore_ctx), - ) - .await - } + self.dispatch_stream_or_call( + tool_name, + arguments, + &context_value, + version_hint.as_deref(), + &apcore_ctx, + progress_token.as_ref().zip(send_notification.as_ref()), + ) + .await } /// Read the session id the transport stamped onto an inbound message. @@ -1180,16 +1192,9 @@ impl ExecutionRouter { /// the extra `Value`. Returns `(None, None, None, None)` when extra is /// `None`. /// - /// `send_notification` stays `None`: it is a closure, and a plain JSON - /// `Value` cannot carry one. `session` no longer does. The transport - /// stamps its session id onto every inbound message - /// ([`stamp_session_id`]), and the live connection behind that id lives in - /// [`SessionRegistry`] — so the trait object is recovered by lookup rather - /// than by deserialization. Without this the `session` slot was - /// hard-coded `None`, which is why an interactive approval prompt could - /// never reach a client (apexe#29). - /// - /// [`stamp_session_id`]: crate::server::transport + /// Session transports stamp the live connection id on incoming messages. + /// The registry provides the session for elicitation and, when there is a + /// progress token, its sink for progress notifications. #[allow(clippy::type_complexity)] fn extract_extra( &self, @@ -1200,24 +1205,42 @@ impl ExecutionRouter { Option>, Option, ) { - // In the current integration the factory passes a plain JSON Value - // which does not carry callbacks. Real callbacks would come from a - // typed CallExtra. For now we extract identity from JSON. let identity = extra.and_then(|v| v.get("identity")).cloned(); - let progress_token = extra.and_then(|v| v.get("progress_token")).and_then(|v| { - if let Some(s) = v.as_str() { - Some(ProgressToken::String(s.to_string())) - } else { - v.as_i64().map(ProgressToken::Integer) - } - }); - - let session = Self::session_id_from_extra(extra) - .and_then(|id| self.session_registry.get(id)) - .map(|session| -> Arc { session }); + let progress_token = extra + .and_then(|v| v.get("progressToken").or_else(|| v.get("progress_token"))) + .and_then(|v| { + if let Some(s) = v.as_str() { + Some(ProgressToken::String(s.to_string())) + } else { + v.as_i64().map(ProgressToken::Integer) + } + }); - (progress_token, None, session, identity) + let session = + Self::session_id_from_extra(extra).and_then(|id| self.session_registry.get(id)); + let notify = session + .as_ref() + .filter(|_| progress_token.is_some()) + .map(|session| { + let session = Arc::clone(session); + let send: SendNotificationFn = Arc::new(move |mut message| { + let session = Arc::clone(&session); + // The registered transport sink owns the JSON-RPC wire. + message["jsonrpc"] = json!("2.0"); + Box::pin(async move { + session.send_notification(message).await?; + Ok(()) + }) + }); + send + }); + ( + progress_token, + notify, + session.map(|session| -> Arc { session }), + identity, + ) } /// The registry of live sessions this router resolves elicitation through. @@ -1295,30 +1318,18 @@ impl ExecutionRouter { } } - // Select execution path: try streaming if both prerequisites present; - // handle_stream will fall back to non-streaming if executor doesn't - // support streaming. - if let (Some(ref pt), Some(ref sn)) = (extra.progress_token, extra.send_notification) { - self.handle_stream( - tool_name, - arguments, - pt, - sn, - Some(&context_value), - None, - Some(&apcore_ctx), - ) - .await - } else { - self.handle_call_async_with_hint( - tool_name, - arguments, - Some(&context_value), - None, - Some(&apcore_ctx), - ) - .await - } + self.dispatch_stream_or_call( + tool_name, + arguments, + &context_value, + None, + &apcore_ctx, + extra + .progress_token + .as_ref() + .zip(extra.send_notification.as_ref()), + ) + .await } // ----------------------------------------------------------------------- @@ -1836,6 +1847,54 @@ impl ExecutionRouter { // by apcore 0.18; when available, capture step traces during streaming // and attach them to `_meta.trace` like the non-streaming path. + async fn dispatch_stream_or_call( + &self, + tool_name: &str, + arguments: &Value, + context: &Value, + version_hint: Option<&str>, + apcore_ctx: &apcore::Context, + progress: Option<(&ProgressToken, &SendNotificationFn)>, + ) -> StreamOutcome { + let tracked = Self::guard_stream(tool_name, async { + let (chunks, completion) = self.executor.as_ref()?.stream_with_completion( + tool_name, + arguments, + apcore_ctx, + version_hint, + )?; + Some( + self.consume_stream(tool_name, chunks, Some(completion), progress, Some(context)) + .await, + ) + }) + .await; + if let Some(outcome) = tracked { + return outcome; + } + if let Some((token, send)) = progress { + return self + .handle_stream( + tool_name, + arguments, + token, + send, + Some(context), + version_hint, + Some(apcore_ctx), + ) + .await; + } + self.handle_call_async_with_hint( + tool_name, + arguments, + Some(context), + version_hint, + Some(apcore_ctx), + ) + .await + } + /// Streaming execution via executor.stream(). /// /// Iterates the async stream, sends progress notifications for each @@ -1856,9 +1915,7 @@ impl ExecutionRouter { context: Option<&Value>, version_hint: Option<&str>, apcore_ctx: Option<&apcore::Context>, - ) -> (Vec, bool, Option) { - use tokio_stream::StreamExt; - + ) -> StreamOutcome { let executor = match &self.executor { Some(e) => e, None => { @@ -1873,27 +1930,51 @@ impl ExecutionRouter { } }; - let stream = match executor.stream(tool_name, arguments, context, version_hint) { - Some(s) => s, - None => { - // Fallback to non-streaming - // `ApcoreExecutorAdapter` does not implement `stream`, so the - // real server always lands here — which is why the typed - // context has to be forwarded rather than dropped. - return self - .handle_call_async_with_hint( - tool_name, - arguments, - context, - version_hint, - apcore_ctx, - ) - .await; - } - }; + let legacy = Self::guard_stream(tool_name, async { + let stream = executor.stream(tool_name, arguments, context, version_hint)?; + Some( + self.consume_stream( + tool_name, + stream, + None, + Some((progress_token, send_notification)), + context, + ) + .await, + ) + }) + .await; + if let Some(outcome) = legacy { + return outcome; + } + // Legacy custom executors may have neither streaming API. + self.handle_call_async_with_hint(tool_name, arguments, context, version_hint, apcore_ctx) + .await + } - tokio::pin!(stream); + async fn guard_stream( + tool_name: &str, + stream: impl std::future::Future>, + ) -> Option { + use futures::FutureExt; + match std::panic::AssertUnwindSafe(stream).catch_unwind().await { + Ok(outcome) => outcome, + Err(_) => { + tracing::error!(tool_name, "streaming executor panicked"); + Some(Self::stream_error("Streaming executor panicked.".into())) + } + } + } + async fn consume_stream( + &self, + tool_name: &str, + mut stream: StreamChunks<'_>, + completion: Option, + progress: Option<(&ProgressToken, &SendNotificationFn)>, + context: Option<&Value>, + ) -> StreamOutcome { + use tokio_stream::StreamExt; let mut accumulated = Value::Object(serde_json::Map::new()); let mut chunk_index: usize = 0; @@ -1906,46 +1987,48 @@ impl ExecutionRouter { // the MCP client even though the final accumulated // value is later redacted. Mirrors Python's // _handle_stream invariant. [A-D-003] - let safe_chunk = self.redact_output(tool_name, &chunk); - - // Send progress notification - let notification = serde_json::json!({ - "method": "notifications/progress", - "params": { - "progressToken": progress_token_to_value(progress_token), - "progress": chunk_index + 1, - "total": null, - "message": serde_json::to_string(&safe_chunk).unwrap_or_default(), + if let Some((progress_token, send_notification)) = progress { + let safe_chunk = self.redact_output(tool_name, &chunk); + let notification = serde_json::json!({ + "method": "notifications/progress", + "params": { + "progressToken": progress_token_to_value(progress_token), + "progress": chunk_index + 1, + "total": null, + "message": serde_json::to_string(&safe_chunk).unwrap_or_default(), + } + }); + if let Err(e) = send_notification(notification).await { + tracing::debug!("Failed to send progress notification: {e}"); } - }); - if let Err(e) = send_notification(notification).await { - tracing::debug!("Failed to send progress notification: {e}"); } - // Accumulate the original (un-redacted) chunk so the - // final result still has full fidelity for redaction - // at the response boundary; redaction is reapplied - // there. The mid-stream notification is the leak - // vector this fix closes. - accumulated = deep_merge(&accumulated, &chunk, 0); + // The local legacy policy is only for custom executors + // without completion, never for a tracked Core stream. + if completion.is_none() { + accumulated = deep_merge(&accumulated, &chunk, 0); + } chunk_index += 1; } Some(Err(error)) => { tracing::error!("handle_call stream error for {tool_name}: {error}"); let text = Self::build_error_text(&error); - return ( - vec![ContentItem { - content_type: "text".into(), - data: Value::String(text), - }], - true, - None, - ); + return Self::stream_error(text); } None => break, } } + if let Some(completion) = completion { + let completion = completion.await; + if let Some(code) = Self::stream_completion_error(&completion) { + return Self::stream_error(format!("Streaming completion failed ({code}).")); + } + let Some(output) = completion.output else { + return Self::stream_error("Streaming completion produced no output.".to_string()); + }; + accumulated = output; + } let redacted_accumulated = self.redact_output(tool_name, &accumulated); let text = self.format_result(&redacted_accumulated); let content = vec![ContentItem { @@ -1958,6 +2041,48 @@ impl ExecutionRouter { .map(|s| s.to_string()); (content, false, trace_id) } + + fn stream_completion_error(completion: &apcore::StreamCompletion) -> Option<&str> { + let step_failed = |step| { + matches!( + step, + StreamStepOutcome::Failed { .. } + | StreamStepOutcome::Skipped { + reason: StreamSkipReason::NotReached + } + ) + }; + match completion.reason { + StreamEndReason::Completed if step_failed(completion.output_validation) => { + Some("SCHEMA_VALIDATION_ERROR") + } + StreamEndReason::Completed if step_failed(completion.middleware_after) => { + Some("MODULE_EXECUTE_ERROR") + } + StreamEndReason::Completed => None, + StreamEndReason::Cancelled | StreamEndReason::ConsumerClosed => { + Some("EXECUTION_CANCELLED") + } + StreamEndReason::TimedOut => Some("MODULE_TIMEOUT"), + StreamEndReason::Failed => Some( + completion + .error_code + .as_deref() + .unwrap_or("MODULE_EXECUTE_ERROR"), + ), + } + } + + fn stream_error(text: String) -> StreamOutcome { + ( + vec![ContentItem { + content_type: "text".into(), + data: Value::String(text), + }], + true, + None, + ) + } } // =========================================================================== @@ -3932,6 +4057,83 @@ mod tests { assert!(text.contains("stream failed at chunk 2")); } + #[tokio::test] + async fn test_e2e_legacy_stream_panics_return_tool_error_without_reexecution() { + use futures::StreamExt; + use std::sync::atomic::{AtomicUsize, Ordering}; + + struct LegacyStream(Arc); + + #[async_trait] + impl Executor for LegacyStream { + async fn call_async( + &self, + _module_id: &str, + _inputs: &Value, + _context: Option<&Value>, + _version_hint: Option<&str>, + ) -> Result { + self.0.fetch_add(1, Ordering::Relaxed); + Ok(json!({"unexpected_fallback": true})) + } + + fn stream( + &self, + _module_id: &str, + inputs: &Value, + _context: Option<&Value>, + _version_hint: Option<&str>, + ) -> Option { + let first = futures::stream::iter([Ok(json!({"first": true}))]); + match inputs["panic"].as_str() { + Some("poll") => Some(Box::pin(first.chain(futures::stream::poll_fn(|_| { + panic!("legacy producer panic") + })))), + Some("open") => panic!("legacy stream opening panic"), + _ => Some(Box::pin(first)), + } + } + } + + let fallback_calls = Arc::new(AtomicUsize::new(0)); + let router = ExecutionRouter::new( + Box::new(LegacyStream(Arc::clone(&fallback_calls))), + false, + None, + ); + let (send, notifications) = make_send_notification(); + let extra = || CallExtra { + progress_token: Some(ProgressToken::Integer(1)), + send_notification: Some(Arc::clone(&send)), + session: None, + identity: None, + typed_identity: None, + }; + for phase in ["poll", "open"] { + let (content, is_error, _) = router + .handle_call_with_extra("mod", &json!({"panic": phase}), Some(extra())) + .await; + assert!(is_error, "{phase}"); + assert!(content[0] + .data + .as_str() + .unwrap() + .contains("executor panicked")); + } + assert_eq!(notifications.lock().unwrap().len(), 1); + + let (content, is_error, _) = router + .handle_call_with_extra("mod", &json!({}), Some(extra())) + .await; + assert!(!is_error); + assert_eq!( + serde_json::from_str::(content[0].data.as_str().unwrap()).unwrap(), + json!({"first": true}) + ); + assert_eq!(notifications.lock().unwrap().len(), 2); + assert_eq!(fallback_calls.load(Ordering::Relaxed), 0); + } + #[tokio::test] async fn test_e2e_streaming_fallback_no_support() { // Executor without stream support falls back to non-streaming diff --git a/mcp/rust/src/server/session.rs b/mcp/rust/src/server/session.rs index 41bb2bce..80873877 100644 --- a/mcp/rust/src/server/session.rs +++ b/mcp/rust/src/server/session.rs @@ -215,6 +215,10 @@ impl McpSession { lock(&self.pending).len() } + pub(crate) async fn send_notification(&self, message: Value) -> Result<(), SessionError> { + self.sink.send(message).await + } + /// Send a server-initiated request and await the client's answer. async fn request(&self, method: &str, params: Value) -> Result { let id = format!("apcore-mcp-{}", uuid::Uuid::new_v4()); diff --git a/mcp/rust/src/server/transport.rs b/mcp/rust/src/server/transport.rs index 16e1f078..c5e5bffe 100644 --- a/mcp/rust/src/server/transport.rs +++ b/mcp/rust/src/server/transport.rs @@ -2,9 +2,11 @@ //! //! Also exposes Prometheus metrics for observability. +use std::collections::{HashMap, VecDeque}; use std::convert::Infallible; -use std::sync::Arc; +use std::sync::{Arc, Mutex}; +use apcore::CancelToken; use axum::extract::Request; use axum::response::{IntoResponse, Redirect}; use axum::routing::{get, post}; @@ -15,8 +17,146 @@ use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncWrite, AsyncWriteExt, BufReader use tokio_stream::wrappers::LinesStream; +use crate::auth::middleware::AUTH_IDENTITY; use crate::server::session::{McpSession, OutboundSink, SessionError, SessionRegistry}; +tokio::task_local! { + /// Wire-level parent of the router's APCore invocation token. + pub(super) static WIRE_CALL_CANCEL: CancelToken; +} + +/// Active JSON-RPC tool calls, owned by one transport session. +#[derive(Clone, Default)] +struct DirectRequests(Arc>>>); + +#[derive(Default)] +struct DirectCancellation { + token: CancelToken, + wake: tokio::sync::Notify, +} + +impl DirectCancellation { + fn cancel(&self) { + self.token.cancel(); + self.wake.notify_one(); + } + + async fn cancelled(&self) { + if !self.token.is_cancelled() { + self.wake.notified().await; + } + } +} + +struct DirectRequestGuard { + requests: DirectRequests, + id: String, + cancellation: Arc, +} + +impl Drop for DirectRequestGuard { + fn drop(&mut self) { + self.requests + .0 + .lock() + .unwrap_or_else(|error| error.into_inner()) + .remove(&self.id); + } +} + +impl DirectRequests { + async fn dispatch(&self, handler: &dyn McpHandler, message: Value) -> Option { + let registration = self.register(&message); + self.dispatch_registered(handler, message, registration, None) + .await + } + + // Registration happens on receipt, before waiting for a dispatch slot. + fn register(&self, message: &Value) -> Result, Value> { + if message["method"] != "tools/call" || message["jsonrpc"] != "2.0" { + return Ok(None); + } + let Some(id) = request_key(&message["id"]) else { + return Ok(None); + }; + let cancellation = Arc::new(DirectCancellation::default()); + let mut requests = self.0.lock().unwrap_or_else(|error| error.into_inner()); + if requests.contains_key(&id) { + return Err(serde_json::json!({ + "jsonrpc": "2.0", "id": message["id"], + "error": {"code": -32600, "message": "Duplicate in-flight request ID"} + })); + } + requests.insert(id.clone(), Arc::clone(&cancellation)); + Ok(Some(DirectRequestGuard { + requests: self.clone(), + id, + cancellation, + })) + } + + async fn dispatch_registered( + &self, + handler: &dyn McpHandler, + message: Value, + registration: Result, Value>, + slots: Option>, + ) -> Option { + if message["jsonrpc"] == "2.0" && is_cancel_notification(&message) { + let id = request_key(&message["params"]["requestId"])?; + let requests = self.0.lock().unwrap_or_else(|error| error.into_inner()); + if let Some(token) = requests.get(&id) { + token.cancel(); + return None; + } + } + let guard = match registration { + Ok(guard) => guard, + Err(response) => return Some(response), + }; + let _permit = match (slots, &guard) { + (Some(slots), Some(guard)) => { + tokio::select! { + biased; + _ = guard.cancellation.cancelled() => return None, + permit = slots.acquire_owned() => Some(permit.ok()?), + } + } + (Some(slots), None) if !is_cancel_notification(&message) => { + Some(slots.acquire_owned().await.ok()?) + } + _ => None, + }; + let Some(guard) = guard else { + return handler.handle_message(message).await; + }; + if guard.cancellation.token.is_cancelled() { + return None; + } + let response = WIRE_CALL_CANCEL + .scope( + guard.cancellation.token.clone(), + handler.handle_message(message), + ) + .await; + // The client's cancellation owns this request, even if the module + // had already prepared a late success response. + if guard.cancellation.token.is_cancelled() { + None + } else { + response + } + } +} + +fn request_key(id: &Value) -> Option { + (id.is_string() || id.is_i64() || id.is_u64()).then(|| id.to_string()) +} + +fn is_cancel_notification(message: &Value) -> bool { + message["method"] == "notifications/cancelled" && message.get("id").is_none() +} + // --------------------------------------------------------------------------- // Task 1: TransportError // --------------------------------------------------------------------------- @@ -469,6 +609,7 @@ impl TransportManager { }; let mut lines = LinesStream::new(BufReader::new(reader).lines()); + let requests = DirectRequests::default(); let mut inflight = FuturesUnordered::new(); let mut eof = false; @@ -508,11 +649,19 @@ impl TransportManager { } } stamp_session_id(&mut message, &session_id); - inflight.push(handler.handle_message(message)); + inflight.push(requests.dispatch(handler, message)); } } } Some(response) = inflight.next(), if !inflight.is_empty() => { + // Fast streamed calls can enqueue progress without ever + // yielding. Write already queued notifications before the + // completed reply, even when this arm wins the select. + for _ in 0..outbound_rx.len() { + if let Ok(outgoing) = outbound_rx.try_recv() { + Self::write_stdio_message(&mut writer, &outgoing).await?; + } + } if let Some(response) = response { Self::write_stdio_message(&mut writer, &response).await?; } @@ -522,7 +671,7 @@ impl TransportManager { } } - if eof && inflight.is_empty() { + if eof && inflight.is_empty() && outbound_rx.is_empty() { return Ok(()); } } @@ -557,14 +706,10 @@ impl TransportManager { handler: Arc, extra_routes: Option, ) -> Router { - // TODO: Per MCP spec, each client connection should get its own - // session ID. Currently a single ID is shared across all connections, - // which means DELETE (session termination) affects all clients. - // Requires a session store keyed by UUID. - let session_id = uuid::Uuid::new_v4().to_string(); let mcp_state = StreamableHttpState { handler, - session_id, + unscoped_id: uuid::Uuid::new_v4().to_string(), + sessions: Default::default(), }; let mcp_router = Router::new() @@ -792,36 +937,81 @@ async fn usage_handler( // Streamable-HTTP state & handlers // --------------------------------------------------------------------------- -/// Shared state for the streamable-HTTP MCP endpoint. -/// -/// # Why this transport has no elicitation -/// -/// `session_id` here is minted once per *application*, not once per -/// connection, so every client that talks to this endpoint reports the same -/// id. Registering it in the [`SessionRegistry`] would therefore point every -/// connection at one [`McpSession`]: a prompt raised by one client's tool -/// call would be written to whichever connection happened to own the entry, -/// and any client could answer another's prompt. That is precisely the -/// cross-connection leak the SSE session isolation work removed, and it must -/// not be reintroduced here for the sake of feature parity. -/// -/// Inbound messages are consequently not stamped with a session id either, so -/// [`ExecutionRouter::extract_extra`] resolves no session and elicitation is -/// simply unavailable — which fails closed: a gated call is denied rather than -/// prompted on the wrong stream. `streamable_http_elicitation_fails_closed` -/// pins that. -/// -/// Making elicitation work here requires per-connection sessions first (the -/// `TODO` in [`TransportManager::build_streamable_http_app`]), not a -/// registration bolted onto the shared id. -/// -/// [`SessionRegistry`]: crate::server::session::SessionRegistry -/// [`McpSession`]: crate::server::session::McpSession -/// [`ExecutionRouter::extract_extra`]: crate::server::router::ExecutionRouter +/// Streamable HTTP keeps cancellation scopes independent from the live +/// server-to-client connections used for elicitation. Legacy clients without +/// an initialized session can still make ordinary stateless requests. #[derive(Clone)] struct StreamableHttpState { handler: Arc, - session_id: String, + unscoped_id: String, + sessions: Arc>>, +} + +#[derive(Clone)] +struct HttpSession { + id: String, + owner: Option<(String, String)>, + requests: DirectRequests, +} + +fn http_session_owner() -> Option<(String, String)> { + AUTH_IDENTITY + .try_with(|owner| { + owner.as_ref().map(|identity| { + ( + identity.identity_type().to_string(), + identity.id().to_string(), + ) + }) + }) + .ok() + .flatten() +} + +impl StreamableHttpState { + fn session(&self, headers: &axum::http::HeaderMap) -> Result, StatusCode> { + let Some(header) = headers.get("mcp-session-id") else { + return Ok(None); + }; + let id = header.to_str().map_err(|_| StatusCode::NOT_FOUND)?; + if id == self.unscoped_id { + return Ok(None); + } + let owner = http_session_owner(); + let mut sessions = self + .sessions + .lock() + .unwrap_or_else(|error| error.into_inner()); + let index = sessions + .iter() + .position(|session| session.id == id && session.owner == owner) + .ok_or(StatusCode::NOT_FOUND)?; + let session = sessions.remove(index).ok_or(StatusCode::NOT_FOUND)?; + sessions.push_back(session.clone()); + Ok(Some(session)) + } + + fn create_session(&self) -> Option { + const MAX_HTTP_SESSIONS: usize = 1024; + let mut sessions = self + .sessions + .lock() + .unwrap_or_else(|error| error.into_inner()); + if sessions.len() == MAX_HTTP_SESSIONS { + // Retire the least recently used session with no active dispatch. + let idle = sessions + .iter() + .position(|session| Arc::strong_count(&session.requests.0) == 1)?; + sessions.remove(idle); + } + let id = uuid::Uuid::new_v4().to_string(); + sessions.push_back(HttpSession { + id: id.clone(), + owner: http_session_owner(), + requests: DirectRequests::default(), + }); + Some(id) + } } #[derive(Debug, thiserror::Error)] @@ -863,19 +1053,45 @@ async fn streamable_http_post_handler( Err(error) => return error.into_response(), }; stamp_http_protocol(&mut body, version); - match state.handler.handle_message(body).await { - Some(response) => ( - StatusCode::OK, - [ - ("content-type", "application/json"), - ("mcp-session-id", state.session_id.as_str()), - ], - serde_json::to_string(&response).unwrap_or_default(), - ) - .into_response(), + let session = match state.session(&headers) { + Ok(session) => session, + Err(status) => return status.into_response(), + }; + let mut session_id = session + .as_ref() + .map(|session| session.id.clone()) + .unwrap_or_else(|| state.unscoped_id.clone()); + let initialize = body["method"] == "initialize"; + let response = match session { + Some(session) => { + session + .requests + .dispatch(state.handler.as_ref(), body) + .await + } + None => state.handler.handle_message(body).await, + }; + match response { + Some(response) => { + if initialize && response.get("result").is_some() { + let Some(id) = state.create_session() else { + return StatusCode::SERVICE_UNAVAILABLE.into_response(); + }; + session_id = id; + } + ( + StatusCode::OK, + [ + ("content-type", "application/json"), + ("mcp-session-id", session_id.as_str()), + ], + serde_json::to_string(&response).unwrap_or_default(), + ) + .into_response() + } None => ( StatusCode::ACCEPTED, - [("mcp-session-id", state.session_id.as_str())], + [("mcp-session-id", session_id.as_str())], ) .into_response(), } @@ -900,7 +1116,11 @@ async fn streamable_http_get_handler( use axum::response::sse::{Event, KeepAlive, Sse}; use std::time::Duration; - let session_id = state.session_id.clone(); + let session_id = match state.session(&headers) { + Ok(Some(session)) => session.id, + Ok(None) => state.unscoped_id, + Err(status) => return status.into_response(), + }; // Per-connection channel: the first item is the `endpoint` event; the // stream then stays open. axum's `KeepAlive` injects SSE comment frames so @@ -934,12 +1154,32 @@ async fn streamable_http_get_handler( /// DELETE /mcp — session termination. async fn streamable_http_delete_handler( - axum::extract::State(_state): axum::extract::State, + axum::extract::State(state): axum::extract::State, headers: axum::http::HeaderMap, ) -> axum::response::Response { if let Err(error) = http_protocol_version(&headers) { return error.into_response(); } + match state.session(&headers) { + Ok(Some(session)) => { + let mut sessions = state + .sessions + .lock() + .unwrap_or_else(|error| error.into_inner()); + sessions.retain(|stored| stored.id != session.id); + for token in session + .requests + .0 + .lock() + .unwrap_or_else(|error| error.into_inner()) + .values() + { + token.cancel(); + } + } + Ok(None) => {} + Err(status) => return status.into_response(), + } StatusCode::OK.into_response() } @@ -1145,6 +1385,9 @@ fn stamp_http_protocol(message: &mut Value, version: &str) { } if let Some(meta) = params["_meta"].as_object_mut() { meta.remove("sessionId"); + if let Some(nested) = meta.get_mut("_meta").and_then(Value::as_object_mut) { + nested.remove("sessionId"); + } meta.insert("mcpProtocolVersion".into(), serde_json::json!(version)); } } @@ -1206,6 +1449,7 @@ async fn sse_stream_handler( let handler = state.handler.clone(); let owned_session_id = session_id.clone(); + let requests = DirectRequests::default(); let dispatch_slots = Arc::new(tokio::sync::Semaphore::new( MAX_CONCURRENT_SESSION_DISPATCHES, )); @@ -1243,14 +1487,12 @@ async fn sse_stream_handler( let handler = Arc::clone(&handler); let event_tx = event_tx.clone(); let slots = Arc::clone(&dispatch_slots); + let requests = requests.clone(); + let registration = requests.register(&message); tokio::spawn(async move { - // Taken inside the task, not in the loop: taking - // it above would put the loop right back to - // waiting on handlers once the session saturates. - let Ok(_permit) = slots.acquire().await else { - return; - }; - if let Some(response) = handler.handle_message(message).await { + if let Some(response) = requests.dispatch_registered( + handler.as_ref(), message, registration, Some(slots) + ).await { let data = serde_json::to_string(&response).unwrap_or_default(); let event = Event::default().event("message").data(data); let _ = event_tx.send(Ok(event)).await; @@ -2392,13 +2634,17 @@ mod tests { #[test] fn test_protocol_metadata_is_transport_owned() { let mut message = serde_json::json!({"method":"tools/call","params":{ - "_meta":{"sessionId":"forged","mcpProtocolVersion":"2025-06-18","progressToken":"p"}}}); + "_meta":{"sessionId":"forged","_meta":{"sessionId":"forged-nested"}, + "mcpProtocolVersion":"2025-06-18","progressToken":"p"}}}); stamp_http_protocol(&mut message, "2025-03-26"); assert_eq!( message["params"]["_meta"]["mcpProtocolVersion"], "2025-03-26" ); assert!(message["params"]["_meta"].get("sessionId").is_none()); + assert!(message["params"]["_meta"]["_meta"] + .get("sessionId") + .is_none()); stamp_session_id(&mut message, "real-session"); assert!(message["params"]["_meta"] .get("mcpProtocolVersion") @@ -3362,6 +3608,351 @@ mod tests { writer.flush().await.expect("flush"); } + struct GatedCalls { + handler: Arc, + entries: tokio::sync::mpsc::UnboundedReceiver, + cancellations: tokio::sync::mpsc::UnboundedReceiver, + release: Arc, + } + + fn gated_calls() -> GatedCalls { + use apcore::registry::ModuleDescriptor; + use apcore::{Context, Module, Registry}; + use tokio::sync::{mpsc, Semaphore}; + + struct GatedModule { + entered: mpsc::UnboundedSender, + cancelled: mpsc::UnboundedSender, + release: Arc, + } + + #[async_trait::async_trait] + impl Module for GatedModule { + fn input_schema(&self) -> Value { + serde_json::json!({"type": "object"}) + } + + fn output_schema(&self) -> Value { + serde_json::json!({"type": "object"}) + } + + fn description(&self) -> &str { + "Wait for cancellation or release" + } + + async fn execute( + &self, + input: Value, + context: &Context, + ) -> Result { + let name = input["name"].as_str().unwrap().to_string(); + let token = context.cancel_token.as_ref().expect("execution token"); + self.entered.send(name.clone()).unwrap(); + loop { + if token.is_cancelled() { + self.cancelled.send(name).unwrap(); + return Err(token.check().unwrap_err().into()); + } + if let Ok(permit) = self.release.try_acquire() { + permit.forget(); + return Ok(input); + } + tokio::time::sleep(std::time::Duration::from_millis(2)).await; + } + } + } + + let (entered, entries) = mpsc::unbounded_channel(); + let (cancelled, cancellations) = mpsc::unbounded_channel(); + let release = Arc::new(Semaphore::new(0)); + let registry = Arc::new(Registry::new()); + registry + .register( + "test.gated", + Box::new(GatedModule { + entered, + cancelled, + release: Arc::clone(&release), + }), + ModuleDescriptor { + module_id: "test.gated".to_string(), + description: "Wait for cancellation or release".to_string(), + input_schema: serde_json::json!({"type": "object"}), + output_schema: serde_json::json!({"type": "object"}), + enabled: true, + name: None, + documentation: None, + version: "1.0.0".to_string(), + tags: vec![], + annotations: None, + examples: vec![], + metadata: Default::default(), + display: None, + sunset_date: None, + dependencies: vec![], + }, + ) + .unwrap(); + + let bridge = crate::APCoreMCP::builder() + .backend(registry) + .build() + .unwrap(); + let (server, _, _, options, _, _) = bridge.build_server_components().unwrap(); + let handler = + Arc::new(crate::server::server::ServerHandler::from_server(&server, options).unwrap()); + + GatedCalls { + handler, + entries, + cancellations, + release, + } + } + + fn gated_call(id: Value, name: &str) -> Value { + serde_json::json!({ + "jsonrpc": "2.0", + "id": id, + "method": "tools/call", + "params": {"name": "test.gated", "arguments": {"name": name}} + }) + } + + fn cancel_request(id: Value) -> Value { + serde_json::json!({ + "jsonrpc": "2.0", + "method": "notifications/cancelled", + "params": {"requestId": id} + }) + } + + #[tokio::test] + async fn stdio_notification_cancels_only_the_matching_wire_request() { + let GatedCalls { + handler, + mut entries, + mut cancellations, + release, + } = gated_calls(); + let mut clients = Vec::new(); + let mut transports = Vec::new(); + for _ in 0..2 { + let (client_io, server_io) = tokio::io::duplex(1024); + let (reader, writer) = tokio::io::split(client_io); + let (server_reader, server_writer) = tokio::io::split(server_io); + let handler = Arc::clone(&handler); + transports.push(tokio::spawn(async move { + TransportManager::new(None) + .run_stdio_with_io(server_reader, server_writer, handler.as_ref()) + .await + .unwrap(); + })); + clients.push((BufReader::new(reader).lines(), writer)); + } + + send(&mut clients[0].1, gated_call(7.into(), "target")).await; + send(&mut clients[0].1, gated_call("7".into(), "same-session")).await; + send(&mut clients[1].1, gated_call(7.into(), "second-session")).await; + + let deadline = std::time::Duration::from_secs(3); + for _ in 0..3 { + tokio::time::timeout(deadline, entries.recv()) + .await + .unwrap() + .unwrap(); + } + send(&mut clients[0].1, cancel_request(7.into())).await; + let target = tokio::time::timeout(deadline, cancellations.recv()).await; + release.add_permits(2); + assert_eq!(target.unwrap().as_deref(), Some("target")); + assert_eq!(recv(&mut clients[0].0).await["id"], "7"); + let peer = recv(&mut clients[1].0).await; + assert_eq!(peer["id"], 7); + assert_eq!(peer["result"]["isError"], false); + assert!(cancellations.try_recv().is_err()); + + drop(clients); + for transport in transports { + transport.await.unwrap(); + } + } + + async fn post_http_rpc( + app: &Router, + session: Option<&str>, + body: Value, + ) -> axum::response::Response { + use tower::ServiceExt; + let mut request = Request::builder() + .method("POST") + .uri("/mcp") + .header("content-type", "application/json"); + if let Some(session) = session { + request = request.header("mcp-session-id", session); + } + app.clone() + .oneshot( + request + .body(axum::body::Body::from(body.to_string())) + .unwrap(), + ) + .await + .unwrap() + } + + #[tokio::test] + async fn http_notification_cancels_only_the_request_in_the_initialized_session() { + use tower::ServiceExt; + + let GatedCalls { + handler, + mut entries, + mut cancellations, + release, + } = gated_calls(); + let app = Arc::new(TransportManager::new(None)).build_streamable_http_app(handler, None); + let mut sessions = Vec::new(); + for _ in 0..2 { + let initialized = post_http_rpc( + &app, + None, + serde_json::json!({ + "jsonrpc": "2.0", "id": 1, "method": "initialize", + "params": {"protocolVersion": "2025-06-18", "capabilities": {}, + "clientInfo": {"name": "test", "version": "1"}} + }), + ) + .await; + assert_eq!(initialized.status(), StatusCode::OK); + sessions.push( + initialized.headers()["mcp-session-id"] + .to_str() + .unwrap() + .to_string(), + ); + } + assert_ne!(sessions[0], sessions[1]); + + let a = tokio::spawn({ + let app = app.clone(); + let session = sessions[0].clone(); + async move { post_http_rpc(&app, Some(&session), gated_call(2.into(), "target")).await } + }); + let b = tokio::spawn({ + let app = app.clone(); + let session = sessions[1].clone(); + async move { post_http_rpc(&app, Some(&session), gated_call(2.into(), "peer")).await } + }); + + let deadline = std::time::Duration::from_secs(3); + for _ in 0..2 { + tokio::time::timeout(deadline, entries.recv()) + .await + .unwrap() + .unwrap(); + } + assert_eq!( + post_http_rpc(&app, Some(&sessions[0]), cancel_request(2.into())) + .await + .status(), + StatusCode::ACCEPTED + ); + let target = tokio::time::timeout(deadline, cancellations.recv()).await; + release.add_permits(1); + assert_eq!(target.unwrap().as_deref(), Some("target")); + assert_eq!(a.await.unwrap().status(), StatusCode::ACCEPTED); + let peer = b.await.unwrap(); + assert_eq!(peer.status(), StatusCode::OK); + let bytes = axum::body::to_bytes(peer.into_body(), usize::MAX) + .await + .unwrap(); + let peer: Value = serde_json::from_slice(&bytes).unwrap(); + assert_eq!(peer["result"]["isError"], false); + assert!(cancellations.try_recv().is_err()); + + let delete = Request::builder() + .method("DELETE") + .uri("/mcp") + .header("mcp-session-id", &sessions[0]) + .body(axum::body::Body::empty()) + .unwrap(); + assert_eq!( + app.clone().oneshot(delete).await.unwrap().status(), + StatusCode::OK + ); + assert_eq!( + post_http_rpc(&app, Some(&sessions[0]), cancel_request(2.into())) + .await + .status(), + StatusCode::NOT_FOUND + ); + assert_eq!( + post_http_rpc(&app, Some(&sessions[1]), cancel_request(2.into())) + .await + .status(), + StatusCode::ACCEPTED + ); + } + + #[tokio::test] + async fn sse_notification_bypasses_full_request_dispatch_queue() { + let GatedCalls { + handler, + mut entries, + mut cancellations, + release, + } = gated_calls(); + #[allow(deprecated)] + let app = Arc::new(TransportManager::new(None)).build_sse_app(handler, None); + let (_body, session) = open_sse_session(&app).await; + for index in 0..MAX_CONCURRENT_SESSION_DISPATCHES { + assert_eq!( + post_sse_raw(&app, &session, gated_call(index.into(), &index.to_string())).await, + StatusCode::ACCEPTED, + ); + } + let deadline = std::time::Duration::from_secs(3); + for _ in 0..MAX_CONCURRENT_SESSION_DISPATCHES { + tokio::time::timeout(deadline, entries.recv()) + .await + .unwrap() + .unwrap(); + } + assert_eq!( + post_sse_raw( + &app, + &session, + gated_call(100.into(), "cancelled while queued") + ) + .await, + StatusCode::ACCEPTED, + ); + assert_eq!( + post_sse_raw(&app, &session, cancel_request(100.into())).await, + StatusCode::ACCEPTED, + ); + assert_eq!( + post_sse_raw(&app, &session, cancel_request(0.into())).await, + StatusCode::ACCEPTED, + ); + let target = tokio::time::timeout(deadline, cancellations.recv()).await; + release.add_permits(MAX_CONCURRENT_SESSION_DISPATCHES); + assert_eq!(target.unwrap().as_deref(), Some("0")); + assert!(cancellations.try_recv().is_err()); + assert_eq!( + post_sse_raw(&app, &session, gated_call(101.into(), "control")).await, + StatusCode::ACCEPTED, + ); + assert_eq!( + tokio::time::timeout(deadline, entries.recv()) + .await + .unwrap() + .as_deref(), + Some("control") + ); + } + #[tokio::test] async fn stdio_carries_an_elicitation_round_trip() { let registry = Arc::new(SessionRegistry::new()); diff --git a/mcp/rust/tests/openapi_backend_conformance.rs b/mcp/rust/tests/openapi_backend_conformance.rs index af2b573d..7663124f 100644 --- a/mcp/rust/tests/openapi_backend_conformance.rs +++ b/mcp/rust/tests/openapi_backend_conformance.rs @@ -42,6 +42,8 @@ struct ModuleCase { struct ExpectedModule { module_id: String, #[serde(default)] + description: Option, + #[serde(default)] mcp_tool_name: Option, #[serde(default)] openai_function_name: Option, @@ -147,6 +149,9 @@ async fn conformance_modules() { panic!("case {}: no definition for {}", case.id, want.module_id) }); let annotations = definition.annotations.clone().unwrap_or_default(); + if let Some(description) = &want.description { + assert_eq!(&definition.description, description); + } // The MCP tool name is the module ID verbatim; OpenAI is dash-normalized. if let Some(tool_name) = &want.mcp_tool_name { diff --git a/mcp/rust/tests/openapi_backend_option_plumbing.rs b/mcp/rust/tests/openapi_backend_option_plumbing.rs index 596a4e93..b7c82e03 100644 --- a/mcp/rust/tests/openapi_backend_option_plumbing.rs +++ b/mcp/rust/tests/openapi_backend_option_plumbing.rs @@ -297,7 +297,7 @@ fn project_dir() -> tempfile::TempDir { // pass for the wrong reason. std::fs::write( dir.path().join("apcore.yaml"), - "version: '0.15.0'\nproject:\n name: wiring-test\n", + "version: '1.0.0'\nproject:\n name: wiring-test\n", ) .unwrap(); std::fs::write( @@ -464,3 +464,57 @@ async fn test_effective_openapi_registration_preflights_and_forwards_selected_op "GET /items/red%2Fblue?tag=red&tag=blue HTTP/1.1\r\n" ); } + +#[tokio::test] +async fn test_backend_refuses_startup_when_a_host_validator_rejects_a_scanned_module() { + use apcore::module::{Module, ValidationResult}; + use apcore::registry::registry::{ModuleDescriptor, ModuleValidator}; + use apcore::ValidationErrorDetail; + + struct RejectUpdate; + + impl ModuleValidator for RejectUpdate { + fn validate( + &self, + _module: &dyn Module, + descriptor: Option<&ModuleDescriptor>, + ) -> ValidationResult { + let mut result = ValidationResult::default(); + result.valid = + !descriptor.is_some_and(|descriptor| descriptor.module_id == "update_item"); + if !result.valid { + result.errors = vec![ValidationErrorDetail::message_only("rejected by host rule")]; + } + result + } + } + + let registry = Arc::new(Registry::new()); + registry.set_validator(Box::new(RejectUpdate)); + let document = json!({ + "openapi": "3.1.0", + "info": {"title": "Inventory", "version": "1"}, + "paths": { + "/items": {"get": {"operationId": "list_items", "summary": "List items", + "responses": {"200": {"description": "OK"}}}}, + "/updates": {"post": {"operationId": "update_item", "summary": "Update item", + "responses": {"200": {"description": "OK"}}}} + } + }); + let message = openapi_backend( + &document, + registry, + OpenAPIBackendOptions { + base_url: Some("http://127.0.0.1:1".to_string()), + acknowledge_unapproved_writes: true, + ..OpenAPIBackendOptions::new() + }, + ) + .await + .expect_err("incomplete assembly must not start") + .to_string(); + assert!( + message.contains("update_item") && message.contains("rejected by host rule"), + "{message}", + ); +} diff --git a/mcp/typescript/CHANGELOG.md b/mcp/typescript/CHANGELOG.md index 9a468e24..b30588df 100644 --- a/mcp/typescript/CHANGELOG.md +++ b/mcp/typescript/CHANGELOG.md @@ -6,6 +6,12 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [0.23.9-alpha.1] - Unreleased + +### Fixed + +- Route inbound cancellation to the active request, derive terminal stream results from Core when available, and fail startup when OpenAPI tools fail to register. + ## [0.23.8] - 2026-11-20 ### Changed diff --git a/mcp/typescript/README.md b/mcp/typescript/README.md index 0f168fe0..6d750c3b 100644 --- a/mcp/typescript/README.md +++ b/mcp/typescript/README.md @@ -646,6 +646,17 @@ await reportProgress(context, 5, 10, "Processing item 5 of 10"); - `total` — Optional total for percentage calculation - `message` — Optional human-readable progress message +When the executor supports streaming completion, a streaming tool uses a +single invocation and returns the executor's final output snapshot. A progress +token enables provisional chunk notifications. Sensitive output fields are +redacted in both notifications and the terminal result. Output-validation and +after-middleware failures make the tool call fail even after provisional +progress has been sent. + +An installed Core executor without streaming completion support uses one +ordinary invocation. Custom executors with only the legacy streaming interface +can still emit progress with a progress token. + ### `elicit(context, message, requestedSchema?)` Ask the MCP client for user input via the elicitation protocol. Returns `null` when called outside an MCP context. diff --git a/mcp/typescript/package.json b/mcp/typescript/package.json index 13db1f2c..74a19dc6 100644 --- a/mcp/typescript/package.json +++ b/mcp/typescript/package.json @@ -1,6 +1,6 @@ { "name": "apcore-mcp", - "version": "0.23.8", + "version": "0.23.9-alpha.1", "packageManager": "pnpm@10.30.1", "description": "Automatic MCP Server & OpenAI Tools Bridge for apcore", "type": "module", @@ -51,8 +51,8 @@ "dependencies": { "@modelcontextprotocol/sdk": "1.32.0", "ajv": "^8.17.1", - "apcore-js": ">=0.33.0", - "apcore-toolkit": ">=0.15.0", + "apcore-js": ">=0.33.0 <1.0.0 || 1.0.0-alpha.1", + "apcore-toolkit": "0.15.1-alpha.1", "jsonwebtoken": ">=9.0.3", "mcp-embedded-ui": ">=0.5.1" }, diff --git a/mcp/typescript/pnpm-lock.yaml b/mcp/typescript/pnpm-lock.yaml index 57cc721b..d178ebfb 100644 --- a/mcp/typescript/pnpm-lock.yaml +++ b/mcp/typescript/pnpm-lock.yaml @@ -15,11 +15,11 @@ importers: specifier: ^8.17.1 version: 8.20.0 apcore-js: - specifier: '>=0.33.0' + specifier: '>=0.33.0 <1.0.0 || 1.0.0-alpha.1' version: 0.33.0 apcore-toolkit: - specifier: '>=0.15.0' - version: 0.15.0(@sinclair/typebox@0.34.48) + specifier: 0.15.1-alpha.1 + version: 0.15.1-alpha.1(@sinclair/typebox@0.34.48) jsonwebtoken: specifier: '>=9.0.3' version: 9.0.3 @@ -623,8 +623,8 @@ packages: resolution: {integrity: sha512-+0UPovkB37qKy9kUwZmgSK6an+RqOUy+XOU9sEAauXStmQYIWmPBV7ACymQ9nwPI4RVAKiWbU4upMIqrCitxoQ==} engines: {node: '>=20.0.0'} - apcore-toolkit@0.15.0: - resolution: {integrity: sha512-PAF0NvA1TRUlS1uHyUwjfe/c7OqttgxxAyMkwcijvQqh45UhUx5V49I6LPrJpHSq1dvkY6komnEO5FeCi/CjqQ==} + apcore-toolkit@0.15.1-alpha.1: + resolution: {integrity: sha512-e8E9gtYAKLeBkpdIQisey4LogMdTR+qffL5PD5U0TyLiVl2v90xSBVXfHof3FkJWMj0/MKRqjlyzBk750xmt+w==} engines: {node: '>=20.10.0'} peerDependencies: '@sinclair/typebox': '>=0.31.0' @@ -1939,7 +1939,7 @@ snapshots: js-yaml: 4.3.2 uuid: 11.1.1 - apcore-toolkit@0.15.0(@sinclair/typebox@0.34.48): + apcore-toolkit@0.15.1-alpha.1(@sinclair/typebox@0.34.48): dependencies: '@sinclair/typebox': 0.34.48 ajv: 8.20.0 diff --git a/mcp/typescript/src/openapi-backend.ts b/mcp/typescript/src/openapi-backend.ts index 504fdbe6..c8c3b7f9 100644 --- a/mcp/typescript/src/openapi-backend.ts +++ b/mcp/typescript/src/openapi-backend.ts @@ -18,6 +18,7 @@ import { HTTPProxyRegistryWriter, OpenAPIScanner, loadSpec, + readProxyRoute, validateEffectiveProxyModules, type ScannedModule, } from "apcore-toolkit"; @@ -275,9 +276,33 @@ export async function openapiBackend( baseUrl, authHeaderFactory: options.authHeaderFactory, }); - for (const result of await writer.write(modules, target)) { - const err = (result as { verificationError?: string }).verificationError; - if (err) log.error(`OpenAPI module ${result.moduleId} failed to register: ${err}`); + // Keep the Toolkit writer's synchronous WriteResult contract while waiting + // for APCore's async host validators before publishing the backend. + const pending: Promise[] = []; + const asyncFailures = new Map(); + const proxyModules = modules.map((module) => { + if (/\P{White_Space}/u.test(module.description)) return module; + const { httpMethod = "GET", urlPath = "/" } = readProxyRoute(module); + const route = `${httpMethod.toUpperCase()} ${urlPath}`.replace(/\p{White_Space}+/gu, " ").trimEnd(); + return { ...module, description: Array.from(route).slice(0, 200).join("") }; + }); + const writes = await writer.write(proxyModules, { + register(moduleId, module) { + pending.push(Promise.resolve(target.register(moduleId, module)).catch((error: unknown) => { + asyncFailures.set(moduleId, error instanceof Error ? error.message : String(error)); + })); + }, + }); + await Promise.all(pending); + const results = new Map(writes.map(result => [result.moduleId, result])); + const failures = modules.flatMap(({ moduleId }) => { + const result = results.get(moduleId); + const error = asyncFailures.get(moduleId); + if (result?.verified && error === undefined && target.get(moduleId) != null) return []; + return [`${moduleId}: ${result?.verificationError ?? error ?? "module not registered"}`]; + }); + if (failures.length > 0) { + throw new Error(`OpenAPI registration incomplete: ${failures.join("; ")}`); } if (!options.acknowledgeUnapprovedWrites) { diff --git a/mcp/typescript/src/server/router.ts b/mcp/typescript/src/server/router.ts index dd0c5d15..ff62d8e3 100644 --- a/mcp/typescript/src/server/router.ts +++ b/mcp/typescript/src/server/router.ts @@ -4,16 +4,17 @@ * Bridges the MCP tools/call protocol with apcore's Executor.call() or callAsync(), * handling success/error formatting for MCP text content responses. * - * When the executor supports stream() and the caller provides a progressToken, - * chunks are forwarded as MCP notifications/progress before returning the - * accumulated result. + * Core completion supplies the authoritative stream result. When requested, + * provisional chunks are sent as MCP progress notifications. */ import * as crypto from "node:crypto"; import { registerStdioExecution } from "./stdio-output.js"; -import { CancelToken } from "apcore-js"; +import { CancelToken, isStreamingModule } from "apcore-js"; +import type { Module } from "apcore-js"; import { ErrorMapper } from "../adapters/errors.js"; -import type { Executor, TextContentDict, McpErrorResponse } from "../types.js"; +import { ErrorCodes } from "../types.js"; +import type { Executor, TextContentDict, McpErrorResponse, StreamCompletion, StreamExecution, StreamStepOutcome } from "../types.js"; import { createBridgeContext } from "./context.js"; import { MCP_PROGRESS_KEY, MCP_ELICIT_KEY } from "../helpers.js"; import type { ElicitResult } from "../helpers.js"; @@ -59,6 +60,55 @@ function deepMerge( return merged; } +function stepSucceeded(step: StreamStepOutcome): boolean { + return step.status === "passed" || (step.status === "skipped" && + (step.reason === "not_configured" || step.reason === "no_match" || step.reason === "strategy_skipped")); +} + +type CorePipeline = Pick & { + describePipeline(): unknown; + governanceState(): unknown; +}; + +function hasCorePipeline(value: unknown): value is CorePipeline { + if (value === null || typeof value !== "object") return false; + const candidate = value as Partial; + return typeof candidate.describePipeline === "function" && + typeof candidate.governanceState === "function" && typeof candidate.registry?.get === "function"; +} + +function isCoreExecutor(executor: Executor): boolean { + if (hasCorePipeline(executor)) return true; + // APCore exposes the same registry as its executor. Capability checks also + // recognize a separate installation of apcore-js. + const inner = (executor as { executor?: unknown }).executor; + return hasCorePipeline(inner) && inner.registry === executor.registry; +} + +const streamErrorCodes: ReadonlySet = new Set(Object.values(ErrorCodes)); + +function authoritativeOutput(receipt: StreamCompletion): Record { + if (receipt.reason === "completed" && receipt.output !== null && + stepSucceeded(receipt.outputValidation) && stepSucceeded(receipt.middlewareAfter)) { + return receipt.output; + } + + let code = ErrorCodes.MODULE_EXECUTE_ERROR as string; + let message = "Streaming invocation did not complete successfully"; + if (receipt.errorCode !== null && streamErrorCodes.has(receipt.errorCode)) { + code = receipt.errorCode; + } else if (receipt.reason === "consumer_closed" || receipt.reason === "cancelled") { + code = ErrorCodes.EXECUTION_CANCELLED; + } else if (receipt.reason === "timed_out") { + code = ErrorCodes.MODULE_TIMEOUT; + } else if (receipt.reason === "completed" && !stepSucceeded(receipt.outputValidation)) { + code = ErrorCodes.SCHEMA_VALIDATION_ERROR; + message = "Streaming output validation did not complete successfully"; + } + // Supply only a known code and a fixed diagnostic to the existing mapper. + throw Object.assign(new Error(message), { code, details: null }); +} + /** Tuple of [content array, isError flag, traceId] returned from handleCall. */ export type CallResult = [TextContentDict[], boolean, string | undefined]; @@ -391,10 +441,8 @@ export class ExecutionRouter { /** * Handle an MCP tools/call request by routing to the executor. * - * Streaming path: if the executor has stream(), a progressToken is present, - * and sendNotification is available, each chunk from stream() is forwarded as - * a `notifications/progress` notification. The chunks are shallow-merged into - * an accumulated result which is returned as the final response. + * For streaming modules, consume the authoritative Core completion even + * without a progress token. Send each chunk provisionally when requested. * * Non-streaming path: tries executor.call() first, then falls back to * executor.callAsync(). @@ -639,63 +687,40 @@ export class ExecutionRouter { // ── Resolve versionHint from request metadata or descriptor ────── let versionHint: string | undefined = extra?.versionHint ?? extra?._meta?.apcore?.version; - if (!versionHint) { - try { - const descriptor = this._executor.registry?.getDefinition?.(toolName); + let declaredStreaming = false; + try { + const descriptor = this._executor.registry?.getDefinition?.(toolName); + declaredStreaming = descriptor?.annotations?.streaming === true; + if (!versionHint) { const metaHint = descriptor?.metadata?.versionHint; if (typeof metaHint === "string") { versionHint = metaHint; } - } catch { - // ignore — registry lookup is best-effort } + if (!declaredStreaming && typeof this._executor.streamWithCompletion === "function") { + const module = this._executor.registry?.get?.(toolName, versionHint); + declaredStreaming = module != null && isStreamingModule(module as Module); + } + } catch { + // Registry lookup is best-effort for structurally compatible executors. } // ── Streaming path ──────────────────────────────────────────────── - if ( - this._executor.stream && - progressToken !== undefined && - sendNotification - ) { - let accumulated: Record = {}; - let chunkIndex = 0; - - // TODO(apcore>=0.19): streaming traces via streamWithTrace - for await (const chunk of this._executor.stream(toolName, args, context, versionHint)) { - // Deep-merge each chunk into the accumulated result - accumulated = deepMerge(accumulated, chunk); - - // Per-chunk redaction MUST happen before the chunk is serialized - // into the progress notification — otherwise an x-sensitive - // credential emitted mid-stream leaks to the MCP client even - // though the final accumulated result is later redacted. - // Mirrors Python's _handle_stream invariant. [A-D-003] - const safeChunk = await this._maybeRedact(toolName, chunk as Record); - - // Send progress notification for each chunk (redacted) - await sendNotification({ - method: "notifications/progress", - params: { - progressToken, - progress: chunkIndex + 1, - message: JSON.stringify(safeChunk), - }, - }); - - chunkIndex++; - } - - const redacted = await this._maybeRedact(toolName, accumulated); - - const content: TextContentDict[] = [ - { - type: "text", - text: await this._formatResult(redacted), - }, - ]; - - const traceId = effectiveTraceId; - return [content, false, traceId]; + const wantsProgress = progressToken !== undefined && sendNotification !== undefined; + const execution = typeof this._executor.streamWithCompletion === "function" && + (declaredStreaming || wantsProgress) + ? this._executor.streamWithCompletion(toolName, args, context, versionHint) + : null; + // Retain the old structural extension point for custom executors. An + // older Core instead uses one ordinary invocation with full validation. + const chunks = execution?.chunks ?? (wantsProgress && !isCoreExecutor(this._executor) + ? this._executor.stream?.(toolName, args, context, versionHint) + : undefined); + if (chunks) { + const progress = wantsProgress ? { token: progressToken, send: sendNotification } : undefined; + const output = await this._collectStream(toolName, chunks, execution, progress); + const redacted = await this._maybeRedact(toolName, output); + return [[{ type: "text", text: await this._formatResult(redacted) }], false, effectiveTraceId]; } // ── Non-streaming path ──────────────────────────────────────────── @@ -762,6 +787,36 @@ export class ExecutionRouter { } } + private async _collectStream( + toolName: string, + chunks: AsyncIterable>, + execution: StreamExecution | null, + progress?: { token: string | number; send: NonNullable }, + ): Promise> { + let accumulated: Record = {}; + let count = 0; + try { + for await (const chunk of chunks) { + if (!execution) accumulated = deepMerge(accumulated, chunk); + if (progress) { + const safeChunk = await this._maybeRedact(toolName, chunk); + await progress.send({ + method: "notifications/progress", + params: { progressToken: progress.token, progress: ++count, message: JSON.stringify(safeChunk) }, + }); + } + } + } catch (error) { + if (!execution) throw error; + // Core settles failures independently of iterator errors. This also + // closes promptly if sending a progress notification failed. + await execution.close(); + authoritativeOutput(await execution.completion); + throw new Error("Streaming progress failed"); + } + return execution ? authoritativeOutput(await execution.completion) : accumulated; + } + /** * Preflight validation for a tool call without executing it. * diff --git a/mcp/typescript/src/types.ts b/mcp/typescript/src/types.ts index 37db3f58..51d5b193 100644 --- a/mcp/typescript/src/types.ts +++ b/mcp/typescript/src/types.ts @@ -117,6 +117,7 @@ export interface ModuleDescriptor { export interface Registry { list(options?: { tags?: string[] | null; prefix?: string | null }): string[]; getDefinition(moduleId: string): ModuleDescriptor | null; + get?(moduleId: string, versionHint?: string): unknown; has?(moduleId: string): boolean; on(event: string, callback: (...args: unknown[]) => void): void; discover?(): Promise; @@ -128,10 +129,31 @@ export interface Executor { call(moduleId: string, inputs: Record, context?: unknown, versionHint?: string): Promise>; callAsync?(moduleId: string, inputs: Record, context?: unknown, versionHint?: string): Promise>; stream?(moduleId: string, inputs: Record, context?: unknown, versionHint?: string): AsyncIterable>; + streamWithCompletion?(moduleId: string, inputs: Record, context?: unknown, versionHint?: string): StreamExecution; validate?(toolName: string, args: Record): unknown | Promise; callWithTrace?(moduleId: string, inputs: Record, context?: unknown, versionHint?: string): Promise<[Record, unknown]>; } +/** Structural subset of Core's optional completion API. */ +export interface StreamExecution { + readonly chunks: AsyncIterable>; + readonly completion: Promise; + close(): Promise; +} + +export interface StreamCompletion { + readonly reason: string; + readonly output: Record | null; + readonly outputValidation: StreamStepOutcome; + readonly middlewareAfter: StreamStepOutcome; + readonly errorCode: string | null; +} + +export interface StreamStepOutcome { + readonly status: string; + readonly reason?: string; +} + // ─── Error Type ────────────────────────────────────────────────────────────── export interface ModuleError extends Error { diff --git a/mcp/typescript/tests/cli.test.ts b/mcp/typescript/tests/cli.test.ts index ab9c0607..c9ad95d0 100644 --- a/mcp/typescript/tests/cli.test.ts +++ b/mcp/typescript/tests/cli.test.ts @@ -5,9 +5,8 @@ * process.exit is mocked to throw a sentinel so that fail()/exit() stops * execution cleanly rather than continuing past the mock. * - * IMPORTANT: apcore-js on npm is a stub without dist/. All test scenarios - * must vi.doMock("apcore-js") BEFORE importing cli.ts to avoid Vite - * resolution errors. + * Tests stub the registry or configuration before importing cli.ts. Leave + * other Core exports available for the same-checkout Toolkit. */ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; @@ -108,22 +107,19 @@ describe("CLI (cli.ts)", () => { // end to end. vi.doMock("apcore-js", async () => vi.importActual("apcore-js")); } else if (apcoreAvailable) { - vi.doMock("apcore-js", () => ({ + vi.doMock("apcore-js", async (importOriginal) => ({ + ...await importOriginal(), Registry: vi.fn(function () { return { discover: vi.fn().mockResolvedValue(discoverCount), }; }), // Only present when a test needs to exercise the mcp.openapi // Config-Bus fallback (A-001) — real apcore-js's Config.getInstance() // shape, narrowed to just what cli.ts reads. - ...(configOpenapi !== undefined - ? { - Config: { - getInstance: () => ({ - get: (key: string) => (key === "mcp.openapi" ? configOpenapi : undefined), - }), - }, - } - : {}), + Config: configOpenapi === undefined ? undefined : { + getInstance: () => ({ + get: (key: string) => (key === "mcp.openapi" ? configOpenapi : undefined), + }), + }, })); } else { vi.doMock("apcore-js", () => { diff --git a/mcp/typescript/tests/config-bus.test.ts b/mcp/typescript/tests/config-bus.test.ts index 147f313f..fa5b1c82 100644 --- a/mcp/typescript/tests/config-bus.test.ts +++ b/mcp/typescript/tests/config-bus.test.ts @@ -44,7 +44,8 @@ vi.mock("../src/server/factory.js", () => ({ const getInstanceSpy = vi.fn().mockReturnValue({ get: vi.fn().mockReturnValue(null) }); -vi.mock("apcore-js", () => ({ +vi.mock("apcore-js", async (importOriginal) => ({ + ...await importOriginal(), Config: { getInstance: (...args: unknown[]) => getInstanceSpy(...args), }, diff --git a/mcp/typescript/tests/effective-openapi-backend.test.ts b/mcp/typescript/tests/effective-openapi-backend.test.ts index ca56ce36..eea2bc1f 100644 --- a/mcp/typescript/tests/effective-openapi-backend.test.ts +++ b/mcp/typescript/tests/effective-openapi-backend.test.ts @@ -61,3 +61,50 @@ it("forwards inherited referenced values after filtering an unsupported operatio })); } }); + + +const registrationDocument = { + ...document, + paths: { + "/items": { get: { operationId: "list_items", summary: "List items", responses: response } }, + "/updates": { post: { operationId: "update_item", summary: "Update item", responses: response } }, + }, +}; + +it("refuses startup when a host validator rejects a scanned module", async () => { + const registry = new Registry(); + registry.setValidator({ + validate: module => + (module as { description: string }).description === "Update item" ? ["rejected by host rule"] : [], + }); + await expect(openapiBackend(registrationDocument, { + registry, + baseUrl: "http://127.0.0.1:1", + acknowledgeUnapprovedWrites: true, + })).rejects.toThrow(/update_item.*rejected by host rule/s); +}); + + +it("waits for asynchronous host validation before publishing the backend", async () => { + const registry = new Registry(); + registry.setValidator({ validate: async () => [] }); + await expect(openapiBackend(registrationDocument, { + registry, + baseUrl: "http://127.0.0.1:1", + acknowledgeUnapprovedWrites: true, + })).resolves.toBe(registry); + expect(registry.list()).toEqual(["list_items", "update_item"]); +}); + +it("refuses publication when asynchronous host validation rejects", async () => { + const registry = new Registry(); + registry.setValidator({ + validate: async module => + (module as { description: string }).description === "Update item" ? ["rejected asynchronously"] : [], + }); + await expect(openapiBackend(registrationDocument, { + registry, + baseUrl: "http://127.0.0.1:1", + acknowledgeUnapprovedWrites: true, + })).rejects.toThrow(/update_item.*rejected asynchronously/s); +}); diff --git a/mcp/typescript/tests/openapi-backend-conformance.test.ts b/mcp/typescript/tests/openapi-backend-conformance.test.ts index ca740a39..b06b58d6 100644 --- a/mcp/typescript/tests/openapi-backend-conformance.test.ts +++ b/mcp/typescript/tests/openapi-backend-conformance.test.ts @@ -18,6 +18,7 @@ import { ModuleIDNormalizer } from "../src/adapters/id-normalizer.js"; interface ExpectedModule { module_id: string; + description?: string; mcp_tool_name?: string; openai_function_name?: string; mcp_annotations?: Record; @@ -109,6 +110,9 @@ describe("conformance: openapiBackend modules", () => { for (const want of c.expected_modules) { // eslint-disable-next-line @typescript-eslint/no-explicit-any const descriptor = await (registry as any).getDefinition(want.module_id); + if (want.description !== undefined) { + expect(descriptor.description).toBe(want.description); + } if (want.mcp_tool_name) expect(want.module_id).toBe(want.mcp_tool_name); if (want.openai_function_name) { expect(NORMALIZER.normalize(want.module_id)).toBe(want.openai_function_name); diff --git a/mcp/typescript/tests/server/request-cancellation.test.ts b/mcp/typescript/tests/server/request-cancellation.test.ts new file mode 100644 index 00000000..fd1c9229 --- /dev/null +++ b/mcp/typescript/tests/server/request-cancellation.test.ts @@ -0,0 +1,62 @@ +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; +import { Executor, Registry, type Context } from "apcore-js"; +import { expect, it } from "vitest"; + +import { MCPServerFactory } from "../../src/server/factory.js"; +import { ExecutionRouter } from "../../src/server/router.js"; + +it("routes a wire cancellation to the target Core invocation only", async () => { + const targetStarted = Promise.withResolvers(); + const peerStarted = Promise.withResolvers(); + const targetExited = Promise.withResolvers(); + const release = Promise.withResolvers(); + const registry = new Registry(); + registry.register("test.gated", { + description: "Wait for cancellation or the test gate", + inputSchema: { type: "object" }, + outputSchema: { type: "object" }, + async execute(inputs: Record, context: Context) { + if (inputs.name === "target") { + const aborted = Promise.withResolvers(); + context.signal.addEventListener("abort", () => aborted.resolve(), { once: true }); + targetStarted.resolve(); + await Promise.race([aborted.promise, release.promise]); + targetExited.resolve(context.signal.aborted); + } else { + peerStarted.resolve(); + await release.promise; + } + return { name: inputs.name, cancelled: context.signal.aborted }; + }, + } as never); + const factory = new MCPServerFactory(); + const server = factory.createServer(); + const executor = Executor.fromRegistry(registry); + const router = new ExecutionRouter(executor as never); + factory.registerHandlers(server, factory.buildTools(registry as never), router); + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + const client = new Client({ name: "wire-cancellation", version: "1" }); + await server.connect(serverTransport); + await client.connect(clientTransport); + + const controller = new AbortController(); + const cancellation = new Error("cancel the target request"); + const target = client.callTool({ name: "test.gated", arguments: { name: "target" } }, undefined, { + signal: controller.signal, + }).catch((error: unknown) => error); + const peer = client.callTool({ name: "test.gated", arguments: { name: "peer" } }); + void peer.catch(() => undefined); + try { + await Promise.all([targetStarted.promise, peerStarted.promise]); + controller.abort(cancellation); + expect(await target).toMatchObject({ message: expect.stringContaining(cancellation.message) }); + expect(await targetExited.promise).toBe(true); + release.resolve(); + expect((await peer).structuredContent).toEqual({ name: "peer", cancelled: false }); + } finally { + release.resolve(); + await client.close(); + await server.close(); + } +}); diff --git a/mcp/typescript/tests/server/stream-completion.test.ts b/mcp/typescript/tests/server/stream-completion.test.ts new file mode 100644 index 00000000..ecd11073 --- /dev/null +++ b/mcp/typescript/tests/server/stream-completion.test.ts @@ -0,0 +1,149 @@ +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; +import * as core from "apcore-js"; +import { cp, mkdir, mkdtemp, realpath, rm, symlink } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { expect, it } from "vitest"; +import { MCPServerFactory } from "../../src/server/factory.js"; +import { ExecutionRouter } from "../../src/server/router.js"; + +const moduleId = "test.completion"; +const hasCompletion = "streamWithCompletion" in core.Executor.prototype; +const redacted = "***REDACTED***"; + +async function connect( + fail: "validation" | "after" | null = null, + declaresStreaming = true, + sdk = core, + throughFacade = false, +) { + let calls = 0; + let streams = 0; + const registry = new sdk.Registry(); + const outputSchema = { + type: "object", + properties: { secret: { type: "string", "x-sensitive": true } }, + ...(fail === "validation" ? { required: ["absent"] } : {}), + }; + await registry.register(moduleId, { + description: "Distinguish ordinary invocation and canonical streaming", + annotations: sdk.createAnnotations({ streaming: declaresStreaming }), + [sdk.STREAMING_MARKER]: true, + inputSchema: { type: "object" }, + outputSchema, + execute: () => { calls++; return { atomic: true, absent: true }; }, + async *stream() { + streams++; + yield { group: { detail: { left: true } }, items: [1], secret: "wire-secret" }; + yield { group: { detail: { right: true } }, items: [2] }; + }, + } as never); + const config = new sdk.Config({ stream: { max_merge_depth: 1 } }); + const executor = throughFacade ? new sdk.APCore({ registry, config }) : new sdk.Executor({ registry, config }); + if (fail === "after") executor.useAfter(() => { throw new Error("private-after-cause"); }); + const factory = new MCPServerFactory(); + const server = factory.createServer(); + const router = new ExecutionRouter(executor as never, { outputSchemaMap: { [moduleId]: outputSchema } }); + factory.registerHandlers(server, factory.buildTools(registry as never), router); + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + const client = new Client({ name: "wire-completion", version: "1" }); + await server.connect(serverTransport); + await client.connect(clientTransport); + return { + client, + counts: () => ({ calls, streams }), + async close() { await client.close(); await server.close(); }, + }; +} + +it.each([false, true])("uses an independent Core package (facade: %s)", async (throughFacade) => { + const entry = await realpath(fileURLToPath(import.meta.resolve("apcore-js"))); + const source = dirname(dirname(entry)); + const copy = await mkdtemp(join(tmpdir(), "apcore-mcp-core-copy-")); + try { + const packageRoot = join(copy, "node_modules", "apcore-js"); + await mkdir(packageRoot, { recursive: true }); + await cp(join(source, "dist"), join(packageRoot, "dist"), { recursive: true }); + await cp(join(source, "package.json"), join(packageRoot, "package.json")); + await symlink(dirname(source), join(packageRoot, "node_modules"), "junction"); + const sdk: typeof core = await import(/* @vite-ignore */ pathToFileURL(join(packageRoot, "dist", "index.js")).href); + expect(sdk.Executor).not.toBe(core.Executor); + expect(sdk.APCore).not.toBe(core.APCore); + const notifications: unknown[] = []; + const target = await connect(hasCompletion ? null : "after", false, sdk, throughFacade); + try { + const result = await target.client.callTool({ name: moduleId, arguments: {} }, undefined, hasCompletion ? undefined : { + onprogress: ({ message }) => { notifications.push(message); }, + }); + if (hasCompletion) { + expect(result.isError).not.toBe(true); + expect(result.structuredContent).toEqual({ group: { detail: { right: true } }, items: [2], secret: redacted }); + expect(target.counts()).toEqual({ calls: 0, streams: 1 }); + } else { + expect(result.isError).toBe(true); + expect(result.structuredContent).toBeUndefined(); + expect(target.counts()).toEqual({ calls: 1, streams: 0 }); + expect(notifications).toEqual([]); + } + } finally { + await target.close(); + } + } finally { + await rm(copy, { recursive: true, force: true }); + } +}); + +it.each([false, true])("uses the capability before executing a tool (progress requested: %s)", async (withProgress) => { + const target = await connect(); + const notifications: unknown[] = []; + try { + const result = await target.client.callTool({ name: moduleId, arguments: {} }, undefined, withProgress ? { + onprogress: ({ message }) => { notifications.push(JSON.parse(message ?? "null")); }, + } : undefined); + expect(result.isError).not.toBe(true); + if (hasCompletion) { + expect(result.structuredContent).toEqual({ group: { detail: { right: true } }, items: [2], secret: redacted }); + expect(target.counts()).toEqual({ calls: 0, streams: 1 }); + expect(notifications).toEqual(withProgress ? [ + { group: { detail: { left: true } }, items: [1], secret: redacted }, + { group: { detail: { right: true } }, items: [2] }, + ] : []); + } else { + expect(result.structuredContent).toEqual({ atomic: true, absent: true }); + expect(target.counts()).toEqual({ calls: 1, streams: 0 }); + expect(notifications).toEqual([]); + } + } finally { + await target.close(); + } +}); + +it.skipIf(!hasCompletion)("runs marked native streams without annotations or a progress token", async () => { + const target = await connect(null, false); + try { + const result = await target.client.callTool({ name: moduleId, arguments: {} }); + expect(result.structuredContent).toMatchObject({ items: [2] }); + expect(target.counts()).toEqual({ calls: 0, streams: 1 }); + } finally { + await target.close(); + } +}); + +it.skipIf(!hasCompletion).each(["validation", "after"] as const)("rejects failed %s after provisional progress", async (failure) => { + const target = await connect(failure); + const notifications: unknown[] = []; + try { + const result = await target.client.callTool({ name: moduleId, arguments: {} }, undefined, { + onprogress: ({ message }) => { notifications.push(JSON.parse(message ?? "null")); }, + }); + expect(result.isError).toBe(true); + expect(result.structuredContent).toBeUndefined(); + expect(notifications).toHaveLength(2); + expect(JSON.stringify(result)).not.toMatch(/wire-secret|private-after-cause/); + expect(target.counts()).toEqual({ calls: 0, streams: 1 }); + } finally { + await target.close(); + } +}); diff --git a/mcp/typescript/tests/server/test-router-stream.test.ts b/mcp/typescript/tests/server/test-router-stream.test.ts index 15d61afc..8728c6bd 100644 --- a/mcp/typescript/tests/server/test-router-stream.test.ts +++ b/mcp/typescript/tests/server/test-router-stream.test.ts @@ -353,7 +353,8 @@ describe("ExecutionRouter — streaming", () => { const chunk2 = buildDeep(33, { deep: "v2" }); const executor = createStreamingExecutor([chunk1, chunk2]); - const router = new ExecutionRouter(executor); + // Isolate the legacy merge boundary from the independent redaction depth. + const router = new ExecutionRouter(executor, { redactOutput: false }); const extra = createExtra("tok-depth"); const [content, isError] = await router.handleCall("test.depth", {}, extra); diff --git a/scripts/verify-rust-core-candidate.py b/scripts/verify-rust-core-candidate.py new file mode 100644 index 00000000..19437212 --- /dev/null +++ b/scripts/verify-rust-core-candidate.py @@ -0,0 +1,99 @@ +#!/usr/bin/env python3 +"""Test a Rust Surface with one exact Core distribution in a disposable checkout.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import re +import subprocess +import tarfile +import tempfile +import tomllib +from pathlib import Path + + +def package_name(manifest: Path) -> str: + return tomllib.loads(manifest.read_text())["package"]["name"] + + +def pin_core(manifest: Path, version: str) -> None: + text, count = re.subn( + r'^apcore = "[^"]+"$', + f'apcore = "={version}"', + manifest.read_text(), + count=1, + flags=re.MULTILINE, + ) + if count != 1: + raise ValueError(f"Expected a version-only apcore dependency in {manifest}") + manifest.write_text(text) + + +def verify(component: str, version: str, archive: Path | None) -> None: + repo = Path(__file__).resolve().parents[1] + manifest = repo / component / "rust" / "Cargo.toml" + toolkit = repo / "toolkit" / "rust" / "Cargo.toml" + manifests = {manifest: manifest.read_bytes(), toolkit: toolkit.read_bytes()} + lock = manifest.with_name("Cargo.lock") + lock_contents = lock.read_bytes() if lock.exists() else None + try: + with tempfile.TemporaryDirectory(prefix="surface-core-") as temp: + patches = ["--config", f"patch.crates-io.apcore-toolkit.path={json.dumps(str(toolkit.parent))}"] + expected_core_path = None + if archive is not None: + print(f"Core crate SHA-256 {hashlib.sha256(archive.read_bytes()).hexdigest()}", flush=True) + with tarfile.open(archive, "r:gz") as crate: + crate.extractall(temp, filter="data") + expected_core_path = Path(temp) / f"apcore-{version}" / "Cargo.toml" + if package_name(expected_core_path) != "apcore": + raise ValueError("Candidate archive does not contain the apcore package") + patches += ["--config", f"patch.crates-io.apcore.path={json.dumps(str(expected_core_path.parent))}"] + + # Stable Cargo ranges exclude pre-releases. Pin the tested component + # and the checkout Toolkit together so both share one Core type identity. + for path in manifests: + pin_core(path, version) + + command = ["cargo", *patches] + rust_host = next( + line.removeprefix("host: ") + for line in subprocess.check_output(["rustc", "-vV"], text=True).splitlines() + if line.startswith("host: ") + ) + info = json.loads(subprocess.check_output( + [*command, "metadata", "--format-version", "1", "--filter-platform", rust_host], + cwd=manifest.parent, + )) + cores = [p for p in info["packages"] if p["name"] == "apcore"] + if len(cores) != 1 or cores[0]["version"] != version: + raise ValueError(f"Expected one apcore {version}, resolved {[p['version'] for p in cores]}") + core = cores[0] + if expected_core_path is None: + if not (core["source"] or "").startswith("registry+"): + raise ValueError("Expected the minimum Core from the registry") + elif Path(core["manifest_path"]).resolve() != expected_core_path.resolve(): + raise ValueError("Consumer did not resolve the verified candidate archive") + toolkits = [p for p in info["packages"] if p["name"] == "apcore-toolkit"] + if len(toolkits) != 1 or Path(toolkits[0]["manifest_path"]).resolve() != toolkit: + raise ValueError("Consumer did not resolve the Toolkit from this checkout") + print(f"Resolved apcore {version} at {core['manifest_path']}", flush=True) + print(f"Resolved apcore-toolkit {toolkits[0]['version']} at {toolkit}", flush=True) + subprocess.run([*command, "test", "--all-features", "--locked"], cwd=manifest.parent, check=True) + finally: + for path, data in manifests.items(): + path.write_bytes(data) + if lock_contents is None: + lock.unlink(missing_ok=True) + else: + lock.write_bytes(lock_contents) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("component", choices=["toolkit", "mcp", "a2a", "cli"]) + parser.add_argument("version") + parser.add_argument("--archive", type=Path) + options = parser.parse_args() + verify(options.component, options.version, options.archive) diff --git a/toolkit/docs/features/output-writers.md b/toolkit/docs/features/output-writers.md index e9dce70e..217a365b 100644 --- a/toolkit/docs/features/output-writers.md +++ b/toolkit/docs/features/output-writers.md @@ -969,6 +969,8 @@ Each `WriteResult` has `module_id`, `path`, `ok`, `verified`, `verification_erro - Verifier results are likewise wrapped into `WriteResult.verification_error` (Python/Rust) / `WriteResult.verificationError` (TypeScript); verifier exceptions are caught and stored, not re-raised. - Rust's `write` returns a bare `Vec` (not wrapped in `Result`) — per-module registration failures are reported exclusively via failed `WriteResult` entries, the same mechanism Python/TypeScript use. There is no top-level error channel in any of the three SDKs; `WriteResult.verified` is always the source of truth. +When assembling a server, check the full selected ID list against the returned results and actual registry contents before publishing the backend. Failed results can coexist with successful writes. Use a startup-owned registry when failures must prevent publication. + ### Returns - On success: list of `WriteResult` — one per module; `path` is `None`/`null` (no file written) diff --git a/toolkit/python/CHANGELOG.md b/toolkit/python/CHANGELOG.md index dc6f3063..380a446c 100644 --- a/toolkit/python/CHANGELOG.md +++ b/toolkit/python/CHANGELOG.md @@ -2,6 +2,12 @@ All notable changes to this project will be documented in this file. +## [0.15.1a1] - Unreleased + +### Added + +- Add a standalone Prometheus listener with liveness and readiness endpoints and isolate it from Core metrics rendering. + ## [0.15.0] - Unreleased ### Added diff --git a/toolkit/python/README.md b/toolkit/python/README.md index 44f349a0..4c15c1d4 100644 --- a/toolkit/python/README.md +++ b/toolkit/python/README.md @@ -32,6 +32,7 @@ pip install apcore-toolkit | `PythonWriter` | Generates `@module`-decorated Python wrapper files | | `RegistryWriter` | Registers modules directly into an `apcore.Registry`. Subclasses customize only the `_adapt_func` / `_build_input_schema` / `_build_output_schema` hooks; field mapping (incl. `annotations`) is centralized so no override can silently drop a field | | `assert_annotations_preserved` | Conformance check for adapter test suites: registers a module and asserts its behavioral annotations (`requires_approval` / `destructive`) survive `get_definition` — guards against a writer silently disabling approval/ACL gating | +| `create_prometheus_server` | Creates an application-owned HTTP listener for Prometheus metrics, liveness and readiness | | `HTTPProxyRegistryWriter` | Registers HTTP proxy modules that forward requests to a running API (requires `pip install apcore-toolkit[http-proxy]`) | | `DeviceAuthClient` | RFC 8628 device-authorization client: `login()`, `ensure_valid()`, `refresh()`, `as_auth_header_factory()` (requires `pip install apcore-toolkit[auth]`) | | `DeviceAuthConfig` | Provider configuration and compatibility surface (endpoints, `discover()`, client auth, `error_aliases` / `field_aliases`, per-kind request encoding, extension hooks) | @@ -83,6 +84,38 @@ pip install apcore-toolkit ## Usage +### Prometheus HTTP server + +`create_prometheus_server` binds to `127.0.0.1:9090` by default and returns a standard +`ThreadingHTTPServer`. It serves GET requests for `/metrics`, `/healthz` and `/readyz`. +Set `metrics_path` for a custom scrape path and supply `is_ready` to report availability. +The application controls readiness and owns the server lifecycle. + +```python +from threading import Event, Thread + +from apcore.observability import MetricsCollector, render_prometheus_metrics +from apcore_toolkit import create_prometheus_server + +metrics = MetricsCollector() +ready = Event() +with create_prometheus_server( + lambda: render_prometheus_metrics(metrics), is_ready=ready.is_set +) as server: + thread = Thread(target=server.serve_forever) + thread.start() + try: + ready.set() + # Run the application's main loop here. + finally: + server.shutdown() + thread.join() +``` + +The context closes the listening socket and waits for accepted requests to finish. +With a Core version that exposes `PrometheusExporter.export`, that bound method can +also serve as the rendering callback. + ### Scanning and Writing ```python diff --git a/toolkit/python/pyproject.toml b/toolkit/python/pyproject.toml index a67bf748..ca84514d 100644 --- a/toolkit/python/pyproject.toml +++ b/toolkit/python/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "apcore-toolkit" -version = "0.15.0" +version = "0.15.1a1" description = "Shared scanner, schema extraction, and output toolkit for apcore framework adapters" requires-python = ">=3.11" readme = "README.md" @@ -23,7 +23,7 @@ keywords = [ "toolkit", ] dependencies = [ - "apcore>=0.33.0", + "apcore>=0.33.0,<=1.0.0a1", "pydantic>=2.0", "PyYAML>=6.0", ] diff --git a/toolkit/python/src/apcore_toolkit/__init__.py b/toolkit/python/src/apcore_toolkit/__init__.py index 7b3e9b13..10362165 100644 --- a/toolkit/python/src/apcore_toolkit/__init__.py +++ b/toolkit/python/src/apcore_toolkit/__init__.py @@ -65,6 +65,7 @@ detect_effective_proxy_hazards, validate_effective_proxy_modules, ) +from apcore_toolkit.prometheus_server import create_prometheus_server from apcore_toolkit.tui_view_model import ( Cell, Column, @@ -161,6 +162,7 @@ "YAMLWriter", "annotations_to_dict", "clone_module", + "create_prometheus_server", "create_scanned_module", "deduplicate_ids", "deep_resolve_refs", diff --git a/toolkit/python/src/apcore_toolkit/output/types.py b/toolkit/python/src/apcore_toolkit/output/types.py index e1490cb6..b31c1ae0 100644 --- a/toolkit/python/src/apcore_toolkit/output/types.py +++ b/toolkit/python/src/apcore_toolkit/output/types.py @@ -37,7 +37,8 @@ class WriteResult: Attributes: module_id: The module that was written. path: Output file path (None for RegistryWriter). - verified: Whether verification passed (always True if verify=False). + verified: False on a write or verification failure. True for a successful + write, including when verification is disabled, or for a dry-run result. verification_error: Error message if verification failed. """ diff --git a/toolkit/python/src/apcore_toolkit/prometheus_server.py b/toolkit/python/src/apcore_toolkit/prometheus_server.py new file mode 100644 index 00000000..0e5c86fd --- /dev/null +++ b/toolkit/python/src/apcore_toolkit/prometheus_server.py @@ -0,0 +1,83 @@ +"""HTTP listener for application-owned Prometheus metrics.""" + +from __future__ import annotations + +import logging +from collections.abc import Callable +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +_logger = logging.getLogger(__name__) +_PROMETHEUS_CONTENT_TYPE = "text/plain; version=0.0.4; charset=utf-8" + + +class _PrometheusHTTPServer(ThreadingHTTPServer): + # The inherited server_close() waits for these request handlers to exit. + daemon_threads = False + + +def create_prometheus_server( + render_metrics: Callable[[], str], + *, + host: str = "127.0.0.1", + port: int = 9090, + metrics_path: str = "/metrics", + is_ready: Callable[[], bool] | None = None, +) -> ThreadingHTTPServer: + """Bind a Prometheus listener without starting its serving loop. + + Call ``serve_forever()`` to serve requests. From another thread, call + ``shutdown()`` to stop accepting work and ``server_close()`` to release + the socket and wait for accepted requests to finish. The scrape path + must be an absolute pathname distinct from the probe paths. + """ + + if ( + not metrics_path.startswith("/") + or metrics_path in {"/healthz", "/readyz"} + or any(character in "?#" or character.isspace() for character in metrics_path) + ): + raise ValueError("metrics_path must be an absolute pathname distinct from /healthz and /readyz") + + class Handler(BaseHTTPRequestHandler): + def parse_request(self) -> bool: + if not super().parse_request(): + return False + if self.command == "GET": + return True + self.send_response(405) + self.send_header("Allow", "GET") + self.send_header("Content-Length", "0") + self.end_headers() + return False + + def do_GET(self) -> None: # noqa: N802 + path = self.path.partition("?")[0] + if path == "/healthz": + self._respond(200, b"OK") + return + try: + if path == "/readyz": + ready = is_ready is not None and is_ready() + status, body, content_type = (200, b"OK", None) if ready else (503, b"Not ready", None) + elif path == metrics_path: + status, body, content_type = 200, render_metrics().encode("utf-8"), _PROMETHEUS_CONTENT_TYPE + else: + status, body, content_type = 404, b"", None + except Exception: + _logger.exception("Prometheus HTTP callback failed for %s", path) + status, body, content_type = 500, b"", None + self._respond(status, body, content_type) + + def _respond(self, status: int, body: bytes, content_type: str | None = None) -> None: + self.send_response(status) + if content_type is not None: + self.send_header("Content-Type", content_type) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + if body: + self.wfile.write(body) + + def log_message(self, format: str, *args: object) -> None: + _logger.debug(format, *args) + + return _PrometheusHTTPServer((host, port), Handler) diff --git a/toolkit/python/tests/test_conformance.py b/toolkit/python/tests/test_conformance.py index e101bf0c..4f55539e 100644 --- a/toolkit/python/tests/test_conformance.py +++ b/toolkit/python/tests/test_conformance.py @@ -2,10 +2,12 @@ from __future__ import annotations +import asyncio from unittest.mock import patch import pytest -from apcore import ModuleAnnotations, Registry +from apcore import Executor, ModuleAnnotations, ModuleError, Registry +from apcore.approval import AlwaysDenyHandler, AutoApproveHandler from apcore_toolkit.conformance import assert_annotations_preserved from apcore_toolkit.output.registry_writer import RegistryWriter @@ -63,3 +65,27 @@ def test_custom_fields(self) -> None: mod = _module(ModuleAnnotations(readonly=True)) with patch("apcore_toolkit.output.registry_writer.resolve_target", return_value=_handler): assert_annotations_preserved(RegistryWriter(), mod, Registry(), fields=("readonly",)) + + +def test_registered_annotation_controls_real_execution() -> None: + calls = 0 + + def handler() -> dict[str, bool]: + nonlocal calls + calls += 1 + return {"ok": True} + + module = _module(ModuleAnnotations(destructive=True, requires_approval=True)) + registry = Registry() + with patch("apcore_toolkit.output.registry_writer.resolve_target", return_value=handler): + assert_annotations_preserved(RegistryWriter(), module, registry) + + denied = Executor(registry=registry, approval_handler=AlwaysDenyHandler()) + with pytest.raises(ModuleError) as caught: + asyncio.run(denied.call_async(module.module_id, {})) + assert caught.value.code == "APPROVAL_DENIED" + assert calls == 0 + + approved = Executor(registry=registry, approval_handler=AutoApproveHandler()) + assert asyncio.run(approved.call_async(module.module_id, {})) == {"ok": True} + assert calls == 1 diff --git a/toolkit/python/tests/test_prometheus_server.py b/toolkit/python/tests/test_prometheus_server.py new file mode 100644 index 00000000..97ea48b6 --- /dev/null +++ b/toolkit/python/tests/test_prometheus_server.py @@ -0,0 +1,132 @@ +"""HTTP-level compatibility for the standalone Prometheus listener.""" + +from __future__ import annotations + +import socket +from collections.abc import Iterator +from concurrent.futures import ThreadPoolExecutor +from contextlib import contextmanager +from http.client import HTTPConnection +from http.server import HTTPServer +from threading import Event, Thread +from typing import Never + +import pytest +from apcore.observability import MetricsCollector, PrometheusExporter, UsageCollector + +from apcore_toolkit import create_prometheus_server + + +@contextmanager +def running(server: HTTPServer) -> Iterator[int]: + with server: + thread = Thread(target=server.serve_forever, kwargs={"poll_interval": 0.01}) + thread.start() + try: + yield server.server_port + finally: + server.shutdown() + thread.join(timeout=3) + + +def request(port: int, path: str, method: str = "GET") -> tuple[int, dict[str, str], bytes]: + client = HTTPConnection("127.0.0.1", port, timeout=3) + try: + client.request(method, path) + response = client.getresponse() + return response.status, dict(response.getheaders()), response.read() + finally: + client.close() + + +@pytest.mark.parametrize("populated", [False, True]) +def test_scrape_matches_legacy_http_response(populated: bool) -> None: + metrics = MetricsCollector() + usage = UsageCollector() + if populated: + metrics.increment("example_calls_total", {"site": "课堂"}) + metrics.observe("apcore_module_duration_seconds", {"module_id": "math.add"}, 0.01) + usage.record(module_id="math.add", caller_id="client", latency_ms=10.0, success=True) + exporter = PrometheusExporter(metrics, usage_collector=usage) + exporter.start(port=0, path="/scrape") + try: + assert exporter._server is not None + legacy_status, legacy_headers, legacy_body = request(exporter._server.server_port, "/scrape") + with running(create_prometheus_server(exporter.export, port=0, metrics_path="/scrape")) as port: + status, headers, body = request(port, "/scrape?format=prometheus") + assert status == legacy_status == 200 + assert body == legacy_body == exporter.export().encode("utf-8") + assert ( + headers["Content-Type"] == legacy_headers["Content-Type"] == "text/plain; version=0.0.4; charset=utf-8" + ) + assert headers["Content-Length"] == str(len(body)) + assert request(port, "/metrics")[0] == 404 + assert request(port, "/scrape/")[0] == 404 + finally: + exporter.stop() + + +def test_routes_readiness_and_rejects_non_get_requests() -> None: + ready = Event() + with running(create_prometheus_server(lambda: "example 1\n", port=0, is_ready=ready.is_set)) as port: + assert request(port, "/healthz?probe=1")[::2] == (200, b"OK") + assert request(port, "/readyz")[::2] == (503, b"Not ready") + assert request(port, "/missing")[0] == 404 + ready.set() + assert request(port, "/readyz?probe=1")[::2] == (200, b"OK") + assert request(port, "/metrics")[::2] == (200, b"example 1\n") + for method in ("HEAD", "POST", "OPTIONS", "PURGE"): + status, headers, body = request(port, "/metrics", method=method) + assert (status, headers["Allow"], body) == (405, "GET", b"") + + +@pytest.mark.parametrize("path", ["/healthz", "/readyz", "metrics", "/metrics?query", "/metrics#fragment"]) +def test_invalid_metrics_paths_are_rejected_before_binding(path: str) -> None: + with ( + pytest.raises(ValueError, match="absolute pathname"), + create_prometheus_server(lambda: "", host="invalid host", metrics_path=path), + ): + pass + + +def test_bind_failure_and_callback_errors_are_visible() -> None: + def fail() -> Never: + raise RuntimeError("internal diagnostic") + + with running(create_prometheus_server(fail, port=0, is_ready=fail)) as port: + with pytest.raises(OSError): + create_prometheus_server(fail, port=port) + assert request(port, "/metrics")[::2] == (500, b"") + assert request(port, "/readyz")[::2] == (500, b"") + assert request(port, "/healthz")[::2] == (200, b"OK") + + with running(create_prometheus_server(lambda: "", port=0)) as port: + assert request(port, "/readyz")[::2] == (503, b"Not ready") + + +def test_shutdown_drains_existing_scrape_and_refuses_new_connections() -> None: + entered = Event() + release = Event() + + def render() -> str: + entered.set() + if not release.wait(3): + raise TimeoutError("test did not release scrape") + return "example 1\n" + + server = create_prometheus_server(render, port=0) + with running(server) as port, ThreadPoolExecutor(max_workers=2) as pool: + response = pool.submit(request, port, "/metrics") + try: + assert entered.wait(3) + assert request(port, "/healthz")[0] == 200 + server.shutdown() + closed = pool.submit(server.server_close) + with pytest.raises(TimeoutError): + closed.result(timeout=0.05) + finally: + release.set() + assert response.result(timeout=3)[::2] == (200, b"example 1\n") + closed.result(timeout=3) + with pytest.raises(OSError), socket.create_connection(("127.0.0.1", port), timeout=3): + pass diff --git a/toolkit/rust/CHANGELOG.md b/toolkit/rust/CHANGELOG.md index 9100c927..4167b629 100644 --- a/toolkit/rust/CHANGELOG.md +++ b/toolkit/rust/CHANGELOG.md @@ -2,6 +2,12 @@ All notable changes to this project will be documented in this file. +## [0.15.1-alpha.1] - Unreleased + +### Added + +- Add a standalone Prometheus listener with liveness and readiness endpoints and isolate it from Core metrics rendering. + ## [0.15.0] - 2026-11-20 ### Added diff --git a/toolkit/rust/CLAUDE.md b/toolkit/rust/CLAUDE.md index 7c45bbb3..25779bc4 100644 --- a/toolkit/rust/CLAUDE.md +++ b/toolkit/rust/CLAUDE.md @@ -48,10 +48,10 @@ ### Async -- The crate itself has **no async-runtime dependency** — consumers bring their own - runtime (e.g. the README's quick-start example uses `#[tokio::main]`). `tokio` only - appears in `[dev-dependencies]`, scoped to `features = ["rt", "macros", "net", "time"]` - for driving async integration tests; it is not a runtime dependency of the crate. +- Consumers bring their own async runtime. Tokio is optional in library builds. + The `http-proxy` and `device-auth` features use its time primitives. The + `prometheus-server` feature also enables the runtime features needed to serve + HTTP in the consumer's Tokio runtime. - Traits with async methods: use **`async-trait`**. ### Logging diff --git a/toolkit/rust/Cargo.lock b/toolkit/rust/Cargo.lock index caa644bb..06a02db3 100644 --- a/toolkit/rust/Cargo.lock +++ b/toolkit/rust/Cargo.lock @@ -48,9 +48,9 @@ checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" [[package]] name = "apcore" -version = "0.33.0" +version = "1.0.0-alpha.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23f7c4d184641deb06d4140cfc058c8f73f6ea57b6e0948b37a9335cb0dc83af" +checksum = "2344e07dc37e34b8a93d8ff66d757587a2ca5adea5ca5cbd204af8d0ff836884" dependencies = [ "async-stream", "async-trait", @@ -76,13 +76,16 @@ dependencies = [ [[package]] name = "apcore-toolkit" -version = "0.15.0" +version = "0.15.1-alpha.1" dependencies = [ "apcore", "async-trait", "chrono", "futures", "futures-timer", + "http-body-util", + "hyper", + "hyper-util", "indexmap", "percent-encoding", "regex", @@ -740,6 +743,12 @@ version = "1.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + [[package]] name = "hyper" version = "1.9.0" @@ -754,6 +763,7 @@ dependencies = [ "http", "http-body", "httparse", + "httpdate", "itoa", "pin-project-lite", "smallvec", @@ -1006,9 +1016,9 @@ checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" [[package]] name = "js-sys" -version = "0.3.95" +version = "0.3.94" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2964e92d1d9dc3364cae4d718d93f227e3abb088e747d92e0395bfdedf1c12ca" +checksum = "2e04e2ef80ce82e13552136fabeef8a5ed1f985a96805761cbb9a2c34e7664d9" dependencies = [ "cfg-if", "futures-util", @@ -1035,7 +1045,6 @@ dependencies = [ "percent-encoding", "referencing", "regex-syntax", - "reqwest", "serde", "serde_json", "uuid-simd", @@ -1367,9 +1376,9 @@ checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" [[package]] name = "pkg-config" -version = "0.3.33" +version = "0.3.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e" +checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c" [[package]] name = "potential_utf" @@ -1506,9 +1515,7 @@ dependencies = [ "base64", "bytes", "encoding_rs", - "futures-channel", "futures-core", - "futures-util", "h2", "http", "http-body", @@ -2277,9 +2284,9 @@ dependencies = [ [[package]] name = "wasm-bindgen" -version = "0.2.118" +version = "0.2.117" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0bf938a0bacb0469e83c1e148908bd7d5a6010354cf4fb73279b7447422e3a89" +checksum = "0551fc1bb415591e3372d0bc4780db7e587d84e2a7e79da121051c5c4b89d0b0" dependencies = [ "cfg-if", "once_cell", @@ -2290,9 +2297,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-futures" -version = "0.4.68" +version = "0.4.67" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f371d383f2fb139252e0bfac3b81b265689bf45b6874af544ffa4c975ac1ebf8" +checksum = "03623de6905b7206edd0a75f69f747f134b7f0a2323392d664448bf2d3c5d87e" dependencies = [ "js-sys", "wasm-bindgen", @@ -2300,9 +2307,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro" -version = "0.2.118" +version = "0.2.117" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eeff24f84126c0ec2db7a449f0c2ec963c6a49efe0698c4242929da037ca28ed" +checksum = "7fbdf9a35adf44786aecd5ff89b4563a90325f9da0923236f6104e603c7e86be" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -2310,9 +2317,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.118" +version = "0.2.117" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d08065faf983b2b80a79fd87d8254c409281cf7de75fc4b773019824196c904" +checksum = "dca9693ef2bab6d4e6707234500350d8dad079eb508dca05530c85dc3a529ff2" dependencies = [ "bumpalo", "proc-macro2", @@ -2323,9 +2330,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-shared" -version = "0.2.118" +version = "0.2.117" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5fd04d9e306f1907bd13c6361b5c6bfc7b3b3c095ed3f8a9246390f8dbdee129" +checksum = "39129a682a6d2d841b6c429d0c51e5cb0ed1a03829d8b3d1e69a011e62cb3d3b" dependencies = [ "unicode-ident", ] @@ -2366,9 +2373,9 @@ dependencies = [ [[package]] name = "web-sys" -version = "0.3.95" +version = "0.3.94" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f2dfbb17949fa2088e5d39408c48368947b86f7834484e87b73de55bc14d97d" +checksum = "cd70027e39b12f0849461e08ffc50b9cd7688d942c1c8e3c7b22273236b4dd0a" dependencies = [ "js-sys", "wasm-bindgen", diff --git a/toolkit/rust/Cargo.toml b/toolkit/rust/Cargo.toml index 07de15bb..9352fae2 100644 --- a/toolkit/rust/Cargo.toml +++ b/toolkit/rust/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "apcore-toolkit" -version = "0.15.0" +version = "0.15.1-alpha.1" edition = "2021" description = "Shared scanner, schema extraction, and output toolkit for apcore framework adapters" license = "Apache-2.0" @@ -21,7 +21,7 @@ all-features = true rustdoc-args = ["--cfg", "docsrs"] [dependencies] -apcore = ">=0.33.0" +apcore = ">=0.33.0, <=1.0.0-alpha.1" serde = { version = "1", features = ["derive"] } # `preserve_order` is required for the toolkit's byte-equivalent tabular # formatters (csv / jsonl): object key order MUST match insertion order to @@ -41,6 +41,9 @@ walkdir = "2" # Runtime-independent, cancellable HTTP deadline watchdog for injected auth # transports. Poll interval SleepFn remains exclusively for protocol delays. futures-timer = { version = "3", optional = true } +http-body-util = { version = "0.1", optional = true } +hyper = { version = "1", features = ["http1", "server"], optional = true } +hyper-util = { version = "0.1", features = ["tokio"], optional = true } # Used by ai_enhancer for synchronous SLM API calls (always included). ureq = { version = "3", features = ["json"] } @@ -50,9 +53,8 @@ version = "0.12" features = ["json"] optional = true -# HTTP features use the async timer for cooperative proxy cancellation and -# the default RFC 8628 polling sleep. Only `time` is needed; reqwest already -# requires Tokio for HTTP I/O. +# The HTTP client features use Tokio time for cancellation and polling. +# The optional Prometheus listener also enables its server runtime features. [dependencies.tokio] version = "1" features = ["time"] @@ -72,6 +74,10 @@ default-features = false default = ["http-proxy", "device-auth"] http-proxy = ["dep:reqwest", "dep:tokio"] device-auth = ["dep:reqwest", "dep:tokio", "dep:futures-timer"] +prometheus-server = [ + "dep:http-body-util", "dep:hyper", "dep:hyper-util", "dep:tokio", + "tokio/macros", "tokio/net", "tokio/rt", "tokio/sync", +] [lints.clippy] # Match the project's pre-commit gate (Makefile + hooks/) — block warnings @@ -86,6 +92,6 @@ tempfile = "3" # Test-only: driving `reqwest`'s async client against a real (loopback) # HTTP server in the W2 regression test (HEAD/OPTIONS/TRACE support in # HTTPProxyRegistryWriter) requires a real async I/O reactor — `futures`' -# bare `block_on` executor has none. Not a runtime dependency of the -# crate itself. -tokio = { version = "1", features = ["rt", "macros", "net", "time"] } +# bare `block_on` executor has none. The Prometheus server tests open and +# read real HTTP connections using the same runtime. +tokio = { version = "1", features = ["rt", "macros", "net", "time", "io-util"] } diff --git a/toolkit/rust/README.md b/toolkit/rust/README.md index 7147d864..1ef2e836 100644 --- a/toolkit/rust/README.md +++ b/toolkit/rust/README.md @@ -321,6 +321,38 @@ print!("{}", format_csv(&rows, true)); See `apcore-toolkit/docs/features/formatting.md` § Tabular Formats for the full contract and `apcore-toolkit/conformance/fixtures/format_csv.json` / `format_jsonl.json` for the shared cross-SDK test corpus. +### Prometheus HTTP listener + +Enable the `prometheus-server` feature to serve Core metrics and health probes. +Pass a renderer backed by your application's existing collectors. The bound +handle reports its address and provides an async `close()` that stops accepting +connections before draining in-flight responses. + +```rust +use std::{io, net::SocketAddr}; + +use apcore::{render_prometheus_metrics, MetricsCollector, UsageCollector}; +use apcore_toolkit::{PrometheusServer, PrometheusServerHandle}; + +async fn listen_for_scrapes( + address: SocketAddr, + metrics: MetricsCollector, + usage: UsageCollector, +) -> io::Result { + PrometheusServer::new(move || render_prometheus_metrics(&metrics, Some(&usage))) + .with_readiness(|| true) + .listen(address) + .await +} +``` + +A GET serves `/metrics` by default, `/healthz` for liveness, and `/readyz` for +the supplied readiness callback. Set a different scrape path with +`with_metrics_path`. Query parameters do not affect endpoint selection. +Readiness defaults to false. Older Core versions can supply a callback that +invokes `PrometheusExporter::export()` on their existing exporter, with the +Toolkit handle owning the listener. + ## Requirements - See `Cargo.toml` for full dependency list @@ -330,6 +362,7 @@ See `apcore-toolkit/docs/features/formatting.md` § Tabular Formats for the full | Feature | Description | |---------|-------------| | `http-proxy` | **Enabled by default.** Provides `HTTPProxyRegistryWriter` (adds the `reqwest` dependency). Disable with `default-features = false` for a leaner build. | +| `prometheus-server` | **Opt-in.** Provides a Tokio HTTP listener for Prometheus metrics and health probes. | ## Documentation diff --git a/toolkit/rust/src/lib.rs b/toolkit/rust/src/lib.rs index f5f47d77..53b04b20 100644 --- a/toolkit/rust/src/lib.rs +++ b/toolkit/rust/src/lib.rs @@ -58,6 +58,8 @@ mod openapi_parameters; mod openapi_proxy; pub mod openapi_scanner; pub mod output; +#[cfg(feature = "prometheus-server")] +pub mod prometheus_server; pub mod resolve_target; pub mod scanner; pub mod schema_utils; @@ -98,6 +100,8 @@ pub use output::verifiers::{ }; pub use output::yaml_writer::YAMLWriter; pub use output::{get_writer, InvalidFormatError, OutputFormat}; +#[cfg(feature = "prometheus-server")] +pub use prometheus_server::{PrometheusServer, PrometheusServerHandle}; pub use resolve_target::{resolve_target, ResolveTargetError, ResolvedTarget}; pub use scanner::{deduplicate_ids, filter_modules, infer_annotations_from_method, BaseScanner}; pub use schema_utils::enrich_schema_descriptions; diff --git a/toolkit/rust/src/prometheus_server.rs b/toolkit/rust/src/prometheus_server.rs new file mode 100644 index 00000000..a8715877 --- /dev/null +++ b/toolkit/rust/src/prometheus_server.rs @@ -0,0 +1,218 @@ +//! HTTP transport for a host-provided Prometheus text renderer. + +use std::convert::Infallible; +use std::io; +use std::net::SocketAddr; +use std::sync::Arc; +use std::time::Duration; + +use http_body_util::Full; +use hyper::body::{Bytes, Incoming}; +use hyper::header::{HeaderValue, ALLOW, CONTENT_TYPE}; +use hyper::server::conn::http1; +use hyper::service::service_fn; +use hyper::{Method, Request, Response, StatusCode}; +use hyper_util::rt::TokioIo; +use tokio::net::{TcpListener, TcpStream}; +use tokio::sync::oneshot; +use tokio::task::{JoinHandle, JoinSet}; +use tokio::time::timeout; + +const REQUEST_TIMEOUT: Duration = Duration::from_secs(10); +const MAX_CONNECTIONS: usize = 64; +const MAX_REQUEST_BUFFER: usize = 8192; +const METRICS_CONTENT_TYPE: &str = "text/plain; version=0.0.4; charset=utf-8"; +const TEXT_CONTENT_TYPE: &str = "text/plain; charset=utf-8"; + +/// Configures a metrics listener with liveness and readiness probes. +pub struct PrometheusServer { + render_metrics: Box String + Send + Sync>, + is_ready: Option bool + Send + Sync>>, + metrics_path: String, +} + +impl PrometheusServer { + /// Create a listener configuration. The renderer is called for each scrape. + pub fn new(render_metrics: impl Fn() -> String + Send + Sync + 'static) -> Self { + Self { + render_metrics: Box::new(render_metrics), + is_ready: None, + metrics_path: "/metrics".into(), + } + } + + /// Set the exact scrape path. Query parameters on requests are ignored. + #[must_use] + pub fn with_metrics_path(mut self, path: impl Into) -> Self { + self.metrics_path = path.into(); + self + } + + /// Check the host's current readiness for each probe. The default is false. + #[must_use] + pub fn with_readiness(mut self, is_ready: impl Fn() -> bool + Send + Sync + 'static) -> Self { + self.is_ready = Some(Box::new(is_ready)); + self + } + + /// Bind the given address and start serving requests in the current Tokio runtime. + /// + /// # Errors + /// Returns an error if the path is invalid or reserved, or the address cannot be bound. + pub async fn listen(self, address: SocketAddr) -> io::Result { + let valid_path = self + .metrics_path + .parse::() + .is_ok_and(|uri| uri.path() == self.metrics_path && uri.path().starts_with('/')); + if !valid_path || matches!(self.metrics_path.as_str(), "/healthz" | "/readyz") { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "metrics path must be an absolute path other than /healthz or /readyz", + )); + } + let listener = TcpListener::bind(address).await?; + let address = listener.local_addr()?; + let (shutdown, receiver) = oneshot::channel(); + let worker = tokio::spawn(run_listener(listener, Arc::new(self), receiver)); + Ok(PrometheusServerHandle { + address, + shutdown: Some(shutdown), + worker: Some(worker), + }) + } + + fn response(&self, request: Request) -> Response> { + if request.method() != Method::GET { + let mut response = response(StatusCode::METHOD_NOT_ALLOWED, TEXT_CONTENT_TYPE, ""); + response + .headers_mut() + .insert(ALLOW, HeaderValue::from_static("GET")); + return response; + } + + match request.uri().path() { + path if path == self.metrics_path => response( + StatusCode::OK, + METRICS_CONTENT_TYPE, + (self.render_metrics)(), + ), + "/healthz" => response(StatusCode::OK, TEXT_CONTENT_TYPE, "OK\n"), + "/readyz" if self.is_ready.as_ref().is_some_and(|ready| ready()) => { + response(StatusCode::OK, TEXT_CONTENT_TYPE, "OK\n") + } + "/readyz" => response( + StatusCode::SERVICE_UNAVAILABLE, + TEXT_CONTENT_TYPE, + "Not ready\n", + ), + _ => response(StatusCode::NOT_FOUND, TEXT_CONTENT_TYPE, "Not Found\n"), + } + } +} + +/// Owns the lifecycle of a bound Prometheus listener. +#[derive(Debug)] +pub struct PrometheusServerHandle { + address: SocketAddr, + shutdown: Option>, + worker: Option>>, +} + +impl PrometheusServerHandle { + /// Return the actual bound address, including a port selected by the OS. + #[must_use] + pub fn local_addr(&self) -> SocketAddr { + self.address + } + + /// Stop accepting and wait up to ten seconds for open connections to drain. + /// + /// A repeated close returns successfully. Dropping this handle signals the + /// same shutdown, while `close` waits for it to finish. + /// + /// # Errors + /// Returns any listener error that ended the server. + pub async fn close(&mut self) -> io::Result<()> { + self.signal_shutdown(); + let Some(worker) = self.worker.as_mut() else { + return Ok(()); + }; + let result = worker.await; + self.worker = None; + result.map_err(io::Error::other)? + } + + fn signal_shutdown(&mut self) { + if let Some(shutdown) = self.shutdown.take() { + let _ = shutdown.send(()); + } + } +} + +impl Drop for PrometheusServerHandle { + fn drop(&mut self) { + self.signal_shutdown(); + } +} + +async fn run_listener( + listener: TcpListener, + server: Arc, + mut shutdown: oneshot::Receiver<()>, +) -> io::Result<()> { + let mut connections = JoinSet::new(); + let result = loop { + tokio::select! { + biased; + _ = &mut shutdown => break Ok(()), + Some(_) = connections.join_next() => {}, + accepted = listener.accept(), if connections.len() < MAX_CONNECTIONS => { + match accepted { + Ok((stream, _)) => { + connections.spawn(serve_connection(stream, Arc::clone(&server))); + } + Err(error) => break Err(error), + } + } + } + }; + + drop(listener); + if timeout(REQUEST_TIMEOUT, async { + while connections.join_next().await.is_some() {} + }) + .await + .is_err() + { + connections.shutdown().await; + } + result +} + +async fn serve_connection(stream: TcpStream, server: Arc) { + let service = + service_fn(|request| std::future::ready(Ok::<_, Infallible>(server.response(request)))); + let connection = http1::Builder::new() + .keep_alive(false) + .header_read_timeout(None) + .max_buf_size(MAX_REQUEST_BUFFER) + .serve_connection(TokioIo::new(stream), service); + match timeout(REQUEST_TIMEOUT, connection).await { + Ok(Ok(())) => {} + Ok(Err(error)) => tracing::debug!(%error, "Prometheus connection closed with an error"), + Err(_) => tracing::debug!("Prometheus connection timed out"), + } +} + +fn response( + status: StatusCode, + content_type: &'static str, + body: impl Into, +) -> Response> { + let mut response = Response::new(Full::new(body.into())); + *response.status_mut() = status; + response + .headers_mut() + .insert(CONTENT_TYPE, HeaderValue::from_static(content_type)); + response +} diff --git a/toolkit/rust/tests/annotation_conformance.rs b/toolkit/rust/tests/annotation_conformance.rs index a4b398dd..fcb51b02 100644 --- a/toolkit/rust/tests/annotation_conformance.rs +++ b/toolkit/rust/tests/annotation_conformance.rs @@ -3,15 +3,17 @@ //! round-trip that approval/ACL gating (which keys on `requires_approval`) //! depends on — a real `Registry`, not a mock. +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Arc; + use apcore::module::ModuleAnnotations; -use apcore::Registry; +use apcore::{AlwaysDenyHandler, AutoApproveHandler, Config, ErrorCode, Executor, Registry}; use apcore_toolkit::assert_annotations_preserved; use apcore_toolkit::types::ScannedModule; -use apcore_toolkit::RegistryWriter; +use apcore_toolkit::{HandlerFn, RegistryWriter}; use serde_json::json; -#[test] -fn base_writer_preserves_annotations() { +fn with_required_approval() -> ScannedModule { let mut module = ScannedModule::new( "orders.delete_order".into(), "Delete an order".into(), @@ -26,6 +28,43 @@ fn base_writer_preserves_annotations() { ..Default::default() }); + module +} + +#[test] +fn base_writer_preserves_annotations() { let registry = Registry::new(); - assert_annotations_preserved(&RegistryWriter::new(), &module, ®istry); + assert_annotations_preserved(&RegistryWriter::new(), &with_required_approval(), ®istry); +} + +#[tokio::test] +async fn toolkit_registered_annotation_controls_real_execution() { + let module = with_required_approval(); + let registry = Arc::new(Registry::new()); + let calls = Arc::new(AtomicUsize::new(0)); + let counter = Arc::clone(&calls); + let handler: HandlerFn = Arc::new(move |_, _| { + counter.fetch_add(1, Ordering::SeqCst); + Box::pin(async { Ok(json!({"ok": true})) }) + }); + let writer = + RegistryWriter::with_handler_factory(Arc::new(move |_| Some(Arc::clone(&handler)))); + assert_annotations_preserved(&writer, &module, ®istry); + + let mut executor = Executor::new(registry, Config::default()); + executor.set_approval_handler(Box::new(AlwaysDenyHandler)); + let denied = executor + .call(&module.module_id, json!({}), None, None) + .await + .unwrap_err(); + assert_eq!(denied.code, ErrorCode::ApprovalDenied); + assert_eq!(calls.load(Ordering::SeqCst), 0); + + executor.set_approval_handler(Box::new(AutoApproveHandler)); + let approved = executor + .call(&module.module_id, json!({}), None, None) + .await + .unwrap(); + assert_eq!(approved, json!({"ok": true})); + assert_eq!(calls.load(Ordering::SeqCst), 1); } diff --git a/toolkit/rust/tests/prometheus_server.rs b/toolkit/rust/tests/prometheus_server.rs new file mode 100644 index 00000000..5fad81d5 --- /dev/null +++ b/toolkit/rust/tests/prometheus_server.rs @@ -0,0 +1,145 @@ +#![cfg(feature = "prometheus-server")] + +use apcore::{MetricsCollector, PrometheusExporter, UsageCollector}; +use apcore_toolkit::PrometheusServer; +use std::io::ErrorKind; +use std::net::{IpAddr, Ipv4Addr, SocketAddr}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Arc; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::TcpStream; +use tokio::time::{timeout, Duration}; + +const LOOPBACK: SocketAddr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0); + +async fn request(address: SocketAddr, method: &str, path: &str) -> String { + timeout(Duration::from_secs(5), async { + let mut connection = TcpStream::connect(address).await.unwrap(); + connection + .write_all(format!("{method} {path} HTTP/1.1\r\nHost: localhost\r\n\r\n").as_bytes()) + .await + .unwrap(); + let mut response = String::new(); + connection.read_to_string(&mut response).await.unwrap(); + response + }) + .await + .unwrap() +} + +fn split_response(response: &str) -> (&str, &str) { + response.split_once("\r\n\r\n").unwrap() +} + +#[tokio::test] +async fn serves_the_legacy_metrics_text_with_routes_and_live_readiness() { + let metrics = MetricsCollector::new(); + let usage = UsageCollector::new(); + let legacy = PrometheusExporter::new(metrics.clone()).with_usage_collector(usage.clone()); + legacy.start(0, "/metrics").await.unwrap(); + let legacy_address = SocketAddr::from(([127, 0, 0, 1], legacy.local_addr().unwrap().port())); + + let ready = Arc::new(AtomicBool::new(false)); + let mut server = PrometheusServer::new({ + let snapshot = legacy.clone(); + move || snapshot.export() + }) + .with_metrics_path("/custom") + .with_readiness({ + let ready = Arc::clone(&ready); + move || ready.load(Ordering::Relaxed) + }) + .listen(LOOPBACK) + .await + .unwrap(); + let address = server.local_addr(); + + let cold = request(address, "GET", "/custom?collect[]=go").await; + let (headers, body) = split_response(&cold); + assert!(headers.starts_with("HTTP/1.1 200 OK")); + assert!(headers + .to_ascii_lowercase() + .contains("content-type: text/plain; version=0.0.4; charset=utf-8")); + let old = request(legacy_address, "GET", "/metrics").await; + assert_eq!(body, split_response(&old).1); + for name in [ + "apcore_module_calls_total", + "apcore_module_errors_total", + "apcore_module_duration_seconds", + ] { + assert!(body.contains(name)); + } + + metrics.increment_calls("sample.metric", "success"); + usage.record("sample.metric", Some("sample.caller"), 1.0, true); + let populated = request(address, "GET", "/custom").await; + let old = request(legacy_address, "GET", "/metrics").await; + let body = split_response(&populated).1; + assert_eq!(body, split_response(&old).1); + assert!(body.contains("apcore_usage_")); + + assert!(request(address, "GET", "/metrics").await.contains("404")); + let rejected = request(address, "POST", "/custom").await; + assert!(rejected.starts_with("HTTP/1.1 405")); + assert!(rejected.to_ascii_lowercase().contains("allow: get")); + assert!(request(address, "GET", "/healthz?probe") + .await + .starts_with("HTTP/1.1 200")); + assert!(request(address, "GET", "/readyz") + .await + .starts_with("HTTP/1.1 503")); + ready.store(true, Ordering::Relaxed); + assert!(request(address, "GET", "/readyz?probe") + .await + .starts_with("HTTP/1.1 200")); + + let bind_error = PrometheusServer::new(String::new) + .listen(address) + .await + .unwrap_err(); + assert_eq!(bind_error.kind(), ErrorKind::AddrInUse); + server.close().await.unwrap(); + server.close().await.unwrap(); + assert_eq!( + TcpStream::connect(address).await.unwrap_err().kind(), + ErrorKind::ConnectionRefused + ); + legacy.shutdown(); +} + +#[tokio::test] +async fn close_stops_accepting_and_drains_an_in_flight_response() { + const LENGTH: usize = 8 * 1024 * 1024; + let mut server = PrometheusServer::new(|| "x".repeat(LENGTH)) + .listen(LOOPBACK) + .await + .unwrap(); + let address = server.local_addr(); + let mut connection = TcpStream::connect(address).await.unwrap(); + connection + .write_all(b"GET /metrics HTTP/1.1\r\nHost: localhost\r\n\r\n") + .await + .unwrap(); + + timeout(Duration::from_secs(5), async { + let mut response = Vec::with_capacity(4096); + connection.read_buf(&mut response).await.unwrap(); + assert!(!response.is_empty()); + let close = tokio::spawn(async move { server.close().await.unwrap() }); + loop { + match TcpStream::connect(address).await { + Err(error) if error.kind() == ErrorKind::ConnectionRefused => break, + Ok(_) => tokio::task::yield_now().await, + Err(error) => panic!("unexpected connect error: {error}"), + } + } + connection.read_to_end(&mut response).await.unwrap(); + let response = String::from_utf8(response).unwrap(); + let (headers, body) = split_response(&response); + assert!(headers.starts_with("HTTP/1.1 200")); + assert_eq!(body.len(), LENGTH); + close.await.unwrap(); + }) + .await + .unwrap(); +} diff --git a/toolkit/typescript/CHANGELOG.md b/toolkit/typescript/CHANGELOG.md index 2caf656f..0ce86924 100644 --- a/toolkit/typescript/CHANGELOG.md +++ b/toolkit/typescript/CHANGELOG.md @@ -2,6 +2,12 @@ All notable changes to this project will be documented in this file. +## [0.15.1-alpha.1] - Unreleased + +### Added + +- Add a standalone Prometheus listener with liveness and readiness endpoints and isolate it from Core metrics rendering. + ## [0.15.0] - Unreleased ### Added diff --git a/toolkit/typescript/README.md b/toolkit/typescript/README.md index 82125f70..8dc26918 100644 --- a/toolkit/typescript/README.md +++ b/toolkit/typescript/README.md @@ -24,6 +24,40 @@ npm install apcore-toolkit ## Usage +### Prometheus HTTP server + +The Node entry point can serve Core's existing metrics and usage collectors on +`/metrics`, with liveness on `/healthz` and application readiness on `/readyz`. +Set `metricsPath` to an absolute pathname. `/healthz` and `/readyz` are reserved +for probes. Routes accept GET requests and match the +pathname, ignoring query parameters. Readiness returns 503 until the supplied +callback reports ready. + +```typescript +import { once } from 'node:events'; +import { MetricsCollector, PrometheusExporter, UsageCollector } from 'apcore-js'; +import { createPrometheusServer } from 'apcore-toolkit'; + +const metrics = new MetricsCollector(); +const usage = new UsageCollector(); +const exporter = new PrometheusExporter({ collector: metrics, usageCollector: usage }); +let ready = false; +const server = createPrometheusServer({ + renderMetrics: () => exporter.export(), + isReady: () => ready, +}); +const listening = once(server, 'listening'); +server.listen(9090, '127.0.0.1'); +await listening; +ready = true; +process.once('SIGTERM', () => { server.close(); }); +``` + +Use the same collector instances that your APCore middleware writes to. +The returned Node server lets the application choose the bind address, handle +listen errors and wait for active responses to finish on shutdown. The legacy +Core exporter and its lifecycle API are available. + ### ScannedModule The canonical representation of a scanned endpoint: diff --git a/toolkit/typescript/package.json b/toolkit/typescript/package.json index 6525a23e..b6e81a68 100644 --- a/toolkit/typescript/package.json +++ b/toolkit/typescript/package.json @@ -1,6 +1,6 @@ { "name": "apcore-toolkit", - "version": "0.15.0", + "version": "0.15.1-alpha.1", "description": "Shared scanner, schema extraction, and output toolkit for apcore framework adapters", "type": "module", "main": "./dist/index.js", @@ -57,7 +57,7 @@ }, "dependencies": { "ajv": "^8.17.0", - "apcore-js": ">=0.33.0", + "apcore-js": ">=0.33.0 <1.0.0 || 1.0.0-alpha.1", "js-yaml": "^4.3.2" }, "peerDependencies": { diff --git a/toolkit/typescript/pnpm-lock.yaml b/toolkit/typescript/pnpm-lock.yaml index d1d95b69..8b711c8f 100644 --- a/toolkit/typescript/pnpm-lock.yaml +++ b/toolkit/typescript/pnpm-lock.yaml @@ -15,7 +15,7 @@ importers: specifier: ^8.17.0 version: 8.20.0 apcore-js: - specifier: '>=0.33.0' + specifier: '>=0.33.0 <1.0.0 || 1.0.0-alpha.1' version: 0.33.0 js-yaml: specifier: ^4.3.2 diff --git a/toolkit/typescript/src/index.ts b/toolkit/typescript/src/index.ts index f1e01e52..91e55302 100644 --- a/toolkit/typescript/src/index.ts +++ b/toolkit/typescript/src/index.ts @@ -259,3 +259,6 @@ import type { ModuleAnnotations } from 'apcore-js'; export function inferAnnotationsFromMethod(method: string): ModuleAnnotations { return _BaseScanner.inferAnnotationsFromMethod(method); } + +export { createPrometheusServer } from './prometheus-server.js'; +export type { PrometheusServerOptions } from './prometheus-server.js'; diff --git a/toolkit/typescript/src/output/http-proxy-writer.ts b/toolkit/typescript/src/output/http-proxy-writer.ts index 6ca9a53f..b8a79566 100644 --- a/toolkit/typescript/src/output/http-proxy-writer.ts +++ b/toolkit/typescript/src/output/http-proxy-writer.ts @@ -301,6 +301,11 @@ export class HTTPProxyRegistryWriter { private buildFunctionModule(mod: ScannedModule): FunctionModule { const effectiveInputs = readOpenApiProxyInputs(mod); const { httpMethod, urlPath, openApiPath } = getHttpFields(mod, effectiveInputs !== undefined); + // OpenAPI makes operation descriptions optional. Supply valid registry + // metadata for an undocumented operation without changing its scanned data. + const description = (mod.description ?? '').trim() + ? mod.description + : `${httpMethod.toUpperCase()} ${urlPath}`.replace(/\s+/g, ' ').slice(0, 200); const pathParams = openApiPath?.parameterNames ?? extractPathParamNames(urlPath); const queryNames = new Set(effectiveInputs?.query); const baseUrl = this.baseUrl; @@ -456,7 +461,7 @@ export class HTTPProxyRegistryWriter { moduleId: mod.moduleId, inputSchema: jsonSchemaToTypeBox(objectSchemaForTypeBox(mod.inputSchema)), outputSchema: jsonSchemaToTypeBox(objectSchemaForTypeBox(mod.outputSchema)), - description: mod.description, + description, documentation: mod.documentation, tags: mod.tags.length > 0 ? [...mod.tags] : null, version: mod.version, diff --git a/toolkit/typescript/src/prometheus-server.ts b/toolkit/typescript/src/prometheus-server.ts new file mode 100644 index 00000000..1a62a4ea --- /dev/null +++ b/toolkit/typescript/src/prometheus-server.ts @@ -0,0 +1,55 @@ +import { createServer, type Server } from 'node:http'; + +export interface PrometheusServerOptions { + /** Return the current Prometheus exposition from the application's collectors. */ + renderMetrics: () => string; + /** Exact absolute scrape pathname, defaulting to /metrics. Probe paths are reserved. */ + metricsPath?: string; + /** Report readiness on each request, defaulting to false. */ + isReady?: () => boolean; +} + +/** Create a Node HTTP server for metrics, liveness and readiness. The caller owns listen and close. */ +export function createPrometheusServer({ + renderMetrics, + metricsPath = '/metrics', + isReady = () => false, +}: PrometheusServerOptions): Server { + if (!metricsPath.startsWith('/') || /[?#\s]/.test(metricsPath) || + metricsPath === '/healthz' || metricsPath === '/readyz') { + throw new RangeError('metricsPath must be an absolute pathname distinct from /healthz and /readyz'); + } + return createServer((request, response) => { + if (request.method !== 'GET') { + response.writeHead(405, { Allow: 'GET' }).end(); + return; + } + + try { + // For origin-form request targets, keep the configured pathname exact + // while ignoring Prometheus scrape query parameters. + const pathname = request.url?.split('?', 1)[0]; + switch (pathname) { + case '/healthz': + response.writeHead(200).end('OK'); + break; + case '/readyz': + if (isReady()) response.writeHead(200).end('OK'); + else response.writeHead(503).end('Not ready'); + break; + case metricsPath: { + const body = Buffer.from(renderMetrics(), 'utf8'); + response.writeHead(200, { + 'Content-Type': 'text/plain; version=0.0.4; charset=utf-8', + 'Content-Length': String(body.length), + }).end(body); + break; + } + default: + response.writeHead(404).end(); + } + } catch { + response.writeHead(500).end(); + } + }); +} diff --git a/toolkit/typescript/tests/conformance.test.ts b/toolkit/typescript/tests/conformance.test.ts index 8ef42290..c9e3f37f 100644 --- a/toolkit/typescript/tests/conformance.test.ts +++ b/toolkit/typescript/tests/conformance.test.ts @@ -1,5 +1,14 @@ import { describe, it, expect, vi } from 'vitest'; -import { Registry, FunctionModule, createAnnotations } from 'apcore-js'; +import { + AlwaysDenyHandler, + AutoApproveHandler, + createAnnotations, + Executor, + FunctionModule, + jsonSchemaToTypeBox, + Registry, +} from 'apcore-js'; +import { resolveTarget } from '../src/resolve-target.js'; import { createScannedModule } from '../src/types.js'; vi.mock('../src/resolve-target.js', () => ({ @@ -31,9 +40,15 @@ describe('assertAnnotationsPreserved', () => { const droppingWriter = { async write(mods: ReturnType[], registry: Registry) { for (const m of mods) { - registry.register( + await registry.register( m.moduleId, - new FunctionModule({ moduleId: m.moduleId, description: m.description, execute: async () => ({}) }), + new FunctionModule({ + moduleId: m.moduleId, + description: m.description, + inputSchema: jsonSchemaToTypeBox(m.inputSchema), + outputSchema: jsonSchemaToTypeBox(m.outputSchema), + execute: async () => ({}), + }), ); } return []; @@ -52,3 +67,23 @@ describe('assertAnnotationsPreserved', () => { ); }); }); + + +it('enforces a Toolkit-registered approval annotation through the real Executor', async () => { + const registry = new Registry(); + const handler = vi.fn(() => ({ result: 'ok' })); + vi.mocked(resolveTarget).mockResolvedValueOnce(handler); + const module = createScannedModule({ + ...BASE, + annotations: createAnnotations({ destructive: true, requiresApproval: true }), + }); + await assertAnnotationsPreserved(new RegistryWriter(), module, registry); + + const denied = new Executor({ registry, approvalHandler: new AlwaysDenyHandler() }); + await expect(denied.call(module.moduleId, {})).rejects.toMatchObject({ code: 'APPROVAL_DENIED' }); + expect(handler).not.toHaveBeenCalled(); + + const approved = new Executor({ registry, approvalHandler: new AutoApproveHandler() }); + await expect(approved.call(module.moduleId, {})).resolves.toEqual({ result: 'ok' }); + expect(handler).toHaveBeenCalledTimes(1); +}); diff --git a/toolkit/typescript/tests/openapi-effective-parameters.test.ts b/toolkit/typescript/tests/openapi-effective-parameters.test.ts index 96982ed3..de1d07b2 100644 --- a/toolkit/typescript/tests/openapi-effective-parameters.test.ts +++ b/toolkit/typescript/tests/openapi-effective-parameters.test.ts @@ -115,7 +115,9 @@ describe('effective OpenAPI parameters', () => { const registry = new Registry(); const writer = new HTTPProxyRegistryWriter({ baseUrl: 'https://example.invalid' }); - expect(writer.write([module], registry)[0].verified).toBe(true); + const [registration] = writer.write([module], registry); + expect(registration.verified, registration.verificationError ?? undefined).toBe(true); + expect(registry.get(module.moduleId)?.description).toBe('GET /boolean'); const inputSchema = registry.get(module.moduleId)?.inputSchema; expect(inputSchema).toBeDefined(); if (inputSchema === undefined) throw new Error('Expected the HTTP proxy input schema'); diff --git a/toolkit/typescript/tests/prometheus-server.test.ts b/toolkit/typescript/tests/prometheus-server.test.ts new file mode 100644 index 00000000..856d1e5d --- /dev/null +++ b/toolkit/typescript/tests/prometheus-server.test.ts @@ -0,0 +1,203 @@ +import { MetricsCollector, PrometheusExporter, UsageCollector } from 'apcore-js'; +import { once } from 'node:events'; +import { request as httpRequest } from 'node:http'; +import type { IncomingMessage, Server, ServerResponse } from 'node:http'; +import { describe, expect, it, vi } from 'vitest'; +import { createPrometheusServer } from '../src/index.js'; + +function request(server: Server, url: string, method = 'GET') { + const response = { writeHead: vi.fn().mockReturnThis(), end: vi.fn() }; + server.emit('request', { url, method } as IncomingMessage, response as unknown as ServerResponse); + return response; +} + +function serverPort(server: Server): number { + const address = server.address(); + if (!address || typeof address === 'string') throw new Error('No bound TCP address'); + return address.port; +} + +async function listen(server: Server, port = 0): Promise { + const started = once(server, 'listening'); + server.listen(port, '127.0.0.1'); + await started; + return serverPort(server); +} + +function close(server: Server): Promise { + return new Promise((resolve, reject) => { + server.close(error => error ? reject(error) : resolve()); + }); +} + +function scrape(port: number, path: string, method = 'GET') { + return new Promise<{ status: number | undefined; headers: IncomingMessage['headers']; body: Buffer }>((resolve, reject) => { + const client = httpRequest({ host: '127.0.0.1', port, path, method, agent: false }, (response) => { + const chunks: Buffer[] = []; + response.on('data', (chunk: Buffer) => chunks.push(chunk)); + response.once('error', reject); + response.once('end', () => resolve({ + status: response.statusCode, + headers: response.headers, + body: Buffer.concat(chunks), + })); + }); + client.once('error', reject); + client.end(); + }); +} + +describe('createPrometheusServer', () => { + it.each(['/healthz', '/readyz', 'metrics', '/metrics?which=all', '/metrics#fragment'])( + 'rejects reserved or invalid scrape pathname %s before listening', + metricsPath => { + expect(() => createPrometheusServer({ metricsPath, renderMetrics: () => '' })) + .toThrow(RangeError); + }, + ); + + it('serves the exact legacy collector output for a custom path', () => { + const collector = new MetricsCollector(); + const usageCollector = new UsageCollector(); + collector.increment('apcore_test_calls_total', {}, 2); + usageCollector.record('learning.review', 12, false); + const exporter = new PrometheusExporter({ collector, usageCollector }); + const server = createPrometheusServer({ renderMetrics: () => exporter.export(), metricsPath: '/scrape' }); + + const reply = request(server, '/scrape'); + const body = Buffer.from(exporter.export(), 'utf8'); + expect(body.toString()).toContain('apcore_usage_calls_total'); + expect(reply.writeHead).toHaveBeenCalledWith(200, { + 'Content-Type': 'text/plain; version=0.0.4; charset=utf-8', + 'Content-Length': String(body.length), + }); + expect(reply.end).toHaveBeenCalledWith(body); + expect(request(server, '/metrics').writeHead).toHaveBeenCalledWith(404); + }); + + it('keeps liveness and readiness separate from metric rendering', () => { + const renderMetrics = vi.fn(() => ''); + let ready = false; + const server = createPrometheusServer({ renderMetrics, isReady: () => ready }); + + expect(request(server, '/healthz').writeHead).toHaveBeenCalledWith(200); + expect(request(server, '/readyz').writeHead).toHaveBeenCalledWith(503); + ready = true; + expect(request(server, '/readyz').writeHead).toHaveBeenCalledWith(200); + expect(request(server, '/metrics', 'POST').writeHead).toHaveBeenCalledWith(405, { Allow: 'GET' }); + expect(renderMetrics).not.toHaveBeenCalled(); + }); + + it('returns an empty 500 on render failure and serves a subsequent scrape', () => { + const renderMetrics = vi.fn(() => 'example 1\n').mockImplementationOnce(() => { + throw new Error('collector failed'); + }); + const server = createPrometheusServer({ renderMetrics }); + + const failed = request(server, '/metrics'); + expect(failed.writeHead).toHaveBeenCalledWith(500); + expect(failed.end).toHaveBeenCalledWith(); + expect(request(server, '/metrics').end).toHaveBeenCalledWith(Buffer.from('example 1\n')); + }); + + it('routes by pathname, retaining the custom path and probe method contracts', async () => { + let ready = false; + const server = createPrometheusServer({ + metricsPath: '/private/scrape', + renderMetrics: () => 'apcore_requests_total{route="測試"} 1\n', + isReady: () => ready, + }); + const port = await listen(server); + try { + const reply = await scrape(port, '/private/scrape?source=prometheus'); + expect(reply.status).toBe(200); + expect(reply.headers['content-type']).toBe('text/plain; version=0.0.4; charset=utf-8'); + expect(reply.headers['content-length']).toBe(String(reply.body.length)); + expect(reply.body.toString()).toBe('apcore_requests_total{route="測試"} 1\n'); + expect((await scrape(port, '/private/scrape/', 'GET')).status).toBe(404); + expect((await scrape(port, '/metrics')).status).toBe(404); + expect((await scrape(port, '/healthz?verbose=false')).body.toString()).toBe('OK'); + const unavailable = await scrape(port, '/readyz?probe=1'); + expect(unavailable.status).toBe(503); + expect(unavailable.body.toString()).toBe('Not ready'); + ready = true; + const available = await scrape(port, '/readyz?probe=2'); + expect(available.status).toBe(200); + expect(available.body.toString()).toBe('OK'); + const rejected = await scrape(port, '/private/scrape?source=prometheus', 'POST'); + expect(rejected.status).toBe(405); + expect(rejected.headers.allow).toBe('GET'); + expect(rejected.body.length).toBe(0); + } finally { + await close(server); + } + }); + + it('returns matching bytes from the legacy and Toolkit listeners for empty and live collectors', async () => { + const collector = new MetricsCollector(); + const usageCollector = new UsageCollector(); + const exporter = new PrometheusExporter({ collector, usageCollector }); + const server = createPrometheusServer({ renderMetrics: () => exporter.export() }); + const port = await listen(server); + try { + exporter.start({ port: 0 }); + // The legacy wrapper does not expose its chosen ephemeral port. + const legacyServer = Reflect.get(exporter, '_server') as Server; + if (!legacyServer.listening) await once(legacyServer, 'listening'); + const legacyPort = serverPort(legacyServer); + + const cold = await scrape(port, '/metrics'); + expect(cold.status).toBe(200); + expect(cold.headers['content-length']).toBe('0'); + expect(cold.body).toEqual((await scrape(legacyPort, '/metrics')).body); + + collector.increment('apcore_test_calls_total', {}, 2); + usageCollector.record('study.review', 12, false); + const live = await scrape(port, '/metrics'); + expect(live.status).toBe(200); + expect(live.body.toString()).toContain('apcore_usage_calls_total'); + expect(live.body).toEqual((await scrape(legacyPort, '/metrics')).body); + expect(live.body).toEqual(Buffer.from(exporter.export(), 'utf8')); + } finally { + await Promise.all([exporter.stop(), close(server)]); + } + }); + + it('reports bind errors through Node and supports another listen attempt', async () => { + const server = createPrometheusServer({ renderMetrics: () => 'example 1\n' }); + const occupied = createPrometheusServer({ renderMetrics: () => '' }); + const port = await listen(occupied); + try { + await expect(listen(server, port)).rejects.toMatchObject({ code: 'EADDRINUSE' }); + expect(server.listening).toBe(false); + await close(occupied); + expect(await listen(server, port)).toBe(port); + expect((await scrape(port, '/metrics')).status).toBe(200); + } finally { + if (occupied.listening) await close(occupied); + if (server.listening) await close(server); + } + }); + + it('drains an accepted request before closing and refuses new connections', async () => { + const server = createPrometheusServer({ renderMetrics: () => 'example 1\n' }); + const port = await listen(server); + const events: string[] = []; + let closed: Promise | undefined; + server.prependOnceListener('request', (_request, response) => { + response.once('finish', () => { events.push('finished response'); }); + closed = close(server).then(() => { events.push('closed listener'); }); + }); + try { + const reply = await scrape(port, '/metrics'); + expect(reply.status).toBe(200); + expect(reply.body.toString()).toBe('example 1\n'); + expect(closed).toBeDefined(); + await closed; + expect(events).toEqual(['finished response', 'closed listener']); + await expect(scrape(port, '/metrics')).rejects.toMatchObject({ code: 'ECONNREFUSED' }); + } finally { + if (server.listening) await close(server); + } + }); +}); From 203baaca535cc97885f38104aecbd6444b172889 Mon Sep 17 00:00:00 2001 From: tercel Date: Fri, 27 Nov 2026 11:12:38 +0800 Subject: [PATCH 02/36] chore(release): lock Rust surfaces to the verified Core crate Signed-off-by: tercel --- cli/rust/Cargo.lock | 2 +- toolkit/rust/Cargo.lock | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/cli/rust/Cargo.lock b/cli/rust/Cargo.lock index 2949548b..e6b3f7a3 100644 --- a/cli/rust/Cargo.lock +++ b/cli/rust/Cargo.lock @@ -135,7 +135,7 @@ checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" name = "apcore" version = "1.0.0-alpha.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2344e07dc37e34b8a93d8ff66d757587a2ca5adea5ca5cbd204af8d0ff836884" +checksum = "bbc1db3680f3d81b7096fa5eb70476a2c043b333681c2a7bba3597a49bbf11f6" dependencies = [ "async-stream", "async-trait", diff --git a/toolkit/rust/Cargo.lock b/toolkit/rust/Cargo.lock index 06a02db3..cda7b630 100644 --- a/toolkit/rust/Cargo.lock +++ b/toolkit/rust/Cargo.lock @@ -50,7 +50,7 @@ checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" name = "apcore" version = "1.0.0-alpha.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2344e07dc37e34b8a93d8ff66d757587a2ca5adea5ca5cbd204af8d0ff836884" +checksum = "bbc1db3680f3d81b7096fa5eb70476a2c043b333681c2a7bba3597a49bbf11f6" dependencies = [ "async-stream", "async-trait", From dfd631cbd9ff4efebf7c060dcbe276c2a04303d1 Mon Sep 17 00:00:00 2001 From: tercel Date: Fri, 27 Nov 2026 11:12:56 +0800 Subject: [PATCH 03/36] chore(release): bind the CLI preview to the verified Toolkit crate Signed-off-by: tercel --- cli/rust/Cargo.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cli/rust/Cargo.lock b/cli/rust/Cargo.lock index e6b3f7a3..9ad0909d 100644 --- a/cli/rust/Cargo.lock +++ b/cli/rust/Cargo.lock @@ -199,7 +199,7 @@ dependencies = [ name = "apcore-toolkit" version = "0.15.1-alpha.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44a190df138e3edc4e21738c8d07f76eb17aab761afb76226e61a08643147dc9" +checksum = "bbfd96cc205126386cc69e11b8cdeaf17349a65cee6038ffc1f59cfa0fbf6de3" dependencies = [ "apcore", "async-trait", From 709d4de2a51a74a71008ab160898e65216f73498 Mon Sep 17 00:00:00 2001 From: tercel Date: Fri, 27 Nov 2026 11:22:55 +0800 Subject: [PATCH 04/36] chore(release): lock MCP and A2A for Rust 1.86 Signed-off-by: tercel --- a2a/rust/.gitignore | 3 - a2a/rust/Cargo.lock | 3485 +++++++++++++++++++++++++++++++++++++++++ mcp/rust/.gitignore | 1 - mcp/rust/Cargo.lock | 3638 +++++++++++++++++++++++++++++++++++++++++++ mcp/rust/Cargo.toml | 1 + 5 files changed, 7124 insertions(+), 4 deletions(-) create mode 100644 a2a/rust/Cargo.lock create mode 100644 mcp/rust/Cargo.lock diff --git a/a2a/rust/.gitignore b/a2a/rust/.gitignore index 990bdb0f..e4920d2c 100644 --- a/a2a/rust/.gitignore +++ b/a2a/rust/.gitignore @@ -1,9 +1,6 @@ # Generated by Cargo /target/ -# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries -Cargo.lock - # IDE .idea/ .vscode/ diff --git a/a2a/rust/Cargo.lock b/a2a/rust/Cargo.lock new file mode 100644 index 00000000..01bac264 --- /dev/null +++ b/a2a/rust/Cargo.lock @@ -0,0 +1,3485 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "ahash" +version = "0.8.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fca89247609239eeb6915e6991111866b92d7b31025e69302bbf430cc4d2c38" +dependencies = [ + "cfg-if", + "getrandom 0.4.3", + "once_cell", + "serde", + "version_check", + "zerocopy", +] + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "android_system_properties" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" +dependencies = [ + "libc", +] + +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + +[[package]] +name = "apcore" +version = "1.0.0-alpha.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbc1db3680f3d81b7096fa5eb70476a2c043b333681c2a7bba3597a49bbf11f6" +dependencies = [ + "async-stream", + "async-trait", + "chrono", + "dashmap", + "futures-core", + "futures-util", + "jsonschema", + "notify", + "parking_lot", + "referencing", + "regex", + "schemars", + "serde", + "serde_json", + "serde_yaml_ng", + "sha2", + "thiserror", + "tokio", + "tracing", + "uuid", +] + +[[package]] +name = "apcore-a2a" +version = "0.8.7-alpha.1" +dependencies = [ + "apcore", + "apcore-toolkit", + "async-stream", + "async-trait", + "axum", + "chrono", + "clap", + "futures-util", + "http-body-util", + "hyper", + "hyper-util", + "jsonwebtoken", + "regex", + "reqwest", + "schemars", + "serde", + "serde_json", + "tempfile", + "thiserror", + "tokio", + "tokio-stream", + "tokio-test", + "tower", + "tower-http", + "tracing", + "tracing-subscriber", + "uuid", +] + +[[package]] +name = "apcore-toolkit" +version = "0.15.1-alpha.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbfd96cc205126386cc69e11b8cdeaf17349a65cee6038ffc1f59cfa0fbf6de3" +dependencies = [ + "apcore", + "async-trait", + "chrono", + "indexmap", + "percent-encoding", + "regex", + "reqwest", + "serde", + "serde_json", + "serde_yaml_ng", + "syn 2.0.119", + "thiserror", + "tokio", + "tracing", + "ureq", + "walkdir", +] + +[[package]] +name = "async-stream" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b5a71a6f37880a80d1d7f19efd781e4b5de42c88f0722cc13bcb6cc2cfe8476" +dependencies = [ + "async-stream-impl", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-stream-impl" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7c24de15d275a1ecfd47a380fb4d5ec9bfe0933f309ed5e705b775596a3574d" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "axum" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" +dependencies = [ + "axum-core", + "base64 0.22.1", + "bytes", + "form_urlencoded", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "serde_core", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "sha1", + "sync_wrapper", + "tokio", + "tokio-tungstenite", + "tower", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-core" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "sync_wrapper", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "base16ct" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + +[[package]] +name = "bit-set" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3" +dependencies = [ + "bit-vec", +] + +[[package]] +name = "bit-vec" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "borrow-or-share" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc0b364ead1874514c8c2855ab558056ebfeb775653e7ae45ff72f28f8f3166c" + +[[package]] +name = "bumpalo" +version = "3.20.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d20789868f4b01b2f2caec9f5c4e0213b41e3e5702a50157d699ae31ced2fcb" + +[[package]] +name = "bytecount" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "175812e0be2bccb6abe50bb8d566126198344f707e304f45c648fd8f2cc0365e" + +[[package]] +name = "bytes" +version = "1.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c" + +[[package]] +name = "cc" +version = "1.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02f0e023adb368345ce0ca6cdfc0f24a06554468d0e8503e14a0841de79bfa69" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "js-sys", + "num-traits", + "serde", + "wasm-bindgen", + "windows-link", +] + +[[package]] +name = "clap" +version = "4.6.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50066ca966813ca8957ee15361752f19424a8ff620dbe9c8993d9f99d99b04b3" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0ed97c96ef4efb3cc84e09fa388df4463e7cc3224ec38d7b1d9e45749333590" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4c174f11f949b9ca8c60580925e282b9cbd5454750e506f08648b2038080cd7" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "clap_lex" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79" + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + +[[package]] +name = "cookie" +version = "0.18.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d55f2d6c30eeec7d5c6f98bd4395d4abb1895629eab97ee6522d340623615f8a" +dependencies = [ + "percent-encoding", + "time", + "version_check", +] + +[[package]] +name = "cookie_store" +version = "0.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3fc4bff745c9b4c7fb1e97b25d13153da2bc7796260141df62378998d070207f" +dependencies = [ + "cookie", + "document-features", + "idna", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "time", + "url", +] + +[[package]] +name = "core-foundation" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crc32fast" +version = "1.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd9ae8fcb3ea71b0b26338b4ffb13006bb175de8fd07921089a906ce7e5e6945" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crypto-bigint" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76" +dependencies = [ + "generic-array", + "rand_core 0.6.4", + "subtle", + "zeroize", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "curve25519-dalek" +version = "4.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be" +dependencies = [ + "cfg-if", + "cpufeatures", + "curve25519-dalek-derive", + "digest", + "fiat-crypto", + "rustc_version", + "subtle", + "zeroize", +] + +[[package]] +name = "curve25519-dalek-derive" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "dashmap" +version = "6.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6361d5c062261c78a176addb82d4c821ae42bed6089de0e12603cd25de2059c" +dependencies = [ + "cfg-if", + "crossbeam-utils", + "hashbrown 0.14.5", + "lock_api", + "once_cell", + "parking_lot_core", +] + +[[package]] +name = "data-encoding" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" + +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid", + "pem-rfc7468", + "zeroize", +] + +[[package]] +name = "deranged" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" +dependencies = [ + "powerfmt", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "const-oid", + "crypto-common", + "subtle", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "document-features" +version = "0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61" +dependencies = [ + "litrs", +] + +[[package]] +name = "dyn-clone" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" + +[[package]] +name = "ecdsa" +version = "0.16.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca" +dependencies = [ + "der", + "digest", + "elliptic-curve", + "rfc6979", + "signature", + "spki", +] + +[[package]] +name = "ed25519" +version = "2.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53" +dependencies = [ + "pkcs8", + "signature", +] + +[[package]] +name = "ed25519-dalek" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9" +dependencies = [ + "curve25519-dalek", + "ed25519", + "serde", + "sha2", + "subtle", + "zeroize", +] + +[[package]] +name = "elliptic-curve" +version = "0.13.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47" +dependencies = [ + "base16ct", + "crypto-bigint", + "digest", + "ff", + "generic-array", + "group", + "hkdf", + "pem-rfc7468", + "pkcs8", + "rand_core 0.6.4", + "sec1", + "subtle", + "zeroize", +] + +[[package]] +name = "email_address" +version = "0.2.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ab6bbd053d3cdc62ba3de82aae11530a97bbd5b3a572fbdbcd0f0e545e3ff21" +dependencies = [ + "serde", +] + +[[package]] +name = "encoding_rs" +version = "0.8.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75030f3c4f45dafd7586dd6780965a8c7e8e285a5ecb86713e63a79c5b2766f3" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "fancy-regex" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e24cb5a94bcae1e5408b0effca5cd7172ea3c5755049c5f3af4cd283a165298" +dependencies = [ + "bit-set", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "ff" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393" +dependencies = [ + "rand_core 0.6.4", + "subtle", +] + +[[package]] +name = "fiat-crypto" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "flate2" +version = "1.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" +dependencies = [ + "crc32fast", + "miniz_oxide", + "zlib-rs", +] + +[[package]] +name = "fluent-uri" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1918b65d96df47d3591bed19c5cca17e3fa5d0707318e4b5ef2eae01764df7e5" +dependencies = [ + "borrow-or-share", + "ref-cast", + "serde", +] + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "foreign-types" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" +dependencies = [ + "foreign-types-shared", +] + +[[package]] +name = "foreign-types-shared" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" + +[[package]] +name = "form_urlencoded" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "fraction" +version = "0.15.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e076045bb43dac435333ed5f04caf35c7463631d0dae2deb2638d94dd0a5b872" +dependencies = [ + "lazy_static", + "num", +] + +[[package]] +name = "fsevent-sys" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76ee7a02da4d231650c7cea31349b889be2f45ddb3ef3032d2ec8185f6313fd2" +dependencies = [ + "libc", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", + "zeroize", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi 6.0.0", + "wasm-bindgen", +] + +[[package]] +name = "group" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" +dependencies = [ + "ff", + "rand_core 0.6.4", + "subtle", +] + +[[package]] +name = "h2" +version = "0.4.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b634322c4924093fe6a6e05ecbe5717cd3c6014934455f4ae8e5cf14ba3264a8" +dependencies = [ + "atomic-waker", + "bytes", + "fnv", + "futures-core", + "futures-sink", + "http", + "indexmap", + "slab", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" + +[[package]] +name = "hashbrown" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hkdf" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7" +dependencies = [ + "hmac", +] + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest", +] + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "hyper" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "229c6ff5584df4c6becbfe00567128bac768c8cd32ebc8a8366bd81ed072e8f3" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "h2", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", +] + +[[package]] +name = "hyper-tls" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70206fc6890eaca9fde8a0bf71caa2ddfc9fe045ac9e5c70df101a7dbde866e0" +dependencies = [ + "bytes", + "http-body-util", + "hyper", + "hyper-util", + "native-tls", + "tokio", + "tokio-native-tls", + "tower-service", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "base64 0.23.1", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "httparse", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "system-configuration", + "tokio", + "tower-service", + "tracing", + "windows-registry", +] + +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "icu_collections" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2984d1cd16c883d7935b9e07e44071dca8d917fd52ecc02c04d5fa0b5a3f191c" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92219b62b3e2b4d88ac5119f8904c10f8f61bf7e95b640d25ba3075e6cac2c29" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c56e5ee99d6e3d33bd91c5d85458b6005a22140021cc324cea84dd0e72cff3b4" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da3be0ae77ea334f4da67c12f149704f19f81d1adf7c51cf482943e84a2bad38" + +[[package]] +name = "icu_properties" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bee3b67d0ea5c2cca5003417989af8996f8604e34fb9ddf96208a033901e70de" +dependencies = [ + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e2bbb201e0c04f7b4b3e14382af113e17ba4f63e2c9d2ee626b720cbce54a14" + +[[package]] +name = "icu_provider" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "139c4cf31c8b5f33d7e199446eff9c1e02decfc2f0eec2c8d71f65befa45b421" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.2", +] + +[[package]] +name = "inotify" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "153be1941a183ec9ccd095ddbe17a8b8d435ef6c76e9e02451b933c3999af2c8" +dependencies = [ + "bitflags", + "inotify-sys", + "libc", +] + +[[package]] +name = "inotify-sys" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c033f80b2c113cdf91ab7a33faa9cbc014726dcad99880c8609af2a370edf37d" +dependencies = [ + "libc", +] + +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "js-sys" +version = "0.3.94" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e04e2ef80ce82e13552136fabeef8a5ed1f985a96805761cbb9a2c34e7664d9" +dependencies = [ + "cfg-if", + "futures-util", + "once_cell", + "wasm-bindgen", +] + +[[package]] +name = "jsonschema" +version = "0.28.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b8f66fe41fa46a5c83ed1c717b7e0b4635988f427083108c8cf0a882cc13441" +dependencies = [ + "ahash", + "base64 0.22.1", + "bytecount", + "email_address", + "fancy-regex", + "fraction", + "idna", + "itoa", + "num-cmp", + "once_cell", + "percent-encoding", + "referencing", + "regex-syntax", + "serde", + "serde_json", + "uuid-simd", +] + +[[package]] +name = "jsonwebtoken" +version = "10.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0529410abe238729a60b108898784df8984c87f6054c9c4fcacc47e4803c1ce1" +dependencies = [ + "base64 0.22.1", + "ed25519-dalek", + "getrandom 0.2.17", + "hmac", + "js-sys", + "p256", + "p384", + "pem", + "rand 0.8.8", + "rsa", + "serde", + "serde_json", + "sha2", + "signature", + "simple_asn1", +] + +[[package]] +name = "kqueue" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "273c0752728918e0ac4976f2b275b6fefb9ecd400585dec929419f3844cd87b5" +dependencies = [ + "kqueue-sys", + "libc", +] + +[[package]] +name = "kqueue-sys" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07293a4e297ac234359b510362495713f75ea345d5307140414f20c69ffeb087" +dependencies = [ + "bitflags", + "libc", +] + +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" +dependencies = [ + "spin", +] + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "litrs" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02b614978e47ce529faee66579f2b2fe19c94aa96d910a6a9a8043b2b02d8175" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "matchers" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +dependencies = [ + "regex-automata", +] + +[[package]] +name = "matchit" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "mime" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5848f5a9e8117cf94f2f90faac24a87ff81600ff8628c1e3deaab572e76bfa1" + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "mio" +version = "1.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a" +dependencies = [ + "libc", + "log", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "native-tls" +version = "0.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "465500e14ea162429d264d44189adc38b199b62b1c21eea9f69e4b73cb03bbf2" +dependencies = [ + "libc", + "log", + "openssl", + "openssl-probe", + "openssl-sys", + "schannel", + "security-framework", + "security-framework-sys", + "tempfile", +] + +[[package]] +name = "notify" +version = "8.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4d3d07927151ff8575b7087f245456e549fea62edf0ec4e565a5ee50c8402bc3" +dependencies = [ + "bitflags", + "fsevent-sys", + "inotify", + "kqueue", + "libc", + "log", + "mio", + "notify-types", + "walkdir", + "windows-sys 0.60.2", +] + +[[package]] +name = "notify-types" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42b8cfee0e339a0337359f3c88165702ac6e600dc01c0cc9579a92d62b08477a" +dependencies = [ + "bitflags", +] + +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "num" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23" +dependencies = [ + "num-bigint", + "num-complex", + "num-integer", + "num-iter", + "num-rational", + "num-traits", +] + +[[package]] +name = "num-bigint" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-bigint-dig" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e661dda6640fad38e827a6d4a310ff4763082116fe217f279885c97f511bb0b7" +dependencies = [ + "lazy_static", + "libm", + "num-integer", + "num-iter", + "num-traits", + "rand 0.8.8", + "smallvec", + "zeroize", +] + +[[package]] +name = "num-cmp" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63335b2e2c34fae2fb0aa2cecfd9f0832a1e24b3b32ecec612c3426d46dc8aaa" + +[[package]] +name = "num-complex" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-conv" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9" + +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-iter" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-rational" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824" +dependencies = [ + "num-bigint", + "num-integer", + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", + "libm", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "openssl" +version = "0.10.82" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4de8111e94a56adca7ebfe6c365b6d42f99deb69b74b6becacd4204e2f193aa2" +dependencies = [ + "bitflags", + "cfg-if", + "foreign-types", + "libc", + "openssl-macros", + "openssl-sys", +] + +[[package]] +name = "openssl-macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "openssl-probe" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" + +[[package]] +name = "openssl-sys" +version = "0.9.118" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19c413d6ec9ebaf5e1c829d355cb3e9f783778d700f135be0921d52fce3c60ae" +dependencies = [ + "cc", + "libc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "outref" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a80800c0488c3a21695ea981a54918fbb37abf04f4d0720c453632255e2ff0e" + +[[package]] +name = "p256" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9863ad85fa8f4460f9c48cb909d38a0d689dba1f6f6988a5e3e0d31071bcd4b" +dependencies = [ + "ecdsa", + "elliptic-curve", + "primeorder", + "sha2", +] + +[[package]] +name = "p384" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe42f1670a52a47d448f14b6a5c61dd78fce51856e68edaa38f7ae3a46b8d6b6" +dependencies = [ + "ecdsa", + "elliptic-curve", + "primeorder", + "sha2", +] + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "pem" +version = "3.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d30c53c26bc5b31a98cd02d20f25a7c8567146caf63ed593a9d87b2775291be" +dependencies = [ + "base64 0.22.1", + "serde_core", +] + +[[package]] +name = "pem-rfc7468" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412" +dependencies = [ + "base64ct", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752" + +[[package]] +name = "pkcs1" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f" +dependencies = [ + "der", + "pkcs8", + "spki", +] + +[[package]] +name = "pkcs8" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +dependencies = [ + "der", + "spki", +] + +[[package]] +name = "pkg-config" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c" + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "powerfmt" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "primeorder" +version = "0.13.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "353e1ca18966c16d9deb1c69278edbc5f194139612772bd9537af60ac231e1e6" +dependencies = [ + "elliptic-curve", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" +dependencies = [ + "libc", + "rand_chacha 0.3.1", + "rand_core 0.6.4", +] + +[[package]] +name = "rand" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha 0.9.0", + "rand_core 0.9.5", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core 0.6.4", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.5", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "ref-cast" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e440fb4e4b4147295338efb76001ab9e4efc0e5839df2c47fc5ac2381d365c3" +dependencies = [ + "ref-cast-impl", +] + +[[package]] +name = "ref-cast-impl" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "referencing" +version = "0.28.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0dcb5ab28989ad7c91eb1b9531a37a1a137cc69a0499aee4117cae4a107c464" +dependencies = [ + "ahash", + "fluent-uri", + "once_cell", + "percent-encoding", + "serde_json", +] + +[[package]] +name = "regex" +version = "1.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9807af0e638c12e753aa1b4e601791bf2a8f71274023c8bbeec12fc149950857" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6" + +[[package]] +name = "reqwest" +version = "0.12.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" +dependencies = [ + "base64 0.22.1", + "bytes", + "encoding_rs", + "futures-core", + "futures-util", + "h2", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-tls", + "hyper-util", + "js-sys", + "log", + "mime", + "native-tls", + "percent-encoding", + "pin-project-lite", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-native-tls", + "tokio-util", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-streams", + "web-sys", +] + +[[package]] +name = "rfc6979" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2" +dependencies = [ + "hmac", + "subtle", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rsa" +version = "0.9.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8573f03f5883dcaebdfcf4725caa1ecb9c15b2ef50c43a07b816e06799bb12d" +dependencies = [ + "const-oid", + "digest", + "num-bigint-dig", + "num-integer", + "num-traits", + "pkcs1", + "pkcs8", + "rand_core 0.6.4", + "signature", + "spki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "log", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "schannel" +version = "0.1.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "schemars" +version = "0.8.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3fbf2ae1b8bc8e02df939598064d22402220cd5bbcca1c76f7d6a310974d5615" +dependencies = [ + "dyn-clone", + "schemars_derive", + "serde", + "serde_json", +] + +[[package]] +name = "schemars_derive" +version = "0.8.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32e265784ad618884abaea0600a9adf15393368d840e0222d101a072f3f7534d" +dependencies = [ + "proc-macro2", + "quote", + "serde_derive_internals", + "syn 2.0.119", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "sec1" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc" +dependencies = [ + "base16ct", + "der", + "generic-array", + "pkcs8", + "subtle", + "zeroize", +] + +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags", + "core-foundation 0.10.1", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_derive_internals" +version = "0.29.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18d26a20a969b9e3fdf2fc2d9f21eda6c40e2de84c9408bb5d3b05d499aae711" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "foldhash", + "indexmap", + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "serde_yaml_ng" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b4db627b98b36d4203a7b458cf3573730f2bb591b28871d916dfa9efabfd41f" +dependencies = [ + "indexmap", + "itoa", + "ryu", + "serde", + "unsafe-libyaml", +] + +[[package]] +name = "sha1" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "signature" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +dependencies = [ + "digest", + "rand_core 0.6.4", +] + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "simple_asn1" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "297f631f50729c8c99b84667867963997ec0b50f32b2a7dbcab828ef0541e8bb" +dependencies = [ + "num-bigint", + "num-traits", + "thiserror", + "time", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "spin" +version = "0.9.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" + +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "system-configuration" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a13f3d0daba03132c0aa9767f98351b3488edc2c100cda2d2ec2b04f3d8d3c8b" +dependencies = [ + "bitflags", + "core-foundation 0.9.4", + "system-configuration-sys", +] + +[[package]] +name = "system-configuration-sys" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "thread_local" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "time" +version = "0.3.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9e442fc33d7fdb45aa9bfeb312c095964abdf596f7567261062b2a7107aaabd" +dependencies = [ + "deranged", + "itoa", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b36ee98fd31ec7426d599183e8fe26932a8dc1fb76ddb6214d05493377d34ca" + +[[package]] +name = "time-macros" +version = "0.2.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71e552d1249bf61ac2a52db88179fd0673def1e1ad8243a00d9ec9ed71fee3dd" +dependencies = [ + "num-conv", + "time-core", +] + +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "bytes", + "libc", + "mio", + "parking_lot", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "tokio-native-tls" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbae76ab933c85776efabc971569dd6119c580d8f5d448769dec1764bf796ef2" +dependencies = [ + "native-tls", + "tokio", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tokio-stream" +version = "0.1.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3d06f0b082ba57c26b79407372e57cf2a1e28124f78e9479fe80322cf53420b" +dependencies = [ + "futures-core", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tokio-test" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12bc5db7778a8e08ee255090861e0e7aac55e784300077e7ed293c7be36168b2" +dependencies = [ + "futures-core", + "tokio", + "tokio-stream", +] + +[[package]] +name = "tokio-tungstenite" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f72a05e828585856dacd553fba484c242c46e391fb0e58917c942ee9202915c" +dependencies = [ + "futures-util", + "log", + "tokio", + "tungstenite", +] + +[[package]] +name = "tokio-util" +version = "0.7.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "libc", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "log", + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex-automata", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "tungstenite" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c01152af293afb9c7c2a57e4b559c5620b421f6d133261c60dd2d0cdb38e6b8" +dependencies = [ + "bytes", + "data-encoding", + "http", + "httparse", + "log", + "rand 0.9.5", + "sha1", + "thiserror", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unsafe-libyaml" +version = "0.2.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "673aac59facbab8a9007c7f6108d11f63b603f7cabff99fabf650fea5c32b861" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "ureq" +version = "3.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ac5cecf619ca81f66a96482db09687c9f7465af65f4300a8c30cca05bd5a59d" +dependencies = [ + "base64 0.23.1", + "cookie_store", + "flate2", + "log", + "percent-encoding", + "rustls", + "rustls-pki-types", + "serde", + "serde_json", + "ureq-proto", + "utf8-zero", + "webpki-roots", +] + +[[package]] +name = "ureq-proto" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622dce33c252115466d83f63e9744a18f12b4406aae51a01c15ad8fcf1185eb3" +dependencies = [ + "base64 0.23.1", + "http", + "httparse", + "log", +] + +[[package]] +name = "url" +version = "2.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8-zero" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e" + +[[package]] +name = "utf8_iter" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "utf_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" + +[[package]] +name = "uuid" +version = "1.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ac8b6f42ead25368cf5b098aeb3dc8a1a2c05a3eee8a9a1a68c640edbfc79d9" +dependencies = [ + "getrandom 0.4.3", + "js-sys", + "serde_core", + "wasm-bindgen", +] + +[[package]] +name = "uuid-simd" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b082222b4f6619906941c17eb2297fff4c2fb96cb60164170522942a200bd8" +dependencies = [ + "outref", + "uuid", + "vsimd", +] + +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "vsimd" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c3082ca00d5a5ef149bb8b555a72ae84c9c59f7250f013ac822ac2e49b19c64" + +[[package]] +name = "walkdir" +version = "2.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b42e295b7452c4604982280d8586001fcad9b8b201cac67bca9771e7a7475403" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "want" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.2+wasi-0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9517f9239f02c069db75e65f174b3da828fe5f5b945c4dd26bd25d89c03ebcf5" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0551fc1bb415591e3372d0bc4780db7e587d84e2a7e79da121051c5c4b89d0b0" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.67" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03623de6905b7206edd0a75f69f747f134b7f0a2323392d664448bf2d3c5d87e" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fbdf9a35adf44786aecd5ff89b4563a90325f9da0923236f6104e603c7e86be" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dca9693ef2bab6d4e6707234500350d8dad079eb508dca05530c85dc3a529ff2" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 2.0.119", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39129a682a6d2d841b6c429d0c51e5cb0ed1a03829d8b3d1e69a011e62cb3d3b" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wasm-streams" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15053d8d85c7eccdbefef60f06769760a563c7f0a9d6902a13d35c7800b0ad65" +dependencies = [ + "futures-util", + "js-sys", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "web-sys" +version = "0.3.94" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd70027e39b12f0849461e08ffc50b9cd7688d942c1c8e3c7b22273236b4dd0a" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-roots" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-registry" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720" +dependencies = [ + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" +dependencies = [ + "windows-targets 0.53.5", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm 0.52.6", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", +] + +[[package]] +name = "windows-targets" +version = "0.53.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" +dependencies = [ + "windows-link", + "windows_aarch64_gnullvm 0.53.1", + "windows_aarch64_msvc 0.53.1", + "windows_i686_gnu 0.53.1", + "windows_i686_gnullvm 0.53.1", + "windows_i686_msvc 0.53.1", + "windows_x86_64_gnu 0.53.1", + "windows_x86_64_gnullvm 0.53.1", + "windows_x86_64_msvc 0.53.1", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_i686_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" + +[[package]] +name = "wit-bindgen" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + +[[package]] +name = "zerocopy" +version = "0.8.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32bc8a75f879cd6fe53a6bedf3c28f0e1b914c77424fc2be9e2ec85d7d25aff5" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8bfd2644ea1681f60cf95029ff18aa8ad1cc3f7b8fe37286f8e473bb29f816b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "zlib-rs" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa76918995d776d9dd34d371030be228d021137449771493d56e29f77e4148ac" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/mcp/rust/.gitignore b/mcp/rust/.gitignore index b93a058e..c5248768 100644 --- a/mcp/rust/.gitignore +++ b/mcp/rust/.gitignore @@ -1,5 +1,4 @@ /target -Cargo.lock *.swp *.swo *~ diff --git a/mcp/rust/Cargo.lock b/mcp/rust/Cargo.lock new file mode 100644 index 00000000..56a5df9d --- /dev/null +++ b/mcp/rust/Cargo.lock @@ -0,0 +1,3638 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "ahash" +version = "0.8.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fca89247609239eeb6915e6991111866b92d7b31025e69302bbf430cc4d2c38" +dependencies = [ + "cfg-if", + "getrandom 0.4.3", + "once_cell", + "serde", + "version_check", + "zerocopy", +] + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + +[[package]] +name = "android_system_properties" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" +dependencies = [ + "libc", +] + +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + +[[package]] +name = "apcore" +version = "1.0.0-alpha.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbc1db3680f3d81b7096fa5eb70476a2c043b333681c2a7bba3597a49bbf11f6" +dependencies = [ + "async-stream", + "async-trait", + "chrono", + "dashmap", + "futures-core", + "futures-util", + "jsonschema 0.28.3", + "notify", + "parking_lot", + "referencing 0.28.3", + "regex", + "schemars", + "serde", + "serde_json", + "serde_yaml_ng", + "sha2", + "thiserror", + "tokio", + "tracing", + "uuid", +] + +[[package]] +name = "apcore-mcp" +version = "0.23.5-alpha.1" +dependencies = [ + "apcore", + "apcore-toolkit", + "async-trait", + "axum", + "chrono", + "clap", + "futures", + "http-body-util", + "hyper", + "hyper-util", + "jsonschema 0.28.3", + "jsonwebtoken", + "mcp-embedded-ui", + "referencing 0.28.3", + "regex", + "rustix", + "schemars", + "serde", + "serde_json", + "strum", + "strum_macros", + "tempfile", + "thiserror", + "tokio", + "tokio-stream", + "tower", + "tracing", + "tracing-subscriber", + "uuid", + "windows-sys 0.61.2", +] + +[[package]] +name = "apcore-toolkit" +version = "0.15.1-alpha.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbfd96cc205126386cc69e11b8cdeaf17349a65cee6038ffc1f59cfa0fbf6de3" +dependencies = [ + "apcore", + "async-trait", + "chrono", + "futures-timer", + "indexmap", + "percent-encoding", + "regex", + "reqwest", + "serde", + "serde_json", + "serde_yaml_ng", + "syn 2.0.119", + "thiserror", + "tokio", + "tracing", + "ureq", + "walkdir", +] + +[[package]] +name = "async-stream" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b5a71a6f37880a80d1d7f19efd781e4b5de42c88f0722cc13bcb6cc2cfe8476" +dependencies = [ + "async-stream-impl", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-stream-impl" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7c24de15d275a1ecfd47a380fb4d5ec9bfe0933f309ed5e705b775596a3574d" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "axum" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" +dependencies = [ + "axum-core", + "base64 0.22.1", + "bytes", + "form_urlencoded", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "serde_core", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "sha1", + "sync_wrapper", + "tokio", + "tokio-tungstenite", + "tower", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-core" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "sync_wrapper", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "base16ct" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + +[[package]] +name = "bit-set" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3" +dependencies = [ + "bit-vec", +] + +[[package]] +name = "bit-vec" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "borrow-or-share" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc0b364ead1874514c8c2855ab558056ebfeb775653e7ae45ff72f28f8f3166c" + +[[package]] +name = "bumpalo" +version = "3.20.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d20789868f4b01b2f2caec9f5c4e0213b41e3e5702a50157d699ae31ced2fcb" + +[[package]] +name = "bytecount" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "175812e0be2bccb6abe50bb8d566126198344f707e304f45c648fd8f2cc0365e" + +[[package]] +name = "bytes" +version = "1.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c" + +[[package]] +name = "cc" +version = "1.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02f0e023adb368345ce0ca6cdfc0f24a06554468d0e8503e14a0841de79bfa69" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "js-sys", + "num-traits", + "serde", + "wasm-bindgen", + "windows-link", +] + +[[package]] +name = "clap" +version = "4.6.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50066ca966813ca8957ee15361752f19424a8ff620dbe9c8993d9f99d99b04b3" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0ed97c96ef4efb3cc84e09fa388df4463e7cc3224ec38d7b1d9e45749333590" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4c174f11f949b9ca8c60580925e282b9cbd5454750e506f08648b2038080cd7" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "clap_lex" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79" + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + +[[package]] +name = "cookie" +version = "0.18.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d55f2d6c30eeec7d5c6f98bd4395d4abb1895629eab97ee6522d340623615f8a" +dependencies = [ + "percent-encoding", + "time", + "version_check", +] + +[[package]] +name = "cookie_store" +version = "0.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3fc4bff745c9b4c7fb1e97b25d13153da2bc7796260141df62378998d070207f" +dependencies = [ + "cookie", + "document-features", + "idna", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "time", + "url", +] + +[[package]] +name = "core-foundation" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crc32fast" +version = "1.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd9ae8fcb3ea71b0b26338b4ffb13006bb175de8fd07921089a906ce7e5e6945" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crypto-bigint" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76" +dependencies = [ + "generic-array", + "rand_core 0.6.4", + "subtle", + "zeroize", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "curve25519-dalek" +version = "4.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be" +dependencies = [ + "cfg-if", + "cpufeatures", + "curve25519-dalek-derive", + "digest", + "fiat-crypto", + "rustc_version", + "subtle", + "zeroize", +] + +[[package]] +name = "curve25519-dalek-derive" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "dashmap" +version = "6.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6361d5c062261c78a176addb82d4c821ae42bed6089de0e12603cd25de2059c" +dependencies = [ + "cfg-if", + "crossbeam-utils", + "hashbrown 0.14.5", + "lock_api", + "once_cell", + "parking_lot_core", +] + +[[package]] +name = "data-encoding" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" + +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid", + "pem-rfc7468", + "zeroize", +] + +[[package]] +name = "deranged" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" +dependencies = [ + "powerfmt", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "const-oid", + "crypto-common", + "subtle", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "document-features" +version = "0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61" +dependencies = [ + "litrs", +] + +[[package]] +name = "dyn-clone" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" + +[[package]] +name = "ecdsa" +version = "0.16.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca" +dependencies = [ + "der", + "digest", + "elliptic-curve", + "rfc6979", + "signature", + "spki", +] + +[[package]] +name = "ed25519" +version = "2.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53" +dependencies = [ + "pkcs8", + "signature", +] + +[[package]] +name = "ed25519-dalek" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9" +dependencies = [ + "curve25519-dalek", + "ed25519", + "serde", + "sha2", + "subtle", + "zeroize", +] + +[[package]] +name = "elliptic-curve" +version = "0.13.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47" +dependencies = [ + "base16ct", + "crypto-bigint", + "digest", + "ff", + "generic-array", + "group", + "hkdf", + "pem-rfc7468", + "pkcs8", + "rand_core 0.6.4", + "sec1", + "subtle", + "zeroize", +] + +[[package]] +name = "email_address" +version = "0.2.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ab6bbd053d3cdc62ba3de82aae11530a97bbd5b3a572fbdbcd0f0e545e3ff21" +dependencies = [ + "serde", +] + +[[package]] +name = "encoding_rs" +version = "0.8.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75030f3c4f45dafd7586dd6780965a8c7e8e285a5ecb86713e63a79c5b2766f3" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "fancy-regex" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e24cb5a94bcae1e5408b0effca5cd7172ea3c5755049c5f3af4cd283a165298" +dependencies = [ + "bit-set", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "fancy-regex" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1e1dacd0d2082dfcf1351c4bdd566bbe89a2b263235a2b50058f1e130a47277" +dependencies = [ + "bit-set", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "ff" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393" +dependencies = [ + "rand_core 0.6.4", + "subtle", +] + +[[package]] +name = "fiat-crypto" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "flate2" +version = "1.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" +dependencies = [ + "crc32fast", + "miniz_oxide", + "zlib-rs", +] + +[[package]] +name = "fluent-uri" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1918b65d96df47d3591bed19c5cca17e3fa5d0707318e4b5ef2eae01764df7e5" +dependencies = [ + "borrow-or-share", + "ref-cast", + "serde", +] + +[[package]] +name = "fluent-uri" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc74ac4d8359ae70623506d512209619e5cf8f347124910440dbc221714b328e" +dependencies = [ + "borrow-or-share", + "ref-cast", + "serde", +] + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "foreign-types" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" +dependencies = [ + "foreign-types-shared", +] + +[[package]] +name = "foreign-types-shared" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" + +[[package]] +name = "form_urlencoded" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "fraction" +version = "0.15.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e076045bb43dac435333ed5f04caf35c7463631d0dae2deb2638d94dd0a5b872" +dependencies = [ + "lazy_static", + "num", +] + +[[package]] +name = "fsevent-sys" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76ee7a02da4d231650c7cea31349b889be2f45ddb3ef3032d2ec8185f6313fd2" +dependencies = [ + "libc", +] + +[[package]] +name = "futures" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-executor" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-timer" +version = "3.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af43fadb8a98512d547e37b4e92e0ced13e205c061b87b4623eff01d918d6968" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", + "zeroize", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi 5.3.0", + "wasip2", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi 6.0.0", + "wasm-bindgen", +] + +[[package]] +name = "group" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" +dependencies = [ + "ff", + "rand_core 0.6.4", + "subtle", +] + +[[package]] +name = "h2" +version = "0.4.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b634322c4924093fe6a6e05ecbe5717cd3c6014934455f4ae8e5cf14ba3264a8" +dependencies = [ + "atomic-waker", + "bytes", + "fnv", + "futures-core", + "futures-sink", + "http", + "indexmap", + "slab", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" + +[[package]] +name = "hashbrown" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash", +] + +[[package]] +name = "hashbrown" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hkdf" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7" +dependencies = [ + "hmac", +] + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest", +] + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "hyper" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "229c6ff5584df4c6becbfe00567128bac768c8cd32ebc8a8366bd81ed072e8f3" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "h2", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", +] + +[[package]] +name = "hyper-tls" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70206fc6890eaca9fde8a0bf71caa2ddfc9fe045ac9e5c70df101a7dbde866e0" +dependencies = [ + "bytes", + "http-body-util", + "hyper", + "hyper-util", + "native-tls", + "tokio", + "tokio-native-tls", + "tower-service", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "base64 0.23.1", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "httparse", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "system-configuration", + "tokio", + "tower-service", + "tracing", + "windows-registry", +] + +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "icu_collections" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2984d1cd16c883d7935b9e07e44071dca8d917fd52ecc02c04d5fa0b5a3f191c" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92219b62b3e2b4d88ac5119f8904c10f8f61bf7e95b640d25ba3075e6cac2c29" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c56e5ee99d6e3d33bd91c5d85458b6005a22140021cc324cea84dd0e72cff3b4" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da3be0ae77ea334f4da67c12f149704f19f81d1adf7c51cf482943e84a2bad38" + +[[package]] +name = "icu_properties" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bee3b67d0ea5c2cca5003417989af8996f8604e34fb9ddf96208a033901e70de" +dependencies = [ + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e2bbb201e0c04f7b4b3e14382af113e17ba4f63e2c9d2ee626b720cbce54a14" + +[[package]] +name = "icu_provider" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "139c4cf31c8b5f33d7e199446eff9c1e02decfc2f0eec2c8d71f65befa45b421" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.2", +] + +[[package]] +name = "inotify" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "153be1941a183ec9ccd095ddbe17a8b8d435ef6c76e9e02451b933c3999af2c8" +dependencies = [ + "bitflags", + "inotify-sys", + "libc", +] + +[[package]] +name = "inotify-sys" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c033f80b2c113cdf91ab7a33faa9cbc014726dcad99880c8609af2a370edf37d" +dependencies = [ + "libc", +] + +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "js-sys" +version = "0.3.94" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e04e2ef80ce82e13552136fabeef8a5ed1f985a96805761cbb9a2c34e7664d9" +dependencies = [ + "cfg-if", + "futures-util", + "once_cell", + "wasm-bindgen", +] + +[[package]] +name = "jsonschema" +version = "0.28.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b8f66fe41fa46a5c83ed1c717b7e0b4635988f427083108c8cf0a882cc13441" +dependencies = [ + "ahash", + "base64 0.22.1", + "bytecount", + "email_address", + "fancy-regex 0.14.0", + "fraction", + "idna", + "itoa", + "num-cmp", + "once_cell", + "percent-encoding", + "referencing 0.28.3", + "regex-syntax", + "serde", + "serde_json", + "uuid-simd", +] + +[[package]] +name = "jsonschema" +version = "0.46.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0a699d3e77675e6aa4bfffe3b907c8b5f7ed3241f9965bffb25475ad4b08d05" +dependencies = [ + "ahash", + "bytecount", + "data-encoding", + "email_address", + "fancy-regex 0.18.0", + "fraction", + "getrandom 0.3.4", + "idna", + "itoa", + "jsonschema-regex", + "num-cmp", + "num-traits", + "percent-encoding", + "referencing 0.46.10", + "regex", + "serde", + "serde_json", + "unicode-general-category", + "uuid-simd", +] + +[[package]] +name = "jsonschema-regex" +version = "0.46.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbd1086b01b9349fd4ef9a07433965af64c8ce8159abe633a189e4ff817bd13" +dependencies = [ + "regex-syntax", +] + +[[package]] +name = "jsonwebtoken" +version = "10.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0529410abe238729a60b108898784df8984c87f6054c9c4fcacc47e4803c1ce1" +dependencies = [ + "base64 0.22.1", + "ed25519-dalek", + "getrandom 0.2.17", + "hmac", + "js-sys", + "p256", + "p384", + "pem", + "rand 0.8.8", + "rsa", + "serde", + "serde_json", + "sha2", + "signature", + "simple_asn1", +] + +[[package]] +name = "kqueue" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "273c0752728918e0ac4976f2b275b6fefb9ecd400585dec929419f3844cd87b5" +dependencies = [ + "kqueue-sys", + "libc", +] + +[[package]] +name = "kqueue-sys" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07293a4e297ac234359b510362495713f75ea345d5307140414f20c69ffeb087" +dependencies = [ + "bitflags", + "libc", +] + +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" +dependencies = [ + "spin", +] + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "litrs" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02b614978e47ce529faee66579f2b2fe19c94aa96d910a6a9a8043b2b02d8175" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "matchers" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +dependencies = [ + "regex-automata", +] + +[[package]] +name = "matchit" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" + +[[package]] +name = "mcp-embedded-ui" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "305a8d31747100d1886fa709acaee2645fd99f1bc15575cca6f9b1a076ca7b34" +dependencies = [ + "async-trait", + "axum", + "jsonschema 0.46.10", + "serde", + "serde_json", + "thiserror", + "tokio", + "tower", + "tracing", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "micromap" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a86d3146ed3995b5913c414f6664344b9617457320782e64f0bb44afd49d74" + +[[package]] +name = "mime" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5848f5a9e8117cf94f2f90faac24a87ff81600ff8628c1e3deaab572e76bfa1" + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "mio" +version = "1.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a" +dependencies = [ + "libc", + "log", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "native-tls" +version = "0.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "465500e14ea162429d264d44189adc38b199b62b1c21eea9f69e4b73cb03bbf2" +dependencies = [ + "libc", + "log", + "openssl", + "openssl-probe", + "openssl-sys", + "schannel", + "security-framework", + "security-framework-sys", + "tempfile", +] + +[[package]] +name = "notify" +version = "8.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4d3d07927151ff8575b7087f245456e549fea62edf0ec4e565a5ee50c8402bc3" +dependencies = [ + "bitflags", + "fsevent-sys", + "inotify", + "kqueue", + "libc", + "log", + "mio", + "notify-types", + "walkdir", + "windows-sys 0.60.2", +] + +[[package]] +name = "notify-types" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42b8cfee0e339a0337359f3c88165702ac6e600dc01c0cc9579a92d62b08477a" +dependencies = [ + "bitflags", +] + +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "num" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23" +dependencies = [ + "num-bigint", + "num-complex", + "num-integer", + "num-iter", + "num-rational", + "num-traits", +] + +[[package]] +name = "num-bigint" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-bigint-dig" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e661dda6640fad38e827a6d4a310ff4763082116fe217f279885c97f511bb0b7" +dependencies = [ + "lazy_static", + "libm", + "num-integer", + "num-iter", + "num-traits", + "rand 0.8.8", + "smallvec", + "zeroize", +] + +[[package]] +name = "num-cmp" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63335b2e2c34fae2fb0aa2cecfd9f0832a1e24b3b32ecec612c3426d46dc8aaa" + +[[package]] +name = "num-complex" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-conv" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9" + +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-iter" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-rational" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824" +dependencies = [ + "num-bigint", + "num-integer", + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", + "libm", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "openssl" +version = "0.10.82" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4de8111e94a56adca7ebfe6c365b6d42f99deb69b74b6becacd4204e2f193aa2" +dependencies = [ + "bitflags", + "cfg-if", + "foreign-types", + "libc", + "openssl-macros", + "openssl-sys", +] + +[[package]] +name = "openssl-macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "openssl-probe" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" + +[[package]] +name = "openssl-sys" +version = "0.9.118" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19c413d6ec9ebaf5e1c829d355cb3e9f783778d700f135be0921d52fce3c60ae" +dependencies = [ + "cc", + "libc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "outref" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a80800c0488c3a21695ea981a54918fbb37abf04f4d0720c453632255e2ff0e" + +[[package]] +name = "p256" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9863ad85fa8f4460f9c48cb909d38a0d689dba1f6f6988a5e3e0d31071bcd4b" +dependencies = [ + "ecdsa", + "elliptic-curve", + "primeorder", + "sha2", +] + +[[package]] +name = "p384" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe42f1670a52a47d448f14b6a5c61dd78fce51856e68edaa38f7ae3a46b8d6b6" +dependencies = [ + "ecdsa", + "elliptic-curve", + "primeorder", + "sha2", +] + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "pem" +version = "3.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d30c53c26bc5b31a98cd02d20f25a7c8567146caf63ed593a9d87b2775291be" +dependencies = [ + "base64 0.22.1", + "serde_core", +] + +[[package]] +name = "pem-rfc7468" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412" +dependencies = [ + "base64ct", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752" + +[[package]] +name = "pkcs1" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f" +dependencies = [ + "der", + "pkcs8", + "spki", +] + +[[package]] +name = "pkcs8" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +dependencies = [ + "der", + "spki", +] + +[[package]] +name = "pkg-config" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c" + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "powerfmt" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "primeorder" +version = "0.13.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "353e1ca18966c16d9deb1c69278edbc5f194139612772bd9537af60ac231e1e6" +dependencies = [ + "elliptic-curve", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" +dependencies = [ + "libc", + "rand_chacha 0.3.1", + "rand_core 0.6.4", +] + +[[package]] +name = "rand" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha 0.9.0", + "rand_core 0.9.5", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core 0.6.4", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.5", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "ref-cast" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e440fb4e4b4147295338efb76001ab9e4efc0e5839df2c47fc5ac2381d365c3" +dependencies = [ + "ref-cast-impl", +] + +[[package]] +name = "ref-cast-impl" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "referencing" +version = "0.28.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0dcb5ab28989ad7c91eb1b9531a37a1a137cc69a0499aee4117cae4a107c464" +dependencies = [ + "ahash", + "fluent-uri 0.3.2", + "once_cell", + "percent-encoding", + "serde_json", +] + +[[package]] +name = "referencing" +version = "0.46.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fbf332a2f81899f6836f22c03da73dae8a664c32e3016b84692c23cddadc95d" +dependencies = [ + "ahash", + "fluent-uri 0.4.1", + "getrandom 0.3.4", + "hashbrown 0.16.1", + "itoa", + "micromap", + "parking_lot", + "percent-encoding", + "serde_json", +] + +[[package]] +name = "regex" +version = "1.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9807af0e638c12e753aa1b4e601791bf2a8f71274023c8bbeec12fc149950857" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6" + +[[package]] +name = "reqwest" +version = "0.12.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" +dependencies = [ + "base64 0.22.1", + "bytes", + "encoding_rs", + "futures-core", + "h2", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-tls", + "hyper-util", + "js-sys", + "log", + "mime", + "native-tls", + "percent-encoding", + "pin-project-lite", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-native-tls", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "rfc6979" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2" +dependencies = [ + "hmac", + "subtle", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rsa" +version = "0.9.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8573f03f5883dcaebdfcf4725caa1ecb9c15b2ef50c43a07b816e06799bb12d" +dependencies = [ + "const-oid", + "digest", + "num-bigint-dig", + "num-integer", + "num-traits", + "pkcs1", + "pkcs8", + "rand_core 0.6.4", + "signature", + "spki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "log", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "schannel" +version = "0.1.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "schemars" +version = "0.8.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3fbf2ae1b8bc8e02df939598064d22402220cd5bbcca1c76f7d6a310974d5615" +dependencies = [ + "dyn-clone", + "schemars_derive", + "serde", + "serde_json", +] + +[[package]] +name = "schemars_derive" +version = "0.8.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32e265784ad618884abaea0600a9adf15393368d840e0222d101a072f3f7534d" +dependencies = [ + "proc-macro2", + "quote", + "serde_derive_internals", + "syn 2.0.119", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "sec1" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc" +dependencies = [ + "base16ct", + "der", + "generic-array", + "pkcs8", + "subtle", + "zeroize", +] + +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags", + "core-foundation 0.10.1", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_derive_internals" +version = "0.29.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18d26a20a969b9e3fdf2fc2d9f21eda6c40e2de84c9408bb5d3b05d499aae711" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "foldhash", + "indexmap", + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "serde_yaml_ng" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b4db627b98b36d4203a7b458cf3573730f2bb591b28871d916dfa9efabfd41f" +dependencies = [ + "indexmap", + "itoa", + "ryu", + "serde", + "unsafe-libyaml", +] + +[[package]] +name = "sha1" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "signature" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +dependencies = [ + "digest", + "rand_core 0.6.4", +] + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "simple_asn1" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "297f631f50729c8c99b84667867963997ec0b50f32b2a7dbcab828ef0541e8bb" +dependencies = [ + "num-bigint", + "num-traits", + "thiserror", + "time", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "spin" +version = "0.9.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" + +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "strum" +version = "0.26.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fec0f0aef304996cf250b31b5a10dee7980c85da9d759361292b8bca5a18f06" + +[[package]] +name = "strum_macros" +version = "0.26.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c6bee85a5a24955dc440386795aa378cd9cf82acd5f764469152d2270e581be" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "rustversion", + "syn 2.0.119", +] + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "system-configuration" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a13f3d0daba03132c0aa9767f98351b3488edc2c100cda2d2ec2b04f3d8d3c8b" +dependencies = [ + "bitflags", + "core-foundation 0.9.4", + "system-configuration-sys", +] + +[[package]] +name = "system-configuration-sys" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "thread_local" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "time" +version = "0.3.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9e442fc33d7fdb45aa9bfeb312c095964abdf596f7567261062b2a7107aaabd" +dependencies = [ + "deranged", + "itoa", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b36ee98fd31ec7426d599183e8fe26932a8dc1fb76ddb6214d05493377d34ca" + +[[package]] +name = "time-macros" +version = "0.2.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71e552d1249bf61ac2a52db88179fd0673def1e1ad8243a00d9ec9ed71fee3dd" +dependencies = [ + "num-conv", + "time-core", +] + +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "bytes", + "libc", + "mio", + "parking_lot", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "tokio-native-tls" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbae76ab933c85776efabc971569dd6119c580d8f5d448769dec1764bf796ef2" +dependencies = [ + "native-tls", + "tokio", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tokio-stream" +version = "0.1.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3d06f0b082ba57c26b79407372e57cf2a1e28124f78e9479fe80322cf53420b" +dependencies = [ + "futures-core", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tokio-tungstenite" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f72a05e828585856dacd553fba484c242c46e391fb0e58917c942ee9202915c" +dependencies = [ + "futures-util", + "log", + "tokio", + "tungstenite", +] + +[[package]] +name = "tokio-util" +version = "0.7.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "libc", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "log", + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex-automata", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "tungstenite" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c01152af293afb9c7c2a57e4b559c5620b421f6d133261c60dd2d0cdb38e6b8" +dependencies = [ + "bytes", + "data-encoding", + "http", + "httparse", + "log", + "rand 0.9.5", + "sha1", + "thiserror", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-general-category" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b993bddc193ae5bd0d623b49ec06ac3e9312875fdae725a975c51db1cc1677f" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unsafe-libyaml" +version = "0.2.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "673aac59facbab8a9007c7f6108d11f63b603f7cabff99fabf650fea5c32b861" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "ureq" +version = "3.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ac5cecf619ca81f66a96482db09687c9f7465af65f4300a8c30cca05bd5a59d" +dependencies = [ + "base64 0.23.1", + "cookie_store", + "flate2", + "log", + "percent-encoding", + "rustls", + "rustls-pki-types", + "serde", + "serde_json", + "ureq-proto", + "utf8-zero", + "webpki-roots", +] + +[[package]] +name = "ureq-proto" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622dce33c252115466d83f63e9744a18f12b4406aae51a01c15ad8fcf1185eb3" +dependencies = [ + "base64 0.23.1", + "http", + "httparse", + "log", +] + +[[package]] +name = "url" +version = "2.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8-zero" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e" + +[[package]] +name = "utf8_iter" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "utf_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" + +[[package]] +name = "uuid" +version = "1.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ac8b6f42ead25368cf5b098aeb3dc8a1a2c05a3eee8a9a1a68c640edbfc79d9" +dependencies = [ + "getrandom 0.4.3", + "js-sys", + "serde_core", + "wasm-bindgen", +] + +[[package]] +name = "uuid-simd" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b082222b4f6619906941c17eb2297fff4c2fb96cb60164170522942a200bd8" +dependencies = [ + "outref", + "uuid", + "vsimd", +] + +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "vsimd" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c3082ca00d5a5ef149bb8b555a72ae84c9c59f7250f013ac822ac2e49b19c64" + +[[package]] +name = "walkdir" +version = "2.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b42e295b7452c4604982280d8586001fcad9b8b201cac67bca9771e7a7475403" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "want" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.2+wasi-0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9517f9239f02c069db75e65f174b3da828fe5f5b945c4dd26bd25d89c03ebcf5" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0551fc1bb415591e3372d0bc4780db7e587d84e2a7e79da121051c5c4b89d0b0" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.67" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03623de6905b7206edd0a75f69f747f134b7f0a2323392d664448bf2d3c5d87e" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fbdf9a35adf44786aecd5ff89b4563a90325f9da0923236f6104e603c7e86be" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dca9693ef2bab6d4e6707234500350d8dad079eb508dca05530c85dc3a529ff2" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 2.0.119", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39129a682a6d2d841b6c429d0c51e5cb0ed1a03829d8b3d1e69a011e62cb3d3b" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "web-sys" +version = "0.3.94" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd70027e39b12f0849461e08ffc50b9cd7688d942c1c8e3c7b22273236b4dd0a" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-roots" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-registry" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720" +dependencies = [ + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" +dependencies = [ + "windows-targets 0.53.5", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm 0.52.6", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", +] + +[[package]] +name = "windows-targets" +version = "0.53.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" +dependencies = [ + "windows-link", + "windows_aarch64_gnullvm 0.53.1", + "windows_aarch64_msvc 0.53.1", + "windows_i686_gnu 0.53.1", + "windows_i686_gnullvm 0.53.1", + "windows_i686_msvc 0.53.1", + "windows_x86_64_gnu 0.53.1", + "windows_x86_64_gnullvm 0.53.1", + "windows_x86_64_msvc 0.53.1", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_i686_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" + +[[package]] +name = "wit-bindgen" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + +[[package]] +name = "zerocopy" +version = "0.8.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32bc8a75f879cd6fe53a6bedf3c28f0e1b914c77424fc2be9e2ec85d7d25aff5" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8bfd2644ea1681f60cf95029ff18aa8ad1cc3f7b8fe37286f8e473bb29f816b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "zlib-rs" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa76918995d776d9dd34d371030be228d021137449771493d56e29f77e4148ac" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/mcp/rust/Cargo.toml b/mcp/rust/Cargo.toml index d6c3f7b6..1529f755 100644 --- a/mcp/rust/Cargo.toml +++ b/mcp/rust/Cargo.toml @@ -2,6 +2,7 @@ name = "apcore-mcp" version = "0.23.5-alpha.1" edition = "2021" +rust-version = "1.86" description = "MCP bridge for apcore — expose apcore modules as MCP tools" license = "Apache-2.0" readme = "README.md" From 6bf595616fed0c7dd8a198584429bd3bf06d967c Mon Sep 17 00:00:00 2001 From: tercel Date: Fri, 27 Nov 2026 11:24:55 +0800 Subject: [PATCH 05/36] ci: allow the Core candidate to verify Surfaces artifacts Signed-off-by: tercel --- .github/workflows/core-candidate.yml | 59 ++++++++++++++++++++++------ 1 file changed, 48 insertions(+), 11 deletions(-) diff --git a/.github/workflows/core-candidate.yml b/.github/workflows/core-candidate.yml index 38614fbc..5afdb6d9 100644 --- a/.github/workflows/core-candidate.yml +++ b/.github/workflows/core-candidate.yml @@ -1,8 +1,35 @@ name: Core candidate compatibility on: + workflow_call: + inputs: + core_run_id: + required: true + type: string + core_sha: + required: true + type: string + surfaces_sha: + required: true + type: string + rust_sha256: + required: false + type: string + python_sha256: + required: false + type: string + npm_sha256: + required: false + type: string + secrets: + APCORE_ARTIFACT_READ_TOKEN: + required: false workflow_dispatch: inputs: + core_sha: + description: Expected Core commit, when supplied + required: false + type: string core_run_id: description: Successful APCore Core distribution verification run ID required: true @@ -22,28 +49,27 @@ on: permissions: contents: read + actions: read jobs: verify-source: runs-on: ubuntu-latest outputs: head_sha: ${{ steps.source.outputs.head_sha }} + run_id: ${{ steps.source.outputs.run_id }} steps: - name: Verify the upstream package run id: source shell: bash env: CORE_RUN_ID: ${{ inputs.core_run_id }} - GH_TOKEN: ${{ secrets.APCORE_ARTIFACT_READ_TOKEN }} + EXPECTED_CORE_SHA: ${{ inputs.core_sha }} + GH_TOKEN: ${{ secrets.APCORE_ARTIFACT_READ_TOKEN || github.token }} run: | if [[ ! "$CORE_RUN_ID" =~ ^[0-9]+$ ]]; then echo "core_run_id must be a numeric APCore workflow run ID." >&2 exit 1 fi - if [[ -z "$GH_TOKEN" ]]; then - echo "Set APCORE_ARTIFACT_READ_TOKEN with Actions read access to aiperceivable/apcore." >&2 - exit 1 - fi run=$(gh api "repos/aiperceivable/apcore/actions/runs/$CORE_RUN_ID") if ! head_sha=$(jq -er ' select( @@ -56,7 +82,12 @@ jobs: echo "Choose a successful push or manual Core distribution verification run from aiperceivable/apcore." >&2 exit 1 fi + if [[ -n "$EXPECTED_CORE_SHA" && "$head_sha" != "$EXPECTED_CORE_SHA" ]]; then + echo "The Core run did not build the reviewed alpha.1 commit." >&2 + exit 1 + fi printf 'head_sha=%s\n' "$head_sha" >> "$GITHUB_OUTPUT" + printf 'run_id=%s\n' "$CORE_RUN_ID" >> "$GITHUB_OUTPUT" printf 'APCore package run %s at %s\n' "$CORE_RUN_ID" "$head_sha" python: @@ -79,6 +110,8 @@ jobs: steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 with: + repository: aiperceivable/apcore-surfaces + ref: ${{ inputs.surfaces_sha || github.sha }} persist-credentials: false - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 with: @@ -87,8 +120,8 @@ jobs: if: matrix.core == 'candidate' with: repository: aiperceivable/apcore - run-id: ${{ inputs.core_run_id }} - github-token: ${{ secrets.APCORE_ARTIFACT_READ_TOKEN }} + run-id: ${{ needs.verify-source.outputs.run_id }} + github-token: ${{ secrets.APCORE_ARTIFACT_READ_TOKEN || github.token }} name: core-python-distributions path: ${{ runner.temp }}/apcore-wheel - name: Install and verify the selected Core and local Toolkit @@ -196,6 +229,8 @@ jobs: steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 with: + repository: aiperceivable/apcore-surfaces + ref: ${{ inputs.surfaces_sha || github.sha }} persist-credentials: false - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 with: @@ -207,8 +242,8 @@ jobs: if: matrix.core == 'candidate' with: repository: aiperceivable/apcore - run-id: ${{ inputs.core_run_id }} - github-token: ${{ secrets.APCORE_ARTIFACT_READ_TOKEN }} + run-id: ${{ needs.verify-source.outputs.run_id }} + github-token: ${{ secrets.APCORE_ARTIFACT_READ_TOKEN || github.token }} name: core-npm-distribution path: ${{ runner.temp }}/apcore-npm - name: Build with the selected Core and local Toolkit @@ -324,6 +359,8 @@ jobs: steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 with: + repository: aiperceivable/apcore-surfaces + ref: ${{ inputs.surfaces_sha || github.sha }} persist-credentials: false - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 with: @@ -335,8 +372,8 @@ jobs: if: matrix.core == 'candidate' with: repository: aiperceivable/apcore - run-id: ${{ inputs.core_run_id }} - github-token: ${{ secrets.APCORE_ARTIFACT_READ_TOKEN }} + run-id: ${{ needs.verify-source.outputs.run_id }} + github-token: ${{ secrets.APCORE_ARTIFACT_READ_TOKEN || github.token }} name: core-rust-distribution path: ${{ runner.temp }}/apcore-crate - name: Verify resolution and run real Executor tests From 16bac9020841c16f52bf7853cc7af07587a6b9b8 Mon Sep 17 00:00:00 2001 From: tercel Date: Fri, 27 Nov 2026 11:30:49 +0800 Subject: [PATCH 06/36] test(toolkit): account for TCP reset during listener shutdown Signed-off-by: tercel --- toolkit/rust/tests/prometheus_server.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/toolkit/rust/tests/prometheus_server.rs b/toolkit/rust/tests/prometheus_server.rs index 5fad81d5..cd895b82 100644 --- a/toolkit/rust/tests/prometheus_server.rs +++ b/toolkit/rust/tests/prometheus_server.rs @@ -129,6 +129,10 @@ async fn close_stops_accepting_and_drains_an_in_flight_response() { loop { match TcpStream::connect(address).await { Err(error) if error.kind() == ErrorKind::ConnectionRefused => break, + // Linux can reset a connection already queued when the listener closes. + Err(error) if error.kind() == ErrorKind::ConnectionReset => { + tokio::task::yield_now().await; + } Ok(_) => tokio::task::yield_now().await, Err(error) => panic!("unexpected connect error: {error}"), } From 1ae19987ed939401ba4ebcb83256dc31d97bb921 Mon Sep 17 00:00:00 2001 From: tercel Date: Fri, 27 Nov 2026 11:31:23 +0800 Subject: [PATCH 07/36] chore(release): relock Rust surfaces against the verified Toolkit archive Signed-off-by: tercel --- a2a/rust/Cargo.lock | 2 +- cli/rust/Cargo.lock | 2 +- mcp/rust/Cargo.lock | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/a2a/rust/Cargo.lock b/a2a/rust/Cargo.lock index 01bac264..4ad5a77b 100644 --- a/a2a/rust/Cargo.lock +++ b/a2a/rust/Cargo.lock @@ -155,7 +155,7 @@ dependencies = [ name = "apcore-toolkit" version = "0.15.1-alpha.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbfd96cc205126386cc69e11b8cdeaf17349a65cee6038ffc1f59cfa0fbf6de3" +checksum = "d2239fcaf5fc1f833ebba79cdc9d022c7a70cc4b523e4fc637538f4a6baaf5f9" dependencies = [ "apcore", "async-trait", diff --git a/cli/rust/Cargo.lock b/cli/rust/Cargo.lock index 9ad0909d..40a44bea 100644 --- a/cli/rust/Cargo.lock +++ b/cli/rust/Cargo.lock @@ -199,7 +199,7 @@ dependencies = [ name = "apcore-toolkit" version = "0.15.1-alpha.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbfd96cc205126386cc69e11b8cdeaf17349a65cee6038ffc1f59cfa0fbf6de3" +checksum = "d2239fcaf5fc1f833ebba79cdc9d022c7a70cc4b523e4fc637538f4a6baaf5f9" dependencies = [ "apcore", "async-trait", diff --git a/mcp/rust/Cargo.lock b/mcp/rust/Cargo.lock index 56a5df9d..90821c29 100644 --- a/mcp/rust/Cargo.lock +++ b/mcp/rust/Cargo.lock @@ -164,7 +164,7 @@ dependencies = [ name = "apcore-toolkit" version = "0.15.1-alpha.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbfd96cc205126386cc69e11b8cdeaf17349a65cee6038ffc1f59cfa0fbf6de3" +checksum = "d2239fcaf5fc1f833ebba79cdc9d022c7a70cc4b523e4fc637538f4a6baaf5f9" dependencies = [ "apcore", "async-trait", From bceddb7acd5ca9f7e9a59e066d355885223c1b7a Mon Sep 17 00:00:00 2001 From: tercel Date: Fri, 27 Nov 2026 11:35:42 +0800 Subject: [PATCH 08/36] test(toolkit): consolidate enabled environment checks Signed-off-by: tercel --- toolkit/rust/src/ai_enhancer.rs | 14 +------------- 1 file changed, 1 insertion(+), 13 deletions(-) diff --git a/toolkit/rust/src/ai_enhancer.rs b/toolkit/rust/src/ai_enhancer.rs index 29473aca..5374e1b5 100644 --- a/toolkit/rust/src/ai_enhancer.rs +++ b/toolkit/rust/src/ai_enhancer.rs @@ -801,13 +801,6 @@ mod tests { assert!(result.is_err()); } - #[test] - fn test_is_enabled_default() { - // Assuming env var is not set in test environment - env::remove_var("APCORE_AI_ENABLED"); - assert!(!AIEnhancer::is_enabled()); - } - #[test] fn test_build_prompt_contains_module_info() { let enhancer = AIEnhancer::new(None, None, None, None, None).unwrap(); @@ -853,14 +846,9 @@ mod tests { .contains("APCORE_AI_TIMEOUT must be a positive integer")); } - // All is_enabled tests are combined into one to prevent env var races - // when tests run in parallel (env vars are process-global). + // Keep all APCORE_AI_ENABLED mutations in one test because it is process-global. #[test] fn test_is_enabled_variants() { - use std::sync::Mutex; - static ENV_LOCK: Mutex<()> = Mutex::new(()); - let _guard = ENV_LOCK.lock().unwrap(); - // Default (unset) → disabled unsafe { env::remove_var("APCORE_AI_ENABLED") }; assert!(!AIEnhancer::is_enabled(), "should be disabled by default"); From 79ab47351e294fdc619b27a8f9e97f37c6555199 Mon Sep 17 00:00:00 2001 From: tercel Date: Fri, 27 Nov 2026 11:36:47 +0800 Subject: [PATCH 09/36] chore(release): bind Rust surfaces to the refreshed Toolkit crate Signed-off-by: tercel --- a2a/rust/Cargo.lock | 2 +- cli/rust/Cargo.lock | 2 +- mcp/rust/Cargo.lock | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/a2a/rust/Cargo.lock b/a2a/rust/Cargo.lock index 4ad5a77b..f28f79b7 100644 --- a/a2a/rust/Cargo.lock +++ b/a2a/rust/Cargo.lock @@ -155,7 +155,7 @@ dependencies = [ name = "apcore-toolkit" version = "0.15.1-alpha.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2239fcaf5fc1f833ebba79cdc9d022c7a70cc4b523e4fc637538f4a6baaf5f9" +checksum = "ab34436cafe0107095f188074f226983d1a1605741529b9397d27de490a3cad9" dependencies = [ "apcore", "async-trait", diff --git a/cli/rust/Cargo.lock b/cli/rust/Cargo.lock index 40a44bea..49f38234 100644 --- a/cli/rust/Cargo.lock +++ b/cli/rust/Cargo.lock @@ -199,7 +199,7 @@ dependencies = [ name = "apcore-toolkit" version = "0.15.1-alpha.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2239fcaf5fc1f833ebba79cdc9d022c7a70cc4b523e4fc637538f4a6baaf5f9" +checksum = "ab34436cafe0107095f188074f226983d1a1605741529b9397d27de490a3cad9" dependencies = [ "apcore", "async-trait", diff --git a/mcp/rust/Cargo.lock b/mcp/rust/Cargo.lock index 90821c29..5f0fe9c1 100644 --- a/mcp/rust/Cargo.lock +++ b/mcp/rust/Cargo.lock @@ -164,7 +164,7 @@ dependencies = [ name = "apcore-toolkit" version = "0.15.1-alpha.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2239fcaf5fc1f833ebba79cdc9d022c7a70cc4b523e4fc637538f4a6baaf5f9" +checksum = "ab34436cafe0107095f188074f226983d1a1605741529b9397d27de490a3cad9" dependencies = [ "apcore", "async-trait", From 2eca45d07c13600e44089c8c50b8433cf2e1c596 Mon Sep 17 00:00:00 2001 From: tercel Date: Fri, 27 Nov 2026 11:39:56 +0800 Subject: [PATCH 10/36] fix(a2a): recover settled outcomes after SSE queue eviction Signed-off-by: tercel --- a2a/python/src/apcore_a2a/server/factory.py | 30 +++++++++++- .../tests/server/test_server_factory.py | 49 ++++++++++++++++++- 2 files changed, 77 insertions(+), 2 deletions(-) diff --git a/a2a/python/src/apcore_a2a/server/factory.py b/a2a/python/src/apcore_a2a/server/factory.py index cee2496f..65424f63 100644 --- a/a2a/python/src/apcore_a2a/server/factory.py +++ b/a2a/python/src/apcore_a2a/server/factory.py @@ -6,6 +6,7 @@ import logging import time import warnings +from collections.abc import AsyncGenerator from dataclasses import dataclass from typing import TYPE_CHECKING, Any @@ -23,8 +24,10 @@ GetTaskRequest, ListTasksRequest, ListTasksResponse, + SendMessageRequest, Task, TaskState, + TaskStatusUpdateEvent, ) from a2a.utils.errors import TaskNotCancelableError from apcore.error_formatter import ErrorFormatterRegistry @@ -50,7 +53,7 @@ from apcore_a2a.server.context import ( identity_of as _identity_of, ) -from apcore_a2a.server.executor import ApCoreAgentExecutor +from apcore_a2a.server.executor import _TERMINAL_STATES, ApCoreAgentExecutor if TYPE_CHECKING: from a2a.server.cluster.task_store import StoredTask @@ -108,6 +111,31 @@ async def delete(self, task_id: str, context: ServerCallContext) -> None: class _TerminalAwareRequestHandler(DefaultRequestHandler): + async def on_message_send_stream( + self, params: SendMessageRequest, context: ServerCallContext + ) -> AsyncGenerator[Event, None]: + task_id: str | None = None + reported_outcome = False + async with contextlib.aclosing(super().on_message_send_stream(params, context)) as stream: + async for event in stream: + if isinstance(event, Task): + task_id = event.id + if isinstance(event, (Task, TaskStatusUpdateEvent)): + reported_outcome |= ( + event.status.state in _TERMINAL_STATES + or event.status.state == TaskState.TASK_STATE_INPUT_REQUIRED + ) + yield event + + if task_id is None or reported_outcome: + return + # The SDK disconnects slow subscribers when their queue fills. After an + # otherwise clean EOF, recover an already-settled terminal through the + # same identity-scoped path as GetTask. + task = await self.on_get_task(GetTaskRequest(id=task_id), context) + if task is not None and task.status.state in _TERMINAL_STATES: + yield TaskStatusUpdateEvent(task_id=task.id, context_id=task.context_id, status=task.status) + async def on_get_task(self, params: GetTaskRequest, context: ServerCallContext) -> Task | None: task = await super().on_get_task(params, context) if task is not None: diff --git a/a2a/python/tests/server/test_server_factory.py b/a2a/python/tests/server/test_server_factory.py index 78fd92a1..6781232b 100644 --- a/a2a/python/tests/server/test_server_factory.py +++ b/a2a/python/tests/server/test_server_factory.py @@ -8,6 +8,7 @@ import pytest from a2a.server.context import ServerCallContext from a2a.server.events.event_queue_v2 import EventQueueSource +from a2a.server.request_handlers import DefaultRequestHandler from a2a.types import AgentCard, CancelTaskRequest, SendMessageRequest, Task, TaskState, TaskStatusUpdateEvent from a2a.utils.errors import TaskNotCancelableError from apcore import Executor, Registry @@ -169,8 +170,27 @@ async def stream(self, inputs, context): @pytest.mark.parametrize("versioned_store", [False, True]) -async def test_get_task_reports_the_terminal_before_a_slow_sse_reader_drains(versioned_store): +async def test_get_task_reports_the_terminal_before_a_slow_sse_reader_drains(versioned_store, monkeypatch, caplog): first_task, allow_send, stopped = asyncio.Event(), asyncio.Event(), asyncio.Event() + terminal_offered = asyncio.Event() + uses_evictable_sink = False + tap = EventQueueSource.tap + enqueue = EventQueueSource.enqueue_event + + async def observe_terminal(source, event): + if isinstance(event, TaskStatusUpdateEvent) and event.status.state == TaskState.TASK_STATE_FAILED: + terminal_offered.set() + await enqueue(source, event) + + async def small_subscriber_buffer(source, *args, **kwargs): + nonlocal uses_evictable_sink + if kwargs.get("evict_on_full"): + uses_evictable_sink = True + kwargs["max_queue_size"] = 2 + return await tap(source, *args, **kwargs) + + monkeypatch.setattr(EventQueueSource, "tap", small_subscriber_buffer) + monkeypatch.setattr(EventQueueSource, "enqueue_event", observe_terminal) task_id = "" class FastProducer: @@ -183,6 +203,7 @@ async def execute(self, inputs, context): async def stream(self, inputs, context): try: + await first_task.wait() for index in range(10_000): yield {"index": index} finally: @@ -244,6 +265,7 @@ async def slow_send(event): try: await asyncio.wait_for(first_task.wait(), 2) await asyncio.wait_for(stopped.wait(), 2) + await asyncio.wait_for(terminal_offered.wait(), 2) query = {"jsonrpc": "2.0", "id": 2, "method": "GetTask", "params": {"id": task_id}} result = await status.post("/", headers=headers, json=query) assert result.json()["result"]["status"]["state"] == "TASK_STATE_FAILED" @@ -253,11 +275,36 @@ async def slow_send(event): response = await asyncio.wait_for(streaming, 3) frames = [json.loads(line[5:])["result"] for line in response.text.splitlines() if line.startswith("data:")] statuses = [event["statusUpdate"]["status"] for event in frames if "statusUpdate" in event] + if uses_evictable_sink: + assert "Evicting event queue sink" in caplog.text assert [item["state"] for item in statuses] == ["TASK_STATE_FAILED"] persisted = await status.post("/", headers=headers, json=query) assert persisted.json()["result"]["status"] == statuses[0] +async def test_closed_subscriber_does_not_report_a_working_task_as_a_terminal(monkeypatch): + context = ServerCallContext() + submitted = Task(id="task", context_id="conversation", status={"state": TaskState.TASK_STATE_SUBMITTED}) + + async def closed_subscriber(self, params, call_context): + assert call_context is context + yield submitted + + monkeypatch.setattr(DefaultRequestHandler, "on_message_send_stream", closed_subscriber) + store = A2ATaskStore() + working = Task(id=submitted.id, context_id=submitted.context_id, status={"state": TaskState.TASK_STATE_WORKING}) + await store.save(working, context) + handler = _TerminalAwareRequestHandler( + agent_executor=ApCoreAgentExecutor(MagicMock(), MagicMock(), MagicMock()), + task_store=store, + agent_card=AgentCard(name="test", capabilities={"streaming": True}), + ) + + result = [event async for event in handler.on_message_send_stream(SendMessageRequest(), context)] + + assert result == [submitted] + + async def test_disconnected_stream_persists_the_terminal_and_retires_the_projection(): class Producer: async def stream(self, module_id, inputs, context): From e6f64b6bf23b1c23fb893c2a4d746a6f2b4b1304 Mon Sep 17 00:00:00 2001 From: tercel Date: Fri, 27 Nov 2026 12:44:47 +0800 Subject: [PATCH 11/36] fix(mcp): preserve unary tool results with progress Signed-off-by: tercel --- mcp/python/src/apcore_mcp/server/router.py | 15 ++-- .../server/test_router_stream_completion.py | 80 +++++++++++++++---- mcp/typescript/src/server/router.ts | 10 ++- .../tests/server/stream-completion.test.ts | 48 ++++++++++- 4 files changed, 128 insertions(+), 25 deletions(-) diff --git a/mcp/python/src/apcore_mcp/server/router.py b/mcp/python/src/apcore_mcp/server/router.py index 456d162c..f34ec0b2 100644 --- a/mcp/python/src/apcore_mcp/server/router.py +++ b/mcp/python/src/apcore_mcp/server/router.py @@ -586,14 +586,19 @@ async def _elicit_callback( has_progress = progress_token is not None and send_notification is not None if callable(self._open_completed_stream): - native_stream = getattr(getattr(descriptor, "annotations", None), "streaming", False) is True - if not has_progress and self._core_backend: + if self._core_backend: + # A progress token lets any module report progress. Only native + # streams should use Core's pre-after completion snapshot. try: - native_stream = isinstance(self._executor.registry.get(tool_name, version_hint), StreamingModule) + use_stream = isinstance(self._executor.registry.get(tool_name, version_hint), StreamingModule) except ModuleError: # Leave unknown or incompatible versions to the pipeline's normal error path. - native_stream = False - if has_progress or native_stream: + use_stream = False + else: + declared_streaming = getattr(getattr(descriptor, "annotations", None), "streaming", False) is True + use_stream = has_progress or declared_streaming + + if use_stream: return await self._handle_completed_stream( tool_name, arguments, progress_token, send_notification, context, version_hint ) diff --git a/mcp/python/tests/server/test_router_stream_completion.py b/mcp/python/tests/server/test_router_stream_completion.py index 70c6c3ec..6f802c14 100644 --- a/mcp/python/tests/server/test_router_stream_completion.py +++ b/mcp/python/tests/server/test_router_stream_completion.py @@ -3,7 +3,7 @@ from __future__ import annotations import json -from collections.abc import AsyncIterator +from collections.abc import AsyncIterator, Awaitable, Callable from contextlib import closing from typing import Any @@ -13,9 +13,11 @@ from apcore.builtin_steps import BuiltinOutputValidation from apcore.middleware import Middleware from mcp import ClientSession +from mcp.types import CallToolResult from pydantic import BaseModel from apcore_mcp import APCoreMCP +from apcore_mcp.helpers import report_progress from apcore_mcp.server.factory import MCPServerFactory from apcore_mcp.server.router import ExecutionRouter from apcore_mcp.server.transport import TransportManager @@ -67,34 +69,80 @@ def _setup( return registry, executor, router -@pytest.mark.parametrize(("send_progress", "annotated"), [(True, True), (False, True), (False, False)]) -@pytest.mark.skipif(not _HAS_COMPLETION, reason="run with the A2 wheel for the completion path") -async def test_real_mcp_final_result_uses_core_snapshot(send_progress: bool, annotated: bool) -> None: - tool = _StreamingTool() - if not annotated: - tool.annotations = ModuleAnnotations() - registry, _, router = _setup(tool) +async def _call_wire_tool( + registry: Registry, + router: ExecutionRouter, + module_id: str, + progress_callback: Callable[[float, float | None, str | None], Awaitable[None]] | None, +) -> CallToolResult: factory = MCPServerFactory() server = factory.create_server() factory.register_handlers(server, factory.build_tools(registry), router) init = factory.build_init_options(server, "test", "1") send_client, read_server = anyio.create_memory_object_stream(10) send_server, read_client = anyio.create_memory_object_stream(10) - messages: list[dict[str, Any]] = [] - - async def progress(_count: float, _total: float | None, text: str | None) -> None: - assert text is not None - messages.append(json.loads(text)) with anyio.fail_after(5): async with anyio.create_task_group() as group: group.start_soon(TransportManager()._run_scoped, server, read_server, send_server, init, "test") async with ClientSession(read_client, send_client) as session: await session.initialize() - result = await session.call_tool( - "test.stream", {}, progress_callback=progress if send_progress else None - ) + result = await session.call_tool(module_id, {}, progress_callback=progress_callback) group.cancel_scope.cancel() + return result + + +@pytest.mark.parametrize("send_progress", [False, True]) +async def test_progress_keeps_unary_output_after_middleware(send_progress: bool) -> None: + class UnaryTool: + input_schema = _Inputs + output_schema = {"type": "object", "properties": {"value": {"type": "integer"}}} + description = "Return an ordinary result and report explicit progress" + + def __init__(self) -> None: + self.calls = 0 + + async def execute(self, inputs: dict[str, Any], context: Context) -> dict[str, int]: + self.calls += 1 + await report_progress(context, 1, 2, "halfway") + return {"value": 1} + + class ChangeOutput(Middleware): + def after(self, module_id: str, inputs: dict[str, Any], output: dict[str, Any], context: Context) -> None: + output["value"] = 2 + + tool = UnaryTool() + registry = Registry() + registry.register("test.unary", tool) + executor = Executor(registry) + executor.use(ChangeOutput()) + router = ExecutionRouter(executor) + notices: list[tuple[float, float | None, str | None]] = [] + + async def progress(count: float, total: float | None, text: str | None) -> None: + notices.append((count, total, text)) + + result = await _call_wire_tool(registry, router, "test.unary", progress if send_progress else None) + assert not result.isError + assert json.loads(result.content[0].text) == {"value": 2} + assert notices == ([(1, 2, "halfway")] if send_progress else []) + assert tool.calls == 1 + + +@pytest.mark.parametrize(("send_progress", "annotated"), [(True, True), (False, True), (False, False)]) +@pytest.mark.skipif(not _HAS_COMPLETION, reason="run with the A2 wheel for the completion path") +async def test_real_mcp_final_result_uses_core_snapshot(send_progress: bool, annotated: bool) -> None: + tool = _StreamingTool() + if not annotated: + tool.annotations = ModuleAnnotations() + registry, _, router = _setup(tool) + messages: list[dict[str, Any]] = [] + + async def progress(_count: float, _total: float | None, text: str | None) -> None: + assert text is not None + messages.append(json.loads(text)) + + result = await _call_wire_tool(registry, router, "test.stream", progress if send_progress else None) assert not result.isError assert json.loads(result.content[0].text) == { diff --git a/mcp/typescript/src/server/router.ts b/mcp/typescript/src/server/router.ts index ff62d8e3..166098ed 100644 --- a/mcp/typescript/src/server/router.ts +++ b/mcp/typescript/src/server/router.ts @@ -687,10 +687,11 @@ export class ExecutionRouter { // ── Resolve versionHint from request metadata or descriptor ────── let versionHint: string | undefined = extra?.versionHint ?? extra?._meta?.apcore?.version; + const coreExecutor = isCoreExecutor(this._executor); let declaredStreaming = false; try { const descriptor = this._executor.registry?.getDefinition?.(toolName); - declaredStreaming = descriptor?.annotations?.streaming === true; + declaredStreaming = !coreExecutor && descriptor?.annotations?.streaming === true; if (!versionHint) { const metaHint = descriptor?.metadata?.versionHint; if (typeof metaHint === "string") { @@ -707,13 +708,16 @@ export class ExecutionRouter { // ── Streaming path ──────────────────────────────────────────────── const wantsProgress = progressToken !== undefined && sendNotification !== undefined; + const customStreamRequested = wantsProgress && !coreExecutor; + // Unary Core tools report progress through the context callback and + // return the ordinary call result, including after-middleware changes. const execution = typeof this._executor.streamWithCompletion === "function" && - (declaredStreaming || wantsProgress) + (declaredStreaming || customStreamRequested) ? this._executor.streamWithCompletion(toolName, args, context, versionHint) : null; // Retain the old structural extension point for custom executors. An // older Core instead uses one ordinary invocation with full validation. - const chunks = execution?.chunks ?? (wantsProgress && !isCoreExecutor(this._executor) + const chunks = execution?.chunks ?? (customStreamRequested ? this._executor.stream?.(toolName, args, context, versionHint) : undefined); if (chunks) { diff --git a/mcp/typescript/tests/server/stream-completion.test.ts b/mcp/typescript/tests/server/stream-completion.test.ts index ecd11073..1c125f7d 100644 --- a/mcp/typescript/tests/server/stream-completion.test.ts +++ b/mcp/typescript/tests/server/stream-completion.test.ts @@ -6,6 +6,7 @@ import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; import { expect, it } from "vitest"; +import { reportProgress } from "../../src/helpers.js"; import { MCPServerFactory } from "../../src/server/factory.js"; import { ExecutionRouter } from "../../src/server/router.js"; @@ -43,6 +44,15 @@ async function connect( const config = new sdk.Config({ stream: { max_merge_depth: 1 } }); const executor = throughFacade ? new sdk.APCore({ registry, config }) : new sdk.Executor({ registry, config }); if (fail === "after") executor.useAfter(() => { throw new Error("private-after-cause"); }); + const target = await connectClient(registry, executor, outputSchema); + return { ...target, counts: () => ({ calls, streams }) }; +} + +async function connectClient( + registry: core.Registry, + executor: core.Executor | core.APCore, + outputSchema: Record, +) { const factory = new MCPServerFactory(); const server = factory.createServer(); const router = new ExecutionRouter(executor as never, { outputSchemaMap: { [moduleId]: outputSchema } }); @@ -53,11 +63,47 @@ async function connect( await client.connect(clientTransport); return { client, - counts: () => ({ calls, streams }), async close() { await client.close(); await server.close(); }, }; } +it.each([false, true])("preserves unary output when progress is requested (facade: %s)", async (throughFacade) => { + const registry = new core.Registry(); + const outputSchema = { + type: "object", + properties: { message: { type: "string" } }, + required: ["message"], + }; + let calls = 0; + await registry.register(moduleId, { + description: "Return a result and report progress independently", + inputSchema: { type: "object" }, + outputSchema, + async execute(_inputs: Record, context: core.Context) { + calls++; + await reportProgress(context, 1, 2, "running"); + return { message: "from module" }; + }, + } as never); + const executor = throughFacade ? new core.APCore({ registry }) : new core.Executor({ registry }); + executor.useAfter(() => ({ message: "from middleware" })); + const target = await connectClient(registry, executor, outputSchema); + const progress: unknown[] = []; + try { + const args = { name: moduleId, arguments: {} }; + const ordinary = await target.client.callTool(args); + const subscribed = await target.client.callTool(args, undefined, { + onprogress: ({ message }) => { progress.push(message); }, + }); + expect(ordinary.structuredContent).toEqual({ message: "from middleware" }); + expect(subscribed.structuredContent).toEqual(ordinary.structuredContent); + expect(progress).toEqual(["running"]); + expect(calls).toBe(2); + } finally { + await target.close(); + } +}); + it.each([false, true])("uses an independent Core package (facade: %s)", async (throughFacade) => { const entry = await realpath(fileURLToPath(import.meta.resolve("apcore-js"))); const source = dirname(dirname(entry)); From aadb5d59779a7634ec778762c8a16848606a4883 Mon Sep 17 00:00:00 2001 From: tercel Date: Fri, 27 Nov 2026 12:46:33 +0800 Subject: [PATCH 12/36] fix(mcp): complete cleanup when requests are canceled Signed-off-by: tercel --- mcp/python/src/apcore_mcp/server/transport.py | 4 +- .../tests/server/test_request_cancellation.py | 66 ++++++++ mcp/rust/src/server/router.rs | 30 +++- mcp/rust/src/server/transport.rs | 142 ++++++++++++++++++ 4 files changed, 238 insertions(+), 4 deletions(-) diff --git a/mcp/python/src/apcore_mcp/server/transport.py b/mcp/python/src/apcore_mcp/server/transport.py index ce4f2056..42a42fa7 100644 --- a/mcp/python/src/apcore_mcp/server/transport.py +++ b/mcp/python/src/apcore_mcp/server/transport.py @@ -197,7 +197,9 @@ async def _scoped_session(self, session_id: str) -> AsyncIterator[None]: bridge = self._async_task_bridge if bridge is not None: try: - await bridge.cancel_session_tasks(session_id) + # The HTTP manager cancels the session's task group on shutdown. + with anyio.CancelScope(shield=True): + await bridge.cancel_session_tasks(session_id) except Exception: # noqa: BLE001 — disconnect must not propagate logger.warning( "cancel_session_tasks(%s) failed during transport teardown", diff --git a/mcp/python/tests/server/test_request_cancellation.py b/mcp/python/tests/server/test_request_cancellation.py index 7aa1201a..d80a4c4e 100644 --- a/mcp/python/tests/server/test_request_cancellation.py +++ b/mcp/python/tests/server/test_request_cancellation.py @@ -9,11 +9,13 @@ import anyio import httpx from apcore import Context, Executor, Identity, Registry +from apcore.async_task import AsyncTaskManager, TaskStatus from mcp import types from mcp.shared.message import SessionMessage from pydantic import BaseModel from apcore_mcp.auth.middleware import AuthMiddleware +from apcore_mcp.server.async_task_bridge import AsyncTaskBridge from apcore_mcp.server.factory import MCPServerFactory from apcore_mcp.server.router import ExecutionRouter from apcore_mcp.server.transport import TransportManager, transport_session_var @@ -199,6 +201,70 @@ async def call(session_headers: dict[str, str], name: str) -> httpx.Response: assert bridge.closed.empty() +async def test_http_manager_shutdown_finishes_session_task_cancellation() -> None: + class SuspendingTaskManager(AsyncTaskManager): + async def cancel(self, task_id: str) -> bool: + await asyncio.sleep(0) + return await super().cancel(task_id) + + module = _GatedModule() + registry = Registry() + registry.register("test.gated", module, metadata={"async": True}) + executor = Executor(registry=registry) + task_manager = SuspendingTaskManager(executor) + bridge = AsyncTaskBridge(task_manager) + factory = MCPServerFactory() + server = factory.create_server() + factory.register_handlers( + server, + factory.build_tools(registry), + ExecutionRouter(executor), + async_bridge=bridge, + descriptor_lookup=registry.get_definition, + ) + transport = TransportManager() + transport.set_async_task_bridge(bridge) + headers = {"Accept": "application/json, text/event-stream", "MCP-Protocol-Version": "2025-06-18"} + + try: + with anyio.fail_after(5): + async with ( + transport.build_streamable_http_app(server, factory.build_init_options(server, "test", "1")) as app, + httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client, + ): + initialized = await client.post( + "/mcp/", headers=headers, json={ + "jsonrpc": "2.0", "id": 1, "method": "initialize", + "params": { + "protocolVersion": "2025-06-18", "capabilities": {}, + "clientInfo": {"name": "test", "version": "1"}, + }, + }, + ) + initialized.raise_for_status() + headers["Mcp-Session-Id"] = initialized.headers["mcp-session-id"] + notification = await client.post( + "/mcp/", headers=headers, json={"jsonrpc": "2.0", "method": "notifications/initialized"} + ) + assert notification.status_code == 202 + response = await client.post("/mcp/", headers=headers, json={ + "jsonrpc": "2.0", "id": 2, "method": "tools/call", + "params": {"name": "test.gated", "arguments": {"name": "shutdown"}}, + }) + response.raise_for_status() + result = next( + json.loads(line[5:])["result"] for line in response.iter_lines() if line.startswith("data:") + ) + task_id = json.loads(result["content"][0]["text"])["task_id"] + assert await module.entered.get() == "shutdown" + + # Exit the HTTP manager with an open session, without sending DELETE. + status = task_manager.get_status(task_id) + assert status is not None and status.status == TaskStatus.CANCELLED + finally: + await task_manager.shutdown() + + async def test_authenticated_http_session_rejects_other_principals_before_dispatch() -> None: class HeaderAuthenticator: def authenticate(self, headers: dict[str, str]) -> Identity | None: diff --git a/mcp/rust/src/server/router.rs b/mcp/rust/src/server/router.rs index 2bb6f361..53c54a99 100644 --- a/mcp/rust/src/server/router.rs +++ b/mcp/rust/src/server/router.rs @@ -1864,8 +1864,15 @@ impl ExecutionRouter { version_hint, )?; Some( - self.consume_stream(tool_name, chunks, Some(completion), progress, Some(context)) - .await, + self.consume_stream( + tool_name, + chunks, + Some(completion), + progress, + Some(context), + apcore_ctx.cancel_token.as_ref(), + ) + .await, ) }) .await; @@ -1939,6 +1946,7 @@ impl ExecutionRouter { None, Some((progress_token, send_notification)), context, + apcore_ctx.and_then(|ctx| ctx.cancel_token.as_ref()), ) .await, ) @@ -1973,6 +1981,7 @@ impl ExecutionRouter { completion: Option, progress: Option<(&ProgressToken, &SendNotificationFn)>, context: Option<&Value>, + cancel_token: Option<&CancelToken>, ) -> StreamOutcome { use tokio_stream::StreamExt; let mut accumulated = Value::Object(serde_json::Map::new()); @@ -1998,7 +2007,22 @@ impl ExecutionRouter { "message": serde_json::to_string(&safe_chunk).unwrap_or_default(), } }); - if let Err(e) = send_notification(notification).await { + let send = send_notification(notification); + let sent = match cancel_token { + Some(token) => tokio::select! { + biased; + // The sink can wait for queue capacity while the + // Core stream is suspended between chunks. + _ = token.cancelled() => { + return Self::stream_error( + "Streaming execution cancelled (EXECUTION_CANCELLED).".into(), + ); + } + result = send => result, + }, + None => send.await, + }; + if let Err(e) = sent { tracing::debug!("Failed to send progress notification: {e}"); } } diff --git a/mcp/rust/src/server/transport.rs b/mcp/rust/src/server/transport.rs index c5e5bffe..b3443a66 100644 --- a/mcp/rust/src/server/transport.rs +++ b/mcp/rust/src/server/transport.rs @@ -3953,6 +3953,148 @@ mod tests { ); } + #[tokio::test] + async fn sse_cancellation_releases_a_stream_blocked_on_progress() { + use apcore::{ChunkStream, Context, Module, ModuleError, Registry, StreamingModule}; + use futures::StreamExt; + use serde_json::json; + use tokio::sync::{mpsc, Notify, Semaphore}; + + struct StreamingTool(Arc<()>); + + #[async_trait::async_trait] + impl Module for StreamingTool { + fn input_schema(&self) -> Value { + json!({"type": "object"}) + } + + fn output_schema(&self) -> Value { + json!({"type": "object"}) + } + + fn description(&self) -> &str { + "Return one native stream chunk" + } + + async fn execute(&self, _: Value, _: &Context) -> Result { + panic!("expected native streaming") + } + + fn as_streaming(&self) -> Option<&dyn StreamingModule> { + Some(self) + } + } + + impl StreamingModule for StreamingTool { + fn stream_typed(&self, _: Value, _: &Context) -> ChunkStream { + let lease = Arc::clone(&self.0); + Box::pin( + futures::stream::iter([Ok(json!({"value": 1}))]).map(move |chunk| { + let _lease = &lease; + chunk + }), + ) + } + } + + struct ObservedSseSink { + sink: SseSink, + sending: Arc, + } + + #[async_trait::async_trait] + impl OutboundSink for ObservedSseSink { + async fn send(&self, message: Value) -> Result<(), SessionError> { + assert_eq!(message["method"], "notifications/progress"); + self.sending.notify_one(); + self.sink.send(message).await + } + } + + let producer_lease = Arc::new(()); + let registry = Arc::new(Registry::new()); + registry + .register_module( + "test.stream", + Box::new(StreamingTool(Arc::clone(&producer_lease))), + ) + .unwrap(); + let bridge = crate::APCoreMCP::builder() + .backend(registry) + .build() + .unwrap(); + let (server, router, _, options, _, _) = bridge.build_server_components().unwrap(); + let handler = + Arc::new(crate::server::server::ServerHandler::from_server(&server, options).unwrap()); + let (events, pending_events) = mpsc::channel(1); + events + .try_send(Ok(axum::response::sse::Event::default())) + .unwrap(); + let sending = Arc::new(Notify::new()); + router.session_registry().insert(Arc::new(McpSession::new( + "test-session", + Arc::new(ObservedSseSink { + sink: SseSink { events }, + sending: Arc::clone(&sending), + }), + ))); + let request = json!({ + "jsonrpc": "2.0", "id": 1, "method": "tools/call", + "params": {"name": "test.stream", "arguments": {}} + }); + let mut blocked_request = request.clone(); + blocked_request["params"]["_meta"] = json!({"progressToken": "test"}); + stamp_session_id(&mut blocked_request, "test-session"); + let requests = DirectRequests::default(); + let slot = Arc::new(Semaphore::new(1)); + let registration = requests.register(&blocked_request); + let blocked = tokio::spawn({ + let requests = requests.clone(); + let handler = Arc::clone(&handler); + let slot = Arc::clone(&slot); + async move { + requests + .dispatch_registered( + handler.as_ref(), + blocked_request, + registration, + Some(slot), + ) + .await + } + }); + let deadline = std::time::Duration::from_secs(3); + tokio::time::timeout(deadline, sending.notified()) + .await + .expect("stream reached the full progress sink"); + assert_eq!(pending_events.len(), 1); + assert_eq!(slot.available_permits(), 0); + assert_eq!(Arc::strong_count(&producer_lease), 3); + + assert!(requests + .dispatch(handler.as_ref(), cancel_request(1.into())) + .await + .is_none()); + assert!(tokio::time::timeout(deadline, blocked) + .await + .expect("cancelled stream must release its slot without draining progress") + .unwrap() + .is_none()); + assert_eq!(pending_events.len(), 1); + assert_eq!(Arc::strong_count(&producer_lease), 2); + + let registration = requests.register(&request); + let response = tokio::time::timeout( + deadline, + requests.dispatch_registered(handler.as_ref(), request, registration, Some(slot)), + ) + .await + .expect("a subsequent request can use the same slot") + .unwrap(); + assert_eq!(response["id"], 1); + assert_eq!(response["result"]["isError"], false); + } + #[tokio::test] async fn stdio_carries_an_elicitation_round_trip() { let registry = Arc::new(SessionRegistry::new()); From 184cc1d3dacda132061bc6c7d836462beaca9c7f Mon Sep 17 00:00:00 2001 From: tercel Date: Fri, 27 Nov 2026 12:47:01 +0800 Subject: [PATCH 13/36] fix(a2a): scope active Rust tasks to their owner Signed-off-by: tercel --- a2a/rust/src/server/factory.rs | 4 +- a2a/rust/src/server/handlers.rs | 131 ++++++++++++++++++++++---------- 2 files changed, 93 insertions(+), 42 deletions(-) diff --git a/a2a/rust/src/server/factory.rs b/a2a/rust/src/server/factory.rs index ba7784f1..5d71cbf0 100644 --- a/a2a/rust/src/server/factory.rs +++ b/a2a/rust/src/server/factory.rs @@ -1,7 +1,7 @@ //! A2AServerFactory — wires all components into an axum Router (A2A 1.0). use std::collections::{HashMap, HashSet}; -use std::sync::{Arc, Mutex}; +use std::sync::Arc; use axum::{ extract::State, @@ -241,7 +241,7 @@ impl A2AServerFactory { agent_card: public_card_value, extended_card, explorer_card, - running_tasks: Arc::new(Mutex::new(HashMap::new())), + running_tasks: Default::default(), push_config_store, http: reqwest::Client::new(), }; diff --git a/a2a/rust/src/server/handlers.rs b/a2a/rust/src/server/handlers.rs index b091c6db..18ae0a2e 100644 --- a/a2a/rust/src/server/handlers.rs +++ b/a2a/rust/src/server/handlers.rs @@ -64,7 +64,7 @@ pub struct AppState { /// Filtered per caller like the extended card: the Explorer sits behind the /// auth middleware whenever one is configured. pub(crate) explorer_card: Arc, - pub(crate) running_tasks: Arc>>>, + pub(crate) running_tasks: RunningTasks, /// Per-task push-notification webhook configs /// (`tasks/pushNotificationConfig/*`), scoped to their owner by the store. pub(crate) push_config_store: Arc, @@ -826,13 +826,8 @@ async fn handle_send( let mut task = submitted_task(&task_id, &context_id); - let execution = register_execution(state, &task_id); - // Unregister the cancel token on every exit path (success, error, panic); - // a Drop guard mirrors handle_stream and avoids leaking the token. - let _cancel_guard = CancelGuard { - state: state.clone(), - task_id: task_id.clone(), - }; + let running = state.running_tasks.register(&task_id, ctx); + let execution = &running.execution; save_task(state, &task_id, serde_json::to_value(&task).unwrap(), ctx).await?; @@ -900,7 +895,7 @@ async fn handle_stream( }) => return failed_task_stream(state, task_id, context_id, ctx, id, message).await, }; - let execution = register_execution(state, &task_id); + let running = state.running_tasks.register(&task_id, ctx); // Reserve capacity for the terminal status and successful end marker. // Artifact backpressure must not block either after the decision is made. @@ -915,11 +910,7 @@ async fn handle_stream( let started = tokio::time::Instant::now(); tokio::spawn(async move { - // Unregister the cancel token on every exit path (success, error, panic). - let _cancel_guard = CancelGuard { - state: state2.clone(), - task_id: task_id.clone(), - }; + let execution = &running.execution; let mut task = submitted_task(&task_id, &context_id); if skill_known { task.status = TaskStatus::new(TaskState::Working); @@ -1188,7 +1179,7 @@ async fn handle_cancel( "Missing required parameter: id".to_string(), ))?; - let execution = state.running_tasks.lock().unwrap().get(task_id).cloned(); + let execution = state.running_tasks.get(task_id, ctx); let terminal = match &execution { Some(execution) => Some(execution.terminal.lock().await), None => None, @@ -1446,7 +1437,7 @@ fn canceled_by_client() -> TaskStatus { ) } -pub(crate) struct TaskExecution { +struct TaskExecution { token: CancelToken, client_canceled: watch::Sender>, terminal: tokio::sync::Mutex<()>, @@ -1458,35 +1449,54 @@ impl TaskExecution { } } -fn register_execution(state: &AppState, task_id: &str) -> Arc { - let (client_canceled, _) = watch::channel(None); - let execution = Arc::new(TaskExecution { - token: CancelToken::new(), - client_canceled, - terminal: tokio::sync::Mutex::new(()), - }); - state - .running_tasks - .lock() - .unwrap() - .insert(task_id.to_string(), execution.clone()); - execution +type RunningTaskKey = (OwnerId, String); + +/// Active executions use the same owner scope as the task store. +#[derive(Clone, Default)] +pub(crate) struct RunningTasks(Arc>>>); + +impl RunningTasks { + fn register(&self, task_id: &str, ctx: &CallContext) -> RunningTask { + let (client_canceled, _) = watch::channel(None); + let execution = Arc::new(TaskExecution { + token: CancelToken::new(), + client_canceled, + terminal: tokio::sync::Mutex::new(()), + }); + let key = (ctx.owner().clone(), task_id.to_string()); + self.0 + .lock() + .unwrap() + .insert(key.clone(), execution.clone()); + RunningTask { + tasks: self.clone(), + key, + execution, + } + } + + fn get(&self, task_id: &str, ctx: &CallContext) -> Option> { + let key = (ctx.owner().clone(), task_id.to_string()); + self.0.lock().unwrap().get(&key).cloned() + } } -/// Drop guard that unregisters a task's cancel token on all exit paths -/// (normal return, early return, or panic), preventing token leaks. -struct CancelGuard { - state: AppState, - task_id: String, +/// Removes the execution from the active registry when its worker exits. +struct RunningTask { + tasks: RunningTasks, + key: RunningTaskKey, + execution: Arc, } -impl Drop for CancelGuard { +impl Drop for RunningTask { fn drop(&mut self) { - self.state - .running_tasks - .lock() - .unwrap() - .remove(&self.task_id); + let mut tasks = self.tasks.0.lock().unwrap(); + if tasks + .get(&self.key) + .is_some_and(|execution| Arc::ptr_eq(execution, &self.execution)) + { + tasks.remove(&self.key); + } } } @@ -1495,6 +1505,47 @@ mod tests { use super::*; use crate::types::Part; + #[test] + fn active_tasks_are_scoped_to_their_store_owner() { + let tasks = RunningTasks::default(); + let alice = CallContext::from_identity(Some(&Identity::new( + "alice".into(), + "user".into(), + vec![], + HashMap::new(), + ))); + let anonymous = CallContext::anonymous(); + let named_run = tasks.register("task", &alice); + let anonymous_run = tasks.register("task", &anonymous); + + let found = tasks.get("task", &alice).unwrap(); + assert!(Arc::ptr_eq(&found, &named_run.execution)); + let found = tasks.get("task", &anonymous).unwrap(); + assert!(Arc::ptr_eq(&found, &anonymous_run.execution)); + + drop(named_run); + assert!(tasks.get("task", &alice).is_none()); + assert!(tasks.get("task", &anonymous).is_some()); + drop(anonymous_run); + assert!(tasks.get("task", &anonymous).is_none()); + } + + #[test] + fn active_task_cleanup_only_removes_its_registration() { + let tasks = RunningTasks::default(); + let ctx = CallContext::anonymous(); + let first = tasks.register("task", &ctx); + let replacement = tasks.register("task", &ctx); + + drop(first); + let found = tasks + .get("task", &ctx) + .expect("replacement is still active"); + assert!(Arc::ptr_eq(&found, &replacement.execution)); + drop(replacement); + assert!(tasks.get("task", &ctx).is_none()); + } + /// Extract the status message's text (if any). fn status_text(status: &TaskStatus) -> Option { status.message.as_ref().and_then(|m| { From ad256fdc80e5a3df8d81c010e578673ceee4295f Mon Sep 17 00:00:00 2001 From: tercel Date: Fri, 27 Nov 2026 13:29:42 +0800 Subject: [PATCH 14/36] fix(a2a): release Python terminal claims after save failure Signed-off-by: tercel --- a2a/python/CHANGELOG.md | 8 ++ a2a/python/pyproject.toml | 2 +- a2a/python/src/apcore_a2a/server/executor.py | 20 +++ a2a/python/src/apcore_a2a/server/factory.py | 22 +++- .../tests/server/test_server_factory.py | 124 +++++++++++++++++- 5 files changed, 167 insertions(+), 9 deletions(-) diff --git a/a2a/python/CHANGELOG.md b/a2a/python/CHANGELOG.md index 310f1f1e..dc6b2961 100644 --- a/a2a/python/CHANGELOG.md +++ b/a2a/python/CHANGELOG.md @@ -11,6 +11,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Provide an opt-in A2A event subscriber for migration from Core. Preserve a single terminal task state under cancellation or backpressure and reject incomplete OpenAPI registration. +### Changed + +- Require `a2a-sdk[http-server]` 1.1.2 or later so streaming clients receive task store write errors. + +### Fixed + +- Retire an unacknowledged terminal status when its writer exits after a save failure. A later request can complete the same task after the store recovers. + ## [0.8.7] - 2026-11-20 ### Changed diff --git a/a2a/python/pyproject.toml b/a2a/python/pyproject.toml index a493bda9..b226dd26 100644 --- a/a2a/python/pyproject.toml +++ b/a2a/python/pyproject.toml @@ -28,7 +28,7 @@ classifiers = [ dependencies = [ "apcore>=0.33.0,<=1.0.0a1", "apcore-toolkit==0.15.1a1", - "a2a-sdk[http-server]>=1.0.0", + "a2a-sdk[http-server]>=1.1.2", "starlette>=0.40.0", "uvicorn>=0.30.0", "httpx>=0.27.0", diff --git a/a2a/python/src/apcore_a2a/server/executor.py b/a2a/python/src/apcore_a2a/server/executor.py index 335a22a8..1289c973 100644 --- a/a2a/python/src/apcore_a2a/server/executor.py +++ b/a2a/python/src/apcore_a2a/server/executor.py @@ -154,6 +154,26 @@ def observe_task_saved(self, task: Task, context: ServerCallContext | None = Non if task.status == self._pending_terminal.get(key): self._pending_terminal.pop(key) + def observe_task_save_failed(self, task: Task, context: ServerCallContext) -> None: + """Release this execution's unacknowledged terminal after SDK persistence stops.""" + key = (task.id, task.context_id, _owner(context)) + status = self._pending_terminal.get(key) + run = self._running.get(key) + writer = asyncio.current_task() + if writer is None or (status is None and run is None): + return + + def retire_unacknowledged_status(_: asyncio.Task[Any]) -> None: + abandoned = status + if abandoned is None and run is not None: + abandoned = run.terminal + if abandoned is not None and self._pending_terminal.get(key) is abandoned: + self._pending_terminal.pop(key) + + # The SDK consumes each task's events in a background task. Its + # retries run there too, so a failed write alone does not end the claim. + writer.add_done_callback(retire_unacknowledged_status) + async def _execute(self, context: RequestContext, event_queue: EventQueue, run: _TaskExecution) -> None: # a2a-sdk 1.0: Establish the Task in the store before any TaskStatusUpdateEvent context_id = context.context_id or context.task_id diff --git a/a2a/python/src/apcore_a2a/server/factory.py b/a2a/python/src/apcore_a2a/server/factory.py index 65424f63..3a3ab624 100644 --- a/a2a/python/src/apcore_a2a/server/factory.py +++ b/a2a/python/src/apcore_a2a/server/factory.py @@ -2,13 +2,14 @@ from __future__ import annotations +import asyncio import contextlib import logging import time import warnings -from collections.abc import AsyncGenerator +from collections.abc import AsyncGenerator, Awaitable from dataclasses import dataclass -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING, Any, TypeVar from a2a.server.context import ServerCallContext from a2a.server.request_handlers import DefaultRequestHandler @@ -69,6 +70,7 @@ class _SDKVersionedTaskStore: logger = logging.getLogger(__name__) +_SaveResult = TypeVar("_SaveResult") class _ObservedTaskStore: @@ -82,8 +84,16 @@ def __getattr__(self, name: str) -> Any: return getattr(self._store, name) async def save(self, task: Task, context: ServerCallContext) -> None: - await self._store.save(task, context) + await self._save(task, context, self._store.save(task, context)) + + async def _save(self, task: Task, context: ServerCallContext, save: Awaitable[_SaveResult]) -> _SaveResult: + try: + result = await save + except (Exception, asyncio.CancelledError): + self._executor.observe_task_save_failed(task, context) + raise self._executor.observe_task_saved(task, context) + return result class _ObservedVersionedTaskStore(_ObservedTaskStore, _SDKVersionedTaskStore): @@ -96,9 +106,9 @@ async def save( prev_version: TaskVersion, context: ServerCallContext, ) -> TaskVersion: - version = await self._store.save(task, event=event, prev=prev, prev_version=prev_version, context=context) - self._executor.observe_task_saved(task, context) - return version + return await self._save( + task, context, self._store.save(task, event=event, prev=prev, prev_version=prev_version, context=context) + ) async def get(self, task_id: str, context: ServerCallContext) -> StoredTask | None: return await self._store.get(task_id, context) diff --git a/a2a/python/tests/server/test_server_factory.py b/a2a/python/tests/server/test_server_factory.py index 6781232b..f9cf2e4c 100644 --- a/a2a/python/tests/server/test_server_factory.py +++ b/a2a/python/tests/server/test_server_factory.py @@ -1,6 +1,7 @@ """Tests for A2AServerFactory.""" import asyncio +import contextlib import json from unittest.mock import AsyncMock, MagicMock @@ -9,7 +10,15 @@ from a2a.server.context import ServerCallContext from a2a.server.events.event_queue_v2 import EventQueueSource from a2a.server.request_handlers import DefaultRequestHandler -from a2a.types import AgentCard, CancelTaskRequest, SendMessageRequest, Task, TaskState, TaskStatusUpdateEvent +from a2a.types import ( + AgentCard, + CancelTaskRequest, + GetTaskRequest, + SendMessageRequest, + Task, + TaskState, + TaskStatusUpdateEvent, +) from a2a.utils.errors import TaskNotCancelableError from apcore import Executor, Registry from pydantic import BaseModel @@ -20,7 +29,13 @@ from apcore_a2a.adapters.parts import PartConverter from apcore_a2a.adapters.schema import SchemaConverter from apcore_a2a.server.executor import ApCoreAgentExecutor -from apcore_a2a.server.factory import A2AServerFactory, A2ATaskStore, _ObservedTaskStore, _TerminalAwareRequestHandler +from apcore_a2a.server.factory import ( + A2AServerFactory, + A2ATaskStore, + _ObservedTaskStore, + _ObservedVersionedTaskStore, + _TerminalAwareRequestHandler, +) @pytest.fixture @@ -356,6 +371,111 @@ async def save(self, task, context): assert agent.project_terminal_status(submitted, context) is submitted +@pytest.mark.parametrize("versioned_store", [False, True]) +async def test_failed_terminal_write_does_not_block_a_recovered_task(versioned_store): + class Producer: + calls = 0 + + async def call_async(self, module_id, inputs, context): + self.calls += 1 + if self.calls == 1: + raise RuntimeError("synthetic execution failure") + return {"value": "recovered"} + + class RecoveringStore(A2ATaskStore): + def __init__(self): + super().__init__() + self.first_write_started = asyncio.Event() + self.allow_first_write = asyncio.Event() + self.backup_write_started = asyncio.Event() + self.allow_backup_write = asyncio.Event() + self.failed_writer = None + self.failed_writes = 0 + self.completed_writes = 0 + + async def save(self, task, context): + if task.status.state == TaskState.TASK_STATE_FAILED: + self.failed_writes += 1 + if self.failed_writes == 1: + self.failed_writer = asyncio.current_task() + self.first_write_started.set() + await self.allow_first_write.wait() + else: + self.backup_write_started.set() + await self.allow_backup_write.wait() + raise OSError("synthetic terminal write failure") + await super().save(task, context) + if task.status.state == TaskState.TASK_STATE_COMPLETED: + self.completed_writes += 1 + + store = RecoveringStore() + producer = Producer() + agent = ApCoreAgentExecutor( + producer, PartConverter(SchemaConverter()), ErrorMapper(), track_terminal_status=True, + ) + if versioned_store: + cluster = pytest.importorskip("a2a.server.cluster.task_store") + observed_store = _ObservedVersionedTaskStore(cluster.LegacyTaskStoreAdapter(store), agent) + else: + observed_store = _ObservedTaskStore(store, agent) + handler = _TerminalAwareRequestHandler( + agent_executor=agent, + task_store=observed_store, + agent_card=AgentCard(name="test", capabilities={"streaming": True}), + ) + context = ServerCallContext() + request = SendMessageRequest( + message={ + "message_id": "terminal-write-fails", + "role": "ROLE_USER", + "parts": [{"text": "test"}], + "metadata": {"skillId": "test.recovering-store"}, + }, + ) + async with asyncio.timeout(2), contextlib.aclosing(handler.on_message_send_stream(request, context)) as stream: + submitted = await anext(stream) + assert isinstance(submitted, Task) + query = GetTaskRequest(id=submitted.id) + async def drain_stream(): + async for _ in stream: + pass + + subscriber = asyncio.create_task(drain_stream()) + backup_write = asyncio.create_task(store.backup_write_started.wait()) + try: + try: + await store.first_write_started.wait() + assert (await handler.on_get_task(query, context)).status.state == TaskState.TASK_STATE_FAILED + assert (await store.get(submitted.id, context)).status.state == TaskState.TASK_STATE_SUBMITTED + store.allow_first_write.set() + done, _ = await asyncio.wait( + (store.failed_writer, backup_write, subscriber), return_when=asyncio.FIRST_COMPLETED, + ) + if backup_write in done: + assert (await handler.on_get_task(query, context)).status.state == TaskState.TASK_STATE_FAILED + finally: + store.allow_first_write.set() + store.allow_backup_write.set() + with pytest.raises(OSError, match="synthetic terminal write failure"): + await subscriber + await asyncio.gather(store.failed_writer, return_exceptions=True) + finally: + backup_write.cancel() + subscriber.cancel() + await asyncio.gather(backup_write, subscriber, return_exceptions=True) + assert (await handler.on_get_task(query, context)).status.state == TaskState.TASK_STATE_SUBMITTED + request.message.message_id = "retry-after-store-recovery" + request.message.task_id = submitted.id + request.message.context_id = submitted.context_id + retry = [event async for event in handler.on_message_send_stream(request, context)] + assert [ + event.status.state for event in retry if isinstance(event, TaskStatusUpdateEvent) + ] == [TaskState.TASK_STATE_COMPLETED] + assert (await store.get(submitted.id, context)).status.state == TaskState.TASK_STATE_COMPLETED + assert producer.calls == 2 + assert store.completed_writes == 1 + + async def test_cancel_reports_one_matching_terminal_to_both_rpc_and_stream(): class Producer: async def stream(self, module_id, inputs, context): From adb3ce77301a6fc5a888a864dc64715f2a39d825 Mon Sep 17 00:00:00 2001 From: tercel Date: Fri, 27 Nov 2026 13:29:43 +0800 Subject: [PATCH 15/36] fix(a2a): coordinate TypeScript task terminal outcomes Signed-off-by: tercel --- a2a/typescript/src/event-subscriber.ts | 4 +- a2a/typescript/src/server/executor.ts | 371 +++++++----------- a2a/typescript/src/server/factory.ts | 13 +- a2a/typescript/src/server/task-persistence.ts | 176 +++++++++ .../conformance/event-subscriber.test.ts | 10 + a2a/typescript/tests/server/executor.test.ts | 74 +++- a2a/typescript/tests/server/factory.test.ts | 70 ++++ 7 files changed, 472 insertions(+), 246 deletions(-) create mode 100644 a2a/typescript/src/server/task-persistence.ts diff --git a/a2a/typescript/src/event-subscriber.ts b/a2a/typescript/src/event-subscriber.ts index 80fcd5c6..55d69fba 100644 --- a/a2a/typescript/src/event-subscriber.ts +++ b/a2a/typescript/src/event-subscriber.ts @@ -26,7 +26,9 @@ export class A2AEventSubscriber implements EventSubscriber { auth?: AuthHeaders, options: A2AEventSubscriberOptions = {}, ) { - this.subscriberId = options.id ?? `a2a-${nextSubscriberId++}`; + // Core's legacy allocator uses unpadded decimal IDs. Reserve the + // zero-prefixed range for the new transport while both can coexist. + this.subscriberId = options.id ?? `a2a-0${nextSubscriberId++}`; this.retry = options.retry; this.timeoutMs = options.timeoutMs ?? 5000; this.skillId = options.skillId ?? "apevo.event_receiver"; diff --git a/a2a/typescript/src/server/executor.ts b/a2a/typescript/src/server/executor.ts index 3654f038..095ef3e9 100644 --- a/a2a/typescript/src/server/executor.ts +++ b/a2a/typescript/src/server/executor.ts @@ -1,7 +1,8 @@ import { v4 as uuidv4 } from "uuid"; -import type { CancelToken } from "apcore-js"; +import { CancelToken, Context } from "apcore-js"; import { Artifact, Part, Role, TaskState } from "@a2a-js/sdk"; import type { Message, TaskStatus } from "@a2a-js/sdk"; +import { TaskNotCancelableError } from "@a2a-js/sdk/errors"; import { AgentEvent, type AgentExecutor, @@ -111,6 +112,25 @@ export interface ApCoreAgentExecutorOptions { discloseRefusalReason?: boolean; } +const OUTCOME_STATES = { + completed: TaskState.TASK_STATE_COMPLETED, + failed: TaskState.TASK_STATE_FAILED, + canceled: TaskState.TASK_STATE_CANCELED, + "input-required": TaskState.TASK_STATE_INPUT_REQUIRED, + rejected: TaskState.TASK_STATE_REJECTED, +} as const; + +type TaskOutcome = keyof typeof OUTCOME_STATES; +type TerminalOutcome = Exclude; + +interface TaskExecution { + readonly taskId: string; + readonly contextId: string; + readonly token: CancelToken; + readonly clientCancellation: AbortController; + terminal?: TerminalOutcome; +} + export class ApCoreAgentExecutor implements AgentExecutor { private executor: ApCoreAgentExecutorOptions["executor"]; private partConverter: PartConverter; @@ -119,8 +139,8 @@ export class ApCoreAgentExecutor implements AgentExecutor { // here in milliseconds for setTimeout / global_deadline arithmetic. private executionTimeoutMs: number; private onStateChange?: (oldState: string, newState: string) => void; - // P0-B: CancelToken map keyed by taskId - private cancelTokens = new Map(); + // The SDK allocates one event bus per task and reuses it across interrupted turns. + private readonly executions = new WeakMap(); private errorMapper: ErrorMapper; constructor(opts: ApCoreAgentExecutorOptions) { @@ -145,11 +165,19 @@ export class ApCoreAgentExecutor implements AgentExecutor { } async execute(context: RequestContext, eventBus: ExecutionEventBus): Promise { - // 1. Initialize task in the event bus so ResultManager can track it - const contextId = context.contextId || context.taskId; + // Install the cancellation state before exposing the task. + const { taskId } = context; + const contextId = context.contextId || taskId; + const task: TaskExecution = { + taskId, + contextId, + token: new CancelToken(), + clientCancellation: new AbortController(), + }; + this.executions.set(eventBus, task); eventBus.publish( AgentEvent.task({ - id: context.taskId, + id: taskId, contextId, status: makeStatus(TaskState.TASK_STATE_SUBMITTED), artifacts: [], @@ -158,12 +186,13 @@ export class ApCoreAgentExecutor implements AgentExecutor { }), ); + if (task.terminal !== undefined) return; + // 2. Get skillId from message metadata const metadata = context.userMessage?.metadata ?? {}; const skillId = metadata.skillId as string | undefined; if (!skillId) { - this.notify("submitted", "failed"); - this.publishFailed(context, eventBus, "Missing required parameter: metadata.skillId"); + this.publishOutcome(task, eventBus, "submitted", "failed", "Missing required parameter: metadata.skillId"); return; } @@ -177,13 +206,11 @@ export class ApCoreAgentExecutor implements AgentExecutor { } catch { // Registry unavailable: cannot confirm the skill, so fail closed rather // than proceeding optimistically. - this.notify("submitted", "failed"); - this.publishFailed(context, eventBus, `Skill not found: ${skillId}`); + this.publishOutcome(task, eventBus, "submitted", "failed", `Skill not found: ${skillId}`); return; } if (!known.includes(skillId)) { - this.notify("submitted", "failed"); - this.publishFailed(context, eventBus, `Skill not found: ${skillId}`); + this.publishOutcome(task, eventBus, "submitted", "failed", `Skill not found: ${skillId}`); return; } } @@ -203,126 +230,73 @@ export class ApCoreAgentExecutor implements AgentExecutor { try { inputs = this.partConverter.partsToInput(parts, descriptor); } catch (e) { - this.notify("submitted", "failed"); - this.publishFailed(context, eventBus, String(e)); + this.publishOutcome(task, eventBus, "submitted", "failed", String(e)); return; } - // 5. Build apcore context with identity and CancelToken (P0-B) - const identity = getAuthIdentity(); - let token: CancelToken | undefined; - let apcoreCtx: unknown = undefined; - try { - const { Context, CancelToken: CoreCancelToken } = await import("apcore-js"); - // P0-B: create a CancelToken per task and store it - token = new CoreCancelToken(); - this.cancelTokens.set(context.taskId, token); - // Map the A2A executionTimeout onto apcore's global_deadline so apcore - // can stop cooperatively between streaming chunks / pipeline steps. - // apcore-js >= 0.31.0 (spec D-99/D-100/D-101) makes the first-class - // `Context.globalDeadline` field (epoch SECONDS) the pipeline's only - // source for this: `BuiltinContextCreation` no longer reads - // data[CTX_GLOBAL_DEADLINE] at all, so seeding it via `data` — the - // workaround for apcore-js's own pre-0.31 bug, where the field was - // documented but never consulted — is now silently inert and the - // task's execution timeout would go unenforced by apcore's pipeline. - // Context.create(identity, traceParent, cancelToken, data, services, globalDeadline) - const globalDeadline = (Date.now() + this.executionTimeoutMs) / 1000; - apcoreCtx = identity - ? Context.create(identity, null, token, undefined, undefined, globalDeadline) - : Context.create(null, null, token, undefined, undefined, globalDeadline); - } catch { - // apcore-js Context/CancelToken not available in this environment - } - - // 6. Check if executor supports streaming (P0-A) + // Check if executor supports streaming (P0-A) const streamFn = (this.executor as { stream?: unknown }).stream; const canStream = typeof streamFn === "function" && (streamFn.constructor?.name === "AsyncGeneratorFunction" || Object.prototype.toString.call(streamFn) === "[object AsyncGeneratorFunction]"); - // 7. Execute with timeout + // Start both the host budget and Core's cooperative deadline for this turn. this.notify("submitted", "working"); + if (task.terminal !== undefined) return; const inputObj = typeof inputs === "string" ? { text: inputs } : inputs; + const globalDeadline = (Date.now() + this.executionTimeoutMs) / 1000; + // Only a client cancellation can preempt the host wait. Core may + // signal its own token before reporting a typed timeout or cancellation. + const clientSignal = task.clientCancellation.signal; try { + const apcoreCtx = Context.create(getAuthIdentity() ?? null, null, task.token, undefined, undefined, globalDeadline); if (canStream) { - await this.executeStreaming(context, eventBus, skillId, inputObj, apcoreCtx, token?.signal); + await this.executeStreaming(eventBus, task, skillId, inputObj, apcoreCtx); } else { - // Non-streaming path (callAsync) - let output: Record; - const coro = apcoreCtx - ? this.executor.callAsync(skillId, inputObj, apcoreCtx) - : this.executor.callAsync(skillId, inputObj); - output = await withTimeout(coro, this.executionTimeoutMs, token?.signal); - if (token?.signal.aborted) return; - - // 8. Publish artifact + completed - const artifact = this.partConverter.outputToParts(output, context.taskId); - - eventBus.publish( - AgentEvent.artifactUpdate({ - taskId: context.taskId, - contextId, - artifact, - append: false, - lastChunk: true, - metadata: undefined, - }), + const output = await withTimeout( + this.executor.callAsync(skillId, inputObj, apcoreCtx), this.executionTimeoutMs, clientSignal, ); + if (clientSignal.aborted) return; + if (task.token.signal.aborted) { + this.publishOutcome(task, eventBus, "working", "canceled", "Execution cancelled"); + return; + } - this.publishCompleted(context, eventBus); + const artifact = this.partConverter.outputToParts(output, taskId); + eventBus.publish(AgentEvent.artifactUpdate({ + taskId, + contextId, + artifact, + append: false, + lastChunk: true, + metadata: undefined, + })); + this.publishOutcome(task, eventBus, "working", "completed"); } } catch (e: unknown) { - // cancelTask owns the CANCELED event after explicitly signaling the token. - if (token?.signal.aborted) return; - if (e instanceof TimeoutError) { - token?.cancel(); - this.notify("working", "failed"); - this.publishFailed(context, eventBus, "Execution timed out"); + if (task.terminal !== undefined) return; + const code = (e as { code?: string } | null)?.code; + if (e instanceof TimeoutError || code === "MODULE_TIMEOUT") { + this.publishOutcome(task, eventBus, "working", "failed", "Execution timed out"); + task.token.cancel(); return; } - const code = (e as { code?: string }).code; - if (code === "MODULE_TIMEOUT") { - // apcore enforced global_deadline (streaming or cooperative step) - token?.cancel(); - this.notify("working", "failed"); - this.publishFailed(context, eventBus, "Execution timed out"); - return; - } - if (code === "EXECUTION_CANCELLED") { - this.notify("working", "canceled"); - this.publishCanceled(context, eventBus, "Execution cancelled"); + if (code === "EXECUTION_CANCELLED" || task.token.signal.aborted) { + this.publishOutcome(task, eventBus, "working", "canceled", "Execution cancelled"); return; } if (code === "APPROVAL_PENDING") { - // A resumable pause, not a refusal: the message carries the approvalId - // the caller resumes with (srs FR-EXE-002). Must not be swept in with - // the governance codes below — `rejected` is terminal, so re-coding it - // would end the conversation. - this.notify("working", "input-required"); - this.publishInputRequired(context, eventBus, String(e)); + this.publishOutcome(task, eventBus, "working", "input-required", String(e)); return; } if (isGovernanceRefusal(code)) { - // A2A 1.0 defines `rejected` as terminal, and a policy refusal is what - // it describes (srs FR-ERR-012). `failed` said only "something broke", - // which for a refusal is both wrong and an invitation to retry. This is - // the surface that matters on message/send, where the response is a - // JSON-RPC `result` and the error code never reaches the caller at all. - this.notify("working", "rejected"); - this.publishRejected(context, eventBus, failureText(e, this.errorMapper)); + this.publishOutcome(task, eventBus, "working", "rejected", failureText(e, this.errorMapper)); return; } - console.error(`Execution failed for task ${context.taskId} skill ${skillId}:`, e); - this.notify("working", "failed"); - this.publishFailed(context, eventBus, failureText(e, this.errorMapper)); - return; - } finally { - // Clean up the cancel token on every exit path (matches Python's - // finally / Rust's Drop guard). - this.cancelTokens.delete(context.taskId); + console.error(`Execution failed for task ${taskId} skill ${skillId}:`, e); + this.publishOutcome(task, eventBus, "working", "failed", failureText(e, this.errorMapper)); } } @@ -331,177 +305,108 @@ export class ApCoreAgentExecutor implements AgentExecutor { * TaskArtifactUpdateEvent for each chunk, then publishes completed. */ private async executeStreaming( - context: RequestContext, eventBus: ExecutionEventBus, + task: TaskExecution, moduleId: string, inputs: Record, - apcoreCtx: unknown, - signal?: AbortSignal, + apcoreCtx: Context, ): Promise { - const contextId = context.contextId || context.taskId; - const artifactId = `art-${context.taskId}`; + const { taskId, contextId } = task; + const clientSignal = task.clientCancellation.signal; + const artifactId = `art-${taskId}`; let chunkIndex = 0; const streamFn = ( this.executor as unknown as { - stream: (moduleId: string, inputs: Record, ctx?: unknown) => AsyncGenerator>; + stream: (moduleId: string, inputs: Record, ctx: Context) => AsyncGenerator>; } ).stream; - const gen = apcoreCtx - ? streamFn.call(this.executor, moduleId, inputs, apcoreCtx) - : streamFn.call(this.executor, moduleId, inputs); + const iterator = streamFn.call(this.executor, moduleId, inputs, apcoreCtx)[Symbol.asyncIterator](); // The host uses a monotonic total budget even if the producer ignores // apcore's cooperative deadline. const deadline = performance.now() + this.executionTimeoutMs; - const iterator = gen[Symbol.asyncIterator](); let exhausted = false; try { for (;;) { - if (signal?.aborted) return; + if (clientSignal.aborted) return; const remaining = deadline - performance.now(); if (remaining <= 0) throw new TimeoutError(); - const next = await withTimeout(iterator.next(), remaining, signal); - if (signal?.aborted) return; + const next = await withTimeout(iterator.next(), remaining, clientSignal); + if (clientSignal.aborted) return; + if (task.token.signal.aborted) { + this.publishOutcome(task, eventBus, "working", "canceled", "Execution cancelled"); + return; + } if (next.done) { exhausted = true; break; } - const artifact = this.partConverter.outputToParts(next.value, context.taskId); - eventBus.publish( - AgentEvent.artifactUpdate({ - taskId: context.taskId, - contextId, - artifact: { ...artifact, artifactId }, - append: chunkIndex > 0, - lastChunk: false, - metadata: undefined, - }), - ); + const artifact = this.partConverter.outputToParts(next.value, taskId); + eventBus.publish(AgentEvent.artifactUpdate({ + taskId, + contextId, + artifact: { ...artifact, artifactId }, + append: chunkIndex > 0, + lastChunk: false, + metadata: undefined, + })); chunkIndex++; } } finally { if (!exhausted) { - // AsyncGenerator.return() queues behind any pending next(). A late - // value or cleanup failure must never change the task's terminal state. + // AsyncGenerator.return() waits behind any pending next(). void Promise.resolve().then(() => iterator.return?.(undefined)).catch((error: unknown) => { - console.warn(`[apcore-a2a] Stream cleanup failed for task ${context.taskId}`, error); + console.warn(`[apcore-a2a] Stream cleanup failed for task ${taskId}`, error); }); } } - // Signal end of stream with lastChunk: true - eventBus.publish( - AgentEvent.artifactUpdate({ - taskId: context.taskId, - contextId, - artifact: Artifact.fromJSON({ artifactId, parts: [] }), - append: chunkIndex > 0, - lastChunk: true, - metadata: undefined, - }), - ); - - if (!signal?.aborted) this.publishCompleted(context, eventBus); + eventBus.publish(AgentEvent.artifactUpdate({ + taskId, + contextId, + artifact: Artifact.fromJSON({ artifactId, parts: [] }), + append: chunkIndex > 0, + lastChunk: true, + metadata: undefined, + })); + this.publishOutcome(task, eventBus, "working", "completed"); } async cancelTask(taskId: string, eventBus: ExecutionEventBus): Promise { - // P0-B: Cancel the running execution via CancelToken - const token = this.cancelTokens.get(taskId); - if (token) { - token.cancel(); - this.cancelTokens.delete(taskId); + const task = this.executions.get(eventBus); + if (task?.taskId === taskId) { + if (task.terminal === "canceled") { + // The SDK's new cancellation listener joined after the terminal event. + queueMicrotask(() => eventBus.finished()); + return; + } + if (task.terminal !== undefined) throw new TaskNotCancelableError(`Task not cancelable: ${taskId}`); + this.publishOutcome(task, eventBus, "working", "canceled", "Canceled by client"); + task.clientCancellation.abort(); + task.token.cancel(); + return; } - eventBus.publish( - AgentEvent.statusUpdate({ - taskId, - contextId: taskId, - status: makeStatus(TaskState.TASK_STATE_CANCELED, textMessage("Canceled by client")), - metadata: undefined, - }), - ); - - this.notify("working", "canceled"); + this.publishOutcome({ taskId, contextId: taskId }, eventBus, "working", "canceled", "Canceled by client"); } - private publishCompleted(context: RequestContext, eventBus: ExecutionEventBus): void { - const contextId = context.contextId || context.taskId; - eventBus.publish( - AgentEvent.statusUpdate({ - taskId: context.taskId, - contextId, - status: makeStatus(TaskState.TASK_STATE_COMPLETED), - metadata: undefined, - }), - ); - - this.notify("working", "completed"); - } - - private publishFailed( - context: RequestContext, - eventBus: ExecutionEventBus, - message: string, - ): void { - const contextId = context.contextId || context.taskId; - eventBus.publish( - AgentEvent.statusUpdate({ - taskId: context.taskId, - contextId, - status: makeStatus(TaskState.TASK_STATE_FAILED, textMessage(message)), - metadata: undefined, - }), - ); - } - - /** Emit REJECTED status for a governance refusal (srs FR-ERR-012). */ - private publishRejected( - context: RequestContext, - eventBus: ExecutionEventBus, - message: string, - ): void { - const contextId = context.contextId || context.taskId; - eventBus.publish( - AgentEvent.statusUpdate({ - taskId: context.taskId, - contextId, - status: makeStatus(TaskState.TASK_STATE_REJECTED, textMessage(message)), - metadata: undefined, - }), - ); - } - - private publishInputRequired( - context: RequestContext, + private publishOutcome( + task: Pick, eventBus: ExecutionEventBus, - message: string, + previous: "submitted" | "working", + outcome: TaskOutcome, + message?: string, ): void { - const contextId = context.contextId || context.taskId; - eventBus.publish( - AgentEvent.statusUpdate({ - taskId: context.taskId, - contextId, - status: makeStatus(TaskState.TASK_STATE_INPUT_REQUIRED, textMessage(message)), - metadata: undefined, - }), - ); - } - - private publishCanceled( - context: RequestContext, - eventBus: ExecutionEventBus, - message: string, - ): void { - const contextId = context.contextId || context.taskId; - eventBus.publish( - AgentEvent.statusUpdate({ - taskId: context.taskId, - contextId, - status: makeStatus(TaskState.TASK_STATE_CANCELED, textMessage(message)), - metadata: undefined, - }), - ); + if (task.terminal !== undefined) return; + if (outcome !== "input-required") task.terminal = outcome; + eventBus.publish(AgentEvent.statusUpdate({ + taskId: task.taskId, + contextId: task.contextId, + status: makeStatus(OUTCOME_STATES[outcome], message === undefined ? undefined : textMessage(message)), + metadata: undefined, + })); + this.notify(previous, outcome); } } diff --git a/a2a/typescript/src/server/factory.ts b/a2a/typescript/src/server/factory.ts index 672d47d4..1bcbdeef 100644 --- a/a2a/typescript/src/server/factory.ts +++ b/a2a/typescript/src/server/factory.ts @@ -2,8 +2,6 @@ import express from "express"; import type { Express, Request, Response } from "express"; import type { AgentCard, AgentCapabilities } from "@a2a-js/sdk"; import { - DefaultRequestHandler, - DefaultExecutionEventBusManager, InMemoryTaskStore, type ServerCallContext, type TaskStore, @@ -33,6 +31,7 @@ import { getAuthIdentity } from "../auth/storage.js"; import { PartConverter } from "../adapters/parts.js"; import { ErrorMapper } from "../adapters/errors.js"; import { ApCoreAgentExecutor } from "./executor.js"; +import { A2ATaskRequestHandler } from "./task-persistence.js"; import { createAuthMiddleware } from "../auth/middleware.js"; import { anonymousContext, identityOf, identityUserBuilder } from "./context.js"; import { createExplorerRouter } from "../explorer/handler.js"; @@ -343,15 +342,7 @@ export class A2AServerFactory { Promise.resolve(buildExtendedCard(fullCard, executor, identityOf(context))) : undefined; - const requestHandler = new DefaultRequestHandler( - agentCard, - taskStore, - apcoreExecutor, - new DefaultExecutionEventBusManager(), - undefined, - undefined, - extendedAgentCardProvider, - ); + const requestHandler = new A2ATaskRequestHandler(agentCard, taskStore, apcoreExecutor, extendedAgentCardProvider); // Build Express app const app = express(); diff --git a/a2a/typescript/src/server/task-persistence.ts b/a2a/typescript/src/server/task-persistence.ts new file mode 100644 index 00000000..d8ed6654 --- /dev/null +++ b/a2a/typescript/src/server/task-persistence.ts @@ -0,0 +1,176 @@ +import { AsyncLocalStorage } from "node:async_hooks"; +import { TaskState } from "@a2a-js/sdk"; +import type { + AgentCard, CancelTaskRequest, SendMessageRequest, StreamResponse, Task, TaskStatus, +} from "@a2a-js/sdk"; +import { DefaultRequestHandler, resolveUserScope } from "@a2a-js/sdk/server"; +import type { + AgentExecutionEvent, AgentExecutor, ExecutionEventBus, ExtendedAgentCardProvider, RequestContext, ServerCallContext, TaskStore, +} from "@a2a-js/sdk/server"; + +const TERMINAL_STATES = new Set([ + TaskState.TASK_STATE_COMPLETED, + TaskState.TASK_STATE_FAILED, + TaskState.TASK_STATE_CANCELED, + TaskState.TASK_STATE_REJECTED, +]); + +function isTerminal(state: TaskState | undefined): boolean { + return state !== undefined && TERMINAL_STATES.has(state); +} + +interface TerminalClaim { + readonly context: ServerCallContext; + readonly contextId: string; + readonly status: TaskStatus; + writes: number; +} + +function taskKey(taskId: string, context: ServerCallContext): string { + return JSON.stringify([context.tenant ?? null, resolveUserScope(context), taskId]); +} + +/** Bridge the gap between emitting a terminal status and committing it to storage. */ +class TaskPersistence implements TaskStore { + private readonly cancelRequests = new AsyncLocalStorage(); + private readonly terminalClaims = new Map(); + private readonly claimKeys = new WeakMap>(); + private readonly abandoned = new WeakSet(); + private readonly watches = new WeakMap void>(); + + constructor(private readonly store: TaskStore) {} + + cancel(taskId: string, run: () => Promise): Promise { + return this.cancelRequests.run(taskId, run); + } + + observe(request: RequestContext, bus: ExecutionEventBus): void { + const { taskId, context } = request; + this.watches.get(bus)?.(); + const release = () => { + bus.off("event", onEvent); + bus.off("finished", release); + this.watches.delete(bus); + }; + const onEvent = (event: AgentExecutionEvent): void => { + const update = event.kind === "statusUpdate" ? event.data : undefined; + const status = update?.status; + if (update?.taskId !== taskId || !status || !TERMINAL_STATES.has(status.state)) return; + release(); + if (this.abandoned.has(context)) return; + const key = taskKey(taskId, context); + if (this.terminalClaims.has(key)) return; + this.terminalClaims.set(key, { context, contextId: update.contextId, status, writes: 0 }); + const keys = this.claimKeys.get(context) ?? new Set(); + keys.add(key); + this.claimKeys.set(context, keys); + }; + this.watches.set(bus, release); + bus.on("event", onEvent); + bus.on("finished", release); + } + + async load(taskId: string, context: ServerCallContext): Promise { + let task: Task | undefined; + try { + task = await this.store.load(taskId, context); + } catch (error) { + this.abandon(context); + throw error; + } + if (!task || this.cancelRequests.getStore() !== taskId || isTerminal(task.status?.state)) { + return task; + } + const claim = this.terminalClaims.get(taskKey(taskId, context)); + // Only an already-authorized task may resolve to a pending terminal outcome. + if (!claim || claim.contextId !== task.contextId) return task; + const status = structuredClone(claim.status); + const history = status.message && !task.history?.some(message => message.messageId === status.message?.messageId) + ? [...(task.history ?? []), status.message] + : task.history; + return { ...task, status, history }; + } + + async save(task: Task, context: ServerCallContext): Promise { + const key = taskKey(task.id, context); + const state = task.status?.state; + let persisting: TerminalClaim | undefined; + try { + if (this.cancelRequests.getStore() === task.id && state === TaskState.TASK_STATE_CANCELED) { + // The SDK can reach its direct-write fallback with a stale Store snapshot. + const current = await this.store.load(task.id, context); + if (!current || isTerminal(current.status?.state)) return; + const claim = this.terminalClaims.get(key); + if (claim?.contextId === task.contextId && claim.status.state !== state) return; + } + + const claim = this.terminalClaims.get(key); + if (claim?.contextId === task.contextId && claim.status.state === state) { + persisting = claim; + persisting.writes++; + } + await this.store.save(task, context); + } catch (error) { + this.abandon(context); + throw error; + } finally { + if (persisting) { + persisting.writes--; + if (persisting.writes === 0 && this.terminalClaims.get(key) === persisting) { + this.terminalClaims.delete(key); + } + } + } + } + + list(...args: Parameters): ReturnType { + return this.store.list(...args); + } + + abandon(context: ServerCallContext): void { + this.abandoned.add(context); + for (const key of this.claimKeys.get(context) ?? []) { + const claim = this.terminalClaims.get(key); + if (claim?.context === context && claim.writes === 0) this.terminalClaims.delete(key); + } + this.claimKeys.delete(context); + } +} + +/** Preserve the SDK's normal routing, authorization, and task persistence. */ +export class A2ATaskRequestHandler extends DefaultRequestHandler { + private readonly persistence: TaskPersistence; + + constructor( + card: AgentCard, + store: TaskStore, + agent: AgentExecutor, + extendedAgentCardProvider?: ExtendedAgentCardProvider, + ) { + const persistence = new TaskPersistence(store); + super(card, persistence, { + execute(context, bus) { + persistence.observe(context, bus); + return agent.execute(context, bus); + }, + cancelTask(taskId, bus) { + return agent.cancelTask(taskId, bus); + }, + }, undefined, undefined, undefined, extendedAgentCardProvider); + this.persistence = persistence; + } + + override cancelTask(params: CancelTaskRequest, context: ServerCallContext): Promise { + return this.persistence.cancel(params.id, () => super.cancelTask(params, context)); + } + + override async *sendMessageStream( + params: SendMessageRequest, context: ServerCallContext, + ): AsyncGenerator { + try { + yield* super.sendMessageStream(params, context); + } finally { + this.persistence.abandon(context); + } + } +} diff --git a/a2a/typescript/tests/conformance/event-subscriber.test.ts b/a2a/typescript/tests/conformance/event-subscriber.test.ts index 56c7cf48..f533fc09 100644 --- a/a2a/typescript/tests/conformance/event-subscriber.test.ts +++ b/a2a/typescript/tests/conformance/event-subscriber.test.ts @@ -76,6 +76,16 @@ function expectRequest(recorded: RecordedRequest, expected: FixtureCase["expecte expect(recorded.body).toEqual({ skillId: expected.skill_id, event: fixture.event }); } +it("assigns distinct generated IDs to legacy and Surface A2A subscribers", () => { + const core = new A2ASubscriber("https://example.invalid/core"); + const surface = new A2AEventSubscriber("https://example.invalid/surface"); + const secondSurface = new A2AEventSubscriber("https://example.invalid/another"); + expect(new Set([core.subscriberId, surface.subscriberId, secondSurface.subscriberId]).size).toBe(3); + expect(surface.subscriberId).toMatch(/^a2a-\d+$/); + expect(surface.subscriberType).toBe(core.subscriberType); + expect(new A2AEventSubscriber("https://example.invalid/explicit", undefined, { id: "receiver" }).subscriberId).toBe("receiver"); +}); + describe("configured A2A event subscriber", () => { const verifyDelivery = async (test: FixtureCase): Promise => { const requests: RecordedRequest[] = []; diff --git a/a2a/typescript/tests/server/executor.test.ts b/a2a/typescript/tests/server/executor.test.ts index fa3d5c40..cb3f0fb6 100644 --- a/a2a/typescript/tests/server/executor.test.ts +++ b/a2a/typescript/tests/server/executor.test.ts @@ -1,6 +1,8 @@ import { describe, it, expect, vi, beforeEach } from "vitest"; import { Context, ErrorCodes, ModuleError } from "apcore-js"; -import { Part, TaskState } from "@a2a-js/sdk"; +import { AgentCard, Message, Part, Role, TaskState } from "@a2a-js/sdk"; +import { TaskNotCancelableError } from "@a2a-js/sdk/errors"; +import { DefaultRequestHandler, InMemoryTaskStore, ServerCallContext } from "@a2a-js/sdk/server"; import type { ExecutionEventBus, AgentExecutionEvent, RequestContext } from "@a2a-js/sdk/server"; import { ApCoreAgentExecutor } from "../../src/server/executor.js"; import { PartConverter } from "../../src/adapters/parts.js"; @@ -66,6 +68,75 @@ function deferred() { return { promise, resolve }; } +describe("task terminal ownership through the A2A SDK", () => { + const card = AgentCard.fromJSON({ capabilities: {} }); + const context = new ServerCallContext(); + + function message(contextId?: string): Message { + return Message.fromJSON({ + messageId: "terminal-test", + contextId, + role: Role.ROLE_USER, + metadata: { skillId: "test" }, + parts: [{ text: "Run the task" }], + }); + } + + it.each(["unary", "stream"] as const)("persists an executor-originated %s cancellation", async (mode) => { + const cancel = (coreContext: unknown): never => { + (coreContext as Context).cancelToken?.cancel(); + throw new ModuleError(ErrorCodes.EXECUTION_CANCELLED, "Executor stopped"); + }; + const agent = new ApCoreAgentExecutor({ + executor: mode === "stream" ? { + callAsync: vi.fn(), + async *stream(_moduleId: string, _inputs: unknown, coreContext: unknown) { + yield cancel(coreContext); + }, + } : { + async callAsync(_moduleId, _inputs, coreContext) { return cancel(coreContext); }, + }, + partConverter: new PartConverter(), + }); + const handler = new DefaultRequestHandler(card, new InMemoryTaskStore(), agent); + const states = []; + let taskId = ""; + for await (const { payload } of handler.sendMessageStream({ message: message() }, context)) { + if (payload?.$case === "task") taskId = payload.value.id; + if (payload?.$case === "statusUpdate") states.push(payload.value.status?.state); + } + expect(states).toEqual([TaskState.TASK_STATE_CANCELED]); + expect((await handler.getTask({ id: taskId }, context)).status?.state).toBe(TaskState.TASK_STATE_CANCELED); + }); + + it("preserves the timeout terminal state when cancellation races its publication", async () => { + const result = deferred(); + let taskId = ""; + let cancellation: Promise | undefined; + const agent = new ApCoreAgentExecutor({ + executor: { async callAsync() { await result.promise; return {}; } }, + partConverter: new PartConverter(), + executionTimeout: 0.03, + onStateChange(_from, to) { + if (to === "failed") cancellation = handler.cancelTask({ id: taskId }, context).catch(error => error); + }, + }); + const handler = new DefaultRequestHandler(card, new InMemoryTaskStore(), agent); + const states = []; + try { + for await (const { payload } of handler.sendMessageStream({ message: message() }, context)) { + if (payload?.$case === "task") taskId = payload.value.id; + if (payload?.$case === "statusUpdate") states.push(payload.value.status?.state); + } + expect(states).toEqual([TaskState.TASK_STATE_FAILED]); + expect(await cancellation).toBeInstanceOf(TaskNotCancelableError); + expect((await handler.getTask({ id: taskId }, context)).status?.state).toBe(TaskState.TASK_STATE_FAILED); + } finally { + result.resolve(); + } + }); +}); + describe("ApCoreAgentExecutor", () => { let partConverter: PartConverter; @@ -244,6 +315,7 @@ describe("ApCoreAgentExecutor", () => { } const updates = (bus.events as AgentExecutionEvent[]).filter((event) => event.kind === "statusUpdate"); expect(updates.map((event) => event.data.status.state)).toEqual([TaskState.TASK_STATE_CANCELED]); + expect(updates[0].data.contextId).toBe("ctx-1"); expect(bus.events).toHaveLength(2); }, 2_000); diff --git a/a2a/typescript/tests/server/factory.test.ts b/a2a/typescript/tests/server/factory.test.ts index 4c9dea39..bec9c5f0 100644 --- a/a2a/typescript/tests/server/factory.test.ts +++ b/a2a/typescript/tests/server/factory.test.ts @@ -2,6 +2,9 @@ import { describe, it, expect, vi, beforeEach } from "vitest"; import { Executor, Registry as CoreRegistry } from "apcore-js"; import { Type } from "@sinclair/typebox"; import request from "supertest"; +import { once } from "node:events"; +import { TaskState, type Task } from "@a2a-js/sdk"; +import { InMemoryTaskStore, type ServerCallContext } from "@a2a-js/sdk/server"; import { A2AServerFactory } from "../../src/server/factory.js"; import type { Registry } from "../../src/adapters/agent-card.js"; @@ -97,6 +100,73 @@ describe("A2AServerFactory", () => { } }); + it.each([false, true])("rejects cancellation during a terminal write (store rejects: %s)", async (writeFails) => { + const enteredWrite = Promise.withResolvers(); + const releaseWrite = Promise.withResolvers(); + const releaseExecutor = Promise.withResolvers(); + const observedTerminalStates: TaskState[] = []; + class DelayedTaskStore extends InMemoryTaskStore { + override async save(task: Task, context: ServerCallContext): Promise { + if (task.status?.state === TaskState.TASK_STATE_FAILED) { + enteredWrite.resolve(task.id); + await releaseWrite.promise; + if (writeFails) throw new Error("Store could not commit the terminal write"); + } + if (task.status?.state !== undefined && task.status.state !== TaskState.TASK_STATE_SUBMITTED) { + observedTerminalStates.push(task.status.state); + } + await super.save(task, context); + } + } + + const taskStore = new DelayedTaskStore(); + const { app } = new A2AServerFactory().create(makeRegistry(), { + async callAsync() { + await releaseExecutor.promise; + return { answer: "late" }; + }, + }, { ...baseOpts, taskStore, executionTimeout: 0.025 }); + const server = app.listen(0, "127.0.0.1"); + await once(server, "listening"); + const rpc = (method: string, params: unknown) => request(server).post("/") + .set("A2A-Version", "1.0").send({ jsonrpc: "2.0", id: 1, method, params }).timeout({ deadline: 2_000 }); + const streamed = rpc("SendStreamingMessage", { + message: { messageId: "delayed-store", role: "ROLE_USER", parts: [{ data: {} }], metadata: { skillId: "echo" } }, + }).then(response => response); + try { + const taskId = await Promise.race([ + enteredWrite.promise, + streamed.then(() => { throw new Error("The stream ended before attempting its terminal write"); }), + ]); + const canceled = await rpc("CancelTask", { id: taskId }); + expect(canceled.body.result).toBeUndefined(); + expect(canceled.body.error?.message).toMatch(/not cancelable/i); + expect(observedTerminalStates).toEqual([]); + + releaseWrite.resolve(); + if (writeFails) { + await streamed.catch(() => undefined); + const retry = await rpc("CancelTask", { id: taskId }); + expect(retry.body.result?.status?.state).toBe("TASK_STATE_CANCELED"); + expect(observedTerminalStates).toEqual([TaskState.TASK_STATE_CANCELED]); + return; + } + + const response = await streamed; + const frames = response.text.split("\n").filter((line: string) => line.startsWith("data:")) + .map((line: string) => JSON.parse(line.slice(5)).result); + const states = frames.flatMap(frame => frame.statusUpdate ? [frame.statusUpdate.status.state] : []); + expect(states).toEqual(["TASK_STATE_FAILED"]); + expect((await rpc("GetTask", { id: taskId })).body.result.status.state).toBe("TASK_STATE_FAILED"); + expect(observedTerminalStates).toEqual([TaskState.TASK_STATE_FAILED]); + } finally { + releaseWrite.resolve(); + releaseExecutor.resolve(); + await streamed.catch(() => undefined); + server.close(); + } + }); + describe("agent card endpoint", () => { it("serves the A2A 1.0 primary endpoint /.well-known/agent-card.json", async () => { const factory = new A2AServerFactory(); From cf2f2f5bea1fe3b882ad475032937ba36b4af3f8 Mon Sep 17 00:00:00 2001 From: tercel Date: Fri, 27 Nov 2026 13:30:00 +0800 Subject: [PATCH 16/36] docs(toolkit): clarify Prometheus shutdown timing Signed-off-by: tercel --- toolkit/rust/README.md | 4 +++- toolkit/rust/src/prometheus_server.rs | 5 ++++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/toolkit/rust/README.md b/toolkit/rust/README.md index 1ef2e836..37472dd9 100644 --- a/toolkit/rust/README.md +++ b/toolkit/rust/README.md @@ -326,7 +326,9 @@ See `apcore-toolkit/docs/features/formatting.md` § Tabular Formats for the full Enable the `prometheus-server` feature to serve Core metrics and health probes. Pass a renderer backed by your application's existing collectors. The bound handle reports its address and provides an async `close()` that stops accepting -connections before draining in-flight responses. +connections before draining in-flight responses. The drain timeout covers +asynchronous connection I/O. The renderer and readiness callback run on the +Tokio runtime and must return without blocking. ```rust use std::{io, net::SocketAddr}; diff --git a/toolkit/rust/src/prometheus_server.rs b/toolkit/rust/src/prometheus_server.rs index a8715877..080c10bf 100644 --- a/toolkit/rust/src/prometheus_server.rs +++ b/toolkit/rust/src/prometheus_server.rs @@ -33,6 +33,7 @@ pub struct PrometheusServer { impl PrometheusServer { /// Create a listener configuration. The renderer is called for each scrape. + /// It runs synchronously on the Tokio runtime and must return without blocking. pub fn new(render_metrics: impl Fn() -> String + Send + Sync + 'static) -> Self { Self { render_metrics: Box::new(render_metrics), @@ -49,6 +50,7 @@ impl PrometheusServer { } /// Check the host's current readiness for each probe. The default is false. + /// The callback runs synchronously on the Tokio runtime and must not block. #[must_use] pub fn with_readiness(mut self, is_ready: impl Fn() -> bool + Send + Sync + 'static) -> Self { self.is_ready = Some(Box::new(is_ready)); @@ -125,7 +127,8 @@ impl PrometheusServerHandle { self.address } - /// Stop accepting and wait up to ten seconds for open connections to drain. + /// Stop accepting and allow up to ten seconds for asynchronous connection I/O + /// to drain. Synchronous renderer and readiness callbacks must return promptly. /// /// A repeated close returns successfully. Dropping this handle signals the /// same shutdown, while `close` waits for it to finish. From d27d9339a9a777a0343abffe869e96acacf28a83 Mon Sep 17 00:00:00 2001 From: tercel Date: Fri, 27 Nov 2026 13:30:18 +0800 Subject: [PATCH 17/36] fix(cli): preserve nullable container flags across SDKs Signed-off-by: tercel --- .../fixtures/structured_flags.json | 21 +++- cli/python/src/apcore_cli/ref_resolver.py | 31 ++--- .../conformance/test_structured_flags.py | 18 +++ cli/rust/src/cli.rs | 32 +++--- cli/rust/src/ref_resolver.rs | 30 +++++ .../tests/conformance_structured_flags.rs | 108 ++++++++++++++++++ cli/typescript/src/main.ts | 18 ++- cli/typescript/src/ref-resolver.ts | 19 +++ cli/typescript/src/schema-parser.ts | 17 ++- 9 files changed, 242 insertions(+), 52 deletions(-) diff --git a/cli/conformance/fixtures/structured_flags.json b/cli/conformance/fixtures/structured_flags.json index 71b8f6ba..f6bf7f46 100644 --- a/cli/conformance/fixtures/structured_flags.json +++ b/cli/conformance/fixtures/structured_flags.json @@ -5,7 +5,11 @@ "properties": { "filters": { "type": "object" }, "labels": { "type": "array", "items": { "type": "string" } }, - "note": { "type": "string" } + "note": { "type": "string" }, + "maybe_filters": { "anyOf": [{ "type": "object" }, { "type": "null" }] }, + "maybe_labels": { "oneOf": [{ "type": "array", "items": { "type": "string" } }, { "type": "null" }] }, + "nullable_labels": { "type": ["array", "null"], "items": { "type": "string" } }, + "no_labels": { "type": "array", "items": { "type": "string" } } }, "required": ["filters", "labels"] }, @@ -20,6 +24,21 @@ "args": ["--filters", "{}", "--labels", "[]"], "expected": { "exit_code": 0, "calls": 1, "input": { "filters": {}, "labels": [] } } }, + { + "id": "nullable_structured_values", + "args": ["--filters", "{}", "--labels", "[]", "--maybe-filters", "{\"enabled\":true}", "--maybe-labels", "[\"choice\"]", "--nullable-labels", "[\"direct\"]"], + "expected": { "exit_code": 0, "calls": 1, "input": { "filters": {}, "labels": [], "maybe_filters": { "enabled": true }, "maybe_labels": ["choice"], "nullable_labels": ["direct"] } } + }, + { + "id": "explicit_null_for_nullable_structured_flags", + "args": ["--filters", "{}", "--labels", "[]", "--maybe-filters", "null", "--maybe-labels", "null", "--nullable-labels", "null"], + "expected": { "exit_code": 0, "calls": 1, "input": { "filters": {}, "labels": [], "maybe_filters": null, "maybe_labels": null, "nullable_labels": null } } + }, + { + "id": "no_prefix_is_part_of_the_property_name", + "args": ["--filters", "{}", "--labels", "[\"always\"]", "--no-labels", "[\"separate\"]"], + "expected": { "exit_code": 0, "calls": 1, "input": { "filters": {}, "labels": ["always"], "no_labels": ["separate"] } } + }, { "id": "malformed_object", "args": ["--filters", "{", "--labels", "[]"], diff --git a/cli/python/src/apcore_cli/ref_resolver.py b/cli/python/src/apcore_cli/ref_resolver.py index 054130be..7c0af77d 100644 --- a/cli/python/src/apcore_cli/ref_resolver.py +++ b/cli/python/src/apcore_cli/ref_resolver.py @@ -138,28 +138,21 @@ def _resolve_node( for k, v in node.items(): if k not in (keyword, "properties", "required") and k not in merged: merged[k] = v - # Pydantic v2 emits Optional[X] as {"anyOf": [, {"type": "null"}]}. - # The branch merge above copies properties but never the scalar `type` from - # branches, so Optional[str]/Optional[int]/etc. lose their type entirely. - # Recover it: if the merged result has no `type`, pick the type of the first - # non-null branch (ignoring {"type": "null"} sentinels). if "type" not in merged: + branch_types: list[Any] = [] for branch in resolved_branches: branch_type = branch.get("type") - if isinstance(branch_type, str) and branch_type != "null": - merged["type"] = branch_type - break - if isinstance(branch_type, list): - # JSON Schema list-form type (e.g. ["string", "null"]): - # recover the first non-null string so downstream never - # sees an unhashable list type. - recovered = next( - (t for t in branch_type if isinstance(t, str) and t != "null"), - None, - ) - if recovered is not None: - merged["type"] = recovered - break + branch_types.extend(branch_type if isinstance(branch_type, list) and branch_type else [branch_type]) + non_null = next((t for t in branch_types if isinstance(t, str) and t != "null"), None) + if non_null is not None: + if all(t in ("object", "array", "null") for t in branch_types): + # JSON container flags can represent an explicit null. Keep + # the inferred union for decoding and local validation. + types = list(dict.fromkeys(branch_types)) + merged["type"] = types if len(types) > 1 else types[0] + else: + # Preserve the existing flag type for scalar compositions. + merged["type"] = non_null return merged # Recursively process every dict-valued child of this node. diff --git a/cli/python/tests/conformance/test_structured_flags.py b/cli/python/tests/conformance/test_structured_flags.py index 7c46a18a..774871e6 100644 --- a/cli/python/tests/conformance/test_structured_flags.py +++ b/cli/python/tests/conformance/test_structured_flags.py @@ -4,6 +4,7 @@ import json from copy import deepcopy +from importlib.metadata import version from pathlib import Path from typing import Any @@ -55,6 +56,23 @@ def test_shared_structured_flag_contract(case: dict[str, Any]) -> None: assert result.stderr +@pytest.mark.skipif(version("apcore") == "0.33.0", reason="Core 0.33.0 loses root references inside unions") +def test_nullable_flag_resolves_a_referenced_container_branch() -> None: + schema = deepcopy(_FIXTURE["schema"]) + schema["$defs"] = {"labels": {"type": "array", "items": {"type": "string"}}} + schema["properties"]["maybe_labels"]["oneOf"][0] = {"$ref": "#/$defs/labels"} + command, module = _command(schema) + + for value in ('["choice"]', "null"): + invoked = CliRunner().invoke(command, ["--filters", "{}", "--labels", "[]", "--maybe-labels", value]) + assert invoked.exit_code == 0, invoked.output + + assert module.calls == [ + {"filters": {}, "labels": [], "maybe_labels": ["choice"]}, + {"filters": {}, "labels": [], "maybe_labels": None}, + ] + + @pytest.mark.parametrize("source", ["stdin", "file"]) def test_structured_flags_override_input_without_reparsing_it(tmp_path: Path, source: str) -> None: schema = deepcopy(_FIXTURE["schema"]) diff --git a/cli/rust/src/cli.rs b/cli/rust/src/cli.rs index a81407af..69e5898f 100644 --- a/cli/rust/src/cli.rs +++ b/cli/rust/src/cli.rs @@ -1035,26 +1035,18 @@ pub fn reconcile_bool_pairs( matches: &clap::ArgMatches, bool_pairs: &[crate::schema_parser::BoolFlagPair], ) -> HashMap { + let supplied = |id: &str| { + // exec has no generated option IDs. For generated options, check + // presence rather than the bool stored by SetTrue or SetFalse. + matches.try_contains_id(id).unwrap_or(false) + && matches.value_source(id) == Some(clap::parser::ValueSource::CommandLine) + }; let mut result = HashMap::new(); for pair in bool_pairs { - // Use try_get_one to avoid panicking when the flag doesn't exist - // in ArgMatches (e.g. exec subcommand doesn't have schema-derived flags). - let pos_set = matches - .try_get_one::(&pair.prop_name) - .ok() - .flatten() - .copied() - .unwrap_or(false); let neg_id = format!("no-{}", pair.prop_name); - let neg_set = matches - .try_get_one::(&neg_id) - .ok() - .flatten() - .copied() - .unwrap_or(false); - let val = if pos_set { + let val = if supplied(&pair.prop_name) { true - } else if neg_set { + } else if supplied(&neg_id) { false } else { pair.default_val @@ -1091,11 +1083,13 @@ fn extract_cli_kwargs( let mut inputs = CliInputs::default(); for arg in &schema_args.args { - let id = arg.get_id().as_str(); - // Skip the no- counterparts of boolean args. - if id.starts_with("no-") { + if matches!( + arg.get_action(), + clap::ArgAction::SetTrue | clap::ArgAction::SetFalse + ) { continue; } + let id = arg.get_id().as_str(); // Use try_get_one to avoid panicking when the arg doesn't exist // in ArgMatches (e.g. exec subcommand doesn't have schema-derived flags). if let Ok(Some(value)) = matches.try_get_one::(id) { diff --git a/cli/rust/src/ref_resolver.rs b/cli/rust/src/ref_resolver.rs index eed01a9a..c3eb2245 100644 --- a/cli/rust/src/ref_resolver.rs +++ b/cli/rust/src/ref_resolver.rs @@ -165,6 +165,32 @@ fn merge_anyof(branches: Vec) -> Value { Value::Object(result) } +// Keep the type information needed to decode JSON-valued options. The +// dispatcher still validates against the original choice and its constraints. +fn nullable_container_type(branches: &[Value]) -> Option { + let mut kinds = Vec::new(); + for branch in branches { + let kind = branch.get("type")?; + let branch_kinds = match kind { + Value::Array(kinds) if !kinds.is_empty() => kinds.as_slice(), + _ => std::slice::from_ref(kind), + }; + for kind in branch_kinds { + if !matches!(kind.as_str(), Some("array" | "object" | "null")) { + return None; + } + if !kinds.contains(kind) { + kinds.push(kind.clone()); + } + } + } + if kinds.len() > 1 && kinds.iter().any(|kind| kind == "null") { + Some(Value::Array(kinds)) + } else { + None + } +} + // --------------------------------------------------------------------------- // resolve_node (private helper) // --------------------------------------------------------------------------- @@ -304,6 +330,7 @@ fn resolve_node( resolved_branches.push(resolved_sub); } + let container_type = nullable_container_type(&resolved_branches); let merged = merge_anyof(resolved_branches); let merged_map = match merged { Value::Object(m) => m, @@ -350,6 +377,9 @@ fn resolve_node( result_map.insert(k.clone(), v.clone()); } } + if let Some(container_type) = container_type { + result_map.entry("type").or_insert(container_type); + } return Ok(Value::Object(result_map)); } } diff --git a/cli/rust/tests/conformance_structured_flags.rs b/cli/rust/tests/conformance_structured_flags.rs index dcc93251..eece3ce1 100644 --- a/cli/rust/tests/conformance_structured_flags.rs +++ b/cli/rust/tests/conformance_structured_flags.rs @@ -204,3 +204,111 @@ async fn composition_and_reference_siblings_keep_container_flags_typed() { ) .await; } + +#[tokio::test] +async fn nullable_choices_decode_json_and_keep_original_schema_constraints() { + let schema = json!({ + "type": "object", + "properties": { + "labels": {"anyOf": [{"$ref": "#/$defs/Labels"}, {"type": "null"}]}, + "filters": {"oneOf": [{"type": "null"}, {"$ref": "#/$defs/Filters"}]}, + "note": {"anyOf": [{"type": "string"}, {"type": "array"}]}, + }, + "$defs": { + "Labels": {"type": "array", "items": {"type": "string"}}, + "Filters": {"type": "object", "required": ["active"]}, + }, + }); + for (id, args, exit_code, value) in [ + ( + "both containers and a string choice", + vec![ + "--labels", + r#"["x"]"#, + "--filters", + r#"{"active":true}"#, + "--note", + "[]", + ], + 0, + Some(json!({"labels": ["x"], "filters": {"active": true}, "note": "[]"})), + ), + ( + "explicit null with another option omitted", + vec!["--labels", "null", "--filters", "null"], + 0, + Some(json!({"labels": null, "filters": null})), + ), + ( + "original array constraints", + vec!["--labels", "[17]"], + 45, + None, + ), + ( + "original object constraints", + vec!["--filters", "{}"], + 45, + None, + ), + ("malformed JSON", vec!["--labels", "["], 45, None), + ] { + let args: Vec = args.into_iter().map(str::to_owned).collect(); + run_case( + &schema, + &args, + id, + &Expected { + exit_code, + calls: usize::from(exit_code == 0), + input: value, + }, + ) + .await; + } +} + +#[tokio::test] +async fn literal_no_prefix_is_a_regular_structured_option() { + let schema = json!({ + "type": "object", + "properties": {"no-labels": {"type": "array"}}, + "required": ["no-labels"], + }); + run_case( + &schema, + &["--no-labels".into(), r#"["x"]"#.into()], + "literal no-labels option", + &Expected { + exit_code: 0, + calls: 1, + input: Some(json!({"no-labels": ["x"]})), + }, + ) + .await; +} + +#[tokio::test] +async fn boolean_negation_uses_explicit_flag_presence() { + let schema = json!({ + "type": "object", + "properties": {"enabled": {"type": "boolean", "default": true}}, + }); + for (id, args, enabled) in [ + ("default true", vec![], true), + ("explicit true", vec!["--enabled".into()], true), + ("explicit false", vec!["--no-enabled".into()], false), + ] { + run_case( + &schema, + &args, + id, + &Expected { + exit_code: 0, + calls: 1, + input: Some(json!({"enabled": enabled})), + }, + ) + .await; + } +} diff --git a/cli/typescript/src/main.ts b/cli/typescript/src/main.ts index 0fb38ee4..903a4e70 100644 --- a/cli/typescript/src/main.ts +++ b/cli/typescript/src/main.ts @@ -1225,6 +1225,13 @@ export function buildModuleCommand( const flagBase = opt.name.replace(/_/g, "-"); const option = new Option(opt.isBooleanFlag ? `--${flagBase}` : opt.flags, opt.description) .default(opt.defaultValue); + // Commander strips "no-" from the key by default. Keep it on declarations + // from the schema so only the generated boolean counterparts negate flags. + if (option.negate) { + const suffix = option.attributeName(); + option.negate = false; + option.attributeName = () => `no${suffix.charAt(0).toUpperCase()}${suffix.slice(1)}`; + } if (opt.parseArg) option.argParser(opt.parseArg); cmd.addOption(option); schemaFlags.push([opt, option.attributeName()]); @@ -1266,14 +1273,17 @@ export function buildModuleCommand( } // 1. Collect and merge input const schemaKwargs: Record = {}; + const structuredFlags: Record = {}; for (const [opt, key] of schemaFlags) { if (!Object.hasOwn(options, key)) continue; const value = options[key]; - schemaKwargs[opt.name] = opt.parseStructuredArg && typeof value === "string" && cmd.getOptionValueSource(key) === "cli" - ? opt.parseStructuredArg(value) - : value; + if (opt.parseStructuredArg && typeof value === "string" && cmd.getOptionValueSource(key) === "cli") { + structuredFlags[opt.name] = opt.parseStructuredArg(value); + } else { + schemaKwargs[opt.name] = value; + } } - merged = await readModuleInput(stdinFlag, schemaKwargs, largeInput); + merged = { ...await readModuleInput(stdinFlag, schemaKwargs, largeInput), ...structuredFlags }; // 2. Reconvert enum values const reconverted = reconvertEnumValues(merged, schemaOptions); diff --git a/cli/typescript/src/ref-resolver.ts b/cli/typescript/src/ref-resolver.ts index ec420333..7bf0386f 100644 --- a/cli/typescript/src/ref-resolver.ts +++ b/cli/typescript/src/ref-resolver.ts @@ -6,6 +6,17 @@ import { CircularRefError, MaxDepthExceededError, UnresolvableRefError } from "./errors.js"; +type StructuredOptionType = "object" | "array" | "null"; + +export function structuredOptionTypes(schemaType: unknown): StructuredOptionType[] | undefined { + const types: unknown[] = Array.isArray(schemaType) ? schemaType : [schemaType]; + if (!types.every((type): type is StructuredOptionType => + type === "object" || type === "array" || type === "null") || !types.some(type => type !== "null")) { + return undefined; + } + return types; +} + // --------------------------------------------------------------------------- // resolveRefs // --------------------------------------------------------------------------- @@ -150,6 +161,7 @@ function resolveNode( ? (obj.required as string[]).slice() : []; const allRequiredSets: Set[] = []; + const branchTypes: unknown[] = []; for (const subSchema of obj[keyword] as unknown[]) { const resolved = resolveNode( subSchema, @@ -159,6 +171,8 @@ function resolveNode( maxDepth, moduleId, ) as Record; + const type = resolved.type; + branchTypes.push(...(Array.isArray(type) && type.length > 0 ? type : [type])); if (resolved.properties) { Object.assign( merged.properties as Record, @@ -196,6 +210,11 @@ function resolveNode( merged[k] = v; } } + // Retain the JSON shape for CLI decoding. Core validates the original schema. + const types = structuredOptionTypes(branchTypes); + if (merged.type === undefined && types) { + merged.type = [...new Set(types)]; + } return merged; } } diff --git a/cli/typescript/src/schema-parser.ts b/cli/typescript/src/schema-parser.ts index e3788c58..c9c1669b 100644 --- a/cli/typescript/src/schema-parser.ts +++ b/cli/typescript/src/schema-parser.ts @@ -8,6 +8,7 @@ import type { OptionConfig } from "./main.js"; import { EXIT_CODES, SchemaValidationError } from "./errors.js"; import { exitWith } from "./exit.js"; import { warn as logWarn } from "./logger.js"; +import { structuredOptionTypes } from "./ref-resolver.js"; // --------------------------------------------------------------------------- // Internal helpers @@ -77,17 +78,15 @@ export function extractHelp(propSchema: Record, maxLength = 100 return text; } -function parseStructuredValue(value: string, flag: string, type: "object" | "array"): unknown { +function parseStructuredValue(value: string, flag: string, types: readonly string[]): unknown { let decoded: unknown; try { decoded = JSON.parse(value); } catch { throw new SchemaValidationError(`${flag} must contain valid JSON.`); } - const matches = type === "array" - ? Array.isArray(decoded) - : typeof decoded === "object" && decoded !== null && !Array.isArray(decoded); - if (!matches) throw new SchemaValidationError(`${flag} must be a JSON ${type}.`); + const type = decoded === null ? "null" : Array.isArray(decoded) ? "array" : typeof decoded; + if (!types.includes(type)) throw new SchemaValidationError(`${flag} must be JSON of type ${types.join(" or ")}.`); return decoded; } @@ -157,7 +156,8 @@ export function schemaToCliOptions( } flagNames[flagName] = propName; - const typeResult = mapType(propName, propSchema); + const structuredTypes = structuredOptionTypes(propSchema.type); + const typeResult = structuredTypes ? "string" : mapType(propName, propSchema); const isRequired = requiredList.includes(propName); const helpBase = extractHelp(propSchema, maxHelpLength); const helpText = isRequired @@ -165,15 +165,14 @@ export function schemaToCliOptions( : helpBase ?? ""; const defaultValue = propSchema.default as unknown; - const structuredType = propSchema.type; - if (structuredType === "object" || structuredType === "array") { + if (structuredTypes) { options.push({ name: propName, flags: `${flagName} `, description: helpText, defaultValue, required: isRequired, - parseStructuredArg: value => parseStructuredValue(value, flagName, structuredType), + parseStructuredArg: value => parseStructuredValue(value, flagName, structuredTypes), }); } else if (typeResult === BOOLEAN_FLAG) { // Boolean flag pair: --flag/--no-flag From ecee2cfa8ff761d29e0cf1de8e7b06078dfa7683 Mon Sep 17 00:00:00 2001 From: tercel Date: Fri, 27 Nov 2026 13:32:14 +0800 Subject: [PATCH 18/36] chore(release): lock Rust surfaces to the reviewed Toolkit crate Signed-off-by: tercel --- a2a/rust/Cargo.lock | 2 +- cli/rust/Cargo.lock | 2 +- mcp/rust/Cargo.lock | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/a2a/rust/Cargo.lock b/a2a/rust/Cargo.lock index f28f79b7..ee5153aa 100644 --- a/a2a/rust/Cargo.lock +++ b/a2a/rust/Cargo.lock @@ -155,7 +155,7 @@ dependencies = [ name = "apcore-toolkit" version = "0.15.1-alpha.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab34436cafe0107095f188074f226983d1a1605741529b9397d27de490a3cad9" +checksum = "7054dcf35f7f9f0823f3118f3ab531a511cca25d6c2f07cdc7c222de10bf0673" dependencies = [ "apcore", "async-trait", diff --git a/cli/rust/Cargo.lock b/cli/rust/Cargo.lock index 49f38234..88ca6d2e 100644 --- a/cli/rust/Cargo.lock +++ b/cli/rust/Cargo.lock @@ -199,7 +199,7 @@ dependencies = [ name = "apcore-toolkit" version = "0.15.1-alpha.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab34436cafe0107095f188074f226983d1a1605741529b9397d27de490a3cad9" +checksum = "7054dcf35f7f9f0823f3118f3ab531a511cca25d6c2f07cdc7c222de10bf0673" dependencies = [ "apcore", "async-trait", diff --git a/mcp/rust/Cargo.lock b/mcp/rust/Cargo.lock index 5f0fe9c1..88d05c8b 100644 --- a/mcp/rust/Cargo.lock +++ b/mcp/rust/Cargo.lock @@ -164,7 +164,7 @@ dependencies = [ name = "apcore-toolkit" version = "0.15.1-alpha.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab34436cafe0107095f188074f226983d1a1605741529b9397d27de490a3cad9" +checksum = "7054dcf35f7f9f0823f3118f3ab531a511cca25d6c2f07cdc7c222de10bf0673" dependencies = [ "apcore", "async-trait", From 40aec69001cf612e6cfd42cf2b613d7dbe34c9d1 Mon Sep 17 00:00:00 2001 From: tercel Date: Fri, 27 Nov 2026 13:36:54 +0800 Subject: [PATCH 19/36] fix(cli): accept explicit null for required nullable fields Signed-off-by: tercel --- cli/typescript/src/main.ts | 16 ++++--- cli/typescript/tests/structured-flags.test.ts | 42 ++++++++++++++++++- 2 files changed, 52 insertions(+), 6 deletions(-) diff --git a/cli/typescript/src/main.ts b/cli/typescript/src/main.ts index 903a4e70..a354f598 100644 --- a/cli/typescript/src/main.ts +++ b/cli/typescript/src/main.ts @@ -238,8 +238,7 @@ function validateInputSchema( const required = schema.required as string[] | undefined; if (required && Array.isArray(required)) { for (const field of required) { - const val = input[field]; - if (val === null || val === undefined) { + if (!Object.hasOwn(input, field) || input[field] === undefined) { return `'${field}' is required`; } } @@ -248,9 +247,16 @@ function validateInputSchema( if (properties) { for (const [field, propSchema] of Object.entries(properties)) { const val = input[field]; - if (val === null || val === undefined) continue; - const expectedType = propSchema.type as string | undefined; - if (!expectedType) continue; + if (val === undefined) continue; + const expectedType = propSchema.type; + if (val === null) { + // A required field may be present with a nullable value. Leave + // schemas without an explicit type to Core's full validation. + const acceptsNull = Array.isArray(expectedType) ? expectedType.includes("null") : expectedType === "null"; + if (expectedType !== undefined && !acceptsNull) return `'${field}' does not accept null`; + continue; + } + if (typeof expectedType !== "string") continue; const actualType = typeof val; if (expectedType === "string" && actualType !== "string") { return `'${field}' must be a string, got ${actualType}`; diff --git a/cli/typescript/tests/structured-flags.test.ts b/cli/typescript/tests/structured-flags.test.ts index 5eda9e88..bbc21203 100644 --- a/cli/typescript/tests/structured-flags.test.ts +++ b/cli/typescript/tests/structured-flags.test.ts @@ -1,4 +1,6 @@ -import { readFileSync } from "node:fs"; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; import { Executor, Registry } from "apcore-js"; import { describe, expect, it, vi } from "vitest"; import { buildModuleCommand } from "../src/main.js"; @@ -77,6 +79,44 @@ describe("structured generated flags", () => { expect(result.diagnostics).toContain("--filters"); }); + it("passes an explicit null for a required nullable field to preflight and execution", async () => { + const schema = { + ...fixture.schema, + required: ["maybe_filters"], + }; + const args = ["--maybe-filters", "null"]; + + const preflight = await invoke(["--dry-run", ...args], schema); + expect(preflight.exitCode).toBe(0); + expect(preflight.preflightInputs).toEqual([{ maybe_filters: null }]); + expect(preflight.inputs).toEqual([]); + + const dispatched = await invoke(args, schema); + expect(dispatched.exitCode).toBe(0); + expect(dispatched.inputs).toEqual([{ maybe_filters: null }]); + }); + + it("still requires the nullable field when its value is omitted", async () => { + const result = await invoke([], { ...fixture.schema, required: ["maybe_filters"] }); + expect(result.exitCode).toBe(45); + expect(result.inputs).toEqual([]); + expect(result.diagnostics).toContain("'maybe_filters' is required"); + }); + + it("rejects null for a required nonnullable field supplied in a JSON file", async () => { + const directory = mkdtempSync(join(tmpdir(), "apcore-cli-nonnullable-")); + const file = join(directory, "input.json"); + try { + writeFileSync(file, JSON.stringify({ filters: null, labels: [] })); + const result = await invoke(["--input", file]); + expect(result.exitCode).toBe(45); + expect(result.inputs).toEqual([]); + expect(result.diagnostics).toContain("'filters' does not accept null"); + } finally { + rmSync(directory, { recursive: true, force: true }); + } + }); + it("uses schema defaults as typed values", async () => { const schemaWithDefaults = { ...fixture.schema, From 148af512b14bf9be702c2dc83d44a25e7b420de9 Mon Sep 17 00:00:00 2001 From: tercel Date: Fri, 27 Nov 2026 13:39:13 +0800 Subject: [PATCH 20/36] fix(mcp): forward documented Rust wire version hints Signed-off-by: tercel --- mcp/rust/src/server/router.rs | 81 +++++++++++++++++++++++++++++++---- mcp/rust/src/server/server.rs | 37 +++++++++++++++- 2 files changed, 109 insertions(+), 9 deletions(-) diff --git a/mcp/rust/src/server/router.rs b/mcp/rust/src/server/router.rs index 53c54a99..b374ba63 100644 --- a/mcp/rust/src/server/router.rs +++ b/mcp/rust/src/server/router.rs @@ -987,8 +987,8 @@ impl ExecutionRouter { let (progress_token, send_notification, session, identity) = self.extract_extra(extra); // Resolve version_hint via the spec's 3-source cascade: [A-D-006] - // 1. extras.version_hint (SDK caller-supplied, highest priority) - // 2. extras._meta.apcore.version (MCP client-supplied) + // 1. extras.version_hint (explicit SDK input or normalized wire metadata) + // 2. extras._meta.apcore.version (wrapped metadata supplied by SDK callers) // 3. registry.get_definition(tool_name).metadata.version_hint // (descriptor default, lowest) // Pre-fix Rust read only source #2. @@ -4387,9 +4387,7 @@ mod tests { #[tokio::test] async fn test_version_hint_flows_through() { - // [A-D-002 regression] Real MCP traffic carries the apcore version - // hint at extras._meta.apcore.version — not at extras.apcore.version. - // Verifies the `_meta` hop is honored in source #2 of the cascade. + // SDK callers can pass wrapped metadata as source #2 of the cascade. let captured: Arc>> = Arc::new(std::sync::Mutex::new(None)); let exec = VersionHintCapturingExecutor { captured: Arc::clone(&captured), @@ -4403,9 +4401,7 @@ mod tests { #[tokio::test] async fn test_version_hint_ignores_top_level_apcore() { - // [A-D-002 regression] Confirms that putting the apcore stanza at - // the TOP level (legacy shape that pre-fix Rust accidentally accepted) - // is now correctly ignored — the cascade only honors `_meta.apcore.version`. + // Top-level apcore is a wire metadata field, normalized by ServerHandler. let captured: Arc>> = Arc::new(std::sync::Mutex::new(None)); let exec = VersionHintCapturingExecutor { captured: Arc::clone(&captured), @@ -4417,6 +4413,75 @@ mod tests { assert_eq!(captured.lock().unwrap().clone(), None); } + #[tokio::test] + async fn tools_call_forwards_the_documented_wire_version_hint() { + use crate::server::factory::MCPServerFactory; + use crate::server::server::ServerHandler; + use crate::server::transport::McpHandler; + + let captured = Arc::new(std::sync::Mutex::new(None)); + let router = Arc::new(ExecutionRouter::new( + Box::new(VersionHintCapturingExecutor { + captured: Arc::clone(&captured), + }), + false, + None, + )); + let factory = MCPServerFactory::new(); + let mut server = factory.create_server("test", "1.0.0").unwrap(); + factory.register_handlers(&mut server, vec![], router); + let options = factory.build_init_options(&server, "test", "1.0.0", None); + let handler = ServerHandler::from_server(&server, options).unwrap(); + + for (metadata, expected) in [ + (json!({"apcore": {"version": "^2.0"}}), Some("^2.0")), + ( + json!({ + "apcore": {"version": "2.1.0"}, + "version_hint": "1.0.0", + "versionHint": "1.1.0", + "_meta": {"apcore": {"version": "1.2.0"}}, + }), + Some("2.1.0"), + ), + ( + json!({ + "version_hint": "1.0.0", + "versionHint": "1.1.0", + "_meta": {"apcore": {"version": "1.2.0"}}, + }), + None, + ), + (json!({"apcore": {"version": 2}}), None), + (json!({"apcore": {"version": "1".repeat(65)}}), None), + (json!({"apcore": {"version": "2.0/3.0"}}), None), + ] { + let response = handler + .handle_message(json!({ + "jsonrpc": "2.0", "id": 1, "method": "tools/call", + "params": {"name": "demo.echo", "arguments": {}, "_meta": metadata}, + })) + .await + .unwrap(); + assert_eq!(response["result"]["isError"], false); + assert_eq!(captured.lock().unwrap().as_deref(), expected); + } + + let result = server + .call_tool( + "demo.echo".into(), + json!({}), + Some(json!({ + "versionHint": "3.0.0", + "_meta": {"apcore": {"version": "2.0.0"}}, + })), + ) + .unwrap() + .await; + assert!(!result.is_error); + assert_eq!(captured.lock().unwrap().as_deref(), Some("3.0.0")); + } + // ================================================================== // P0 #1: W3C traceparent ↔ MCP _meta.traceparent // ================================================================== diff --git a/mcp/rust/src/server/server.rs b/mcp/rust/src/server/server.rs index 3cb2572d..b5c3298f 100644 --- a/mcp/rust/src/server/server.rs +++ b/mcp/rust/src/server/server.rs @@ -684,6 +684,41 @@ impl ServerHandler { None } + fn tool_call_extra(params: &Value) -> Option { + let mut extra = params.get("_meta")?.clone(); + if let Some(metadata) = extra.as_object_mut() { + // A wire call contributes a hint only at params._meta.apcore.version. + // The router also accepts separate SDK extra shapes from in-process callers. + let version = metadata + .get_mut("apcore") + .and_then(Value::as_object_mut) + .and_then(|apcore| apcore.remove("version")); + metadata.remove("version_hint"); + metadata.remove("versionHint"); + if let Some(apcore) = metadata + .get_mut("_meta") + .and_then(|wrapped| wrapped.get_mut("apcore")) + .and_then(Value::as_object_mut) + { + apcore.remove("version"); + } + if let Some(version) = version { + let valid = version.as_str().is_some_and(|hint| { + hint.len() <= 64 + && hint.bytes().all(|byte| { + byte.is_ascii_alphanumeric() || b".-+_~^>=<* ".contains(&byte) + }) + }); + if valid { + metadata.insert("version_hint".into(), version); + } else { + tracing::debug!("Ignoring invalid APCore wire version hint"); + } + } + } + Some(extra) + } + fn negotiated_protocol(message: &Value) -> &'static str { match message["params"]["protocolVersion"].as_str() { Some("2024-11-05") => "2024-11-05", @@ -838,7 +873,7 @@ impl crate::server::transport::McpHandler for ServerHandler { .get("arguments") .cloned() .unwrap_or(Value::Object(Default::default())); - let extra = params.get("_meta").cloned(); + let extra = Self::tool_call_extra(params); let mut call_result = (self.call_tool)(name, arguments, extra).await; if !self.supports_structured_results(&message) { call_result.structured_content = None; From c42ecd4f85a2a929d183539995afb0c4dc2ab708 Mon Sep 17 00:00:00 2001 From: tercel Date: Fri, 27 Nov 2026 13:41:04 +0800 Subject: [PATCH 21/36] fix(cli): audit closed output pipes in strict streaming Signed-off-by: tercel --- cli/typescript/src/strict-stream.ts | 9 ++- cli/typescript/tests/strict-stream.test.ts | 68 +++++++++++++++++++++- 2 files changed, 75 insertions(+), 2 deletions(-) diff --git a/cli/typescript/src/strict-stream.ts b/cli/typescript/src/strict-stream.ts index 6e986722..b0475e64 100644 --- a/cli/typescript/src/strict-stream.ts +++ b/cli/typescript/src/strict-stream.ts @@ -67,13 +67,18 @@ export async function executeStrictStream( throw new InvalidCliInputError("Strict streaming requires an Executor with stream completion support."); } let writeOrIterationFailed = false; + const stdout = process.stdout; + // A failed write also emits an error event. Keep it from interrupting + // receipt handling, cleanup, and auditing after the callback rejects. + const onOutputError = (): void => { writeOrIterationFailed = true; }; + stdout.on("error", onOutputError); try { for await (const chunk of stream.chunks) { const line = JSON.stringify(chunk) + "\n"; // The failure path can exit the process immediately. Flush each line // before advancing so already-emitted JSONL survives a piped exit. await new Promise((resolve, reject) => { - process.stdout.write(line, error => error ? reject(error) : resolve()); + stdout.write(line, error => error ? reject(error) : resolve()); }); } } catch { @@ -81,6 +86,8 @@ export async function executeStrictStream( // The receipt keeps the canonical failure without exposing the iterator's // exception details. Close also stops the invocation if output failed. await stream.close(); + } finally { + stdout.off("error", onOutputError); } const failure = completionError(await stream.completion); if (failure) throw failure; diff --git a/cli/typescript/tests/strict-stream.test.ts b/cli/typescript/tests/strict-stream.test.ts index fcd159c4..146feb17 100644 --- a/cli/typescript/tests/strict-stream.test.ts +++ b/cli/typescript/tests/strict-stream.test.ts @@ -1,8 +1,12 @@ -import { mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { spawn } from "node:child_process"; +import { once } from "node:events"; +import { mkdtempSync, readFileSync, rmSync, symlinkSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; import { Executor, Registry, STREAMING_MARKER, createAnnotations } from "apcore-js"; import { describe, expect, it, vi } from "vitest"; +import { build } from "tsup"; import { buildModuleCommand, createCli } from "../src/main.js"; import { AuditLogger, getAuditLogger, setAuditLogger } from "../src/security/audit.js"; @@ -131,3 +135,65 @@ it("keeps the legacy stream completion and audit behavior", async () => { expect(app.counts()).toEqual({ calls: 0, streams: 1 }); } finally { app.close(); } }); + +it.skipIf(!hasCompletion)("closes a strict stream and records one failed audit when its pipe closes", async () => { + const directory = mkdtempSync(join(tmpdir(), "apcore-cli-closed-pipe-")); + const audit = join(directory, "audit.jsonl"); + const closed = join(directory, "producer-closed"); + const cliBundle = pathToFileURL(join(directory, "cli.mjs")).href; + const packageRoot = fileURLToPath(new URL("../", import.meta.url)); + try { + symlinkSync(join(packageRoot, "node_modules"), join(directory, "node_modules"), "junction"); + await build({ + entry: { cli: join(packageRoot, "src/index.ts") }, + config: false, + outDir: directory, + outExtension: () => ({ js: ".mjs" }), + format: ["esm"], + dts: false, + silent: true, + }); + const fixture = ` + import { writeFileSync } from "node:fs"; + import { Executor, Registry, STREAMING_MARKER, createAnnotations } from "apcore-js"; + const [bundle, audit, closed] = process.argv.slice(1); + const { AuditLogger, buildModuleCommand, setAuditLogger } = await import(bundle); + const moduleId = "test.pipe"; + const registry = new Registry(); + await registry.register(moduleId, { + description: "Write a provisional result", + annotations: createAnnotations({ streaming: true }), + [STREAMING_MARKER]: true, + inputSchema: { type: "object" }, + outputSchema: { type: "object" }, + execute() { return {}; }, + async *stream() { + try { yield { result: "provisional" }; } + finally { writeFileSync(closed, "closed"); } + }, + }); + setAuditLogger(new AuditLogger(audit)); + const cmd = buildModuleCommand(registry.getDefinition(moduleId), Executor.fromRegistry(registry), + undefined, undefined, undefined, { exit: code => { process.exitCode = code; } }); + await cmd.parseAsync(["--strict-stream"], { from: "user" }); + `; + const child = spawn(process.execPath, ["--input-type=module", "-e", fixture, cliBundle, audit, closed], { + cwd: packageRoot, + stdio: ["ignore", "pipe", "pipe"], + timeout: 5_000, + }); + child.stdout.destroy(); + let stderr = ""; + child.stderr.setEncoding("utf8").on("data", chunk => { stderr += chunk; }); + const [code, signal] = await once(child, "close"); + expect(signal).toBeNull(); + expect(code).toBe(1); + expect(stderr).not.toContain("Unhandled 'error' event"); + expect(JSON.parse(stderr)).toMatchObject({ error: true, exit_code: 1 }); + expect(readFileSync(closed, "utf8")).toBe("closed"); + const entries = readFileSync(audit, "utf8").trim().split("\n").map(line => JSON.parse(line)); + expect(entries).toMatchObject([{ module_id: "test.pipe", status: "error", exit_code: 1 }]); + } finally { + rmSync(directory, { recursive: true, force: true }); + } +}, 10_000); From 3e8705d743082303ca895aba68722b59674bd9ea Mon Sep 17 00:00:00 2001 From: tercel Date: Fri, 27 Nov 2026 13:46:11 +0800 Subject: [PATCH 22/36] fix(mcp): bind Python version hints to the published tool contract Signed-off-by: tercel --- mcp/python/README.md | 3 + mcp/python/src/apcore_mcp/server/factory.py | 71 +++++++- mcp/python/src/apcore_mcp/server/router.py | 104 ++++++++--- .../tests/server/test_versioned_tool_wire.py | 169 ++++++++++++++++++ 4 files changed, 318 insertions(+), 29 deletions(-) create mode 100644 mcp/python/tests/server/test_versioned_tool_wire.py diff --git a/mcp/python/README.md b/mcp/python/README.md index 735c445b..a104714f 100644 --- a/mcp/python/README.md +++ b/mcp/python/README.md @@ -735,6 +735,9 @@ For clients negotiating MCP 2025-06-18 or a later supported version, object outp Clients negotiating 2025-03-26 or 2024-11-05 retain text-only tools and results. Stdio and SSE use the negotiated session version; Streamable HTTP uses the trusted `MCP-Protocol-Version` header on each request, defaulting to 2025-03-26 when absent. Client-supplied request metadata cannot enable structured output. +A `tools/call` version hint at `_meta.apcore.version` can select another registration under the same tool name when its published contract matches. A request for a different contract is rejected before execution. Core must be able to identify the selected registration's descriptor, and older Core can only preflight its default version. Background tool execution does not accept version hints. + + ## Development ```bash diff --git a/mcp/python/src/apcore_mcp/server/factory.py b/mcp/python/src/apcore_mcp/server/factory.py index bf500e04..15f4a48d 100644 --- a/mcp/python/src/apcore_mcp/server/factory.py +++ b/mcp/python/src/apcore_mcp/server/factory.py @@ -13,7 +13,8 @@ import anyio import jsonschema # type: ignore[import-untyped] # MCP supplies jsonschema without its optional typing stubs. -from apcore import CancelToken, Identity +from apcore import CancelToken, Identity, ModuleError +from apcore import Registry as CoreRegistry from apcore.schema.exporter import SchemaExporter from apcore.schema.types import SchemaDefinition from mcp import types as mcp_types @@ -30,6 +31,7 @@ from apcore_mcp.auth.middleware import _REQUEST_IDENTITY_KEY, auth_identity_var from apcore_mcp.server.approval_bridge import ApprovalBridge from apcore_mcp.server.async_task_bridge import RESERVED_PREFIX, AsyncTaskBridge +from apcore_mcp.server.router import ExecutionRouter, _descriptor_version_hint, _matches_registered_version from apcore_mcp.server.transport import _protocol_source_var, transport_session_var logger = logging.getLogger(__name__) @@ -481,6 +483,15 @@ def build_tools( logger.warning("Skipped module %s: no definition found", module_id) continue try: + # Advertise the same registration used when an unhinted + # request takes the module's configured version default. + version_hint = _descriptor_version_hint(descriptor) + if isinstance(registry, CoreRegistry) and version_hint is not None: + selected = registry.get_definition(module_id, version_hint) + if selected is not None and _matches_registered_version( + registry, module_id, version_hint, selected.version, + ): + descriptor = selected # Keep compatibility arguments while preserving the runtime schema. tools.append(self.build_tool(descriptor, registry=registry, strict=strict)) except ValueError as e: @@ -496,6 +507,45 @@ def build_tools( continue return tools + def _bind_requested_version( + self, + router: ExecutionRouter, + published: mcp_types.Tool, + extra: dict[str, Any], + *, + async_enabled: bool, + ) -> str | None: + try: + selection = router._select_wire_version(published.name, extra) + except ModuleError as error: + return self._error_mapper.to_mcp_error(error)["message"] + if selection is None: + return None + selected, default, can_pin = selection + mismatch = f"Requested version {selected.version} does not match the advertised tool contract." + try: + selected_tool = self.build_tool(selected) + except ValueError: + return mismatch + fields = {"inputSchema", "annotations", "meta"} + if _supports_structured_output(): + fields.add("outputSchema") + published_contract = json.dumps(published.model_dump(mode="json", include=fields), sort_keys=True) + selected_contract = json.dumps(selected_tool.model_dump(mode="json", include=fields), sort_keys=True) + if selected_tool.name != published.name or published_contract != selected_contract: + return mismatch + if not can_pin: + return "This Core version cannot confirm the requested tool registration." + if async_enabled: + default_async = AsyncTaskBridge.is_async_module(default) + if default_async != AsyncTaskBridge.is_async_module(selected): + return mismatch + if default_async: + return "Version hints are unavailable for background tool execution." + extra["version_hint"] = selected.version + extra["_mcp_wire_version"] = True + return None + def register_handlers( self, server: Server, @@ -537,6 +587,8 @@ def register_handlers( if approval_bridge is not None: combined_tools.extend(approval_bridge.build_meta_tools()) + regular_tool_ids = {id(tool) for tool in tools} + @server.list_tools() async def handle_list_tools() -> list[mcp_types.Tool]: if _supports_structured_output(): @@ -576,6 +628,21 @@ async def send_notification(notification: dict[str, Any]) -> None: extra["send_notification"] = send_notification extra["progress_token"] = progress_token + published = next((tool for tool in reversed(combined_tools) if tool.name == name), None) + if ( + published is not None + and id(published) in regular_tool_ids + and isinstance(router, ExecutionRouter) + ): + error = self._bind_requested_version( + router, + published, + extra, + async_enabled=async_bridge is not None and descriptor_lookup is not None, + ) + if error is not None: + return _build_call_result([mcp_types.TextContent(type="text", text=error)], True, None) + # Meta-tool route: handled entirely by the async bridge. if async_bridge is not None and async_bridge.is_meta_tool(name): content, is_error, _trace_id = await async_bridge.handle_meta_tool( @@ -655,7 +722,7 @@ async def send_notification(notification: dict[str, Any]) -> None: text_contents.append(mcp_types.TextContent(type="text", text=item["text"], _meta=item_meta)) else: text_contents.append(mcp_types.TextContent(type="text", text=item["text"])) - output_schema = next((tool.outputSchema for tool in reversed(combined_tools) if tool.name == name), None) + output_schema = published.outputSchema if published is not None else None return _build_call_result(text_contents, is_error, output_schema) def register_resource_handlers( diff --git a/mcp/python/src/apcore_mcp/server/router.py b/mcp/python/src/apcore_mcp/server/router.py index f34ec0b2..e539c87b 100644 --- a/mcp/python/src/apcore_mcp/server/router.py +++ b/mcp/python/src/apcore_mcp/server/router.py @@ -13,6 +13,8 @@ from typing import Any from apcore import APCore, CancelToken, Context, Executor, ModuleError, StreamingModule +from apcore.registry.types import ModuleDescriptor +from apcore.registry.version import matches_version_hint from apcore.trace_context import TraceContext, TraceParent from apcore_mcp.adapters.errors import ErrorMapper @@ -29,6 +31,31 @@ _POLICY_SKIPS = {"not_configured", "no_match", "strategy_skipped"} +def _request_version_hint(extra: dict[str, Any] | None) -> str | None: + if extra is None: + return None + if extra.get("version_hint") is not None: + return extra["version_hint"] + meta = extra.get("_meta") + apcore_meta = meta.get("apcore") if isinstance(meta, dict) else None + version = apcore_meta.get("version") if isinstance(apcore_meta, dict) else None + return version if isinstance(version, str) else None + + +def _descriptor_version_hint(descriptor: Any) -> str | None: + metadata = getattr(descriptor, "metadata", None) + hint = metadata.get("version_hint") if isinstance(metadata, dict) else None + return hint if isinstance(hint, str) else None + + +def _matches_registered_version(registry: Any, module_id: str, requested: str, reported: str) -> bool: + # Older Core releases resolved the instance but could report another + # registration's version and annotations in the descriptor. + return matches_version_hint(reported, requested) and ( + registry.get(module_id, reported) is registry.get(module_id, requested) + ) + + def _deep_merge(base: dict[str, Any], overlay: dict[str, Any], depth: int = 0) -> dict[str, Any]: """Recursively merge *overlay* into *base*, capped at ``_DEEP_MERGE_MAX_DEPTH``. @@ -90,6 +117,11 @@ def __init__( self._trace_executor = executor.executor if isinstance(executor, APCore) else executor self._error_mapper = ErrorMapper() self._validate_inputs = validate_inputs + self._versioned_preflight = ( + self._core_backend + and validate_inputs + and "version_hint" in inspect.signature(executor.validate).parameters + ) self._output_formatter = output_formatter self._output_format = output_format self._redact_output = redact_output @@ -190,16 +222,38 @@ def _maybe_redact(self, tool_name: str, result: Any, output_schema: dict[str, An logger.warning("redact_sensitive failed for %s, returning unredacted output", tool_name, exc_info=True) return result + def _select_wire_version( + self, tool_name: str, extra: dict[str, Any] + ) -> tuple[ModuleDescriptor, ModuleDescriptor | None, bool] | None: + """Resolve a hinted Core registration before comparing it with the advertised tool.""" + if not self._core_backend: + return None + registry = self._executor.registry + default = registry.get_definition(tool_name) + version_hint = _request_version_hint(extra) + if version_hint is None: + version_hint = _descriptor_version_hint(default) + if version_hint is None: + return None + selected = registry.get_definition(tool_name, version_hint) + if selected is None: + raise ModuleError("MODULE_NOT_FOUND", f"Module '{tool_name}' not found for the requested version") + return selected, default, _matches_registered_version(registry, tool_name, version_hint, selected.version) + def _output_projection( self, tool_name: str, version_hint: str | None ) -> tuple[str | None, dict[str, Any] | None]: if not self._redact_output or not self._core_backend or version_hint is None: return version_hint, None - definition = self._executor.registry.get_definition(tool_name, version_hint) + registry = self._executor.registry + definition = registry.get_definition(tool_name, version_hint) if definition is None: raise ModuleError("MODULE_NOT_FOUND", f"Module '{tool_name}' not found") - # Resolve a range once, so execution and projection use the same registration. - return definition.version, definition.output_schema + # Pin only when Core can report the actual selected version. Direct + # router callers can still pass the original range to older Core. + if _matches_registered_version(registry, tool_name, version_hint, definition.version): + version_hint = definition.version + return version_hint, definition.output_schema def _format_result(self, result: Any) -> str: """Format an execution result into text for LLM consumption. @@ -524,24 +578,8 @@ async def _elicit_callback( cancel_token=cancel_token, ) - # version_hint resolution per spec's 3-source cascade: [A-D-006] - # 1. extras.version_hint (SDK caller-supplied, highest priority) - # 2. extras._meta.apcore.version (MCP client-supplied) - # 3. descriptor.metadata.version_hint (descriptor default, lowest) - # Pre-fix Python only consulted #1 and #2; #3 was never read. - version_hint: str | None = None - if extra is not None: - version_hint = extra.get("version_hint") - if version_hint is None: - meta = extra.get("_meta") - if isinstance(meta, dict): - apcore_meta = meta.get("apcore") - if isinstance(apcore_meta, dict): - raw = apcore_meta.get("version") - if isinstance(raw, str): - version_hint = raw - # Source #3: descriptor default fallback. Read the same descriptor - # to route annotated streaming modules without progress metadata. + # Explicit SDK hint, then MCP metadata, then descriptor default. + version_hint = _request_version_hint(extra) descriptor = None if version_hint is None or callable(self._open_completed_stream): registry = getattr(self._executor, "registry", None) @@ -551,16 +589,28 @@ async def _elicit_callback( descriptor = get_def(tool_name) except Exception: # noqa: BLE001 # defensive — registry may raise descriptor = None - if descriptor is not None and version_hint is None: - meta_attr = getattr(descriptor, "metadata", None) or {} - raw = meta_attr.get("version_hint") if isinstance(meta_attr, dict) else None - if isinstance(raw, str): - version_hint = raw + if version_hint is None: + version_hint = _descriptor_version_hint(descriptor) # Pre-execution validation if self._validate_inputs: try: - validation = self._executor.validate(tool_name, arguments, context) + preflight_options: dict[str, str | None] = {} + if extra is not None and extra.get("_mcp_wire_version") is True: + if self._versioned_preflight: + preflight_options["version_hint"] = version_hint + else: + registry = self._executor.registry + if registry.get(tool_name, version_hint) is not registry.get(tool_name): + return ( + [{ + "type": "text", + "text": "This Core version cannot preflight a non-default module version", + }], + True, + None, + ) + validation = self._executor.validate(tool_name, arguments, context, **preflight_options) if not validation.valid: parts: list[str] = [] for e in validation.errors: diff --git a/mcp/python/tests/server/test_versioned_tool_wire.py b/mcp/python/tests/server/test_versioned_tool_wire.py new file mode 100644 index 00000000..8107f2ca --- /dev/null +++ b/mcp/python/tests/server/test_versioned_tool_wire.py @@ -0,0 +1,169 @@ +"""MCP discovery and requested version selection through a real client session.""" + +from __future__ import annotations + +import json +from collections.abc import AsyncIterator +from contextlib import asynccontextmanager + +import anyio +import pytest +from apcore import Executor, Registry +from mcp import ClientSession, types + +from apcore_mcp import APCoreMCP +from apcore_mcp.server.router import ExecutionRouter +from apcore_mcp.server.transport import TransportManager + +_MODULE = "fixture.versioned" + + +class Report: + description = "Return a synthetic count" + input_schema = {"type": "object"} + + def __init__(self, field: str, value: int) -> None: + self.field = field + self.value = value + self.calls = 0 + self.output_schema = { + "type": "object", + "properties": {field: {"type": "integer"}}, + "required": [field], + } + + async def execute(self, inputs, context) -> dict[str, int]: + self.calls += 1 + return {self.field: self.value} + + +@asynccontextmanager +async def connected_client(registry: Registry, **options) -> AsyncIterator[ClientSession]: + server, _, _, init, _ = APCoreMCP(registry, **options)._build_server_components() + send_client, read_server = anyio.create_memory_object_stream(10) + send_server, read_client = anyio.create_memory_object_stream(10) + with anyio.fail_after(5): + async with anyio.create_task_group() as group: + group.start_soon(TransportManager()._run_scoped, server, read_server, send_server, init, "test") + async with ClientSession(read_client, send_client) as session: + await session.initialize() + yield session + group.cancel_scope.cancel() + + +@pytest.mark.parametrize("redact_output", [True, False]) +async def test_version_with_different_public_output_is_rejected_before_execution(redact_output: bool) -> None: + registry = Registry() + older = Report("older_count", 1) + current = Report("count", 2) + registry.register(_MODULE, older, version="1.0.0") + registry.register(_MODULE, current, version="2.0.0") + + async with connected_client(registry, redact_output=redact_output) as session: + tools = await session.list_tools() + assert tools.tools[0].outputSchema["required"] == ["count"] + hinted = await session.call_tool(_MODULE, {}, meta={"apcore": {"version": "^1.0"}}) + assert older.calls == 0 + assert hinted.isError + assert "does not match the advertised tool contract" in hinted.content[0].text + default = await session.call_tool(_MODULE, {}) + + assert not default.isError + assert default.structuredContent == {"count": 2} + assert current.calls == 1 + + +@pytest.mark.parametrize(("legacy", "validate_inputs"), [(True, False), (False, False), (False, True)]) +async def test_compatible_version_hint_uses_requested_version(legacy: bool, validate_inputs: bool, monkeypatch) -> None: + registry = Registry() + older = Report("count", 1) + current = Report("count", 2) + registry.register(_MODULE, older, version="1.0.0") + registry.register(_MODULE, current, version="2.0.0") + if legacy: + monkeypatch.setattr(types, "LATEST_PROTOCOL_VERSION", "2025-03-26") + + async with connected_client(registry, redact_output=False, validate_inputs=validate_inputs) as session: + tools = await session.list_tools() + assert (tools.tools[0].outputSchema is None) is legacy + result = await session.call_tool(_MODULE, {}, meta={"apcore": {"version": "^1.0"}}) + default = await session.call_tool(_MODULE, {}, meta={"apcore": {"version": "^2.0"}}) + assert not default.isError + assert json.loads(default.content[0].text) == {"count": 2} + assert current.calls == 1 + if registry.get_definition(_MODULE, "^1.0").version == "1.0.0": + assert not result.isError + assert json.loads(result.content[0].text) == {"count": 1} + assert result.structuredContent == (None if legacy else {"count": 1}) + assert older.calls == 1 + else: + assert result.isError + assert "cannot confirm the requested tool registration" in result.content[0].text + assert older.calls == 0 + + +async def test_compatible_client_input_does_not_hide_a_different_advertised_input_contract() -> None: + registry = Registry() + older = Report("count", 1) + older.input_schema = {"type": "object", "properties": {"scale": {"type": "integer"}}} + registry.register(_MODULE, older, version="1.0.0") + registry.register(_MODULE, Report("count", 2), version="2.0.0") + + async with connected_client(registry) as session: + hinted = await session.call_tool(_MODULE, {}, meta={"apcore": {"version": "^1.0"}}) + + assert hinted.isError + assert "does not match the advertised tool contract" in hinted.content[0].text + assert older.calls == 0 + + +async def test_configured_default_uses_its_advertised_contract() -> None: + registry = Registry() + older = Report("older_count", 1) + current = Report("count", 2) + registry.register(_MODULE, older, version="1.0.0") + registry.register(_MODULE, current, version="2.0.0", metadata={"version_hint": "^1.0"}) + + async with connected_client(registry) as session: + tools = await session.list_tools() + default = await session.call_tool(_MODULE, {}) + if registry.get_definition(_MODULE, "^1.0").version == "1.0.0": + assert tools.tools[0].outputSchema["required"] == ["older_count"] + assert not default.isError + assert default.structuredContent == {"older_count": 1} + assert (older.calls, current.calls) == (1, 0) + else: + assert tools.tools[0].outputSchema["required"] == ["count"] + assert default.isError + assert (older.calls, current.calls) == (0, 0) + + +async def test_background_hint_reports_unavailable_before_submission() -> None: + registry = Registry() + report = Report("count", 2) + registry.register(_MODULE, report, version="2.0.0", metadata={"async": True}) + + async with connected_client(registry, async_tasks=True) as session: + hinted = await session.call_tool(_MODULE, {}, meta={"apcore": {"version": "^2.0"}}) + assert hinted.isError + assert "Version hints are unavailable for background tool execution" in hinted.content[0].text + assert report.calls == 0 + ordinary = await session.call_tool(_MODULE, {}) + + assert not ordinary.isError + assert json.loads(ordinary.content[0].text)["task_id"] + + +async def test_direct_router_keeps_version_hint_without_a_published_contract() -> None: + registry = Registry() + older = Report("older_count", 1) + current = Report("count", 2) + registry.register(_MODULE, older, version="1.0.0") + registry.register(_MODULE, current, version="2.0.0") + + router = ExecutionRouter(Executor(registry)) + output, is_error, _ = await router.handle_call(_MODULE, {}, extra={"version_hint": "^1.0"}) + + assert not is_error + assert json.loads(output[0]["text"]) == {"older_count": 1} + assert (older.calls, current.calls) == (1, 0) From 52d250a3e992be848bda1377066c1e86d48da250 Mon Sep 17 00:00:00 2001 From: tercel Date: Fri, 27 Nov 2026 13:47:25 +0800 Subject: [PATCH 23/36] fix(toolkit): verify TypeScript proxy registration after it settles Signed-off-by: tercel --- toolkit/docs/features/output-writers.md | 10 ++- toolkit/typescript/CHANGELOG.md | 4 + toolkit/typescript/README.md | 9 +- .../src/output/http-proxy-writer.ts | 58 +++++++----- .../tests/http-cancellation-deadlines.test.ts | 14 +-- .../tests/http-proxy-writer.test.ts | 90 ++++++++++++++++--- .../typescript/tests/http-slow-body.test.ts | 5 +- .../openapi-effective-parameters.test.ts | 18 ++-- 8 files changed, 151 insertions(+), 57 deletions(-) diff --git a/toolkit/docs/features/output-writers.md b/toolkit/docs/features/output-writers.md index 217a365b..d1eb257e 100644 --- a/toolkit/docs/features/output-writers.md +++ b/toolkit/docs/features/output-writers.md @@ -246,7 +246,7 @@ Registers scanned modules as HTTP proxy classes that forward requests to a runni baseUrl: "http://localhost:8000", authHeaderFactory: () => ({ Authorization: "Bearer xxx" }), }); - writer.write(modules, registry); + const results = await writer.writeAsync(modules, registry); ``` === "Rust" @@ -417,16 +417,18 @@ An `unsupported_input` has operation scope and includes `location`, ### Inputs - `modules`: list of `ScannedModule`, required -- `registry`: `apcore.Registry` (Python) / `Registry` (TypeScript, from `apcore-js`) / `&apcore::Registry` (Rust), required — the live registry to register HTTP proxy modules into +- `registry`: the live registry into which proxies are registered. Python and Rust accept their Core registries. In TypeScript, use `write()` for synchronous registries and `await writeAsync()` for apcore-js or other registries whose `register()` returns a promise. ### Errors - None raised. Per-module failures (registry rejection, target validation, proxy-class build error) are captured into a failed `WriteResult` (Python: `verified=False, verification_error=...`; TypeScript: `createWriteResult(..., false, msg)`; Rust: `WriteResult::failed(...)`) and returned in the result list, so one failing module does not abort the batch. HTTP requests themselves are issued later, at module call-time — not during `write`. Callers should iterate the returned list and check each entry's `verified` field. ### Returns -- On success: list of `WriteResult` — `path` is `None`/`null` (no file written) +- One `WriteResult` per module, in input order. `path` is `None`/`null` because the writer creates no files. +- TypeScript `writeAsync()` resolves to a result array after the registrations settle and reports any rejection on its module's result. +- If TypeScript `write()` detects a promise-like return, it handles its rejection and returns a failed result directing the caller to `writeAsync()`. The registration may already have started and can still complete. Check the registry before retrying the same ID. ### Properties -- async: false +- async: `false` for `write()`. The TypeScript `writeAsync()` returns `Promise`. - pure: false (mutates registry) - availability: Python (always — requires `httpx`; install with `apcore-toolkit[http-proxy]`), TypeScript (included in the standard package; uses global `fetch` — available in Node.js 20+, browsers, Deno, and workers), and Rust (the `http-proxy` Cargo feature is enabled by default so a vanilla dependency declaration exposes `HTTPProxyRegistryWriter`; opt out with `default-features = false` for lean builds). diff --git a/toolkit/typescript/CHANGELOG.md b/toolkit/typescript/CHANGELOG.md index 0ce86924..193193c1 100644 --- a/toolkit/typescript/CHANGELOG.md +++ b/toolkit/typescript/CHANGELOG.md @@ -8,6 +8,10 @@ All notable changes to this project will be documented in this file. - Add a standalone Prometheus listener with liveness and readiness endpoints and isolate it from Core metrics rendering. +### Fixed + +- Await Core registry validation with `HTTPProxyRegistryWriter.writeAsync()`, which records per-module registration failures. The synchronous `write()` still returns a result array and reports promise-like registrations as unverified. + ## [0.15.0] - Unreleased ### Added diff --git a/toolkit/typescript/README.md b/toolkit/typescript/README.md index 8dc26918..80ed64df 100644 --- a/toolkit/typescript/README.md +++ b/toolkit/typescript/README.md @@ -226,10 +226,15 @@ const doc = await resp.json(); const modules = new BindingParser().loadData(doc); // Register each module as an HTTP proxy in an in-browser registry. -const writer = new HTTPProxyRegistryWriter({ baseUrl: '/api' }); -await writer.write(modules, registry); +const writer = new HTTPProxyRegistryWriter({ baseUrl: new URL('/api', location.href).href }); +const results = await writer.writeAsync(modules, registry); ``` +Use `writeAsync()` for Core registries and check each result's `verified` field. +`write()` returns an immediate result array for synchronous registries. If a +registry returns a promise, `write()` reports it as unverified and handles any +rejection. The registration may continue after the call returns. + The default entry continues to re-export every symbol it always did (for tri-SDK parity with the Python and Rust toolkits and for unchanged behaviour in `nestjs-apcore` etc.). The `/browser` subpath is strictly additive — it diff --git a/toolkit/typescript/src/output/http-proxy-writer.ts b/toolkit/typescript/src/output/http-proxy-writer.ts index b8a79566..fc6804f3 100644 --- a/toolkit/typescript/src/output/http-proxy-writer.ts +++ b/toolkit/typescript/src/output/http-proxy-writer.ts @@ -18,7 +18,7 @@ * baseUrl: 'http://localhost:8000', * authHeaderFactory: () => ({ Authorization: 'Bearer xxx' }), * }); - * const results = await writer.write(modules, registry); + * const results = await writer.writeAsync(modules, registry); * ``` */ @@ -70,9 +70,9 @@ function percentEncodePathSegment(value: string): string { } /** - * Shape of a registry that `HTTPProxyRegistryWriter` writes to. + * Minimal registry interface for the proxy writer. * - * Mirrors the minimal surface used by `RegistryWriter.write()`. + * Use `writeAsync()` if the method returns a promise, as apcore-js does. */ export interface ProxyRegistry { register(moduleId: string, module: unknown): void; @@ -211,6 +211,11 @@ function extractErrorMessage(resp: Response, text: string): string { return text.slice(0, 200); } +function failedRegistration(moduleId: string, error: unknown): WriteResult { + const diagnostic = error instanceof Error ? `${error.name}: ${error.message}` : String(error); + return createWriteResult(moduleId, null, false, diagnostic); +} + /** * Register each {@link ScannedModule} as an HTTP proxy module in the * provided registry. Each registered module's `execute()` forwards its @@ -270,29 +275,40 @@ export class HTTPProxyRegistryWriter { } /** - * Register each module's HTTP proxy into the registry. - * - * Returns one {@link WriteResult} per module. A module that fails to - * build is reported with `verified: false` rather than throwing, so - * one bad module does not abort the batch. - * - * The method is synchronous — `write` performs no I/O, only registry - * mutation. This matches the spec property `async: false` and the - * Python and Rust SDKs. (HTTP requests happen later, at module call - * time.) The previous `async` modifier was return-type sugar with no - * internal `await`; existing callers using `await writer.write(...)` - * keep working because `await` on a non-promise resolves immediately. + * Register proxies in a synchronous registry and return one result per module. + * A promise-like return cannot establish success here. If detected, its + * rejection is consumed and the result directs the caller to `writeAsync()`. + * The registration may already have started by the time this is detected. */ write(modules: ScannedModule[], registry: ProxyRegistry): WriteResult[] { + return modules.map((mod) => { + try { + const registration: unknown = registry.register(mod.moduleId, this.buildFunctionModule(mod)); + const then = (registration as { then?: unknown } | null | undefined)?.then; + if (typeof then === 'function') { + void Promise.resolve({ then: then.bind(registration) }).catch(() => undefined); + throw new TypeError('Registry registration returned a promise. Use writeAsync() to await registration.'); + } + return createWriteResult(mod.moduleId); + } catch (error) { + return failedRegistration(mod.moduleId, error); + } + }); + } + + /** + * Build and register proxies in input order, waiting for each registration. + * A build error, thrown registration error, or rejected registration promise + * produces a failed result without stopping the rest of the batch. + */ + async writeAsync(modules: ScannedModule[], registry: ProxyRegistry): Promise { const results: WriteResult[] = []; for (const mod of modules) { try { - const fm = this.buildFunctionModule(mod); - registry.register(mod.moduleId, fm); - results.push(createWriteResult(mod.moduleId, null, true)); - } catch (err) { - const msg = err instanceof Error ? `${err.name}: ${err.message}` : String(err); - results.push(createWriteResult(mod.moduleId, null, false, msg)); + await registry.register(mod.moduleId, this.buildFunctionModule(mod)); + results.push(createWriteResult(mod.moduleId)); + } catch (error) { + results.push(failedRegistration(mod.moduleId, error)); } } return results; diff --git a/toolkit/typescript/tests/http-cancellation-deadlines.test.ts b/toolkit/typescript/tests/http-cancellation-deadlines.test.ts index 7b86bd80..8a42617a 100644 --- a/toolkit/typescript/tests/http-cancellation-deadlines.test.ts +++ b/toolkit/typescript/tests/http-cancellation-deadlines.test.ts @@ -23,10 +23,10 @@ function stalledBodyFetch(status = 200): { fetchImpl: typeof fetch; signals: Abo return { fetchImpl, signals }; } -function proxy(fetchImpl: typeof fetch, timeout = 250, authHeaderFactory?: () => Record) { +async function proxy(fetchImpl: typeof fetch, timeout = 250, authHeaderFactory?: () => Record) { const registry = new Registry(); const writer = new HTTPProxyRegistryWriter({ baseUrl: 'https://example.test', fetchImpl, timeoutMs: timeout, authHeaderFactory }); - const results = writer.write([createScannedModule({ + const results = await writer.writeAsync([createScannedModule({ moduleId: 'probe.get', description: 'probe', target: 'probe:get', inputSchema: { type: 'object' }, outputSchema: { type: 'object' }, tags: [], metadata: { httpMethod: 'GET', urlPath: '/probe' }, @@ -52,7 +52,7 @@ describe('HTTP proxy cancellation', () => { const token = new CancelToken(); token.cancel(); const fetchImpl = vi.fn(async () => new Response('{}')); const auth = vi.fn(() => ({})); - await expect(proxy(fetchImpl, 250, auth).execute({}, Context.create(null, null, token))) + await expect((await proxy(fetchImpl, 250, auth)).execute({}, Context.create(null, null, token))) .rejects.toBeInstanceOf(ExecutionCancelledError); expect(fetchImpl).not.toHaveBeenCalled(); expect(auth).not.toHaveBeenCalled(); @@ -69,7 +69,7 @@ describe('HTTP proxy cancellation', () => { signal.addEventListener('abort', () => reject(new DOMException('Aborted', 'AbortError')), { once: true }); }); }; - const outcome = proxy(fetchImpl).execute({}, Context.create(null, null, token)) + const outcome = (await proxy(fetchImpl)).execute({}, Context.create(null, null, token)) .then(value => ({ value, error: null }), (error: unknown) => ({ value: null, error })); await vi.advanceTimersByTimeAsync(25); token.cancel(); @@ -82,7 +82,7 @@ describe('HTTP proxy cancellation', () => { it('does not start a request if cancellation happens while credentials are resolved', async () => { const token = new CancelToken(); const fetchImpl = vi.fn(async () => new Response('{}')); - const module = proxy(fetchImpl, 250, () => { token.cancel(); return {}; }); + const module = await proxy(fetchImpl, 250, () => { token.cancel(); return {}; }); await expect(module.execute({}, Context.create(null, null, token))) .rejects.toBeInstanceOf(ExecutionCancelledError); expect(fetchImpl).not.toHaveBeenCalled(); @@ -97,7 +97,7 @@ describe('HTTP proxy cancellation', () => { if (outcome === 'failure') throw new Error('offline'); return new Response('{"ok":true}'); }; - const result = proxy(fetchImpl).execute({}, Context.create(null, null, token)); + const result = (await proxy(fetchImpl)).execute({}, Context.create(null, null, token)); if (outcome === 'failure') await expect(result).rejects.toThrow('HTTP transport error'); else await expect(result).resolves.toEqual({ ok: true }); const added = add.mock.calls.filter(([name]) => name === 'abort'); @@ -111,7 +111,7 @@ describe('HTTP timeouts cover response bodies', () => { it.each([200, 500])('bounds proxy body reads for status %s without a context token', async (status) => { vi.useFakeTimers(); const { fetchImpl, signals } = stalledBodyFetch(status); - const outcome = proxy(fetchImpl).execute({}, Context.create()) + const outcome = (await proxy(fetchImpl)).execute({}, Context.create()) .then(() => null, (error: unknown) => error); await vi.advanceTimersByTimeAsync(251); expect(signals[0].aborted).toBe(true); diff --git a/toolkit/typescript/tests/http-proxy-writer.test.ts b/toolkit/typescript/tests/http-proxy-writer.test.ts index 614d85c0..2078acbb 100644 --- a/toolkit/typescript/tests/http-proxy-writer.test.ts +++ b/toolkit/typescript/tests/http-proxy-writer.test.ts @@ -1,4 +1,4 @@ -import { describe, it, expect, beforeEach } from 'vitest'; +import { describe, it, expect, beforeEach, vi } from 'vitest'; import { Registry } from 'apcore-js'; import type { Context } from 'apcore-js'; @@ -80,13 +80,79 @@ describe('HTTPProxyRegistryWriter', () => { registry = new Registry(); }); + it('returns immediate array results for a synchronous registry', () => { + const writer = new HTTPProxyRegistryWriter({ baseUrl: 'https://example.invalid' }); + const registered: string[] = []; + const register = (moduleId: string): void => { + if (moduleId === 'tasks.denied') throw new Error('Rejected synchronously'); + registered.push(moduleId); + }; + const results = writer.write([mkModule({ moduleId: 'tasks.denied' }), mkModule()], { register }); + + expect(Array.isArray(results)).toBe(true); + expect(results).toMatchObject([ + { moduleId: 'tasks.denied', verified: false, verificationError: 'Error: Rejected synchronously' }, + { moduleId: 'tasks.create', verified: true, verificationError: null }, + ]); + expect(registered).toEqual(['tasks.create']); + }); + + it('does not report a returned thenable as verified and consumes its rejection', async () => { + const writer = new HTTPProxyRegistryWriter({ baseUrl: 'https://example.invalid' }); + const then = vi.fn((_resolve: () => void, reject: (error: Error) => void) => { + reject(new Error('Custom registry rejected registration')); + }); + const register = vi.fn(() => ({ then })); + const [result] = writer.write([mkModule()], { register }); + + expect(result.verified).toBe(false); + expect(result.verificationError).toContain('writeAsync()'); + expect(register).toHaveBeenCalledOnce(); + await Promise.resolve(); + expect(then).toHaveBeenCalledOnce(); + }); + + it('waits for Core registration, reports its rejection, and continues the batch', async () => { + const writer = new HTTPProxyRegistryWriter({ baseUrl: 'https://example.invalid' }); + const started = Promise.withResolvers(); + const release = Promise.withResolvers(); + registry.setValidator({ + async validate(module) { + if ((module as { description?: string }).description !== 'reject this module') return []; + started.resolve(); + await release.promise; + return ['Rejected by host validation']; + }, + }); + const rejected = mkModule({ moduleId: 'tasks.denied', description: 'reject this module' }); + const settled = vi.fn(); + const results = writer.writeAsync([rejected, mkModule()], registry).then(settled); + try { + await started.promise; + expect(settled).not.toHaveBeenCalled(); + expect(registry.get(rejected.moduleId)).toBeNull(); + } finally { + release.resolve(); + await results; + } + + expect(settled).toHaveBeenCalledExactlyOnceWith([ + { + moduleId: 'tasks.denied', path: null, verified: false, + verificationError: expect.stringContaining('Rejected by host validation'), + }, + { moduleId: 'tasks.create', path: null, verified: true, verificationError: null }, + ]); + expect(registry.list()).toEqual(['tasks.create']); + }); + it('registers each module with WriteResult verified=true', async () => { const { fetchImpl } = recordingFetch(() => jsonResponse(200, { ok: true })); const writer = new HTTPProxyRegistryWriter({ baseUrl: 'http://localhost:8000', fetchImpl, }); - const results = await writer.write([mkModule()], registry); + const results = await writer.writeAsync([mkModule()], registry); expect(results).toHaveLength(1); expect(results[0].verified).toBe(true); expect(results[0].moduleId).toBe('tasks.create'); @@ -98,7 +164,7 @@ describe('HTTPProxyRegistryWriter', () => { baseUrl: 'http://localhost:8000', fetchImpl, }); - await writer.write([mkModule()], registry); + await writer.writeAsync([mkModule()], registry); const mod = getRegistered(registry, 'tasks.create'); const result = await mod.execute({ title: 'a' }, {} as Context); expect(calls).toHaveLength(1); @@ -114,7 +180,7 @@ describe('HTTPProxyRegistryWriter', () => { baseUrl: 'http://localhost:8000', fetchImpl, }); - await writer.write( + await writer.writeAsync( [ mkModule({ moduleId: 'tasks.update', @@ -138,7 +204,7 @@ describe('HTTPProxyRegistryWriter', () => { baseUrl: 'http://localhost:8000', fetchImpl, }); - await writer.write( + await writer.writeAsync( [ mkModule({ moduleId: 'tasks.fetch', @@ -161,7 +227,7 @@ describe('HTTPProxyRegistryWriter', () => { baseUrl: 'http://localhost:8000', fetchImpl, }); - await writer.write( + await writer.writeAsync( [ mkModule({ moduleId: 'tasks.miss', @@ -181,7 +247,7 @@ describe('HTTPProxyRegistryWriter', () => { baseUrl: 'http://localhost:8000', fetchImpl, }); - await writer.write( + await writer.writeAsync( [ mkModule({ moduleId: 'tasks.list', @@ -206,7 +272,7 @@ describe('HTTPProxyRegistryWriter', () => { authHeaderFactory: () => ({ Authorization: 'Bearer xxx' }), fetchImpl, }); - await writer.write([mkModule()], registry); + await writer.writeAsync([mkModule()], registry); await getRegistered(registry, 'tasks.create').execute({}, {} as Context); expect(calls[0].headers['Authorization']).toBe('Bearer xxx'); }); @@ -219,7 +285,7 @@ describe('HTTPProxyRegistryWriter', () => { baseUrl: 'http://localhost:8000', fetchImpl, }); - await writer.write([mkModule()], registry); + await writer.writeAsync([mkModule()], registry); await expect( getRegistered(registry, 'tasks.create').execute({}, {} as Context), ).rejects.toThrow(/HTTP 400: invalid input/); @@ -230,7 +296,7 @@ describe('HTTPProxyRegistryWriter', () => { baseUrl: 'http://localhost:8000', fetchImpl: recordingFetch(() => jsonResponse(200, {})).fetchImpl, }); - const results = await writer.write( + const results = await writer.writeAsync( [ mkModule({ moduleId: 'tasks.bad', @@ -392,7 +458,7 @@ describe('HTTPProxyRegistryWriter', () => { outputSchema: { type: 'object', additionalProperties: true }, tags: [], }); - await writer.write([mod], registry); + await writer.writeAsync([mod], registry); const registered = getRegistered(registry, 'snake.module'); await registered.execute({ data: 'x' }, {} as Context); expect(calls).toHaveLength(1); @@ -414,7 +480,7 @@ describe('HTTPProxyRegistryWriter', () => { outputSchema: { type: 'object', additionalProperties: true }, tags: [], }); - await writer.write([mod], registry); + await writer.writeAsync([mod], registry); const registered = getRegistered(registry, 'camel.module'); await registered.execute({}, {} as Context); expect(calls).toHaveLength(1); diff --git a/toolkit/typescript/tests/http-slow-body.test.ts b/toolkit/typescript/tests/http-slow-body.test.ts index 61dee2f4..f736d73e 100644 --- a/toolkit/typescript/tests/http-slow-body.test.ts +++ b/toolkit/typescript/tests/http-slow-body.test.ts @@ -79,11 +79,12 @@ describe('real HTTP slow-body deadlines', () => { await withDrippingServer(status, async base => { const registry = new Registry(); const writer = new HTTPProxyRegistryWriter({ baseUrl: base, timeoutMs: TIMEOUT_MS }); - expect(writer.write([createScannedModule({ + const [result] = await writer.writeAsync([createScannedModule({ moduleId: 'probe.get', description: 'probe', target: 'probe:get', inputSchema: { type: 'object' }, outputSchema: { type: 'object' }, tags: [], metadata: { httpMethod: 'GET', urlPath: '/drip' }, - })], registry)[0].verified).toBe(true); + })], registry); + expect(result.verified).toBe(true); const module = registry.get('probe.get') as unknown as { execute(inputs: Record, ctx: Context): Promise>; }; diff --git a/toolkit/typescript/tests/openapi-effective-parameters.test.ts b/toolkit/typescript/tests/openapi-effective-parameters.test.ts index de1d07b2..5ccb55de 100644 --- a/toolkit/typescript/tests/openapi-effective-parameters.test.ts +++ b/toolkit/typescript/tests/openapi-effective-parameters.test.ts @@ -42,7 +42,7 @@ async function captureProxyRequests(exercise: (writer: HTTPProxyRegistryWriter) } describe('effective OpenAPI parameters', () => { - it('preserves boolean inputs reached directly and through schema and Parameter Object references', () => { + it('preserves boolean inputs reached directly and through schema and Parameter Object references', async () => { const spec = { openapi: '3.1.0', components: { @@ -115,7 +115,7 @@ describe('effective OpenAPI parameters', () => { const registry = new Registry(); const writer = new HTTPProxyRegistryWriter({ baseUrl: 'https://example.invalid' }); - const [registration] = writer.write([module], registry); + const [registration] = await writer.writeAsync([module], registry); expect(registration.verified, registration.verificationError ?? undefined).toBe(true); expect(registry.get(module.moduleId)?.description).toBe('GET /boolean'); const inputSchema = registry.get(module.moduleId)?.inputSchema; @@ -191,7 +191,7 @@ describe('effective OpenAPI parameters', () => { ]); }); - it('preserves conjunctive reference assertions and resolves fragment and array pointers', () => { + it('preserves conjunctive reference assertions and resolves fragment and array pointers', async () => { const spec = { openapi: '3.1.0', components: { schemas: { @@ -221,7 +221,7 @@ describe('effective OpenAPI parameters', () => { expect(module.outputSchema).toEqual({}); const registry = new Registry(); const writer = new HTTPProxyRegistryWriter({ baseUrl: 'https://example.invalid' }); - expect(writer.write([module], registry)[0].verified).toBe(true); + expect((await writer.writeAsync([module], registry))[0].verified).toBe(true); const schema = registry.get(module.moduleId)?.inputSchema; if (schema === undefined) throw new Error('Expected the HTTP proxy input schema'); expect(Value.Check(schema, { color: 'red' })).toBe(true); @@ -288,7 +288,7 @@ describe('effective OpenAPI parameters', () => { const requests = await captureProxyRequests(async writer => { for (const module of [selected, legacy]) { const registry = new Registry(); - expect(writer.write([module], registry)[0].verified).toBe(true); + expect((await writer.writeAsync([module], registry))[0].verified).toBe(true); const runtime = registry.get(module.moduleId); if (runtime === undefined) throw new Error('Expected the HTTP proxy module'); await runtime.execute({ tag: ['red', 'blue'] }, Context.create()); @@ -317,7 +317,7 @@ describe('effective OpenAPI parameters', () => { const requests = await captureProxyRequests(async writer => { for (const module of [effective, legacy]) { const registry = new Registry(); - expect(writer.write([module], registry)[0].verified).toBe(true); + expect((await writer.writeAsync([module], registry))[0].verified).toBe(true); const runtime = registry.get(module.moduleId); if (runtime === undefined) throw new Error('Expected the HTTP proxy module'); await runtime.execute({}, Context.create()); @@ -374,7 +374,7 @@ it('forwards literal OpenAPI colons and uses only brace placeholders', async () expect(detectEffectiveProxyHazards(modules)).toEqual([]); const requests = await captureProxyRequests(async writer => { const registry = new Registry(); - expect(writer.write(modules, registry).every(result => result.verified)).toBe(true); + expect((await writer.writeAsync(modules, registry)).every(result => result.verified)).toBe(true); await registry.get('inventory_search')!.execute({ item: 'a/b' }, Context.create()); await registry.get('static_search')!.execute({}, Context.create()); @@ -382,7 +382,7 @@ it('forwards literal OpenAPI colons and uses only brace placeholders', async () const legacyModules = new OpenAPIScanner().scan({ openapi: '3.1.0', paths: { '/legacy/:item': { get: { parameters: [parameter('item', 'path', 'string', true)], responses: response } }, } }); - expect(writer.write(legacyModules, legacy)[0].verified).toBe(true); + expect((await writer.writeAsync(legacyModules, legacy))[0].verified).toBe(true); await legacy.get(legacyModules[0].moduleId)!.execute({ item: 'a/b' }, Context.create()); }); expect(requests.map(request => request.url)).toEqual([ @@ -441,7 +441,7 @@ it('refuses complex effective input to an otherwise scalar path or query at exec }); const requests = await captureProxyRequests(async writer => { const registry = new Registry(); - expect(writer.write([module], registry)[0].verified).toBe(true); + expect((await writer.writeAsync([module], registry))[0].verified).toBe(true); const proxy = registry.get(module.moduleId)!; await expect(proxy.execute({ id: ['one'] }, Context.create())).rejects.toThrow(/Path parameter "id"/); await expect(proxy.execute({ id: 'one', filter: { color: 'red' } }, Context.create())).rejects.toThrow(/Query parameter "filter"/); From 17968fac48296f0a7351b84e6352e517755f6bad Mon Sep 17 00:00:00 2001 From: tercel Date: Fri, 27 Nov 2026 13:47:54 +0800 Subject: [PATCH 24/36] feat(mcp): store scoped Python approval grants atomically Signed-off-by: tercel --- mcp/python/src/apcore_mcp/__init__.py | 4 +- mcp/python/src/apcore_mcp/approval_store.py | 168 +++++++++++++++----- mcp/python/tests/test_approval_store.py | 40 ++++- 3 files changed, 168 insertions(+), 44 deletions(-) diff --git a/mcp/python/src/apcore_mcp/__init__.py b/mcp/python/src/apcore_mcp/__init__.py index f6e5ca59..b28e5a7d 100644 --- a/mcp/python/src/apcore_mcp/__init__.py +++ b/mcp/python/src/apcore_mcp/__init__.py @@ -29,7 +29,7 @@ from apcore_mcp.apcore_mcp import ( _load_config_bus_overrides as _load_config_bus_overrides, # noqa: F401 - re-export for tests ) -from apcore_mcp.approval_store import ApprovalStore, InMemoryApprovalStore +from apcore_mcp.approval_store import ApprovalScope, ApprovalStore, InMemoryApprovalStore, ScopedApprovalStore from apcore_mcp.auth import ( Authenticator, AuthMiddleware, @@ -83,8 +83,10 @@ "META_TOOL_NAMES", "APCORE_META_TOOL_PREFIX", # ApprovalStore and Phase B polling + "ApprovalScope", "ApprovalStore", "InMemoryApprovalStore", + "ScopedApprovalStore", "StorageBackedApprovalHandler", "ApprovalBridge", "APPROVAL_META_TOOL_NAMES", diff --git a/mcp/python/src/apcore_mcp/approval_store.py b/mcp/python/src/apcore_mcp/approval_store.py index d4253358..ec66fe04 100644 --- a/mcp/python/src/apcore_mcp/approval_store.py +++ b/mcp/python/src/apcore_mcp/approval_store.py @@ -9,8 +9,12 @@ import asyncio import contextlib +import hmac import logging +import threading import time +from copy import deepcopy +from dataclasses import dataclass from typing import Any, Protocol, runtime_checkable logger = logging.getLogger(__name__) @@ -44,6 +48,38 @@ async def resolve(self, approval_id: str, *, approved: bool, reason: str | None ... +ApprovalPrincipal = tuple[str, str] | None + + +@dataclass(frozen=True) +class ApprovalScope: + """Trusted caller and immutable snapshot of the requested invocation.""" + + principal: ApprovalPrincipal + caller_id: str | None + module_id: str + arguments_digest: str + + +@runtime_checkable +class ScopedApprovalStore(ApprovalStore, Protocol): + """Persistence for owner-scoped polling and one-shot resumption.""" + + async def save_scoped_pending( + self, approval_id: str, arguments: dict[str, Any], scope: ApprovalScope, verifier: str + ) -> None: + """Save a public record ID and an opaque credential verifier together.""" + ... + + async def get_scoped_result(self, approval_id: str, principal: ApprovalPrincipal) -> dict[str, Any] | None: + """Return a live record's status to its caller.""" + ... + + async def consume_scoped(self, approval_id: str, scope: ApprovalScope, verifier: str) -> dict[str, Any] | None: + """Match scope and credential before returning status. Atomically consume approved grants.""" + ... + + class InMemoryApprovalStore: """In-process approval store for testing and local development. @@ -75,6 +111,7 @@ def __init__( self._sweep_interval = sweep_interval self._max_records = max_records + self._lock = threading.RLock() self._records: dict[str, dict[str, Any]] = {} self._events: dict[str, asyncio.Event] = {} self._sweep_task: asyncio.Task | None = None @@ -99,41 +136,94 @@ def stop(self) -> None: # ── public API ─────────────────────────────────────────────────────── async def save_pending(self, approval_id: str, module_id: str, arguments: dict) -> None: - if len(self._records) >= self._max_records: - self._evict_oldest_pending() + self._save_pending(approval_id, module_id, arguments) - now = time.monotonic() - self._records[approval_id] = { - "status": "pending", - "module_id": module_id, - "arguments": arguments, - "reason": None, - "created_at": now, - "resolved_at": None, - } - self._events[approval_id] = asyncio.Event() - self._schedule_cleanup(approval_id, self._pending_ttl) + async def save_scoped_pending( + self, approval_id: str, arguments: dict[str, Any], scope: ApprovalScope, verifier: str + ) -> None: + self._save_pending(approval_id, scope.module_id, deepcopy(arguments), scope=scope, verifier=verifier) + + def _save_pending( + self, + approval_id: str, + module_id: str, + arguments: dict[str, Any], + *, + scope: ApprovalScope | None = None, + verifier: str | None = None, + ) -> None: + with self._lock: + if len(self._records) >= self._max_records: + self._evict_oldest_pending() + + self._records[approval_id] = { + "status": "pending", + "module_id": module_id, + "arguments": arguments, + "reason": None, + "created_at": time.monotonic(), + "resolved_at": None, + "scope": scope, + "verifier": verifier, + } + self._events[approval_id] = asyncio.Event() + self._schedule_cleanup(approval_id, self._pending_ttl) async def get_result(self, approval_id: str) -> dict[str, Any] | None: - return self._project(self._records.get(approval_id)) + with self._lock: + return self._project(self._records.get(approval_id)) - async def resolve(self, approval_id: str, *, approved: bool, reason: str | None = None) -> bool: + async def get_scoped_result(self, approval_id: str, principal: ApprovalPrincipal) -> dict[str, Any] | None: + with self._lock: + record = self._live_scoped_record(approval_id) + if record is None or record["scope"].principal != principal: + return None + return self._project(record) + + async def consume_scoped(self, approval_id: str, scope: ApprovalScope, verifier: str) -> dict[str, Any] | None: + with self._lock: + record = self._live_scoped_record(approval_id) + if record is None or record["scope"] != scope: + return None + expected = record["verifier"] + if expected is None or not hmac.compare_digest(expected, verifier): + return None + if record["status"] == "approved": + record["verifier"] = None + return self._project(record) + + def _live_scoped_record(self, approval_id: str) -> dict[str, Any] | None: record = self._records.get(approval_id) - if record is None or record["status"] != "pending": - return False + if record is None or record["scope"] is None or self._expired(record, time.monotonic()): + return None + return record - now = time.monotonic() - record["status"] = "approved" if approved else "rejected" - record["reason"] = reason - record["resolved_at"] = now - record.pop("arguments", None) + def _expired(self, record: dict[str, Any], now: float) -> bool: + resolved_at = record["resolved_at"] + pending_expired = now >= record["created_at"] + self._pending_ttl + if resolved_at is None: + return pending_expired + return (record["scope"] is not None and pending_expired) or now >= resolved_at + self._resolved_ttl - event = self._events.pop(approval_id, None) - if event: - event.set() + async def resolve(self, approval_id: str, *, approved: bool, reason: str | None = None) -> bool: + with self._lock: + record = self._records.get(approval_id) + if record is None or record["status"] != "pending": + return False + if record["scope"] is not None and self._live_scoped_record(approval_id) is None: + return False - self._schedule_cleanup(approval_id, self._resolved_ttl) - return True + record["status"] = "approved" if approved else "rejected" + record["reason"] = reason + record["resolved_at"] = time.monotonic() + record.pop("arguments", None) + + event = self._events.pop(approval_id, None) + if event: + event.set() + + self._schedule_cleanup(approval_id, self._resolved_ttl) + return True async def wait_for_resolution(self, approval_id: str, timeout: float = 300.0) -> dict[str, Any] | None: """Block until resolved or timeout. Helper for tests.""" @@ -175,10 +265,11 @@ def _schedule_cleanup(self, approval_id: str, delay: float) -> None: loop.call_later(delay, self._delete_record, approval_id) def _delete_record(self, approval_id: str) -> None: - self._records.pop(approval_id, None) - event = self._events.pop(approval_id, None) - if event and not event.is_set(): - event.set() + with self._lock: + self._records.pop(approval_id, None) + event = self._events.pop(approval_id, None) + if event and not event.is_set(): + event.set() def _evict_oldest_pending(self) -> None: oldest_id = None @@ -209,16 +300,9 @@ async def _sweep_loop(self) -> None: def _sweep(self) -> None: now = time.monotonic() - to_delete = [] - for aid, rec in self._records.items(): - status = rec["status"] - created = rec.get("created_at", 0.0) - resolved = rec.get("resolved_at") - if (status == "pending" and (now - created) > self._pending_ttl) or ( - status in ("approved", "rejected") and resolved is not None and (now - resolved) > self._resolved_ttl - ): - to_delete.append(aid) - for aid in to_delete: - self._delete_record(aid) + with self._lock: + to_delete = [aid for aid, record in self._records.items() if self._expired(record, now)] + for aid in to_delete: + self._delete_record(aid) if to_delete: logger.debug("approval store sweep: deleted %d expired records", len(to_delete)) diff --git a/mcp/python/tests/test_approval_store.py b/mcp/python/tests/test_approval_store.py index 5270bf88..fb91f990 100644 --- a/mcp/python/tests/test_approval_store.py +++ b/mcp/python/tests/test_approval_store.py @@ -3,10 +3,12 @@ from __future__ import annotations import asyncio +from types import SimpleNamespace import pytest -from apcore_mcp.approval_store import ApprovalStore, InMemoryApprovalStore +from apcore_mcp import approval_store +from apcore_mcp.approval_store import ApprovalScope, ApprovalStore, InMemoryApprovalStore, ScopedApprovalStore # --------------------------------------------------------------------------- # Protocol check @@ -16,6 +18,42 @@ def test_in_memory_store_implements_protocol() -> None: store = InMemoryApprovalStore() assert isinstance(store, ApprovalStore) + assert isinstance(store, ScopedApprovalStore) + + +@pytest.mark.asyncio +async def test_scoped_approval_has_one_successful_consumer() -> None: + store = InMemoryApprovalStore() + scope = ApprovalScope(("user", "reviewer"), None, "notebook.archive", "archive-example") + await store.save_scoped_pending("archive-review", {"note": 1}, scope, "test-verifier") + + pending = await store.consume_scoped("archive-review", scope, "test-verifier") + assert pending is not None and pending["status"] == "pending" + assert await store.resolve("archive-review", approved=True) + decisions = await asyncio.gather( + store.consume_scoped("archive-review", scope, "test-verifier"), + store.consume_scoped("archive-review", scope, "test-verifier"), + ) + + approved = [decision for decision in decisions if decision is not None] + assert len(approved) == 1 and approved[0]["status"] == "approved" + assert "verifier" not in approved[0] + assert "arguments" not in approved[0] + assert (await store.get_scoped_result("archive-review", scope.principal))["status"] == "approved" + + +@pytest.mark.asyncio +async def test_scoped_approval_checks_deadline_on_read_and_use(monkeypatch) -> None: + now = 100.0 + monkeypatch.setattr(approval_store, "time", SimpleNamespace(monotonic=lambda: now)) + store = InMemoryApprovalStore(pending_ttl=10.0, resolved_ttl=20.0) + scope = ApprovalScope(("user", "reviewer"), None, "notebook.archive", "archive-example") + await store.save_scoped_pending("archive-review", {"note": 1}, scope, "test-verifier") + assert await store.resolve("archive-review", approved=True) + + now = 110.0 + assert await store.get_scoped_result("archive-review", scope.principal) is None + assert await store.consume_scoped("archive-review", scope, "test-verifier") is None # --------------------------------------------------------------------------- From f44558468d72d9680a599c593ff2a3d9e282e7e1 Mon Sep 17 00:00:00 2001 From: tercel Date: Fri, 27 Nov 2026 14:08:26 +0800 Subject: [PATCH 25/36] fix(mcp): wire Python scoped approval through the tool transport Signed-off-by: tercel --- mcp/python/CHANGELOG.md | 1 + .../src/apcore_mcp/adapters/approval.py | 299 +++++++++++++++--- mcp/python/src/apcore_mcp/adapters/errors.py | 17 +- mcp/python/src/apcore_mcp/apcore_mcp.py | 69 ++-- .../src/apcore_mcp/server/approval_bridge.py | 113 +++++-- mcp/python/src/apcore_mcp/server/factory.py | 95 ++++-- mcp/python/src/apcore_mcp/server/router.py | 34 +- mcp/python/tests/adapters/test_errors.py | 20 +- .../tests/server/test_approval_bridge.py | 106 ++++--- .../tests/server/test_scoped_approval_wire.py | 233 ++++++++++++++ mcp/python/tests/test_apcore_mcp.py | 13 +- mcp/python/tests/test_review_fixes.py | 1 + 12 files changed, 809 insertions(+), 192 deletions(-) create mode 100644 mcp/python/tests/server/test_scoped_approval_wire.py diff --git a/mcp/python/CHANGELOG.md b/mcp/python/CHANGELOG.md index 5be7d62b..f9e4afac 100644 --- a/mcp/python/CHANGELOG.md +++ b/mcp/python/CHANGELOG.md @@ -11,6 +11,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed - Route inbound cancellation to the active request, derive terminal stream results from Core when available, and fail startup when OpenAPI tools fail to register. +- Resume foreground Phase B calls through scoped Core approval. Keep the record ID public, return the private credential only in pending result metadata, and consume approved grants once. ## [0.23.4] - 2026-11-20 diff --git a/mcp/python/src/apcore_mcp/adapters/approval.py b/mcp/python/src/apcore_mcp/adapters/approval.py index 702a8de8..e8731ef9 100644 --- a/mcp/python/src/apcore_mcp/adapters/approval.py +++ b/mcp/python/src/apcore_mcp/adapters/approval.py @@ -4,11 +4,22 @@ import json import logging +import re +import secrets import uuid -from typing import Any - +from collections.abc import Iterator +from contextlib import contextmanager +from contextvars import ContextVar +from dataclasses import dataclass +from hashlib import sha256 +from typing import Any, Protocol, TypeGuard + +from apcore import Identity +from apcore import approval as core_approval from apcore.approval import ApprovalHandler, ApprovalRequest, ApprovalResult +from apcore.errors import ApprovalPendingError +from apcore_mcp.approval_store import ApprovalPrincipal, ApprovalScope, ScopedApprovalStore from apcore_mcp.helpers import MCP_ELICIT_KEY logger = logging.getLogger(__name__) @@ -127,68 +138,268 @@ def _store_failure_reason(exc: BaseException) -> str: return "Storage error" -class StorageBackedApprovalHandler(ApprovalHandler): - """Phase B approval handler backed by a pluggable ApprovalStore. +_CORE_SCOPED_APPROVAL = hasattr(core_approval, "ScopedApprovalHandler") +_TOKEN_SECRET = re.compile(r"[A-Za-z0-9_-]{43}") +_NO_PHASE_B = "Scoped approval is unavailable for this call" + + +def _approval_principal(identity: Identity | None) -> ApprovalPrincipal: + return (identity.type, identity.id) if isinstance(identity, Identity) else None + + +def _is_public_approval_id(value: object) -> TypeGuard[str]: + if not isinstance(value, str) or len(value) != 36: + return False + try: + identifier = uuid.UUID(value) + return identifier.version == 4 and str(identifier) == value + except ValueError: + return False + + +def _argument_snapshot(arguments: dict[str, Any]) -> str: + return json.dumps(arguments, sort_keys=True, separators=(",", ":"), allow_nan=False) + - ``request_approval()`` saves a pending record and returns - ``ApprovalResult(status="pending", approval_id=...)`` causing apcore to raise - ``ApprovalPendingError``, which the bridge maps to ``APPROVAL_PENDING`` in - the MCP envelope. The agent receives ``{"errorType": "APPROVAL_PENDING", - "details": {"approvalId": "..."}}`` and polls ``__apcore_approval_check``. +def _scope_for(request: ApprovalRequest, snapshot: str) -> ApprovalScope: + return ApprovalScope( + _approval_principal(request.context.identity), + request.caller_id, + request.module_id, + sha256(snapshot.encode("utf-8")).hexdigest(), + ) - ``check_approval()`` reads the store; called by apcore when the client - retries with ``_meta.approvalId`` set. - ``notify_callback`` (optional) lets callers fan out to Slack/email/etc. - Signature: ``async (approval_id: str, module_id: str, arguments: dict) -> None`` +class _ScopedMCPApprovalHandler(Protocol): + @property + def scoped_approval_available(self) -> bool: ... + + async def request_approval(self, request: ApprovalRequest) -> ApprovalResult: ... + + async def check_approval(self, approval_id: str) -> ApprovalResult: ... + + async def check_approval_for_call(self, credential: str, request: ApprovalRequest) -> ApprovalResult: ... + + async def poll_approval(self, approval_id: str, principal: ApprovalPrincipal) -> ApprovalResult: ... + + +def _implements_mcp_scoped_approval(handler: object) -> TypeGuard[_ScopedMCPApprovalHandler]: + return ( + getattr(handler, "scoped_approval_available", None) is True + and all(callable(getattr(handler, method, None)) for method in ( + "request_approval", "check_approval", "check_approval_for_call", "poll_approval", + )) + ) + + +class StorageBackedApprovalHandler(ApprovalHandler): + """Store a scoped approval with a public record ID and a separate private credential. - Neither method raises: a store failure on either path is contained and - surfaced as ``ApprovalResult(status="rejected", ...)`` so the gate fails - closed rather than propagating out of apcore's approval call. + Out-of-band notification receives the public ID, module ID and original + business arguments. Only the pending approval result carries the credential. """ - def __init__( - self, - store: Any, - *, - notify_callback: Any | None = None, - ) -> None: + def __init__(self, store: Any, *, notify_callback: Any | None = None) -> None: self._store = store self._notify = notify_callback + @property + def scoped_approval_available(self) -> bool: + return _CORE_SCOPED_APPROVAL and isinstance(self._store, ScopedApprovalStore) + async def request_approval(self, request: ApprovalRequest) -> ApprovalResult: + if not self.scoped_approval_available: + return ApprovalResult(status="rejected", reason=_NO_PHASE_B) + try: + snapshot = _argument_snapshot(request.arguments) + scope = _scope_for(request, snapshot) + except (TypeError, ValueError, RecursionError): + return ApprovalResult(status="rejected", reason="Approval requires JSON business arguments") approval_id = str(uuid.uuid4()) - module_id = getattr(request, "module_id", "unknown") - arguments = getattr(request, "arguments", {}) or {} - + credential = f"{approval_id}.{secrets.token_urlsafe(32)}" + verifier = sha256(credential.encode("ascii")).hexdigest() try: - await self._store.save_pending(approval_id, module_id, arguments) + await self._store.save_scoped_pending(approval_id, json.loads(snapshot), scope, verifier) except Exception as exc: - reason = _store_failure_reason(exc) - logger.error("approval store save_pending failed for %s: %s", approval_id, reason, exc_info=True) - return ApprovalResult(status="rejected", reason=reason) + return self._storage_failure("save", exc) if self._notify is not None: try: - await self._notify(approval_id, module_id, arguments) + await self._notify(approval_id, request.module_id, json.loads(snapshot)) except Exception: - logger.warning("notify_callback raised for approval %s", approval_id, exc_info=True) - - return ApprovalResult(status="pending", approval_id=approval_id) + logger.warning("Approval notification failed for record %s", approval_id) + return ApprovalResult(status="pending", approval_id=credential, audit_id=approval_id) async def check_approval(self, approval_id: str) -> ApprovalResult: + # Older Core invokes this status-only method for authorization and + # cannot pass a current invocation scope. + return ApprovalResult(status="rejected", reason=_NO_PHASE_B) + + async def poll_approval(self, approval_id: str, principal: ApprovalPrincipal) -> ApprovalResult: + if not self.scoped_approval_available or not _is_public_approval_id(approval_id): + return ApprovalResult(status="rejected", reason=_NO_PHASE_B) try: - record = await self._store.get_result(approval_id) + record = await self._store.get_scoped_result(approval_id, principal) except Exception as exc: - reason = _store_failure_reason(exc) - logger.error("approval store get_result failed for %s: %s", approval_id, reason, exc_info=True) - return ApprovalResult(status="rejected", reason=reason) - if record is None: - return ApprovalResult(status="rejected", reason="approval_id not found") - status = record.get("status", "pending") - reason = record.get("reason") + return self._storage_failure("poll", exc) + return self._public_decision(record) + + async def check_approval_for_call(self, credential: str, request: ApprovalRequest) -> ApprovalResult: + approval_id, _, secret = credential.partition(".") + if ( + not self.scoped_approval_available + or not _is_public_approval_id(approval_id) + or not _TOKEN_SECRET.fullmatch(secret) + ): + return ApprovalResult(status="rejected", reason="Approval is unavailable for this invocation") + try: + scope = _scope_for(request, _argument_snapshot(request.arguments)) + except (TypeError, ValueError, RecursionError): + return ApprovalResult(status="rejected", reason="Approval requires JSON business arguments") + verifier = sha256(credential.encode("ascii")).hexdigest() + try: + record = await self._store.consume_scoped(approval_id, scope, verifier) + except Exception as exc: + return self._storage_failure("resume", exc) + decision = self._public_decision(record) + if decision.status == "pending": + return ApprovalResult(status="pending", approval_id=credential, audit_id=approval_id) + return ApprovalResult(status=decision.status, reason=decision.reason, audit_id=approval_id if record else None) + + @staticmethod + def _public_decision(record: dict[str, Any] | None) -> ApprovalResult: + status = record.get("status") if record is not None else None if status == "approved": return ApprovalResult(status="approved") - if status == "rejected": - return ApprovalResult(status="rejected", reason=reason) - return ApprovalResult(status="pending", approval_id=approval_id) + if status == "pending": + return ApprovalResult(status="pending") + return ApprovalResult(status="rejected", reason="Approval is unavailable for this invocation") + + @staticmethod + def _storage_failure(operation: str, exc: Exception) -> ApprovalResult: + reason = _store_failure_reason(exc) + # Store exceptions may contain sensitive arguments or credentials. + logger.warning("Approval store %s failed: %s", operation, reason) + return ApprovalResult(status="rejected", reason=reason) + + +@dataclass +class _ApprovalDelivery: + handler: _ScopedMCPApprovalHandler + module_id: str + active: bool = True + pending: ApprovalResult | None = None + metadata: dict[str, str] | None = None + + +_approval_delivery: ContextVar[_ApprovalDelivery | None] = ContextVar("mcp_approval_delivery", default=None) + + +@contextmanager +def _capture_approval_delivery(handler: _ScopedMCPApprovalHandler, module_id: str) -> Iterator[_ApprovalDelivery]: + delivery = _ApprovalDelivery(handler, module_id) + token = _approval_delivery.set(delivery) + try: + yield delivery + finally: + delivery.active = False + _approval_delivery.reset(token) + + +def _pending_metadata(result: ApprovalResult) -> dict[str, str] | None: + approval_id, credential = result.audit_id, result.approval_id + if ( + _is_public_approval_id(approval_id) + and isinstance(credential, str) + and 0 < len(credential) <= 256 + and approval_id != credential + ): + return {"approvalId": approval_id, "resumeToken": credential} + return None + + +def _capture_pending_error(error: ApprovalPendingError) -> None: + delivery = _approval_delivery.get() + if delivery is not None and delivery.pending is not None and error.result is delivery.pending: + delivery.metadata = _pending_metadata(delivery.pending) + + +class _MCPScopedApprovalGate: + """Allow credential issuance and consumption on MCP's scoped result path.""" + + def __init__(self, handler: _ScopedMCPApprovalHandler) -> None: + self._handler = handler + + def _delivery_for(self, request: ApprovalRequest) -> _ApprovalDelivery | None: + delivery = _approval_delivery.get() + if ( + _CORE_SCOPED_APPROVAL + and delivery is not None + and delivery.active + and delivery.handler is self._handler + and request.caller_id is None + and request.module_id == delivery.module_id + ): + return delivery + return None + + @staticmethod + def _record_decision( + result: ApprovalResult, delivery: _ApprovalDelivery, credential: str | None = None, + ) -> ApprovalResult: + if result.status == "pending": + metadata = _pending_metadata(result) + if metadata is None: + return ApprovalResult(status="rejected", reason="The provider returned an invalid pending approval") + # Core audits reasons and approvers. A pending result only needs + # the private credential and its separate public correlation ID. + pending = ApprovalResult( + status="pending", approval_id=metadata["resumeToken"], audit_id=metadata["approvalId"], + ) + delivery.pending = pending + return pending + + credentials = {value for value in (credential, result.approval_id) if isinstance(value, str) and value} + + def redact(value: str | None) -> str | None: + if not isinstance(value, str): + return None + for secret in credentials: + value = value.replace(secret, "[redacted]") + return value + + return ApprovalResult( + status=result.status, + reason=redact(result.reason), + approved_by=redact(result.approved_by), + audit_id=( + result.audit_id + if _is_public_approval_id(result.audit_id) and result.audit_id not in credentials + else None + ), + ) + + async def request_approval(self, request: ApprovalRequest) -> ApprovalResult: + delivery = self._delivery_for(request) + if delivery is None: + return ApprovalResult(status="rejected", reason=_NO_PHASE_B) + try: + result = await self._handler.request_approval(request) + return self._record_decision(result, delivery) + except Exception: + logger.warning("Scoped approval request failed") + return ApprovalResult(status="rejected", reason=_NO_PHASE_B) + + async def check_approval(self, approval_id: str) -> ApprovalResult: + return ApprovalResult(status="rejected", reason=_NO_PHASE_B) + + async def check_approval_for_call(self, credential: str, request: ApprovalRequest) -> ApprovalResult: + delivery = self._delivery_for(request) + if delivery is None: + return ApprovalResult(status="rejected", reason=_NO_PHASE_B) + try: + result = await self._handler.check_approval_for_call(credential, request) + return self._record_decision(result, delivery, credential) + except Exception: + logger.warning("Scoped approval resumption failed") + return ApprovalResult(status="rejected", reason=_NO_PHASE_B) diff --git a/mcp/python/src/apcore_mcp/adapters/errors.py b/mcp/python/src/apcore_mcp/adapters/errors.py index d31d96b6..59750df4 100644 --- a/mcp/python/src/apcore_mcp/adapters/errors.py +++ b/mcp/python/src/apcore_mcp/adapters/errors.py @@ -6,6 +6,7 @@ from apcore.cancel import ExecutionCancelledError from apcore.errors import ( + ApprovalPendingError, ModuleError, TaskLimitExceededError, ) @@ -20,6 +21,7 @@ except ImportError: # pragma: no cover CircuitBreakerOpenError = None # type: ignore[assignment,misc] +from apcore_mcp.adapters.approval import _is_public_approval_id from apcore_mcp.constants import ERROR_CODES # Canonical recovery hint emitted when apcore did not populate a per-module @@ -224,16 +226,21 @@ def _handle_apcore_error(self, error: Exception) -> dict[str, Any]: # Approval errors: pass through with specific handling if code == ERROR_CODES["APPROVAL_PENDING"]: - # Narrow details to only approvalId; drop everything else. - # apcore uses snake_case (approval_id); output uses camelCase (approvalId) for MCP convention. - narrowed = {"approvalId": details["approval_id"]} if details and "approval_id" in details else None + # Core's approval_id is confidential. Only the non-secret record + # correlation ID belongs in generic error envelopes. + pending = error.result if isinstance(error, ApprovalPendingError) else None + audit_id = getattr(pending, "audit_id", None) + narrowed = ( + {"approvalId": audit_id} + if _is_public_approval_id(audit_id) and audit_id != getattr(pending, "approval_id", None) + else None + ) result = { "isError": True, "errorType": code, - "message": message, + "message": "Approval pending for this tool.", "details": narrowed, } - self._attach_ai_guidance(error, result) return result if code == ERROR_CODES["APPROVAL_TIMEOUT"]: diff --git a/mcp/python/src/apcore_mcp/apcore_mcp.py b/mcp/python/src/apcore_mcp/apcore_mcp.py index 68c7fcea..89b2c390 100644 --- a/mcp/python/src/apcore_mcp/apcore_mcp.py +++ b/mcp/python/src/apcore_mcp/apcore_mcp.py @@ -24,10 +24,17 @@ from pathlib import Path from typing import TYPE_CHECKING, Any +from apcore import APCore, Executor from starlette.routing import Mount, Route from apcore_mcp._stdio import configured_output from apcore_mcp._utils import resolve_executor, resolve_registry +from apcore_mcp.adapters.approval import ( + _CORE_SCOPED_APPROVAL, + StorageBackedApprovalHandler, + _implements_mcp_scoped_approval, + _MCPScopedApprovalGate, +) from apcore_mcp.auth.protocol import Authenticator from apcore_mcp.server.transport import MetricsExporter @@ -474,10 +481,12 @@ def __init__( # Auto-construct StorageBackedApprovalHandler when approval_store is given # and no explicit handler was provided. if approval_store is not None and approval_handler is None: - from apcore_mcp.adapters.approval import StorageBackedApprovalHandler - approval_handler = StorageBackedApprovalHandler(approval_store, notify_callback=approval_notify) + scoped_handler = approval_handler if _implements_mcp_scoped_approval(approval_handler) else None + gate_handler = _MCPScopedApprovalGate(scoped_handler) if scoped_handler is not None else approval_handler + self._phase_b_handler = scoped_handler if _CORE_SCOPED_APPROVAL else None + # Resolve mcp.openapi from the Config Bus early — before the base # backend is built — because an omitted extensions_dir_or_backend # depends entirely on it, and a supplied one needs the resulting @@ -560,13 +569,29 @@ def __init__( if strategy is not None and hasattr(backend, "call_async"): logger.warning("strategy parameter ignored when Executor is provided") + storage_backed = isinstance(gate_handler, (_MCPScopedApprovalGate, StorageBackedApprovalHandler)) + supplied_executor = backend.executor if isinstance(backend, APCore) else backend + if ( + storage_backed + and isinstance(supplied_executor, Executor) + and supplied_executor.governance_state().approval_handler_configured + ): + raise ValueError("The supplied Core executor already has an approval handler") + self._executor = resolve_executor( backend, - approval_handler=approval_handler, + approval_handler=gate_handler, strategy=pipeline_strategy or strategy, middleware=combined_middleware, acl=effective_acl, ) + if storage_backed: + executor = self._executor.executor if isinstance(self._executor, APCore) else self._executor + if not isinstance(executor, Executor) or not executor.governance_state().builtin_approval_gate_wired: + raise ValueError("Storage-backed approval requires a Core executor with a wired approval gate") + # resolve_executor preserves an executor supplied by the host. Bind + # the same handler to that executor and the MCP polling bridge. + executor.set_approval_handler(gate_handler) # Observability auto-wiring. ``metrics_collector=True`` or # ``observability=True`` provisions apcore's default MetricsCollector + @@ -717,18 +742,11 @@ def _build_server_components(self) -> tuple[Any, Any, list, Any, str]: async_bridge = AsyncTaskBridge(mgr) self._async_bridge = async_bridge - # Register the approval poll meta-tool whenever an approval handler is - # present. Phase B (async polling) is driven entirely by the handler's - # ``check_approval()`` — the store is an implementation detail of - # ``StorageBackedApprovalHandler``. Gating on ``approval_store`` here - # broke the legitimate "pass StorageBackedApprovalHandler(store) as - # approval_handler directly" usage, where ``self._approval_store`` is - # None but the handler still needs ``__apcore_approval_check`` exposed. approval_bridge = None - if self._approval_handler is not None: + if self._phase_b_handler is not None: from apcore_mcp.server.approval_bridge import ApprovalBridge - approval_bridge = ApprovalBridge(self._approval_handler) + approval_bridge = ApprovalBridge(self._phase_b_handler) descriptor_lookup = self._registry.get_definition if self._async_tasks else None factory.register_handlers( @@ -803,9 +821,14 @@ def _build_auth_middleware( explorer: bool = False, explorer_prefix: str = "/explorer", ) -> list[tuple[type, dict]] | None: - """Build auth middleware list if authenticator is configured.""" + """Build the HTTP middleware needed for authentication and approval responses.""" + middleware: list[tuple[type, dict]] = [] + if self._phase_b_handler is not None: + from apcore_mcp.server.approval_bridge import _ApprovalLogMiddleware + + middleware.append((_ApprovalLogMiddleware, {})) if self._authenticator is None: - return None + return middleware or None from apcore_mcp.auth import AuthMiddleware @@ -816,7 +839,8 @@ def _build_auth_middleware( mw_kwargs["exempt_paths"] = self._exempt_paths if explorer: mw_kwargs["exempt_prefixes"] = {explorer_prefix} - return [(AuthMiddleware, mw_kwargs)] + middleware.append((AuthMiddleware, mw_kwargs)) + return middleware def _maybe_append_usage_routes( self, @@ -859,6 +883,9 @@ def _build_serve_coro( _pkg = importlib.import_module("apcore_mcp") TransportManager = _pkg.TransportManager # noqa: N806 + if transport.lower() == "sse" and self._phase_b_handler is not None: + raise ValueError("Scoped approval is unavailable on the legacy SSE transport; use Streamable HTTP or stdio") + server, router, tools, init_options, version = self._build_server_components() if self._dynamic: @@ -890,7 +917,7 @@ def _build_serve_coro( ) auth_middleware: list[tuple[type, dict]] | None = None - if self._authenticator is not None and transport_lower in ("streamable-http", "sse"): + if transport_lower in ("streamable-http", "sse"): auth_middleware = self._build_auth_middleware( explorer=explorer, explorer_prefix=explorer_prefix, @@ -1090,12 +1117,10 @@ async def async_serve( explorer_project_url=explorer_project_url, ) - auth_middleware: list[tuple[type, dict]] | None = None - if self._authenticator is not None: - auth_middleware = self._build_auth_middleware( - explorer=explorer, - explorer_prefix=explorer_prefix, - ) + auth_middleware = self._build_auth_middleware( + explorer=explorer, + explorer_prefix=explorer_prefix, + ) transport_manager = TransportManager(metrics_collector=self._metrics_collector) transport_manager.set_module_count(len(tools)) diff --git a/mcp/python/src/apcore_mcp/server/approval_bridge.py b/mcp/python/src/apcore_mcp/server/approval_bridge.py index 9a838390..69dbc5ed 100644 --- a/mcp/python/src/apcore_mcp/server/approval_bridge.py +++ b/mcp/python/src/apcore_mcp/server/approval_bridge.py @@ -8,10 +8,22 @@ import json import logging +from contextlib import AbstractContextManager +from contextvars import ContextVar +from dataclasses import dataclass from typing import Any +from apcore import Identity from mcp import types as mcp_types - +from starlette.types import ASGIApp, Receive, Scope, Send + +from apcore_mcp.adapters.approval import ( + _approval_principal, + _ApprovalDelivery, + _capture_approval_delivery, + _is_public_approval_id, + _ScopedMCPApprovalHandler, +) from apcore_mcp.adapters.errors import ErrorMapper logger = logging.getLogger(__name__) @@ -21,25 +33,65 @@ APPROVAL_META_TOOL_NAMES = ("__apcore_approval_check",) -class ApprovalBridge: - """Thin meta-tool layer over StorageBackedApprovalHandler. +@dataclass +class _ApprovalResponseLog: + carries_credential: bool = False + + +_RESPONSE_LOG_SCOPE_KEY = "apcore_mcp.approval_response_log" +_response_log_context: ContextVar[_ApprovalResponseLog | None] = ContextVar("approval_response_log", default=None) + + +class _ApprovalResponseLogFilter(logging.Filter): + """Protect the raw SSE chunk diagnostic for a credential-bearing response.""" + + def filter(self, record: logging.LogRecord) -> bool: + response = _response_log_context.get() + return not ( + response is not None + and response.carries_credential + and record.levelno == logging.DEBUG + and isinstance(record.msg, str) + and record.msg.startswith("chunk:") + ) + + +_approval_response_log_filter = _ApprovalResponseLogFilter() - Exposes ``__apcore_approval_check`` so MCP clients can poll the status - of a pending approval without blocking the connection. The full flow:: - 1. Module call → APPROVAL_PENDING {approvalId: "abc"} - 2. Agent calls __apcore_approval_check(approval_id="abc") - → {status: "pending"} - 3. External system resolves: store.resolve("abc", approved=True) - 4. Agent polls again → {status: "approved"} - 5. Agent retries module call with _meta.approvalId="abc" - → apcore calls handler.check_approval("abc") → approved → executes - """ +class _ApprovalLogMiddleware: + def __init__(self, app: ASGIApp) -> None: + self._app = app + logging.getLogger("sse_starlette.sse").addFilter(_approval_response_log_filter) - def __init__(self, handler: Any) -> None: + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + if scope["type"] != "http": + await self._app(scope, receive, send) + return + response = _ApprovalResponseLog() + token = _response_log_context.set(response) + try: + await self._app({**scope, _RESPONSE_LOG_SCOPE_KEY: response}, receive, send) + finally: + _response_log_context.reset(token) + + +def _approval_response_log(request: Any) -> _ApprovalResponseLog | None: + scope = getattr(request, "scope", None) + marker = scope.get(_RESPONSE_LOG_SCOPE_KEY) if isinstance(scope, dict) else None + return marker if isinstance(marker, _ApprovalResponseLog) else None + + +class ApprovalBridge: + """Expose a caller-scoped status tool and capture pending wire responses.""" + + def __init__(self, handler: _ScopedMCPApprovalHandler) -> None: self._handler = handler self._error_mapper = ErrorMapper() + def delivery(self, name: str) -> AbstractContextManager[_ApprovalDelivery]: + return _capture_approval_delivery(self._handler, name) + @staticmethod def is_meta_tool(name: str) -> bool: return name in APPROVAL_META_TOOL_NAMES @@ -50,17 +102,17 @@ def build_meta_tools(self) -> list[mcp_types.Tool]: name="__apcore_approval_check", description=( "Poll the status of a pending approval request. " - "Returns {approval_id, status, reason}. " + "Returns {approval_id, status}. " "status is 'pending', 'approved', or 'rejected'. " "When 'approved', retry the original tool call with " - "_meta.approvalId set to this approval_id." + "_meta.approvalId set to the separate resumeToken from the pending result." ), inputSchema={ "type": "object", "properties": { "approval_id": { "type": "string", - "description": "The approval_id from the APPROVAL_PENDING response", + "description": "The public approvalId from the pending result metadata", } }, "required": ["approval_id"], @@ -70,27 +122,26 @@ def build_meta_tools(self) -> list[mcp_types.Tool]: ] async def handle_meta_tool( - self, name: str, arguments: dict[str, Any] + self, name: str, arguments: dict[str, Any], *, identity: Identity | None = None, ) -> tuple[list[dict[str, Any]], bool, str | None]: """Dispatch a meta-tool call. Returns (content, is_error, trace_id).""" if name == "__apcore_approval_check": - return await self._handle_check(arguments or {}) + return await self._handle_check(arguments or {}, identity) return self._error_response(ValueError(f"Unknown approval meta-tool: {name}")) - async def _handle_check(self, args: dict[str, Any]) -> tuple[list[dict[str, Any]], bool, str | None]: + async def _handle_check( + self, args: dict[str, Any], identity: Identity | None + ) -> tuple[list[dict[str, Any]], bool, str | None]: approval_id = args.get("approval_id") - if not isinstance(approval_id, str) or not approval_id: - return self._error_response(ValueError("approval_id is required")) + if not _is_public_approval_id(approval_id): + return self._error_response(ValueError("approval_id must be a public approval record ID")) try: - result = await self._handler.check_approval(approval_id) - except Exception as exc: - logger.exception("approval check failed for %s", approval_id) - return self._error_response(exc) - status = getattr(result, "status", "pending") - reason = getattr(result, "reason", None) - payload: dict[str, Any] = {"approval_id": approval_id, "status": status} - if reason is not None: - payload["reason"] = reason + result = await self._handler.poll_approval(approval_id, _approval_principal(identity)) + except Exception: + logger.warning("Approval status lookup failed") + return self._error_response(ValueError("Approval status lookup failed")) + status = result.status if result.status in ("pending", "approved", "rejected") else "rejected" + payload = {"approval_id": approval_id, "status": status} return ([{"type": "text", "text": json.dumps(payload)}], False, None) def _error_response(self, exc: Exception) -> tuple[list[dict[str, Any]], bool, str | None]: diff --git a/mcp/python/src/apcore_mcp/server/factory.py b/mcp/python/src/apcore_mcp/server/factory.py index 15f4a48d..4e41dad9 100644 --- a/mcp/python/src/apcore_mcp/server/factory.py +++ b/mcp/python/src/apcore_mcp/server/factory.py @@ -6,6 +6,7 @@ import json import logging import math +from contextlib import nullcontext from copy import deepcopy from decimal import Decimal, DecimalException from typing import Any @@ -29,7 +30,7 @@ import apcore_mcp.markdown as _markdown from apcore_mcp.adapters.annotations import AnnotationMapper from apcore_mcp.auth.middleware import _REQUEST_IDENTITY_KEY, auth_identity_var -from apcore_mcp.server.approval_bridge import ApprovalBridge +from apcore_mcp.server.approval_bridge import ApprovalBridge, _approval_response_log from apcore_mcp.server.async_task_bridge import RESERVED_PREFIX, AsyncTaskBridge from apcore_mcp.server.router import ExecutionRouter, _descriptor_version_hint, _matches_registered_version from apcore_mcp.server.transport import _protocol_source_var, transport_session_var @@ -37,6 +38,9 @@ logger = logging.getLogger(__name__) +_NO_APPROVAL_CREDENTIAL = object() + + _AI_INTENT_KEYS = ("x-when-to-use", "x-when-not-to-use", "x-common-mistakes", "x-workflow-hints") # aiperceivable/apcore-mcp#15: the three read-only `system.*` namespaces. @@ -210,6 +214,8 @@ def _build_call_result( content: list[mcp_types.TextContent], is_error: bool, output_schema: dict[str, Any] | None, + *, + approval: dict[str, str] | None = None, ) -> mcp_types.CallToolResult: """Project only the router's already-redacted JSON text as structured data.""" structured: dict[str, Any] | None = None @@ -247,7 +253,8 @@ def _build_call_result( ], isError=True, ) - return mcp_types.CallToolResult(content=[*content], structuredContent=structured, isError=is_error) + metadata = {"apcore": {"approval": approval}} if is_error and approval else None + return mcp_types.CallToolResult(content=[*content], structuredContent=structured, isError=is_error, _meta=metadata) class MCPServerFactory: @@ -605,8 +612,11 @@ async def handle_call_tool(name: str, arguments: dict[str, Any]) -> mcp_types.Ca # Always pass session for elicitation support extra: dict[str, Any] = {"session": ctx.session} + approval_token = _NO_APPROVAL_CREDENTIAL if ctx.meta is not None: + approval_token = getattr(ctx.meta, "approvalId", _NO_APPROVAL_CREDENTIAL) meta_dump = ctx.meta.model_dump(exclude_none=True) + meta_dump.pop("approvalId", None) if meta_dump: extra["_meta"] = meta_dump @@ -629,11 +639,8 @@ async def send_notification(notification: dict[str, Any]) -> None: extra["progress_token"] = progress_token published = next((tool for tool in reversed(combined_tools) if tool.name == name), None) - if ( - published is not None - and id(published) in regular_tool_ids - and isinstance(router, ExecutionRouter) - ): + regular_tool = published is not None and id(published) in regular_tool_ids + if published is not None and regular_tool and isinstance(router, ExecutionRouter): error = self._bind_requested_version( router, published, @@ -643,8 +650,42 @@ async def send_notification(notification: dict[str, Any]) -> None: if error is not None: return _build_call_result([mcp_types.TextContent(type="text", text=error)], True, None) + async_meta_tool = async_bridge is not None and async_bridge.is_meta_tool(name) + approval_meta_tool = approval_bridge is not None and approval_bridge.is_meta_tool(name) + background_tool = ( + not async_meta_tool + and not approval_meta_tool + and async_bridge is not None + and descriptor_lookup is not None + and async_bridge.is_async_module(descriptor_lookup(name)) + ) + response_log = _approval_response_log(ctx.request) + can_deliver_approval = ctx.request is None or ( + _protocol_source_var.get() != "session" and response_log is not None + ) + scoped_approval = ( + approval_bridge is not None + and regular_tool + and can_deliver_approval + and not background_tool + and isinstance(router, ExecutionRouter) + ) + credential_error = None + if "_approval_token" in (arguments or {}): + credential_error = "Send the approval credential in MCP request metadata." + elif approval_token is not _NO_APPROVAL_CREDENTIAL: + if not scoped_approval: + credential_error = "Scoped approval is unavailable for this call." + elif not isinstance(approval_token, str) or not 0 < len(approval_token) <= 256: + credential_error = "Invalid approval credential." + else: + extra["_mcp_approval_token"] = approval_token + if credential_error is not None: + return _build_call_result([mcp_types.TextContent(type="text", text=credential_error)], True, None) + + pending_approval = None # Meta-tool route: handled entirely by the async bridge. - if async_bridge is not None and async_bridge.is_meta_tool(name): + if async_bridge is not None and async_meta_tool: content, is_error, _trace_id = await async_bridge.handle_meta_tool( name, arguments or {}, @@ -652,14 +693,12 @@ async def send_notification(notification: dict[str, Any]) -> None: router_extra=extra, ) # Approval meta-tool route: handled by the approval bridge. - elif approval_bridge is not None and approval_bridge.is_meta_tool(name): - content, is_error, _trace_id = await approval_bridge.handle_meta_tool(name, arguments or {}) + elif approval_bridge is not None and approval_meta_tool: + content, is_error, _trace_id = await approval_bridge.handle_meta_tool( + name, arguments or {}, identity=identity, + ) # Async-hint route: submit to AsyncTaskManager, return task envelope. - elif ( - async_bridge is not None - and descriptor_lookup is not None - and async_bridge.is_async_module(descriptor_lookup(name)) - ): + elif async_bridge is not None and background_tool: from apcore import Context from apcore.trace_context import TraceContext, TraceParent @@ -702,15 +741,21 @@ async def send_notification(notification: dict[str, Any]) -> None: token = CancelToken() extra["_transport_cancel_token"] = token extra["call_id"] = f"mcp:{id(ctx.session)}:{ctx.request_id!r}" - call = asyncio.create_task(router.handle_call(name, arguments or {}, extra=extra)) - try: - content, is_error, _trace_id = await asyncio.shield(call) - except asyncio.CancelledError: - token.cancel() - call.cancel() - with anyio.CancelScope(shield=True): - await asyncio.gather(call, return_exceptions=True) - raise + capture = approval_bridge.delivery(name) if scoped_approval and approval_bridge else nullcontext() + with capture as delivery: + call = asyncio.create_task(router.handle_call(name, arguments or {}, extra=extra)) + try: + content, is_error, _trace_id = await asyncio.shield(call) + except asyncio.CancelledError: + token.cancel() + call.cancel() + with anyio.CancelScope(shield=True): + await asyncio.gather(call, return_exceptions=True) + raise + if delivery is not None: + pending_approval = delivery.metadata + if pending_approval is not None and response_log is not None: + response_log.carries_credential = True # A direct CallToolResult preserves error status and text metadata. text_contents: list[mcp_types.TextContent] = [] @@ -723,7 +768,7 @@ async def send_notification(notification: dict[str, Any]) -> None: else: text_contents.append(mcp_types.TextContent(type="text", text=item["text"])) output_schema = published.outputSchema if published is not None else None - return _build_call_result(text_contents, is_error, output_schema) + return _build_call_result(text_contents, is_error, output_schema, approval=pending_approval) def register_resource_handlers( self, diff --git a/mcp/python/src/apcore_mcp/server/router.py b/mcp/python/src/apcore_mcp/server/router.py index e539c87b..5a8ba034 100644 --- a/mcp/python/src/apcore_mcp/server/router.py +++ b/mcp/python/src/apcore_mcp/server/router.py @@ -13,10 +13,12 @@ from typing import Any from apcore import APCore, CancelToken, Context, Executor, ModuleError, StreamingModule +from apcore.errors import ApprovalPendingError from apcore.registry.types import ModuleDescriptor from apcore.registry.version import matches_version_hint from apcore.trace_context import TraceContext, TraceParent +from apcore_mcp.adapters.approval import _capture_pending_error from apcore_mcp.adapters.errors import ErrorMapper from apcore_mcp.helpers import MCP_ELICIT_KEY, MCP_PROGRESS_KEY @@ -634,6 +636,13 @@ async def _elicit_callback( error_info = self._error_mapper.to_mcp_error(error) return ([{"type": "text", "text": error_info["message"]}], True, None) + # The factory supplies this only after MCP input validation. Keep + # preflight and routing on business arguments; Core separates the + # credential at pipeline entry before governance or module execution. + approval_token = extra.get("_mcp_approval_token") if extra is not None else None + if approval_token is not None: + arguments = {**arguments, "_approval_token": approval_token} + has_progress = progress_token is not None and send_notification is not None if callable(self._open_completed_stream): if self._core_backend: @@ -783,6 +792,16 @@ def _build_error_text(error_info: dict[str, Any]) -> str: text += "\n\n" + json.dumps(guidance) return text + def _invocation_error_text(self, error: Exception, arguments: dict[str, Any]) -> str: + if isinstance(error, ApprovalPendingError): + _capture_pending_error(error) + return "Approval pending for this tool." + text = self._build_error_text(self._error_mapper.to_mcp_error(error)) + credential = arguments.get("_approval_token") + if isinstance(credential, str) and credential: + return text.replace(credential, "[redacted]") + return text + async def _handle_call_async( self, tool_name: str, @@ -822,9 +841,9 @@ async def _handle_call_async( trace_id = context.trace_id if context is not None else None return (content, False, trace_id) except Exception as error: - logger.error("handle_call error for %s: %s", tool_name, error) - error_info = self._error_mapper.to_mcp_error(error) - error_content: list[dict[str, Any]] = [{"type": "text", "text": self._build_error_text(error_info)}] + if not isinstance(error, ApprovalPendingError) and "_approval_token" not in arguments: + logger.error("handle_call error for %s: %s", tool_name, error) + error_content = [{"type": "text", "text": self._invocation_error_text(error, arguments)}] self._attach_traceparent(error_content, context) return (error_content, True, context.trace_id if context is not None else None) @@ -856,8 +875,7 @@ async def _handle_completed_stream( self._attach_traceparent(content, context) return content, False, context.trace_id except Exception as error: - info = self._error_mapper.to_mcp_error(error) - failure: list[dict[str, Any]] = [{"type": "text", "text": self._build_error_text(info)}] + failure = [{"type": "text", "text": self._invocation_error_text(error, arguments)}] self._attach_traceparent(failure, context) return failure, True, context.trace_id @@ -941,8 +959,8 @@ async def _handle_stream( trace_id = context.trace_id if context is not None else None return (content, False, trace_id) except Exception as error: - logger.error("handle_call stream error for %s: %s", tool_name, error) - error_info = self._error_mapper.to_mcp_error(error) - stream_error_content: list[dict[str, Any]] = [{"type": "text", "text": self._build_error_text(error_info)}] + if not isinstance(error, ApprovalPendingError) and "_approval_token" not in arguments: + logger.error("handle_call stream error for %s: %s", tool_name, error) + stream_error_content = [{"type": "text", "text": self._invocation_error_text(error, arguments)}] self._attach_traceparent(stream_error_content, context) return (stream_error_content, True, context.trace_id if context is not None else None) diff --git a/mcp/python/tests/adapters/test_errors.py b/mcp/python/tests/adapters/test_errors.py index 6b2bb279..ad7bd6e8 100644 --- a/mcp/python/tests/adapters/test_errors.py +++ b/mcp/python/tests/adapters/test_errors.py @@ -2,6 +2,7 @@ from __future__ import annotations +from types import SimpleNamespace from typing import Any import pytest @@ -510,8 +511,8 @@ def test_approval_timeout_marks_retryable(self, mapper: ErrorMapper) -> None: assert result["errorType"] == "APPROVAL_TIMEOUT" assert result["retryable"] is True - def test_approval_pending_includes_approval_id(self, mapper: ErrorMapper) -> None: - """APPROVAL_PENDING includes approvalId in details (camelCase output).""" + def test_approval_pending_hides_the_core_resume_credential(self, mapper: ErrorMapper) -> None: + """A generic pending error does not serialize the credential.""" error = ModuleError( code="APPROVAL_PENDING", message="Awaiting approval", @@ -521,7 +522,20 @@ def test_approval_pending_includes_approval_id(self, mapper: ErrorMapper) -> Non assert result["isError"] is True assert result["errorType"] == "APPROVAL_PENDING" - assert result["details"]["approvalId"] == "apr-123" + assert result["details"] is None + assert "apr-123" not in str(result) + + def test_scoped_pending_error_includes_only_its_public_audit_id(self, mapper: ErrorMapper) -> None: + from apcore.errors import ApprovalPendingError + + record_id = "c5b92219-e067-485a-9752-d09cd362588d" + error = ApprovalPendingError( + result=SimpleNamespace(approval_id="confidential-synthetic-credential", audit_id=record_id), + module_id="example.report", + ) + result = mapper.to_mcp_error(error) + assert result["details"] == {"approvalId": record_id} + assert "confidential-synthetic-credential" not in str(result) def test_approval_pending_without_approval_id_has_none_details(self, mapper: ErrorMapper) -> None: """APPROVAL_PENDING without approval_id narrows details to None.""" diff --git a/mcp/python/tests/server/test_approval_bridge.py b/mcp/python/tests/server/test_approval_bridge.py index 2c9020da..69bcfac4 100644 --- a/mcp/python/tests/server/test_approval_bridge.py +++ b/mcp/python/tests/server/test_approval_bridge.py @@ -7,11 +7,15 @@ from unittest.mock import AsyncMock import pytest +from apcore import Registry -from apcore_mcp.adapters.approval import StorageBackedApprovalHandler +from apcore_mcp.adapters.approval import _CORE_SCOPED_APPROVAL, StorageBackedApprovalHandler from apcore_mcp.approval_store import InMemoryApprovalStore from apcore_mcp.server.approval_bridge import APPROVAL_META_TOOL_NAMES, ApprovalBridge +_requires_scoped_core = pytest.mark.skipif(not _CORE_SCOPED_APPROVAL, reason="requires scoped Core approval") + + # --------------------------------------------------------------------------- # Helpers # --------------------------------------------------------------------------- @@ -78,47 +82,58 @@ def test_build_meta_tools_has_description() -> None: # --------------------------------------------------------------------------- +@_requires_scoped_core @pytest.mark.asyncio async def test_check_returns_pending() -> None: - bridge, handler, store = _make_bridge() - await store.save_pending("abc-123", "mod", {"x": 1}) - content, is_error, trace_id = await bridge.handle_meta_tool("__apcore_approval_check", {"approval_id": "abc-123"}) + bridge, handler, _ = _make_bridge() + pending = await handler.request_approval(_make_approval_request()) + content, is_error, _ = await bridge.handle_meta_tool( + "__apcore_approval_check", {"approval_id": pending.audit_id}, + ) assert is_error is False body = json.loads(content[0]["text"]) assert body["status"] == "pending" - assert body["approval_id"] == "abc-123" + assert body["approval_id"] == pending.audit_id + assert pending.approval_id not in content[0]["text"] +@_requires_scoped_core @pytest.mark.asyncio async def test_check_returns_approved() -> None: bridge, handler, store = _make_bridge() - await store.save_pending("abc-456", "mod", {}) - await store.resolve("abc-456", approved=True) - content, is_error, _ = await bridge.handle_meta_tool("__apcore_approval_check", {"approval_id": "abc-456"}) + pending = await handler.request_approval(_make_approval_request()) + await store.resolve(pending.audit_id, approved=True) + content, is_error, _ = await bridge.handle_meta_tool( + "__apcore_approval_check", {"approval_id": pending.audit_id}, + ) assert is_error is False body = json.loads(content[0]["text"]) assert body["status"] == "approved" - assert body["approval_id"] == "abc-456" + assert body["approval_id"] == pending.audit_id assert "reason" not in body +@_requires_scoped_core @pytest.mark.asyncio -async def test_check_returns_rejected_with_reason() -> None: +async def test_check_returns_rejected_without_provider_text() -> None: bridge, handler, store = _make_bridge() - await store.save_pending("abc-789", "mod", {}) - await store.resolve("abc-789", approved=False, reason="not today") - content, is_error, _ = await bridge.handle_meta_tool("__apcore_approval_check", {"approval_id": "abc-789"}) + pending = await handler.request_approval(_make_approval_request()) + await store.resolve(pending.audit_id, approved=False, reason="not today") + content, is_error, _ = await bridge.handle_meta_tool( + "__apcore_approval_check", {"approval_id": pending.audit_id}, + ) assert is_error is False body = json.loads(content[0]["text"]) assert body["status"] == "rejected" - assert body["reason"] == "not today" + assert "reason" not in body @pytest.mark.asyncio async def test_check_unknown_id_returns_rejected() -> None: - bridge, handler, store = _make_bridge() - content, is_error, _ = await bridge.handle_meta_tool("__apcore_approval_check", {"approval_id": "unknown-xyz"}) - # handler.check_approval returns rejected for unknown ids + bridge, _, _ = _make_bridge() + content, is_error, _ = await bridge.handle_meta_tool( + "__apcore_approval_check", {"approval_id": "c5b92219-e067-485a-9752-d09cd362588d"}, + ) assert is_error is False body = json.loads(content[0]["text"]) assert body["status"] == "rejected" @@ -155,6 +170,7 @@ async def test_check_unknown_meta_tool_name_is_error() -> None: # --------------------------------------------------------------------------- +@_requires_scoped_core @pytest.mark.asyncio async def test_request_approval_returns_pending_with_id() -> None: store = InMemoryApprovalStore() @@ -174,13 +190,14 @@ async def test_request_approval_returns_pending_with_id() -> None: ) result = await handler.request_approval(request) assert result.status == "pending" - assert result.approval_id is not None - # store should have the pending record - record = await store.get_result(result.approval_id) + assert result.approval_id is not None and result.audit_id is not None + assert result.approval_id != result.audit_id + record = await store.get_result(result.audit_id) assert record is not None assert record["status"] == "pending" +@_requires_scoped_core @pytest.mark.asyncio async def test_request_approval_calls_notify_callback() -> None: store = InMemoryApprovalStore() @@ -202,9 +219,11 @@ async def test_request_approval_calls_notify_callback() -> None: result = await handler.request_approval(request) notify.assert_awaited_once() args = notify.call_args - assert args[0][0] == result.approval_id + assert args[0][0] == result.audit_id + assert args[0][0] != result.approval_id +@_requires_scoped_core @pytest.mark.asyncio async def test_request_approval_swallows_notify_exception() -> None: """notify_callback errors must not propagate.""" @@ -237,19 +256,20 @@ async def bad_notify(*args: Any) -> None: # --------------------------------------------------------------------------- -class _FailingStore: - """ApprovalStore stand-in whose every operation raises.""" +class _FailingStore(InMemoryApprovalStore): + """Scoped approval store stand-in whose operations raise.""" def __init__(self, exc: BaseException) -> None: + super().__init__() self._exc = exc - async def save_pending(self, approval_id: str, module_id: str, arguments: dict) -> None: + async def save_scoped_pending(self, approval_id, arguments, scope, verifier) -> None: raise self._exc - async def get_result(self, approval_id: str) -> dict[str, Any] | None: + async def get_scoped_result(self, approval_id, principal) -> dict[str, Any] | None: raise self._exc - async def resolve(self, approval_id: str, *, approved: bool, reason: str | None = None) -> bool: + async def consume_scoped(self, approval_id, scope, verifier) -> dict[str, Any] | None: raise self._exc @@ -267,6 +287,7 @@ def _make_approval_request() -> Any: ) +@_requires_scoped_core @pytest.mark.asyncio async def test_request_approval_returns_rejected_when_save_pending_raises() -> None: """A store that cannot persist must fail the gate closed, not raise.""" @@ -278,17 +299,19 @@ async def test_request_approval_returns_rejected_when_save_pending_raises() -> N assert result.reason == "Storage error" +@_requires_scoped_core @pytest.mark.asyncio async def test_check_approval_returns_rejected_when_get_result_raises() -> None: """A store that cannot be read must fail the gate closed, not raise.""" handler = StorageBackedApprovalHandler(_FailingStore(RuntimeError("redis down"))) - result = await handler.check_approval("apr-1") + result = await handler.poll_approval("c5b92219-e067-485a-9752-d09cd362588d", None) assert result.status == "rejected" assert result.reason == "Storage error" +@_requires_scoped_core @pytest.mark.asyncio async def test_capacity_failures_report_the_capacity_reason() -> None: """A capacity rejection is reported distinctly from a generic storage error.""" @@ -296,7 +319,7 @@ async def test_capacity_failures_report_the_capacity_reason() -> None: named = StorageBackedApprovalHandler(_FailingStore(RuntimeError("store capacity exceeded"))) assert (await handler.request_approval(_make_approval_request())).reason == "Store capacity exceeded" - assert (await named.check_approval("apr-1")).reason == "Store capacity exceeded" + assert (await named.poll_approval("c5b92219-e067-485a-9752-d09cd362588d", None)).reason == "Store capacity exceeded" # --------------------------------------------------------------------------- @@ -306,40 +329,35 @@ async def test_capacity_failures_report_the_capacity_reason() -> None: def test_approval_store_param_creates_handler() -> None: """Passing approval_store to APCoreMCP auto-creates StorageBackedApprovalHandler.""" - from unittest.mock import MagicMock - store = InMemoryApprovalStore() - mock_registry = MagicMock() - mock_registry.list.return_value = [] - mock_executor = MagicMock() - mock_executor.registry = mock_registry - from apcore_mcp.apcore_mcp import APCoreMCP - mcp = APCoreMCP(mock_executor, approval_store=store, async_tasks=False) + mcp = APCoreMCP(Registry(), approval_store=store, async_tasks=False) assert mcp._approval_store is store assert isinstance(mcp._approval_handler, StorageBackedApprovalHandler) def test_explicit_approval_handler_not_overridden_by_store() -> None: """Explicit approval_handler takes precedence over approval_store auto-wiring.""" - from unittest.mock import MagicMock - store = InMemoryApprovalStore() explicit_handler = StorageBackedApprovalHandler(store) - mock_registry = MagicMock() - mock_registry.list.return_value = [] - mock_executor = MagicMock() - mock_executor.registry = mock_registry - from apcore_mcp.apcore_mcp import APCoreMCP mcp = APCoreMCP( - mock_executor, + Registry(), approval_handler=explicit_handler, approval_store=store, async_tasks=False, ) assert mcp._approval_handler is explicit_handler + + +@pytest.mark.asyncio +async def test_legacy_status_method_cannot_authorize() -> None: + _, handler, store = _make_bridge() + record_id = "c5b92219-e067-485a-9752-d09cd362588d" + await store.save_pending(record_id, "mod", {}) + await store.resolve(record_id, approved=True) + assert (await handler.check_approval(record_id)).status == "rejected" diff --git a/mcp/python/tests/server/test_scoped_approval_wire.py b/mcp/python/tests/server/test_scoped_approval_wire.py new file mode 100644 index 00000000..76672d04 --- /dev/null +++ b/mcp/python/tests/server/test_scoped_approval_wire.py @@ -0,0 +1,233 @@ +"""Phase B through the real MCP request handler and the Core approval gate.""" + +from __future__ import annotations + +import asyncio +import json +from typing import Any + +import httpx +import pytest +from apcore import AlwaysDenyHandler, Executor, Identity, ModuleAnnotations, Registry + +from apcore_mcp import APCoreMCP +from apcore_mcp.adapters.approval import _CORE_SCOPED_APPROVAL +from apcore_mcp.approval_store import InMemoryApprovalStore +from tests.server.test_versioned_tool_wire import connected_client + +_TOOL = "fixture.approved_report" +_requires_scoped_core = pytest.mark.skipif(not _CORE_SCOPED_APPROVAL, reason="requires scoped Core approval") + + +class Report: + description = "Return an approved synthetic report" + input_schema = { + "type": "object", + "properties": {"count": {"type": "integer"}}, + "required": ["count"], + "additionalProperties": False, + } + output_schema = {"type": "object"} + annotations = ModuleAnnotations(requires_approval=True) + + def __init__(self) -> None: + self.inputs = [] + + async def execute(self, inputs, context): + self.inputs.append(inputs.copy()) + return inputs + + +class StreamingReport(Report): + annotations = ModuleAnnotations(requires_approval=True, streaming=True) + + async def stream(self, inputs, context): + self.inputs.append(inputs.copy()) + yield inputs + + +def test_phase_b_preserves_a_supplied_executors_existing_handler() -> None: + executor = Executor(Registry(), approval_handler=AlwaysDenyHandler()) + + with pytest.raises(ValueError, match="already has an approval handler"): + APCoreMCP(executor, approval_store=InMemoryApprovalStore()) + + +@_requires_scoped_core +@pytest.mark.parametrize("tool_type", [Report, StreamingReport]) +async def test_pending_credentials_and_status_round_trip_through_core(tool_type, caplog) -> None: + registry = Registry() + report = tool_type() + registry.register(_TOOL, report) + store = InMemoryApprovalStore() + notifications = [] + audit_events = [] + + class EventRecorder: + def emit(self, event): + if event.event_type == "apcore.approval.decision": + audit_events.append(event.data) + + executor = Executor(registry, event_emitter=EventRecorder()) + + async def notify(approval_id, module_id, arguments): + notifications.append((approval_id, module_id, arguments)) + + with caplog.at_level("DEBUG"): + async with connected_client( + executor, approval_store=store, approval_notify=notify, validate_inputs=True, trace=True, + ) as session: + pending = await session.call_tool(_TOOL, {"count": 1}) + assert pending.isError + approval = pending.meta["apcore"]["approval"] + public_id, credential = approval["approvalId"], approval["resumeToken"] + assert public_id != credential + assert report.inputs == [] + assert notifications == [(public_id, _TOOL, {"count": 1})] + assert credential not in repr(pending.content) + poll = await session.call_tool("__apcore_approval_check", {"approval_id": public_id}) + assert json.loads(poll.content[0].text)["status"] == "pending" + assert credential not in poll.model_dump_json() + still_pending = await session.call_tool(_TOOL, {"count": 1}, meta={"approvalId": credential}) + assert still_pending.isError + assert still_pending.meta["apcore"]["approval"] == approval + assert await store.resolve(public_id, approved=True) + approved = await session.call_tool("__apcore_approval_check", {"approval_id": public_id}) + assert json.loads(approved.content[0].text)["status"] == "approved" + other_scope = await session.call_tool(_TOOL, {"count": 2}, meta={"approvalId": credential}) + assert other_scope.isError + assert "apcore" not in (other_scope.meta or {}) + assert report.inputs == [] + + requests = [session.call_tool(_TOOL, {"count": 1}, meta={"approvalId": credential}) for _ in range(2)] + first, second = await asyncio.gather(*requests) + assert sorted(result.isError for result in (first, second)) == [False, True] + result = next(result for result in (first, second) if not result.isError) + assert result.structuredContent == {"count": 1} + assert report.inputs == [{"count": 1}] + if credential in caplog.text: + pytest.fail("Approval credential entered debug logs") + assert credential not in repr(audit_events) + assert any(event["approval_id"] == public_id for event in audit_events) + + +class _HttpSession: + def __init__(self, client: httpx.AsyncClient, principal: str) -> None: + self.client = client + self.headers = { + "accept": "application/json, text/event-stream", + "authorization": principal, + "mcp-protocol-version": "2025-06-18", + } + self.request_id = 0 + + async def request(self, method: str, params: dict[str, Any]) -> dict[str, Any]: + self.request_id += 1 + response = await self.client.post("/mcp/", headers=self.headers, json={ + "jsonrpc": "2.0", "method": method, "params": params, "id": self.request_id, + }) + assert response.status_code == 200 + session_id = response.headers.get("mcp-session-id") + if session_id: + self.headers["mcp-session-id"] = session_id + if response.headers.get("content-type", "").startswith("application/json"): + return response.json()["result"] + return json.loads(next(line[6:] for line in response.text.splitlines() if line.startswith("data: ")))["result"] + + async def initialize(self) -> None: + await self.request("initialize", { + "protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": {"name": "test", "version": "1"}, + }) + response = await self.client.post("/mcp/", headers=self.headers, json={ + "jsonrpc": "2.0", "method": "notifications/initialized", + }) + assert response.status_code == 202 + + +@_requires_scoped_core +async def test_streamable_http_poll_and_resume_are_bound_to_the_authenticated_identity(caplog) -> None: + class Authenticator: + def authenticate(self, headers): + return { + "Bearer fixture-owner": Identity(id="owner"), + "Bearer fixture-reader": Identity(id="reader"), + }.get(headers.get("authorization")) + + registry = Registry() + report = Report() + registry.register(_TOOL, report) + store = InMemoryApprovalStore() + mcp = APCoreMCP(registry, approval_store=store, authenticator=Authenticator()) + with caplog.at_level("DEBUG"): + async with mcp.async_serve() as app, httpx.AsyncClient( + transport=httpx.ASGITransport(app=app), base_url="http://localhost", + ) as client, asyncio.timeout(5): + owner = _HttpSession(client, "Bearer fixture-owner") + reader = _HttpSession(client, "Bearer fixture-reader") + await owner.initialize() + await reader.initialize() + request = {"name": _TOOL, "arguments": {"count": 1}} + pending = await owner.request("tools/call", request) + approval = pending["_meta"]["apcore"]["approval"] + public_id, credential = approval["approvalId"], approval["resumeToken"] + poll = {"name": "__apcore_approval_check", "arguments": {"approval_id": public_id}} + + assert json.loads((await reader.request("tools/call", poll))["content"][0]["text"])["status"] == "rejected" + assert json.loads((await owner.request("tools/call", poll))["content"][0]["text"])["status"] == "pending" + assert await store.resolve(public_id, approved=True) + retry = {**request, "_meta": {"approvalId": credential}} + assert (await reader.request("tools/call", retry))["isError"] + assert not (await owner.request("tools/call", retry))["isError"] + if credential in caplog.text: + pytest.fail("Approval credential entered debug logs") + assert report.inputs == [{"count": 1}] + assert "chunk:" in caplog.text # Unrelated HTTP debug logging remains available. + + +@pytest.mark.skipif(_CORE_SCOPED_APPROVAL, reason="exercises the minimum Core compatibility path") +async def test_legacy_core_reports_scoped_approval_unavailable() -> None: + registry = Registry() + report = Report() + registry.register(_TOOL, report) + async with connected_client(registry, approval_store=InMemoryApprovalStore()) as session: + tools = await session.list_tools() + assert "__apcore_approval_check" not in {tool.name for tool in tools.tools} + result = await session.call_tool(_TOOL, {"count": 1}) + assert result.isError + assert "Scoped approval is unavailable" in result.content[0].text + assert "apcore" not in (result.meta or {}) + assert report.inputs == [] + + +@_requires_scoped_core +async def test_background_tool_has_no_channel_to_issue_approval_credentials() -> None: + registry = Registry() + report = Report() + registry.register(_TOOL, report, metadata={"async": True}) + notifications = [] + + async def notify(*args): + notifications.append(args) + + async with connected_client( + registry, approval_store=InMemoryApprovalStore(), approval_notify=notify, async_tasks=True, + ) as session: + submitted = await session.call_tool(_TOOL, {"count": 1}) + task_id = json.loads(submitted.content[0].text)["task_id"] + async with asyncio.timeout(2): + while True: + result = await session.call_tool("__apcore_task_status", {"task_id": task_id}) + status = json.loads(result.content[0].text) + if status["status"] == "failed": + break + await asyncio.sleep(0) + assert notifications == [] + assert report.inputs == [] + assert "resumeToken" not in result.model_dump_json() + + +@_requires_scoped_core +def test_scoped_approval_is_explicitly_unavailable_on_legacy_sse() -> None: + mcp = APCoreMCP(Registry(), approval_store=InMemoryApprovalStore()) + with pytest.raises(ValueError, match="legacy SSE transport"): + mcp.serve(transport="sse") diff --git a/mcp/python/tests/test_apcore_mcp.py b/mcp/python/tests/test_apcore_mcp.py index 95890f51..7d4f3a4a 100644 --- a/mcp/python/tests/test_apcore_mcp.py +++ b/mcp/python/tests/test_apcore_mcp.py @@ -182,15 +182,8 @@ def test_approval_handler_stored(self) -> None: assert hasattr(mcp, "_approval_handler") assert mcp._approval_handler is handler - def test_build_server_components_passes_approval_bridge_for_handler_only(self) -> None: - """[Problem A] _build_server_components must construct an ApprovalBridge - whenever a handler is present, regardless of approval_store. - - Passing StorageBackedApprovalHandler(store) directly as approval_handler - (with approval_store unset) must still register the - __apcore_approval_check meta-tool. Previously the bridge was gated on - both store AND handler, silently breaking Phase B polling. - """ + def test_build_server_components_only_advertises_a_scoped_handler(self) -> None: + """A status-only or elicitation handler does not expose Phase B polling.""" handler = MagicMock() mcp = APCoreMCP(StubRegistry(), approval_handler=handler, async_tasks=False) assert mcp._approval_store is None @@ -208,7 +201,7 @@ def register_handlers(self, *args: Any, **kwargs: Any) -> None: with patch("apcore_mcp.MCPServerFactory", SpyFactory): mcp._build_server_components() - assert captured["approval_bridge"] is not None + assert captured["approval_bridge"] is None def test_default_output_formatter_is_none(self) -> None: """Default output_formatter is None (raw JSON).""" diff --git a/mcp/python/tests/test_review_fixes.py b/mcp/python/tests/test_review_fixes.py index 1c09d247..af9a3f3d 100644 --- a/mcp/python/tests/test_review_fixes.py +++ b/mcp/python/tests/test_review_fixes.py @@ -351,6 +351,7 @@ def test_apcore_mcp_build_server_components_passes_output_schema_map(self) -> No mcp._async_bridge = None mcp._approval_handler = None mcp._approval_store = None + mcp._phase_b_handler = None mcp._build_server_components() From e6c69bae000badd481f509900db5c70e427b7d84 Mon Sep 17 00:00:00 2001 From: tercel Date: Fri, 27 Nov 2026 14:08:26 +0800 Subject: [PATCH 26/36] fix(mcp): enforce scoped approval resumption in Rust Signed-off-by: tercel --- mcp/rust/CHANGELOG.md | 1 + mcp/rust/Cargo.lock | 2 + mcp/rust/Cargo.toml | 2 + mcp/rust/README.md | 14 + mcp/rust/src/adapters/approval.rs | 403 ++++++++++++++++++++--- mcp/rust/src/adapters/errors.rs | 23 +- mcp/rust/src/apcore_mcp.rs | 301 +++++++++++++++-- mcp/rust/src/approval_store.rs | 297 +++++++++++++---- mcp/rust/src/server/approval_bridge.rs | 108 +++++- mcp/rust/src/server/async_task_bridge.rs | 72 +++- mcp/rust/src/server/factory.rs | 15 +- mcp/rust/src/server/router.rs | 73 +++- mcp/rust/src/server/server.rs | 13 + mcp/rust/src/server/transport.rs | 12 +- 14 files changed, 1144 insertions(+), 192 deletions(-) diff --git a/mcp/rust/CHANGELOG.md b/mcp/rust/CHANGELOG.md index 01e21369..75c6cf0c 100644 --- a/mcp/rust/CHANGELOG.md +++ b/mcp/rust/CHANGELOG.md @@ -11,6 +11,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed - Route inbound cancellation to the active request, derive terminal stream results from Core when available, and fail startup when OpenAPI tools fail to register. +- Resume foreground Phase B calls through scoped Core approval. Keep the record ID public, return the private credential only in pending result metadata, and consume approved grants once. ## [0.23.4] - 2026-11-20 diff --git a/mcp/rust/Cargo.lock b/mcp/rust/Cargo.lock index 88d05c8b..9582bd20 100644 --- a/mcp/rust/Cargo.lock +++ b/mcp/rust/Cargo.lock @@ -147,8 +147,10 @@ dependencies = [ "schemars", "serde", "serde_json", + "sha2", "strum", "strum_macros", + "subtle", "tempfile", "thiserror", "tokio", diff --git a/mcp/rust/Cargo.toml b/mcp/rust/Cargo.toml index 1529f755..b093403e 100644 --- a/mcp/rust/Cargo.toml +++ b/mcp/rust/Cargo.toml @@ -28,6 +28,8 @@ mcp-embedded-ui = "0.5" tokio = { version = "1", features = ["full"] } serde = { version = "1", features = ["derive"] } serde_json = { version = "1", features = ["float_roundtrip"] } +sha2 = "0.10" +subtle = "2" # MCP schema validation must reject external retrieval even when apcore enables it. jsonschema = { version = "0.28", default-features = false } # Inspect all schema references, including unused definitions, without retrieval. diff --git a/mcp/rust/README.md b/mcp/rust/README.md index b60e6609..b2cfb9f6 100644 --- a/mcp/rust/README.md +++ b/mcp/rust/README.md @@ -476,6 +476,20 @@ CLI usage: apcore-mcp --extensions-dir ./extensions --approval elicit ``` +For Phase B, configure the builder with `approval_store`. The store supports +stdio and Streamable HTTP direct tool calls. A supplied Core executor must be +unshared and have no installed approval handler when the builder attaches the +store. Background jobs that require an approval report that Phase B is +unavailable for that job. + +The pending tool response provides an operator record ID at +`_meta.apcore.approval.approvalId` and a private credential at +`_meta.apcore.approval.resumeToken`. The notification callback receives the +operator record ID. The approval store uses that ID for resolution, and +`__apcore_approval_check` takes it as `approval_id` for owner-scoped status +queries. After approval, retry the original tool inputs with the private +credential in the request's `params._meta.approvalId`. + ### Output Formatting By default, tool execution results are serialized as JSON. You can customize this by passing an `output_format` name or a custom `output_formatter` closure. diff --git a/mcp/rust/src/adapters/approval.rs b/mcp/rust/src/adapters/approval.rs index bccc01a4..c05b0698 100644 --- a/mcp/rust/src/adapters/approval.rs +++ b/mcp/rust/src/adapters/approval.rs @@ -10,9 +10,13 @@ use std::sync::Arc; use apcore::approval::{ApprovalHandler, ApprovalRequest, ApprovalResult}; use apcore::errors::ModuleError; use async_trait::async_trait; +use sha2::{Digest, Sha256}; use uuid::Uuid; -use crate::approval_store::ApprovalStore; +use crate::approval_store::{ + ApprovalPrincipal, ApprovalRecord, ApprovalScope, ApprovalStatus, ApprovalStore, + ApprovalVerifier, +}; use crate::helpers::{ElicitAction, ElicitCallback, MCP_ELICIT_CALL_ID_KEY}; use crate::server::elicit_registry::{self, SharedElicitCallback}; @@ -262,18 +266,17 @@ impl ApprovalHandler for ElicitationApprovalHandler { // ── StorageBackedApprovalHandler ───────────────────────────────────────────── -/// Callback type for out-of-band approval notifications (approval_id, module_id, arguments). +pub(crate) const BACKGROUND_APPROVAL_CONTEXT_KEY: &str = "mcp.background_task"; + +/// Callback type for out-of-band approval notifications (audit_id, module_id, arguments). pub type ApprovalNotifyCallback = Arc; /// Phase B approval handler backed by a pluggable [`ApprovalStore`]. /// -/// On `request_approval`, generates a UUID, writes a pending record to the -/// store, fires an optional notify callback, and returns -/// `ApprovalResult { status: "pending", approval_id: Some(uuid) }`. -/// -/// On `check_approval`, reads the record from the store and maps its status -/// to the corresponding `ApprovalResult`. +/// The public `audit_id` identifies the record for human resolution and status. +/// Only the pending result given to the caller carries the resume credential +/// in `approval_id`. Scoped resumption verifies and consumes it through the store. pub struct StorageBackedApprovalHandler { store: Arc, notify_callback: Option, @@ -290,7 +293,7 @@ impl StorageBackedApprovalHandler { /// Attach an optional notification callback. /// - /// The callback receives `(approval_id, module_id, arguments)` and can + /// The callback receives `(audit_id, module_id, arguments)` and can /// be used to send an out-of-band notification (e.g. Slack, email). pub fn with_notify(mut self, callback: F) -> Self where @@ -299,6 +302,40 @@ impl StorageBackedApprovalHandler { self.notify_callback = Some(Arc::new(callback)); self } + + /// Read a public approval record scoped to the current authenticated principal. + pub async fn check_scoped_approval( + &self, + audit_id: &str, + identity: Option<&apcore::Identity>, + ) -> ApprovalResult { + scoped_approval_status(self.store.as_ref(), audit_id, identity).await + } +} + +pub(crate) async fn scoped_approval_status( + store: &dyn ApprovalStore, + audit_id: &str, + identity: Option<&apcore::Identity>, +) -> ApprovalResult { + if !is_public_approval_id(audit_id) { + return rejected("Approval record not found"); + } + let principal = identity.map(ApprovalPrincipal::from); + match store.get_scoped_result(audit_id, principal.as_ref()).await { + Ok(Some(record)) => stored_result(record, Some(audit_id)), + Ok(None) => rejected("Approval record not found"), + Err(_) => store_error(), + } +} + +pub(crate) fn is_public_approval_id(audit_id: &str) -> bool { + audit_id.len() == 36 + && Uuid::parse_str(audit_id).is_ok_and(|id| { + id.get_version_num() == 4 + && id.get_variant() == uuid::Variant::RFC4122 + && id.hyphenated().to_string() == audit_id + }) } impl fmt::Debug for StorageBackedApprovalHandler { @@ -309,71 +346,120 @@ impl fmt::Debug for StorageBackedApprovalHandler { } } +pub(crate) fn resume_audit_id(credential: &str) -> Option<&str> { + let (audit_id, secret) = credential.split_once('.')?; + (is_public_approval_id(audit_id) && secret.len() == 32 && Uuid::parse_str(secret).is_ok()) + .then_some(audit_id) +} + +fn credential_verifier(credential: &str) -> ApprovalVerifier { + Sha256::digest(credential.as_bytes()).into() +} + +fn stored_result(record: ApprovalRecord, audit_id: Option<&str>) -> ApprovalResult { + let mut result = ApprovalResult::default(); + result.status = record.status.to_string(); + result.audit_id = audit_id.map(str::to_owned); + if record.status == ApprovalStatus::Rejected { + result.reason = record.reason; + } + result +} + +fn store_error() -> ApprovalResult { + tracing::error!("Approval store operation failed"); + rejected("internal store error") +} + +fn is_background_call(request: &ApprovalRequest) -> bool { + request.context.as_ref().is_some_and(|context| { + context + .data + .read() + .get(BACKGROUND_APPROVAL_CONTEXT_KEY) + .and_then(serde_json::Value::as_bool) + == Some(true) + }) +} + #[async_trait] impl ApprovalHandler for StorageBackedApprovalHandler { async fn request_approval( &self, request: &ApprovalRequest, ) -> Result { - let approval_id = Uuid::new_v4().to_string(); - let module_id = request.module_id.as_str(); - let arguments = request.arguments.clone(); - - if let Err(e) = self + if is_background_call(request) { + return Ok(rejected("Background tasks do not support Phase B approval")); + } + let audit_id = Uuid::new_v4().to_string(); + let credential = format!("{audit_id}.{}", Uuid::new_v4().simple()); + let verifier = credential_verifier(&credential); + let scope = ApprovalScope::from(request); + if self .store - .save_pending(&approval_id, module_id, &arguments) + .save_scoped_pending(&audit_id, &verifier, &scope) .await + .is_err() { - tracing::error!("approval store save_pending failed: {e}"); - let mut result = ApprovalResult::default(); - result.status = "rejected".to_string(); - result.reason = Some("internal store error".to_string()); - return Ok(result); + return Ok(store_error()); } if let Some(cb) = &self.notify_callback { - cb(approval_id.clone(), module_id.to_string(), arguments); + cb( + audit_id.clone(), + request.module_id.clone(), + request.arguments.clone(), + ); } let mut result = ApprovalResult::default(); result.status = "pending".to_string(); - result.approval_id = Some(approval_id); + result.approval_id = Some(credential); + result.audit_id = Some(audit_id); Ok(result) } - async fn check_approval(&self, approval_id: &str) -> Result { - match self.store.get_result(approval_id).await { - Err(e) => { - let mut result = ApprovalResult::default(); - result.status = "rejected".to_string(); - result.reason = Some(format!("store error: {e}")); - Ok(result) - } - Ok(None) => { - let mut result = ApprovalResult::default(); - result.status = "rejected".to_string(); - result.reason = Some("approval_id not found".to_string()); - Ok(result) + async fn check_approval(&self, audit_id: &str) -> Result { + if resume_audit_id(audit_id).is_some() { + return Ok(rejected("Approval record not found")); + } + Ok(match self.store.get_result(audit_id).await { + Ok(Some(record)) => { + let public_id = Uuid::parse_str(audit_id).is_ok().then_some(audit_id); + stored_result(record, public_id) } - Ok(Some(rec)) => { - use crate::approval_store::ApprovalStatus; - let mut result = ApprovalResult::default(); - result.approval_id = Some(approval_id.to_string()); - match rec.status { - ApprovalStatus::Approved => { - result.status = "approved".to_string(); - } - ApprovalStatus::Rejected => { - result.status = "rejected".to_string(); - result.reason = rec.reason; - } - ApprovalStatus::Pending => { - result.status = "pending".to_string(); + Ok(None) => rejected("Approval record not found"), + Err(_) => store_error(), + }) + } + + async fn check_approval_for_call( + &self, + credential: &str, + request: &ApprovalRequest, + ) -> Result { + if is_background_call(request) { + return Ok(rejected("Background tasks do not support Phase B approval")); + } + let Some(audit_id) = resume_audit_id(credential) else { + return Ok(rejected("Approval credential unavailable for this call")); + }; + let verifier = credential_verifier(credential); + let scope = ApprovalScope::from(request); + Ok( + match self.store.consume_scoped(audit_id, &verifier, &scope).await { + Ok(Some(record)) => { + let pending = record.status == ApprovalStatus::Pending; + let mut result = stored_result(record, Some(audit_id)); + if pending { + result.approval_id = Some(credential.to_owned()); } + result } - Ok(result) - } - } + Ok(None) => rejected("Approval credential unavailable for this call"), + Err(_) => store_error(), + }, + ) } } @@ -388,6 +474,219 @@ mod tests { use serde_json::json; use std::sync::{Arc, Mutex}; + fn scoped_request() -> ApprovalRequest { + let mut request = ApprovalRequest::default(); + request.module_id = "sample.render".into(); + request.caller_id = Some("sample.caller".into()); + request.arguments = json!({"label": "draft", "options": {"width": 12, "height": 8}}); + request.context = Some(apcore::Context::new(apcore::Identity::new( + "editor".into(), + "user".into(), + vec![], + Default::default(), + ))); + request + } + + #[tokio::test] + async fn storage_approval_notifies_with_a_public_record_id() { + let store = Arc::new(crate::approval_store::InMemoryApprovalStore::new()); + let notified = Arc::new(Mutex::new(None)); + let handler = StorageBackedApprovalHandler::new(store).with_notify({ + let notified = Arc::clone(¬ified); + move |id, _, _| *notified.lock().unwrap() = Some(id) + }); + let request = scoped_request(); + let result = handler.request_approval(&request).await.unwrap(); + assert_eq!(result.status, "pending"); + let audit_id = result + .audit_id + .as_deref() + .expect("public approval record ID"); + let credential = result.approval_id.as_deref().expect("resume credential"); + assert!(Uuid::parse_str(audit_id).is_ok()); + assert_ne!(audit_id, credential); + assert_eq!(notified.lock().unwrap().as_deref(), Some(audit_id)); + + let identity = request.context.as_ref().unwrap().identity.as_ref(); + let status = handler.check_scoped_approval(audit_id, identity).await; + assert_eq!(status.status, "pending"); + assert!(status.approval_id.is_none()); + assert_eq!(status.audit_id.as_deref(), Some(audit_id)); + let anonymous = handler.check_scoped_approval(audit_id, None).await; + assert_eq!(anonymous.status, "rejected"); + assert!(anonymous.audit_id.is_none()); + } + + #[tokio::test] + async fn approved_invocation_consumes_its_credential_once() { + let store = Arc::new(crate::approval_store::InMemoryApprovalStore::new()); + let handler = StorageBackedApprovalHandler::new(store.clone()); + let request = scoped_request(); + let result = handler.request_approval(&request).await.unwrap(); + let audit_id = result.audit_id.as_deref().unwrap(); + let credential = result.approval_id.as_deref().unwrap(); + let pending = handler + .check_approval_for_call(credential, &request) + .await + .unwrap(); + assert_eq!(pending.status, "pending"); + assert_eq!(pending.approval_id.as_deref(), Some(credential)); + assert!(store.resolve(audit_id, true, None).await.unwrap()); + + let (first, second) = tokio::join!( + handler.check_approval_for_call(credential, &request), + handler.check_approval_for_call(credential, &request), + ); + let mut statuses = [first.unwrap().status, second.unwrap().status]; + statuses.sort(); + assert_eq!(statuses, ["approved", "rejected"]); + assert_eq!( + handler.check_approval(audit_id).await.unwrap().status, + "approved" + ); + } + + #[tokio::test] + async fn phase_b_scope_covers_the_invocation_and_does_not_depend_on_object_key_order() { + let store = Arc::new(crate::approval_store::InMemoryApprovalStore::new()); + let handler = StorageBackedApprovalHandler::new(store.clone()); + let request = scoped_request(); + let result = handler.request_approval(&request).await.unwrap(); + let audit_id = result.audit_id.as_deref().unwrap(); + let credential = result.approval_id.as_deref().unwrap(); + assert!(store.resolve(audit_id, true, None).await.unwrap()); + + let mut other_module = request.clone(); + other_module.module_id = "sample.preview".into(); + let mut other_caller = request.clone(); + other_caller.caller_id = None; + let mut other_principal = request.clone(); + other_principal.context = Some(apcore::Context::new(apcore::Identity::new( + "viewer".into(), + "user".into(), + vec![], + Default::default(), + ))); + let mut other_identity_type = request.clone(); + other_identity_type.context = Some(apcore::Context::new(apcore::Identity::new( + "editor".into(), + "service".into(), + vec![], + Default::default(), + ))); + let mut other_arguments = request.clone(); + other_arguments.arguments["options"]["width"] = json!(24); + for other in [ + other_module, + other_caller, + other_principal, + other_identity_type, + other_arguments, + ] { + let result = handler + .check_approval_for_call(credential, &other) + .await + .unwrap(); + assert_eq!(result.status, "rejected"); + assert!(result.approval_id.is_none()); + } + + let mut same = request; + same.arguments = json!({"options": {"height": 8, "width": 12}, "label": "draft"}); + let result = handler + .check_approval_for_call(credential, &same) + .await + .unwrap(); + assert_eq!(result.status, "approved"); + assert_eq!(result.audit_id.as_deref(), Some(audit_id)); + assert!(result.approval_id.is_none()); + } + + #[tokio::test] + async fn status_only_store_remains_queryable_and_declines_scoped_approval() { + use crate::approval_store::StoreResult; + + struct StatusOnly; + + #[async_trait] + impl ApprovalStore for StatusOnly { + async fn save_pending( + &self, + _: &str, + _: &str, + _: &serde_json::Value, + ) -> StoreResult<()> { + Ok(()) + } + + async fn get_result(&self, _: &str) -> StoreResult> { + Ok(Some(ApprovalRecord { + status: ApprovalStatus::Approved, + module_id: "sample.render".into(), + reason: None, + })) + } + + async fn resolve(&self, _: &str, _: bool, _: Option) -> StoreResult { + Ok(true) + } + } + + let handler = StorageBackedApprovalHandler::new(Arc::new(StatusOnly)); + let id = Uuid::new_v4().to_string(); + let legacy_status = handler.check_approval(&id).await.unwrap(); + assert_eq!(legacy_status.status, "approved"); + assert!(legacy_status.approval_id.is_none()); + let request = scoped_request(); + assert_eq!( + handler.request_approval(&request).await.unwrap().status, + "rejected" + ); + let credential = format!("{id}.{}", Uuid::new_v4().simple()); + assert_eq!( + handler + .check_approval_for_call(&credential, &request) + .await + .unwrap() + .status, + "rejected" + ); + assert_eq!( + handler.check_scoped_approval(&id, None).await.status, + "rejected" + ); + } + + #[tokio::test(start_paused = true)] + async fn phase_b_expiry_enforces_both_deadlines_without_a_sweeper() { + use std::time::Duration; + + for (resolved_ttl, pending_ttl) in [(60, 5), (5, 60)] { + let store = Arc::new(crate::approval_store::InMemoryApprovalStore::with_options( + Duration::from_secs(resolved_ttl), + Duration::from_secs(pending_ttl), + 10, + )); + let handler = StorageBackedApprovalHandler::new(store.clone()); + let request = scoped_request(); + let result = handler.request_approval(&request).await.unwrap(); + let audit_id = result.audit_id.as_deref().unwrap(); + let credential = result.approval_id.as_deref().unwrap(); + assert!(store.resolve(audit_id, true, None).await.unwrap()); + tokio::time::advance(Duration::from_secs(5)).await; + assert_eq!( + handler + .check_approval_for_call(credential, &request) + .await + .unwrap() + .status, + "rejected" + ); + assert!(store.get_result(audit_id).await.unwrap().is_none()); + } + } + /// Create a mock elicit callback that returns the given action. fn mock_elicit(action: ElicitAction) -> ElicitCallback { Box::new(move |_msg, _schema| { diff --git a/mcp/rust/src/adapters/errors.rs b/mcp/rust/src/adapters/errors.rs index 93d8dd39..951387b0 100644 --- a/mcp/rust/src/adapters/errors.rs +++ b/mcp/rust/src/adapters/errors.rs @@ -124,24 +124,18 @@ impl ErrorMapper { return resp; } - // Approval pending → narrow details to only approvalId + // The pending credential belongs only in the initiating tool response metadata. if code == ApcoreErrorCode::ApprovalPending { - let narrowed = error - .details - .get("approval_id") - .map(|v| serde_json::json!({ "approvalId": v })); - let mut resp = McpErrorResponse { + return McpErrorResponse { is_error: true, error_type, - message: error.message.clone(), - details: narrowed, + message: "Approval is pending".to_string(), + details: None, retryable: None, ai_guidance: None, user_fixable: None, suggestion: None, }; - attach_ai_guidance(error, &mut resp); - return resp; } // Approval timeout → pass through with retryable=true @@ -638,7 +632,7 @@ mod tests { // ---- Approval pending ---- #[test] - fn test_approval_pending_narrowed() { + fn test_approval_pending_omits_confidential_details() { let mut details = HashMap::new(); details.insert( "approval_id".to_string(), @@ -656,11 +650,8 @@ mod tests { let resp = ErrorMapper::to_mcp_error(&err); assert!(resp.is_error); assert_eq!(resp.error_type, "APPROVAL_PENDING"); - assert_eq!(resp.message, "Awaiting approval"); - let d = resp.details.unwrap(); - assert_eq!(d.get("approvalId").unwrap().as_str().unwrap(), "abc-123"); - // module_id should NOT be present - assert!(d.get("module_id").is_none()); + assert_eq!(resp.message, "Approval is pending"); + assert!(resp.details.is_none()); } // ---- Approval timeout ---- diff --git a/mcp/rust/src/apcore_mcp.rs b/mcp/rust/src/apcore_mcp.rs index b38d6b9b..90ffdc94 100644 --- a/mcp/rust/src/apcore_mcp.rs +++ b/mcp/rust/src/apcore_mcp.rs @@ -262,7 +262,7 @@ impl crate::server::router::Executor for ApcoreExecutorAdapter { .await .map_err(|e| ExecutorError::Execution { code: format!("{:?}", e.code), - message: e.to_string(), + message: crate::server::approval_bridge::safe_execution_message(&e), details: None, }) } @@ -287,7 +287,7 @@ impl crate::server::router::Executor for ApcoreExecutorAdapter { let chunks = chunks.map(|item| { item.map_err(|error| ExecutorError::Execution { code: error.code.wire_str(), - message: error.to_string(), + message: crate::server::approval_bridge::safe_execution_message(&error), details: None, }) }); @@ -318,7 +318,7 @@ impl crate::server::router::Executor for ApcoreExecutorAdapter { } Err(e) => Err(ExecutorError::Execution { code: format!("{:?}", e.code), - message: e.to_string(), + message: crate::server::approval_bridge::safe_execution_message(&e), details: None, }), }) @@ -347,7 +347,7 @@ impl crate::server::router::Executor for ApcoreExecutorAdapter { ) -> Option), ExecutorError>> { let to_executor_error = |e: apcore::errors::ModuleError| ExecutorError::Execution { code: format!("{:?}", e.code), - message: e.to_string(), + message: crate::server::approval_bridge::safe_execution_message(&e), details: None, }; if want_trace { @@ -605,10 +605,14 @@ impl APCoreMCP { // `__apcore_approval_check` meta-tool so MCP clients can poll the // status of pending approval requests. let approval_bridge = self.approval_handler.as_ref().map(|handler| { - MCPServerFactory::append_approval_meta_tools(&mut tools); - Arc::new(crate::server::approval_bridge::ApprovalBridge::new( - Arc::clone(handler), - )) + let bridge = crate::server::approval_bridge::ApprovalBridge::new(Arc::clone(handler)); + let bridge = if let Some(store) = &self.approval_store { + MCPServerFactory::append_approval_meta_tools(&mut tools); + bridge.with_store(Arc::clone(store)) + } else { + bridge + }; + Arc::new(bridge) }); // Create execution router backed by the real apcore Executor, and @@ -914,6 +918,11 @@ impl APCoreMCP { self.config.transport.clone(), )); } + if self.approval_store.is_some() && transport == "sse" { + return Err(APCoreMCPError::Config( + "Phase B approval requires stdio or Streamable HTTP".to_string(), + )); + } let (server, router, tools, init_options, version, async_bridge) = self.build_server_components()?; @@ -1528,11 +1537,9 @@ impl APCoreMCPBuilder { /// Set the Phase B approval handler directly. /// - /// When set, `build()` retains the handler and `build_server_components` - /// instantiates an [`ApprovalBridge`](crate::server::approval_bridge::ApprovalBridge), - /// advertising the `__apcore_approval_check` meta-tool so MCP clients can - /// poll pending approvals. Prefer [`approval_store`](Self::approval_store) - /// for the storage-backed handler with an optional notify callback. [H-1] + /// When set, `build()` retains this handler for host integrations. + /// Use [`approval_store`](Self::approval_store) to enable scoped MCP + /// polling and resumption with an optional notification callback. pub fn approval_handler(mut self, handler: Arc) -> Self { self.approval_handler = Some(handler); self @@ -1540,8 +1547,10 @@ impl APCoreMCPBuilder { /// Configure Phase B async approvals backed by the given store. /// - /// At `build()` time a [`StorageBackedApprovalHandler`] is created from - /// this store and stored as the `approval_handler`. Combine with + /// At `build()` time a [`StorageBackedApprovalHandler`] is installed on + /// the executor and on the MCP status bridge. Supported on stdio and + /// Streamable HTTP for direct tool calls. A supplied executor must be + /// unshared and must not already have an approval handler. Combine with /// [`approval_notify`] to attach an out-of-band notification callback. /// /// [`StorageBackedApprovalHandler`]: crate::adapters::approval::StorageBackedApprovalHandler @@ -1552,7 +1561,7 @@ impl APCoreMCPBuilder { /// Attach a notification callback for Phase B approvals. /// - /// The callback receives `(approval_id, module_id, arguments)` and can + /// The callback receives `(audit_id, module_id, arguments)` and can /// send an out-of-band notification (e.g. Slack, email). Only takes effect /// when [`approval_store`] is also set. /// @@ -1842,6 +1851,31 @@ impl APCoreMCPBuilder { BackendSource::Executor(exec) => (None, exec), }; + // Build approval handler: approval_store takes precedence over approval_handler. + // The store (when supplied) is retained so the serve entry points can + // start its TTL sweep. [H-1] + let retained_store = self.approval_store.clone(); + let approval_handler = if let Some(store) = self.approval_store { + use crate::adapters::approval::StorageBackedApprovalHandler; + let owned_executor = Arc::get_mut(&mut executor).ok_or_else(|| { + APCoreMCPError::Config("Phase B approval requires an unshared Executor".to_string()) + })?; + if owned_executor.approval_handler.is_some() { + return Err(APCoreMCPError::Config( + "The Executor already has an approval handler".to_string(), + )); + } + let mut handler = StorageBackedApprovalHandler::new(store); + if let Some(cb) = self.approval_notify_callback { + handler = handler.with_notify(move |id, module, args| cb(id, module, args)); + } + let handler: Arc = Arc::new(handler); + owned_executor.set_approval_handler_shared(Arc::clone(&handler)); + Some(handler) + } else { + self.approval_handler + }; + // ── Install middleware (Config Bus entries first, then builder) ── let config_value = crate::config::get_middleware_config(); let config_middleware = @@ -1916,21 +1950,6 @@ impl APCoreMCPBuilder { (None, None) }; - // Build approval handler: approval_store takes precedence over approval_handler. - // The store (when supplied) is retained so the serve entry points can - // start its TTL sweep. [H-1] - let retained_store = self.approval_store.clone(); - let approval_handler = if let Some(store) = self.approval_store { - use crate::adapters::approval::StorageBackedApprovalHandler; - let mut handler = StorageBackedApprovalHandler::new(store); - if let Some(cb) = self.approval_notify_callback { - handler = handler.with_notify(move |id, module, args| cb(id, module, args)); - } - Some(Arc::new(handler) as Arc) - } else { - self.approval_handler - }; - // [L-3] Resolve the strategy preset by name (when set) so it can be // threaded into execution. Unknown names surface a warning and are // ignored (the executor keeps its default strategy) rather than @@ -2653,6 +2672,226 @@ mod tests { } } + #[tokio::test] + async fn wire_phase_b_keeps_approval_credentials_in_response_metadata() { + verify_wire_phase_b(false).await; + verify_wire_phase_b(true).await; + } + + #[tokio::test] + async fn phase_b_approval_requires_an_identity_aware_transport() { + let bridge = APCoreMCP::builder() + .backend(Arc::new(Registry::new())) + .transport("sse") + .approval_store(Arc::new(crate::approval_store::InMemoryApprovalStore::new())) + .build() + .unwrap(); + let result = bridge.serve_async().await; + assert!(matches!(result, Err(APCoreMCPError::Config(message)) + if message == "Phase B approval requires stdio or Streamable HTTP")); + } + + async fn verify_wire_phase_b(native_stream: bool) { + use crate::approval_store::{ApprovalStore, InMemoryApprovalStore}; + use crate::auth::middleware::AUTH_IDENTITY; + use crate::server::transport::McpHandler; + use std::sync::atomic::{AtomicUsize, Ordering}; + + struct Render(Arc, bool); + + #[async_trait::async_trait] + impl apcore::Module for Render { + fn input_schema(&self) -> Value { + json!({ + "type": "object", "properties": {"label": {"type": "string"}}, + "required": ["label"], "additionalProperties": false + }) + } + + fn output_schema(&self) -> Value { + json!({"type": "object"}) + } + + fn description(&self) -> &str { + "Render a sample label" + } + + fn annotations(&self) -> apcore::ModuleAnnotations { + apcore::ModuleAnnotations { + requires_approval: true, + ..Default::default() + } + } + + async fn execute( + &self, + inputs: Value, + _: &apcore::Context, + ) -> Result { + assert!(!self.1, "native module must stay on the streaming path"); + self.0.fetch_add(1, Ordering::SeqCst); + Ok(inputs) + } + + fn as_streaming(&self) -> Option<&dyn apcore::StreamingModule> { + self.1.then_some(self) + } + } + + impl apcore::StreamingModule for Render { + fn stream_typed( + &self, + inputs: Value, + _: &apcore::Context, + ) -> apcore::ChunkStream { + self.0.fetch_add(1, Ordering::SeqCst); + Box::pin(futures::stream::iter([Ok(inputs)])) + } + } + + let calls = Arc::new(AtomicUsize::new(0)); + let registry = Arc::new(Registry::new()); + registry + .register_module( + "demo.render", + Box::new(Render(Arc::clone(&calls), native_stream)), + ) + .unwrap(); + let store = Arc::new(InMemoryApprovalStore::new()); + let bridge = APCoreMCP::builder() + .backend(registry) + .approval_store(store.clone()) + .validate_inputs(true) + .build() + .unwrap(); + let (server, _, _, init, _, _) = bridge.build_server_components().unwrap(); + let handler = ServerHandler::from_server(&server, init).unwrap(); + let identity = + apcore::Identity::new("editor".into(), "user".into(), vec![], Default::default()); + let arguments = json!({"label": "draft"}); + let call = |name, args, metadata| { + handler.handle_message(json!({ + "jsonrpc": "2.0", "id": 1, "method": "tools/call", + "params": {"name": name, "arguments": args, "_meta": metadata} + })) + }; + + let pending = AUTH_IDENTITY + .scope( + Some(identity.clone()), + call("demo.render", arguments.clone(), json!({})), + ) + .await + .unwrap(); + assert_eq!(pending["result"]["isError"], true); + assert_eq!(calls.load(Ordering::SeqCst), 0); + let approval = &pending["result"]["_meta"]["apcore"]["approval"]; + let audit_id = approval["approvalId"].as_str().expect("public approval ID"); + let token = approval["resumeToken"] + .as_str() + .expect("caller resume credential"); + assert_ne!(audit_id, token); + assert!(!pending["result"]["content"].to_string().contains(token)); + + let poll = AUTH_IDENTITY + .scope( + Some(identity.clone()), + call( + "__apcore_approval_check", + json!({"approval_id": audit_id}), + json!({}), + ), + ) + .await + .unwrap(); + assert!(poll["result"]["content"][0]["text"] + .as_str() + .unwrap() + .contains("pending")); + assert!(!poll.to_string().contains(token)); + + let other_identity = + apcore::Identity::new("viewer".into(), "user".into(), vec![], Default::default()); + let other_poll = AUTH_IDENTITY + .scope( + Some(other_identity), + call( + "__apcore_approval_check", + json!({"approval_id": audit_id}), + json!({}), + ), + ) + .await + .unwrap(); + assert_eq!(other_poll["result"]["isError"], false); + let unavailable: Value = + serde_json::from_str(other_poll["result"]["content"][0]["text"].as_str().unwrap()) + .unwrap(); + assert_eq!( + unavailable, + json!({"approval_id": audit_id, "status": "rejected"}) + ); + + let still_pending = AUTH_IDENTITY + .scope( + Some(identity.clone()), + call( + "demo.render", + arguments.clone(), + json!({"approvalId": token}), + ), + ) + .await + .unwrap(); + assert!( + still_pending["result"]["_meta"]["apcore"]["approval"]["resumeToken"].as_str() + == Some(token) + ); + + assert!(store.resolve(audit_id, true, None).await.unwrap()); + + let invalid = AUTH_IDENTITY + .scope( + Some(identity.clone()), + call( + "demo.render", + json!({"label": 5}), + json!({"approvalId": token}), + ), + ) + .await + .unwrap(); + assert_eq!(invalid["result"]["isError"], true); + assert_eq!(calls.load(Ordering::SeqCst), 0); + + let resumed = AUTH_IDENTITY + .scope( + Some(identity.clone()), + call( + "demo.render", + arguments.clone(), + json!({"approvalId": token}), + ), + ) + .await + .unwrap(); + assert_eq!(resumed["result"]["isError"], false); + assert_eq!(calls.load(Ordering::SeqCst), 1); + assert!(!resumed.to_string().contains(token)); + assert!(!resumed.to_string().contains("_approval_token")); + + let repeated = AUTH_IDENTITY + .scope( + Some(identity), + call("demo.render", arguments, json!({"approvalId": token})), + ) + .await + .unwrap(); + assert_eq!(repeated["result"]["isError"], true); + assert_eq!(calls.load(Ordering::SeqCst), 1); + assert!(!repeated.to_string().contains(token)); + } + struct CompletionFixture { entries: Arc, } diff --git a/mcp/rust/src/approval_store.rs b/mcp/rust/src/approval_store.rs index 3ae14864..6b78f734 100644 --- a/mcp/rust/src/approval_store.rs +++ b/mcp/rust/src/approval_store.rs @@ -3,14 +3,20 @@ //! Users implement `ApprovalStore` (Redis, DB, etc.). //! `InMemoryApprovalStore` is provided for testing and local development only. -use async_trait::async_trait; use std::collections::HashMap; +use std::io; use std::sync::Arc; -use std::time::{Duration, Instant}; +use std::time::Duration; + +use apcore::{ApprovalRequest, Identity}; +use async_trait::async_trait; +use sha2::{Digest, Sha256}; +use subtle::ConstantTimeEq; use tokio::sync::{Mutex, Notify}; +use tokio::time::Instant; /// Convenience alias for the store's fallible operations. -type StoreResult = Result>; +pub type StoreResult = Result>; /// Status of an approval record. #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] @@ -39,6 +45,51 @@ pub struct ApprovalRecord { pub reason: Option, } +/// The authenticated identity used to scope approval records. +#[derive(Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub struct ApprovalPrincipal { + pub identity_type: String, + pub id: String, +} + +impl From<&Identity> for ApprovalPrincipal { + fn from(identity: &Identity) -> Self { + Self { + identity_type: identity.identity_type().to_owned(), + id: identity.id().to_owned(), + } + } +} + +/// The stable parts of the invocation for which approval was requested. +#[derive(Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub struct ApprovalScope { + pub module_id: String, + pub caller_id: Option, + pub principal: Option, + pub arguments_sha256: [u8; 32], +} + +impl From<&ApprovalRequest> for ApprovalScope { + fn from(request: &ApprovalRequest) -> Self { + let mut arguments = request.arguments.clone(); + arguments.sort_all_objects(); + Self { + module_id: request.module_id.clone(), + caller_id: request.caller_id.clone(), + principal: request + .context + .as_ref() + .and_then(|context| context.identity.as_ref()) + .map(ApprovalPrincipal::from), + arguments_sha256: Sha256::digest(arguments.to_string().as_bytes()).into(), + } + } +} + +/// SHA-256 verifier for the confidential resume credential. +pub type ApprovalVerifier = [u8; 32]; + /// Pluggable storage for Phase B approval state. #[async_trait] pub trait ApprovalStore: Send + Sync + 'static { @@ -62,6 +113,43 @@ pub trait ApprovalStore: Send + Sync + 'static { reason: Option, ) -> StoreResult; + /// Persist a scoped record under its public audit ID without holding the credential. + /// Status-only stores reject this operation by default. + async fn save_scoped_pending( + &self, + _audit_id: &str, + _verifier: &ApprovalVerifier, + _scope: &ApprovalScope, + ) -> StoreResult<()> { + Err(io::Error::new( + io::ErrorKind::Unsupported, + "scoped approval storage unavailable", + ) + .into()) + } + + /// Read a scoped status only when the record belongs to this principal. + /// An absent principal is the anonymous scope. + async fn get_scoped_result( + &self, + _audit_id: &str, + _principal: Option<&ApprovalPrincipal>, + ) -> StoreResult> { + Ok(None) + } + + /// Match the verifier and invocation scope, check expiry, and consume an + /// approved credential within one transaction. Pending results remain + /// available. Unknown, expired, mismatched, or consumed records yield None. + async fn consume_scoped( + &self, + _audit_id: &str, + _verifier: &ApprovalVerifier, + _scope: &ApprovalScope, + ) -> StoreResult> { + Ok(None) + } + /// Start a background TTL sweep for this store, returning the spawned /// task handle (or `None` if the store needs no sweeping). /// @@ -84,15 +172,38 @@ struct InternalRecord { created_at: Instant, resolved_at: Option, notify: Arc, + scoped: Option, +} + +struct ScopedApproval { + verifier: Option, + scope: ApprovalScope, +} + +impl InternalRecord { + fn expired(&self, now: Instant, pending_ttl: Duration, resolved_ttl: Duration) -> bool { + now.duration_since(self.created_at) >= pending_ttl + || self + .resolved_at + .is_some_and(|time| now.duration_since(time) >= resolved_ttl) + } + + fn snapshot(&self) -> ApprovalRecord { + ApprovalRecord { + status: self.status.clone(), + module_id: self.module_id.clone(), + reason: self.reason.clone(), + } + } } /// In-process approval store for testing and local development. /// /// NOT suitable for production. /// -/// Memory management: resolved records expire after `resolved_ttl`, -/// pending records after `pending_ttl`. A background sweep task (started -/// via `start_sweep`) handles records whose timeouts were missed. +/// The pending TTL caps the lifetime of a record. The resolved TTL can shorten +/// the lifetime after a decision. Reads and writes enforce both deadlines. +/// The optional background sweep removes expired records that are never read. pub struct InMemoryApprovalStore { records: Arc>>, resolved_ttl: Duration, @@ -125,20 +236,12 @@ impl InMemoryApprovalStore { tokio::time::sleep(interval).await; let mut map = records.lock().await; let now = Instant::now(); - map.retain(|_, rec| { - if rec.status == ApprovalStatus::Pending { - now.duration_since(rec.created_at) <= pending_ttl - } else { - rec.resolved_at - .map(|t| now.duration_since(t) <= resolved_ttl) - .unwrap_or(true) - } - }); + map.retain(|_, record| !record.expired(now, pending_ttl, resolved_ttl)); } }) } - async fn evict_oldest_pending(map: &mut HashMap) { + fn evict_oldest_pending(map: &mut HashMap) { let oldest = map .iter() .filter(|(_, r)| r.status == ApprovalStatus::Pending) @@ -148,57 +251,80 @@ impl InMemoryApprovalStore { map.remove(&id); } } -} -impl Default for InMemoryApprovalStore { - fn default() -> Self { - Self::new() + fn live_record<'a>( + &self, + records: &'a mut HashMap, + audit_id: &str, + ) -> Option<&'a mut InternalRecord> { + let now = Instant::now(); + if records + .get(audit_id) + .is_some_and(|record| record.expired(now, self.pending_ttl, self.resolved_ttl)) + { + records.remove(audit_id); + } + records.get_mut(audit_id) } -} -#[async_trait] -impl ApprovalStore for InMemoryApprovalStore { - async fn save_pending( + async fn insert_pending( &self, - approval_id: &str, + audit_id: &str, module_id: &str, - _arguments: &serde_json::Value, + scoped: Option, ) -> StoreResult<()> { - let mut map = self.records.lock().await; - if map.len() >= self.max_records { - Self::evict_oldest_pending(&mut map).await; + let mut records = self.records.lock().await; + let now = Instant::now(); + records.retain(|_, record| !record.expired(now, self.pending_ttl, self.resolved_ttl)); + if records.contains_key(audit_id) { + return Err( + io::Error::new(io::ErrorKind::AlreadyExists, "approval record exists").into(), + ); } - map.insert( - approval_id.to_string(), + if records.len() >= self.max_records { + Self::evict_oldest_pending(&mut records); + if records.len() >= self.max_records { + return Err(io::Error::other("approval store is at capacity").into()); + } + } + records.insert( + audit_id.to_owned(), InternalRecord { status: ApprovalStatus::Pending, - module_id: module_id.to_string(), + module_id: module_id.to_owned(), reason: None, - created_at: Instant::now(), + created_at: now, resolved_at: None, notify: Arc::new(Notify::new()), + scoped, }, ); + Ok(()) + } +} - // Schedule TTL cleanup - let records = Arc::clone(&self.records); - let id = approval_id.to_string(); - let ttl = self.pending_ttl; - tokio::spawn(async move { - tokio::time::sleep(ttl).await; - records.lock().await.remove(&id); - }); +impl Default for InMemoryApprovalStore { + fn default() -> Self { + Self::new() + } +} - Ok(()) +#[async_trait] +impl ApprovalStore for InMemoryApprovalStore { + async fn save_pending( + &self, + approval_id: &str, + module_id: &str, + _arguments: &serde_json::Value, + ) -> StoreResult<()> { + self.insert_pending(approval_id, module_id, None).await } async fn get_result(&self, approval_id: &str) -> StoreResult> { - let map = self.records.lock().await; - Ok(map.get(approval_id).map(|r| ApprovalRecord { - status: r.status.clone(), - module_id: r.module_id.clone(), - reason: r.reason.clone(), - })) + let mut records = self.records.lock().await; + Ok(self + .live_record(&mut records, approval_id) + .map(|record| record.snapshot())) } async fn resolve( @@ -207,8 +333,8 @@ impl ApprovalStore for InMemoryApprovalStore { approved: bool, reason: Option, ) -> StoreResult { - let mut map = self.records.lock().await; - let Some(rec) = map.get_mut(approval_id) else { + let mut records = self.records.lock().await; + let Some(rec) = self.live_record(&mut records, approval_id) else { return Ok(false); }; if rec.status != ApprovalStatus::Pending { @@ -223,17 +349,58 @@ impl ApprovalStore for InMemoryApprovalStore { rec.resolved_at = Some(Instant::now()); rec.notify.notify_waiters(); - // Schedule resolved-TTL cleanup - let records = Arc::clone(&self.records); - let id = approval_id.to_string(); - let ttl = self.resolved_ttl; - drop(map); // release lock before spawning - tokio::spawn(async move { - tokio::time::sleep(ttl).await; - records.lock().await.remove(&id); + Ok(true) + } + + async fn save_scoped_pending( + &self, + audit_id: &str, + verifier: &ApprovalVerifier, + scope: &ApprovalScope, + ) -> StoreResult<()> { + self.insert_pending( + audit_id, + &scope.module_id, + Some(ScopedApproval { + verifier: Some(*verifier), + scope: scope.clone(), + }), + ) + .await + } + + async fn get_scoped_result( + &self, + audit_id: &str, + principal: Option<&ApprovalPrincipal>, + ) -> StoreResult> { + let mut records = self.records.lock().await; + let result = self.live_record(&mut records, audit_id).and_then(|record| { + let scope = &record.scoped.as_ref()?.scope; + (scope.principal.as_ref() == principal).then(|| record.snapshot()) }); + Ok(result) + } - Ok(true) + async fn consume_scoped( + &self, + audit_id: &str, + verifier: &ApprovalVerifier, + scope: &ApprovalScope, + ) -> StoreResult> { + let mut records = self.records.lock().await; + let result = self.live_record(&mut records, audit_id).and_then(|record| { + let scoped = record.scoped.as_mut()?; + let matches_verifier = bool::from(scoped.verifier.as_ref()?.ct_eq(verifier)); + if !matches_verifier || scoped.scope != *scope { + return None; + } + if record.status == ApprovalStatus::Approved { + scoped.verifier = None; + } + Some(record.snapshot()) + }); + Ok(result) } fn start_sweep(&self) -> Option> { @@ -248,14 +415,14 @@ impl InMemoryApprovalStore { approval_id: &str, timeout: Duration, ) -> Option { - let notify = { - let map = self.records.lock().await; - map.get(approval_id) + let notified = { + let mut records = self.records.lock().await; + self.live_record(&mut records, approval_id) .filter(|r| r.status == ApprovalStatus::Pending) - .map(|r| Arc::clone(&r.notify)) + .map(|r| Arc::clone(&r.notify).notified_owned()) }; - if let Some(n) = notify { - let _ = tokio::time::timeout(timeout, n.notified()).await; + if let Some(notification) = notified { + let _ = tokio::time::timeout(timeout, notification).await; } self.get_result(approval_id).await.ok().flatten() } diff --git a/mcp/rust/src/server/approval_bridge.rs b/mcp/rust/src/server/approval_bridge.rs index 2e5f5b6d..0452cb2b 100644 --- a/mcp/rust/src/server/approval_bridge.rs +++ b/mcp/rust/src/server/approval_bridge.rs @@ -3,20 +3,111 @@ //! Symmetric with AsyncTaskBridge. use apcore::approval::{ApprovalHandler, ApprovalResult}; +use apcore::{ErrorCode, Identity, ModuleError}; use serde_json::{json, Value}; +use std::cell::RefCell; +use std::future::Future; use std::sync::Arc; +use crate::adapters::approval::{is_public_approval_id, resume_audit_id, scoped_approval_status}; +use crate::approval_store::ApprovalStore; use crate::server::types::Tool; pub const APPROVAL_META_TOOL_NAMES: &[&str] = &["__apcore_approval_check"]; +struct PendingApproval { + audit_id: String, + credential: String, +} + +tokio::task_local! { + static PENDING_APPROVAL: RefCell>; +} + +/// Capture the pending decision separately from ordinary result content and errors. +pub(crate) async fn capture_pending_approval( + operation: impl Future, +) -> (T, Option) { + PENDING_APPROVAL + .scope(RefCell::new(None), async { + let result = operation.await; + let approval = PENDING_APPROVAL.with(|pending| pending.borrow_mut().take()); + let metadata = approval.map(|approval| { + json!({"approvalId": approval.audit_id, "resumeToken": approval.credential}) + }); + (result, metadata) + }) + .await +} + +pub(crate) fn has_tool_response_context() -> bool { + PENDING_APPROVAL.try_with(|_| ()).is_ok() +} + +pub(crate) fn safe_execution_message(error: &ModuleError) -> String { + if error.code != ErrorCode::ApprovalPending { + return error.to_string(); + } + if let Some((audit_id, credential)) = error.details.get("result").and_then(|result| { + let audit_id = result.get("audit_id")?.as_str()?; + let credential = result.get("approval_id")?.as_str()?; + (resume_audit_id(credential) == Some(audit_id)).then_some((audit_id, credential)) + }) { + let _ = PENDING_APPROVAL.try_with(|pending| { + pending.replace(Some(PendingApproval { + audit_id: audit_id.to_owned(), + credential: credential.to_owned(), + })); + }); + } + "APPROVAL_PENDING: Approval is pending".to_string() +} + pub struct ApprovalBridge { handler: Arc, + store: Option>, } impl ApprovalBridge { pub fn new(handler: Arc) -> Self { - Self { handler } + Self { + handler, + store: None, + } + } + + pub(crate) fn with_store(mut self, store: Arc) -> Self { + self.store = Some(store); + self + } + + pub(crate) fn supports_scoped_approval(&self) -> bool { + self.store.is_some() + } + + pub(crate) async fn check_wire_status( + &self, + arguments: &Value, + identity: Option<&Identity>, + ) -> (Value, bool) { + let Some(audit_id) = arguments + .get("approval_id") + .and_then(Value::as_str) + .filter(|id| is_public_approval_id(id)) + else { + return (json!({"error": "A public approval_id is required"}), true); + }; + let Some(store) = &self.store else { + return ( + json!({"error": "Scoped approval status is unavailable"}), + true, + ); + }; + let result = scoped_approval_status(store.as_ref(), audit_id, identity).await; + ( + json!({"approval_id": audit_id, "status": result.status}), + false, + ) } pub fn is_meta_tool(name: &str) -> bool { @@ -28,16 +119,16 @@ impl ApprovalBridge { output_schema: None, name: "__apcore_approval_check".to_string(), description: "Poll the status of a pending approval request. Returns \ - {approval_id, status, reason}. status is 'pending', 'approved', or 'rejected'. \ - When 'approved', retry the original tool call with _meta.approvalId set to \ - this approval_id." + {approval_id, status}. status is 'pending', 'approved', or 'rejected'. \ + When 'approved', retry the original tool call with its private resumeToken \ + in _meta.approvalId." .to_string(), input_schema: json!({ "type": "object", "properties": { "approval_id": { "type": "string", - "description": "The approval_id from the APPROVAL_PENDING response" + "description": "The public approvalId from _meta.apcore.approval" } }, "required": ["approval_id"], @@ -69,12 +160,15 @@ impl ApprovalBridge { ) } }; + if resume_audit_id(&approval_id).is_some() { + return (json!({"error": "Approval record not found"}), true); + } let result: ApprovalResult = match self.handler.check_approval(&approval_id).await { Ok(r) => r, - Err(e) => { + Err(_) => { return ( - json!({"error": format!("store error: {e}"), "is_error": true}), + json!({"error": "Approval status is unavailable", "is_error": true}), true, ) } diff --git a/mcp/rust/src/server/async_task_bridge.rs b/mcp/rust/src/server/async_task_bridge.rs index 36ff21f3..baa9df81 100644 --- a/mcp/rust/src/server/async_task_bridge.rs +++ b/mcp/rust/src/server/async_task_bridge.rs @@ -233,8 +233,21 @@ impl AsyncTaskBridge { send_notification: Option, session_key: Option<&str>, ) -> Result { - let ctx: Option> = identity.map(Context::new); - let task_id = self.manager.submit(module_id, inputs, ctx).await?; + if inputs.get("_approval_token").is_some() { + return Err(apcore::errors::ModuleError::new( + apcore::errors::ErrorCode::GeneralInvalidInput, + "Background tasks do not support approval resumption", + )); + } + let context: Context = identity.map_or_else(Context::anonymous, Context::new); + context.data.write().insert( + crate::adapters::approval::BACKGROUND_APPROVAL_CONTEXT_KEY.into(), + Value::Bool(true), + ); + let task_id = self + .manager + .submit(module_id, inputs, Some(context)) + .await?; // Store progress sink: token + sender pair, mirroring the Python // `_install_progress_sink` and TS inline-closure patterns. [A-D-220] @@ -955,6 +968,13 @@ mod tests { /// `handle_submit` path post-A-D-008 (which now rejects non-async /// module ids with ASYNC_MODULE_NOT_ASYNC). fn make_executor_with_async(module_id: &str) -> Arc { + make_executor_with_async_approval(module_id, false) + } + + fn make_executor_with_async_approval( + module_id: &str, + requires_approval: bool, + ) -> Arc { #[derive(Debug)] struct AsyncDummyModule; @@ -992,7 +1012,10 @@ mod tests { output_schema: json!({"type": "object"}), version: "1.0.0".to_string(), tags: vec![], - annotations: Some(ModuleAnnotations::default()), + annotations: Some(ModuleAnnotations { + requires_approval, + ..Default::default() + }), examples: vec![], metadata, display: None, @@ -1145,6 +1168,49 @@ mod tests { ); } + #[tokio::test] + async fn background_execution_rejects_only_calls_that_require_phase_b_approval() { + use crate::adapters::approval::StorageBackedApprovalHandler; + use crate::approval_store::InMemoryApprovalStore; + + for (requires_approval, expected) in + [(false, TaskStatus::Completed), (true, TaskStatus::Failed)] + { + let mut executor = + make_executor_with_async_approval("sample.render", requires_approval); + Arc::get_mut(&mut executor) + .unwrap() + .set_approval_handler(Box::new( + StorageBackedApprovalHandler::new(Arc::new(InMemoryApprovalStore::new())) + .with_notify(|_, _, _| panic!("background task must not create approval")), + )); + let bridge = AsyncTaskBridge::new(executor); + let task_id = bridge + .submit("sample.render", json!({}), None, None, None, None) + .await + .unwrap() + .task_id; + let terminal = tokio::time::timeout(std::time::Duration::from_secs(3), async { + loop { + let task = bridge.get_status(&task_id).unwrap().unwrap(); + if matches!(task.status, TaskStatus::Completed | TaskStatus::Failed) { + break task; + } + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); + assert_eq!(terminal.status, expected); + if requires_approval { + assert!(terminal + .error + .unwrap() + .contains("Background tasks do not support Phase B approval")); + } + } + } + /// Regression test for [A-D-008]. /// /// `__apcore_task_submit` against a module that is NOT async-hinted diff --git a/mcp/rust/src/server/factory.rs b/mcp/rust/src/server/factory.rs index fa862977..5074e65a 100644 --- a/mcp/rust/src/server/factory.rs +++ b/mcp/rust/src/server/factory.rs @@ -838,8 +838,11 @@ impl MCPServerFactory { .and_then(|id| router.session_registry().get(id)) .is_some_and(|session| session.supports_structured_results()); let extra_ref = extra.as_ref(); - let (content_items, is_error, trace_id) = - router.handle_call(&name, &arguments, extra_ref).await; + let ((content_items, is_error, trace_id), pending) = + crate::server::approval_bridge::capture_pending_approval( + router.handle_call(&name, &arguments, extra_ref), + ) + .await; // Extract any pipeline trace item for `_meta.trace`. let mut meta_trace: Option = None; @@ -861,6 +864,14 @@ impl MCPServerFactory { if let Some(t) = meta_trace { meta_obj.insert("trace".to_string(), t); } + if let Some(approval) = + pending.filter(|_| is_error && router.supports_scoped_approval()) + { + meta_obj.insert( + "apcore".to_string(), + serde_json::json!({"approval": approval}), + ); + } if let Some(tid) = trace_id.as_deref() { // Synthesize a W3C traceparent from the context trace_id. // Strip dashes to produce 32 lowercase hex chars; generate diff --git a/mcp/rust/src/server/router.rs b/mcp/rust/src/server/router.rs index b374ba63..5301c694 100644 --- a/mcp/rust/src/server/router.rs +++ b/mcp/rust/src/server/router.rs @@ -669,6 +669,12 @@ impl ExecutionRouter { self } + pub(crate) fn supports_scoped_approval(&self) -> bool { + self.approval_bridge + .as_ref() + .is_some_and(|bridge| bridge.supports_scoped_approval()) + } + /// Cooperatively cancel an in-flight tool call. [B-002] /// /// Looks up the [`CancelToken`] registered for `call_id` in @@ -780,10 +786,14 @@ impl ExecutionRouter { /// `"***REDACTED***"`. Returns the original inputs unchanged when no /// schema is available. fn redact_inputs(&self, tool_name: &str, inputs: &Value) -> Value { - match self.tool_schemas.get(tool_name) { + let mut redacted = match self.tool_schemas.get(tool_name) { Some(schema) => apcore::redact_sensitive(inputs, schema), None => inputs.clone(), + }; + if let Some(fields) = redacted.as_object_mut() { + fields.remove("_approval_token"); } + redacted } /// Redact sensitive fields from tool output before formatting. @@ -976,12 +986,32 @@ impl ExecutionRouter { .unwrap_or_else(|| uuid::Uuid::new_v4().to_string()); let (_cancel_guard, cancel_token) = self._cancel_guard(&call_id); - let redacted = self.redact_inputs(tool_name, arguments); - tracing::debug!( - tool = tool_name, - inputs = %redacted, - "Executing tool call" - ); + if !ApprovalBridge::is_meta_tool(tool_name) { + let redacted = self.redact_inputs(tool_name, arguments); + tracing::debug!( + tool = tool_name, + inputs = %redacted, + "Executing tool call" + ); + } + + let credential = match extra.and_then(|extra| extra.get("approvalId")) { + None => None, + Some(value) => match value.as_str() { + Some(token) + if crate::adapters::approval::resume_audit_id(token).is_some() + && self.supports_scoped_approval() + && !AsyncTaskBridge::is_reserved_id(tool_name) => + { + Some(token) + } + _ => { + return Self::stream_error( + "Approval resumption is unavailable for this call".into(), + ) + } + }, + }; // Extract streaming helpers and identity from extra let (progress_token, send_notification, session, identity) = self.extract_extra(extra); @@ -1040,7 +1070,13 @@ impl ExecutionRouter { if let Some(approval_bridge) = &self.approval_bridge { if ApprovalBridge::is_meta_tool(tool_name) { let (value, is_error) = - approval_bridge.handle_meta_tool(tool_name, arguments).await; + if crate::server::approval_bridge::has_tool_response_context() { + approval_bridge + .check_wire_status(arguments, apcore_ctx.identity.as_ref()) + .await + } else { + approval_bridge.handle_meta_tool(tool_name, arguments).await + }; let result = if is_error { Err(apcore::errors::ModuleError::new( apcore::errors::ErrorCode::GeneralInvalidInput, @@ -1097,6 +1133,11 @@ impl ExecutionRouter { // registration) — the pre-fix static `async_module_ids` set // was frozen at startup and stale on mutations. [A-D-031] if bridge.is_async_module_registered_self(tool_name) { + if credential.is_some() { + return Self::stream_error( + "Background tasks do not support approval resumption".into(), + ); + } let res = bridge .submit( tool_name, @@ -1163,9 +1204,23 @@ impl ExecutionRouter { } } + let resumed_arguments; + let execution_arguments = if let Some(credential) = credential { + let Some(mut fields) = arguments.as_object().cloned() else { + return Self::stream_error("Tool arguments must be a JSON object".into()); + }; + fields.insert( + "_approval_token".into(), + Value::String(credential.to_owned()), + ); + resumed_arguments = Value::Object(fields); + &resumed_arguments + } else { + arguments + }; self.dispatch_stream_or_call( tool_name, - arguments, + execution_arguments, &context_value, version_hint.as_deref(), &apcore_ctx, diff --git a/mcp/rust/src/server/server.rs b/mcp/rust/src/server/server.rs index b5c3298f..ed1d6967 100644 --- a/mcp/rust/src/server/server.rs +++ b/mcp/rust/src/server/server.rs @@ -687,6 +687,7 @@ impl ServerHandler { fn tool_call_extra(params: &Value) -> Option { let mut extra = params.get("_meta")?.clone(); if let Some(metadata) = extra.as_object_mut() { + metadata.remove("identity"); // A wire call contributes a hint only at params._meta.apcore.version. // The router also accepts separate SDK extra shapes from in-process callers. let version = metadata @@ -873,6 +874,18 @@ impl crate::server::transport::McpHandler for ServerHandler { .get("arguments") .cloned() .unwrap_or(Value::Object(Default::default())); + if arguments.get("_approval_token").is_some() + || (name == crate::server::async_task_bridge::META_TOOL_SUBMIT + && arguments + .get("arguments") + .and_then(|value| value.get("_approval_token")) + .is_some()) + { + return Self::wrap_response( + id, + Self::rpc_error(-32602, "Approval credentials belong in request metadata"), + ); + } let extra = Self::tool_call_extra(params); let mut call_result = (self.call_tool)(name, arguments, extra).await; if !self.supports_structured_results(&message) { diff --git a/mcp/rust/src/server/transport.rs b/mcp/rust/src/server/transport.rs index b3443a66..91fab9cb 100644 --- a/mcp/rust/src/server/transport.rs +++ b/mcp/rust/src/server/transport.rs @@ -3956,7 +3956,6 @@ mod tests { #[tokio::test] async fn sse_cancellation_releases_a_stream_blocked_on_progress() { use apcore::{ChunkStream, Context, Module, ModuleError, Registry, StreamingModule}; - use futures::StreamExt; use serde_json::json; use tokio::sync::{mpsc, Notify, Semaphore}; @@ -3988,12 +3987,11 @@ mod tests { impl StreamingModule for StreamingTool { fn stream_typed(&self, _: Value, _: &Context) -> ChunkStream { let lease = Arc::clone(&self.0); - Box::pin( - futures::stream::iter([Ok(json!({"value": 1}))]).map(move |chunk| { - let _lease = &lease; - chunk - }), - ) + let mut chunks = [Ok(json!({"value": 1}))].into_iter(); + Box::pin(futures::stream::poll_fn(move |_| { + let _lease = &lease; + std::task::Poll::Ready(chunks.next()) + })) } } From f099ed87e4002e1335ddd54e4e690bf26d0aedef Mon Sep 17 00:00:00 2001 From: tercel Date: Fri, 27 Nov 2026 14:08:26 +0800 Subject: [PATCH 27/36] fix(mcp): enforce scoped approval resumption in TypeScript Signed-off-by: tercel --- mcp/typescript/CHANGELOG.md | 1 + mcp/typescript/README.md | 12 + mcp/typescript/src/adapters/approval.ts | 201 +++++++++++--- mcp/typescript/src/adapters/errors.ts | 18 +- mcp/typescript/src/apcore-mcp.ts | 50 +--- mcp/typescript/src/approval-reply.ts | 74 +++++ mcp/typescript/src/approval-store.ts | 193 ++++++++----- mcp/typescript/src/index.ts | 27 +- mcp/typescript/src/server/approval-bridge.ts | 66 +++-- .../src/server/async-task-bridge.ts | 7 + mcp/typescript/src/server/factory.ts | 42 ++- mcp/typescript/src/server/router.ts | 37 ++- mcp/typescript/src/server/transport.ts | 4 +- .../tests/adapters/approval.test.ts | 78 ++---- mcp/typescript/tests/adapters/errors.test.ts | 76 +----- mcp/typescript/tests/approval-store.test.ts | 42 +++ mcp/typescript/tests/serve-features.test.ts | 19 +- .../tests/server/approval-bridge.test.ts | 169 ++++-------- .../tests/server/outputSafety.test.ts | 10 +- .../tests/server/scoped-approval.test.ts | 254 ++++++++++++++++++ 20 files changed, 908 insertions(+), 472 deletions(-) create mode 100644 mcp/typescript/src/approval-reply.ts create mode 100644 mcp/typescript/tests/server/scoped-approval.test.ts diff --git a/mcp/typescript/CHANGELOG.md b/mcp/typescript/CHANGELOG.md index b30588df..ec29c1ac 100644 --- a/mcp/typescript/CHANGELOG.md +++ b/mcp/typescript/CHANGELOG.md @@ -11,6 +11,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed - Route inbound cancellation to the active request, derive terminal stream results from Core when available, and fail startup when OpenAPI tools fail to register. +- Resume foreground Phase B calls through scoped Core approval. Keep the record ID public, return the private credential only in pending result metadata, and consume approved grants once. ## [0.23.8] - 2026-11-20 diff --git a/mcp/typescript/README.md b/mcp/typescript/README.md index 6d750c3b..1301b290 100644 --- a/mcp/typescript/README.md +++ b/mcp/typescript/README.md @@ -481,6 +481,18 @@ await serve(registry, { - **Custom prefix** — use `explorerPrefix: "/browse"` to mount at a different path. - **Authorization UI** — Swagger-UI-style Authorization input field. Paste a Bearer token to authenticate tool execution requests. Generated cURL commands automatically include the Authorization header. +### Stored approvals (Phase B) + +Pass a Registry and an `approvalStore` to `serve()` or `asyncServe()`. Phase B uses Core scoped approval support with stdio or Streamable HTTP. Use `InMemoryApprovalStore` for local runs. A persistent store must implement the scoped methods on `ScopedApprovalStore` and atomically verify and consume an approved credential. + +For a foreground `tools/call` awaiting an operator decision: + +1. Read `approvalId` and `resumeToken` from the result's `_meta.apcore.approval`. +2. Let the operator resolve `approvalId` in the store, or pass it as `approval_id` to `__apcore_approval_check` to poll. +3. Once approved, call the same tool with the same arguments and principal. Put `resumeToken` in the request's `_meta.approvalId` and keep it confidential. + +The operator callback receives the public ID. Authenticate callers with distinct principals on shared HTTP deployments. Unauthenticated calls share the anonymous principal and are suitable for a single trust domain. + ### JWT Authentication apcore-mcp supports JWT Bearer token authentication for HTTP-based transports. diff --git a/mcp/typescript/src/adapters/approval.ts b/mcp/typescript/src/adapters/approval.ts index 75d89d3a..38b46a79 100644 --- a/mcp/typescript/src/adapters/approval.ts +++ b/mcp/typescript/src/adapters/approval.ts @@ -5,31 +5,33 @@ * approval requests to the human user via the MCP client. */ -import { randomUUID } from "crypto"; +import { createHash, randomBytes, randomUUID } from "node:crypto"; +import { createApprovalResult } from "apcore-js"; +import { canIssueApprovalReply, recordPendingApproval } from "../approval-reply.js"; +import { supportsScopedApprovalStore } from "../approval-store.js"; import { MCP_ELICIT_KEY } from "../helpers.js"; -import type { ApprovalStore } from "../approval-store.js"; +import type { ApprovalPrincipal, ApprovalScope, ApprovalStore } from "../approval-store.js"; export interface ApprovalRequest { moduleId: string; description?: string | null; arguments: Record; - context?: { data?: Record } | null; + callerId?: string | null; + context?: { + data?: Record; + identity?: ApprovalPrincipal | null; + callerId?: string | null; + } | null; } export interface ApprovalResult { status: "approved" | "rejected" | "timeout" | "pending"; /** Human-readable explanation. Never used to carry the approval id. */ reason?: string | null; - /** - * Identifier of a pending approval, echoed back by the agent as - * `_meta.approvalId` and polled via `__apcore_approval_check`. - * - * [A-D-AP-1] Matches apcore-js `ApprovalResult.approvalId`, Python's - * `ApprovalResult(approval_id=...)` and Rust's `result.approval_id`. It was - * previously smuggled through `reason`, which left the field this repo's own - * ApprovalBridge reads (`{status; reason?; approvalId?}`) undefined. - */ + /** Confidential credential for the Core gate when status is pending. */ approvalId?: string; + /** Public record ID for telemetry and the operator. */ + auditId?: string; } /** @@ -120,16 +122,67 @@ export class ElicitationApprovalHandler { } } +const PUBLIC_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/; + +export function isPublicApprovalId(value: unknown): value is string { + return typeof value === "string" && PUBLIC_ID.test(value); +} + +function approvalRecordId(credential: string): string | null { + if (credential.length !== 101) return null; + const [id, secret, remainder] = credential.split("."); + return remainder === undefined && isPublicApprovalId(id) && /^[0-9a-f]{64}$/.test(secret ?? "") ? id : null; +} + +export function isApprovalResumeToken(value: unknown): value is string { + return typeof value === "string" && approvalRecordId(value) !== null; +} + +/** The scoped gate, credential isolation, and audit IDs shipped together. */ +export function supportsScopedCore(): boolean { + const auditId = "scoped-approval-capability"; + const result = createApprovalResult({ status: "pending", ...{ auditId } }); + return Reflect.get(result, "auditId") === auditId; +} + +function sha256(value: string): string { + return createHash("sha256").update(value).digest("hex"); +} + +function canonicalValue(value: unknown): unknown { + if (value === null || typeof value === "string" || typeof value === "boolean" || + (typeof value === "number" && Number.isFinite(value))) return value; + if (Array.isArray(value)) return Array.from(value, canonicalValue); + if (typeof value === "object" && + (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null)) { + const record = value as Record; + return Object.fromEntries(Object.keys(record).sort().map(key => [key, canonicalValue(record[key])])); + } + throw new Error("Approval arguments must be JSON"); +} + +function businessArguments(request: ApprovalRequest): Record { + const { _approval_token: _, ...args } = request.arguments; + return args; +} + +function invocationScope(request: ApprovalRequest, args: Record): ApprovalScope { + const identity = request.context?.identity; + return { + principal: identity ? { type: identity.type, id: identity.id } : null, + callerId: request.callerId ?? request.context?.callerId ?? null, + moduleId: request.moduleId, + argumentsDigest: sha256(JSON.stringify(canonicalValue(args))), + }; +} + +function rejected(reason: string): ApprovalResult { + return { status: "rejected", reason }; +} + /** - * Phase B approval handler backed by a pluggable ApprovalStore. - * - * requestApproval() saves a pending record and returns a pending ApprovalResult - * causing apcore to raise ApprovalPendingError → APPROVAL_PENDING in MCP envelope. - * checkApproval() reads the store; called by apcore when client retries with - * _meta.approvalId set. - * - * notifyCallback lets callers fan out to Slack/email/webhooks. - * Signature: (approvalId: string, moduleId: string, arguments: Record) => Promise + * Phase B handler with separate public record IDs and resume credentials. + * The operator callback receives only the public ID and business arguments. */ export class StorageBackedApprovalHandler { private readonly store: ApprovalStore; @@ -139,44 +192,106 @@ export class StorageBackedApprovalHandler { store: ApprovalStore, options: { notifyCallback?: (approvalId: string, moduleId: string, args: Record) => Promise; - } = {} + } = {}, ) { this.store = store; this.notifyCallback = options.notifyCallback; } - async requestApproval(request: ApprovalRequest): Promise { - const approvalId = randomUUID(); - const moduleId = request.moduleId ?? "unknown"; - const args = request.arguments ?? {}; + assertScopedSupport(): void { + if (!supportsScopedCore()) throw new Error("Phase B requires Core with scoped approval support"); + if (!supportsScopedApprovalStore(this.store)) throw new Error("Phase B requires a scoped approval store"); + } + + /** Bind the provider to the server's private foreground response path. */ + forMcpServer(): Pick { + const isForeground = (request: ApprovalRequest) => canIssueApprovalReply( + request.moduleId, request.callerId ?? request.context?.callerId ?? null, request.context?.data, true, + ); + return { + requestApproval: async request => isForeground(request) + ? this.requestApproval(request) + : rejected("Scoped approval requires a direct tool call"), + checkApproval: this.checkApproval.bind(this), + checkApprovalForPrincipal: this.checkApprovalForPrincipal.bind(this), + checkApprovalForCall: async (credential, request) => isForeground(request) + ? this.checkApprovalForCall(credential, request) + : rejected("Scoped approval requires a direct tool call"), + }; + } - await this.store.savePending(approvalId, moduleId, args); + async requestApproval(request: ApprovalRequest): Promise { + if (!supportsScopedCore() || !supportsScopedApprovalStore(this.store)) { + return rejected("Scoped approval unavailable"); + } + const args = businessArguments(request); + const contextData = request.context?.data; + let scope: ApprovalScope; + let auditId: string; + let credential: string; + try { + scope = invocationScope(request, args); + if (!canIssueApprovalReply(scope.moduleId, scope.callerId, contextData, false)) { + return rejected("Scoped approval requires a direct tool call"); + } + auditId = randomUUID(); + credential = `${auditId}.${randomBytes(32).toString("hex")}`; + await this.store.saveScopedPending(auditId, sha256(credential), scope); + } catch { + console.warn("[apcore-mcp] Approval could not be recorded"); + return rejected("Approval could not be recorded"); + } if (this.notifyCallback) { try { - await this.notifyCallback(approvalId, moduleId, args); - } catch (err) { - // log but don't fail the approval request - console.warn(`[apcore-mcp] notifyCallback raised for approval ${approvalId}:`, err); + await this.notifyCallback(auditId, scope.moduleId, args); + } catch { + console.warn("[apcore-mcp] Approval notification failed"); } } + recordPendingApproval(scope.moduleId, scope.callerId, contextData, { approvalId: auditId, resumeToken: credential }); + return { status: "pending", approvalId: credential, auditId }; + } - return { status: "pending", approvalId }; + async checkApproval(_approvalId: string): Promise { + return rejected("Scoped approval verification is required"); } - async checkApproval(approvalId: string): Promise { - const record = await this.store.getResult(approvalId); - if (!record) { - return { status: "rejected", reason: "approval_id not found" }; + async checkApprovalForPrincipal( + approvalId: string, principal: ApprovalPrincipal | null, + ): Promise { + if (!isPublicApprovalId(approvalId) || !supportsScopedCore() || !supportsScopedApprovalStore(this.store)) { + return rejected("Approval record not found"); } - if (record.status === "approved") { - return { status: "approved" }; + try { + const record = await this.store.getScopedResult(approvalId, principal); + return record ? { status: record.status, auditId: approvalId } : rejected("Approval record not found"); + } catch { + return rejected("Approval status unavailable"); } - if (record.status === "rejected") { - return { status: "rejected", reason: record.reason ?? undefined }; + } + + async checkApprovalForCall(credential: string, request: ApprovalRequest): Promise { + const auditId = approvalRecordId(credential); + if (!auditId || !supportsScopedCore() || !supportsScopedApprovalStore(this.store)) { + return rejected("Approval credential unavailable for this call"); + } + try { + const scope = invocationScope(request, businessArguments(request)); + const contextData = request.context?.data; + if (!canIssueApprovalReply(scope.moduleId, scope.callerId, contextData, false)) { + return rejected("Scoped approval requires a direct tool call"); + } + const record = await this.store.consumeScoped(auditId, sha256(credential), scope); + if (!record) return rejected("Approval credential unavailable for this call"); + if (record.status === "pending") { + recordPendingApproval(scope.moduleId, scope.callerId, contextData, { approvalId: auditId, resumeToken: credential }); + return { status: "pending", approvalId: credential, auditId }; + } + return { status: record.status, auditId }; + } catch { + return rejected("Approval verification failed"); } - // [A-D-AP-1] Echo the id on the pending path, matching Python - // (approval.py: ApprovalResult(status="pending", approval_id=approval_id)). - return { status: "pending", approvalId }; } } diff --git a/mcp/typescript/src/adapters/errors.ts b/mcp/typescript/src/adapters/errors.ts index d1da415d..35542fe7 100644 --- a/mcp/typescript/src/adapters/errors.ts +++ b/mcp/typescript/src/adapters/errors.ts @@ -152,25 +152,13 @@ export class ErrorMapper { return result; } - // Approval pending -> narrow details to approvalId only. - // [D10-003] Cross-language parity: upstream apcore SDKs emit - // snake_case (`approval_id`) exclusively, so the previous dual-key - // branch for camelCase `approvalId` was dormant and diverged from - // Python/Rust contracts (which accept snake_case only). Drop the - // camelCase source key; the output stays camelCase per MCP convention. if (code === ErrorCodes.APPROVAL_PENDING) { - const narrowed = - details && "approval_id" in details - ? { approvalId: details["approval_id"] } - : null; - const result: McpErrorResponse = { + return { isError: true, errorType: code, - message: error.message, - details: narrowed, + message: "Approval is pending", + details: null, }; - this._attachAiGuidance(error, result); - return result; } // Approval timeout -> mark as retryable diff --git a/mcp/typescript/src/apcore-mcp.ts b/mcp/typescript/src/apcore-mcp.ts index 198665c6..4cc29cff 100644 --- a/mcp/typescript/src/apcore-mcp.ts +++ b/mcp/typescript/src/apcore-mcp.ts @@ -37,7 +37,6 @@ import type { MetricsExporter } from "./server/transport.js"; import type { ObservabilityFlag } from "./server/observability.js"; import type { ApprovalStore } from "./approval-store.js"; import { withStdioOutput } from "./server/stdio-output.js"; -import { StorageBackedApprovalHandler } from "./adapters/approval.js"; import { serve, asyncServe, @@ -178,8 +177,6 @@ export class APCoreMCP { private _registry: Registry | undefined; private _executor: Executor | undefined; private readonly _extensionsDir: string | undefined; - private readonly _approvalStore: ApprovalStore | undefined; - private readonly _approvalHandler: StorageBackedApprovalHandler | undefined; /** * Create an APCoreMCP instance. @@ -213,18 +210,6 @@ export class APCoreMCP { this._options = { name, ...options }; - // Auto-create StorageBackedApprovalHandler when approvalStore is provided - // and no explicit approvalHandler was given. - if (options.approvalStore && !options.approvalHandler) { - this._approvalStore = options.approvalStore; - this._approvalHandler = new StorageBackedApprovalHandler(options.approvalStore, { - notifyCallback: options.approvalNotify, - }); - } else { - this._approvalStore = options.approvalStore; - this._approvalHandler = undefined; - } - if (typeof extensionsDirOrBackend === "string") { // Defer discovery to first use — will be resolved lazily this._backend = null; @@ -301,7 +286,9 @@ export class APCoreMCP { authenticator: this._options.authenticator, requireAuth: this._options.requireAuth, exemptPaths: this._options.exemptPaths, - approvalHandler: this._approvalHandler ?? this._options.approvalHandler, + approvalHandler: this._options.approvalHandler, + approvalStore: this._options.approvalStore, + approvalNotify: this._options.approvalNotify, outputFormatter: this._options.outputFormatter, middleware: this._options.middleware, acl: this._options.acl, @@ -348,17 +335,7 @@ export class APCoreMCP { async serve(options: APCoreMCPServeOptions = {}): Promise { const launch = async (): Promise => { const backend = await this._resolveBackend(); - const store = this._approvalStore; - if (store && typeof (store as unknown as { start?: () => void }).start === "function") { - (store as unknown as { start: () => void }).start(); - } - try { - await serve(backend, this._buildServeOptions(options)); - } finally { - if (store && typeof (store as unknown as { stop?: () => void }).stop === "function") { - (store as unknown as { stop: () => void }).stop(); - } - } + await serve(backend, this._buildServeOptions(options)); }; if (options.transport !== undefined && options.transport !== "stdio") { await launch(); @@ -403,27 +380,16 @@ export class APCoreMCP { authenticator: this._options.authenticator, requireAuth: this._options.requireAuth, exemptPaths: this._options.exemptPaths, - approvalHandler: this._approvalHandler ?? this._options.approvalHandler, + approvalHandler: this._options.approvalHandler, + approvalStore: this._options.approvalStore, + approvalNotify: this._options.approvalNotify, endpoint: options.endpoint, outputFormatter: this._options.outputFormatter, middleware: this._options.middleware, acl: this._options.acl, }; - const store = this._approvalStore; - if (store && typeof (store as unknown as { start?: () => void }).start === "function") { - (store as unknown as { start: () => void }).start(); - } - - const app = await asyncServe(backend, asyncOpts); - const originalClose = app.close; - app.close = async () => { - await originalClose(); - if (store && typeof (store as unknown as { stop?: () => void }).stop === "function") { - (store as unknown as { stop: () => void }).stop(); - } - }; - return app; + return asyncServe(backend, asyncOpts); } /** diff --git a/mcp/typescript/src/approval-reply.ts b/mcp/typescript/src/approval-reply.ts new file mode 100644 index 00000000..fe9fbe7e --- /dev/null +++ b/mcp/typescript/src/approval-reply.ts @@ -0,0 +1,74 @@ +import { AsyncLocalStorage } from "node:async_hooks"; + +export interface PendingApprovalReply { + readonly approvalId: string; + readonly resumeToken: string; +} + +export interface ApprovalReplyCapture { + readonly moduleId: string; + candidate?: PendingApprovalReply; + confirmed: boolean; +} + +interface Invocation { + readonly reply: ApprovalReplyCapture; + readonly contextData: object; + active: boolean; +} + +const invocations = new AsyncLocalStorage(); +const backgroundContexts = new WeakSet(); +const scopedServers = new WeakSet(); + +export function enableApprovalReplies(server: object): void { + scopedServers.add(server); +} + +export function hasApprovalReplies(server: object): boolean { + return scopedServers.has(server); +} + +export function markBackgroundApprovalContext(data: object): void { + backgroundContexts.add(data); +} + +function matchingInvocation( + moduleId: string, callerId: string | null, contextData: object | undefined, +): Invocation | undefined { + const invocation = invocations.getStore(); + return invocation?.active && invocation.reply.moduleId === moduleId + && callerId === null && invocation.contextData === contextData ? invocation : undefined; +} + +export function canIssueApprovalReply( + moduleId: string, callerId: string | null, contextData: object | undefined, requireForeground: boolean, +): boolean { + if (contextData && backgroundContexts.has(contextData)) return false; + if (!requireForeground && invocations.getStore() === undefined) return true; + return matchingInvocation(moduleId, callerId, contextData) !== undefined; +} + +/** Enter the private handoff scope only for an active foreground Core invocation. */ +export async function runApprovalInvocation( + reply: ApprovalReplyCapture | undefined, contextData: object, invoke: () => Promise, +): Promise { + if (!reply) return invoke(); + const invocation: Invocation = { reply, contextData, active: true }; + try { + return await invocations.run(invocation, invoke); + } finally { + invocation.active = false; + } +} + +export function recordPendingApproval( + moduleId: string, callerId: string | null, contextData: object | undefined, approval: PendingApprovalReply, +): void { + const invocation = matchingInvocation(moduleId, callerId, contextData); + if (invocation) invocation.reply.candidate = approval; +} + +export function confirmPendingApproval(reply: ApprovalReplyCapture | undefined): void { + if (reply?.candidate) reply.confirmed = true; +} diff --git a/mcp/typescript/src/approval-store.ts b/mcp/typescript/src/approval-store.ts index 09cfb178..6e5c0bc0 100644 --- a/mcp/typescript/src/approval-store.ts +++ b/mcp/typescript/src/approval-store.ts @@ -6,6 +6,8 @@ * it does NOT survive process restarts and is not suitable for production. */ +import { timingSafeEqual } from "node:crypto"; + export interface ApprovalRecord { status: "pending" | "approved" | "rejected"; moduleId: string; @@ -14,11 +16,29 @@ export interface ApprovalRecord { resolvedAt: number | null; } +export interface ApprovalPrincipal { + readonly type: string; + readonly id: string; +} + +export interface ApprovalScope { + readonly principal: ApprovalPrincipal | null; + readonly callerId: string | null; + readonly moduleId: string; + readonly argumentsDigest: string; +} + /** Pluggable storage for Phase B approval state. */ export interface ApprovalStore { savePending(approvalId: string, moduleId: string, arguments_: Record): Promise; getResult(approvalId: string): Promise; resolve(approvalId: string, options: { approved: boolean; reason?: string }): Promise; + /** Persist a public ID and SHA-256 credential verifier with the invocation scope. */ + saveScopedPending?(approvalId: string, verifier: string, scope: ApprovalScope): Promise; + /** Read only a live record owned by this trusted principal. */ + getScopedResult?(approvalId: string, principal: ApprovalPrincipal | null): Promise; + /** Verify an unexpired record and consume an approved verifier atomically before returning it. */ + consumeScoped?(approvalId: string, verifier: string, scope: ApprovalScope): Promise; /** * Optional lifecycle hook. When present, serve()/asyncServe()/APCoreMCP call * it before the transport binds so the store can spin up background work @@ -33,30 +53,46 @@ export interface ApprovalStore { stop?(): void; } +type ScopedMethods = "saveScopedPending" | "getScopedResult" | "consumeScoped"; +export type ScopedApprovalStore = ApprovalStore & Required>; + +export function supportsScopedApprovalStore(store: ApprovalStore): store is ScopedApprovalStore { + return typeof store.saveScopedPending === "function" && + typeof store.getScopedResult === "function" && typeof store.consumeScoped === "function"; +} + interface InternalRecord extends ApprovalRecord { - arguments_?: Record; + expiresAt: number; + timer: ReturnType; + scope?: ApprovalScope; + verifier?: Buffer; +} + +function samePrincipal(left: ApprovalPrincipal | null, right: ApprovalPrincipal | null): boolean { + return left === null || right === null ? left === right : left.type === right.type && left.id === right.id; +} + +function sameScope(left: ApprovalScope, right: ApprovalScope): boolean { + return left.callerId === right.callerId && left.moduleId === right.moduleId && + left.argumentsDigest === right.argumentsDigest && samePrincipal(left.principal, right.principal); +} + +function publicRecord({ status, moduleId, reason, createdAt, resolvedAt }: InternalRecord): ApprovalRecord { + return { status, moduleId, reason, createdAt, resolvedAt }; } /** - * In-process approval store for testing and local development. - * - * NOT suitable for production: state is lost on restart, not shared - * across processes. - * - * Memory management: - * - Resolved records deleted after `resolvedTtlMs` (default 120 000 ms) - * - Pending records abandoned without resolution deleted after `pendingTtlMs` (default 3 600 000 ms) - * - Background sweep every `sweepIntervalMs` (default 300 000 ms) - * - Hard cap `maxRecords` with oldest-pending eviction + * In-process store for testing and local development. State is not shared + * between processes and lasts only until restart. */ -export class InMemoryApprovalStore implements ApprovalStore { +export class InMemoryApprovalStore implements ScopedApprovalStore { private readonly resolvedTtlMs: number; private readonly pendingTtlMs: number; private readonly sweepIntervalMs: number; private readonly maxRecords: number; private records = new Map(); - private resolvers = new Map void>(); + private resolvers = new Map void>(); private sweepTimer: ReturnType | null = null; constructor(options: { @@ -86,66 +122,86 @@ export class InMemoryApprovalStore implements ApprovalStore { } } - async savePending(approvalId: string, moduleId: string, arguments_: Record): Promise { + async savePending(approvalId: string, moduleId: string, _arguments: Record): Promise { + this.insertPending(approvalId, moduleId); + } + + async saveScopedPending(approvalId: string, verifier: string, scope: ApprovalScope): Promise { + if (!/^[0-9a-f]{64}$/.test(verifier)) throw new Error("Invalid approval verifier"); + const storedScope = { ...scope, principal: scope.principal === null ? null : { ...scope.principal } }; + this.insertPending(approvalId, scope.moduleId, storedScope, Buffer.from(verifier, "hex")); + } + + private insertPending(approvalId: string, moduleId: string, scope?: ApprovalScope, verifier?: Buffer): void { + const existing = this.liveRecord(approvalId); + if (existing && (existing.scope || scope)) throw new Error("Approval record already exists"); + if (existing) this.deleteRecord(approvalId); if (this.records.size >= this.maxRecords) { - this.evictOldestPending(); + this.sweep(); + if (this.records.size >= this.maxRecords) this.evictOldestPending(); + if (this.records.size >= this.maxRecords) throw new Error("Approval store capacity reached"); } - const now = Date.now(); + const createdAt = Date.now(); + const expiresAt = createdAt + this.pendingTtlMs; this.records.set(approvalId, { status: "pending", moduleId, - arguments_, reason: null, - createdAt: now, + createdAt, resolvedAt: null, + expiresAt, + timer: this.scheduleExpiry(approvalId, expiresAt), + scope, + verifier, }); - setTimeout(() => this.deleteRecord(approvalId), this.pendingTtlMs); } async getResult(approvalId: string): Promise { - const rec = this.records.get(approvalId); - if (!rec) return null; - // Return public fields only (omit arguments_) - return { - status: rec.status, - moduleId: rec.moduleId, - reason: rec.reason, - createdAt: rec.createdAt, - resolvedAt: rec.resolvedAt, - }; + const record = this.liveRecord(approvalId); + return record ? publicRecord(record) : null; } - async resolve(approvalId: string, options: { approved: boolean; reason?: string }): Promise { - const rec = this.records.get(approvalId); - if (!rec || rec.status !== "pending") return false; - - rec.status = options.approved ? "approved" : "rejected"; - rec.reason = options.reason ?? null; - rec.resolvedAt = Date.now(); - delete rec.arguments_; // reclaim memory - - const resolver = this.resolvers.get(approvalId); - if (resolver) { - resolver(rec); - this.resolvers.delete(approvalId); - } + async getScopedResult(approvalId: string, principal: ApprovalPrincipal | null): Promise { + const record = this.liveRecord(approvalId); + return record?.scope && samePrincipal(record.scope.principal, principal) ? publicRecord(record) : null; + } + + async consumeScoped(approvalId: string, verifier: string, scope: ApprovalScope): Promise { + const record = this.liveRecord(approvalId); + if (!record?.scope || !record.verifier || !/^[0-9a-f]{64}$/.test(verifier) || + !timingSafeEqual(record.verifier, Buffer.from(verifier, "hex")) || !sameScope(record.scope, scope)) return null; + // No await between checking the scope and removing the verifier. + if (record.status === "approved") delete record.verifier; + return publicRecord(record); + } - setTimeout(() => this.deleteRecord(approvalId), this.resolvedTtlMs); + async resolve(approvalId: string, options: { approved: boolean; reason?: string }): Promise { + const record = this.liveRecord(approvalId); + if (!record || record.status !== "pending") return false; + + record.status = options.approved ? "approved" : "rejected"; + record.reason = options.reason ?? null; + record.resolvedAt = Date.now(); + record.expiresAt = Math.min(record.expiresAt, record.resolvedAt + this.resolvedTtlMs); + clearTimeout(record.timer); + record.timer = this.scheduleExpiry(approvalId, record.expiresAt); + this.resolvers.get(approvalId)?.(publicRecord(record)); + this.resolvers.delete(approvalId); return true; } /** Wait until resolved or timeout. Helper for tests. */ async waitForResolution(approvalId: string, timeoutMs = 300_000): Promise { - const rec = this.records.get(approvalId); - if (!rec) return null; - if (rec.status !== "pending") return rec; + const record = this.liveRecord(approvalId); + if (!record) return null; + if (record.status !== "pending") return publicRecord(record); return new Promise((resolve) => { const timer = setTimeout(() => { this.resolvers.delete(approvalId); - resolve(this.records.get(approvalId) ?? null); + const current = this.liveRecord(approvalId); + resolve(current ? publicRecord(current) : null); }, timeoutMs); - this.resolvers.set(approvalId, (resolved) => { clearTimeout(timer); resolve(resolved); @@ -153,33 +209,40 @@ export class InMemoryApprovalStore implements ApprovalStore { }); } + private liveRecord(approvalId: string, now = Date.now()): InternalRecord | undefined { + const record = this.records.get(approvalId); + if (record && now >= record.expiresAt) { + this.deleteRecord(approvalId); + return undefined; + } + return record; + } + + private scheduleExpiry(approvalId: string, expiresAt: number): ReturnType { + const timer = setTimeout(() => this.liveRecord(approvalId), Math.max(0, expiresAt - Date.now())); + timer.unref?.(); + return timer; + } + private deleteRecord(approvalId: string): void { + const record = this.records.get(approvalId); + if (record) clearTimeout(record.timer); this.records.delete(approvalId); + this.resolvers.get(approvalId)?.(null); this.resolvers.delete(approvalId); } private evictOldestPending(): void { - let oldestId: string | null = null; - let oldestTime = Infinity; - for (const [id, rec] of this.records) { - if (rec.status === "pending" && rec.createdAt < oldestTime) { - oldestTime = rec.createdAt; - oldestId = id; + for (const [id, record] of this.records) { + if (record.status === "pending") { + this.deleteRecord(id); + return; } } - if (oldestId !== null) { - this.deleteRecord(oldestId); - } } private sweep(): void { const now = Date.now(); - for (const [id, rec] of this.records) { - if (rec.status === "pending" && now - rec.createdAt > this.pendingTtlMs) { - this.deleteRecord(id); - } else if (rec.status !== "pending" && rec.resolvedAt !== null && now - rec.resolvedAt > this.resolvedTtlMs) { - this.deleteRecord(id); - } - } + for (const id of this.records.keys()) this.liveRecord(id, now); } } diff --git a/mcp/typescript/src/index.ts b/mcp/typescript/src/index.ts index 41f778a0..2acc3c0c 100644 --- a/mcp/typescript/src/index.ts +++ b/mcp/typescript/src/index.ts @@ -32,6 +32,7 @@ import type { Authenticator } from "./auth/types.js"; import { buildExplorerAuthHook } from "./auth/hooks.js"; import type { ApprovalStore } from "./approval-store.js"; import { StorageBackedApprovalHandler } from "./adapters/approval.js"; +import { ApprovalBridge } from "./server/approval-bridge.js"; import pkg from "../package.json" with { type: "json" }; export const VERSION: string = pkg.version; @@ -101,7 +102,7 @@ export { ModuleIDNormalizer } from "./adapters/id-normalizer.js"; export { ElicitationApprovalHandler, StorageBackedApprovalHandler } from "./adapters/approval.js"; export type { ApprovalRequest, ApprovalResult } from "./adapters/approval.js"; export { InMemoryApprovalStore } from "./approval-store.js"; -export type { ApprovalStore, ApprovalRecord } from "./approval-store.js"; +export type { ApprovalStore, ApprovalRecord, ApprovalPrincipal, ApprovalScope, ScopedApprovalStore } from "./approval-store.js"; export { ApprovalBridge, APPROVAL_META_TOOL_NAMES } from "./server/approval-bridge.js"; export type { ApprovalMetaToolName } from "./server/approval-bridge.js"; export { McpErrorFormatter, registerMcpFormatter } from "./adapters/mcp-error-formatter.js"; @@ -125,6 +126,19 @@ export function resolveRegistry(registryOrExecutor: RegistryOrExecutor): Registr return registryOrExecutor as Registry; } +function configuredScopedApproval( + approvalHandler: unknown, backend: RegistryOrExecutor, transport?: string, +): { handler: ReturnType; bridge: ApprovalBridge } | undefined { + if (!(approvalHandler instanceof StorageBackedApprovalHandler)) return undefined; + approvalHandler.assertScopedSupport(); + if (transport === "sse") throw new Error("Phase B is unavailable on the legacy SSE transport"); + if ("call" in backend || "callAsync" in backend) { + throw new Error("Phase B requires a Registry so the server can wire the scoped Core approval handler"); + } + const handler = approvalHandler.forMcpServer(); + return { handler, bridge: new ApprovalBridge(handler) }; +} + /** * Get or create an Executor from either a Registry or Executor instance. * @@ -856,9 +870,10 @@ async function serveInternal( if (minLevel > 3) console.error = () => { }; } + const scopedApproval = configuredScopedApproval(effectiveApprovalHandler, resolvedBackend, transport); const registry = resolveRegistry(resolvedBackend); const executor = await resolveExecutor(resolvedBackend, { - approvalHandler: effectiveApprovalHandler, + approvalHandler: scopedApproval?.handler ?? effectiveApprovalHandler, strategy: resolvedStrategy, middleware: combinedMiddleware, acl: effectiveAcl, @@ -944,7 +959,7 @@ async function serveInternal( trace, asyncTaskBridge: asyncBridge ?? undefined, }); - factory.registerHandlers(server, tools, router); + factory.registerHandlers(server, tools, router, scopedApproval ? { approvalBridge: scopedApproval.bridge } : undefined); factory.registerResourceHandlers(server, registry, router); // Start dynamic tool registration listener if enabled @@ -1190,6 +1205,8 @@ export async function asyncServe( // Config-Bus-resolved values. validateServeOptions({ name, tags, prefix, explorer, explorerPrefix }); + const scopedApproval = configuredScopedApproval(effectiveApprovalHandler, resolvedBackend); + // Apply log-level suppression (post-resolution so Config Bus values apply). if (logLevel) { const levels = ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]; @@ -1202,7 +1219,7 @@ export async function asyncServe( const registry = resolveRegistry(resolvedBackend); const executor = await resolveExecutor(resolvedBackend, { - approvalHandler: effectiveApprovalHandler, + approvalHandler: scopedApproval?.handler ?? effectiveApprovalHandler, strategy: resolvedStrategy, middleware: combinedMiddleware, acl: effectiveAcl, @@ -1283,7 +1300,7 @@ export async function asyncServe( trace, asyncTaskBridge: asyncBridge ?? undefined, }); - factory.registerHandlers(server, tools, router); + factory.registerHandlers(server, tools, router, scopedApproval ? { approvalBridge: scopedApproval.bridge } : undefined); factory.registerResourceHandlers(server, registry, router); // Start dynamic tool registration listener if enabled. The embedded handler diff --git a/mcp/typescript/src/server/approval-bridge.ts b/mcp/typescript/src/server/approval-bridge.ts index 605a951d..19ebc5af 100644 --- a/mcp/typescript/src/server/approval-bridge.ts +++ b/mcp/typescript/src/server/approval-bridge.ts @@ -5,37 +5,44 @@ * alongside asyncBridge. */ import type { Tool } from "@modelcontextprotocol/sdk/types.js"; +import { isPublicApprovalId, supportsScopedCore } from "../adapters/approval.js"; +import type { ApprovalPrincipal } from "../approval-store.js"; export const APPROVAL_META_TOOL_NAMES = ["__apcore_approval_check"] as const; export type ApprovalMetaToolName = (typeof APPROVAL_META_TOOL_NAMES)[number]; export class ApprovalBridge { - // handler is StorageBackedApprovalHandler but typed loosely for cross-SDK compat constructor(private readonly handler: { - checkApproval(approvalId: string): Promise<{ status: string; reason?: string; approvalId?: string }>; + checkApproval?(approvalId: string): Promise<{ status: string }>; + checkApprovalForPrincipal?( + approvalId: string, principal: ApprovalPrincipal | null, + ): Promise<{ status: string }>; }) {} + get available(): boolean { + return supportsScopedCore() && typeof this.handler.checkApprovalForPrincipal === "function"; + } + static isMetaTool(name: string): name is ApprovalMetaToolName { return (APPROVAL_META_TOOL_NAMES as readonly string[]).includes(name); } buildMetaTools(): Tool[] { + if (!this.available) return []; return [ { name: "__apcore_approval_check", description: "Poll the status of a pending approval request. " + - "Returns {approval_id, status, reason}. " + - "status is 'pending', 'approved', or 'rejected'. " + - "When 'approved', retry the original tool call with " + - "_meta.approvalId set to this approval_id.", + "Use the public approvalId from the pending result metadata. " + + "When approved, retry the original tool with its resumeToken in request _meta.approvalId.", inputSchema: { type: "object" as const, properties: { approval_id: { type: "string", - description: "The approval_id from the APPROVAL_PENDING response", + description: "The public approvalId from _meta.apcore.approval", }, }, required: ["approval_id"], @@ -47,10 +54,11 @@ export class ApprovalBridge { async handleMetaTool( name: string, - arguments_: Record + arguments_: Record, + principal: ApprovalPrincipal | null = null, ): Promise<[Array<{ type: string; text: string }>, boolean, string | null]> { if (name === "__apcore_approval_check") { - return this.handleCheck(arguments_); + return this.handleCheck(arguments_, principal); } return [ [{ type: "text", text: `Unknown approval meta-tool: ${name}` }], @@ -60,36 +68,22 @@ export class ApprovalBridge { } private async handleCheck( - args: Record - ): Promise<[Array<{ type: string; text: string }>, boolean, string | null]> { + args: Record, + principal: ApprovalPrincipal | null, + ): Promise<[Array<{ type: "text"; text: string }>, boolean, string | null]> { const approvalId = args["approval_id"]; - if (typeof approvalId !== "string" || !approvalId) { - return [ - [{ type: "text", text: "approval_id is required" }], - true, - null, - ]; + if (!isPublicApprovalId(approvalId)) { + return [[{ type: "text", text: "A public approval_id is required" }], true, null]; + } + if (!this.available || !this.handler.checkApprovalForPrincipal) { + return [[{ type: "text", text: "Scoped approval status unavailable" }], true, null]; } try { - const result = await this.handler.checkApproval(approvalId); - const payload: Record = { - approval_id: approvalId, - status: result.status, - }; - if (result.reason !== undefined) { - payload["reason"] = result.reason; - } - return [ - [{ type: "text", text: JSON.stringify(payload) }], - false, - null, - ]; - } catch (err) { - return [ - [{ type: "text", text: `Approval check failed: ${String(err)}` }], - true, - null, - ]; + const result = await this.handler.checkApprovalForPrincipal(approvalId, principal); + const status = result.status === "approved" || result.status === "pending" ? result.status : "rejected"; + return [[{ type: "text", text: JSON.stringify({ approval_id: approvalId, status }) }], false, null]; + } catch { + return [[{ type: "text", text: "Approval status unavailable" }], true, null]; } } } diff --git a/mcp/typescript/src/server/async-task-bridge.ts b/mcp/typescript/src/server/async-task-bridge.ts index 53901be0..28aa0660 100644 --- a/mcp/typescript/src/server/async-task-bridge.ts +++ b/mcp/typescript/src/server/async-task-bridge.ts @@ -12,6 +12,7 @@ * Full spec: apcore-mcp/docs/features/async-task-bridge.md (F-043). */ +import { markBackgroundApprovalContext } from "../approval-reply.js"; import type { ModuleDescriptor } from "../types.js"; import { ErrorCodes } from "../types.js"; @@ -315,6 +316,12 @@ export class AsyncTaskBridge { } } + // Core preserves Context.data when it clones a context for the background job. + // The marker carries no approval state or credentials. + if (context && typeof context === "object" && "data" in context + && context.data && typeof context.data === "object") { + markBackgroundApprovalContext(context.data); + } const taskId = await this._manager.submit(moduleId, inputs, { context: context ?? null }); if (options?.progressToken !== undefined) { this._progressTokens.set(taskId, options.progressToken); diff --git a/mcp/typescript/src/server/factory.ts b/mcp/typescript/src/server/factory.ts index 903814a8..a86f35cd 100644 --- a/mcp/typescript/src/server/factory.ts +++ b/mcp/typescript/src/server/factory.ts @@ -34,6 +34,8 @@ import type { HandleCallExtra } from "./router.js"; import { buildTraceparent } from "./trace-context.js"; import { APCORE_META_TOOL_PREFIX, AsyncTaskBridge } from "./async-task-bridge.js"; import { ApprovalBridge } from "./approval-bridge.js"; +import { isApprovalResumeToken } from "../adapters/approval.js"; +import { enableApprovalReplies, type ApprovalReplyCapture, type PendingApprovalReply } from "../approval-reply.js"; import { isMarkdownAvailable, primeMarkdownToolkit, @@ -626,7 +628,8 @@ export class MCPServerFactory { observeStdioWork(server); // [D11-014] If asyncTaskBridge is provided, extend tools list with meta-tools. const bridge = options?.asyncTaskBridge; - const approvalBridge = options?.approvalBridge; + const approvalBridge = options?.approvalBridge?.available ? options.approvalBridge : undefined; + if (approvalBridge) enableApprovalReplies(server); let allTools: Tool[] = bridge ? this.attachAsyncMetaTools(tools, bridge) : tools; // Append approval bridge meta-tools if present. @@ -674,6 +677,16 @@ export class MCPServerFactory { }; const reqMeta = (request.params as { _meta?: Record })._meta; + if (reqMeta && Object.hasOwn(reqMeta, "approvalId")) { + const token = reqMeta["approvalId"]; + if (!approvalBridge || ApprovalBridge.isMetaTool(name) || !isApprovalResumeToken(token)) { + throw new McpError(ErrorCode.InvalidParams, "Invalid or unsupported approval resume metadata"); + } + handleCallExtra.approvalResumeToken = token; + } + if (Object.hasOwn(toolArgs, "_approval_token")) { + throw new McpError(ErrorCode.InvalidParams, "Use request metadata for approval resumption"); + } const apcoreMeta = reqMeta?.["apcore"] as { version?: string } | undefined; if (apcoreMeta?.version) { handleCallExtra._meta = { @@ -712,23 +725,34 @@ export class MCPServerFactory { // Dispatch to approval bridge meta-tool if applicable (AFTER async bridge, // BEFORE the async-hint route in router.handleCall). if (approvalBridge && ApprovalBridge.isMetaTool(name)) { - const [apContent, apIsError] = await approvalBridge.handleMetaTool(name, toolArgs); + const [apContent, apIsError] = await approvalBridge.handleMetaTool(name, toolArgs, handleCallExtra.identity ?? null); const apTextContents = apContent.map(c => ({ type: "text" as const, text: c.text })); return { content: apTextContents, ...(apIsError ? { isError: true } : {}) }; } - const [content, isError, traceId] = await router.handleCall( - name, - toolArgs, - handleCallExtra, - ); - + const reply: ApprovalReplyCapture | undefined = approvalBridge + ? { moduleId: name, confirmed: false } + : undefined; + handleCallExtra.approvalReply = reply; + let approval: PendingApprovalReply | undefined; + let callResult: Awaited>; + try { + callResult = await router.handleCall(name, toolArgs, handleCallExtra); + if (reply?.confirmed) approval = reply.candidate; + } finally { + if (reply) delete reply.candidate; + } + const [content, isError, traceId] = callResult; const textContents = content.map(c => ({ type: "text" as const, text: c.text })); // Tool execution failures are successful JSON-RPC responses carrying // isError. Throwing here turns them into protocol-level internal errors. if (isError) { - return { content: textContents, isError: true }; + return { + content: textContents, + isError: true, + ...(approval ? { _meta: { apcore: { approval } } } : {}), + }; } const result: CallToolResult & { _meta?: Record } = { diff --git a/mcp/typescript/src/server/router.ts b/mcp/typescript/src/server/router.ts index 166098ed..fdea8e35 100644 --- a/mcp/typescript/src/server/router.ts +++ b/mcp/typescript/src/server/router.ts @@ -10,7 +10,9 @@ import * as crypto from "node:crypto"; import { registerStdioExecution } from "./stdio-output.js"; -import { CancelToken, isStreamingModule } from "apcore-js"; +import { CancelToken, InvalidInputError, isStreamingModule } from "apcore-js"; +import { isApprovalResumeToken, supportsScopedCore } from "../adapters/approval.js"; +import { confirmPendingApproval, runApprovalInvocation, type ApprovalReplyCapture } from "../approval-reply.js"; import type { Module } from "apcore-js"; import { ErrorMapper } from "../adapters/errors.js"; import { ErrorCodes } from "../types.js"; @@ -122,6 +124,10 @@ export type CallResult = [TextContentDict[], boolean, string | undefined]; * - `_meta.traceparent` — W3C trace_context header propagated from caller */ export interface HandleCallExtra { + /** Validated MCP request metadata for Phase B resumption. */ + approvalResumeToken?: string; + /** Per-request response handoff, created by the server factory. */ + approvalReply?: ApprovalReplyCapture; /** MCP request cancellation, including transport disconnect. */ signal?: AbortSignal; sendNotification?: (notification: Record) => Promise; @@ -493,6 +499,13 @@ export class ExecutionRouter { ): Promise { try { // ── Build context with MCP callbacks ────────────────────────────── + const resumeToken = extra?.approvalResumeToken; + if (Object.hasOwn(args, "_approval_token")) { + throw new InvalidInputError("Use request metadata for approval resumption"); + } + if (resumeToken !== undefined && (!isApprovalResumeToken(resumeToken) || !supportsScopedCore())) { + throw new InvalidInputError("Invalid or unsupported approval resume metadata"); + } const progressToken = extra?._meta?.progressToken; const sendNotification = extra?.sendNotification; const sendRequest = extra?.sendRequest; @@ -583,6 +596,7 @@ export class ExecutionRouter { // ── F-043: Async Task Bridge meta-tool dispatch ──────────────────── if (this._asyncTaskBridge && this._asyncTaskBridge.isMetaTool(toolName)) { + if (resumeToken !== undefined) throw new InvalidInputError("Approval resumption requires a direct tool call"); try { const metaResult = await this._asyncTaskBridge.handleMetaTool( toolName, @@ -603,7 +617,7 @@ export class ExecutionRouter { } // ── F-043: Async-hinted module → AsyncTaskManager.submit() ───────── - if (this._asyncTaskBridge && this._asyncTaskBridge.enabled) { + if (this._asyncTaskBridge?.enabled) { let descriptor: import("../types.js").ModuleDescriptor | null = null; try { descriptor = this._executor.registry?.getDefinition?.(toolName) ?? null; @@ -611,6 +625,7 @@ export class ExecutionRouter { // registry lookup is best-effort — leave descriptor null } if (this._asyncTaskBridge.isAsyncModule(descriptor)) { + if (resumeToken !== undefined) throw new InvalidInputError("Approval resumption requires a direct tool call"); try { // [A-D-018] Forward progressToken AND sessionKey so the bridge // records both for terminal-state fan-out (progressToken) and @@ -684,6 +699,9 @@ export class ExecutionRouter { } } + // Core separates the credential from business arguments before its pipeline. + const executionArgs = resumeToken === undefined ? args : { ...args, _approval_token: resumeToken }; + // ── Resolve versionHint from request metadata or descriptor ────── let versionHint: string | undefined = extra?.versionHint ?? extra?._meta?.apcore?.version; @@ -713,16 +731,17 @@ export class ExecutionRouter { // return the ordinary call result, including after-middleware changes. const execution = typeof this._executor.streamWithCompletion === "function" && (declaredStreaming || customStreamRequested) - ? this._executor.streamWithCompletion(toolName, args, context, versionHint) + ? this._executor.streamWithCompletion(toolName, executionArgs, context, versionHint) : null; // Retain the old structural extension point for custom executors. An // older Core instead uses one ordinary invocation with full validation. const chunks = execution?.chunks ?? (customStreamRequested - ? this._executor.stream?.(toolName, args, context, versionHint) + ? this._executor.stream?.(toolName, executionArgs, context, versionHint) : undefined); if (chunks) { const progress = wantsProgress ? { token: progressToken, send: sendNotification } : undefined; - const output = await this._collectStream(toolName, chunks, execution, progress); + const output = await runApprovalInvocation(extra?.approvalReply, context.data, () => + this._collectStream(toolName, chunks, execution, progress)); const redacted = await this._maybeRedact(toolName, output); return [[{ type: "text", text: await this._formatResult(redacted) }], false, effectiveTraceId]; } @@ -732,7 +751,9 @@ export class ExecutionRouter { let traceMeta: Record | undefined; if (this._trace && typeof this._executor.callWithTrace === 'function') { - const [traceResult, pipelineTrace] = await this._executor.callWithTrace(toolName, args, context, versionHint); + const callWithTrace = this._executor.callWithTrace.bind(this._executor); + const [traceResult, pipelineTrace] = await runApprovalInvocation(extra?.approvalReply, context.data, () => + callWithTrace(toolName, executionArgs, context, versionHint)); result = traceResult; // Convert pipeline trace to a serialisable dict if (pipelineTrace && typeof pipelineTrace === 'object') { @@ -760,7 +781,8 @@ export class ExecutionRouter { if (!callFn) { throw new Error('Executor must implement call() or callAsync()'); } - result = await callFn(toolName, args, context, versionHint); + result = await runApprovalInvocation(extra?.approvalReply, context.data, () => + callFn(toolName, executionArgs, context, versionHint)); } const redacted = await this._maybeRedact(toolName, result); @@ -779,6 +801,7 @@ export class ExecutionRouter { // Error messages, stacks, codes and attached fields may contain secrets. console.error("Tool execution failed"); const errorInfo = this._errorMapper.toMcpError(error); + if (errorInfo.errorType === ErrorCodes.APPROVAL_PENDING) confirmPendingApproval(extra?.approvalReply); const content: TextContentDict[] = [ { diff --git a/mcp/typescript/src/server/transport.ts b/mcp/typescript/src/server/transport.ts index 83e96bfe..058a494c 100644 --- a/mcp/typescript/src/server/transport.ts +++ b/mcp/typescript/src/server/transport.ts @@ -14,6 +14,7 @@ import { bindStdioWork, withStdioOutput } from "./stdio-output.js"; import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js"; import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js"; +import { hasApprovalReplies } from "../approval-reply.js"; import type { Authenticator } from "../auth/types.js"; import { identityStorage } from "../auth/storage.js"; @@ -508,7 +509,7 @@ export class TransportManager { rejectClosed(error); void closeTransport().catch(() => {}); }; - transport.onerror = (error) => { console.error("MCP stdio transport error:", error); }; + transport.onerror = () => { console.error("MCP stdio transport error"); }; let transportClosed = false; transport.onclose = () => { if (transportClosed) return; @@ -628,6 +629,7 @@ export class TransportManager { server: Server, options: HttpTransportOptions, ): Promise { + if (hasApprovalReplies(server)) throw new Error("Phase B is unavailable on the legacy SSE transport"); this._validateHostPort(options.host, options.port); const endpoint = options.endpoint ?? "/sse"; diff --git a/mcp/typescript/tests/adapters/approval.test.ts b/mcp/typescript/tests/adapters/approval.test.ts index db3d6025..8b99c08e 100644 --- a/mcp/typescript/tests/adapters/approval.test.ts +++ b/mcp/typescript/tests/adapters/approval.test.ts @@ -2,6 +2,7 @@ import { describe, it, expect, vi } from "vitest"; import { ElicitationApprovalHandler, StorageBackedApprovalHandler, + supportsScopedCore, } from "../../src/adapters/approval.js"; import { InMemoryApprovalStore } from "../../src/approval-store.js"; import { MCP_ELICIT_KEY } from "../../src/helpers.js"; @@ -153,69 +154,36 @@ describe("ElicitationApprovalHandler", () => { }); describe("StorageBackedApprovalHandler", () => { - const UUID_RE = - /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + const request = { moduleId: "test.module", arguments: { x: 1 } }; - it("[A-D-AP-1] returns the approval id in approvalId, not in reason", async () => { - const store = new InMemoryApprovalStore(); - try { - const handler = new StorageBackedApprovalHandler(store); - - const result = await handler.requestApproval({ - moduleId: "test.module", - arguments: { x: 1 }, - }); - - expect(result.status).toBe("pending"); - // Python returns ApprovalResult(status="pending", approval_id=...) and Rust - // sets result.approval_id; `reason` is human-readable text in all three. - expect(result.approvalId).toMatch(UUID_RE); - expect(result.reason ?? undefined).toBeUndefined(); - - // The id must address the record the handler actually persisted. - const record = await store.getResult(result.approvalId!); - expect(record).not.toBeNull(); - expect(record!.moduleId).toBe("test.module"); - } finally { - store.stop(); - } + it.skipIf(supportsScopedCore())("declines Phase B when Core only supports unscoped approval", async () => { + const handler = new StorageBackedApprovalHandler(new InMemoryApprovalStore()); + expect(() => handler.assertScopedSupport()).toThrow("scoped approval support"); + expect(await handler.requestApproval(request)).toMatchObject({ status: "rejected" }); }); - it("[A-D-AP-1] checkApproval echoes approvalId while still pending", async () => { + it.skipIf(!supportsScopedCore())("keeps Core credentials separate from public operator IDs", async () => { const store = new InMemoryApprovalStore(); + const notify = vi.fn().mockResolvedValue(undefined); + const handler = new StorageBackedApprovalHandler(store, { notifyCallback: notify }); try { - const handler = new StorageBackedApprovalHandler(store); - const pending = await handler.requestApproval({ - moduleId: "test.module", - arguments: {}, + const pending = await handler.requestApproval(request); + expect(pending).toMatchObject({ status: "pending", auditId: expect.any(String), approvalId: expect.any(String) }); + expect(pending.approvalId).not.toBe(pending.auditId); + expect(notify).toHaveBeenCalledWith(pending.auditId, request.moduleId, request.arguments); + expect(await store.getResult(pending.auditId!)).toMatchObject({ moduleId: request.moduleId }); + expect(await store.getResult(pending.approvalId!)).toBeNull(); + expect(await handler.checkApproval(pending.approvalId!)).toMatchObject({ status: "rejected" }); + expect(await handler.checkApprovalForPrincipal(pending.auditId!, null)).toEqual({ + status: "pending", auditId: pending.auditId, }); + expect(await handler.checkApprovalForCall(pending.approvalId!, request)).toEqual(pending); - const checked = await handler.checkApproval(pending.approvalId!); - - expect(checked.status).toBe("pending"); - expect(checked.approvalId).toBe(pending.approvalId); - } finally { - store.stop(); - } - }); - - it("checkApproval carries the rejection reason, not an id", async () => { - const store = new InMemoryApprovalStore(); - try { - const handler = new StorageBackedApprovalHandler(store); - const pending = await handler.requestApproval({ - moduleId: "test.module", - arguments: {}, - }); - await store.resolve(pending.approvalId!, { - approved: false, - reason: "denied by operator", + await store.resolve(pending.auditId!, { approved: true }); + expect(await handler.checkApprovalForCall(pending.approvalId!, request)).toEqual({ + status: "approved", auditId: pending.auditId, }); - - const checked = await handler.checkApproval(pending.approvalId!); - - expect(checked.status).toBe("rejected"); - expect(checked.reason).toBe("denied by operator"); + expect(await handler.checkApprovalForCall(pending.approvalId!, request)).toMatchObject({ status: "rejected" }); } finally { store.stop(); } diff --git a/mcp/typescript/tests/adapters/errors.test.ts b/mcp/typescript/tests/adapters/errors.test.ts index f2d50e17..0de35c09 100644 --- a/mcp/typescript/tests/adapters/errors.test.ts +++ b/mcp/typescript/tests/adapters/errors.test.ts @@ -313,49 +313,20 @@ describe("ErrorMapper", () => { expect(result.suggestion).toBeUndefined(); }); - // TC-ERROR-014: APPROVAL_PENDING narrows snake_case approval_id to camelCase approvalId. - // [D10-003] Upstream apcore SDKs always emit snake_case; the camelCase - // input branch has been removed for cross-language parity. - it("narrows APPROVAL_PENDING details from snake_case approval_id to approvalId", () => { + it.each(["approval_id", "approvalId"])("omits pending credentials in %s and guidance", (field) => { + const credential = "private-pending-credential"; const error = createModuleError( "APPROVAL_PENDING", - "Approval pending", - { approval_id: "abc-123", extra: "should-be-dropped" }, + `Approval pending for ${credential}`, + { [field]: credential }, + { suggestion: credential, aiGuidance: credential, userFixable: true }, ); - - const result = mapper.toMcpError(error); - - expect(result.isError).toBe(true); - expect(result.errorType).toBe("APPROVAL_PENDING"); - expect(result.message).toBe("Approval pending"); - expect(result.details).toEqual({ approvalId: "abc-123" }); - }); - - // [D10-003] camelCase approvalId input is no longer accepted — drops to null - // to match Python/Rust which only recognize snake_case approval_id. - it("drops camelCase approvalId source key (D10-003 parity)", () => { - const error = createModuleError( - "APPROVAL_PENDING", - "Approval pending", - { approvalId: "camel-789" }, - ); - - const result = mapper.toMcpError(error); - - expect(result.details).toBeNull(); - }); - - // TC-ERROR-015: APPROVAL_PENDING with no approvalId in details - it("returns null details for APPROVAL_PENDING without approvalId", () => { - const error = createModuleError( - "APPROVAL_PENDING", - "Approval pending", - { other: "data" }, - ); - - const result = mapper.toMcpError(error); - - expect(result.details).toBeNull(); + expect(mapper.toMcpError(error)).toEqual({ + isError: true, + errorType: "APPROVAL_PENDING", + message: "Approval is pending", + details: null, + }); }); // TC-ERROR-016: APPROVAL_TIMEOUT marked retryable @@ -452,31 +423,6 @@ describe("ErrorMapper", () => { }); }); -// [D10-003] Approval source-key contract: only snake_case approval_id is -// accepted; camelCase approvalId is dropped. This supersedes the older -// D10-011 dual-key handling test block which asserted both branches. -describe("D10-003: approval_id snake_case is the sole accepted source key", () => { - it("handles snake_case approval_id (apcore-py/rs/js shared convention)", () => { - const mapper = new ErrorMapper(); - const error = createModuleError("APPROVAL_PENDING", "Approval needed", { - approval_id: "xyz-456", - }); - const result = mapper.toMcpError(error); - expect(result.errorType).toBe("APPROVAL_PENDING"); - expect((result.details as Record)?.approvalId).toBe("xyz-456"); - }); - - it("drops the input when only camelCase approvalId is present", () => { - const mapper = new ErrorMapper(); - const error = createModuleError("APPROVAL_PENDING", "Approval needed", { - approvalId: "abc-123", - }); - const result = mapper.toMcpError(error); - expect(result.errorType).toBe("APPROVAL_PENDING"); - expect(result.details).toBeNull(); - }); -}); - // D11-016: userFixable pass-through for DEPENDENCY_NOT_FOUND / DEPENDENCY_VERSION_MISMATCH. // apcore-js >=0.24.0 sets userFixable on these error codes; the bridge passes it through // via _attachAiGuidance. diff --git a/mcp/typescript/tests/approval-store.test.ts b/mcp/typescript/tests/approval-store.test.ts index 4b7224c4..1c66a00d 100644 --- a/mcp/typescript/tests/approval-store.test.ts +++ b/mcp/typescript/tests/approval-store.test.ts @@ -156,3 +156,45 @@ describe("InMemoryApprovalStore", () => { expect(Object.keys(rec!)).toEqual(["status", "moduleId", "reason", "createdAt", "resolvedAt"]); }); }); + +describe("scoped approval storage", () => { + const scope = { + principal: { type: "user", id: "operator" }, + callerId: null, + moduleId: "test.confirm", + argumentsDigest: "a".repeat(64), + }; + const verifier = "b".repeat(64); + const id = "00000000-0000-4000-8000-000000000000"; + + it("matches a trusted scope and consumes an approved grant once", async () => { + const store = new InMemoryApprovalStore(); + await store.saveScopedPending(id, verifier, scope); + expect(await store.getScopedResult(id, { type: "user", id: "another" })).toBeNull(); + expect(await store.getScopedResult(id, scope.principal)).toMatchObject({ status: "pending" }); + expect(await store.consumeScoped(id, verifier, scope)).toMatchObject({ status: "pending" }); + await store.resolve(id, { approved: true }); + expect(await store.consumeScoped(id, verifier, { ...scope, argumentsDigest: "c".repeat(64) })).toBeNull(); + const results = await Promise.all([ + store.consumeScoped(id, verifier, scope), + store.consumeScoped(id, verifier, scope), + ]); + expect(results).toEqual([expect.objectContaining({ status: "approved" }), null]); + expect(await store.getScopedResult(id, scope.principal)).toMatchObject({ status: "approved" }); + expect(Object.keys((await store.getResult(id)) ?? {})).not.toContain("verifier"); + }); + + it("rejects expired records synchronously even before sweeping", async () => { + vi.useFakeTimers(); + try { + const store = new InMemoryApprovalStore({ pendingTtlMs: 100, resolvedTtlMs: 25 }); + await store.saveScopedPending(id, verifier, scope); + await store.resolve(id, { approved: true }); + vi.setSystemTime(Date.now() + 26); + expect(await store.consumeScoped(id, verifier, scope)).toBeNull(); + expect(await store.getScopedResult(id, scope.principal)).toBeNull(); + } finally { + vi.useRealTimers(); + } + }); +}); diff --git a/mcp/typescript/tests/serve-features.test.ts b/mcp/typescript/tests/serve-features.test.ts index 41027de5..d84b50fc 100644 --- a/mcp/typescript/tests/serve-features.test.ts +++ b/mcp/typescript/tests/serve-features.test.ts @@ -38,6 +38,7 @@ vi.mock("../src/server/factory.js", () => ({ // Import serve after mocks are set up import { serve } from "../src/index.js"; +import { ElicitationApprovalHandler, supportsScopedCore } from "../src/adapters/approval.js"; // --------------------------------------------------------------------------- // Helpers @@ -351,6 +352,18 @@ describe("serve() onStartup/onShutdown (F4)", () => { // --------------------------------------------------------------------------- describe("serve() approvalStore lifecycle", () => { + it("declines Phase B with an unscoped store before connecting transport", async () => { + const store = { + savePending: vi.fn().mockResolvedValue(undefined), + getResult: vi.fn().mockResolvedValue(null), + resolve: vi.fn().mockResolvedValue(false), + }; + await expect(serve(createMockRegistry({}), { transport: "stdio", approvalStore: store })) + .rejects.toThrow(supportsScopedCore() ? "scoped approval store" : "scoped approval support"); + expect(mockRunStdio).not.toHaveBeenCalled(); + }); + + it("starts the store before the transport and stops it after", async () => { const registry = createMockRegistry({}); const executor = createMockExecutor(registry); @@ -367,7 +380,7 @@ describe("serve() approvalStore lifecycle", () => { order.push("transport"); }); - await serve(executor, { transport: "stdio", approvalStore: store }); + await serve(executor, { transport: "stdio", approvalStore: store, approvalHandler: new ElicitationApprovalHandler() }); expect(store.start).toHaveBeenCalledTimes(1); expect(store.stop).toHaveBeenCalledTimes(1); @@ -389,7 +402,7 @@ describe("serve() approvalStore lifecycle", () => { mockRunStdio.mockRejectedValueOnce(new Error("transport failed")); await expect( - serve(executor, { transport: "stdio", approvalStore: store }), + serve(executor, { transport: "stdio", approvalStore: store, approvalHandler: new ElicitationApprovalHandler() }), ).rejects.toThrow("transport failed"); expect(store.start).toHaveBeenCalledTimes(1); @@ -407,7 +420,7 @@ describe("serve() approvalStore lifecycle", () => { }; // Should not throw despite missing start()/stop(). - await serve(executor, { transport: "stdio", approvalStore: store }); + await serve(executor, { transport: "stdio", approvalStore: store, approvalHandler: new ElicitationApprovalHandler() }); expect(mockRunStdio).toHaveBeenCalledTimes(1); }); diff --git a/mcp/typescript/tests/server/approval-bridge.test.ts b/mcp/typescript/tests/server/approval-bridge.test.ts index ad232d8a..1fc49557 100644 --- a/mcp/typescript/tests/server/approval-bridge.test.ts +++ b/mcp/typescript/tests/server/approval-bridge.test.ts @@ -1,142 +1,65 @@ import { describe, it, expect, vi } from "vitest"; +import { supportsScopedCore } from "../../src/adapters/approval.js"; import { ApprovalBridge, APPROVAL_META_TOOL_NAMES } from "../../src/server/approval-bridge.js"; -function buildHandler(overrides: Partial<{ - checkApproval: (id: string) => Promise<{ status: string; reason?: string; approvalId?: string }>; -}> = {}) { - return { - checkApproval: overrides.checkApproval ?? vi.fn().mockResolvedValue({ status: "pending", approvalId: "abc" }), - }; -} +const check = "__apcore_approval_check"; +const id = "4f2c29a5-d981-4e46-9ca1-0b17535abd12"; describe("ApprovalBridge", () => { - describe("isMetaTool", () => { - it("returns true for __apcore_approval_check", () => { - expect(ApprovalBridge.isMetaTool("__apcore_approval_check")).toBe(true); - }); - - it("returns false for async task meta-tools", () => { - expect(ApprovalBridge.isMetaTool("__apcore_task_submit")).toBe(false); - expect(ApprovalBridge.isMetaTool("__apcore_task_status")).toBe(false); - }); - - it("returns false for regular tool names", () => { - expect(ApprovalBridge.isMetaTool("my.module")).toBe(false); - expect(ApprovalBridge.isMetaTool("")).toBe(false); - }); + it("recognizes the approval tool separately from ordinary and task tools", () => { + expect(APPROVAL_META_TOOL_NAMES).toContain(check); + expect(ApprovalBridge.isMetaTool(check)).toBe(true); + expect(ApprovalBridge.isMetaTool("__apcore_task_submit")).toBe(false); + expect(ApprovalBridge.isMetaTool("my.module")).toBe(false); }); - describe("APPROVAL_META_TOOL_NAMES constant", () => { - it("contains __apcore_approval_check", () => { - expect(APPROVAL_META_TOOL_NAMES).toContain("__apcore_approval_check"); - }); + it("does not offer polling for an unscoped handler", async () => { + const legacy = vi.fn().mockResolvedValue({ status: "approved" }); + const bridge = new ApprovalBridge({ checkApproval: legacy }); + expect(bridge.buildMetaTools()).toEqual([]); + expect((await bridge.handleMetaTool(check, { approval_id: id }))[1]).toBe(true); + expect(legacy).not.toHaveBeenCalled(); }); - describe("buildMetaTools", () => { - it("returns one tool with correct name", () => { - const bridge = new ApprovalBridge(buildHandler()); - const tools = bridge.buildMetaTools(); - expect(tools).toHaveLength(1); - expect(tools[0].name).toBe("__apcore_approval_check"); - }); - - it("tool has correct input schema requiring approval_id", () => { - const bridge = new ApprovalBridge(buildHandler()); - const [tool] = bridge.buildMetaTools(); - const schema = tool.inputSchema as Record; - expect(schema.type).toBe("object"); - expect(schema.required).toContain("approval_id"); - expect(schema.additionalProperties).toBe(false); - }); - - it("tool description mentions approval_id and status values", () => { - const bridge = new ApprovalBridge(buildHandler()); - const [tool] = bridge.buildMetaTools(); - expect(tool.description).toContain("approval_id"); - expect(tool.description).toContain("pending"); - expect(tool.description).toContain("approved"); - expect(tool.description).toContain("rejected"); - }); + it.skipIf(!supportsScopedCore())("lists only the public approval ID as input", () => { + const bridge = new ApprovalBridge({ checkApprovalForPrincipal: async () => ({ status: "pending" }) }); + expect(bridge.buildMetaTools()).toMatchObject([{ + name: check, + inputSchema: { type: "object", required: ["approval_id"], additionalProperties: false }, + }]); }); - describe("handleMetaTool - __apcore_approval_check", () => { - it("passes through pending status", async () => { - const handler = buildHandler({ - checkApproval: vi.fn().mockResolvedValue({ status: "pending", approvalId: "abc" }), - }); - const bridge = new ApprovalBridge(handler); - const [content, isError, traceId] = await bridge.handleMetaTool("__apcore_approval_check", { - approval_id: "abc", - }); + it.skipIf(!supportsScopedCore()).each(["pending", "approved", "rejected"])( + "returns only the authorized public %s status", async status => { + const principal = { type: "service", id: "operator-client" }; + const poll = vi.fn().mockResolvedValue({ status, reason: "private operator note" }); + const bridge = new ApprovalBridge({ checkApprovalForPrincipal: poll }); + const [content, isError, traceId] = await bridge.handleMetaTool(check, { approval_id: id }, principal); expect(isError).toBe(false); expect(traceId).toBeNull(); - const payload = JSON.parse(content[0].text); - expect(payload.approval_id).toBe("abc"); - expect(payload.status).toBe("pending"); - }); - - it("passes through approved status without reason", async () => { - const handler = buildHandler({ - checkApproval: vi.fn().mockResolvedValue({ status: "approved" }), - }); - const bridge = new ApprovalBridge(handler); - const [content, isError] = await bridge.handleMetaTool("__apcore_approval_check", { - approval_id: "my-id", - }); - expect(isError).toBe(false); - const payload = JSON.parse(content[0].text); - expect(payload.status).toBe("approved"); - expect("reason" in payload).toBe(false); - }); - - it("passes through rejected status with reason", async () => { - const handler = buildHandler({ - checkApproval: vi.fn().mockResolvedValue({ status: "rejected", reason: "no budget" }), - }); - const bridge = new ApprovalBridge(handler); - const [content, isError] = await bridge.handleMetaTool("__apcore_approval_check", { - approval_id: "my-id", - }); - expect(isError).toBe(false); - const payload = JSON.parse(content[0].text); - expect(payload.status).toBe("rejected"); - expect(payload.reason).toBe("no budget"); - }); + expect(JSON.parse(content[0].text)).toEqual({ approval_id: id, status }); + expect(poll).toHaveBeenCalledWith(id, principal); + }, + ); - it("missing approval_id returns is_error=true", async () => { - const bridge = new ApprovalBridge(buildHandler()); - const [content, isError] = await bridge.handleMetaTool("__apcore_approval_check", {}); - expect(isError).toBe(true); - expect(content[0].text).toContain("approval_id"); - }); - - it("empty string approval_id returns is_error=true", async () => { - const bridge = new ApprovalBridge(buildHandler()); - const [content, isError] = await bridge.handleMetaTool("__apcore_approval_check", { - approval_id: "", - }); - expect(isError).toBe(true); - }); + it("does not reflect an invalid identifier", async () => { + const bridge = new ApprovalBridge({ checkApprovalForPrincipal: vi.fn() }); + const [content, isError] = await bridge.handleMetaTool(check, { approval_id: "invalid-id" }); + expect(isError).toBe(true); + expect(content[0].text).toBe("A public approval_id is required"); + }); - it("checkApproval throwing returns is_error=true", async () => { - const handler = buildHandler({ - checkApproval: vi.fn().mockRejectedValue(new Error("store down")), - }); - const bridge = new ApprovalBridge(handler); - const [content, isError] = await bridge.handleMetaTool("__apcore_approval_check", { - approval_id: "abc", - }); - expect(isError).toBe(true); - expect(content[0].text).toContain("store down"); - }); + it.skipIf(!supportsScopedCore())("returns a generic store error", async () => { + const poll = vi.fn().mockRejectedValue(new Error("private store detail")); + const bridge = new ApprovalBridge({ checkApprovalForPrincipal: poll }); + const [content, isError] = await bridge.handleMetaTool(check, { approval_id: id }); + expect(isError).toBe(true); + expect(content[0].text).toBe("Approval status unavailable"); }); - describe("handleMetaTool - unknown tool name", () => { - it("returns is_error=true for unknown meta-tool", async () => { - const bridge = new ApprovalBridge(buildHandler()); - const [content, isError] = await bridge.handleMetaTool("__apcore_unknown_tool", {}); - expect(isError).toBe(true); - expect(content[0].text).toContain("Unknown approval meta-tool"); - }); + it("declines an unknown meta-tool", async () => { + const bridge = new ApprovalBridge({}); + const [, isError] = await bridge.handleMetaTool("__apcore_unknown_tool", {}); + expect(isError).toBe(true); }); }); diff --git a/mcp/typescript/tests/server/outputSafety.test.ts b/mcp/typescript/tests/server/outputSafety.test.ts index b7878b75..cedcddff 100644 --- a/mcp/typescript/tests/server/outputSafety.test.ts +++ b/mcp/typescript/tests/server/outputSafety.test.ts @@ -23,7 +23,7 @@ describe("tool errors on the MCP wire", () => { const server = factory.createServer(); const call = vi.fn(async () => { throw new apcore.ModuleError(code, "Controlled tool failure"); }); const router = new ExecutionRouter({ ...executor({}), call }); - const approval = new ApprovalBridge({ checkApproval: async () => ({ status: "pending" }) }); + const approval = new ApprovalBridge({ checkApprovalForPrincipal: async () => ({ status: "pending" }) }); factory.registerHandlers(server, [{ name: "demo", inputSchema: { type: "object" } }], router, { approvalBridge: approval }); const client = new Client({ name: "output-safety", version: "1" }); const [ct, st] = InMemoryTransport.createLinkedPair(); @@ -34,8 +34,12 @@ describe("tool errors on the MCP wire", () => { expect(call).toHaveBeenCalledOnce(); await expect(client.callTool({ name: "missing.tool", arguments: {} })).rejects.toMatchObject({ code: -32602 }); expect(call).toHaveBeenCalledOnce(); - const denied = await client.callTool({ name: "__apcore_approval_check", arguments: {} }); - expect(denied).toMatchObject({ isError: true, content: [{ text: "approval_id is required" }] }); + const poll = () => client.callTool({ name: "__apcore_approval_check", arguments: {} }); + if (approval.available) { + expect(await poll()).toMatchObject({ isError: true, content: [{ text: "A public approval_id is required" }] }); + } else { + await expect(poll()).rejects.toMatchObject({ code: -32602 }); + } await expect(client.request({ method: "unsupported" } as never, CallToolResultSchema)).rejects.toMatchObject({ code: -32601 }); } finally { await client.close(); diff --git a/mcp/typescript/tests/server/scoped-approval.test.ts b/mcp/typescript/tests/server/scoped-approval.test.ts new file mode 100644 index 00000000..e794aaa8 --- /dev/null +++ b/mcp/typescript/tests/server/scoped-approval.test.ts @@ -0,0 +1,254 @@ +import { once } from "node:events"; +import { createServer } from "node:http"; +import type { AddressInfo } from "node:net"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; +import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; +import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js"; +import * as core from "apcore-js"; +import { describe, expect, it, vi } from "vitest"; +import { StorageBackedApprovalHandler, supportsScopedCore } from "../../src/adapters/approval.js"; +import { InMemoryApprovalStore } from "../../src/approval-store.js"; +import { identityStorage } from "../../src/auth/storage.js"; +import { APCoreMCP, asyncServe } from "../../src/index.js"; +import { ApprovalBridge } from "../../src/server/approval-bridge.js"; +import { AsyncTaskBridge, META_TOOL_NAMES } from "../../src/server/async-task-bridge.js"; +import { MCPServerFactory } from "../../src/server/factory.js"; +import { ExecutionRouter } from "../../src/server/router.js"; + +const moduleId = "sample.review"; +const regularId = "sample.regular"; +const approvalCheck = "__apcore_approval_check"; +const reviewer = core.createIdentity("sample-user", "user"); +const otherReviewer = core.createIdentity("other-user", "user"); +const inputSchema = { + type: "object", + properties: { subject: { type: "string" }, copies: { type: "integer" } }, + required: ["subject", "copies"], + additionalProperties: false, +}; +const args = { subject: "example", copies: 2 }; + +interface PendingMetadata { + approvalId: string; + resumeToken: string; +} + +function approvalMetadata(result: CallToolResult): PendingMetadata | undefined { + return (result._meta?.apcore as { approval?: PendingMetadata } | undefined)?.approval; +} + +async function connect(options: { streaming?: boolean; background?: boolean; trace?: boolean } = {}) { + const store = new InMemoryApprovalStore(); + const notify = vi.fn().mockResolvedValue(undefined); + const handler = new StorageBackedApprovalHandler(store, { notifyCallback: notify }).forMcpServer(); + const events = new core.EventEmitter(); + const audit: Record[] = []; + events.subscribe({ + eventPattern: "apcore.approval.decision", + onEvent: (event) => { audit.push(event.data); }, + }); + const registry = new core.Registry(); + const execute = vi.fn((inputs) => ({ reviewed: inputs.subject })); + const stream = vi.fn(async function* (inputs) { yield { reviewed: inputs.subject }; }); + await registry.register(moduleId, { + description: "Review the supplied example", + annotations: core.createAnnotations({ + requiresApproval: true, + streaming: options.streaming, + extra: options.background ? { mcp_async: "true" } : {}, + }), + inputSchema, + outputSchema: { type: "object" }, + execute, + ...(options.streaming ? { [core.STREAMING_MARKER]: true, stream } : {}), + } as never); + await registry.register(regularId, { + description: "Return an ordinary background result", + annotations: core.createAnnotations({ extra: { mcp_async: "true" } }), + inputSchema, + outputSchema: { type: "object" }, + execute: () => ({ job: "ordinary" }), + } as never); + const executor = new core.Executor({ registry, approvalHandler: handler as never, eventEmitter: events }); + const manager = options.background ? new core.AsyncTaskManager({ executor }) : undefined; + const asyncTaskBridge = manager ? new AsyncTaskBridge(manager as never, { + descriptorLookup: id => registry.getDefinition(id) as never, + }) : undefined; + const factory = new MCPServerFactory({ richDescription: false }); + const server = factory.createServer(); + const router = new ExecutionRouter(executor as never, { + validateInputs: true, + trace: options.trace, + asyncTaskBridge, + }); + factory.registerHandlers(server, factory.buildTools(registry as never), router, { + approvalBridge: new ApprovalBridge(handler), + asyncTaskBridge, + }); + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + const client = new Client({ name: "scoped-approval", version: "1" }); + await server.connect(serverTransport); + await client.connect(clientTransport); + return { + store, notify, events, audit, client, manager, execute, stream, + async close() { + await client.close(); + await server.close(); + await manager?.shutdown(); + await events.shutdown(); + store.stop(); + }, + }; +} + +describe.skipIf(!supportsScopedCore())("scoped approval through the MCP wire", () => { + it.each(["unary", "traced", "streamed"])("completes the %s approval lifecycle with private credential delivery", async kind => { + const target = await connect({ trace: kind === "traced", streaming: kind === "streamed" }); + const run = (arguments_ = args, resumeToken?: string) => identityStorage.run(reviewer, () => + target.client.callTool({ + name: moduleId, + arguments: arguments_, + ...(resumeToken ? { _meta: { approvalId: resumeToken } } : {}), + })); + const poll = (identity: core.Identity | null, approvalId: string) => identityStorage.run(identity, async () => { + const result = await target.client.callTool({ name: approvalCheck, arguments: { approval_id: approvalId } }); + return JSON.parse((result.content as { text: string }[])[0].text); + }); + try { + expect((await target.client.listTools()).tools.map(tool => tool.name)).toContain(approvalCheck); + const pending = await run(); + const approval = approvalMetadata(pending); + expect(pending.isError).toBe(true); + expect(approval).toMatchObject({ approvalId: expect.any(String), resumeToken: expect.any(String) }); + const { approvalId, resumeToken } = approval!; + expect(JSON.stringify(pending.content)).toContain("Approval is pending"); + expect(JSON.stringify(pending.content)).not.toContain(resumeToken); + expect(target.notify).toHaveBeenCalledExactlyOnceWith(approvalId, moduleId, args); + expect(await poll(reviewer, approvalId)).toEqual({ approval_id: approvalId, status: "pending" }); + expect(await poll(otherReviewer, approvalId)).toEqual({ approval_id: approvalId, status: "rejected" }); + expect(await poll(null, approvalId)).toEqual({ approval_id: approvalId, status: "rejected" }); + expect(approvalMetadata(await run(args, resumeToken))).toEqual(approval); + expect(await target.store.resolve(approvalId, { approved: true })).toBe(true); + expect(await poll(reviewer, approvalId)).toEqual({ approval_id: approvalId, status: "approved" }); + const completions = await Promise.all([ + run({ copies: 2, subject: "example" }, resumeToken), + run(args, resumeToken), + ]); + expect(completions.filter(result => result.isError !== true)).toHaveLength(1); + const runner = kind === "streamed" ? target.stream : target.execute; + expect(runner).toHaveBeenCalledOnce(); + expect(runner.mock.calls[0][0]).toEqual(args); + expect(JSON.stringify(completions)).not.toContain(resumeToken); + + await target.events.flush(); + expect(target.audit).toContainEqual(expect.objectContaining({ approval_id: approvalId, status: "pending" })); + expect(target.audit).toContainEqual(expect.objectContaining({ approval_id: approvalId, status: "approved" })); + expect(JSON.stringify(target.audit)).not.toContain(resumeToken); + } finally { + await target.close(); + } + }); + + it("permits ordinary background jobs and declines Phase B for background submissions", async () => { + const target = await connect({ background: true }); + const save = vi.spyOn(target.store, "saveScopedPending"); + async function taskFor(name: string) { + const result = await target.client.callTool({ name, arguments: args }); + expect(result.isError).not.toBe(true); + expect(approvalMetadata(result)).toBeUndefined(); + return JSON.parse((result.content as { text: string }[])[0].text).task_id as string; + } + try { + const ordinary = await taskFor(regularId); + const protectedTask = await taskFor(moduleId); + await vi.waitFor(async () => { + expect(await target.manager!.getStatus(ordinary)).toMatchObject({ status: "completed", result: { job: "ordinary" } }); + expect(await target.manager!.getStatus(protectedTask)).toMatchObject({ + status: "failed", error: expect.stringContaining("Scoped approval requires a direct tool call"), + }); + }); + expect(save).not.toHaveBeenCalled(); + expect(target.notify).not.toHaveBeenCalled(); + expect(target.execute).not.toHaveBeenCalled(); + const syntheticToken = "4f2c29a5-d981-4e46-9ca1-0b17535abd12." + "1".repeat(64); + const submitted = await target.client.callTool({ + name: META_TOOL_NAMES.SUBMIT, + arguments: { module_id: regularId, arguments: args }, + _meta: { approvalId: syntheticToken }, + }); + expect(submitted).toMatchObject({ isError: true }); + expect(JSON.stringify(submitted.content)).toContain("Approval resumption requires a direct tool call"); + expect(JSON.stringify(submitted)).not.toContain(syntheticToken); + } finally { + await target.close(); + } + }); +}); + +it.skipIf(supportsScopedCore()).each([false, true])( + "explicit Phase B declines unscoped Core before starting the store (facade: %s)", async throughFacade => { + const info = console.info; + const registry = new core.Registry(); + const approvalStore = new InMemoryApprovalStore(); + const start = vi.spyOn(approvalStore, "start"); + const options = { approvalStore, logLevel: "ERROR" as const }; + const startup = throughFacade + ? new APCoreMCP(registry as never, options).asyncServe() + : asyncServe(registry as never, options); + await expect(startup).rejects.toThrow("Phase B requires Core with scoped approval support"); + expect(start).not.toHaveBeenCalled(); + expect(console.info).toBe(info); + }, +); + +it.skipIf(!supportsScopedCore()).each([false, true])( + "asyncServe wires scoped approval for Streamable HTTP (facade: %s)", async throughFacade => { + const registry = new core.Registry(); + await registry.register(moduleId, { + description: "Review the supplied example", + annotations: core.createAnnotations({ requiresApproval: true }), + inputSchema, + outputSchema: { type: "object" }, + execute: () => ({ reviewed: "example" }), + } as never); + const approvalStore = new InMemoryApprovalStore(); + const options = { + approvalStore, + async: false as const, + authenticator: { + authenticate: async (headers: Record) => + headers.authorization === "Bearer fixture-identity" ? reviewer : null, + }, + }; + const app = throughFacade + ? await new APCoreMCP(registry as never, options).asyncServe() + : await asyncServe(registry as never, options); + const http = createServer(app.handler); + const client = new Client({ name: "scoped-server", version: "1" }); + try { + http.listen(0, "127.0.0.1"); + await once(http, "listening"); + const url = new URL(`http://127.0.0.1:${(http.address() as AddressInfo).port}/mcp`); + await client.connect(new StreamableHTTPClientTransport(url, { + requestInit: { headers: { Authorization: "Bearer fixture-identity" } }, + })); + const result = await client.callTool({ name: moduleId, arguments: args }); + const approval = approvalMetadata(result); + expect(approval).toBeDefined(); + await approvalStore.resolve(approval!.approvalId, { approved: true }); + const resumed = await client.callTool({ + name: moduleId, + arguments: args, + _meta: { approvalId: approval!.resumeToken }, + }); + expect(resumed.isError).not.toBe(true); + expect(resumed.structuredContent).toEqual({ reviewed: "example" }); + } finally { + await client.close(); + await app.close(); + http.closeAllConnections(); + await new Promise(resolve => http.close(() => resolve())); + } + }, +); From 329ce88e93231810ad9e8ba764e3cbe9008abd3a Mon Sep 17 00:00:00 2001 From: tercel Date: Fri, 27 Nov 2026 14:08:26 +0800 Subject: [PATCH 28/36] docs(mcp): describe the scoped approval wire contract Signed-off-by: tercel --- mcp/docs/configuration.md | 35 +- mcp/docs/features/approval-phase-b.md | 501 +++----------------------- mcp/docs/features/error-mapper.md | 2 +- mcp/docs/prd-apcore-mcp.md | 4 +- mcp/docs/srs-apcore-mcp.md | 2 +- mcp/docs/tech-design-apcore-mcp.md | 2 +- mcp/docs/test-plan-apcore-mcp.md | 4 +- 7 files changed, 75 insertions(+), 475 deletions(-) diff --git a/mcp/docs/configuration.md b/mcp/docs/configuration.md index 5e11a800..675a542b 100644 --- a/mcp/docs/configuration.md +++ b/mcp/docs/configuration.md @@ -507,11 +507,10 @@ interactive MCP clients. ### Phase B — storage-backed approvals -Phase A needs the caller to stay connected while a human decides. Phase B does not: the call returns -immediately with an `APPROVAL_PENDING` response carrying an `approval_id`, the decision is recorded -out-of-band, and the agent polls until it resolves. Pass an `approval_store` — and optionally an -`approval_notify` callback that fires when a request is created, so you can push it to Slack, email, -or a review queue. +Phase B requires Core's scoped approval gate and a store that can consume a grant atomically. +Set `approval_store` and optionally configure an `approval_notify` callback to send the public +approval record ID to a review queue. The tool call returns `APPROVAL_PENDING` while a reviewer +records a decision. === "Python" @@ -559,24 +558,14 @@ or a review queue. mcp.serve()?; ``` -**The agent-side flow.** When a store is configured the bridge also exposes a meta-tool, -`__apcore_approval_check`: - -1. The agent calls the gated tool. It comes back with an `APPROVAL_PENDING` response containing an - `approval_id`. -2. A human resolves the request out-of-band — `store.resolve(approval_id, approved=True)`, or - whatever your backend does. -3. The agent polls `__apcore_approval_check({"approval_id": "..."})`, which returns - `{approval_id, status, reason?}` where `status` is `pending`, `approved`, or `rejected`. -4. Once `approved`, the agent retries the original tool call with `_meta.approvalId` set to that - `approval_id`. - -`InMemoryApprovalStore` is process-local and non-durable: pending records expire, resolved records -are kept only briefly, and everything is lost on restart. It is the right default for a single -process and the wrong one for anything horizontally scaled — implement the `ApprovalStore` interface -against Redis or a database for that. See -[Approval Handler (Phase B)](features/approval-phase-b.md) for the full contract, including the -Redis-backed pseudocode. +The pending result carries `approvalId` and the private `resumeToken` in +`_meta.apcore.approval`. Resolve the record or query `__apcore_approval_check` with the public +ID. Once approved, send the original business arguments again with the private token in +`params._meta.approvalId`. Core checks the invocation scope and consumes the approval on use. + +`InMemoryApprovalStore` holds approvals for the lifetime of the process. Use a shared durable +store when requests can be handled by multiple instances or must survive restarts. See the +[Phase B approval contract](features/approval-phase-b.md) for the wire and storage behavior. ## Tool Explorer diff --git a/mcp/docs/features/approval-phase-b.md b/mcp/docs/features/approval-phase-b.md index 4c1518ce..70c22eda 100644 --- a/mcp/docs/features/approval-phase-b.md +++ b/mcp/docs/features/approval-phase-b.md @@ -1,491 +1,102 @@ --- -description: "Approval Phase B feature spec: StorageBackedApprovalHandler implements long-lived, out-of-band human approval via persistent ApprovalStore, __apcore_approval_check meta-tool, and optional notify callback." +description: "Storage-backed human approval and one-shot MCP tool resumption." --- # Approval Phase B -> Feature spec for cross-SDK implementation planning. -> Source: derived from apcore-mcp/docs/srs-apcore-mcp.md and approval-handler.md -> Created: 2026-06-12 - ## Overview -Approval Phase B complements Phase A (`ElicitationApprovalHandler`) by providing a storage-backed approval flow that survives beyond the lifetime of a single MCP request. Instead of blocking synchronously for an inline user response via MCP elicitation, `StorageBackedApprovalHandler` persists the approval request to an `ApprovalStore`, returns an `APPROVAL_PENDING` sentinel immediately, and relies on an external system (Slack, email, web UI, webhook) to resolve the approval out of band. The agent polls via the `__apcore_approval_check` meta-tool and retries the original call once the approval is resolved. +`StorageBackedApprovalHandler` lets a tool call return while a reviewer decides whether it may proceed. The caller keeps the original input and a private resume token. A trusted review system records the decision in the approval store. -Phase B is not a replacement for Phase A. Both implement the same `ApprovalHandler` protocol from the apcore SDK; the choice between them is a deployment decision. +Phase B requires Core's scoped approval gate and a store that can atomically verify and consume an approval. Phase A uses the inline `ElicitationApprovalHandler` and can run with the package's minimum Core version. ## When to Use Each Phase -| Criterion | Phase A: `ElicitationApprovalHandler` | Phase B: `StorageBackedApprovalHandler` | -|---|---|---| -| Approval lifetime | Short-lived (seconds to minutes) | Long-lived (minutes to days) | -| MCP client support | Requires elicitation support in client | No elicitation required | -| Flow style | Synchronous, inline | Asynchronous, polling | -| Resolution path | User responds inside the MCP client UI | External system (Slack/email/web UI) | -| Persistence | None (in-memory per request) | Required (survives restarts) | -| Agent retry | Not required; handler blocks until resolved | Required; agent must poll and retry | - -Choose Phase A when the MCP client (e.g., Claude Desktop) supports elicitation and the user is present at the keyboard. Choose Phase B for automated pipelines, mobile approvals, team workflows, or any case where the approver is not watching the terminal in real time. +| Phase | Decision | Typical use | +| --- | --- | --- | +| Phase A | Inline MCP elicitation | The reviewer is present while the call waits. | +| Phase B | A separate review action | The call returns pending while a reviewer decides. | ## Complete Flow -The numbered steps below trace a full approval cycle from initial call to approved retry. - -``` -1. Agent calls some_module(args) - → apcore calls handler.request_approval(ApprovalRequest) - → handler generates approval_id (UUID v4) - → handler.save_pending(approval_id, module_id, args) → stored - → handler fires notify_callback(approval_id, module_id, args) [fire-and-forget] - → returns ApprovalResult(status="pending", approval_id="abc-123") - → apcore raises ApprovalPendingError(approval_id="abc-123") - → bridge returns: { errorType: "APPROVAL_PENDING", details: { approvalId: "abc-123" } } - -2. Agent polls: - __apcore_approval_check({ "approval_id": "abc-123" }) - → { "approval_id": "abc-123", "status": "pending" } - -3. External system resolves (out of band): - # Python - store.resolve("abc-123", approved=True) - - # TypeScript - await store.resolve("abc-123", { approved: true }) - - # Rust - store.resolve("abc-123", true, None).await - -4. Agent polls again: - __apcore_approval_check({ "approval_id": "abc-123" }) - → { "approval_id": "abc-123", "status": "approved" } - -5. Agent retries: - some_module(args, _meta={ "approvalId": "abc-123" }) - → apcore calls handler.check_approval("abc-123") - → store.get_result("abc-123") → { approved: true } - → execution proceeds normally -``` - -### Rejection path - -If the external system rejects: - -``` - store.resolve("abc-123", approved=False, reason="Not authorized") # Python - await store.resolve("abc-123", { approved: false, reason: "Not authorized" }) # TypeScript - store.resolve("abc-123", false, Some("Not authorized")).await # Rust -``` +1. Call a tool that requires approval. The tool returns `isError: true` and `APPROVAL_PENDING`. The result metadata contains the approval record ID and the caller's private resume token. + + ```json + { + "_meta": { + "apcore": { + "approval": { + "approvalId": "example-record-id", + "resumeToken": "" + } + } + } + } + ``` + +2. The reviewer calls the host application's `resolve` operation with `approvalId`. Notify callbacks also receive this record ID. +3. The initiating caller polls `__apcore_approval_check` with `{"approval_id": "example-record-id"}`. The result reports `pending`, `approved`, or `rejected`. +4. On approval, call the same tool with the original business arguments. Set `params._meta.approvalId` to the private `resumeToken` from the pending response. + + ```json + { + "method": "tools/call", + "params": { + "name": "notebook.archive", + "arguments": {"note_id": "n1"}, + "_meta": {"approvalId": ""} + } + } + ``` -On the next poll: -``` - → { "approval_id": "abc-123", "status": "rejected", "reason": "Not authorized" } -``` +Core checks its access and approval gates on the retry. The handler matches the trusted principal, `caller_id`, target module, and business arguments. It consumes the grant when it authorizes one invocation. A further attempt needs its own approval. -On retry with `_meta.approvalId`, the handler returns `ApprovalResult(status="rejected")` and apcore surfaces the rejection to the agent. +Use the record ID for polling, review notifications, and audit correlation. Restrict the resume token to the pending result and the caller's resumption request. ## ApprovalStore Interface -`ApprovalStore` is the persistence abstraction implemented by all store backends. All three SDKs define an identical behavioral contract; method names use snake_case (Python/Rust) or camelCase (TypeScript). +The host's `ApprovalStore` exposes enrollment, status lookup, and `resolve` by record ID. `resolve` transitions a pending record once and returns whether it recorded a decision. -### `save_pending(approval_id, module_id, arguments)` - -Persists a new pending approval record. - -- **approval_id** — UUID v4 string; generated by `StorageBackedApprovalHandler` before this call. -- **module_id** — String identifier of the module requiring approval. -- **arguments** — Dict/object of the arguments passed to the module. Stored for reference by the external approver system; NOT returned in `get_result()` (see note below). -- **Idempotency** — Must be idempotent per `approval_id`. A second call with the same `approval_id` silently no-ops or overwrites with identical data. This prevents duplicate records on network retries. -- **Initial status** — Always `"pending"`. - -### `get_result(approval_id) → Record | None` - -Retrieves the current state of an approval record. - -- Returns `None` (Python/Rust) or `null`/`undefined` (TypeScript) for unknown `approval_id` values. -- Returns a record with at minimum: `{ "approval_id": str, "status": "pending" | "approved" | "rejected" }`. -- `reason` field is included when present (set during `resolve()`). -- `arguments` are **not** included in the returned record. They are accepted in `save_pending()` for the notify callback and external UI display, then dropped after `resolve()` to reclaim memory and avoid leaking sensitive inputs. - -### `resolve(approval_id, approved, reason?) → bool` - -Resolves an approval record to a terminal state. - -- **approval_id** — Must match a previously saved pending record. -- **approved** — Boolean. `True`/`true` → `"approved"` status; `False`/`false` → `"rejected"` status. -- **reason** — Optional string. Stored and returned in subsequent `get_result()` calls. -- **Returns** — `True`/`true` if the record was successfully resolved; `False`/`false` if: - - The `approval_id` is unknown. - - The record was already resolved (idempotency guard — prevents double-resolve races). -- **Side effects** — After resolve, `arguments` MAY be dropped by the implementation. The `InMemoryApprovalStore` drops them immediately. Persistent stores should document their own eviction policy. - -### Cross-language signatures - -```python -# Python (ApprovalStore ABC) -class ApprovalStore(ABC): - @abstractmethod - async def save_pending(self, approval_id: str, module_id: str, arguments: dict) -> None: ... - - @abstractmethod - async def get_result(self, approval_id: str) -> dict | None: ... - - @abstractmethod - async def resolve(self, approval_id: str, approved: bool, reason: str | None = None) -> bool: ... -``` +A scoped store also supports the following operations. Python and Rust use snake case and TypeScript uses camel case. -```typescript -// TypeScript -interface ApprovalStore { - savePending(approvalId: string, moduleId: string, arguments: Record): Promise; - getResult(approvalId: string): Promise; - resolve(approvalId: string, options: { approved: boolean; reason?: string }): Promise; -} -``` +| Operation | Contract | +| --- | --- | +| `save_scoped_pending` | Persist a pending record with the original invocation scope, deadline, and credential verifier. | +| `get_scoped_result` | Project the status of a live record for the same trusted principal. | +| `consume_scoped` | Verify the live record, scope, and credential verifier together. Consume an approved grant as part of the same atomic operation. | -```rust -// Rust -#[async_trait] -pub trait ApprovalStore: Send + Sync { - async fn save_pending(&self, approval_id: &str, module_id: &str, arguments: serde_json::Value) -> Result<()>; - async fn get_result(&self, approval_id: &str) -> Result>; - async fn resolve(&self, approval_id: &str, approved: bool, reason: Option) -> Result; -} -``` +Store only the verifier for the resume token. Provide an allowlisted status projection for polling. Keep the arguments available to the trusted review workflow only as long as that workflow needs them. ## InMemoryApprovalStore -`InMemoryApprovalStore` is the reference implementation bundled with all three SDKs. It is provided **for testing only** and MUST NOT be used in production. - -**Why not production:** All state is lost on process restart. In a multi-instance deployment, each instance holds a disjoint store — cross-instance polls will return `None` as if the approval never existed. - -### Memory management - -Because long-lived approvals can accumulate without bound, `InMemoryApprovalStore` applies two defensive caps: - -| Parameter | Default | Description | -|---|---|---| -| `ttl_seconds` | `3600` (1 hour) | Records older than this are eligible for sweep. | -| `max_records` | `10000` | Hard cap on total stored records. | -| `sweep_interval_seconds` | `300` (5 min) | How often the background sweep task runs (where applicable). | - -- **TTL sweep** — Expired records are removed during periodic sweeps. Accessing a swept record via `get_result()` returns `None` (same as unknown). -- **max_records cap** — When the cap is reached, `save_pending()` raises `ApprovalStorageCapacityError` (Python/TypeScript) or returns an `Err(CapacityExceeded)` (Rust). This is mapped through the Error Mapper before reaching the MCP client. -- **No persistence** — Records vanish on GC, restart, or eviction. The store does not write to disk or any external service. - -### Instantiation - -```python -# Python — defaults -store = InMemoryApprovalStore() - -# Python — custom limits -store = InMemoryApprovalStore(ttl_seconds=600, max_records=500) -``` - -```typescript -// TypeScript -const store = new InMemoryApprovalStore(); -const store = new InMemoryApprovalStore({ ttlSeconds: 600, maxRecords: 500 }); -``` - -```rust -// Rust -let store = InMemoryApprovalStore::new(); -let store = InMemoryApprovalStore::with_config(InMemoryStoreConfig { - ttl_seconds: 600, - max_records: 500, - ..Default::default() -}); -``` +The bundled store is process-local. Use it for local development and tests. It expires pending and resolved records and enforces their deadlines when checking or consuming scoped approvals. ## APCoreMCP Integration -`APCoreMCP` accepts `approval_store` (Python/Rust snake_case) / `approvalStore` (TypeScript camelCase) as a constructor parameter. When provided, the factory automatically wraps it in a `StorageBackedApprovalHandler` and registers `__apcore_approval_check` as a meta-tool alongside the `__apcore_task_*` tools. - -```python -# Python -mcp = APCoreMCP("./extensions", - approval_store=InMemoryApprovalStore(), - approval_notify=my_slack_notifier, # optional -) -``` - -```typescript -// TypeScript -const mcp = new APCoreMCP(registry, { - approvalStore: new InMemoryApprovalStore(), - approvalNotify: mySlackNotifier, // optional -}); -``` - -```rust -// Rust -let mcp = APCoreMCP::builder() - .backend(executor) - .approval_store(Arc::new(InMemoryApprovalStore::new())) - .approval_notify(my_slack_notifier) // optional - .build()?; -``` +Set `approval_store` in Python, `approvalStore` in TypeScript, or `approval_store(...)` on the Rust builder. The server wraps the store in a `StorageBackedApprovalHandler` and exposes the polling meta-tool when that handler owns the Core approval gate. See the [configuration examples](../configuration.md#phase-b-storage-backed-approvals). -### Parameter precedence +Pass a registry to have the adapter set up the approval gate. Python also accepts a Core executor with a wired gate and no existing approval handler. Rust accepts an unshared Core executor with the same gate configuration. -- Passing `approval_store` auto-creates a `StorageBackedApprovalHandler` that wraps the store. This is the standard path. -- Passing `approval_handler` directly bypasses `approval_store` entirely and uses the provided handler as-is. Use this to supply a fully custom `ApprovalHandler` implementation (e.g., one backed by a message queue) without going through `StorageBackedApprovalHandler`. -- Passing both `approval_store` and `approval_handler` is a configuration error and raises `ValueError` / `ConfigurationError` at construction time. -- Passing neither leaves the approval handler as `None`; modules that require approval will have their `ApprovalPendingError` surface directly to the agent with no poll mechanism. +Use Phase B for foreground tools over stdio or Streamable HTTP. Keep the caller authenticated when serving multiple principals. A background invocation that requires this approval returns a refusal and can be retried as a foreground invocation where the tool supports foreground execution. ## `__apcore_approval_check` Meta-Tool Spec -This tool is registered automatically whenever a `StorageBackedApprovalHandler` is active. It follows the same `__apcore_` reserved-prefix convention as the async task meta-tools. - -### Tool name - -`__apcore_approval_check` - -### Input schema - -```json -{ - "type": "object", - "properties": { - "approval_id": { - "type": "string", - "description": "The approval_id returned in the APPROVAL_PENDING error details." - } - }, - "required": ["approval_id"], - "additionalProperties": false -} -``` - -### Output schema +Pass the public `approval_id` as a tool argument. The tool uses the trusted identity from the active MCP connection. A successful poll returns a JSON object in its text content. ```json -{ - "type": "object", - "properties": { - "approval_id": { "type": "string" }, - "status": { "enum": ["pending", "approved", "rejected"] }, - "reason": { "type": "string" } - }, - "required": ["approval_id", "status"] -} +{"approval_id":"example-record-id","status":"pending"} ``` -`reason` is only present when the record carries one (i.e., `resolve()` was called with a reason string). - -### is_error behaviour - -- **is_error: false** in all non-exception outcomes, including when `approval_id` is not found. Unknown IDs return `{ "approval_id": "...", "status": "rejected" }` rather than an error. This ensures agents can branch cleanly on `status` without needing separate error-path handling. -- **is_error: true** only when `approval_id` is missing or empty in the request. This is the only exception case; it indicates a malformed call rather than a normal "not found" result. - -### Example responses - -```json -// Pending -{ "approval_id": "abc-123", "status": "pending" } - -// Approved -{ "approval_id": "abc-123", "status": "approved" } - -// Rejected with reason -{ "approval_id": "abc-123", "status": "rejected", "reason": "Not authorized by policy" } - -// Unknown id — not an error, surfaces as rejected -{ "approval_id": "abc-123", "status": "rejected" } - -// Missing approval_id — is_error: true -{ "error": "INVALID_ARG", "message": "approval_id is required" } -``` +The poll contains the public ID and one of `pending`, `approved`, or `rejected`. A missing or malformed record ID is a tool error. A record unavailable to the current caller reports a rejected status. ## notify_callback Contract -The `approval_notify` / `approvalNotify` parameter accepts an optional callback that is invoked once each time `request_approval()` stores a new pending record. Its purpose is to trigger an external notification (e.g., post a Slack message, send an email) so a human approver is alerted. - -### Invocation semantics - -- Called **once per `request_approval()` call** — not on poll, not on retry. -- Called **after** `save_pending()` succeeds. -- Failures are **logged at warning level and swallowed**. The callback MUST NOT propagate exceptions to the module caller; the approval flow proceeds regardless of notification success or failure. -- The callback is fire-and-forget. `StorageBackedApprovalHandler` does not await its result (Python/TypeScript) or join its future (Rust) before returning `ApprovalResult(status="pending")`. - -### Signature - -```python -# Python — sync or async, both accepted -def notify(approval_id: str, module_id: str, arguments: dict) -> None: ... -async def notify(approval_id: str, module_id: str, arguments: dict) -> None: ... -``` - -```typescript -// TypeScript -type ApprovalNotifyCallback = ( - approvalId: string, - moduleId: string, - arguments: Record, -) => void | Promise; -``` - -```rust -// Rust — synchronous callback wrapped in Arc -pub type ApprovalNotifyCallback = - Arc; -``` - -### Example: Slack notifier - -```python -async def slack_notify(approval_id: str, module_id: str, arguments: dict) -> None: - await slack_client.post_message( - channel="#approvals", - text=f"Approval needed for `{module_id}` (id: `{approval_id}`)\nArgs: {arguments}", - ) - -mcp = APCoreMCP("./extensions", - approval_store=InMemoryApprovalStore(), - approval_notify=slack_notify, -) -``` +The notify callback receives the public approval record ID, module ID, and business arguments after persistence. Use it to deliver a review request to a trusted queue or application. The reviewer uses the record ID to resolve the decision. ## Production Store Guidance -`InMemoryApprovalStore` is not suitable for production. A production implementation must satisfy: - -1. **Persistent storage** — Records survive process restarts. Use a database (PostgreSQL, Redis, DynamoDB) or a durable key-value store. -2. **TTL / expiry on records** — Expired records must be cleaned up automatically. Most storage backends (Redis TTL, DynamoDB TTL, SQL job) support this natively. -3. **Concurrent access safety** — Multiple server instances must not corrupt each other's records. `resolve()` in particular must be atomic: only the first call for a given `approval_id` transitions the status; subsequent calls return `False`. -4. **`resolve()` atomicity** — Implement as a conditional write (e.g., `UPDATE ... WHERE status = 'pending'` in SQL; `SET NX` or Lua script in Redis). The `bool` return value depends on whether the row was actually updated. - -### Pseudocode: Redis-backed store - -```python -class RedisApprovalStore(ApprovalStore): - def __init__(self, redis: Redis, ttl_seconds: int = 86400): - self._redis = redis - self._ttl = ttl_seconds - - async def save_pending(self, approval_id, module_id, arguments): - key = f"approval:{approval_id}" - record = {"approval_id": approval_id, "module_id": module_id, "status": "pending"} - # NX = only set if key does not exist (idempotency) - await self._redis.set(key, json.dumps(record), ex=self._ttl, nx=True) - - async def get_result(self, approval_id): - raw = await self._redis.get(f"approval:{approval_id}") - return json.loads(raw) if raw else None - - async def resolve(self, approval_id, approved, reason=None): - key = f"approval:{approval_id}" - # Atomic compare-and-swap via Lua script - status = "approved" if approved else "rejected" - script = """ - local raw = redis.call('GET', KEYS[1]) - if not raw then return 0 end - local rec = cjson.decode(raw) - if rec['status'] ~= 'pending' then return 0 end - rec['status'] = ARGV[1] - if ARGV[2] ~= '' then rec['reason'] = ARGV[2] end - rec['arguments'] = nil -- drop arguments after resolve - redis.call('SET', KEYS[1], cjson.encode(rec), 'KEEPTTL') - return 1 - """ - result = await self._redis.eval(script, 1, key, status, reason or "") - return result == 1 -``` - -Key properties of the script above: -- Returns `0` (→ `False`) if the key does not exist or the record is not `pending`. -- Drops `arguments` from the stored record after resolve to reclaim memory. -- Preserves TTL on the record so it expires naturally. +Use a shared durable store when approvals must survive restarts or reach multiple server instances. Give each record an expiry. Apply `resolve` and `consume_scoped` as conditional atomic updates. For consumption, compare the approved status, deadline, invocation scope, and verifier in the same transaction that marks the grant consumed. ## Cross-SDK Conformance Notes -All three SDKs (Python, TypeScript, Rust) implement identical wire-level behavior. The following invariants MUST hold across all implementations: - -| Property | Value | -|---|---| -| `approval_id` format | UUID v4, generated by `StorageBackedApprovalHandler` (not the store) | -| `__apcore_approval_check` tool name | Exact string `__apcore_approval_check` | -| `APPROVAL_PENDING` error wire key | `errorType: "APPROVAL_PENDING"` | -| `approvalId` in error details | camelCase — `details.approvalId` (matches MCP/OpenAI convention) | -| `approval_id` in meta-tool schema | snake_case — input param and output field | -| `arguments` in `get_result()` | NOT returned (dropped after resolve) | -| Reserved tool prefix | `__apcore_` — same as `__apcore_task_*` meta-tools | -| `is_error` on unknown approval_id | `false` — status field carries `"rejected"` | -| `is_error` on missing approval_id param | `true` | - -### Naming asymmetry - -The camelCase / snake_case asymmetry between the error envelope (`details.approvalId`) and the meta-tool schema (`approval_id`) is intentional: - -- The error envelope is part of the MCP wire protocol where camelCase is the convention. -- The meta-tool input schema is exposed as a tool argument, where snake_case matches apcore's module naming conventions and is consistent with the async task meta-tools (`task_id`). - ---- - -## Contract: StorageBackedApprovalHandler.request_approval - -### Inputs -- request: ApprovalRequest, required, validates[has `module_id`, `arguments` fields] - -### Errors -- Returns `ApprovalResult(status="rejected", reason="Storage error")` — when `save_pending()` raises unexpectedly -- Returns `ApprovalResult(status="rejected", reason="Store capacity exceeded")` — when store raises `ApprovalStorageCapacityError` -- Never raises; all failure modes return a rejected ApprovalResult - -### Returns -- On success: `ApprovalResult(status="pending", approval_id=)` — always; the caller checks `_meta.approvalId` to short-circuit on retry -- The `approval_id` is a freshly generated UUID v4 (generated before calling `save_pending`) - -### Properties -- async: true -- thread_safe: true -- pure: false -- idempotent: false - ---- - -## Contract: StorageBackedApprovalHandler.check_approval - -> Called by apcore when the agent retries a call with `_meta.approvalId` set. - -### Inputs -- approval_id: str, required, validates[non-empty string] - -### Errors -- Returns `ApprovalResult(status="rejected", reason="Storage error")` — when `get_result()` raises -- Returns `ApprovalResult(status="rejected", reason="Approval not found or expired")` — when `get_result()` returns None - -### Returns -- On success: `ApprovalResult(status="approved")` when record status is `"approved"` -- On rejection: `ApprovalResult(status="rejected", reason=)` when record status is `"rejected"` -- On pending: `ApprovalResult(status="rejected", reason="Approval still pending")` — pending on retry is treated as rejection to prevent indefinite blocking - -### Properties -- async: true -- thread_safe: true -- pure: false -- idempotent: true - ---- - -## Contract: `__apcore_approval_check` handler - -> Internal handler — dispatched by the meta-tool router for tool name `__apcore_approval_check`. - -### Inputs -- approval_id: str, required, validates[non-empty string], reject_with=error tuple (is_error=true) - -### Errors -- Returns `(content, is_error=True, None)` with `{"error": "INVALID_ARG", "message": "approval_id is required"}` — when approval_id is missing or empty - -### Returns -- On success: tuple `(list[dict], is_error=False, None)` — content is JSON-serialised `{ "approval_id": str, "status": str, "reason"?: str }` -- Unknown approval_id: same tuple with `{ "approval_id": ..., "status": "rejected" }` — is_error remains false -- On storage read failure: `{ "approval_id": ..., "status": "rejected", "reason": "Storage error" }` — is_error remains false; failure is logged at warning level - -### Properties -- async: true -- thread_safe: true -- pure: false -- idempotent: true +The stock bridge shares the tool result and request metadata shape across the SDKs. Exercise the public tool endpoint with an ordinary module. Check pending discovery and polling, the approved retry, expiry and scope enforcement, and a concurrent retry in which exactly one invocation runs. Check that the resume token stays out of the status response, audit events, and logs. diff --git a/mcp/docs/features/error-mapper.md b/mcp/docs/features/error-mapper.md index 3f668624..dc25b980 100644 --- a/mcp/docs/features/error-mapper.md +++ b/mcp/docs/features/error-mapper.md @@ -133,7 +133,7 @@ Only errors derived from `ModuleError` (which are designed to be user-facing) ar - CALL_DEPTH_EXCEEDED, CIRCULAR_CALL, CALL_FREQUENCY_EXCEEDED → sanitized "Internal error occurred" message - ACL_DENIED → sanitized "Access denied", details: null - SCHEMA_VALIDATION_ERROR → multi-line bulleted message with field-level errors; details preserved -- APPROVAL_PENDING → details narrowed to `{"approvalId": ...}` (camelCase) +- APPROVAL_PENDING → safe status text. The initiating holder receives any private resume token through the [Phase B result metadata](approval-phase-b.md#complete-flow). - APPROVAL_TIMEOUT → `retryable: true` - AI guidance fields (retryable, aiGuidance, userFixable, suggestion) attached from error attributes when present and not already set - On failure: returns safe fallback dict (never raises) diff --git a/mcp/docs/prd-apcore-mcp.md b/mcp/docs/prd-apcore-mcp.md index f3a24291..73a67266 100644 --- a/mcp/docs/prd-apcore-mcp.md +++ b/mcp/docs/prd-apcore-mcp.md @@ -821,7 +821,7 @@ This feature bridges the gap between HTTP-level authentication and apcore's modu **Description:** Modules annotated with `requires_approval=True` trigger an approval gate before execution. The `ElicitationApprovalHandler` uses the MCP elicitation protocol to present approval requests to the human user via the MCP client. The user can accept or reject the request, and the result is mapped to an `ApprovalResult` that controls whether execution proceeds. Built-in handlers (`AutoApproveHandler`, `AlwaysDenyHandler`) are available for dev/testing scenarios via the upstream `apcore` library. -Three new error codes (`APPROVAL_DENIED`, `APPROVAL_TIMEOUT`, `APPROVAL_PENDING`) enable structured error handling for approval-related failures, each with specific behavior: `APPROVAL_TIMEOUT` is marked auto-retryable, `APPROVAL_PENDING` narrows response details to `approvalId` only, and `APPROVAL_DENIED` extracts the denial reason. +The approval error codes enable structured handling. `APPROVAL_TIMEOUT` is retryable, `APPROVAL_PENDING` uses a status-only diagnostic, and `APPROVAL_DENIED` extracts the denial reason. The [Phase B tool result](features/approval-phase-b.md#complete-flow) carries any resume token in metadata for the initiating caller. **User Story:** As an AI agent platform operator, I want modules that modify production data to require human approval before execution, so that I can enforce a human-in-the-loop safety net without changing module code. @@ -832,7 +832,7 @@ Three new error codes (`APPROVAL_DENIED`, `APPROVAL_TIMEOUT`, `APPROVAL_PENDING` 4. `checkApproval()` returns rejected with "Phase B not supported" since MCP elicitation is stateless. 5. CLI provides `--approval` flag with choices: `elicit` (uses `ElicitationApprovalHandler`), `auto-approve` (uses `apcore.AutoApproveHandler`), `always-deny` (uses `apcore.AlwaysDenyHandler`), `off` (default, no approval). 6. Error codes `APPROVAL_DENIED`, `APPROVAL_TIMEOUT`, `APPROVAL_PENDING` are added to the error constants. -7. `ErrorMapper` handles approval errors with specific behavior: `APPROVAL_TIMEOUT` sets `retryable=true`, `APPROVAL_PENDING` narrows details to `approvalId`, `APPROVAL_DENIED` extracts `reason` from details. +7. `ErrorMapper` marks `APPROVAL_TIMEOUT` as retryable, formats `APPROVAL_PENDING` as a safe status message, and extracts `reason` from `APPROVAL_DENIED`. 8. `ElicitationApprovalHandler`, `ApprovalRequest`, and `ApprovalResult` are exported from the public API. 9. Graceful degradation: when `apcore-js` (TypeScript) does not yet export approval handlers, `--approval auto-approve`/`--approval always-deny` fails with a descriptive error. 10. The `--approval elicit` mode works independently of the upstream library's approval system (only requires the MCP elicit callback in context). diff --git a/mcp/docs/srs-apcore-mcp.md b/mcp/docs/srs-apcore-mcp.md index cce3272f..2e640bd8 100644 --- a/mcp/docs/srs-apcore-mcp.md +++ b/mcp/docs/srs-apcore-mcp.md @@ -2789,7 +2789,7 @@ async Authenticator.authenticate(headers: dict[str, str]) -> Identity | None **Input/Trigger:** ModuleError with code matching an approval error code. **Expected Output:** -- `APPROVAL_PENDING`: Details narrowed to `{"approvalId": ...}` only. If no `approval_id`/`approvalId` in details, details set to null. +- `APPROVAL_PENDING` emits a safe status message with null details. Scoped resumption information travels in the [Phase B tool result metadata](features/approval-phase-b.md#complete-flow). - `APPROVAL_TIMEOUT`: `retryable: true` set on response. Details passed through. - `APPROVAL_DENIED`: `reason` extracted from details. If present, details set to `{"reason": ...}`. Otherwise details passed through. diff --git a/mcp/docs/tech-design-apcore-mcp.md b/mcp/docs/tech-design-apcore-mcp.md index 5a399e44..4b7a39ec 100644 --- a/mcp/docs/tech-design-apcore-mcp.md +++ b/mcp/docs/tech-design-apcore-mcp.md @@ -1932,7 +1932,7 @@ MCP Client → tools/call → ExecutionRouter → Executor | Error Code | Behavior | Wire Format | |------------|----------|-------------| -| `APPROVAL_PENDING` | Narrow details to `{approvalId}` only | `{"approvalId": "..."}` | +| `APPROVAL_PENDING` | Use a status-only diagnostic | [Phase B tool result metadata](features/approval-phase-b.md#complete-flow) carries scoped resumption information for the initiating caller. | | `APPROVAL_TIMEOUT` | Set `retryable: true` | AI agents should retry | | `APPROVAL_DENIED` | Extract `reason` from details | `{"reason": "..."}` | diff --git a/mcp/docs/test-plan-apcore-mcp.md b/mcp/docs/test-plan-apcore-mcp.md index 43759a8f..a484438c 100644 --- a/mcp/docs/test-plan-apcore-mcp.md +++ b/mcp/docs/test-plan-apcore-mcp.md @@ -3381,8 +3381,8 @@ Uses real apcore modules from `examples/extensions/` (greeting, math_calc, text_ | ID | Description | Input | Expected Result | Traces to | |----|-------------|-------|-----------------|-----------| -| TC-APPROVAL-010 | APPROVAL_PENDING narrows to approvalId | Error with `{approval_id: "abc"}` | `details: {approvalId: "abc"}` | FR-APPROVAL-002 | -| TC-APPROVAL-011 | APPROVAL_PENDING snake_case fallback (TS) | Error with `{approval_id: "xyz"}` | `details: {approvalId: "xyz"}` | FR-APPROVAL-002 | +| TC-APPROVAL-010 | APPROVAL_PENDING uses credential-free error formatting | A pending result carrying a private resume token | Generic error formatting emits the pending status. Only the initiating tool result includes the token in `_meta.apcore.approval`. | FR-APPROVAL-002 | +| TC-APPROVAL-011 | A resolved approval authorizes one invocation | Two retries using the approved grant and its original invocation scope | One invocation executes. The status response carries the public approval record ID. | FR-APPROVAL-002 | | TC-APPROVAL-012 | APPROVAL_PENDING without ID → null details | Error with `{other: "data"}` | `details: null` | FR-APPROVAL-002 | | TC-APPROVAL-013 | APPROVAL_TIMEOUT marked retryable | Error code APPROVAL_TIMEOUT | `retryable: true` | FR-APPROVAL-002 | | TC-APPROVAL-014 | APPROVAL_DENIED extracts reason | Error with `{reason: "Denied"}` | `details: {reason: "Denied"}` | FR-APPROVAL-002 | From d80659c06c665656daaab9d45b71c23e6a934218 Mon Sep 17 00:00:00 2001 From: tercel Date: Fri, 27 Nov 2026 14:17:03 +0800 Subject: [PATCH 29/36] ci: pin the Golden Path separately from Core distributions Signed-off-by: tercel --- .github/workflows/core-candidate.yml | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/.github/workflows/core-candidate.yml b/.github/workflows/core-candidate.yml index 5afdb6d9..5bab1d3a 100644 --- a/.github/workflows/core-candidate.yml +++ b/.github/workflows/core-candidate.yml @@ -9,6 +9,10 @@ on: core_sha: required: true type: string + core_example_sha: + description: Core commit containing the matching Golden Path example + required: false + type: string surfaces_sha: required: true type: string @@ -30,6 +34,10 @@ on: description: Expected Core commit, when supplied required: false type: string + core_example_sha: + description: Core commit containing the matching Golden Path example + required: false + type: string core_run_id: description: Successful APCore Core distribution verification run ID required: true @@ -56,6 +64,7 @@ jobs: runs-on: ubuntu-latest outputs: head_sha: ${{ steps.source.outputs.head_sha }} + example_sha: ${{ steps.source.outputs.example_sha }} run_id: ${{ steps.source.outputs.run_id }} steps: - name: Verify the upstream package run @@ -64,6 +73,7 @@ jobs: env: CORE_RUN_ID: ${{ inputs.core_run_id }} EXPECTED_CORE_SHA: ${{ inputs.core_sha }} + EXPECTED_EXAMPLE_SHA: ${{ inputs.core_example_sha }} GH_TOKEN: ${{ secrets.APCORE_ARTIFACT_READ_TOKEN || github.token }} run: | if [[ ! "$CORE_RUN_ID" =~ ^[0-9]+$ ]]; then @@ -86,7 +96,13 @@ jobs: echo "The Core run did not build the reviewed alpha.1 commit." >&2 exit 1 fi + example_sha="${EXPECTED_EXAMPLE_SHA:-$head_sha}" + if [[ ! "$example_sha" =~ ^[0-9a-f]{40}$ ]]; then + echo "core_example_sha must be a full commit SHA." >&2 + exit 1 + fi printf 'head_sha=%s\n' "$head_sha" >> "$GITHUB_OUTPUT" + printf 'example_sha=%s\n' "$example_sha" >> "$GITHUB_OUTPUT" printf 'run_id=%s\n' "$CORE_RUN_ID" >> "$GITHUB_OUTPUT" printf 'APCore package run %s at %s\n' "$CORE_RUN_ID" "$head_sha" @@ -196,12 +212,12 @@ jobs: python -m build --wheel --outdir "$RUNNER_TEMP/surface-wheel" python -m pip install --force-reinstall --no-deps "$RUNNER_TEMP"/surface-wheel/*.whl python -m pip check - - name: Check out the verified Core source + - name: Check out the pinned Core Golden Path if: matrix.component == 'mcp' && matrix.core == 'candidate' uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 with: repository: aiperceivable/apcore - ref: ${{ needs.verify-source.outputs.head_sha }} + ref: ${{ needs.verify-source.outputs.example_sha }} path: core-source persist-credentials: false - name: Verify the Python Golden Path with the installed packages From 1247d6e3599b4394f5b1543aa1c60c9446df8529 Mon Sep 17 00:00:00 2001 From: tercel Date: Fri, 27 Nov 2026 14:26:10 +0800 Subject: [PATCH 30/36] fix(mcp): validate TypeScript scoped approval wiring Signed-off-by: tercel --- mcp/typescript/src/index.ts | 24 ++++++++++------- .../src/server/async-task-bridge.ts | 4 +++ .../tests/server/scoped-approval.test.ts | 26 +++++++++++++++++++ 3 files changed, 45 insertions(+), 9 deletions(-) diff --git a/mcp/typescript/src/index.ts b/mcp/typescript/src/index.ts index 2acc3c0c..1d00b036 100644 --- a/mcp/typescript/src/index.ts +++ b/mcp/typescript/src/index.ts @@ -886,6 +886,9 @@ async function serveInternal( // warning is never silenced by `logLevel`. Warning only; never blocks // startup. const governanceState = tryGovernanceState(executor); + if (scopedApproval && (!governanceState?.builtinApprovalGateWired || !governanceState.approvalHandlerConfigured)) { + throw new Error("Phase B requires a wired Core approval gate"); + } if (governanceState) { const warning = formatUnprotectedControlSurfaceWarning(governanceState); if (warning) origWarn(warning); @@ -1207,6 +1210,18 @@ export async function asyncServe( const scopedApproval = configuredScopedApproval(effectiveApprovalHandler, resolvedBackend); + const registry = resolveRegistry(resolvedBackend); + const executor = await resolveExecutor(resolvedBackend, { + approvalHandler: scopedApproval?.handler ?? effectiveApprovalHandler, + strategy: resolvedStrategy, + middleware: combinedMiddleware, + acl: effectiveAcl, + }); + const governanceState = tryGovernanceState(executor); + if (scopedApproval && (!governanceState?.builtinApprovalGateWired || !governanceState.approvalHandlerConfigured)) { + throw new Error("Phase B requires a wired Core approval gate"); + } + // Apply log-level suppression (post-resolution so Config Bus values apply). if (logLevel) { const levels = ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]; @@ -1217,18 +1232,9 @@ export async function asyncServe( if (minLevel > 3) console.error = () => { }; } - const registry = resolveRegistry(resolvedBackend); - const executor = await resolveExecutor(resolvedBackend, { - approvalHandler: scopedApproval?.handler ?? effectiveApprovalHandler, - strategy: resolvedStrategy, - middleware: combinedMiddleware, - acl: effectiveAcl, - }); - // aiperceivable/apcore-mcp#15(b): see serve() for rationale — warn before // the app is built when system.control.* is reachable with no recognised // gate. Warning only; never blocks startup. - const governanceState = tryGovernanceState(executor); if (governanceState) { const warning = formatUnprotectedControlSurfaceWarning(governanceState); if (warning) origWarn(warning); diff --git a/mcp/typescript/src/server/async-task-bridge.ts b/mcp/typescript/src/server/async-task-bridge.ts index 28aa0660..b247f950 100644 --- a/mcp/typescript/src/server/async-task-bridge.ts +++ b/mcp/typescript/src/server/async-task-bridge.ts @@ -12,6 +12,7 @@ * Full spec: apcore-mcp/docs/features/async-task-bridge.md (F-043). */ +import { InvalidInputError } from "apcore-js"; import { markBackgroundApprovalContext } from "../approval-reply.js"; import type { ModuleDescriptor } from "../types.js"; import { ErrorCodes } from "../types.js"; @@ -528,6 +529,9 @@ export class AsyncTaskBridge { ); } const inputs = (rawArgs as Record | undefined) ?? {}; + if (Object.hasOwn(inputs, "_approval_token")) { + throw new InvalidInputError("Approval resumption requires a direct tool call"); + } // [A-D-222] Catch TaskLimitExceededError from manager.submit() and // surface it as a structured TASK_LIMIT_EXCEEDED envelope with // retryable=true. Mirrors Python's diff --git a/mcp/typescript/tests/server/scoped-approval.test.ts b/mcp/typescript/tests/server/scoped-approval.test.ts index e794aaa8..d00f47df 100644 --- a/mcp/typescript/tests/server/scoped-approval.test.ts +++ b/mcp/typescript/tests/server/scoped-approval.test.ts @@ -180,6 +180,13 @@ describe.skipIf(!supportsScopedCore())("scoped approval through the MCP wire", ( expect(submitted).toMatchObject({ isError: true }); expect(JSON.stringify(submitted.content)).toContain("Approval resumption requires a direct tool call"); expect(JSON.stringify(submitted)).not.toContain(syntheticToken); + const nested = await target.client.callTool({ + name: META_TOOL_NAMES.SUBMIT, + arguments: { module_id: regularId, arguments: { ...args, _approval_token: "reserved input" } }, + }); + expect(nested).toMatchObject({ isError: true }); + expect(JSON.stringify(nested.content)).toContain("Approval resumption requires a direct tool call"); + expect(JSON.stringify(nested)).not.toContain("reserved input"); } finally { await target.close(); } @@ -202,6 +209,25 @@ it.skipIf(supportsScopedCore()).each([false, true])( }, ); +it.skipIf(!supportsScopedCore()).each([false, true])( + "Phase B requires a wired Core approval gate (facade: %s)", async throughFacade => { + const info = console.info; + const registry = new core.Registry(); + const approvalStore = new InMemoryApprovalStore(); + const start = vi.spyOn(approvalStore, "start"); + const options = { approvalStore, strategy: "internal", logLevel: "ERROR" as const }; + const startup = throughFacade + ? new APCoreMCP(registry as never, options).asyncServe() + : asyncServe(registry as never, options); + await expect(startup.then(async app => { + await app.close(); + return app; + })).rejects.toThrow("Phase B requires a wired Core approval gate"); + expect(start).not.toHaveBeenCalled(); + expect(console.info).toBe(info); + }, +); + it.skipIf(!supportsScopedCore()).each([false, true])( "asyncServe wires scoped approval for Streamable HTTP (facade: %s)", async throughFacade => { const registry = new core.Registry(); From ea640758d816ded3a7d65c43fbc741ab20ccbb59 Mon Sep 17 00:00:00 2001 From: tercel Date: Fri, 27 Nov 2026 14:28:17 +0800 Subject: [PATCH 31/36] fix(mcp): protect Python approval diagnostics Signed-off-by: tercel --- .../src/apcore_mcp/server/approval_bridge.py | 98 ++++++++++++++++++- mcp/python/src/apcore_mcp/server/factory.py | 29 +++++- .../tests/server/test_scoped_approval_wire.py | 64 ++++++++++++ 3 files changed, 184 insertions(+), 7 deletions(-) diff --git a/mcp/python/src/apcore_mcp/server/approval_bridge.py b/mcp/python/src/apcore_mcp/server/approval_bridge.py index 69dbc5ed..53791927 100644 --- a/mcp/python/src/apcore_mcp/server/approval_bridge.py +++ b/mcp/python/src/apcore_mcp/server/approval_bridge.py @@ -8,14 +8,19 @@ import json import logging -from contextlib import AbstractContextManager +from collections.abc import AsyncIterator +from contextlib import AbstractContextManager, asynccontextmanager from contextvars import ContextVar from dataclasses import dataclass from typing import Any from apcore import Identity from mcp import types as mcp_types -from starlette.types import ASGIApp, Receive, Scope, Send +from mcp.server.lowlevel import Server +from mcp.server.lowlevel import server as mcp_lowlevel +from mcp.shared import session as mcp_session +from starlette.datastructures import Headers, MutableHeaders +from starlette.types import ASGIApp, Message, Receive, Scope, Send from apcore_mcp.adapters.approval import ( _approval_principal, @@ -57,6 +62,72 @@ def filter(self, record: logging.LogRecord) -> bool: _approval_response_log_filter = _ApprovalResponseLogFilter() +_sdk_approval_logs = ContextVar("sdk_approval_logs", default=False) + + +class _ApprovalRequestLogFilter(logging.Filter): + """Narrow MCP SDK diagnostics that can contain the original request.""" + + def filter(self, record: logging.LogRecord) -> bool: + if not _sdk_approval_logs.get() or not isinstance(record.msg, str): + return True + if record.pathname == mcp_session.__file__: + if record.msg.startswith("Message that failed validation:"): + return False + if not record.msg.startswith(("Failed to validate request:", "Failed to validate notification:")): + return True + elif record.pathname == mcp_lowlevel.__file__: + if record.msg == "Received message: %s" and isinstance(record.args, tuple): + return not (len(record.args) == 1 and isinstance(record.args[0], Exception)) + if not record.msg.startswith("Received exception from stream:"): + return True + else: + return True + + record.msg = "MCP request validation failed" + record.args = () + record.exc_info = None + record.exc_text = None + return True + + +_approval_request_log_filter = _ApprovalRequestLogFilter() + + +def _protect_sdk_approval_logs(server: Server) -> None: + # MCP emits its session validation warnings through the root logger. + for name in (None, mcp_session.__name__, mcp_lowlevel.__name__): + logging.getLogger(name).addFilter(_approval_request_log_filter) + lifespan = server.lifespan + + @asynccontextmanager + async def protected_lifespan(active_server: Server) -> AsyncIterator[Any]: + token = _sdk_approval_logs.set(True) + try: + async with lifespan(active_server) as value: + yield value + finally: + _sdk_approval_logs.reset(token) + + server.lifespan = protected_lifespan + + +def _safe_http_validation_error(body: bytes) -> bytes: + """Preserve the SDK's outer JSON-RPC error without its raw validation text.""" + try: + response = json.loads(body) + except ValueError: + return body + if not isinstance(response, dict) or response.get("id") != "server-error": + return body + error = response.get("error") + if not isinstance(error, dict) or error.get("code") != mcp_types.INVALID_PARAMS: + return body + message = error.get("message") + if not isinstance(message, str) or not message.startswith("Validation error:"): + return body + error["message"] = "Invalid request parameters" + return json.dumps(response, separators=(",", ":")).encode() class _ApprovalLogMiddleware: @@ -69,9 +140,30 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: await self._app(scope, receive, send) return response = _ApprovalResponseLog() + pending_start: Message | None = None + + async def send_safe(message: Message) -> None: + nonlocal pending_start + if message["type"] == "http.response.start" and message["status"] == 400: + content_type = Headers(raw=message["headers"]).get("content-type", "") + if content_type.partition(";")[0] == "application/json": + pending_start = message + return + if pending_start is not None: + start = pending_start + pending_start = None + if message["type"] == "http.response.body" and not message.get("more_body"): + body = message.get("body", b"") + safe_body = _safe_http_validation_error(body) + if safe_body is not body: + MutableHeaders(scope=start)["content-length"] = str(len(safe_body)) + message = {**message, "body": safe_body} + await send(start) + await send(message) + token = _response_log_context.set(response) try: - await self._app({**scope, _RESPONSE_LOG_SCOPE_KEY: response}, receive, send) + await self._app({**scope, _RESPONSE_LOG_SCOPE_KEY: response}, receive, send_safe) finally: _response_log_context.reset(token) diff --git a/mcp/python/src/apcore_mcp/server/factory.py b/mcp/python/src/apcore_mcp/server/factory.py index 4e41dad9..843c6510 100644 --- a/mcp/python/src/apcore_mcp/server/factory.py +++ b/mcp/python/src/apcore_mcp/server/factory.py @@ -30,7 +30,7 @@ import apcore_mcp.markdown as _markdown from apcore_mcp.adapters.annotations import AnnotationMapper from apcore_mcp.auth.middleware import _REQUEST_IDENTITY_KEY, auth_identity_var -from apcore_mcp.server.approval_bridge import ApprovalBridge, _approval_response_log +from apcore_mcp.server.approval_bridge import ApprovalBridge, _approval_response_log, _protect_sdk_approval_logs from apcore_mcp.server.async_task_bridge import RESERVED_PREFIX, AsyncTaskBridge from apcore_mcp.server.router import ExecutionRouter, _descriptor_version_hint, _matches_registered_version from apcore_mcp.server.transport import _protocol_source_var, transport_session_var @@ -593,6 +593,7 @@ def register_handlers( combined_tools.extend(async_bridge.build_meta_tools()) if approval_bridge is not None: combined_tools.extend(approval_bridge.build_meta_tools()) + _protect_sdk_approval_logs(server) regular_tool_ids = {id(tool) for tool in tools} @@ -671,9 +672,7 @@ async def send_notification(notification: dict[str, Any]) -> None: and isinstance(router, ExecutionRouter) ) credential_error = None - if "_approval_token" in (arguments or {}): - credential_error = "Send the approval credential in MCP request metadata." - elif approval_token is not _NO_APPROVAL_CREDENTIAL: + if approval_token is not _NO_APPROVAL_CREDENTIAL: if not scoped_approval: credential_error = "Scoped approval is unavailable for this call." elif not isinstance(approval_token, str) or not 0 < len(approval_token) <= 256: @@ -770,6 +769,28 @@ async def send_notification(notification: dict[str, Any]) -> None: output_schema = published.outputSchema if published is not None else None return _build_call_result(text_contents, is_error, output_schema, approval=pending_approval) + sdk_call_tool = server.request_handlers[mcp_types.CallToolRequest] + + async def check_reserved_approval_input(request: mcp_types.CallToolRequest) -> mcp_types.ServerResult: + arguments = request.params.arguments or {} + nested_arguments = ( + arguments.get("arguments") + if request.params.name in {"__apcore_task_submit", "__apcore_module_preview"} + else None + ) + if "_approval_token" in arguments or ( + isinstance(nested_arguments, dict) and "_approval_token" in nested_arguments + ): + message = mcp_types.TextContent( + type="text", text="Send the approval credential in MCP request metadata." + ) + return mcp_types.ServerResult(_build_call_result([message], True, None)) + return await sdk_call_tool(request) + + # The SDK validates the business schema before its decorated callback. + # Check reserved fields first so SDK validation cannot print them. + server.request_handlers[mcp_types.CallToolRequest] = check_reserved_approval_input + def register_resource_handlers( self, server: Server, diff --git a/mcp/python/tests/server/test_scoped_approval_wire.py b/mcp/python/tests/server/test_scoped_approval_wire.py index 76672d04..a452e92e 100644 --- a/mcp/python/tests/server/test_scoped_approval_wire.py +++ b/mcp/python/tests/server/test_scoped_approval_wire.py @@ -4,15 +4,20 @@ import asyncio import json +import logging from typing import Any import httpx import pytest from apcore import AlwaysDenyHandler, Executor, Identity, ModuleAnnotations, Registry +from mcp.server.lowlevel import Server +from mcp.shared import session as mcp_session +from starlette.responses import JSONResponse from apcore_mcp import APCoreMCP from apcore_mcp.adapters.approval import _CORE_SCOPED_APPROVAL from apcore_mcp.approval_store import InMemoryApprovalStore +from apcore_mcp.server.approval_bridge import _ApprovalLogMiddleware, _protect_sdk_approval_logs from tests.server.test_versioned_tool_wire import connected_client _TOOL = "fixture.approved_report" @@ -231,3 +236,62 @@ def test_scoped_approval_is_explicitly_unavailable_on_legacy_sse() -> None: mcp = APCoreMCP(Registry(), approval_store=InMemoryApprovalStore()) with pytest.raises(ValueError, match="legacy SSE transport"): mcp.serve(transport="sse") + + +async def test_sdk_diagnostic_filter_protects_only_the_scoped_server(caplog) -> None: + server = Server("fixture") + _protect_sdk_approval_logs(server) + root = logging.getLogger() + with caplog.at_level("DEBUG"): + async with server.lifespan(server): + for level, diagnostic in ( + (logging.WARNING, "Failed to validate request: synthetic-value"), + (logging.DEBUG, "Message that failed validation: synthetic-value"), + (logging.DEBUG, "Read stream closed by client"), + ): + root.handle(logging.LogRecord("root", level, mcp_session.__file__, 1, diagnostic, (), None)) + root.handle(logging.LogRecord( + "root", logging.WARNING, mcp_session.__file__, 1, "Failed to validate request: host diagnostic", (), None, + )) + + assert "synthetic-value" not in caplog.text + assert "MCP request validation failed" in caplog.text + assert "Read stream closed by client" in caplog.text + assert "host diagnostic" in caplog.text + + +async def test_http_diagnostic_filter_keeps_validation_envelope_and_replaces_payload() -> None: + async def example_app(scope, receive, send): + response = JSONResponse({ + "jsonrpc": "2.0", "id": "server-error", "error": {"code": -32602, "message": "Validation error: value"}, + }, status_code=400, headers={"Mcp-Session-Id": "fixture-session"}) + await response(scope, receive, send) + + transport = httpx.ASGITransport(app=_ApprovalLogMiddleware(example_app)) + async with httpx.AsyncClient(transport=transport, base_url="http://localhost") as client: + response = await client.post("/mcp") + + assert response.status_code == 400 + assert response.headers["Mcp-Session-Id"] == "fixture-session" + assert int(response.headers["content-length"]) == len(response.content) + assert response.json() == { + "jsonrpc": "2.0", "id": "server-error", "error": {"code": -32602, "message": "Invalid request parameters"}, + } + + +async def test_reserved_approval_input_is_checked_before_tool_schema_validation() -> None: + registry = Registry() + report = Report() + registry.register(_TOOL, report, metadata={"async": True}) + async with connected_client(registry, approval_store=InMemoryApprovalStore(), async_tasks=True) as session: + invalid = await session.call_tool(_TOOL, {"count": "invalid"}) + direct = await session.call_tool(_TOOL, {"count": 1, "_approval_token": "synthetic-value"}) + submitted = await session.call_tool("__apcore_task_submit", { + "module_id": _TOOL, "arguments": {"count": 1, "_approval_token": "synthetic-value"}, + }) + + assert invalid.isError and "Input validation error" in invalid.content[0].text + for result in (direct, submitted): + assert result.isError + assert result.content[0].text == "Send the approval credential in MCP request metadata." + assert report.inputs == [] From 670d9715277f3d889b3773cb7f1247536c643c2d Mon Sep 17 00:00:00 2001 From: tercel Date: Fri, 27 Nov 2026 14:28:17 +0800 Subject: [PATCH 32/36] fix(mcp): bind Rust scoped approvals to tool calls Signed-off-by: tercel --- mcp/rust/examples/stdio_noise.rs | 64 +++++++++----- mcp/rust/src/adapters/approval.rs | 78 ++++++++++++++-- mcp/rust/src/apcore_mcp.rs | 73 ++++++++++++++- mcp/rust/src/approval_store.rs | 9 ++ mcp/rust/src/server/approval_bridge.rs | 108 ++++++++++++++++++----- mcp/rust/src/server/async_task_bridge.rs | 25 ++++++ mcp/rust/src/server/router.rs | 61 +++++++++---- 7 files changed, 346 insertions(+), 72 deletions(-) diff --git a/mcp/rust/examples/stdio_noise.rs b/mcp/rust/examples/stdio_noise.rs index 07fdb614..c1566a74 100644 --- a/mcp/rust/examples/stdio_noise.rs +++ b/mcp/rust/examples/stdio_noise.rs @@ -11,6 +11,10 @@ use apcore::events::{ApCoreEvent, EventSubscriber, StdoutSubscriber}; use apcore::executor::Executor; use apcore::module::Module; use apcore::registry::registry::{ModuleDescriptor, Registry}; +use apcore_mcp::approval_store::{ + ApprovalPrincipal, ApprovalRecord, ApprovalScope, ApprovalStore, ApprovalVerifier, + InMemoryApprovalStore, StoreResult, +}; use apcore_mcp::{APCoreMCP, ServeOptions}; use async_trait::async_trait; use serde_json::{json, Value}; @@ -29,33 +33,53 @@ impl Drop for CancellationCleanup { } } -struct NoisyApprovalStore; -type StoreError = Box; +#[derive(Default)] +struct NoisyApprovalStore(InMemoryApprovalStore); #[async_trait] -impl apcore_mcp::approval_store::ApprovalStore for NoisyApprovalStore { - async fn save_pending( +impl ApprovalStore for NoisyApprovalStore { + fn supports_scoped_approval(&self) -> bool { + self.0.supports_scoped_approval() + } + + async fn save_pending(&self, id: &str, module: &str, arguments: &Value) -> StoreResult<()> { + self.0.save_pending(id, module, arguments).await + } + + async fn get_result(&self, id: &str) -> StoreResult> { + self.0.get_result(id).await + } + + async fn resolve(&self, id: &str, approved: bool, reason: Option) -> StoreResult { + self.0.resolve(id, approved, reason).await + } + + async fn save_scoped_pending( &self, - _id: &str, - _module: &str, - _arguments: &Value, - ) -> Result<(), StoreError> { - Ok(()) + id: &str, + verifier: &ApprovalVerifier, + scope: &ApprovalScope, + ) -> StoreResult<()> { + self.0.save_scoped_pending(id, verifier, scope).await } - async fn get_result( + + async fn get_scoped_result( &self, - _id: &str, - ) -> Result, StoreError> { - Ok(None) + id: &str, + principal: Option<&ApprovalPrincipal>, + ) -> StoreResult> { + self.0.get_scoped_result(id, principal).await } - async fn resolve( + + async fn consume_scoped( &self, - _id: &str, - _approved: bool, - _reason: Option, - ) -> Result { - Ok(false) + id: &str, + verifier: &ApprovalVerifier, + scope: &ApprovalScope, + ) -> StoreResult> { + self.0.consume_scoped(id, verifier, scope).await } + fn start_sweep(&self) -> Option> { struct SweepCleanup; impl Drop for SweepCleanup { @@ -177,7 +201,7 @@ fn main() -> Result<(), Box> { let executor = Arc::new(Executor::new(Arc::new(registry), Arc::new(config))); let mut builder = APCoreMCP::builder().backend(executor).transport("stdio"); if mode == "sweep" { - builder = builder.approval_store(Arc::new(NoisyApprovalStore)); + builder = builder.approval_store(Arc::new(NoisyApprovalStore::default())); } let server = builder.build()?; let options = ServeOptions { diff --git a/mcp/rust/src/adapters/approval.rs b/mcp/rust/src/adapters/approval.rs index c05b0698..c52bd32a 100644 --- a/mcp/rust/src/adapters/approval.rs +++ b/mcp/rust/src/adapters/approval.rs @@ -280,6 +280,7 @@ pub type ApprovalNotifyCallback = pub struct StorageBackedApprovalHandler { store: Arc, notify_callback: Option, + require_foreground: bool, } impl StorageBackedApprovalHandler { @@ -288,9 +289,20 @@ impl StorageBackedApprovalHandler { Self { store, notify_callback: None, + require_foreground: false, } } + /// Only the server-owned handler depends on MCP's private reply channel. + pub(crate) fn for_tool_responses(mut self) -> Self { + self.require_foreground = true; + self + } + + fn allows_foreground_scope(&self, request: &ApprovalRequest) -> bool { + !self.require_foreground || crate::server::approval_bridge::is_foreground_approval(request) + } + /// Attach an optional notification callback. /// /// The callback receives `(audit_id, module_id, arguments)` and can @@ -323,7 +335,7 @@ pub(crate) async fn scoped_approval_status( } let principal = identity.map(ApprovalPrincipal::from); match store.get_scoped_result(audit_id, principal.as_ref()).await { - Ok(Some(record)) => stored_result(record, Some(audit_id)), + Ok(Some(record)) => stored_result(&record, Some(audit_id)), Ok(None) => rejected("Approval record not found"), Err(_) => store_error(), } @@ -356,13 +368,10 @@ fn credential_verifier(credential: &str) -> ApprovalVerifier { Sha256::digest(credential.as_bytes()).into() } -fn stored_result(record: ApprovalRecord, audit_id: Option<&str>) -> ApprovalResult { +fn stored_result(record: &ApprovalRecord, audit_id: Option<&str>) -> ApprovalResult { let mut result = ApprovalResult::default(); result.status = record.status.to_string(); result.audit_id = audit_id.map(str::to_owned); - if record.status == ApprovalStatus::Rejected { - result.reason = record.reason; - } result } @@ -391,6 +400,9 @@ impl ApprovalHandler for StorageBackedApprovalHandler { if is_background_call(request) { return Ok(rejected("Background tasks do not support Phase B approval")); } + if !self.allows_foreground_scope(request) { + return Ok(rejected("Phase B approval requires a direct MCP tool call")); + } let audit_id = Uuid::new_v4().to_string(); let credential = format!("{audit_id}.{}", Uuid::new_v4().simple()); let verifier = credential_verifier(&credential); @@ -412,6 +424,7 @@ impl ApprovalHandler for StorageBackedApprovalHandler { ); } + crate::server::approval_bridge::record_pending_approval(request, &audit_id, &credential); let mut result = ApprovalResult::default(); result.status = "pending".to_string(); result.approval_id = Some(credential); @@ -426,7 +439,11 @@ impl ApprovalHandler for StorageBackedApprovalHandler { Ok(match self.store.get_result(audit_id).await { Ok(Some(record)) => { let public_id = Uuid::parse_str(audit_id).is_ok().then_some(audit_id); - stored_result(record, public_id) + let mut result = stored_result(&record, public_id); + if record.status == ApprovalStatus::Rejected { + result.reason = record.reason; + } + result } Ok(None) => rejected("Approval record not found"), Err(_) => store_error(), @@ -441,6 +458,9 @@ impl ApprovalHandler for StorageBackedApprovalHandler { if is_background_call(request) { return Ok(rejected("Background tasks do not support Phase B approval")); } + if !self.allows_foreground_scope(request) { + return Ok(rejected("Phase B approval requires a direct MCP tool call")); + } let Some(audit_id) = resume_audit_id(credential) else { return Ok(rejected("Approval credential unavailable for this call")); }; @@ -450,8 +470,11 @@ impl ApprovalHandler for StorageBackedApprovalHandler { match self.store.consume_scoped(audit_id, &verifier, &scope).await { Ok(Some(record)) => { let pending = record.status == ApprovalStatus::Pending; - let mut result = stored_result(record, Some(audit_id)); + let mut result = stored_result(&record, Some(audit_id)); if pending { + crate::server::approval_bridge::record_pending_approval( + request, audit_id, credential, + ); result.approval_id = Some(credential.to_owned()); } result @@ -603,6 +626,36 @@ mod tests { assert!(result.approval_id.is_none()); } + #[tokio::test] + async fn scoped_rejection_keeps_the_operator_note_in_the_store() { + let store = Arc::new(crate::approval_store::InMemoryApprovalStore::new()); + let handler = StorageBackedApprovalHandler::new(store.clone()); + let request = scoped_request(); + let pending = handler.request_approval(&request).await.unwrap(); + let id = pending.audit_id.unwrap(); + let note = "Sample internal review note"; + assert!(store.resolve(&id, false, Some(note.into())).await.unwrap()); + + let decision = handler + .check_approval_for_call(&pending.approval_id.unwrap(), &request) + .await + .unwrap(); + assert_eq!(decision.status, "rejected"); + assert_eq!(decision.audit_id.as_deref(), Some(id.as_str())); + assert!(decision.reason.is_none()); + assert!(decision.approval_id.is_none()); + assert_eq!( + store + .get_result(&id) + .await + .unwrap() + .unwrap() + .reason + .as_deref(), + Some(note) + ); + } + #[tokio::test] async fn status_only_store_remains_queryable_and_declines_scoped_approval() { use crate::approval_store::StoreResult; @@ -633,7 +686,16 @@ mod tests { } } - let handler = StorageBackedApprovalHandler::new(Arc::new(StatusOnly)); + let store = Arc::new(StatusOnly); + let bridge = crate::APCoreMCP::builder() + .backend(Arc::new(apcore::Registry::new())) + .approval_store(store.clone()) + .build(); + assert!( + matches!(bridge, Err(crate::apcore_mcp::APCoreMCPError::Config(message)) + if message.contains("requires a scoped approval store")) + ); + let handler = StorageBackedApprovalHandler::new(store); let id = Uuid::new_v4().to_string(); let legacy_status = handler.check_approval(&id).await.unwrap(); assert_eq!(legacy_status.status, "approved"); diff --git a/mcp/rust/src/apcore_mcp.rs b/mcp/rust/src/apcore_mcp.rs index 90ffdc94..9f657f9d 100644 --- a/mcp/rust/src/apcore_mcp.rs +++ b/mcp/rust/src/apcore_mcp.rs @@ -1857,6 +1857,11 @@ impl APCoreMCPBuilder { let retained_store = self.approval_store.clone(); let approval_handler = if let Some(store) = self.approval_store { use crate::adapters::approval::StorageBackedApprovalHandler; + if !store.supports_scoped_approval() { + return Err(APCoreMCPError::Config( + "Phase B approval requires a scoped approval store".to_string(), + )); + } let owned_executor = Arc::get_mut(&mut executor).ok_or_else(|| { APCoreMCPError::Config("Phase B approval requires an unshared Executor".to_string()) })?; @@ -1865,7 +1870,16 @@ impl APCoreMCPBuilder { "The Executor already has an approval handler".to_string(), )); } - let mut handler = StorageBackedApprovalHandler::new(store); + if !owned_executor + .governance_state() + .builtin_approval_gate_wired + { + return Err(APCoreMCPError::Config( + "Phase B approval requires the built-in approval gate in the Executor" + .to_string(), + )); + } + let mut handler = StorageBackedApprovalHandler::new(store).for_tool_responses(); if let Some(cb) = self.approval_notify_callback { handler = handler.with_notify(move |id, module, args| cb(id, module, args)); } @@ -1968,6 +1982,20 @@ impl APCoreMCPBuilder { } }); + if retained_store.is_some() + && self.config.trace + && resolved_strategy.as_ref().is_some_and(|strategy| { + !strategy.steps().iter().any(|step| { + step.builtin_gate() == Some(apcore::pipeline::BuiltinGate::Approval) + }) + }) + { + return Err(APCoreMCPError::Config( + "Phase B approval requires the built-in approval gate in the traced strategy" + .to_string(), + )); + } + Ok(APCoreMCP { config: self.config, standalone_registry, @@ -2678,6 +2706,29 @@ mod tests { verify_wire_phase_b(true).await; } + #[test] + fn phase_b_requires_the_builtin_approval_gate_for_default_and_traced_calls() { + use crate::approval_store::InMemoryApprovalStore; + + let executor = + Executor::with_strategy_name(Registry::new(), Config::default(), "internal").unwrap(); + let default = APCoreMCP::builder() + .backend(Arc::new(executor)) + .approval_store(Arc::new(InMemoryApprovalStore::new())) + .build(); + assert!(matches!(default, Err(APCoreMCPError::Config(message)) + if message.contains("built-in approval gate"))); + + let traced = APCoreMCP::builder() + .backend(Arc::new(Registry::new())) + .strategy("internal") + .trace(true) + .approval_store(Arc::new(InMemoryApprovalStore::new())) + .build(); + assert!(matches!(traced, Err(APCoreMCPError::Config(message)) + if message.contains("built-in approval gate"))); + } + #[tokio::test] async fn phase_b_approval_requires_an_identity_aware_transport() { let bridge = APCoreMCP::builder() @@ -2758,17 +2809,34 @@ mod tests { ) .unwrap(); let store = Arc::new(InMemoryApprovalStore::new()); + let notified = Arc::new(AtomicUsize::new(0)); + let notices = Arc::clone(¬ified); let bridge = APCoreMCP::builder() .backend(registry) .approval_store(store.clone()) + .approval_notify(move |_, _, _| { + notices.fetch_add(1, Ordering::SeqCst); + }) .validate_inputs(true) .build() .unwrap(); - let (server, _, _, init, _, _) = bridge.build_server_components().unwrap(); + let (server, router, tools, init, _, _) = bridge.build_server_components().unwrap(); let handler = ServerHandler::from_server(&server, init).unwrap(); let identity = apcore::Identity::new("editor".into(), "user".into(), vec![], Default::default()); let arguments = json!({"label": "draft"}); + + let explorer = + bridge.build_explorer_config(&tools, &router, "/explorer", true, "Sample", None, None); + let (content, is_error, _) = + (explorer.handle_call.unwrap())("demo.render".into(), arguments.clone()).await; + assert!(is_error); + assert!(content[0]["text"] + .as_str() + .unwrap() + .contains("Phase B approval requires a direct MCP tool call")); + assert_eq!(notified.load(Ordering::SeqCst), 0); + let call = |name, args, metadata| { handler.handle_message(json!({ "jsonrpc": "2.0", "id": 1, "method": "tools/call", @@ -2787,6 +2855,7 @@ mod tests { assert_eq!(calls.load(Ordering::SeqCst), 0); let approval = &pending["result"]["_meta"]["apcore"]["approval"]; let audit_id = approval["approvalId"].as_str().expect("public approval ID"); + assert_eq!(notified.load(Ordering::SeqCst), 1); let token = approval["resumeToken"] .as_str() .expect("caller resume credential"); diff --git a/mcp/rust/src/approval_store.rs b/mcp/rust/src/approval_store.rs index 6b78f734..b7b3b68a 100644 --- a/mcp/rust/src/approval_store.rs +++ b/mcp/rust/src/approval_store.rs @@ -93,6 +93,11 @@ pub type ApprovalVerifier = [u8; 32]; /// Pluggable storage for Phase B approval state. #[async_trait] pub trait ApprovalStore: Send + Sync + 'static { + /// Opt in only when all scoped storage operations below are implemented. + fn supports_scoped_approval(&self) -> bool { + false + } + /// Persist a new pending approval record. async fn save_pending( &self, @@ -311,6 +316,10 @@ impl Default for InMemoryApprovalStore { #[async_trait] impl ApprovalStore for InMemoryApprovalStore { + fn supports_scoped_approval(&self) -> bool { + true + } + async fn save_pending( &self, approval_id: &str, diff --git a/mcp/rust/src/server/approval_bridge.rs b/mcp/rust/src/server/approval_bridge.rs index 0452cb2b..6b953539 100644 --- a/mcp/rust/src/server/approval_bridge.rs +++ b/mcp/rust/src/server/approval_bridge.rs @@ -2,7 +2,8 @@ //! //! Symmetric with AsyncTaskBridge. -use apcore::approval::{ApprovalHandler, ApprovalResult}; +use apcore::approval::{ApprovalHandler, ApprovalRequest, ApprovalResult}; +use apcore::context::SharedData; use apcore::{ErrorCode, Identity, ModuleError}; use serde_json::{json, Value}; use std::cell::RefCell; @@ -20,46 +21,107 @@ struct PendingApproval { credential: String, } +struct ApprovalReply { + pending: Option, + confirmed: bool, +} + +struct ForegroundCall { + module_id: String, + data: SharedData, +} + tokio::task_local! { - static PENDING_APPROVAL: RefCell>; + static APPROVAL_REPLY: RefCell; + static FOREGROUND_CALL: ForegroundCall; } /// Capture the pending decision separately from ordinary result content and errors. pub(crate) async fn capture_pending_approval( operation: impl Future, ) -> (T, Option) { - PENDING_APPROVAL - .scope(RefCell::new(None), async { - let result = operation.await; - let approval = PENDING_APPROVAL.with(|pending| pending.borrow_mut().take()); - let metadata = approval.map(|approval| { - json!({"approvalId": approval.audit_id, "resumeToken": approval.credential}) - }); - (result, metadata) - }) + APPROVAL_REPLY + .scope( + RefCell::new(ApprovalReply { + pending: None, + confirmed: false, + }), + async { + let result = operation.await; + let metadata = APPROVAL_REPLY.with(|reply| { + let mut reply = reply.borrow_mut(); + let approval = reply.pending.take()?; + reply.confirmed.then(|| { + json!({"approvalId": approval.audit_id, "resumeToken": approval.credential}) + }) + }); + (result, metadata) + }, + ) .await } pub(crate) fn has_tool_response_context() -> bool { - PENDING_APPROVAL.try_with(|_| ()).is_ok() + APPROVAL_REPLY.try_with(|_| ()).is_ok() } -pub(crate) fn safe_execution_message(error: &ModuleError) -> String { - if error.code != ErrorCode::ApprovalPending { - return error.to_string(); +pub(crate) async fn run_foreground_approval( + module_id: &str, + context: &apcore::Context, + operation: impl Future, +) -> T { + if !has_tool_response_context() { + return operation.await; } - if let Some((audit_id, credential)) = error.details.get("result").and_then(|result| { - let audit_id = result.get("audit_id")?.as_str()?; - let credential = result.get("approval_id")?.as_str()?; - (resume_audit_id(credential) == Some(audit_id)).then_some((audit_id, credential)) - }) { - let _ = PENDING_APPROVAL.try_with(|pending| { - pending.replace(Some(PendingApproval { + FOREGROUND_CALL + .scope( + ForegroundCall { + module_id: module_id.to_owned(), + data: Arc::clone(&context.data), + }, + operation, + ) + .await +} + +pub(crate) fn is_foreground_approval(request: &ApprovalRequest) -> bool { + request.caller_id.is_none() + && FOREGROUND_CALL + .try_with(|call| { + call.module_id == request.module_id + && request + .context + .as_ref() + .is_some_and(|context| Arc::ptr_eq(&call.data, &context.data)) + }) + .unwrap_or(false) +} + +pub(crate) fn record_pending_approval(request: &ApprovalRequest, audit_id: &str, credential: &str) { + if is_foreground_approval(request) { + let _ = APPROVAL_REPLY.try_with(|reply| { + reply.borrow_mut().pending = Some(PendingApproval { audit_id: audit_id.to_owned(), credential: credential.to_owned(), - })); + }); }); } +} + +pub(crate) fn safe_execution_message(error: &ModuleError) -> String { + if error.code != ErrorCode::ApprovalPending { + return error.to_string(); + } + let _ = APPROVAL_REPLY.try_with(|reply| { + let mut reply = reply.borrow_mut(); + reply.confirmed = reply.pending.as_ref().is_some_and(|pending| { + error.details.get("result").is_some_and(|result| { + result.get("audit_id").and_then(Value::as_str) == Some(&pending.audit_id) + && result.get("approval_id").and_then(Value::as_str) + == Some(&pending.credential) + }) + }); + }); "APPROVAL_PENDING: Approval is pending".to_string() } diff --git a/mcp/rust/src/server/async_task_bridge.rs b/mcp/rust/src/server/async_task_bridge.rs index baa9df81..c77b84f1 100644 --- a/mcp/rust/src/server/async_task_bridge.rs +++ b/mcp/rust/src/server/async_task_bridge.rs @@ -1211,6 +1211,31 @@ mod tests { } } + #[tokio::test] + async fn explicit_task_submission_rejects_the_reserved_input_before_creating_a_task() { + let bridge = + AsyncTaskBridge::new(make_executor_with_async_approval("sample.render", false)); + let error = bridge + .handle_meta_tool( + META_TOOL_SUBMIT, + &json!({ + "module_id": "sample.render", + "arguments": {"_approval_token": "reserved field placeholder"} + }), + None, + None, + None, + None, + ) + .await + .unwrap() + .unwrap_err(); + assert!(error + .message + .contains("Background tasks do not support approval resumption")); + assert!(bridge.list_tasks(None).unwrap().is_empty()); + } + /// Regression test for [A-D-008]. /// /// `__apcore_task_submit` against a module that is NOT async-hinted diff --git a/mcp/rust/src/server/router.rs b/mcp/rust/src/server/router.rs index 5301c694..9a7a5d4b 100644 --- a/mcp/rust/src/server/router.rs +++ b/mcp/rust/src/server/router.rs @@ -779,6 +779,15 @@ impl ExecutionRouter { self.async_bridge.as_ref() } + fn has_approval_input(tool_name: &str, arguments: &Value) -> bool { + arguments.get("_approval_token").is_some() + || (tool_name == crate::server::async_task_bridge::META_TOOL_SUBMIT + && arguments + .get("arguments") + .and_then(|value| value.get("_approval_token")) + .is_some()) + } + /// Redact sensitive fields from tool inputs for safe logging. /// /// If a schema is registered for `tool_name`, uses @@ -960,6 +969,9 @@ impl ExecutionRouter { arguments: &Value, extra: Option<&Value>, ) -> (Vec, bool, Option) { + if Self::has_approval_input(tool_name, arguments) { + return Self::stream_error("Approval credentials belong in request metadata".into()); + } // [B-002] Register a CancelToken for this call so an inbound MCP // `notifications/cancelled` (forwarded into `router.cancel_call(call_id)`) // cooperatively cancels in-flight work. call_id sourced from @@ -1001,6 +1013,7 @@ impl ExecutionRouter { Some(token) if crate::adapters::approval::resume_audit_id(token).is_some() && self.supports_scoped_approval() + && crate::server::approval_bridge::has_tool_response_context() && !AsyncTaskBridge::is_reserved_id(tool_name) => { Some(token) @@ -1069,14 +1082,15 @@ impl ExecutionRouter { // dispatch below. if let Some(approval_bridge) = &self.approval_bridge { if ApprovalBridge::is_meta_tool(tool_name) { - let (value, is_error) = - if crate::server::approval_bridge::has_tool_response_context() { - approval_bridge - .check_wire_status(arguments, apcore_ctx.identity.as_ref()) - .await - } else { - approval_bridge.handle_meta_tool(tool_name, arguments).await - }; + let (value, is_error) = if approval_bridge.supports_scoped_approval() + || crate::server::approval_bridge::has_tool_response_context() + { + approval_bridge + .check_wire_status(arguments, apcore_ctx.identity.as_ref()) + .await + } else { + approval_bridge.handle_meta_tool(tool_name, arguments).await + }; let result = if is_error { Err(apcore::errors::ModuleError::new( apcore::errors::ErrorCode::GeneralInvalidInput, @@ -1218,13 +1232,17 @@ impl ExecutionRouter { } else { arguments }; - self.dispatch_stream_or_call( + crate::server::approval_bridge::run_foreground_approval( tool_name, - execution_arguments, - &context_value, - version_hint.as_deref(), &apcore_ctx, - progress_token.as_ref().zip(send_notification.as_ref()), + self.dispatch_stream_or_call( + tool_name, + execution_arguments, + &context_value, + version_hint.as_deref(), + &apcore_ctx, + progress_token.as_ref().zip(send_notification.as_ref()), + ), ) .await } @@ -1317,12 +1335,17 @@ impl ExecutionRouter { arguments: &Value, extra: Option, ) -> (Vec, bool, Option) { - let redacted = self.redact_inputs(tool_name, arguments); - tracing::debug!( - tool = tool_name, - inputs = %redacted, - "Executing tool call" - ); + if Self::has_approval_input(tool_name, arguments) { + return Self::stream_error("Approval credentials belong in request metadata".into()); + } + if !ApprovalBridge::is_meta_tool(tool_name) { + let redacted = self.redact_inputs(tool_name, arguments); + tracing::debug!( + tool = tool_name, + inputs = %redacted, + "Executing tool call" + ); + } let extra = extra.unwrap_or_else(|| CallExtra { progress_token: None, From fa3ab784dc5f69afa75c0a8e969fb8d985b187ed Mon Sep 17 00:00:00 2001 From: tercel Date: Fri, 27 Nov 2026 14:28:17 +0800 Subject: [PATCH 33/36] docs(mcp): clarify scoped approval configuration Signed-off-by: tercel --- mcp/docs/features/approval-phase-b.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/mcp/docs/features/approval-phase-b.md b/mcp/docs/features/approval-phase-b.md index 70c22eda..cf8e7a8e 100644 --- a/mcp/docs/features/approval-phase-b.md +++ b/mcp/docs/features/approval-phase-b.md @@ -26,7 +26,7 @@ Phase B requires Core's scoped approval gate and a store that can atomically ver "_meta": { "apcore": { "approval": { - "approvalId": "example-record-id", + "approvalId": "4f2c29a5-d981-4e46-9ca1-0b17535abd12", "resumeToken": "" } } @@ -35,7 +35,7 @@ Phase B requires Core's scoped approval gate and a store that can atomically ver ``` 2. The reviewer calls the host application's `resolve` operation with `approvalId`. Notify callbacks also receive this record ID. -3. The initiating caller polls `__apcore_approval_check` with `{"approval_id": "example-record-id"}`. The result reports `pending`, `approved`, or `rejected`. +3. The initiating caller polls `__apcore_approval_check` with `{"approval_id": "4f2c29a5-d981-4e46-9ca1-0b17535abd12"}`. The result reports `pending`, `approved`, or `rejected`. 4. On approval, call the same tool with the original business arguments. Set `params._meta.approvalId` to the private `resumeToken` from the pending response. ```json @@ -67,6 +67,8 @@ A scoped store also supports the following operations. Python and Rust use snake Store only the verifier for the resume token. Provide an allowlisted status projection for polling. Keep the arguments available to the trusted review workflow only as long as that workflow needs them. +A custom Rust store must return `true` from `supports_scoped_approval()` after implementing all three scoped operations. The builder rejects stores that supply only the unscoped operations. + ## InMemoryApprovalStore The bundled store is process-local. Use it for local development and tests. It expires pending and resolved records and enforces their deadlines when checking or consuming scoped approvals. @@ -75,7 +77,7 @@ The bundled store is process-local. Use it for local development and tests. It e Set `approval_store` in Python, `approvalStore` in TypeScript, or `approval_store(...)` on the Rust builder. The server wraps the store in a `StorageBackedApprovalHandler` and exposes the polling meta-tool when that handler owns the Core approval gate. See the [configuration examples](../configuration.md#phase-b-storage-backed-approvals). -Pass a registry to have the adapter set up the approval gate. Python also accepts a Core executor with a wired gate and no existing approval handler. Rust accepts an unshared Core executor with the same gate configuration. +Pass a registry to have the adapter set up the approval gate. The effective execution strategy must include Core's built-in approval gate. Python also accepts a Core executor with a wired gate and no existing approval handler. Rust accepts an unshared Core executor with the same gate configuration. Use Phase B for foreground tools over stdio or Streamable HTTP. Keep the caller authenticated when serving multiple principals. A background invocation that requires this approval returns a refusal and can be retried as a foreground invocation where the tool supports foreground execution. @@ -84,7 +86,7 @@ Use Phase B for foreground tools over stdio or Streamable HTTP. Keep the caller Pass the public `approval_id` as a tool argument. The tool uses the trusted identity from the active MCP connection. A successful poll returns a JSON object in its text content. ```json -{"approval_id":"example-record-id","status":"pending"} +{"approval_id":"4f2c29a5-d981-4e46-9ca1-0b17535abd12","status":"pending"} ``` The poll contains the public ID and one of `pending`, `approved`, or `rejected`. A missing or malformed record ID is a tool error. A record unavailable to the current caller reports a rejected status. From 8f7357acc34cc8c6a14fd13b259b7081b8b7fa89 Mon Sep 17 00:00:00 2001 From: tercel Date: Fri, 27 Nov 2026 15:44:20 +0800 Subject: [PATCH 34/36] ci(python): verify Surfaces wheels with local Toolkit Signed-off-by: tercel --- .github/workflows/python.yml | 12 +++++++++--- mcp/docs/features/approval-phase-b.md | 2 +- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/.github/workflows/python.yml b/.github/workflows/python.yml index ff4eae44..4c1674f0 100644 --- a/.github/workflows/python.yml +++ b/.github/workflows/python.yml @@ -77,11 +77,17 @@ jobs: python -m build - name: Install and import the built wheel in isolation shell: bash + env: + COMPONENT: ${{ matrix.component }} run: | - wheel=( "$PWD"/dist/*.whl ) + wheels=( "$PWD"/dist/*.whl ) temporary=$(mktemp -d) + if [[ "$COMPONENT" == a2a || "$COMPONENT" == cli ]]; then + python -m build --wheel --outdir "$temporary/wheels" "$GITHUB_WORKSPACE/toolkit/python" + wheels+=( "$temporary"/wheels/apcore_toolkit-*.whl ) + fi python -m venv "$temporary/venv" cd "$temporary" - "$temporary/venv/bin/python" -m pip install "${wheel[0]}" + "$temporary/venv/bin/python" -m pip install "${wheels[@]}" "$temporary/venv/bin/python" -m pip check - "$temporary/venv/bin/python" -c 'import importlib, sys; importlib.import_module("apcore_" + sys.argv[1])' "${{ matrix.component }}" + "$temporary/venv/bin/python" -c 'import importlib, sys; importlib.import_module("apcore_" + sys.argv[1])' "$COMPONENT" diff --git a/mcp/docs/features/approval-phase-b.md b/mcp/docs/features/approval-phase-b.md index cf8e7a8e..9dc7e419 100644 --- a/mcp/docs/features/approval-phase-b.md +++ b/mcp/docs/features/approval-phase-b.md @@ -19,7 +19,7 @@ Phase B requires Core's scoped approval gate and a store that can atomically ver ## Complete Flow -1. Call a tool that requires approval. The tool returns `isError: true` and `APPROVAL_PENDING`. The result metadata contains the approval record ID and the caller's private resume token. +1. Call a tool that requires approval. Identify a pending result by `isError: true` and the presence of `_meta.apcore.approval`. That object contains the approval record ID and the caller's private resume token. ```json { From 18ae2bb6e9812f44b2111c9e9747c29804c862e1 Mon Sep 17 00:00:00 2001 From: tercel Date: Fri, 27 Nov 2026 15:46:09 +0800 Subject: [PATCH 35/36] ci(rust): verify Surfaces crates with pinned prereleases Signed-off-by: tercel --- .github/workflows/rust.yml | 79 ++++++++++++++++++++--------- scripts/verify-rust-surface.py | 91 ++++++++++++++++++++++++++++++++++ 2 files changed, 146 insertions(+), 24 deletions(-) create mode 100644 scripts/verify-rust-surface.py diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 5ce2e242..271754d3 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -7,16 +7,25 @@ on: - '*/rust/**' - '*/conformance/**' - '.github/workflows/rust.yml' + - 'scripts/verify-rust-surface.py' pull_request: paths: - '*/rust/**' - '*/conformance/**' - '.github/workflows/rust.yml' + - 'scripts/verify-rust-surface.py' workflow_dispatch: permissions: contents: read +env: + # The released lockfiles already reference these prereleases. Bootstrap CI + # from the reviewed Core commit while those versions are unpublished. + CORE_REF: b28e1bfd01b804c8662e9e418d8487d0e08cc0ce + CORE_CRATE_VERSION: 1.0.0-alpha.1 + CORE_CRATE_SHA256: bbc1db3680f3d81b7096fa5eb70476a2c043b333681c2a7bba3597a49bbf11f6 + jobs: source: name: Rust source tests (${{ matrix.component }}) @@ -34,6 +43,14 @@ jobs: working-directory: ${{ matrix.component }}/rust steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 + with: + persist-credentials: false + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 + with: + repository: aiperceivable/apcore + ref: ${{ env.CORE_REF }} + path: .ci-apcore-core + persist-credentials: false - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 with: python-version: "3.12" @@ -48,31 +65,14 @@ jobs: ${{ matrix.component }}/rust/target key: ${{ runner.os }}-cargo-${{ matrix.component }}-${{ hashFiles('*/rust/Cargo.lock') }} - run: cargo fmt --all -- --check - - name: Check and test toolkit - if: matrix.component == 'toolkit' - run: | - cargo clippy --locked --all-targets --all-features -- -D warnings - cargo test --locked --all-features - cargo check --locked --no-default-features - - name: Check and test the surface against this checkout's toolkit - if: matrix.component != 'toolkit' + - name: Check and test against the pinned Core and checkout Toolkit shell: bash + env: + COMPONENT: ${{ matrix.component }} run: | - patch="patch.crates-io.apcore-toolkit.path='$GITHUB_WORKSPACE/toolkit/rust'" - cargo --config "$patch" metadata --format-version 1 | python -c ' - import json, sys - from pathlib import Path - expected = (Path(sys.argv[1]) / "toolkit/rust/Cargo.toml").resolve() - packages = [p for p in json.load(sys.stdin)["packages"] if p["name"] == "apcore-toolkit"] - if len(packages) != 1 or Path(packages[0]["manifest_path"]).resolve() != expected: - raise SystemExit("Consumer did not resolve the toolkit from this checkout") - ' "$GITHUB_WORKSPACE" - cargo --config "$patch" clippy --all-targets --all-features -- -D warnings - cargo --config "$patch" test --all-features - cargo --config "$patch" build --examples - if [[ "${{ matrix.component }}" == a2a ]]; then - cargo --config "$patch" check --no-default-features - fi + git -C "$GITHUB_WORKSPACE/.ci-apcore-core" rev-parse HEAD + python "$GITHUB_WORKSPACE/scripts/verify-rust-surface.py" "$COMPONENT" source \ + "$GITHUB_WORKSPACE/.ci-apcore-core/rust" package: name: Rust crate verification (${{ matrix.component }}) @@ -86,5 +86,36 @@ jobs: working-directory: ${{ matrix.component }}/rust steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 + with: + persist-credentials: false + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 + with: + repository: aiperceivable/apcore + ref: ${{ env.CORE_REF }} + path: .ci-apcore-core + persist-credentials: false + - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 + with: + python-version: "3.12" - uses: dtolnay/rust-toolchain@stable - - run: cargo package --locked + - name: Build and verify the pinned Core archive digest + working-directory: .ci-apcore-core/rust + shell: bash + env: + CARGO_TARGET_DIR: ${{ runner.temp }}/core-dependency-target + run: | + git rev-parse HEAD + rustup toolchain install 1.86.0 --profile minimal + # Core was already verified upstream. Reproduce the same archive. + cargo +1.86.0 package --locked --all-features --no-verify + archive="$CARGO_TARGET_DIR/package/apcore-$CORE_CRATE_VERSION.crate" + printf '%s %s\n' "$CORE_CRATE_SHA256" "$archive" | sha256sum --check + mkdir "$RUNNER_TEMP/core-dependency" + tar -xzf "$archive" --strip-components=1 -C "$RUNNER_TEMP/core-dependency" + - name: Package and verify the Surface crate + shell: bash + env: + COMPONENT: ${{ matrix.component }} + run: | + python "$GITHUB_WORKSPACE/scripts/verify-rust-surface.py" "$COMPONENT" package \ + "$RUNNER_TEMP/core-dependency" diff --git a/scripts/verify-rust-surface.py b/scripts/verify-rust-surface.py new file mode 100644 index 00000000..05ead0cd --- /dev/null +++ b/scripts/verify-rust-surface.py @@ -0,0 +1,91 @@ +"""Run ordinary Rust CI against pinned local prerelease inputs.""" + +from __future__ import annotations + +import argparse +import json +import os +import subprocess +import tarfile +import tempfile +import tomllib +from pathlib import Path + + +def verify(component: str, mode: str, core: Path) -> None: + repo = Path(__file__).resolve().parents[1] + core = core.resolve(strict=True) + with tempfile.TemporaryDirectory(prefix="surface-rust-ci-") as temporary: + scratch = Path(temporary).resolve() + # Cargo path patches replace two registry entries in the lock. Keep + # that lock in a disposable snapshot, including for crate packaging. + archive = scratch / "source.tar" + subprocess.run(["git", "archive", "--output", archive, "HEAD"], cwd=repo, check=True) + with tarfile.open(archive) as source: + source.extractall(scratch, filter="data") + archive.unlink() + + crate = scratch / component / "rust" + toolkit = scratch / "toolkit" / "rust" + expected = {"apcore": core, "apcore-toolkit": toolkit} + patches = ["--config", f"patch.crates-io.apcore.path={json.dumps(core.as_posix())}"] + if component != "toolkit": + patches += ["--config", f"patch.crates-io.apcore-toolkit.path={json.dumps(toolkit.as_posix())}"] + + env = os.environ.copy() + env.setdefault("CARGO_TARGET_DIR", str(repo / component / "rust" / "target")) + host = next( + line.removeprefix("host: ") + for line in subprocess.check_output(["rustc", "-vV"], text=True, env=env).splitlines() + if line.startswith("host: ") + ) + lockfile = crate / "Cargo.lock" + locked = tomllib.loads(lockfile.read_text(encoding="utf-8"))["package"] + metadata = json.loads(subprocess.check_output( + ["cargo", "metadata", *patches, "--all-features", "--format-version", "1", "--filter-platform", host], + cwd=crate, + env=env, + )) + for name, path in expected.items(): + versions = [entry["version"] for entry in locked if entry["name"] == name] + matches = [entry for entry in metadata["packages"] if entry["name"] == name] + if ( + len(versions) != 1 + or len(matches) != 1 + or matches[0]["version"] != versions[0] + or Path(matches[0]["manifest_path"]).resolve() != path / "Cargo.toml" + ): + raise ValueError(f"Expected one locked {name} version {versions!r} at {path}") + print(f"Resolved {name} {versions[0]} at {matches[0]['manifest_path']}", flush=True) + + # The path substitution must not advance or otherwise change any + # locked dependencies. Only the local source identifiers disappear. + for entry in locked: + if entry["name"] in expected: + entry.pop("source", None) + entry.pop("checksum", None) + if tomllib.loads(lockfile.read_text(encoding="utf-8"))["package"] != locked: + raise ValueError("Cargo changed the locked dependency graph while applying the prerelease inputs") + + if mode == "package": + subprocess.run(["cargo", "package", *patches, "--locked"], cwd=crate, env=env, check=True) + return + commands = [ + ["clippy", "--locked", "--all-targets", "--all-features", "--", "-D", "warnings"], + ["test", "--locked", "--all-features"], + ] + if component != "toolkit": + commands.append(["build", "--locked", "--examples"]) + if component in {"toolkit", "a2a"}: + commands.append(["check", "--locked", "--no-default-features"]) + for subcommand, *args in commands: + subprocess.run(["cargo", subcommand, *patches, *args], cwd=crate, env=env, check=True) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("component", choices=["toolkit", "mcp", "a2a", "cli"]) + parser.add_argument("mode", choices=["source", "package"]) + parser.add_argument("core", type=Path) + options = parser.parse_args() + verify(options.component, options.mode, options.core) From 18946f7186975c1afdb6d3fe58497314fd725ac1 Mon Sep 17 00:00:00 2001 From: tercel Date: Fri, 27 Nov 2026 15:49:14 +0800 Subject: [PATCH 36/36] ci(typescript): test unpublished Toolkit with local archives Signed-off-by: tercel --- .github/workflows/typescript.yml | 65 ++++++++++++++----- .../tests/prometheus-server.test.ts | 4 +- 2 files changed, 52 insertions(+), 17 deletions(-) diff --git a/.github/workflows/typescript.yml b/.github/workflows/typescript.yml index 2a746d2b..0f1896b0 100644 --- a/.github/workflows/typescript.yml +++ b/.github/workflows/typescript.yml @@ -33,23 +33,43 @@ jobs: - uses: pnpm/action-setup@v4 with: version: '10.30.1' - - name: Install pinned dependencies - run: pnpm install --frozen-lockfile - - name: Build and link the toolkit from this checkout - if: matrix.component != 'toolkit' + - &install-dependencies + name: Install dependencies with the checkout's Toolkit + shell: bash run: | toolkit="$GITHUB_WORKSPACE/toolkit/typescript" + if [[ "$PWD" == "$toolkit" ]]; then + pnpm install --frozen-lockfile + exit + fi + pnpm --dir "$toolkit" install --frozen-lockfile pnpm --dir "$toolkit" build - pnpm link "$toolkit" - node --input-type=module <<'JS' + + # Use the local Toolkit before pnpm attempts to fetch the registry + # artifact. Restore both inputs before running build or pack. + saved=$(mktemp -d) + cp package.json pnpm-lock.yaml "$saved/" + trap 'cp "$saved/package.json" "$saved/pnpm-lock.yaml" .; rm -rf "$saved"' EXIT + TOOLKIT="$toolkit" node --input-type=module <<'JS' + import { readFileSync, writeFileSync } from 'node:fs'; + + const file = 'package.json'; + const manifest = JSON.parse(readFileSync(file, 'utf8')); + manifest.pnpm ??= {}; + manifest.pnpm.overrides ??= {}; + manifest.pnpm.overrides['apcore-toolkit'] = 'link:' + process.env.TOOLKIT; + writeFileSync(file, JSON.stringify(manifest, null, 2) + '\n'); + JS + pnpm install --no-frozen-lockfile + TOOLKIT="$toolkit" node --input-type=module <<'JS' + import assert from 'node:assert/strict'; import { realpathSync } from 'node:fs'; import { resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; - const expected = realpathSync(resolve(process.env.GITHUB_WORKSPACE, 'toolkit/typescript/dist/index.js')); - if (realpathSync(fileURLToPath(import.meta.resolve('apcore-toolkit'))) !== expected) { - throw new Error('Consumer did not resolve the toolkit from this checkout'); - } + + const expected = realpathSync(resolve(process.env.TOOLKIT, 'dist/index.js')); + assert.equal(realpathSync(fileURLToPath(import.meta.resolve('apcore-toolkit'))), expected); JS - name: Run the toolkit source checks if: matrix.component == 'toolkit' @@ -86,19 +106,34 @@ jobs: - uses: pnpm/action-setup@v4 with: version: '10.30.1' - - run: pnpm install --frozen-lockfile + - *install-dependencies - run: pnpm build - name: Pack and install as an external consumer shell: bash + env: + COMPONENT: ${{ matrix.component }} run: | temporary=$(mktemp -d) pnpm pack --pack-destination "$temporary" - archive=( "$temporary"/*.tgz ) + if [[ "$COMPONENT" != toolkit ]]; then + toolkit="$GITHUB_WORKSPACE/toolkit/typescript" + pnpm --dir "$toolkit" pack --pack-destination "$temporary" + fi + archives=( "$temporary"/*.tgz ) + toolkit_archive=( "$temporary"/apcore-toolkit-*.tgz ) cd "$temporary" npm init -y - npm install "${archive[0]}" - node --input-type=module - 'apcore-${{ matrix.component }}' <<'JS' - const name = process.argv[2]; + npm install "${archives[@]}" + node --input-type=module - "apcore-$COMPONENT" "${toolkit_archive[0]}" <<'JS' + import assert from 'node:assert/strict'; + import { readFileSync, realpathSync } from 'node:fs'; + import { resolve } from 'node:path'; + + const [, , name, toolkitArchive] = process.argv; + const lock = JSON.parse(readFileSync('package-lock.json', 'utf8')); + const lockedToolkit = lock.packages['node_modules/apcore-toolkit'].resolved; + assert.ok(lockedToolkit.startsWith('file:')); + assert.equal(realpathSync(resolve(lockedToolkit.slice('file:'.length))), realpathSync(toolkitArchive)); await import(name); if (name === 'apcore-toolkit') await import(name + '/browser'); JS diff --git a/toolkit/typescript/tests/prometheus-server.test.ts b/toolkit/typescript/tests/prometheus-server.test.ts index 856d1e5d..c3b4f064 100644 --- a/toolkit/typescript/tests/prometheus-server.test.ts +++ b/toolkit/typescript/tests/prometheus-server.test.ts @@ -104,7 +104,7 @@ describe('createPrometheusServer', () => { let ready = false; const server = createPrometheusServer({ metricsPath: '/private/scrape', - renderMetrics: () => 'apcore_requests_total{route="測試"} 1\n', + renderMetrics: () => 'apcore_requests_total{route="\u6e2c\u8a66"} 1\n', isReady: () => ready, }); const port = await listen(server); @@ -113,7 +113,7 @@ describe('createPrometheusServer', () => { expect(reply.status).toBe(200); expect(reply.headers['content-type']).toBe('text/plain; version=0.0.4; charset=utf-8'); expect(reply.headers['content-length']).toBe(String(reply.body.length)); - expect(reply.body.toString()).toBe('apcore_requests_total{route="測試"} 1\n'); + expect(reply.body.toString()).toBe('apcore_requests_total{route="\u6e2c\u8a66"} 1\n'); expect((await scrape(port, '/private/scrape/', 'GET')).status).toBe(404); expect((await scrape(port, '/metrics')).status).toBe(404); expect((await scrape(port, '/healthz?verbose=false')).body.toString()).toBe('OK');