Compare commits
17
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4e7440f25e | ||
|
|
44774883a0 | ||
|
|
a0365bb80b | ||
|
|
2499016dc7 | ||
|
|
f613250fd3 | ||
|
|
862cde8559 | ||
|
|
49c8af24ed | ||
|
|
a965bc4137 | ||
|
|
47a6e54660 | ||
|
|
206ca784f7 | ||
|
|
a438c1df42 | ||
|
|
aed83268a0 | ||
|
|
12d8a3d490 | ||
|
|
e57ab47c05 | ||
|
|
1baeefe889 | ||
|
|
9567bbf3aa | ||
|
|
54ce770682 |
No files matched your search
+10
-38
@@ -11,6 +11,12 @@ on:
|
|||||||
options: [story, feature]
|
options: [story, feature]
|
||||||
default: story
|
default: story
|
||||||
required: true
|
required: true
|
||||||
|
deploy_target:
|
||||||
|
description: Deployment target for this run
|
||||||
|
type: choice
|
||||||
|
options: [none, production]
|
||||||
|
default: none
|
||||||
|
required: true
|
||||||
push:
|
push:
|
||||||
branches:
|
branches:
|
||||||
- main
|
- main
|
||||||
@@ -81,6 +87,9 @@ jobs:
|
|||||||
cargo run -p crank-metrics --bin crank-metrics-contract -- --check
|
cargo run -p crank-metrics --bin crank-metrics-contract -- --check
|
||||||
python3 scripts/check-metrics-boundaries.py --root .
|
python3 scripts/check-metrics-boundaries.py --root .
|
||||||
|
|
||||||
|
- name: Run tooling unit tests
|
||||||
|
run: python3 -m unittest discover -s tests/unit
|
||||||
|
|
||||||
- name: Check Capability Inventory
|
- name: Check Capability Inventory
|
||||||
run: |
|
run: |
|
||||||
required_args=""
|
required_args=""
|
||||||
@@ -145,50 +154,15 @@ jobs:
|
|||||||
docker --version
|
docker --version
|
||||||
|
|
||||||
|
|
||||||
- name: Detect UI changes
|
|
||||||
id: ui-diff
|
|
||||||
env:
|
|
||||||
FEATURE_VALIDATION: ${{ inputs.validation_level == 'feature' || contains(gitea.event.pull_request.labels.*.name, 'feature-ready') }}
|
|
||||||
BASE_SHA: ${{ gitea.event.pull_request.base.sha || gitea.event.before }}
|
|
||||||
run: |
|
|
||||||
run_ui=true
|
|
||||||
reason="no reliable base revision; checking UI conservatively"
|
|
||||||
|
|
||||||
if [ "$FEATURE_VALIDATION" = "true" ]; then
|
|
||||||
reason="feature validation requested"
|
|
||||||
elif [[ ! "$BASE_SHA" =~ ^([0-9a-fA-F]{40}|[0-9a-fA-F]{64})$ ]] || [[ "$BASE_SHA" =~ ^0+$ ]]; then
|
|
||||||
: # Keep the conservative default when the event has no usable base.
|
|
||||||
else
|
|
||||||
if ! git cat-file -e "$BASE_SHA^{commit}" 2>/dev/null; then
|
|
||||||
git fetch --no-tags --depth=1 origin "$BASE_SHA" >/dev/null 2>&1 || true
|
|
||||||
fi
|
|
||||||
if git cat-file -e "$BASE_SHA^{commit}" 2>/dev/null && git diff --quiet "$BASE_SHA" HEAD -- apps/ui/ crank-community.png; then
|
|
||||||
run_ui=false
|
|
||||||
reason="UI inputs are unchanged from the event base"
|
|
||||||
else
|
|
||||||
reason="apps/ui changed or the base comparison was unavailable"
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
|
|
||||||
echo "run_ui=$run_ui" >> "$GITHUB_OUTPUT"
|
|
||||||
if [ "$run_ui" = "false" ]; then
|
|
||||||
echo "UI checks not applicable: $reason."
|
|
||||||
else
|
|
||||||
echo "Running UI checks: $reason."
|
|
||||||
fi
|
|
||||||
|
|
||||||
- name: Install UI dependencies
|
- name: Install UI dependencies
|
||||||
if: steps.ui-diff.outputs.run_ui == 'true'
|
|
||||||
working-directory: apps/ui
|
working-directory: apps/ui
|
||||||
run: npm ci
|
run: npm ci
|
||||||
|
|
||||||
- name: Audit UI dependencies
|
- name: Audit UI dependencies
|
||||||
if: steps.ui-diff.outputs.run_ui == 'true'
|
|
||||||
working-directory: apps/ui
|
working-directory: apps/ui
|
||||||
run: npm audit --audit-level=high
|
run: npm audit --audit-level=high
|
||||||
|
|
||||||
- name: Build UI bundle
|
- name: Build UI bundle
|
||||||
if: steps.ui-diff.outputs.run_ui == 'true'
|
|
||||||
working-directory: apps/ui
|
working-directory: apps/ui
|
||||||
run: npm run build
|
run: npm run build
|
||||||
|
|
||||||
@@ -238,8 +212,6 @@ jobs:
|
|||||||
docker info
|
docker info
|
||||||
- name: Install dependency policy tool
|
- name: Install dependency policy tool
|
||||||
run: cargo install cargo-deny --version 0.20.2 --locked
|
run: cargo install cargo-deny --version 0.20.2 --locked
|
||||||
- name: Run tooling unit tests
|
|
||||||
run: python3 -m unittest discover -s tests/unit
|
|
||||||
- name: Check dependency licenses and advisories
|
- name: Check dependency licenses and advisories
|
||||||
run: cargo deny --locked check advisories bans licenses sources
|
run: cargo deny --locked check advisories bans licenses sources
|
||||||
- name: Run offline OpenAPI support corpus gate
|
- name: Run offline OpenAPI support corpus gate
|
||||||
@@ -533,7 +505,7 @@ jobs:
|
|||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
needs:
|
needs:
|
||||||
- required-checks
|
- required-checks
|
||||||
if: ${{ gitea.event_name == 'push' && gitea.ref == 'refs/heads/main' }}
|
if: ${{ gitea.event_name == 'workflow_dispatch' && gitea.ref == 'refs/heads/main' && inputs.validation_level == 'feature' && inputs.deploy_target == 'production' }}
|
||||||
env:
|
env:
|
||||||
REGISTRY: git.itexp.me
|
REGISTRY: git.itexp.me
|
||||||
IMAGE_TAG: ${{ gitea.sha }}
|
IMAGE_TAG: ${{ gitea.sha }}
|
||||||
|
|||||||
@@ -212,7 +212,9 @@ jobs:
|
|||||||
- name: Publish release bundles, checksums, evidence, and SBOM to Gitea
|
- name: Publish release bundles, checksums, evidence, and SBOM to Gitea
|
||||||
if: startsWith(gitea.ref, 'refs/tags/v')
|
if: startsWith(gitea.ref, 'refs/tags/v')
|
||||||
env:
|
env:
|
||||||
GITEA_SERVER_URL: ${{ gitea.server_url }}
|
# gitea.server_url inside the job container is the internal http://gitea:3000 origin;
|
||||||
|
# the publisher only forwards its token to the public HTTPS origin.
|
||||||
|
GITEA_SERVER_URL: https://git.itexp.me
|
||||||
GITEA_REPOSITORY: ${{ gitea.repository }}
|
GITEA_REPOSITORY: ${{ gitea.repository }}
|
||||||
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
|
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
|
||||||
RELEASE_TAG: ${{ gitea.ref_name }}
|
RELEASE_TAG: ${{ gitea.ref_name }}
|
||||||
|
|||||||
@@ -9,9 +9,11 @@ mod integration {
|
|||||||
mod mcp_completion;
|
mod mcp_completion;
|
||||||
mod mcp_logging;
|
mod mcp_logging;
|
||||||
mod mcp_prompts;
|
mod mcp_prompts;
|
||||||
|
mod mcp_signals;
|
||||||
mod request_context;
|
mod request_context;
|
||||||
mod revision_matrix;
|
mod revision_matrix;
|
||||||
mod static_resources;
|
mod static_resources;
|
||||||
mod tool_search;
|
mod tool_search;
|
||||||
|
mod tools_lifecycle;
|
||||||
mod transport_protocol;
|
mod transport_protocol;
|
||||||
}
|
}
|
||||||
@@ -60,6 +60,31 @@ impl SharedLogWriter {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Story 3.4: a capturing writer plus the subscriber that records into it, so a test can prove that a
|
||||||
|
/// request-scoped progress token never reaches the log projection. Install it with
|
||||||
|
/// `tracing::subscriber::set_default` around the request on the `current_thread` runtime.
|
||||||
|
pub(super) fn capturing_subscriber() -> (
|
||||||
|
CapturedLogs,
|
||||||
|
impl tracing::Subscriber + Send + Sync + 'static,
|
||||||
|
) {
|
||||||
|
let writer = SharedLogWriter::default();
|
||||||
|
let subscriber = tracing_subscriber::fmt()
|
||||||
|
.with_writer(writer.clone())
|
||||||
|
.with_max_level(LevelFilter::TRACE)
|
||||||
|
.with_ansi(false)
|
||||||
|
.finish();
|
||||||
|
(CapturedLogs(writer), subscriber)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The captured log text of one scoped subscriber.
|
||||||
|
pub(super) struct CapturedLogs(SharedLogWriter);
|
||||||
|
|
||||||
|
impl CapturedLogs {
|
||||||
|
pub(super) fn output(&self) -> String {
|
||||||
|
self.0.output()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl<'a> MakeWriter<'a> for SharedLogWriter {
|
impl<'a> MakeWriter<'a> for SharedLogWriter {
|
||||||
type Writer = SharedLogGuard;
|
type Writer = SharedLogGuard;
|
||||||
|
|
||||||
|
|||||||
@@ -241,6 +241,11 @@ async fn inventory_projection_sidecar_is_provenance_only_and_names_the_projectio
|
|||||||
assert_eq!(
|
assert_eq!(
|
||||||
triples,
|
triples,
|
||||||
vec![
|
vec![
|
||||||
|
(
|
||||||
|
"server".to_owned(),
|
||||||
|
"capability".to_owned(),
|
||||||
|
"logging".to_owned()
|
||||||
|
),
|
||||||
(
|
(
|
||||||
"server".to_owned(),
|
"server".to_owned(),
|
||||||
"capability".to_owned(),
|
"capability".to_owned(),
|
||||||
@@ -262,7 +267,7 @@ async fn inventory_projection_sidecar_is_provenance_only_and_names_the_projectio
|
|||||||
"tools".to_owned()
|
"tools".to_owned()
|
||||||
)
|
)
|
||||||
],
|
],
|
||||||
"the advertised server capabilities of the current scope are `completions`, `prompts`, `resources` and `tools`"
|
"the advertised server capabilities of the current scope are `logging`, `completions`, `prompts`, `resources` and `tools`"
|
||||||
);
|
);
|
||||||
|
|
||||||
// The sidecar is not the payload: byte comparison is against the frozen file only.
|
// The sidecar is not the payload: byte comparison is against the frozen file only.
|
||||||
|
|||||||
@@ -454,6 +454,18 @@ async fn a_request_value_can_never_reach_a_notification() {
|
|||||||
"the positive control must reflect the canary in the error message, got {message:?}"
|
"the positive control must reflect the canary in the error message, got {message:?}"
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// Positive control on delivery: the event is really delivered and its body is exactly the
|
||||||
|
// closed one for a rejected request, so the canary assertions below cannot pass vacuously.
|
||||||
|
assert_eq!(
|
||||||
|
reply.notifications,
|
||||||
|
vec![expected_notification(
|
||||||
|
"warning",
|
||||||
|
"mcp.request.rejected",
|
||||||
|
"invalid_params"
|
||||||
|
)],
|
||||||
|
"a rejected request must deliver exactly one safe warning event"
|
||||||
|
);
|
||||||
|
|
||||||
// The delivered notification is exactly the closed safe body: no canary, no argument value.
|
// The delivered notification is exactly the closed safe body: no canary, no argument value.
|
||||||
for notification in &reply.notifications {
|
for notification in &reply.notifications {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
@@ -724,6 +736,45 @@ async fn the_modern_era_has_no_set_level_method() {
|
|||||||
assert!(after.notifications.is_empty());
|
assert!(after.notifications.is_empty());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// AT-3.18-01/03: a method this era does not implement is a pinned client error, so the safe event
|
||||||
|
/// of an opted-in client describes a client-side rejection, never an internal server failure.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn an_unknown_method_is_a_rejection_not_an_internal_failure() {
|
||||||
|
let endpoint = logging_endpoint().await;
|
||||||
|
let session = endpoint.legacy_session(AGENT_SLUG, &endpoint.api_key).await;
|
||||||
|
endpoint.set_level(&session, json!("info")).await;
|
||||||
|
|
||||||
|
// `server/discover` is a modern-era method, so the legacy adapter answers it with -32601.
|
||||||
|
let reply = endpoint
|
||||||
|
.legacy_post(
|
||||||
|
AGENT_SLUG,
|
||||||
|
&endpoint.api_key,
|
||||||
|
&session,
|
||||||
|
json!({
|
||||||
|
"jsonrpc": "2.0",
|
||||||
|
"id": 71,
|
||||||
|
"method": "server/discover",
|
||||||
|
"params": {}
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(
|
||||||
|
reply.error().0,
|
||||||
|
-32601,
|
||||||
|
"an unimplemented method is a pinned client error: {}",
|
||||||
|
reply.response
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
reply.notifications,
|
||||||
|
vec![expected_notification(
|
||||||
|
"warning",
|
||||||
|
"mcp.request.rejected",
|
||||||
|
"invalid_params"
|
||||||
|
)],
|
||||||
|
"a pinned client error must not be reported as an internal failure"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
/// AT-3.18-01/03 (independence): a level belongs to one client context, so a second session and a
|
/// AT-3.18-01/03 (independence): a level belongs to one client context, so a second session and a
|
||||||
/// second Agent keep their own (or no) level.
|
/// second Agent keep their own (or no) level.
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ async fn advertisement_declares_prompts_on_both_revisions() {
|
|||||||
let discover = endpoint.modern("server/discover", json!({}), None).await;
|
let discover = endpoint.modern("server/discover", json!({}), None).await;
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
discover["result"]["capabilities"]["prompts"],
|
discover["result"]["capabilities"]["prompts"],
|
||||||
json!({"listChanged": false}),
|
json!({"listChanged": true}),
|
||||||
"the modern advertisement must declare the prompts capability: {discover}"
|
"the modern advertisement must declare the prompts capability: {discover}"
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -50,7 +50,7 @@ async fn advertisement_declares_prompts_on_both_revisions() {
|
|||||||
let initialize = json_body(initialize_response).await;
|
let initialize = json_body(initialize_response).await;
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
initialize["result"]["capabilities"]["prompts"],
|
initialize["result"]["capabilities"]["prompts"],
|
||||||
json!({"listChanged": false}),
|
json!({"listChanged": true}),
|
||||||
"the legacy advertisement must declare the prompts capability: {initialize}"
|
"the legacy advertisement must declare the prompts capability: {initialize}"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,928 @@
|
|||||||
|
//! Story 3.19 acceptance tests (AT-3.19-01..03, FR-19): committed Resource/Prompt catalog changes
|
||||||
|
//! are announced to a client that asked for the signal of its revision, and the ordinary list
|
||||||
|
//! methods stay authoritative when a notification is lost.
|
||||||
|
//!
|
||||||
|
//! Everything here is the production path: the real loopback MCP endpoint, the real PostgreSQL
|
||||||
|
//! registry, the real immutable artifact store and real commits through the registry API. No stubbed
|
||||||
|
//! route, no faked notification, no seeded notification table.
|
||||||
|
|
||||||
|
#![allow(dead_code)]
|
||||||
|
|
||||||
|
mod scenarios;
|
||||||
|
|
||||||
|
use std::{
|
||||||
|
fs,
|
||||||
|
path::PathBuf,
|
||||||
|
sync::atomic::{AtomicU64, Ordering},
|
||||||
|
time::Duration,
|
||||||
|
};
|
||||||
|
|
||||||
|
use axum::http::header;
|
||||||
|
use crank_artifacts::ArtifactStore;
|
||||||
|
use crank_core::{
|
||||||
|
Agent, AgentId, AgentStatus, AgentVersion, PlatformApiKeyScope, ToolAccessMode, ToolGroup,
|
||||||
|
ToolSearchSettings, ToolSelectionPolicy,
|
||||||
|
ids::{PromptId, ResourceId},
|
||||||
|
prompt::{PromptDefinition, PromptSensitivity},
|
||||||
|
};
|
||||||
|
use crank_registry::model::{
|
||||||
|
AgentPromptBinding, CreatePromptDraftRequest, PublishPromptRequest,
|
||||||
|
SaveAgentCatalogConfigRequest,
|
||||||
|
resource::{CreateResourceDraftRequest, PublishResourceVersionRequest},
|
||||||
|
};
|
||||||
|
use crank_registry::{
|
||||||
|
AgentResourceBinding, CreateAgentDraftVersionRequest, CreateAgentRequest, PostgresRegistry,
|
||||||
|
PublishAgentRequest, PublishRequest,
|
||||||
|
};
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
use time::OffsetDateTime;
|
||||||
|
|
||||||
|
use super::common::*;
|
||||||
|
|
||||||
|
const MODERN_REVISION: &str = "2026-07-28";
|
||||||
|
const LEGACY_REVISION: &str = "2025-11-25";
|
||||||
|
|
||||||
|
const META_PROTOCOL_VERSION: &str = "io.modelcontextprotocol/protocolVersion";
|
||||||
|
const META_CLIENT_CAPABILITIES: &str = "io.modelcontextprotocol/clientCapabilities";
|
||||||
|
const META_CLIENT_INFO: &str = "io.modelcontextprotocol/clientInfo";
|
||||||
|
|
||||||
|
const RESOURCE_LIST_CHANGED: &str = "notifications/resources/list_changed";
|
||||||
|
const PROMPT_LIST_CHANGED: &str = "notifications/prompts/list_changed";
|
||||||
|
const TOOL_LIST_CHANGED: &str = "notifications/tools/list_changed";
|
||||||
|
const SUBSCRIPTIONS_ACKNOWLEDGED: &str = "notifications/subscriptions/acknowledged";
|
||||||
|
const SUBSCRIPTION_ID_KEY: &str = "io.modelcontextprotocol/subscriptionId";
|
||||||
|
|
||||||
|
const AGENT_SLUG: &str = "sales-signals";
|
||||||
|
/// A second published Agent of the same workspace: its catalog must never reach another Agent.
|
||||||
|
const OTHER_AGENT_SLUG: &str = "sales-other";
|
||||||
|
|
||||||
|
static NEXT_ROOT: AtomicU64 = AtomicU64::new(0);
|
||||||
|
|
||||||
|
/// Test-owned artifact root (0700), removed on drop.
|
||||||
|
struct TestRoot(PathBuf);
|
||||||
|
|
||||||
|
impl TestRoot {
|
||||||
|
fn new() -> Self {
|
||||||
|
let path = std::env::temp_dir().join(format!(
|
||||||
|
"crank-mcp-signals-{}-{}",
|
||||||
|
std::process::id(),
|
||||||
|
NEXT_ROOT.fetch_add(1, Ordering::Relaxed)
|
||||||
|
));
|
||||||
|
fs::create_dir_all(&path).expect("artifact root must be creatable");
|
||||||
|
let mut permissions = fs::metadata(&path).unwrap().permissions();
|
||||||
|
std::os::unix::fs::PermissionsExt::set_mode(&mut permissions, 0o700);
|
||||||
|
fs::set_permissions(&path, permissions).expect("artifact root must be private");
|
||||||
|
Self(path)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for TestRoot {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
let _ = fs::remove_dir_all(&self.0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The published fixture: one Tool, two bound Prompts, one published but initially unbound Resource.
|
||||||
|
struct SignalsEndpoint {
|
||||||
|
client: reqwest::Client,
|
||||||
|
base_url: String,
|
||||||
|
mcp_url: String,
|
||||||
|
api_key: String,
|
||||||
|
registry: PostgresRegistry,
|
||||||
|
artifact_store: ArtifactStore,
|
||||||
|
root: TestRoot,
|
||||||
|
agent_id: AgentId,
|
||||||
|
operation: crank_core::Operation<crank_schema::Schema, crank_mapping::MappingSet>,
|
||||||
|
second_operation: crank_core::Operation<crank_schema::Schema, crank_mapping::MappingSet>,
|
||||||
|
greeting: PromptId,
|
||||||
|
review: PromptId,
|
||||||
|
extra_prompt: PromptId,
|
||||||
|
notice: ResourceId,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SignalsEndpoint {
|
||||||
|
fn modern_meta() -> Value {
|
||||||
|
json!({
|
||||||
|
META_PROTOCOL_VERSION: MODERN_REVISION,
|
||||||
|
META_CLIENT_CAPABILITIES: {},
|
||||||
|
META_CLIENT_INFO: { "name": "crank-signals-atdd", "version": "0.1.0" }
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn modern_post(&self, payload: Value) -> reqwest::Response {
|
||||||
|
self.client
|
||||||
|
.post(&self.mcp_url)
|
||||||
|
.header(header::ACCEPT, "application/json, text/event-stream")
|
||||||
|
.header(header::AUTHORIZATION, format!("Bearer {}", self.api_key))
|
||||||
|
.json(&payload)
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One modern request whose result is a JSON body (never a stream).
|
||||||
|
async fn modern(&self, method: &str, params: Value) -> Value {
|
||||||
|
let mut params = params;
|
||||||
|
params["_meta"] = Self::modern_meta();
|
||||||
|
let response = self
|
||||||
|
.client
|
||||||
|
.post(&self.mcp_url)
|
||||||
|
.header(header::ACCEPT, "application/json")
|
||||||
|
.header(header::AUTHORIZATION, format!("Bearer {}", self.api_key))
|
||||||
|
.header("MCP-Protocol-Version", MODERN_REVISION)
|
||||||
|
.header("Mcp-Method", method)
|
||||||
|
.json(&json!({"jsonrpc": "2.0", "id": 5, "method": method, "params": params}))
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let status = response.status();
|
||||||
|
let body = response.text().await.unwrap();
|
||||||
|
serde_json::from_str(&body).unwrap_or_else(|error| {
|
||||||
|
panic!("expected JSON for {method}, {status} {body:?}: {error}")
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One modern request that offers both response modes and is expected to answer a JSON body
|
||||||
|
/// (an admission or validation rejection, never a stream).
|
||||||
|
async fn modern_offering_stream(&self, method: &str, params: Value) -> Value {
|
||||||
|
let mut params = params;
|
||||||
|
params["_meta"] = Self::modern_meta();
|
||||||
|
let response = self
|
||||||
|
.client
|
||||||
|
.post(&self.mcp_url)
|
||||||
|
.header(header::ACCEPT, "application/json, text/event-stream")
|
||||||
|
.header(header::AUTHORIZATION, format!("Bearer {}", self.api_key))
|
||||||
|
.header("MCP-Protocol-Version", MODERN_REVISION)
|
||||||
|
.header("Mcp-Method", method)
|
||||||
|
.json(&json!({"jsonrpc": "2.0", "id": 9, "method": method, "params": params}))
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(response.status(), reqwest::StatusCode::OK);
|
||||||
|
let body = response.text().await.unwrap();
|
||||||
|
serde_json::from_str(&body).unwrap_or_else(|error| {
|
||||||
|
panic!("expected a JSON rejection for {method}: {body:?} {error}")
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One legacy request inside the initialized session of this Agent.
|
||||||
|
async fn legacy(&self, session: &str, method: &str, params: Value) -> Value {
|
||||||
|
let response = self
|
||||||
|
.client
|
||||||
|
.post(&self.mcp_url)
|
||||||
|
.header(header::ACCEPT, "application/json, text/event-stream")
|
||||||
|
.header(header::AUTHORIZATION, format!("Bearer {}", self.api_key))
|
||||||
|
.header("MCP-Protocol-Version", LEGACY_REVISION)
|
||||||
|
.header("MCP-Session-Id", session)
|
||||||
|
.json(&json!({"jsonrpc": "2.0", "id": 6, "method": method, "params": params}))
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let status = response.status();
|
||||||
|
let body = response.text().await.unwrap();
|
||||||
|
serde_json::from_str(&body).unwrap_or_else(|error| {
|
||||||
|
panic!("expected JSON for {method}, {status} {body:?}: {error}")
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn legacy_session(&self) -> String {
|
||||||
|
initialize_session(&self.client, &self.mcp_url, &self.api_key).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The legacy notification stream (`GET`), consumed as an SSE response.
|
||||||
|
async fn legacy_stream(&self, session: &str) -> SseResponse {
|
||||||
|
let response = self
|
||||||
|
.client
|
||||||
|
.get(&self.mcp_url)
|
||||||
|
.header(header::ACCEPT, "text/event-stream")
|
||||||
|
.header(header::AUTHORIZATION, format!("Bearer {}", self.api_key))
|
||||||
|
.header("MCP-Protocol-Version", LEGACY_REVISION)
|
||||||
|
.header("MCP-Session-Id", session)
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
SseResponse::assert_open(response).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Open the modern `subscriptions/listen` stream with an explicit filter.
|
||||||
|
async fn listen(&self, request_id: Value, filter: Value) -> SseResponse {
|
||||||
|
let params = json!({ "notifications": filter, "_meta": Self::modern_meta() });
|
||||||
|
let response = self
|
||||||
|
.client
|
||||||
|
.post(&self.mcp_url)
|
||||||
|
.header(header::ACCEPT, "text/event-stream")
|
||||||
|
.header(header::AUTHORIZATION, format!("Bearer {}", self.api_key))
|
||||||
|
.header("MCP-Protocol-Version", MODERN_REVISION)
|
||||||
|
.header("Mcp-Method", "subscriptions/listen")
|
||||||
|
.json(&json!({
|
||||||
|
"jsonrpc": "2.0",
|
||||||
|
"id": request_id,
|
||||||
|
"method": "subscriptions/listen",
|
||||||
|
"params": params
|
||||||
|
}))
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
SseResponse::assert_open(response).await
|
||||||
|
}
|
||||||
|
|
||||||
|
fn agent_version(&self, version: u32) -> AgentVersion {
|
||||||
|
AgentVersion {
|
||||||
|
agent_id: self.agent_id.clone(),
|
||||||
|
version,
|
||||||
|
status: AgentStatus::Draft,
|
||||||
|
instructions: json!({}),
|
||||||
|
tool_selection_policy: ToolSelectionPolicy::default(),
|
||||||
|
created_at: OffsetDateTime::now_utc(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn open_draft(&self, version: u32) {
|
||||||
|
self.registry
|
||||||
|
.create_agent_draft_version(CreateAgentDraftVersionRequest {
|
||||||
|
workspace_id: &test_workspace_id(),
|
||||||
|
agent_id: &self.agent_id,
|
||||||
|
version: &self.agent_version(version),
|
||||||
|
bindings: &[],
|
||||||
|
updated_at: &OffsetDateTime::now_utc(),
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.expect("a new Agent draft version opens");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Write the exact catalog config of one draft version: Tool bindings, Resource bindings and
|
||||||
|
/// Prompt bindings in the single accepted transition.
|
||||||
|
async fn configure_draft(
|
||||||
|
&self,
|
||||||
|
version: u32,
|
||||||
|
tool_bindings: &[crank_core::AgentOperationBinding],
|
||||||
|
resource_bindings: &[AgentResourceBinding],
|
||||||
|
prompt_bindings: &[AgentPromptBinding],
|
||||||
|
) {
|
||||||
|
self.configure_draft_with_policy(
|
||||||
|
version,
|
||||||
|
tool_bindings,
|
||||||
|
&ToolSelectionPolicy::default(),
|
||||||
|
resource_bindings,
|
||||||
|
prompt_bindings,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The same transition with an explicit Tool selection policy (Story 3.5: the policy is part of
|
||||||
|
/// the served `tools/list` projection).
|
||||||
|
async fn configure_draft_with_policy(
|
||||||
|
&self,
|
||||||
|
version: u32,
|
||||||
|
tool_bindings: &[crank_core::AgentOperationBinding],
|
||||||
|
tool_selection_policy: &ToolSelectionPolicy,
|
||||||
|
resource_bindings: &[AgentResourceBinding],
|
||||||
|
prompt_bindings: &[AgentPromptBinding],
|
||||||
|
) {
|
||||||
|
self.registry
|
||||||
|
.save_agent_catalog_config_editable_with_prompts(
|
||||||
|
SaveAgentCatalogConfigRequest {
|
||||||
|
workspace_id: &test_workspace_id(),
|
||||||
|
agent_id: &self.agent_id,
|
||||||
|
agent_version: version,
|
||||||
|
bindings: tool_bindings,
|
||||||
|
tool_selection_policy,
|
||||||
|
resource_bindings,
|
||||||
|
expected_state: None,
|
||||||
|
},
|
||||||
|
prompt_bindings,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.expect("the exact catalog config of the draft version saves");
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn publish_version(&self, version: u32) {
|
||||||
|
self.registry
|
||||||
|
.publish_agent(PublishAgentRequest {
|
||||||
|
workspace_id: &test_workspace_id(),
|
||||||
|
agent_id: &self.agent_id,
|
||||||
|
version,
|
||||||
|
published_at: &OffsetDateTime::now_utc(),
|
||||||
|
published_by: Some("alice"),
|
||||||
|
expected_state: None,
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.expect("the draft Agent version publishes");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn tool_bindings(&self) -> Vec<crank_core::AgentOperationBinding> {
|
||||||
|
vec![binding_for_operation(&self.operation)]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn both_tool_bindings(&self) -> Vec<crank_core::AgentOperationBinding> {
|
||||||
|
vec![
|
||||||
|
binding_for_operation(&self.operation),
|
||||||
|
binding_for_operation(&self.second_operation),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn base_prompts(&self) -> Vec<AgentPromptBinding> {
|
||||||
|
vec![
|
||||||
|
AgentPromptBinding {
|
||||||
|
prompt_id: self.greeting.clone(),
|
||||||
|
prompt_version: 1,
|
||||||
|
},
|
||||||
|
AgentPromptBinding {
|
||||||
|
prompt_id: self.review.clone(),
|
||||||
|
prompt_version: 1,
|
||||||
|
},
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn extended_prompts(&self) -> Vec<AgentPromptBinding> {
|
||||||
|
let mut prompts = self.base_prompts();
|
||||||
|
prompts.push(AgentPromptBinding {
|
||||||
|
prompt_id: self.extra_prompt.clone(),
|
||||||
|
prompt_version: 1,
|
||||||
|
});
|
||||||
|
prompts
|
||||||
|
}
|
||||||
|
|
||||||
|
fn notice_binding(&self) -> AgentResourceBinding {
|
||||||
|
AgentResourceBinding {
|
||||||
|
resource_id: self.notice.clone(),
|
||||||
|
resource_version: 1,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The draft version this Agent would open next, so the commit helpers do not depend on the
|
||||||
|
/// order the test calls them in.
|
||||||
|
async fn next_draft_version(&self) -> u32 {
|
||||||
|
self.registry
|
||||||
|
.get_agent_summary(&test_workspace_id(), &self.agent_id)
|
||||||
|
.await
|
||||||
|
.expect("the Agent summary reads")
|
||||||
|
.expect("the fixture Agent exists")
|
||||||
|
.current_draft_version
|
||||||
|
+ 1
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The committed catalog change of AT-3.19-01: one Resource binding and one Prompt binding join
|
||||||
|
/// the published Agent snapshot in a single publication.
|
||||||
|
async fn commit_resource_and_prompt_change(&self) {
|
||||||
|
let version = self.next_draft_version().await;
|
||||||
|
self.open_draft(version).await;
|
||||||
|
self.configure_draft(
|
||||||
|
version,
|
||||||
|
&self.tool_bindings(),
|
||||||
|
&[self.notice_binding()],
|
||||||
|
&self.extended_prompts(),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
self.publish_version(version).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A commit that only changes the Tool catalog: the visible Resource/Prompt projection is
|
||||||
|
/// identical, so it must not produce a Resource or Prompt signal.
|
||||||
|
async fn commit_tool_only_change(&self) {
|
||||||
|
let version = self.next_draft_version().await;
|
||||||
|
self.open_draft(version).await;
|
||||||
|
self.configure_draft(
|
||||||
|
version,
|
||||||
|
&self.both_tool_bindings(),
|
||||||
|
&[self.notice_binding()],
|
||||||
|
&self.extended_prompts(),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
self.publish_version(version).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A commit that only changes the Resource catalog: the visible Prompt projection is identical,
|
||||||
|
/// so it must produce a Resource signal only.
|
||||||
|
async fn commit_resource_only_change(&self) {
|
||||||
|
let version = self.next_draft_version().await;
|
||||||
|
self.open_draft(version).await;
|
||||||
|
self.configure_draft(
|
||||||
|
version,
|
||||||
|
&self.tool_bindings(),
|
||||||
|
&[self.notice_binding()],
|
||||||
|
&self.base_prompts(),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
self.publish_version(version).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A commit that only changes the Prompt catalog: the visible Resource projection is identical,
|
||||||
|
/// so it must produce a Prompt signal only.
|
||||||
|
async fn commit_prompt_only_change(&self) {
|
||||||
|
let version = self.next_draft_version().await;
|
||||||
|
self.open_draft(version).await;
|
||||||
|
self.configure_draft(
|
||||||
|
version,
|
||||||
|
&self.tool_bindings(),
|
||||||
|
&[self.notice_binding()],
|
||||||
|
&self.extended_prompts(),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
self.publish_version(version).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A draft-only edit: nothing is published, so no committed catalog state changed.
|
||||||
|
async fn edit_draft_without_publishing(&self) {
|
||||||
|
let version = self.next_draft_version().await;
|
||||||
|
self.open_draft(version).await;
|
||||||
|
self.configure_draft(
|
||||||
|
version,
|
||||||
|
&self.both_tool_bindings(),
|
||||||
|
&[self.notice_binding()],
|
||||||
|
&self.base_prompts(),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The reverse Tool-only commit: the second Tool binding leaves the published snapshot while the
|
||||||
|
/// visible Resource/Prompt projection stays identical.
|
||||||
|
async fn commit_tool_only_revert(&self) {
|
||||||
|
let version = self.next_draft_version().await;
|
||||||
|
self.open_draft(version).await;
|
||||||
|
self.configure_draft(
|
||||||
|
version,
|
||||||
|
&self.tool_bindings(),
|
||||||
|
&[self.notice_binding()],
|
||||||
|
&self.extended_prompts(),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
self.publish_version(version).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The search-mode Tool selection policy of this Agent: one group over the bound Tool.
|
||||||
|
fn search_policy(&self) -> ToolSelectionPolicy {
|
||||||
|
ToolSelectionPolicy {
|
||||||
|
mode: ToolAccessMode::Search,
|
||||||
|
groups: vec![ToolGroup {
|
||||||
|
id: "crm".to_owned(),
|
||||||
|
name: "CRM".to_owned(),
|
||||||
|
description: "CRM operations".to_owned(),
|
||||||
|
tool_names: vec![self.operation.name.clone()],
|
||||||
|
}],
|
||||||
|
search: ToolSearchSettings::default(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A commit that changes only the Tool selection policy: same Tool, Resource and Prompt
|
||||||
|
/// bindings, direct mode -> search mode. The served `tools/list` changes from the bound Tool to
|
||||||
|
/// `search_tools`/`call_tool`, so this is a visible Tool catalog change.
|
||||||
|
async fn commit_policy_only_change(&self) {
|
||||||
|
let version = self.next_draft_version().await;
|
||||||
|
self.open_draft(version).await;
|
||||||
|
self.configure_draft_with_policy(
|
||||||
|
version,
|
||||||
|
&self.tool_bindings(),
|
||||||
|
&self.search_policy(),
|
||||||
|
&[],
|
||||||
|
&self.base_prompts(),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
self.publish_version(version).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A search-mode commit that only adds a Tool binding: `tools/list` still serves exactly
|
||||||
|
/// `search_tools`/`call_tool`, so it must not announce a Tools change.
|
||||||
|
async fn commit_search_mode_binding_change(&self) {
|
||||||
|
let version = self.next_draft_version().await;
|
||||||
|
self.open_draft(version).await;
|
||||||
|
self.configure_draft_with_policy(
|
||||||
|
version,
|
||||||
|
&self.both_tool_bindings(),
|
||||||
|
&self.search_policy(),
|
||||||
|
&[],
|
||||||
|
&self.base_prompts(),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
self.publish_version(version).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Publish an independent Agent of the same workspace, bound to the first fixture operation, and
|
||||||
|
/// return its read-only MCP client key.
|
||||||
|
async fn publish_other_agent(&self, slug: &str) -> String {
|
||||||
|
let agent_id = test_agent_id(slug);
|
||||||
|
let now = OffsetDateTime::now_utc();
|
||||||
|
self.registry
|
||||||
|
.create_agent(CreateAgentRequest {
|
||||||
|
agent: &Agent {
|
||||||
|
id: agent_id.clone(),
|
||||||
|
workspace_id: test_workspace_id(),
|
||||||
|
slug: slug.to_owned(),
|
||||||
|
display_name: slug.to_owned(),
|
||||||
|
description: "Story 3.5 isolation fixture".to_owned(),
|
||||||
|
status: AgentStatus::Draft,
|
||||||
|
current_draft_version: 1,
|
||||||
|
latest_published_version: None,
|
||||||
|
created_at: now,
|
||||||
|
updated_at: now,
|
||||||
|
published_at: None,
|
||||||
|
},
|
||||||
|
version: &AgentVersion {
|
||||||
|
agent_id: agent_id.clone(),
|
||||||
|
version: 1,
|
||||||
|
status: AgentStatus::Draft,
|
||||||
|
instructions: json!({}),
|
||||||
|
tool_selection_policy: ToolSelectionPolicy::default(),
|
||||||
|
created_at: now,
|
||||||
|
},
|
||||||
|
bindings: &[binding_for_operation(&self.operation)],
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.expect("the second Agent is created");
|
||||||
|
self.registry
|
||||||
|
.publish_agent(PublishAgentRequest {
|
||||||
|
workspace_id: &test_workspace_id(),
|
||||||
|
agent_id: &agent_id,
|
||||||
|
version: 1,
|
||||||
|
published_at: &OffsetDateTime::now_utc(),
|
||||||
|
published_by: Some("alice"),
|
||||||
|
expected_state: None,
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.expect("the second Agent publishes");
|
||||||
|
create_platform_api_key(
|
||||||
|
&self.registry,
|
||||||
|
slug,
|
||||||
|
"mcp-signals-other",
|
||||||
|
&[PlatformApiKeyScope::Read],
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A committed Tool-only change of the independent Agent: it binds the second fixture Tool.
|
||||||
|
async fn commit_other_agent_tool_change(&self, slug: &str) {
|
||||||
|
let agent_id = test_agent_id(slug);
|
||||||
|
let version = AgentVersion {
|
||||||
|
agent_id: agent_id.clone(),
|
||||||
|
version: 2,
|
||||||
|
status: AgentStatus::Draft,
|
||||||
|
instructions: json!({}),
|
||||||
|
tool_selection_policy: ToolSelectionPolicy::default(),
|
||||||
|
created_at: OffsetDateTime::now_utc(),
|
||||||
|
};
|
||||||
|
self.registry
|
||||||
|
.create_agent_draft_version(CreateAgentDraftVersionRequest {
|
||||||
|
workspace_id: &test_workspace_id(),
|
||||||
|
agent_id: &agent_id,
|
||||||
|
version: &version,
|
||||||
|
bindings: &[],
|
||||||
|
updated_at: &OffsetDateTime::now_utc(),
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.expect("a second draft version of the other Agent opens");
|
||||||
|
self.registry
|
||||||
|
.save_agent_catalog_config_editable_with_prompts(
|
||||||
|
SaveAgentCatalogConfigRequest {
|
||||||
|
workspace_id: &test_workspace_id(),
|
||||||
|
agent_id: &agent_id,
|
||||||
|
agent_version: 2,
|
||||||
|
bindings: &self.both_tool_bindings(),
|
||||||
|
tool_selection_policy: &ToolSelectionPolicy::default(),
|
||||||
|
resource_bindings: &[],
|
||||||
|
expected_state: None,
|
||||||
|
},
|
||||||
|
&[],
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.expect("the other Agent's second catalog config saves");
|
||||||
|
self.registry
|
||||||
|
.publish_agent(PublishAgentRequest {
|
||||||
|
workspace_id: &test_workspace_id(),
|
||||||
|
agent_id: &agent_id,
|
||||||
|
version: 2,
|
||||||
|
published_at: &OffsetDateTime::now_utc(),
|
||||||
|
published_by: Some("alice"),
|
||||||
|
expected_state: None,
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.expect("the other Agent's second version publishes");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A live SSE response, read event by event.
|
||||||
|
struct SseResponse {
|
||||||
|
response: reqwest::Response,
|
||||||
|
buffer: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SseResponse {
|
||||||
|
async fn assert_open(response: reqwest::Response) -> Self {
|
||||||
|
assert_eq!(
|
||||||
|
response.status(),
|
||||||
|
reqwest::StatusCode::OK,
|
||||||
|
"the notification stream must be served"
|
||||||
|
);
|
||||||
|
let content_type = response
|
||||||
|
.headers()
|
||||||
|
.get(header::CONTENT_TYPE)
|
||||||
|
.and_then(|value| value.to_str().ok())
|
||||||
|
.unwrap_or_default()
|
||||||
|
.to_owned();
|
||||||
|
assert!(
|
||||||
|
content_type.starts_with("text/event-stream"),
|
||||||
|
"the notification stream must be an SSE response, got {content_type}"
|
||||||
|
);
|
||||||
|
Self {
|
||||||
|
response,
|
||||||
|
buffer: String::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The payload of the next `data:` frame, or `None` when nothing arrived within `timeout`.
|
||||||
|
async fn next_data(&mut self, timeout: Duration) -> Option<Value> {
|
||||||
|
loop {
|
||||||
|
if let Some(index) = self.buffer.find("\n\n") {
|
||||||
|
let block: String = self.buffer.drain(..index + 2).collect();
|
||||||
|
for line in block.lines() {
|
||||||
|
if let Some(data) = line.strip_prefix("data:") {
|
||||||
|
return Some(
|
||||||
|
serde_json::from_str(data.trim_start())
|
||||||
|
.unwrap_or_else(|error| panic!("SSE frame must be JSON: {error}")),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let chunk = tokio::time::timeout(timeout, self.response.chunk())
|
||||||
|
.await
|
||||||
|
.ok()?
|
||||||
|
.ok()??;
|
||||||
|
self.buffer.push_str(&String::from_utf8_lossy(&chunk));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The next frame within the watcher's bound.
|
||||||
|
async fn expect_frame(&mut self, what: &str) -> Value {
|
||||||
|
self.next_data(Duration::from_secs(6))
|
||||||
|
.await
|
||||||
|
.unwrap_or_else(|| panic!("expected {what} on the notification stream"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Exactly one safe negative window: no frame within `wait`.
|
||||||
|
async fn expect_silence(&mut self, wait: Duration, what: &str) {
|
||||||
|
if let Some(frame) = self.next_data(wait).await {
|
||||||
|
panic!("expected no {what}, got {frame}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn publish_prompt(registry: &PostgresRegistry, prompt_id: &PromptId, name: &str) -> PromptId {
|
||||||
|
let definition = PromptDefinition::parse(&json!({
|
||||||
|
"name": name,
|
||||||
|
"description": format!("{name} fixture"),
|
||||||
|
"arguments": [],
|
||||||
|
"messages": [{"role": "user", "content": format!("Use {name}.")}]
|
||||||
|
}))
|
||||||
|
.expect("the fixture Prompt definition is valid");
|
||||||
|
let created = registry
|
||||||
|
.create_prompt_draft(CreatePromptDraftRequest {
|
||||||
|
workspace_id: test_workspace_id(),
|
||||||
|
prompt_id: prompt_id.clone(),
|
||||||
|
sensitivity: PromptSensitivity::Internal,
|
||||||
|
definition,
|
||||||
|
created_at: OffsetDateTime::now_utc(),
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.expect("the Prompt Draft is created");
|
||||||
|
registry
|
||||||
|
.publish_prompt_draft(PublishPromptRequest {
|
||||||
|
workspace_id: test_workspace_id(),
|
||||||
|
prompt_id: prompt_id.clone(),
|
||||||
|
expected_updated_at: created.updated_at,
|
||||||
|
published_at: OffsetDateTime::now_utc(),
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.expect("the Prompt version publishes");
|
||||||
|
prompt_id.clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Publish one static Resource through the production 3.6/3.7 registry transition.
|
||||||
|
async fn publish_resource(
|
||||||
|
registry: &PostgresRegistry,
|
||||||
|
store: &ArtifactStore,
|
||||||
|
resource_id: &ResourceId,
|
||||||
|
bytes: &[u8],
|
||||||
|
) {
|
||||||
|
let artifact = store
|
||||||
|
.put_registered(bytes)
|
||||||
|
.expect("the fixture bytes are registered durably");
|
||||||
|
registry
|
||||||
|
.create_resource_draft(CreateResourceDraftRequest {
|
||||||
|
workspace_id: test_workspace_id(),
|
||||||
|
resource_id: resource_id.clone(),
|
||||||
|
uri: format!("crank://resources/{}", resource_id.as_str()),
|
||||||
|
name: resource_id.as_str().to_owned(),
|
||||||
|
description: "Story 3.19 signal fixture".to_owned(),
|
||||||
|
kind: "text".to_owned(),
|
||||||
|
mime_type: "text/plain".to_owned(),
|
||||||
|
sensitivity: "internal".to_owned(),
|
||||||
|
artifact,
|
||||||
|
created_at: OffsetDateTime::now_utc(),
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.expect("the Resource Draft is created");
|
||||||
|
let current = registry
|
||||||
|
.get_resource_draft(test_workspace_id().as_str(), resource_id)
|
||||||
|
.await
|
||||||
|
.expect("the Resource Draft reads");
|
||||||
|
registry
|
||||||
|
.publish_resource_version(PublishResourceVersionRequest {
|
||||||
|
workspace_id: test_workspace_id(),
|
||||||
|
resource_id: resource_id.clone(),
|
||||||
|
expected_updated_at: current.resource.updated_at,
|
||||||
|
expected_version: current.version.version,
|
||||||
|
expected_digest: current.version.digest.clone(),
|
||||||
|
expected_size_bytes: current.version.size_bytes,
|
||||||
|
artifact: store
|
||||||
|
.put_registered(bytes)
|
||||||
|
.expect("the published bytes are registered durably"),
|
||||||
|
published_at: OffsetDateTime::now_utc(),
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.expect("the Resource version publishes");
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn signals_endpoint() -> SignalsEndpoint {
|
||||||
|
let root = TestRoot::new();
|
||||||
|
let artifact_store = ArtifactStore::open(root.0.clone()).expect("the artifact store opens");
|
||||||
|
let registry = test_registry().await;
|
||||||
|
let upstream_base_url = spawn_upstream_server().await;
|
||||||
|
|
||||||
|
let operation = test_operation(&upstream_base_url, "crm_create_lead");
|
||||||
|
registry
|
||||||
|
.create_operation(&test_workspace_id(), &operation, Some("alice"))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
registry
|
||||||
|
.publish_operation(PublishRequest {
|
||||||
|
workspace_id: &test_workspace_id(),
|
||||||
|
operation_id: &operation.id,
|
||||||
|
version: 1,
|
||||||
|
published_at: &OffsetDateTime::now_utc(),
|
||||||
|
published_by: Some("alice"),
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let second_operation = test_operation(&upstream_base_url, "crm_create_second");
|
||||||
|
registry
|
||||||
|
.create_operation(&test_workspace_id(), &second_operation, Some("alice"))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
registry
|
||||||
|
.publish_operation(PublishRequest {
|
||||||
|
workspace_id: &test_workspace_id(),
|
||||||
|
operation_id: &second_operation.id,
|
||||||
|
version: 1,
|
||||||
|
published_at: &OffsetDateTime::now_utc(),
|
||||||
|
published_by: Some("alice"),
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let greeting = publish_prompt(®istry, &PromptId::new("prm_a_greeting"), "greeting").await;
|
||||||
|
let review = publish_prompt(®istry, &PromptId::new("prm_b_review"), "review").await;
|
||||||
|
let extra_prompt = publish_prompt(®istry, &PromptId::new("prm_c_extra"), "extra").await;
|
||||||
|
let notice = ResourceId::new("res_a_notice");
|
||||||
|
publish_resource(®istry, &artifact_store, ¬ice, b"first notice").await;
|
||||||
|
|
||||||
|
let agent_id = AgentId::new(format!("agent_{AGENT_SLUG}"));
|
||||||
|
let now = OffsetDateTime::now_utc();
|
||||||
|
registry
|
||||||
|
.create_agent(CreateAgentRequest {
|
||||||
|
agent: &Agent {
|
||||||
|
id: agent_id.clone(),
|
||||||
|
workspace_id: test_workspace_id(),
|
||||||
|
slug: AGENT_SLUG.to_owned(),
|
||||||
|
display_name: AGENT_SLUG.to_owned(),
|
||||||
|
description: "Story 3.19 signal fixture".to_owned(),
|
||||||
|
status: AgentStatus::Draft,
|
||||||
|
current_draft_version: 1,
|
||||||
|
latest_published_version: None,
|
||||||
|
created_at: now,
|
||||||
|
updated_at: now,
|
||||||
|
published_at: None,
|
||||||
|
},
|
||||||
|
version: &AgentVersion {
|
||||||
|
agent_id: agent_id.clone(),
|
||||||
|
version: 1,
|
||||||
|
status: AgentStatus::Draft,
|
||||||
|
instructions: json!({}),
|
||||||
|
tool_selection_policy: ToolSelectionPolicy::default(),
|
||||||
|
created_at: now,
|
||||||
|
},
|
||||||
|
bindings: &[binding_for_operation(&operation)],
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.expect("the draft Agent is created");
|
||||||
|
registry
|
||||||
|
.save_agent_catalog_config_editable_with_prompts(
|
||||||
|
SaveAgentCatalogConfigRequest {
|
||||||
|
workspace_id: &test_workspace_id(),
|
||||||
|
agent_id: &agent_id,
|
||||||
|
agent_version: 1,
|
||||||
|
bindings: &[binding_for_operation(&operation)],
|
||||||
|
tool_selection_policy: &ToolSelectionPolicy::default(),
|
||||||
|
resource_bindings: &[],
|
||||||
|
expected_state: None,
|
||||||
|
},
|
||||||
|
&[
|
||||||
|
AgentPromptBinding {
|
||||||
|
prompt_id: greeting.clone(),
|
||||||
|
prompt_version: 1,
|
||||||
|
},
|
||||||
|
AgentPromptBinding {
|
||||||
|
prompt_id: review.clone(),
|
||||||
|
prompt_version: 1,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.expect("the exact bound Prompt versions are accepted");
|
||||||
|
registry
|
||||||
|
.publish_agent(PublishAgentRequest {
|
||||||
|
workspace_id: &test_workspace_id(),
|
||||||
|
agent_id: &agent_id,
|
||||||
|
version: 1,
|
||||||
|
published_at: &OffsetDateTime::now_utc(),
|
||||||
|
published_by: Some("alice"),
|
||||||
|
expected_state: None,
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.expect("the bound Agent publishes");
|
||||||
|
|
||||||
|
let api_key = create_platform_api_key(
|
||||||
|
®istry,
|
||||||
|
AGENT_SLUG,
|
||||||
|
"mcp-signals",
|
||||||
|
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
let base_url = spawn_mcp_server(build_test_app_with_artifacts(
|
||||||
|
registry.clone(),
|
||||||
|
Duration::from_millis(0),
|
||||||
|
None,
|
||||||
|
artifact_store.clone(),
|
||||||
|
))
|
||||||
|
.await;
|
||||||
|
|
||||||
|
SignalsEndpoint {
|
||||||
|
client: reqwest::Client::new(),
|
||||||
|
mcp_url: agent_mcp_url(&base_url, AGENT_SLUG),
|
||||||
|
base_url,
|
||||||
|
api_key,
|
||||||
|
registry,
|
||||||
|
artifact_store,
|
||||||
|
root,
|
||||||
|
agent_id,
|
||||||
|
operation,
|
||||||
|
second_operation,
|
||||||
|
greeting,
|
||||||
|
review,
|
||||||
|
extra_prompt,
|
||||||
|
notice,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn prompt_names(list: &Value) -> Vec<String> {
|
||||||
|
list["result"]["prompts"]
|
||||||
|
.as_array()
|
||||||
|
.unwrap_or_else(|| panic!("prompts/list must return a page: {list}"))
|
||||||
|
.iter()
|
||||||
|
.map(|prompt| prompt["name"].as_str().unwrap().to_owned())
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn resource_uris(list: &Value) -> Vec<String> {
|
||||||
|
list["result"]["resources"]
|
||||||
|
.as_array()
|
||||||
|
.unwrap_or_else(|| panic!("resources/list must return a page: {list}"))
|
||||||
|
.iter()
|
||||||
|
.map(|resource| resource["uri"].as_str().unwrap().to_owned())
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn tool_names(list: &Value) -> Vec<String> {
|
||||||
|
let mut names: Vec<String> = list["result"]["tools"]
|
||||||
|
.as_array()
|
||||||
|
.unwrap_or_else(|| panic!("tools/list must return a page: {list}"))
|
||||||
|
.iter()
|
||||||
|
.map(|tool| tool["name"].as_str().unwrap().to_owned())
|
||||||
|
.collect();
|
||||||
|
names.sort();
|
||||||
|
names
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Write a stand file that only the current user may read (credential files live here).
|
||||||
|
fn write_private(path: &PathBuf, contents: &str) {
|
||||||
|
use std::io::Write as _;
|
||||||
|
use std::os::unix::fs::OpenOptionsExt as _;
|
||||||
|
let mut file = fs::OpenOptions::new()
|
||||||
|
.create(true)
|
||||||
|
.truncate(true)
|
||||||
|
.write(true)
|
||||||
|
.mode(0o600)
|
||||||
|
.open(path)
|
||||||
|
.unwrap_or_else(|error| panic!("stand file {path:?} must be writable: {error}"));
|
||||||
|
file.write_all(contents.as_bytes())
|
||||||
|
.expect("the stand file must be written");
|
||||||
|
}
|
||||||
@@ -0,0 +1,791 @@
|
|||||||
|
//! Story 3.19 acceptance scenarios (AT-3.19-01..03, FR-19) on the harness in the parent module.
|
||||||
|
//!
|
||||||
|
//! Moved out of `mcp_signals.rs` verbatim (code-health split, 1000-line limit); no scenario,
|
||||||
|
//! assertion or fixture changed.
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
/// Loopback disposable stand for the AC-3 representative-client evidence. This is deliberately not
|
||||||
|
/// part of the automated ATDD: it publishes the fixture catalog, serves the real MCP endpoint on
|
||||||
|
/// `127.0.0.1`, and then performs one commit per command file so an external MCP client can observe
|
||||||
|
/// the signals on its own stream.
|
||||||
|
///
|
||||||
|
/// Run it explicitly (the credential file is `0600` and never printed):
|
||||||
|
///
|
||||||
|
/// ```text
|
||||||
|
/// MCP_SIGNALS_STAND_DIR=/tmp/crank-signals-stand \
|
||||||
|
/// cargo test -p mcp-server --test integration mcp_signals::scenarios::representative_client_stand \
|
||||||
|
/// -- --ignored --exact --nocapture
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// Commands (create the file, wait for `<command>.done`): `commit-both`, `commit-prompt`,
|
||||||
|
/// `commit-resource`, `commit-tool`, `draft`, `stop`.
|
||||||
|
#[tokio::test]
|
||||||
|
#[ignore = "manual loopback stand for the representative MCP Inspector client evidence"]
|
||||||
|
async fn representative_client_stand() {
|
||||||
|
let directory = PathBuf::from(
|
||||||
|
std::env::var("MCP_SIGNALS_STAND_DIR")
|
||||||
|
.expect("MCP_SIGNALS_STAND_DIR names the disposable stand directory"),
|
||||||
|
);
|
||||||
|
fs::create_dir_all(&directory).expect("the stand directory is creatable");
|
||||||
|
let endpoint = signals_endpoint().await;
|
||||||
|
write_private(
|
||||||
|
&directory.join("stand.json"),
|
||||||
|
&json!({ "url": endpoint.mcp_url, "token": endpoint.api_key }).to_string(),
|
||||||
|
);
|
||||||
|
println!("stand ready: {}", directory.join("stand.json").display());
|
||||||
|
|
||||||
|
let deadline = tokio::time::Instant::now() + Duration::from_secs(900);
|
||||||
|
while tokio::time::Instant::now() < deadline {
|
||||||
|
for command in [
|
||||||
|
"commit-both",
|
||||||
|
"commit-prompt",
|
||||||
|
"commit-resource",
|
||||||
|
"commit-tool",
|
||||||
|
"draft",
|
||||||
|
"stop",
|
||||||
|
] {
|
||||||
|
let marker = directory.join(command);
|
||||||
|
if !marker.exists() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
fs::remove_file(&marker).expect("the command file is consumed once");
|
||||||
|
if command == "stop" {
|
||||||
|
println!("stand stopped: {command}");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
match command {
|
||||||
|
"commit-both" => endpoint.commit_resource_and_prompt_change().await,
|
||||||
|
"commit-prompt" => endpoint.commit_prompt_only_change().await,
|
||||||
|
"commit-resource" => endpoint.commit_resource_only_change().await,
|
||||||
|
"commit-tool" => endpoint.commit_tool_only_change().await,
|
||||||
|
_ => endpoint.edit_draft_without_publishing().await,
|
||||||
|
}
|
||||||
|
write_private(&directory.join(format!("{command}.done")), "done");
|
||||||
|
println!("stand committed: {command}");
|
||||||
|
}
|
||||||
|
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// AT-3.19-01 (legacy): an open notification stream receives the Resource and Prompt list-change
|
||||||
|
/// notifications only after the catalog commit, and `resources/list` / `prompts/list` serve the new
|
||||||
|
/// state afterwards.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn legacy_stream_announces_a_committed_catalog_change_after_the_commit() {
|
||||||
|
let endpoint = signals_endpoint().await;
|
||||||
|
let session = endpoint.legacy_session().await;
|
||||||
|
|
||||||
|
let mut stream = endpoint.legacy_stream(&session).await;
|
||||||
|
// The watcher takes its baseline before it can report anything; let it settle before the commit.
|
||||||
|
tokio::time::sleep(Duration::from_millis(1_500)).await;
|
||||||
|
stream
|
||||||
|
.expect_silence(Duration::from_millis(1_200), "signal before any commit")
|
||||||
|
.await;
|
||||||
|
|
||||||
|
// A draft-only edit is not a commit: nothing is announced.
|
||||||
|
endpoint.edit_draft_without_publishing().await;
|
||||||
|
stream
|
||||||
|
.expect_silence(Duration::from_millis(2_500), "signal for a draft-only edit")
|
||||||
|
.await;
|
||||||
|
|
||||||
|
endpoint.commit_resource_and_prompt_change().await;
|
||||||
|
|
||||||
|
let mut methods = Vec::new();
|
||||||
|
for _ in 0..2 {
|
||||||
|
let frame = stream
|
||||||
|
.expect_frame("the committed list-change signals")
|
||||||
|
.await;
|
||||||
|
assert_eq!(frame["jsonrpc"], json!("2.0"));
|
||||||
|
assert!(
|
||||||
|
frame.get("params").is_none(),
|
||||||
|
"a legacy list-change notification carries no parameters: {frame}"
|
||||||
|
);
|
||||||
|
methods.push(frame["method"].as_str().unwrap().to_owned());
|
||||||
|
}
|
||||||
|
methods.sort();
|
||||||
|
assert_eq!(
|
||||||
|
methods,
|
||||||
|
vec![
|
||||||
|
PROMPT_LIST_CHANGED.to_owned(),
|
||||||
|
RESOURCE_LIST_CHANGED.to_owned()
|
||||||
|
],
|
||||||
|
"one signal per changed catalog type"
|
||||||
|
);
|
||||||
|
|
||||||
|
// The ordinary list methods are authoritative for the same committed state.
|
||||||
|
let prompts = endpoint.legacy(&session, "prompts/list", json!({})).await;
|
||||||
|
assert!(
|
||||||
|
prompt_names(&prompts).contains(&"extra".to_owned()),
|
||||||
|
"prompts/list must serve the newly bound Prompt: {prompts}"
|
||||||
|
);
|
||||||
|
let resources = endpoint.legacy(&session, "resources/list", json!({})).await;
|
||||||
|
assert!(
|
||||||
|
resource_uris(&resources)
|
||||||
|
.iter()
|
||||||
|
.any(|uri| uri == &format!("crank://resources/{}", endpoint.notice.as_str())),
|
||||||
|
"resources/list must serve the newly bound Resource: {resources}"
|
||||||
|
);
|
||||||
|
|
||||||
|
// A Tool-only commit keeps the Resource/Prompt projection: only a Tools frame follows (Story 3.5).
|
||||||
|
endpoint.commit_tool_only_change().await;
|
||||||
|
let frame = stream
|
||||||
|
.expect_frame("the committed Tools list-change signal")
|
||||||
|
.await;
|
||||||
|
assert_eq!(frame["method"], TOOL_LIST_CHANGED);
|
||||||
|
assert!(
|
||||||
|
frame.get("params").is_none(),
|
||||||
|
"a legacy list-change notification carries no parameters: {frame}"
|
||||||
|
);
|
||||||
|
stream
|
||||||
|
.expect_silence(
|
||||||
|
Duration::from_millis(2_500),
|
||||||
|
"a Resource or Prompt signal for a Tool-only commit",
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// AT-3.19-01/03 (modern): `subscriptions/listen` acknowledges the honoured filter with the request
|
||||||
|
/// id, then delivers coalesced list-change notifications carrying the subscription id.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn modern_listen_stream_acknowledges_then_announces_coalesced_changes() {
|
||||||
|
let endpoint = signals_endpoint().await;
|
||||||
|
let mut stream = endpoint
|
||||||
|
.listen(
|
||||||
|
json!(41),
|
||||||
|
json!({
|
||||||
|
"resourcesListChanged": true,
|
||||||
|
"promptsListChanged": true,
|
||||||
|
"toolsListChanged": true,
|
||||||
|
"resourceSubscriptions": ["crank://resources/res_a_notice"]
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
|
||||||
|
let acknowledgement = stream.expect_frame("the acknowledgment").await;
|
||||||
|
assert_eq!(acknowledgement["method"], SUBSCRIPTIONS_ACKNOWLEDGED);
|
||||||
|
assert_eq!(
|
||||||
|
acknowledgement["params"]["_meta"][SUBSCRIPTION_ID_KEY],
|
||||||
|
json!(41)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
acknowledgement["params"]["notifications"],
|
||||||
|
json!({
|
||||||
|
"promptsListChanged": true,
|
||||||
|
"resourcesListChanged": true,
|
||||||
|
"toolsListChanged": true
|
||||||
|
}),
|
||||||
|
"only the implemented list-change types are acknowledged: {acknowledgement}"
|
||||||
|
);
|
||||||
|
|
||||||
|
tokio::time::sleep(Duration::from_millis(1_500)).await;
|
||||||
|
|
||||||
|
// Two commits in quick succession coalesce into one signal per changed type.
|
||||||
|
endpoint.commit_resource_and_prompt_change().await;
|
||||||
|
endpoint.commit_tool_only_change().await;
|
||||||
|
|
||||||
|
let mut methods = Vec::new();
|
||||||
|
for _ in 0..3 {
|
||||||
|
let frame = stream
|
||||||
|
.expect_frame("the coalesced list-change signal")
|
||||||
|
.await;
|
||||||
|
assert_eq!(frame["params"]["_meta"][SUBSCRIPTION_ID_KEY], json!(41));
|
||||||
|
methods.push(frame["method"].as_str().unwrap().to_owned());
|
||||||
|
}
|
||||||
|
methods.sort();
|
||||||
|
assert_eq!(
|
||||||
|
methods,
|
||||||
|
vec![
|
||||||
|
PROMPT_LIST_CHANGED.to_owned(),
|
||||||
|
RESOURCE_LIST_CHANGED.to_owned(),
|
||||||
|
TOOL_LIST_CHANGED.to_owned()
|
||||||
|
]
|
||||||
|
);
|
||||||
|
stream
|
||||||
|
.expect_silence(
|
||||||
|
Duration::from_millis(2_500),
|
||||||
|
"a duplicate or unrequested signal",
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
|
||||||
|
// A client that missed every notification still recovers the authoritative catalog.
|
||||||
|
let prompts = endpoint.modern("prompts/list", json!({})).await;
|
||||||
|
assert!(
|
||||||
|
prompt_names(&prompts).contains(&"extra".to_owned()),
|
||||||
|
"{prompts}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// AT-3.19-01/03 (modern): the acknowledged filter is the delivery contract. A prompts-only stream
|
||||||
|
/// stays silent for a Resource-only commit, delivers exactly one Prompt frame with the subscription
|
||||||
|
/// id for a Prompt commit, and never delivers an unrequested type.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn modern_listen_delivers_only_the_negotiated_signal_types() {
|
||||||
|
let endpoint = signals_endpoint().await;
|
||||||
|
let mut stream = endpoint
|
||||||
|
.listen(
|
||||||
|
json!("prompts-only"),
|
||||||
|
json!({
|
||||||
|
"promptsListChanged": true,
|
||||||
|
"toolsListChanged": true,
|
||||||
|
"resourceSubscriptions": ["crank://resources/res_a_notice"]
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
|
||||||
|
let acknowledgement = stream.expect_frame("the acknowledgment").await;
|
||||||
|
assert_eq!(acknowledgement["method"], SUBSCRIPTIONS_ACKNOWLEDGED);
|
||||||
|
assert_eq!(
|
||||||
|
acknowledgement["params"]["_meta"][SUBSCRIPTION_ID_KEY],
|
||||||
|
json!("prompts-only")
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
acknowledgement["params"]["notifications"],
|
||||||
|
json!({ "promptsListChanged": true, "toolsListChanged": true }),
|
||||||
|
"only the implemented and requested types are acknowledged: {acknowledgement}"
|
||||||
|
);
|
||||||
|
|
||||||
|
// The watcher takes its baseline before it can report anything.
|
||||||
|
tokio::time::sleep(Duration::from_millis(1_500)).await;
|
||||||
|
|
||||||
|
// A Resource-only commit is outside the negotiated filter: a server that ignored the filter would
|
||||||
|
// emit a Resource frame here.
|
||||||
|
endpoint.commit_resource_only_change().await;
|
||||||
|
stream
|
||||||
|
.expect_silence(
|
||||||
|
Duration::from_millis(2_500),
|
||||||
|
"signal for a Resource-only commit on a prompts-only stream",
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
|
||||||
|
// A Prompt-only commit is inside it: exactly one frame, correlated by the subscription id.
|
||||||
|
endpoint.commit_prompt_only_change().await;
|
||||||
|
let frame = stream
|
||||||
|
.expect_frame("the negotiated Prompt list-change signal")
|
||||||
|
.await;
|
||||||
|
assert_eq!(frame["method"], PROMPT_LIST_CHANGED);
|
||||||
|
assert_eq!(
|
||||||
|
frame["params"]["_meta"][SUBSCRIPTION_ID_KEY],
|
||||||
|
json!("prompts-only")
|
||||||
|
);
|
||||||
|
|
||||||
|
// No Tool commit happened, so no Tools frame follows; `resourceSubscriptions` was not honoured.
|
||||||
|
stream
|
||||||
|
.expect_silence(
|
||||||
|
Duration::from_millis(2_500),
|
||||||
|
"a duplicate, Tools or URI-content signal",
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// AT-3.19-03: the unsupported URI-content subscription surface is never acknowledged, and the
|
||||||
|
/// legacy revision has no `subscriptions/listen` request at all.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn unsupported_subscription_surfaces_are_refused_rather_than_faked() {
|
||||||
|
let endpoint = signals_endpoint().await;
|
||||||
|
|
||||||
|
for method in ["resources/subscribe", "resources/unsubscribe"] {
|
||||||
|
let reply = endpoint
|
||||||
|
.modern(method, json!({ "uri": "crank://resources/res_a_notice" }))
|
||||||
|
.await;
|
||||||
|
assert_eq!(
|
||||||
|
reply["error"]["code"],
|
||||||
|
json!(-32601),
|
||||||
|
"{method} must stay unimplemented: {reply}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// The legacy revision opens its notification stream with GET only.
|
||||||
|
let session = endpoint.legacy_session().await;
|
||||||
|
let legacy_listen = endpoint
|
||||||
|
.legacy(
|
||||||
|
&session,
|
||||||
|
"subscriptions/listen",
|
||||||
|
json!({ "notifications": {} }),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(
|
||||||
|
legacy_listen["error"]["code"],
|
||||||
|
json!(-32601),
|
||||||
|
"subscriptions/listen is a modern-only request: {legacy_listen}"
|
||||||
|
);
|
||||||
|
|
||||||
|
// A malformed filter is a bounded invalid-params answer with no echoed value.
|
||||||
|
let malformed = endpoint
|
||||||
|
.modern_offering_stream(
|
||||||
|
"subscriptions/listen",
|
||||||
|
json!({ "notifications": ["promptsListChanged"] }),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(malformed["error"]["code"], json!(-32602));
|
||||||
|
assert_eq!(
|
||||||
|
malformed["error"]["message"],
|
||||||
|
json!("invalid subscriptions/listen notification filter")
|
||||||
|
);
|
||||||
|
|
||||||
|
// Without an SSE-capable client the stream cannot be served at all.
|
||||||
|
let without_sse = endpoint
|
||||||
|
.client
|
||||||
|
.post(&endpoint.mcp_url)
|
||||||
|
.header(header::ACCEPT, "application/json")
|
||||||
|
.header(
|
||||||
|
header::AUTHORIZATION,
|
||||||
|
format!("Bearer {}", endpoint.api_key),
|
||||||
|
)
|
||||||
|
.header("MCP-Protocol-Version", MODERN_REVISION)
|
||||||
|
.header("Mcp-Method", "subscriptions/listen")
|
||||||
|
.json(&json!({
|
||||||
|
"jsonrpc": "2.0",
|
||||||
|
"id": 42,
|
||||||
|
"method": "subscriptions/listen",
|
||||||
|
"params": {
|
||||||
|
"notifications": { "promptsListChanged": true },
|
||||||
|
"_meta": SignalsEndpoint::modern_meta()
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(without_sse.status(), reqwest::StatusCode::NOT_ACCEPTABLE);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// AT-3.19-02: a missed notification never loses committed state — a legacy client re-initializes
|
||||||
|
/// (the retired session is a safe `404`) and reads the authoritative catalog, while the modern
|
||||||
|
/// stateless client recovers through `server/discover` and the list methods.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_lost_notification_is_recovered_through_the_authoritative_methods() {
|
||||||
|
let endpoint = signals_endpoint().await;
|
||||||
|
|
||||||
|
// Modern recovery: the commit happens with no stream open at all.
|
||||||
|
endpoint.commit_resource_and_prompt_change().await;
|
||||||
|
let discover = endpoint.modern("server/discover", json!({})).await;
|
||||||
|
assert_eq!(
|
||||||
|
discover["result"]["capabilities"]["prompts"]["listChanged"],
|
||||||
|
json!(true)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
discover["result"]["capabilities"]["resources"]["listChanged"],
|
||||||
|
json!(true)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
discover["result"]["capabilities"]["tools"]["listChanged"],
|
||||||
|
json!(true),
|
||||||
|
"the Tools list-change capability is advertised: {discover}"
|
||||||
|
);
|
||||||
|
let resources = endpoint.modern("resources/list", json!({})).await;
|
||||||
|
assert!(
|
||||||
|
resource_uris(&resources)
|
||||||
|
.iter()
|
||||||
|
.any(|uri| uri == &format!("crank://resources/{}", endpoint.notice.as_str())),
|
||||||
|
"the committed Resource is served to a client that missed the signal: {resources}"
|
||||||
|
);
|
||||||
|
|
||||||
|
// Legacy recovery: the negotiated session can be dropped, and the revision-correct answer is a
|
||||||
|
// safe `404` that makes the client re-initialize instead of resuming a stale stream.
|
||||||
|
let session = endpoint.legacy_session().await;
|
||||||
|
let mut stream = endpoint.legacy_stream(&session).await;
|
||||||
|
tokio::time::sleep(Duration::from_millis(1_500)).await;
|
||||||
|
|
||||||
|
let deleted = endpoint
|
||||||
|
.client
|
||||||
|
.delete(&endpoint.mcp_url)
|
||||||
|
.header(
|
||||||
|
header::AUTHORIZATION,
|
||||||
|
format!("Bearer {}", endpoint.api_key),
|
||||||
|
)
|
||||||
|
.header("MCP-Protocol-Version", LEGACY_REVISION)
|
||||||
|
.header("MCP-Session-Id", &session)
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(deleted.status(), reqwest::StatusCode::NO_CONTENT);
|
||||||
|
stream
|
||||||
|
.expect_silence(
|
||||||
|
Duration::from_millis(2_500),
|
||||||
|
"a signal on the retired session",
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
|
||||||
|
let stale_get = endpoint
|
||||||
|
.client
|
||||||
|
.get(&endpoint.mcp_url)
|
||||||
|
.header(header::ACCEPT, "text/event-stream")
|
||||||
|
.header(
|
||||||
|
header::AUTHORIZATION,
|
||||||
|
format!("Bearer {}", endpoint.api_key),
|
||||||
|
)
|
||||||
|
.header("MCP-Protocol-Version", LEGACY_REVISION)
|
||||||
|
.header("MCP-Session-Id", &session)
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
stale_get.status(),
|
||||||
|
reqwest::StatusCode::NOT_FOUND,
|
||||||
|
"a retired session is never resumed"
|
||||||
|
);
|
||||||
|
|
||||||
|
let fresh = endpoint.legacy_session().await;
|
||||||
|
let prompts = endpoint.legacy(&fresh, "prompts/list", json!({})).await;
|
||||||
|
assert!(
|
||||||
|
prompt_names(&prompts).contains(&"extra".to_owned()),
|
||||||
|
"re-initialization serves the authoritative catalog: {prompts}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------------------------------------
|
||||||
|
// Story 3.5 (FR-14): Tool catalog change signals. A client that negotiated the Tools list-changed
|
||||||
|
// notification learns about a *committed* Tool catalog change, and `tools/list` stays the
|
||||||
|
// authoritative source for a client without the notification or after a reconnect.
|
||||||
|
// ------------------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// AT-3.5-01/02 (modern): the Tools signal is delivered only to the stream that negotiated it, once
|
||||||
|
/// per committed change, and `tools/list` serves the same committed snapshot.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn modern_tools_list_changed_is_delivered_only_to_a_client_that_asks_for_it() {
|
||||||
|
let endpoint = signals_endpoint().await;
|
||||||
|
let mut tools = endpoint
|
||||||
|
.listen(json!(51), json!({ "toolsListChanged": true }))
|
||||||
|
.await;
|
||||||
|
let mut prompts = endpoint
|
||||||
|
.listen(json!(52), json!({ "promptsListChanged": true }))
|
||||||
|
.await;
|
||||||
|
|
||||||
|
let acknowledgement = tools.expect_frame("the Tools acknowledgment").await;
|
||||||
|
assert_eq!(acknowledgement["method"], SUBSCRIPTIONS_ACKNOWLEDGED);
|
||||||
|
assert_eq!(
|
||||||
|
acknowledgement["params"]["notifications"],
|
||||||
|
json!({ "toolsListChanged": true }),
|
||||||
|
"the Tools list-change type must be honoured and acknowledged: {acknowledgement}"
|
||||||
|
);
|
||||||
|
let other = prompts.expect_frame("the Prompts acknowledgment").await;
|
||||||
|
assert_eq!(
|
||||||
|
other["params"]["notifications"],
|
||||||
|
json!({ "promptsListChanged": true }),
|
||||||
|
"a stream that did not ask for Tools is acknowledged without it: {other}"
|
||||||
|
);
|
||||||
|
|
||||||
|
// The watchers take their baseline before they can report anything.
|
||||||
|
tokio::time::sleep(Duration::from_millis(1_500)).await;
|
||||||
|
|
||||||
|
// A draft-only edit is not a commit: nothing is announced.
|
||||||
|
endpoint.edit_draft_without_publishing().await;
|
||||||
|
tools
|
||||||
|
.expect_silence(
|
||||||
|
Duration::from_millis(2_500),
|
||||||
|
"Tools signal for a draft-only edit",
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
|
||||||
|
// A committed Resource/Prompt change is not a Tools change: the Tools stream stays silent while
|
||||||
|
// the Prompts stream receives exactly its own type.
|
||||||
|
endpoint.commit_resource_and_prompt_change().await;
|
||||||
|
let prompt_frame = prompts
|
||||||
|
.expect_frame("the committed Prompt list-change signal")
|
||||||
|
.await;
|
||||||
|
assert_eq!(prompt_frame["method"], PROMPT_LIST_CHANGED);
|
||||||
|
tools
|
||||||
|
.expect_silence(
|
||||||
|
Duration::from_millis(2_500),
|
||||||
|
"Tools signal for a Resource/Prompt commit",
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
|
||||||
|
// One committed Tool catalog change is announced exactly once.
|
||||||
|
endpoint.commit_tool_only_change().await;
|
||||||
|
let frame = tools
|
||||||
|
.expect_frame("the committed Tools list-change signal")
|
||||||
|
.await;
|
||||||
|
assert_eq!(frame["jsonrpc"], json!("2.0"));
|
||||||
|
assert_eq!(frame["method"], TOOL_LIST_CHANGED);
|
||||||
|
assert_eq!(frame["params"]["_meta"][SUBSCRIPTION_ID_KEY], json!(51));
|
||||||
|
tools
|
||||||
|
.expect_silence(Duration::from_millis(2_500), "a repeated Tools signal")
|
||||||
|
.await;
|
||||||
|
|
||||||
|
// The prompts-only stream was never told about Tools, even though the commit happened after it
|
||||||
|
// opened.
|
||||||
|
prompts
|
||||||
|
.expect_silence(Duration::from_millis(1_200), "unrequested Tools signal")
|
||||||
|
.await;
|
||||||
|
|
||||||
|
// `tools/list` is authoritative for the same committed state, notification or not.
|
||||||
|
let list = endpoint.modern("tools/list", json!({})).await;
|
||||||
|
assert_eq!(
|
||||||
|
tool_names(&list),
|
||||||
|
vec!["crm_create_lead".to_owned(), "crm_create_second".to_owned()]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// AT-3.5-01/02 (legacy): the legacy `GET` stream carries the Tools signal after the commit; a
|
||||||
|
/// Resource/Prompt commit produces no Tools frame; a committed change of another Agent is never
|
||||||
|
/// disclosed on this stream, and `tools/list` stays authoritative.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn legacy_stream_announces_a_committed_tools_change_and_never_another_agents() {
|
||||||
|
let endpoint = signals_endpoint().await;
|
||||||
|
let other_key = endpoint.publish_other_agent(OTHER_AGENT_SLUG).await;
|
||||||
|
let session = endpoint.legacy_session().await;
|
||||||
|
|
||||||
|
let mut stream = endpoint.legacy_stream(&session).await;
|
||||||
|
tokio::time::sleep(Duration::from_millis(1_500)).await;
|
||||||
|
stream
|
||||||
|
.expect_silence(Duration::from_millis(1_200), "signal before any commit")
|
||||||
|
.await;
|
||||||
|
|
||||||
|
// A committed Resource/Prompt change keeps the Tool binding set: no Tools frame.
|
||||||
|
endpoint.commit_resource_and_prompt_change().await;
|
||||||
|
let mut methods = Vec::new();
|
||||||
|
for _ in 0..2 {
|
||||||
|
let frame = stream.expect_frame("the committed catalog signals").await;
|
||||||
|
assert!(
|
||||||
|
frame.get("params").is_none(),
|
||||||
|
"a legacy list-change notification carries no parameters: {frame}"
|
||||||
|
);
|
||||||
|
methods.push(frame["method"].as_str().unwrap().to_owned());
|
||||||
|
}
|
||||||
|
methods.sort();
|
||||||
|
assert_eq!(
|
||||||
|
methods,
|
||||||
|
vec![
|
||||||
|
PROMPT_LIST_CHANGED.to_owned(),
|
||||||
|
RESOURCE_LIST_CHANGED.to_owned()
|
||||||
|
],
|
||||||
|
"a Resource/Prompt commit must not announce Tools"
|
||||||
|
);
|
||||||
|
|
||||||
|
// A committed Tool change of another Agent of the same workspace never reaches this stream or
|
||||||
|
// this Agent's `tools/list`.
|
||||||
|
endpoint
|
||||||
|
.commit_other_agent_tool_change(OTHER_AGENT_SLUG)
|
||||||
|
.await;
|
||||||
|
stream
|
||||||
|
.expect_silence(
|
||||||
|
Duration::from_millis(2_500),
|
||||||
|
"Tools signal for another Agent's commit",
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
let isolated = endpoint.legacy(&session, "tools/list", json!({})).await;
|
||||||
|
assert_eq!(
|
||||||
|
tool_names(&isolated),
|
||||||
|
vec!["crm_create_lead".to_owned()],
|
||||||
|
"another Agent's commit must not change this Agent's catalog: {isolated}"
|
||||||
|
);
|
||||||
|
// The commit really happened: the other Agent serves its own two-Tool catalog.
|
||||||
|
let other_url = agent_mcp_url(&endpoint.base_url, OTHER_AGENT_SLUG);
|
||||||
|
let other_session = initialize_session(&endpoint.client, &other_url, &other_key).await;
|
||||||
|
let other_list = endpoint
|
||||||
|
.client
|
||||||
|
.post(&other_url)
|
||||||
|
.header(header::ACCEPT, "application/json, text/event-stream")
|
||||||
|
.header(header::AUTHORIZATION, format!("Bearer {other_key}"))
|
||||||
|
.header("MCP-Protocol-Version", LEGACY_REVISION)
|
||||||
|
.header("MCP-Session-Id", &other_session)
|
||||||
|
.json(&json!({
|
||||||
|
"jsonrpc": "2.0",
|
||||||
|
"id": 7,
|
||||||
|
"method": "tools/list",
|
||||||
|
"params": {}
|
||||||
|
}))
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let other_list: Value = serde_json::from_str(&other_list.text().await.unwrap()).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
tool_names(&other_list),
|
||||||
|
vec!["crm_create_lead".to_owned(), "crm_create_second".to_owned()],
|
||||||
|
"the other Agent's committed catalog changed: {other_list}"
|
||||||
|
);
|
||||||
|
|
||||||
|
// This Agent's committed Tool change is announced after the commit, exactly once.
|
||||||
|
endpoint.commit_tool_only_change().await;
|
||||||
|
let frame = stream
|
||||||
|
.expect_frame("the committed Tools list-change signal")
|
||||||
|
.await;
|
||||||
|
assert_eq!(frame["method"], TOOL_LIST_CHANGED);
|
||||||
|
assert!(
|
||||||
|
frame.get("params").is_none(),
|
||||||
|
"a legacy list-change notification carries no parameters: {frame}"
|
||||||
|
);
|
||||||
|
stream
|
||||||
|
.expect_silence(
|
||||||
|
Duration::from_millis(2_500),
|
||||||
|
"a repeated or unrequested signal",
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
|
||||||
|
let list = endpoint.legacy(&session, "tools/list", json!({})).await;
|
||||||
|
assert_eq!(
|
||||||
|
tool_names(&list),
|
||||||
|
vec!["crm_create_lead".to_owned(), "crm_create_second".to_owned()],
|
||||||
|
"tools/list must serve the committed catalog without the notification: {list}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// AT-3.5-04: the Tools signal follows the same projection `tools/list` serves, so a committed
|
||||||
|
/// publication that only changes the Tool selection policy is announced on both revisions, while a
|
||||||
|
/// committed binding change that leaves `tools/list` unchanged is silent.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_policy_only_commit_is_announced_on_both_revisions_and_an_invisible_change_is_silent() {
|
||||||
|
let endpoint = signals_endpoint().await;
|
||||||
|
let direct_projection = vec!["crm_create_lead".to_owned()];
|
||||||
|
// `tool_names` sorts the served page.
|
||||||
|
let search_projection = vec!["call_tool".to_owned(), "search_tools".to_owned()];
|
||||||
|
|
||||||
|
// Both revisions negotiate the Tools signal and take their baseline before anything can arrive.
|
||||||
|
let mut modern = endpoint
|
||||||
|
.listen(json!(61), json!({ "toolsListChanged": true }))
|
||||||
|
.await;
|
||||||
|
let acknowledgement = modern.expect_frame("the Tools acknowledgment").await;
|
||||||
|
assert_eq!(acknowledgement["method"], SUBSCRIPTIONS_ACKNOWLEDGED);
|
||||||
|
assert_eq!(
|
||||||
|
acknowledgement["params"]["notifications"],
|
||||||
|
json!({ "toolsListChanged": true })
|
||||||
|
);
|
||||||
|
let session = endpoint.legacy_session().await;
|
||||||
|
let mut legacy = endpoint.legacy_stream(&session).await;
|
||||||
|
tokio::time::sleep(Duration::from_millis(1_500)).await;
|
||||||
|
|
||||||
|
// The served projection before the commit is the direct-mode binding itself.
|
||||||
|
assert_eq!(
|
||||||
|
tool_names(&endpoint.modern("tools/list", json!({})).await),
|
||||||
|
direct_projection
|
||||||
|
);
|
||||||
|
|
||||||
|
// A policy-only commit: identical Tool/Resource/Prompt bindings, direct -> search mode. The
|
||||||
|
// served list changes, so each negotiated stream receives exactly one Tools frame.
|
||||||
|
endpoint.commit_policy_only_change().await;
|
||||||
|
let modern_frame = modern
|
||||||
|
.expect_frame("the committed Tools list-change signal (modern)")
|
||||||
|
.await;
|
||||||
|
assert_eq!(modern_frame["method"], TOOL_LIST_CHANGED);
|
||||||
|
assert_eq!(
|
||||||
|
modern_frame["params"]["_meta"][SUBSCRIPTION_ID_KEY],
|
||||||
|
json!(61)
|
||||||
|
);
|
||||||
|
let legacy_frame = legacy
|
||||||
|
.expect_frame("the committed Tools list-change signal (legacy)")
|
||||||
|
.await;
|
||||||
|
assert_eq!(legacy_frame["method"], TOOL_LIST_CHANGED);
|
||||||
|
assert!(
|
||||||
|
legacy_frame.get("params").is_none(),
|
||||||
|
"a legacy list-change notification carries no parameters: {legacy_frame}"
|
||||||
|
);
|
||||||
|
modern
|
||||||
|
.expect_silence(
|
||||||
|
Duration::from_millis(2_500),
|
||||||
|
"a repeated modern Tools signal",
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
legacy
|
||||||
|
.expect_silence(
|
||||||
|
Duration::from_millis(2_500),
|
||||||
|
"a repeated legacy Tools signal",
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
|
||||||
|
// `tools/list` is authoritative for the new projection on both revisions.
|
||||||
|
assert_eq!(
|
||||||
|
tool_names(&endpoint.modern("tools/list", json!({})).await),
|
||||||
|
search_projection
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
tool_names(&endpoint.legacy(&session, "tools/list", json!({})).await),
|
||||||
|
search_projection
|
||||||
|
);
|
||||||
|
|
||||||
|
// The inverse direction: in search mode a binding-only commit does not change `tools/list`, so
|
||||||
|
// neither stream may claim a visible Tool change.
|
||||||
|
endpoint.commit_search_mode_binding_change().await;
|
||||||
|
modern
|
||||||
|
.expect_silence(
|
||||||
|
Duration::from_millis(3_500),
|
||||||
|
"a Tools signal for an unchanged modern tools/list",
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
legacy
|
||||||
|
.expect_silence(
|
||||||
|
Duration::from_millis(2_500),
|
||||||
|
"a Tools signal for an unchanged legacy tools/list",
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(
|
||||||
|
tool_names(&endpoint.modern("tools/list", json!({})).await),
|
||||||
|
search_projection
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// AT-3.5-02/03: a client that missed the notification recovers Tool discovery from the authoritative
|
||||||
|
/// state — the modern stateless client after a reconnect, and the legacy client after re-initializing
|
||||||
|
/// a retired session — and a reconnected stream never replays the missed change.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_reconnected_client_recovers_tools_discovery_from_the_authoritative_state() {
|
||||||
|
let endpoint = signals_endpoint().await;
|
||||||
|
|
||||||
|
// Modern: the commit happens while no stream is open at all, then a client reconnects.
|
||||||
|
endpoint.commit_tool_only_change().await;
|
||||||
|
let mut reconnected = endpoint
|
||||||
|
.listen(
|
||||||
|
json!("after-reconnect"),
|
||||||
|
json!({ "toolsListChanged": true }),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
let acknowledgement = reconnected.expect_frame("the Tools acknowledgment").await;
|
||||||
|
assert_eq!(
|
||||||
|
acknowledgement["params"]["notifications"],
|
||||||
|
json!({ "toolsListChanged": true })
|
||||||
|
);
|
||||||
|
// The baseline of a new stream is the committed state: the missed change is not replayed.
|
||||||
|
reconnected
|
||||||
|
.expect_silence(
|
||||||
|
Duration::from_millis(2_500),
|
||||||
|
"a replayed Tools signal after reconnect",
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
let list = endpoint.modern("tools/list", json!({})).await;
|
||||||
|
assert_eq!(
|
||||||
|
tool_names(&list),
|
||||||
|
vec!["crm_create_lead".to_owned(), "crm_create_second".to_owned()],
|
||||||
|
"a client without the notification recovers the committed catalog: {list}"
|
||||||
|
);
|
||||||
|
|
||||||
|
// Legacy: one more committed Tool change is announced on the live stream, then the session is
|
||||||
|
// retired and the client re-initializes.
|
||||||
|
let session = endpoint.legacy_session().await;
|
||||||
|
let mut stale = endpoint.legacy_stream(&session).await;
|
||||||
|
tokio::time::sleep(Duration::from_millis(1_500)).await;
|
||||||
|
endpoint.commit_tool_only_revert().await;
|
||||||
|
let frame = stale
|
||||||
|
.expect_frame("the committed Tools list-change signal")
|
||||||
|
.await;
|
||||||
|
assert_eq!(frame["method"], TOOL_LIST_CHANGED);
|
||||||
|
|
||||||
|
let deleted = endpoint
|
||||||
|
.client
|
||||||
|
.delete(&endpoint.mcp_url)
|
||||||
|
.header(
|
||||||
|
header::AUTHORIZATION,
|
||||||
|
format!("Bearer {}", endpoint.api_key),
|
||||||
|
)
|
||||||
|
.header("MCP-Protocol-Version", LEGACY_REVISION)
|
||||||
|
.header("MCP-Session-Id", &session)
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(deleted.status(), reqwest::StatusCode::NO_CONTENT);
|
||||||
|
|
||||||
|
let fresh = endpoint.legacy_session().await;
|
||||||
|
let list = endpoint.legacy(&fresh, "tools/list", json!({})).await;
|
||||||
|
assert_eq!(
|
||||||
|
tool_names(&list),
|
||||||
|
vec!["crm_create_lead".to_owned()],
|
||||||
|
"re-initialization serves the committed catalog: {list}"
|
||||||
|
);
|
||||||
|
// A stream reopened after the reconnect starts from the committed baseline, not from a replay.
|
||||||
|
let mut reopened = endpoint.legacy_stream(&fresh).await;
|
||||||
|
reopened
|
||||||
|
.expect_silence(
|
||||||
|
Duration::from_millis(2_500),
|
||||||
|
"a replayed Tools signal on a reconnected stream",
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
}
|
||||||
@@ -114,8 +114,8 @@ fn now_rfc3339() -> String {
|
|||||||
.unwrap_or_else(|error| format!("unformatted-utc ({error})"))
|
.unwrap_or_else(|error| format!("unformatted-utc ({error})"))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A single timed `resources/list`, built directly on `reqwest` so transport/timeout/HTTP failures are
|
/// A single timed `resources/list` call, built directly on `reqwest` so transport/timeout/HTTP
|
||||||
/// recorded as outcomes instead of aborting the run.
|
/// failures are recorded as outcomes instead of aborting the run.
|
||||||
async fn timed_list(
|
async fn timed_list(
|
||||||
endpoint: &ResourceEndpoint,
|
endpoint: &ResourceEndpoint,
|
||||||
revision: &'static str,
|
revision: &'static str,
|
||||||
|
|||||||
+94
-25
@@ -1,18 +1,56 @@
|
|||||||
use super::*;
|
use super::*;
|
||||||
use std::process::Command;
|
use std::{
|
||||||
|
env,
|
||||||
|
io::{Read, Write},
|
||||||
|
net::{TcpListener, TcpStream, ToSocketAddrs},
|
||||||
|
process::Command,
|
||||||
|
thread,
|
||||||
|
time::{Duration, Instant},
|
||||||
|
};
|
||||||
|
|
||||||
pub(super) struct TestValkey(String);
|
pub(super) struct TestValkey(String);
|
||||||
|
|
||||||
impl TestValkey {
|
impl TestValkey {
|
||||||
pub(super) fn start() -> (Self, u16) {
|
pub(super) fn start() -> (Self, u16) {
|
||||||
let output = Command::new("docker")
|
let in_docker_job = if std::path::Path::new("/.dockerenv").exists() {
|
||||||
.args([
|
let hostname = env::var("HOSTNAME").unwrap_or_default();
|
||||||
"run",
|
assert!(
|
||||||
"--detach",
|
matches!(hostname.len(), 12 | 64)
|
||||||
"--publish",
|
&& hostname.bytes().all(|byte| byte.is_ascii_hexdigit()),
|
||||||
"127.0.0.1::6379",
|
"Docker job hostname must be a full 12- or 64-character container ID"
|
||||||
"valkey/valkey:8-alpine",
|
);
|
||||||
])
|
Some(hostname)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
|
||||||
|
let port = if in_docker_job.is_some() {
|
||||||
|
let listener = TcpListener::bind(("127.0.0.1", 0))
|
||||||
|
.expect("test-owned Valkey loopback port must be available");
|
||||||
|
let port = listener.local_addr().unwrap().port();
|
||||||
|
drop(listener);
|
||||||
|
Some(port)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut docker = Command::new("docker");
|
||||||
|
docker.args([
|
||||||
|
"run",
|
||||||
|
"--detach",
|
||||||
|
"--label",
|
||||||
|
"crank.test.fixture=static-resources-valkey",
|
||||||
|
]);
|
||||||
|
if let (Some(hostname), Some(port)) = (&in_docker_job, port) {
|
||||||
|
docker
|
||||||
|
.arg("--network")
|
||||||
|
.arg(format!("container:{hostname}"))
|
||||||
|
.arg("valkey/valkey:8-alpine")
|
||||||
|
.args(["valkey-server", "--port", &port.to_string()]);
|
||||||
|
} else {
|
||||||
|
docker.args(["--publish", "127.0.0.1::6379", "valkey/valkey:8-alpine"]);
|
||||||
|
}
|
||||||
|
let output = docker
|
||||||
.output()
|
.output()
|
||||||
.expect("Docker CLI must start the test-owned Valkey container");
|
.expect("Docker CLI must start the test-owned Valkey container");
|
||||||
assert!(
|
assert!(
|
||||||
@@ -25,22 +63,29 @@ impl TestValkey {
|
|||||||
.trim()
|
.trim()
|
||||||
.to_owned();
|
.to_owned();
|
||||||
let valkey = Self(id);
|
let valkey = Self(id);
|
||||||
let port_output = Command::new("docker")
|
let port = match port {
|
||||||
.args(["port", &valkey.0, "6379/tcp"])
|
Some(port) => port,
|
||||||
.output()
|
None => {
|
||||||
.expect("Docker CLI must report the test-owned port");
|
let port_output = Command::new("docker")
|
||||||
assert!(
|
.args(["port", &valkey.0, "6379/tcp"])
|
||||||
port_output.status.success(),
|
.output()
|
||||||
"test-owned Valkey port must be available"
|
.expect("Docker CLI must report the test-owned port");
|
||||||
);
|
assert!(
|
||||||
let address = String::from_utf8(port_output.stdout).expect("Docker port must be UTF-8");
|
port_output.status.success(),
|
||||||
let port = address
|
"test-owned Valkey port must be available"
|
||||||
.trim()
|
);
|
||||||
.rsplit(':')
|
let address =
|
||||||
.next()
|
String::from_utf8(port_output.stdout).expect("Docker port must be UTF-8");
|
||||||
.unwrap()
|
address
|
||||||
.parse()
|
.trim()
|
||||||
.expect("Docker mapped port must be numeric");
|
.rsplit(':')
|
||||||
|
.next()
|
||||||
|
.unwrap()
|
||||||
|
.parse()
|
||||||
|
.expect("Docker mapped port must be numeric")
|
||||||
|
}
|
||||||
|
};
|
||||||
|
wait_for_valkey(port);
|
||||||
(valkey, port)
|
(valkey, port)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -53,6 +98,30 @@ impl TestValkey {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn wait_for_valkey(port: u16) {
|
||||||
|
let address = ("127.0.0.1", port)
|
||||||
|
.to_socket_addrs()
|
||||||
|
.expect("test-owned Valkey loopback address must resolve")
|
||||||
|
.next()
|
||||||
|
.unwrap();
|
||||||
|
let deadline = Instant::now() + Duration::from_secs(10);
|
||||||
|
while Instant::now() < deadline {
|
||||||
|
if let Ok(mut stream) = TcpStream::connect_timeout(&address, Duration::from_millis(250)) {
|
||||||
|
let _ = stream.set_read_timeout(Some(Duration::from_millis(250)));
|
||||||
|
let _ = stream.set_write_timeout(Some(Duration::from_millis(250)));
|
||||||
|
let mut reply = [0_u8; 7];
|
||||||
|
if stream.write_all(b"*1\r\n$4\r\nPING\r\n").is_ok()
|
||||||
|
&& stream.read_exact(&mut reply).is_ok()
|
||||||
|
&& &reply == b"+PONG\r\n"
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
thread::sleep(Duration::from_millis(100));
|
||||||
|
}
|
||||||
|
panic!("test-owned Valkey did not answer PING on 127.0.0.1:{port} within 10 seconds");
|
||||||
|
}
|
||||||
|
|
||||||
impl Drop for TestValkey {
|
impl Drop for TestValkey {
|
||||||
fn drop(&mut self) {
|
fn drop(&mut self) {
|
||||||
let _ = Command::new("docker").args(["rm", "-f", &self.0]).output();
|
let _ = Command::new("docker").args(["rm", "-f", &self.0]).output();
|
||||||
|
|||||||
@@ -0,0 +1,868 @@
|
|||||||
|
//! Story 3.4 (FR-14) ATDD: progress and cancellation of one synchronous `tools/call`.
|
||||||
|
//!
|
||||||
|
//! Every case drives the real HTTP endpoint of the real application against a real (counted, slow)
|
||||||
|
//! upstream and real published catalog/registry state; nothing here is a fake client of the server
|
||||||
|
//! internals. The oracles are the pinned MCP shapes: `notifications/progress` (monotonic `progress`,
|
||||||
|
//! the request's own `progressToken`, no invented `total`) and the terminal `tools/call` result.
|
||||||
|
//!
|
||||||
|
//! Cancellation is revision-correct: `2025-11-25` cancels with `notifications/cancelled`, and
|
||||||
|
//! `2026-07-28` cancels by closing the request's own response stream. Both are proven to stop the
|
||||||
|
//! work, to release the call, and to never produce a `completed` record.
|
||||||
|
|
||||||
|
use std::{
|
||||||
|
sync::{
|
||||||
|
Arc,
|
||||||
|
atomic::{AtomicUsize, Ordering},
|
||||||
|
},
|
||||||
|
time::Duration,
|
||||||
|
};
|
||||||
|
|
||||||
|
use axum::{Json, Router, routing::post};
|
||||||
|
use crank_core::{InvocationStatus, OperationId, PlatformApiKeyScope};
|
||||||
|
use crank_registry::{ListInvocationLogsQuery, PostgresRegistry, PublishRequest};
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
use time::{OffsetDateTime, format_description::well_known::Rfc3339};
|
||||||
|
use tokio::net::TcpListener;
|
||||||
|
|
||||||
|
use super::common::{
|
||||||
|
agent_mcp_url, build_test_app, capturing_subscriber, create_platform_api_key,
|
||||||
|
initialize_session, post_jsonrpc, post_jsonrpc_with_headers, publish_agent_for_operation,
|
||||||
|
spawn_mcp_server, test_operation, test_registry, test_workspace_id,
|
||||||
|
};
|
||||||
|
|
||||||
|
const LEGACY: &str = "2025-11-25";
|
||||||
|
const MODERN: &str = "2026-07-28";
|
||||||
|
const META_PROTOCOL_VERSION: &str = "io.modelcontextprotocol/protocolVersion";
|
||||||
|
const META_CLIENT_CAPABILITIES: &str = "io.modelcontextprotocol/clientCapabilities";
|
||||||
|
const META_CLIENT_INFO: &str = "io.modelcontextprotocol/clientInfo";
|
||||||
|
|
||||||
|
const TOOL: &str = "crm_lifecycle_lead";
|
||||||
|
/// A call that is long enough for the client to observe real progress, short enough for a suite.
|
||||||
|
const HOLD_MS: u64 = 250;
|
||||||
|
/// A call that is still running when the client cancels it.
|
||||||
|
const LONG_HOLD_MS: u64 = 1_500;
|
||||||
|
/// The grace period after a cancellation. It must exceed [`LONG_HOLD_MS`]: a call that was *not*
|
||||||
|
/// stopped completes its upstream request and records the outcome inside this window, so the checks
|
||||||
|
/// after it prove that the cancellation stopped the call rather than only that it had not finished
|
||||||
|
/// yet.
|
||||||
|
const CANCEL_GRACE_MS: u64 = 2_500;
|
||||||
|
/// The suite depends on that order: the constant must not silently drop back below the hold.
|
||||||
|
const _: () = assert!(CANCEL_GRACE_MS > LONG_HOLD_MS);
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug)]
|
||||||
|
enum Revision {
|
||||||
|
Legacy,
|
||||||
|
Modern,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Revision {
|
||||||
|
const fn label(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Self::Legacy => LEGACY,
|
||||||
|
Self::Modern => MODERN,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Upstream {
|
||||||
|
base_url: String,
|
||||||
|
started: Arc<AtomicUsize>,
|
||||||
|
completed: Arc<AtomicUsize>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A real upstream that records when a request starts and when it finishes. A cancelled call must
|
||||||
|
/// increment `started` exactly once and never `completed`: the request really was dispatched (so the
|
||||||
|
/// outcome is not `certain`-not-sent) and its response really was abandoned (so it is not retried).
|
||||||
|
async fn spawn_counted_slow_upstream(hold_ms: u64) -> Upstream {
|
||||||
|
let started = Arc::new(AtomicUsize::new(0));
|
||||||
|
let completed = Arc::new(AtomicUsize::new(0));
|
||||||
|
let handler_started = Arc::clone(&started);
|
||||||
|
let handler_completed = Arc::clone(&completed);
|
||||||
|
let app = Router::new().route(
|
||||||
|
"/crm/lifecycle-leads",
|
||||||
|
post(move |Json(payload): Json<Value>| {
|
||||||
|
let started = Arc::clone(&handler_started);
|
||||||
|
let completed = Arc::clone(&handler_completed);
|
||||||
|
async move {
|
||||||
|
started.fetch_add(1, Ordering::SeqCst);
|
||||||
|
tokio::time::sleep(Duration::from_millis(hold_ms)).await;
|
||||||
|
completed.fetch_add(1, Ordering::SeqCst);
|
||||||
|
Json(json!({ "id": "lead_123", "email": payload["email"] }))
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||||
|
let address = listener.local_addr().unwrap();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
axum::serve(listener, app).await.unwrap();
|
||||||
|
});
|
||||||
|
Upstream {
|
||||||
|
base_url: format!("http://{address}"),
|
||||||
|
started,
|
||||||
|
completed,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Fixture {
|
||||||
|
client: reqwest::Client,
|
||||||
|
mcp_url: String,
|
||||||
|
api_key: String,
|
||||||
|
other_api_key: String,
|
||||||
|
registry: PostgresRegistry,
|
||||||
|
operation_id: OperationId,
|
||||||
|
upstream: Upstream,
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn fixture(agent_slug: &str, hold_ms: u64, timeout_ms: u64) -> Fixture {
|
||||||
|
let upstream = spawn_counted_slow_upstream(hold_ms).await;
|
||||||
|
let registry = test_registry().await;
|
||||||
|
let mut operation = test_operation(&upstream.base_url, TOOL);
|
||||||
|
let crank_core::Target::Rest(target) = &mut operation.target;
|
||||||
|
target.path_template = "/crm/lifecycle-leads".to_owned();
|
||||||
|
operation.execution_config.timeout_ms = timeout_ms;
|
||||||
|
registry
|
||||||
|
.create_operation(&test_workspace_id(), &operation, Some("alice"))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
registry
|
||||||
|
.publish_operation(PublishRequest {
|
||||||
|
workspace_id: &test_workspace_id(),
|
||||||
|
operation_id: &operation.id,
|
||||||
|
version: 1,
|
||||||
|
published_at: &OffsetDateTime::parse("2026-03-26T10:00:00Z", &Rfc3339).unwrap(),
|
||||||
|
published_by: Some("alice"),
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
publish_agent_for_operation(®istry, &operation, agent_slug).await;
|
||||||
|
let scopes = [PlatformApiKeyScope::Read, PlatformApiKeyScope::Write];
|
||||||
|
let api_key = create_platform_api_key(®istry, agent_slug, "mcp-lifecycle", &scopes).await;
|
||||||
|
let other_api_key =
|
||||||
|
create_platform_api_key(®istry, agent_slug, "mcp-lifecycle-other", &scopes).await;
|
||||||
|
let base_url = spawn_mcp_server(build_test_app(
|
||||||
|
registry.clone(),
|
||||||
|
Duration::ZERO,
|
||||||
|
Some("https://crank.example.com".to_owned()),
|
||||||
|
))
|
||||||
|
.await;
|
||||||
|
|
||||||
|
Fixture {
|
||||||
|
client: reqwest::Client::new(),
|
||||||
|
mcp_url: agent_mcp_url(&base_url, agent_slug),
|
||||||
|
api_key,
|
||||||
|
other_api_key,
|
||||||
|
registry,
|
||||||
|
operation_id: operation.id,
|
||||||
|
upstream,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One parsed answer: the HTTP status, the negotiated media type and every JSON-RPC frame in order.
|
||||||
|
struct Reply {
|
||||||
|
status: reqwest::StatusCode,
|
||||||
|
content_type: String,
|
||||||
|
frames: Vec<Value>,
|
||||||
|
raw: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Reply {
|
||||||
|
fn parse(status: reqwest::StatusCode, content_type: String, body: String) -> Self {
|
||||||
|
let mut frames = Vec::new();
|
||||||
|
for block in body.split("\n\n") {
|
||||||
|
for line in block.lines() {
|
||||||
|
let Some(data) = line.strip_prefix("data:") else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let data = data.trim_start();
|
||||||
|
if data.is_empty() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
frames.push(
|
||||||
|
serde_json::from_str(data)
|
||||||
|
.unwrap_or_else(|error| panic!("every frame is JSON: {data:?} {error}")),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if frames.is_empty() && !body.trim().is_empty() {
|
||||||
|
frames.push(
|
||||||
|
serde_json::from_str(body.trim()).unwrap_or_else(|error| {
|
||||||
|
panic!("expected a JSON-RPC body, got {body:?}: {error}")
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Self {
|
||||||
|
status,
|
||||||
|
content_type,
|
||||||
|
frames,
|
||||||
|
raw: body,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn assert_stream(&self) {
|
||||||
|
assert_eq!(self.status, reqwest::StatusCode::OK);
|
||||||
|
assert!(
|
||||||
|
self.content_type.starts_with("text/event-stream"),
|
||||||
|
"a progress answer must be the request's SSE stream, got {:?}: {}",
|
||||||
|
self.content_type,
|
||||||
|
self.raw
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn progress_frames(&self) -> Vec<&Value> {
|
||||||
|
self.frames
|
||||||
|
.iter()
|
||||||
|
.filter(|frame| frame["method"] == json!("notifications/progress"))
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn terminal(&self) -> &Value {
|
||||||
|
let terminal = self
|
||||||
|
.frames
|
||||||
|
.last()
|
||||||
|
.unwrap_or_else(|| panic!("the stream must carry a terminal frame: {}", self.raw));
|
||||||
|
assert!(
|
||||||
|
terminal.get("method").is_none(),
|
||||||
|
"the terminal frame must be the JSON-RPC response, got {terminal}"
|
||||||
|
);
|
||||||
|
terminal
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Fixture {
|
||||||
|
fn call_params(&self, token: Option<Value>, revision: Revision) -> Value {
|
||||||
|
let mut params = json!({
|
||||||
|
"name": TOOL,
|
||||||
|
"arguments": { "email": "lifecycle@example.com" },
|
||||||
|
});
|
||||||
|
let mut meta = match revision {
|
||||||
|
Revision::Modern => json!({
|
||||||
|
META_PROTOCOL_VERSION: MODERN,
|
||||||
|
META_CLIENT_CAPABILITIES: {},
|
||||||
|
META_CLIENT_INFO: { "name": "crank-3.4-atdd", "version": "0.1.0" },
|
||||||
|
}),
|
||||||
|
Revision::Legacy => json!({}),
|
||||||
|
};
|
||||||
|
if let Some(token) = token {
|
||||||
|
meta["progressToken"] = token;
|
||||||
|
}
|
||||||
|
if meta.as_object().is_some_and(|object| !object.is_empty()) {
|
||||||
|
params["_meta"] = meta;
|
||||||
|
}
|
||||||
|
params
|
||||||
|
}
|
||||||
|
|
||||||
|
fn headers(&self, revision: Revision, session: Option<&str>) -> Vec<(&'static str, String)> {
|
||||||
|
let mut headers = vec![("MCP-Protocol-Version", revision.label().to_owned())];
|
||||||
|
match revision {
|
||||||
|
Revision::Legacy => {
|
||||||
|
if let Some(session) = session {
|
||||||
|
headers.push(("MCP-Session-Id", session.to_owned()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Revision::Modern => {
|
||||||
|
headers.push(("Mcp-Method", "tools/call".to_owned()));
|
||||||
|
headers.push(("Mcp-Name", TOOL.to_owned()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
headers
|
||||||
|
}
|
||||||
|
|
||||||
|
fn request(
|
||||||
|
&self,
|
||||||
|
accept: &'static str,
|
||||||
|
key: &str,
|
||||||
|
headers: &[(&'static str, String)],
|
||||||
|
payload: Value,
|
||||||
|
) -> reqwest::RequestBuilder {
|
||||||
|
let mut request = self
|
||||||
|
.client
|
||||||
|
.post(&self.mcp_url)
|
||||||
|
.header(reqwest::header::ACCEPT, accept)
|
||||||
|
.header(reqwest::header::AUTHORIZATION, format!("Bearer {key}"));
|
||||||
|
for (name, value) in headers {
|
||||||
|
request = request.header(*name, value);
|
||||||
|
}
|
||||||
|
request.json(&payload)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One `tools/call` whose answer is negotiated as the request's own SSE stream.
|
||||||
|
async fn call_stream(
|
||||||
|
&self,
|
||||||
|
revision: Revision,
|
||||||
|
id: u64,
|
||||||
|
params: Value,
|
||||||
|
session: Option<&str>,
|
||||||
|
request_id: &str,
|
||||||
|
) -> Reply {
|
||||||
|
self.call_stream_with_key(revision, &self.api_key, id, params, session, request_id)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn call_stream_with_key(
|
||||||
|
&self,
|
||||||
|
revision: Revision,
|
||||||
|
key: &str,
|
||||||
|
id: u64,
|
||||||
|
params: Value,
|
||||||
|
session: Option<&str>,
|
||||||
|
request_id: &str,
|
||||||
|
) -> Reply {
|
||||||
|
self.send(
|
||||||
|
"text/event-stream",
|
||||||
|
key,
|
||||||
|
revision,
|
||||||
|
id,
|
||||||
|
params,
|
||||||
|
session,
|
||||||
|
Some(request_id),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One `tools/call` whose answer is negotiated as a single JSON body.
|
||||||
|
async fn call_json(
|
||||||
|
&self,
|
||||||
|
revision: Revision,
|
||||||
|
id: u64,
|
||||||
|
params: Value,
|
||||||
|
session: Option<&str>,
|
||||||
|
) -> Reply {
|
||||||
|
self.send(
|
||||||
|
"application/json",
|
||||||
|
&self.api_key,
|
||||||
|
revision,
|
||||||
|
id,
|
||||||
|
params,
|
||||||
|
session,
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(clippy::too_many_arguments)]
|
||||||
|
async fn send(
|
||||||
|
&self,
|
||||||
|
accept: &'static str,
|
||||||
|
key: &str,
|
||||||
|
revision: Revision,
|
||||||
|
id: u64,
|
||||||
|
params: Value,
|
||||||
|
session: Option<&str>,
|
||||||
|
request_id: Option<&str>,
|
||||||
|
) -> Reply {
|
||||||
|
let headers = self.headers(revision, session);
|
||||||
|
let payload =
|
||||||
|
json!({ "jsonrpc": "2.0", "id": id, "method": "tools/call", "params": params });
|
||||||
|
let mut request = self.request(accept, key, &headers, payload);
|
||||||
|
if let Some(request_id) = request_id {
|
||||||
|
request = request.header("x-request-id", request_id);
|
||||||
|
}
|
||||||
|
let response = request.send().await.expect("the MCP endpoint answers");
|
||||||
|
let status = response.status();
|
||||||
|
let content_type = response
|
||||||
|
.headers()
|
||||||
|
.get(reqwest::header::CONTENT_TYPE)
|
||||||
|
.and_then(|value| value.to_str().ok())
|
||||||
|
.unwrap_or_default()
|
||||||
|
.to_owned();
|
||||||
|
let body = response.text().await.expect("the body is readable");
|
||||||
|
Reply::parse(status, content_type, body)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn cancel(&self, key: &str, session: &str, request_id: Value) -> reqwest::StatusCode {
|
||||||
|
let response = self
|
||||||
|
.request(
|
||||||
|
"application/json",
|
||||||
|
key,
|
||||||
|
&[
|
||||||
|
("MCP-Protocol-Version", LEGACY.to_owned()),
|
||||||
|
("MCP-Session-Id", session.to_owned()),
|
||||||
|
],
|
||||||
|
json!({
|
||||||
|
"jsonrpc": "2.0",
|
||||||
|
"method": "notifications/cancelled",
|
||||||
|
"params": { "requestId": request_id, "reason": "user requested cancellation" }
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.expect("the cancellation is acknowledged");
|
||||||
|
response.status()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every Invocation History row of this operation and request id, oldest first.
|
||||||
|
async fn history(&self, request_id: &str) -> Vec<crank_core::InvocationLog> {
|
||||||
|
self.registry
|
||||||
|
.list_invocation_logs(ListInvocationLogsQuery {
|
||||||
|
workspace_id: &test_workspace_id(),
|
||||||
|
level: None,
|
||||||
|
status: None,
|
||||||
|
outcome_group: None,
|
||||||
|
search_text: None,
|
||||||
|
source: Some(crank_core::InvocationSource::AgentToolCall),
|
||||||
|
operation_id: Some(&self.operation_id),
|
||||||
|
agent_id: None,
|
||||||
|
created_after: None,
|
||||||
|
created_before: None,
|
||||||
|
cursor_created_at: None,
|
||||||
|
cursor_id: None,
|
||||||
|
limit: 50,
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
.into_iter()
|
||||||
|
.map(|record| record.log)
|
||||||
|
.filter(|log| log.request_id.as_deref() == Some(request_id))
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Wait for the counted upstream to be entered, so a cancellation happens while it really runs.
|
||||||
|
async fn wait_until_dispatched(&self) {
|
||||||
|
for _ in 0..200 {
|
||||||
|
if self.upstream.started.load(Ordering::SeqCst) > 0 {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
tokio::time::sleep(Duration::from_millis(5)).await;
|
||||||
|
}
|
||||||
|
panic!("the upstream was never dispatched");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn progress_values(frames: &[&Value]) -> Vec<u64> {
|
||||||
|
frames
|
||||||
|
.iter()
|
||||||
|
.map(|frame| {
|
||||||
|
frame["params"]["progress"]
|
||||||
|
.as_u64()
|
||||||
|
.unwrap_or_else(|| panic!("progress must be a number, got {frame}"))
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
// AT-3.4-01: a negotiated stream carries bounded monotonic progress of the real execution, and a
|
||||||
|
// missing token (or a missing carrier) never changes the execution result.
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn at_3_4_01_legacy_progress_stream_is_monotonic_and_ends_with_the_real_result() {
|
||||||
|
let fixture = fixture("lifecycle-legacy-progress", HOLD_MS, 5_000).await;
|
||||||
|
let session = initialize_session(&fixture.client, &fixture.mcp_url, &fixture.api_key).await;
|
||||||
|
|
||||||
|
let reply = fixture
|
||||||
|
.call_stream(
|
||||||
|
Revision::Legacy,
|
||||||
|
501,
|
||||||
|
fixture.call_params(Some(json!("tok-legacy-progress")), Revision::Legacy),
|
||||||
|
Some(&session),
|
||||||
|
"req-legacy-progress",
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
reply.assert_stream();
|
||||||
|
|
||||||
|
let progress = reply.progress_frames();
|
||||||
|
assert!(
|
||||||
|
!progress.is_empty(),
|
||||||
|
"a token with a stream carrier must produce progress, got {}",
|
||||||
|
reply.raw
|
||||||
|
);
|
||||||
|
for frame in &progress {
|
||||||
|
assert_eq!(frame["jsonrpc"], json!("2.0"));
|
||||||
|
assert_eq!(
|
||||||
|
frame["params"]["progressToken"],
|
||||||
|
json!("tok-legacy-progress")
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
frame["params"].get("total").is_none(),
|
||||||
|
"this server knows no total and must not invent one: {frame}"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
frame["params"]["message"].is_string(),
|
||||||
|
"every real step names itself: {frame}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let values = progress_values(&progress);
|
||||||
|
assert!(
|
||||||
|
values.windows(2).all(|pair| pair[0] < pair[1]),
|
||||||
|
"progress must be strictly monotonic, got {values:?}"
|
||||||
|
);
|
||||||
|
// One event per real execution step this server actually crosses: resolved, authorized,
|
||||||
|
// dispatched. Never a timer-driven percentage and never an unbounded stream.
|
||||||
|
assert_eq!(values, vec![1, 2, 3], "got {values:?}");
|
||||||
|
|
||||||
|
let terminal = reply.terminal();
|
||||||
|
assert_eq!(terminal["id"], json!(501));
|
||||||
|
assert_eq!(terminal["error"], Value::Null);
|
||||||
|
assert_eq!(terminal["result"]["isError"], json!(false));
|
||||||
|
assert_eq!(
|
||||||
|
terminal["result"]["structuredContent"],
|
||||||
|
json!({ "id": "lead_123" })
|
||||||
|
);
|
||||||
|
assert_eq!(fixture.upstream.started.load(Ordering::SeqCst), 1);
|
||||||
|
assert_eq!(fixture.upstream.completed.load(Ordering::SeqCst), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn at_3_4_01_modern_progress_stream_is_monotonic_and_ends_with_the_real_result() {
|
||||||
|
let fixture = fixture("lifecycle-modern-progress", HOLD_MS, 5_000).await;
|
||||||
|
|
||||||
|
let reply = fixture
|
||||||
|
.call_stream(
|
||||||
|
Revision::Modern,
|
||||||
|
502,
|
||||||
|
fixture.call_params(Some(json!(77)), Revision::Modern),
|
||||||
|
None,
|
||||||
|
"req-modern-progress",
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
reply.assert_stream();
|
||||||
|
|
||||||
|
let progress = reply.progress_frames();
|
||||||
|
assert!(!progress.is_empty(), "got {}", reply.raw);
|
||||||
|
for frame in &progress {
|
||||||
|
assert_eq!(frame["params"]["progressToken"], json!(77));
|
||||||
|
}
|
||||||
|
let values = progress_values(&progress);
|
||||||
|
assert!(
|
||||||
|
values.windows(2).all(|pair| pair[0] < pair[1]),
|
||||||
|
"{values:?}"
|
||||||
|
);
|
||||||
|
|
||||||
|
let terminal = reply.terminal();
|
||||||
|
assert_eq!(terminal["result"]["isError"], json!(false));
|
||||||
|
assert_eq!(
|
||||||
|
terminal["result"]["structuredContent"],
|
||||||
|
json!({ "id": "lead_123" })
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
// AT-3.4-01 (TL correction): the official SDK sends the dual `Accept` JSON-first. A `tools/call`
|
||||||
|
// that carries a validated token and offers `text/event-stream` in that same header must still be
|
||||||
|
// answered on its own stream, wherever the media types are ordered.
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
#[tokio::test]
|
||||||
|
async fn at_3_4_01_json_first_dual_accept_keeps_progress_for_a_valid_token() {
|
||||||
|
/// Exactly what the official MCP SDK sends when it can read a stream.
|
||||||
|
const SDK_ACCEPT: &str = "application/json, text/event-stream";
|
||||||
|
let fixture = fixture("lifecycle-json-first", HOLD_MS, 5_000).await;
|
||||||
|
let session = initialize_session(&fixture.client, &fixture.mcp_url, &fixture.api_key).await;
|
||||||
|
|
||||||
|
for revision in [Revision::Legacy, Revision::Modern] {
|
||||||
|
let carrier = match revision {
|
||||||
|
Revision::Legacy => Some(session.as_str()),
|
||||||
|
Revision::Modern => None,
|
||||||
|
};
|
||||||
|
let token = json!("tok-json-first");
|
||||||
|
let reply = fixture
|
||||||
|
.send(
|
||||||
|
SDK_ACCEPT,
|
||||||
|
&fixture.api_key,
|
||||||
|
revision,
|
||||||
|
550,
|
||||||
|
fixture.call_params(Some(token.clone()), revision),
|
||||||
|
carrier,
|
||||||
|
Some("req-json-first"),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
reply.assert_stream();
|
||||||
|
|
||||||
|
let progress = reply.progress_frames();
|
||||||
|
assert!(
|
||||||
|
!progress.is_empty(),
|
||||||
|
"{revision:?}: a valid token with an acceptable stream must produce progress, got {}",
|
||||||
|
reply.raw
|
||||||
|
);
|
||||||
|
for frame in &progress {
|
||||||
|
assert_eq!(frame["params"]["progressToken"], token, "{frame}");
|
||||||
|
assert!(
|
||||||
|
frame["params"].get("total").is_none(),
|
||||||
|
"this server knows no total: {frame}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let values = progress_values(&progress);
|
||||||
|
assert!(
|
||||||
|
values.windows(2).all(|pair| pair[0] < pair[1]),
|
||||||
|
"{revision:?}: progress must be strictly monotonic, got {values:?}"
|
||||||
|
);
|
||||||
|
assert_eq!(values, vec![1, 2, 3], "{revision:?}: got {values:?}");
|
||||||
|
|
||||||
|
let terminal = reply.terminal();
|
||||||
|
assert_eq!(terminal["id"], json!(550), "{revision:?}");
|
||||||
|
assert_eq!(terminal["result"]["isError"], json!(false), "{revision:?}");
|
||||||
|
assert_eq!(
|
||||||
|
terminal["result"]["structuredContent"],
|
||||||
|
json!({ "id": "lead_123" }),
|
||||||
|
"{revision:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// The correction is scoped to a call that can actually carry progress: the same JSON-first
|
||||||
|
// header without a token, and with an unusable token, keeps the negotiated single JSON body.
|
||||||
|
for token in [None, Some(json!("x".repeat(4096)))] {
|
||||||
|
let reply = fixture
|
||||||
|
.send(
|
||||||
|
SDK_ACCEPT,
|
||||||
|
&fixture.api_key,
|
||||||
|
Revision::Legacy,
|
||||||
|
551,
|
||||||
|
fixture.call_params(token.clone(), Revision::Legacy),
|
||||||
|
Some(&session),
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(reply.status, reqwest::StatusCode::OK);
|
||||||
|
assert!(
|
||||||
|
reply.content_type.starts_with("application/json"),
|
||||||
|
"token {token:?} must keep the negotiated JSON body, got {:?}: {}",
|
||||||
|
reply.content_type,
|
||||||
|
reply.raw
|
||||||
|
);
|
||||||
|
assert!(reply.progress_frames().is_empty(), "{token:?}");
|
||||||
|
assert_eq!(
|
||||||
|
reply.terminal()["result"]["structuredContent"],
|
||||||
|
json!({ "id": "lead_123" }),
|
||||||
|
"token {token:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn at_3_4_01_no_token_and_no_carrier_keep_the_result_identical() {
|
||||||
|
let fixture = fixture("lifecycle-no-token", HOLD_MS, 5_000).await;
|
||||||
|
let session = initialize_session(&fixture.client, &fixture.mcp_url, &fixture.api_key).await;
|
||||||
|
|
||||||
|
// Without a token the very same call is one plain JSON body: no notification exists.
|
||||||
|
let without_token = fixture
|
||||||
|
.call_json(
|
||||||
|
Revision::Legacy,
|
||||||
|
510,
|
||||||
|
fixture.call_params(None, Revision::Legacy),
|
||||||
|
Some(&session),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(without_token.status, reqwest::StatusCode::OK);
|
||||||
|
assert!(without_token.progress_frames().is_empty());
|
||||||
|
let plain = without_token.terminal()["result"].clone();
|
||||||
|
assert_eq!(plain["isError"], json!(false));
|
||||||
|
|
||||||
|
// With a token but only the `application/json` carrier the result is the same and progress is
|
||||||
|
// simply not sent (the receiver is never obligated to send it).
|
||||||
|
let token_without_carrier = fixture
|
||||||
|
.call_json(
|
||||||
|
Revision::Legacy,
|
||||||
|
511,
|
||||||
|
fixture.call_params(Some(json!("tok-no-carrier")), Revision::Legacy),
|
||||||
|
Some(&session),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(token_without_carrier.status, reqwest::StatusCode::OK);
|
||||||
|
assert!(token_without_carrier.progress_frames().is_empty());
|
||||||
|
assert_eq!(token_without_carrier.terminal()["result"], plain);
|
||||||
|
|
||||||
|
// In the stream mode without a token the only frame is the terminal response itself.
|
||||||
|
let stream_without_token = fixture
|
||||||
|
.call_stream(
|
||||||
|
Revision::Legacy,
|
||||||
|
512,
|
||||||
|
fixture.call_params(None, Revision::Legacy),
|
||||||
|
Some(&session),
|
||||||
|
"req-no-token-stream",
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert!(stream_without_token.progress_frames().is_empty());
|
||||||
|
assert_eq!(stream_without_token.frames.len(), 1);
|
||||||
|
assert_eq!(stream_without_token.terminal()["result"], plain);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The streamed answer keeps the Story 3.18 projection: a client that opted in to logging gets the
|
||||||
|
/// same single closed `notifications/message` of this call before the terminal frame, next to the
|
||||||
|
/// progress events of Story 3.4.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn at_3_4_01_a_progress_stream_keeps_the_logging_projection() {
|
||||||
|
let fixture = fixture("lifecycle-progress-logging", HOLD_MS, 5_000).await;
|
||||||
|
let session = initialize_session(&fixture.client, &fixture.mcp_url, &fixture.api_key).await;
|
||||||
|
let set_level = fixture
|
||||||
|
.request(
|
||||||
|
"application/json",
|
||||||
|
&fixture.api_key,
|
||||||
|
&[
|
||||||
|
("MCP-Protocol-Version", LEGACY.to_owned()),
|
||||||
|
("MCP-Session-Id", session.clone()),
|
||||||
|
],
|
||||||
|
json!({
|
||||||
|
"jsonrpc": "2.0", "id": 900, "method": "logging/setLevel",
|
||||||
|
"params": { "level": "debug" }
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.expect("the level is accepted");
|
||||||
|
assert_eq!(set_level.status(), reqwest::StatusCode::OK);
|
||||||
|
|
||||||
|
let reply = fixture
|
||||||
|
.call_stream(
|
||||||
|
Revision::Legacy,
|
||||||
|
901,
|
||||||
|
fixture.call_params(Some(json!("tok-logging")), Revision::Legacy),
|
||||||
|
Some(&session),
|
||||||
|
"req-progress-logging",
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
reply.assert_stream();
|
||||||
|
assert!(!reply.progress_frames().is_empty(), "got {}", reply.raw);
|
||||||
|
|
||||||
|
let logged: Vec<&Value> = reply
|
||||||
|
.frames
|
||||||
|
.iter()
|
||||||
|
.filter(|frame| frame["method"] == json!("notifications/message"))
|
||||||
|
.collect();
|
||||||
|
assert_eq!(
|
||||||
|
logged.len(),
|
||||||
|
1,
|
||||||
|
"exactly one closed log event per response, got {}",
|
||||||
|
reply.raw
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
logged[0]["params"]["data"]["event"],
|
||||||
|
json!("mcp.request.served")
|
||||||
|
);
|
||||||
|
assert_eq!(logged[0]["params"]["data"]["outcome"], json!("ok"));
|
||||||
|
assert_eq!(reply.terminal()["result"]["isError"], json!(false));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
// AT-3.4-02: a malformed, reused-in-another-scope or oversized token disables progress, and the
|
||||||
|
// token never becomes a metric label, a log field or an authorization scope.
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
#[tokio::test]
|
||||||
|
async fn at_3_4_02_malformed_and_oversized_tokens_disable_progress_without_changing_the_result() {
|
||||||
|
let fixture = fixture("lifecycle-bad-token", HOLD_MS, 5_000).await;
|
||||||
|
let session = initialize_session(&fixture.client, &fixture.mcp_url, &fixture.api_key).await;
|
||||||
|
|
||||||
|
// Both supported revisions read the token from the same pinned `RequestMetaObject` field, so an
|
||||||
|
// unusable token must behave identically in each of them: no progress, unchanged result.
|
||||||
|
for revision in [Revision::Legacy, Revision::Modern] {
|
||||||
|
let carrier = match revision {
|
||||||
|
Revision::Legacy => Some(session.as_str()),
|
||||||
|
Revision::Modern => None,
|
||||||
|
};
|
||||||
|
let tokens = [
|
||||||
|
json!(""),
|
||||||
|
json!({ "not": "a token" }),
|
||||||
|
json!([1, 2]),
|
||||||
|
json!(true),
|
||||||
|
json!("x".repeat(4096)),
|
||||||
|
];
|
||||||
|
let mut observed = Vec::new();
|
||||||
|
for token in tokens {
|
||||||
|
let reply = fixture
|
||||||
|
.call_stream(
|
||||||
|
revision,
|
||||||
|
520,
|
||||||
|
fixture.call_params(Some(token.clone()), revision),
|
||||||
|
carrier,
|
||||||
|
"req-bad-token",
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
observed.push((token, reply));
|
||||||
|
}
|
||||||
|
|
||||||
|
for (token, reply) in observed {
|
||||||
|
assert!(
|
||||||
|
reply.progress_frames().is_empty(),
|
||||||
|
"{revision:?}: token {token} must not produce progress, got {}",
|
||||||
|
reply.raw
|
||||||
|
);
|
||||||
|
let terminal = reply.terminal();
|
||||||
|
assert_eq!(
|
||||||
|
terminal["result"]["structuredContent"],
|
||||||
|
json!({ "id": "lead_123" }),
|
||||||
|
"{revision:?}: token {token} must not change the execution result, got {terminal}"
|
||||||
|
);
|
||||||
|
assert_eq!(terminal["result"]["isError"], json!(false));
|
||||||
|
assert!(terminal["error"].is_null() || terminal.get("error").is_none());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn at_3_4_02_a_reused_token_is_scoped_to_its_own_request() {
|
||||||
|
let fixture = fixture("lifecycle-reused-token", HOLD_MS, 5_000).await;
|
||||||
|
let first = initialize_session(&fixture.client, &fixture.mcp_url, &fixture.api_key).await;
|
||||||
|
let second = initialize_session(&fixture.client, &fixture.mcp_url, &fixture.api_key).await;
|
||||||
|
let token = json!("tok-shared");
|
||||||
|
|
||||||
|
let (first_reply, second_reply) = tokio::join!(
|
||||||
|
fixture.call_stream(
|
||||||
|
Revision::Legacy,
|
||||||
|
530,
|
||||||
|
fixture.call_params(Some(token.clone()), Revision::Legacy),
|
||||||
|
Some(&first),
|
||||||
|
"req-first",
|
||||||
|
),
|
||||||
|
fixture.call_stream(
|
||||||
|
Revision::Legacy,
|
||||||
|
531,
|
||||||
|
fixture.call_params(Some(token.clone()), Revision::Legacy),
|
||||||
|
Some(&second),
|
||||||
|
"req-second",
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
for (reply, id) in [(&first_reply, 530), (&second_reply, 531)] {
|
||||||
|
reply.assert_stream();
|
||||||
|
let values = progress_values(&reply.progress_frames());
|
||||||
|
// Each request counts its own real steps: a reused token never inherits another call's count.
|
||||||
|
assert_eq!(values, vec![1, 2, 3], "request {id} got {values:?}");
|
||||||
|
assert_eq!(reply.terminal()["id"], json!(id));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn at_3_4_02_a_progress_token_never_reaches_logs_or_invocation_history() {
|
||||||
|
const CANARY: &str = "crank-progress-canary-4f1c2d";
|
||||||
|
let fixture = fixture("lifecycle-token-leak", HOLD_MS, 5_000).await;
|
||||||
|
let session = initialize_session(&fixture.client, &fixture.mcp_url, &fixture.api_key).await;
|
||||||
|
let (writer, subscriber) = capturing_subscriber();
|
||||||
|
|
||||||
|
let reply = {
|
||||||
|
let _guard = tracing::subscriber::set_default(subscriber);
|
||||||
|
fixture
|
||||||
|
.call_stream(
|
||||||
|
Revision::Legacy,
|
||||||
|
540,
|
||||||
|
fixture.call_params(Some(json!(CANARY)), Revision::Legacy),
|
||||||
|
Some(&session),
|
||||||
|
"req-token-leak",
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
};
|
||||||
|
reply.assert_stream();
|
||||||
|
|
||||||
|
let logs = writer.output();
|
||||||
|
assert!(
|
||||||
|
logs.contains("mcp request received"),
|
||||||
|
"the capture must really see the endpoint's own log projection, got {logs}"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
!logs.contains(CANARY),
|
||||||
|
"the progress token is client data and must never be logged, got {logs}"
|
||||||
|
);
|
||||||
|
|
||||||
|
let history = fixture.history("req-token-leak").await;
|
||||||
|
assert_eq!(history.len(), 1, "got {history:?}");
|
||||||
|
let row = &history[0];
|
||||||
|
let serialized = serde_json::to_string(row).unwrap();
|
||||||
|
assert!(
|
||||||
|
!serialized.contains(CANARY),
|
||||||
|
"the progress token must never reach Invocation History, got {serialized}"
|
||||||
|
);
|
||||||
|
assert_eq!(row.status, InvocationStatus::Ok);
|
||||||
|
}
|
||||||
|
|
||||||
|
// AT-3.4-03: a cancellation stops a call that can still be stopped, releases it and never yields a
|
||||||
|
// `completed` result or record.
|
||||||
|
mod cancellation;
|
||||||
|
// AT-3.4-05: the client-visible smoke of both supported revisions.
|
||||||
|
mod smoke;
|
||||||
@@ -0,0 +1,294 @@
|
|||||||
|
//! AT-3.4-03: a cancellation stops a call that can still be stopped, releases it, and never yields a
|
||||||
|
//! `completed` result or history row. The harness of the suite lives in `super`.
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
// AT-3.4-03: a cancellation stops a call that can still be stopped, releases it, and never yields a
|
||||||
|
// `completed` result or history row.
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn at_3_4_03_legacy_cancellation_stops_the_call_and_never_completes_it() {
|
||||||
|
let fixture = fixture("lifecycle-legacy-cancel", LONG_HOLD_MS, 30_000).await;
|
||||||
|
let session = initialize_session(&fixture.client, &fixture.mcp_url, &fixture.api_key).await;
|
||||||
|
|
||||||
|
let call_session = session.clone();
|
||||||
|
let call = tokio::spawn({
|
||||||
|
let fixture_client = fixture.client.clone();
|
||||||
|
let mcp_url = fixture.mcp_url.clone();
|
||||||
|
let api_key = fixture.api_key.clone();
|
||||||
|
let params = fixture.call_params(Some(json!("tok-cancel")), Revision::Legacy);
|
||||||
|
async move {
|
||||||
|
let response = fixture_client
|
||||||
|
.post(mcp_url)
|
||||||
|
.header(reqwest::header::ACCEPT, "text/event-stream")
|
||||||
|
.header(reqwest::header::AUTHORIZATION, format!("Bearer {api_key}"))
|
||||||
|
.header("MCP-Protocol-Version", LEGACY)
|
||||||
|
.header("MCP-Session-Id", call_session)
|
||||||
|
.header("x-request-id", "req-legacy-cancel")
|
||||||
|
.json(&json!({
|
||||||
|
"jsonrpc": "2.0",
|
||||||
|
"id": 601,
|
||||||
|
"method": "tools/call",
|
||||||
|
"params": params,
|
||||||
|
}))
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
(response.status(), response.text().await.unwrap())
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
fixture.wait_until_dispatched().await;
|
||||||
|
assert_eq!(
|
||||||
|
fixture.cancel(&fixture.api_key, &session, json!(601)).await,
|
||||||
|
reqwest::StatusCode::ACCEPTED,
|
||||||
|
"an accepted cancellation is acknowledged without a body"
|
||||||
|
);
|
||||||
|
|
||||||
|
let (status, body) = tokio::time::timeout(Duration::from_secs(10), call)
|
||||||
|
.await
|
||||||
|
.expect("the cancelled call is released, it does not hang")
|
||||||
|
.expect("the request task joins");
|
||||||
|
assert_eq!(status, reqwest::StatusCode::OK);
|
||||||
|
let reply = Reply::parse(status, String::new(), body);
|
||||||
|
assert!(
|
||||||
|
reply
|
||||||
|
.frames
|
||||||
|
.iter()
|
||||||
|
.all(|frame| frame.get("method").is_some()),
|
||||||
|
"a cancelled request gets no terminal message, only the progress it already saw: {}",
|
||||||
|
reply.raw
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
reply.progress_frames().len(),
|
||||||
|
3,
|
||||||
|
"the client really saw the real steps before the stop: {}",
|
||||||
|
reply.raw
|
||||||
|
);
|
||||||
|
|
||||||
|
tokio::time::sleep(Duration::from_millis(CANCEL_GRACE_MS)).await;
|
||||||
|
assert_eq!(
|
||||||
|
fixture.upstream.completed.load(Ordering::SeqCst),
|
||||||
|
0,
|
||||||
|
"the abandoned upstream response must never complete the call"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
fixture.upstream.started.load(Ordering::SeqCst),
|
||||||
|
1,
|
||||||
|
"the write really was dispatched and must not be retried automatically"
|
||||||
|
);
|
||||||
|
|
||||||
|
let history = fixture.history("req-legacy-cancel").await;
|
||||||
|
assert!(
|
||||||
|
history.iter().all(|row| row.status != InvocationStatus::Ok),
|
||||||
|
"a cancelled call must never be recorded as completed, got {history:?}"
|
||||||
|
);
|
||||||
|
// The record contract admits a non-`ok` row only with a closed execution error code, and a
|
||||||
|
// cancellation is not one of them: the honest terminal state of this call is "no record" instead
|
||||||
|
// of an invented error code. Either way nothing claims that the call completed.
|
||||||
|
assert!(
|
||||||
|
history.is_empty(),
|
||||||
|
"a stopped call has no terminal outcome to record, got {history:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn at_3_4_03_a_foreign_or_unknown_cancellation_never_touches_the_active_call() {
|
||||||
|
let fixture = fixture("lifecycle-foreign-cancel", HOLD_MS, 5_000).await;
|
||||||
|
let session = initialize_session(&fixture.client, &fixture.mcp_url, &fixture.api_key).await;
|
||||||
|
let foreign_session =
|
||||||
|
initialize_session(&fixture.client, &fixture.mcp_url, &fixture.other_api_key).await;
|
||||||
|
|
||||||
|
let call = tokio::spawn({
|
||||||
|
let client = fixture.client.clone();
|
||||||
|
let mcp_url = fixture.mcp_url.clone();
|
||||||
|
let api_key = fixture.api_key.clone();
|
||||||
|
let call_session = session.clone();
|
||||||
|
let params = fixture.call_params(Some(json!("tok-owner")), Revision::Legacy);
|
||||||
|
async move {
|
||||||
|
let response = client
|
||||||
|
.post(mcp_url)
|
||||||
|
.header(reqwest::header::ACCEPT, "text/event-stream")
|
||||||
|
.header(reqwest::header::AUTHORIZATION, format!("Bearer {api_key}"))
|
||||||
|
.header("MCP-Protocol-Version", LEGACY)
|
||||||
|
.header("MCP-Session-Id", call_session)
|
||||||
|
.header("x-request-id", "req-owner")
|
||||||
|
.json(&json!({
|
||||||
|
"jsonrpc": "2.0", "id": 602, "method": "tools/call", "params": params,
|
||||||
|
}))
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
response.text().await.unwrap()
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
fixture.wait_until_dispatched().await;
|
||||||
|
// A foreign credential of the same agent, and an unknown request id: neither may cancel this call.
|
||||||
|
assert_eq!(
|
||||||
|
fixture
|
||||||
|
.cancel(&fixture.other_api_key, &session, json!(602))
|
||||||
|
.await,
|
||||||
|
reqwest::StatusCode::ACCEPTED
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
fixture
|
||||||
|
.cancel(&fixture.api_key, &session, json!(999_999))
|
||||||
|
.await,
|
||||||
|
reqwest::StatusCode::ACCEPTED
|
||||||
|
);
|
||||||
|
// A foreign session of the same credential cannot reach this call either.
|
||||||
|
assert_eq!(
|
||||||
|
fixture
|
||||||
|
.cancel(&fixture.api_key, &foreign_session, json!(602))
|
||||||
|
.await,
|
||||||
|
reqwest::StatusCode::ACCEPTED
|
||||||
|
);
|
||||||
|
|
||||||
|
let body = tokio::time::timeout(Duration::from_secs(10), call)
|
||||||
|
.await
|
||||||
|
.expect("the untouched call completes")
|
||||||
|
.expect("the request task joins");
|
||||||
|
let reply = Reply::parse(reqwest::StatusCode::OK, String::new(), body);
|
||||||
|
assert_eq!(
|
||||||
|
reply.terminal()["result"]["structuredContent"],
|
||||||
|
json!({ "id": "lead_123" }),
|
||||||
|
"a foreign cancellation must not stop the owner's call, got {}",
|
||||||
|
reply.raw
|
||||||
|
);
|
||||||
|
let history = fixture.history("req-owner").await;
|
||||||
|
assert_eq!(history.len(), 1, "got {history:?}");
|
||||||
|
assert_eq!(history[0].status, InvocationStatus::Ok);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn at_3_4_03_a_late_cancellation_after_the_result_is_ignored() {
|
||||||
|
let fixture = fixture("lifecycle-late-cancel", HOLD_MS, 5_000).await;
|
||||||
|
let session = initialize_session(&fixture.client, &fixture.mcp_url, &fixture.api_key).await;
|
||||||
|
|
||||||
|
let reply = fixture
|
||||||
|
.call_stream(
|
||||||
|
Revision::Legacy,
|
||||||
|
603,
|
||||||
|
fixture.call_params(Some(json!("tok-late")), Revision::Legacy),
|
||||||
|
Some(&session),
|
||||||
|
"req-late-cancel",
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
reply.assert_stream();
|
||||||
|
assert_eq!(reply.terminal()["result"]["isError"], json!(false));
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
fixture.cancel(&fixture.api_key, &session, json!(603)).await,
|
||||||
|
reqwest::StatusCode::ACCEPTED
|
||||||
|
);
|
||||||
|
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||||
|
|
||||||
|
let history = fixture.history("req-late-cancel").await;
|
||||||
|
assert_eq!(
|
||||||
|
history.len(),
|
||||||
|
1,
|
||||||
|
"a cancellation of a finished call must not add a second record, got {history:?}"
|
||||||
|
);
|
||||||
|
assert_eq!(history[0].status, InvocationStatus::Ok);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn at_3_4_03_a_plain_json_call_is_cancellable_too() {
|
||||||
|
let fixture = fixture("lifecycle-json-cancel", LONG_HOLD_MS, 30_000).await;
|
||||||
|
let session = initialize_session(&fixture.client, &fixture.mcp_url, &fixture.api_key).await;
|
||||||
|
|
||||||
|
let call = tokio::spawn({
|
||||||
|
let client = fixture.client.clone();
|
||||||
|
let mcp_url = fixture.mcp_url.clone();
|
||||||
|
let api_key = fixture.api_key.clone();
|
||||||
|
let call_session = session.clone();
|
||||||
|
let params = fixture.call_params(None, Revision::Legacy);
|
||||||
|
async move {
|
||||||
|
let response = client
|
||||||
|
.post(mcp_url)
|
||||||
|
.header(reqwest::header::ACCEPT, "application/json")
|
||||||
|
.header(reqwest::header::AUTHORIZATION, format!("Bearer {api_key}"))
|
||||||
|
.header("MCP-Protocol-Version", LEGACY)
|
||||||
|
.header("MCP-Session-Id", call_session)
|
||||||
|
.header("x-request-id", "req-json-cancel")
|
||||||
|
.json(&json!({
|
||||||
|
"jsonrpc": "2.0", "id": 605, "method": "tools/call", "params": params,
|
||||||
|
}))
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let status = response.status();
|
||||||
|
(status, response.text().await.unwrap())
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
fixture.wait_until_dispatched().await;
|
||||||
|
assert_eq!(
|
||||||
|
fixture.cancel(&fixture.api_key, &session, json!(605)).await,
|
||||||
|
reqwest::StatusCode::ACCEPTED
|
||||||
|
);
|
||||||
|
|
||||||
|
let (status, body) = tokio::time::timeout(Duration::from_secs(10), call)
|
||||||
|
.await
|
||||||
|
.expect("the cancelled call is released")
|
||||||
|
.expect("the request task joins");
|
||||||
|
assert_eq!(status, reqwest::StatusCode::OK);
|
||||||
|
let reply = Reply::parse(status, String::new(), body);
|
||||||
|
assert!(
|
||||||
|
reply.frames.is_empty(),
|
||||||
|
"a cancelled request gets no terminal message, got {}",
|
||||||
|
reply.raw
|
||||||
|
);
|
||||||
|
|
||||||
|
tokio::time::sleep(Duration::from_millis(CANCEL_GRACE_MS)).await;
|
||||||
|
assert_eq!(fixture.upstream.completed.load(Ordering::SeqCst), 0);
|
||||||
|
let history = fixture.history("req-json-cancel").await;
|
||||||
|
assert!(
|
||||||
|
history.iter().all(|row| row.status != InvocationStatus::Ok),
|
||||||
|
"a cancelled call must never be recorded as completed, got {history:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn at_3_4_03_closing_the_modern_response_stream_cancels_the_call() {
|
||||||
|
let fixture = fixture("lifecycle-modern-disconnect", LONG_HOLD_MS, 30_000).await;
|
||||||
|
|
||||||
|
let response = fixture
|
||||||
|
.request(
|
||||||
|
"text/event-stream",
|
||||||
|
&fixture.api_key,
|
||||||
|
&fixture.headers(Revision::Modern, None),
|
||||||
|
json!({
|
||||||
|
"jsonrpc": "2.0",
|
||||||
|
"id": 604,
|
||||||
|
"method": "tools/call",
|
||||||
|
"params": fixture.call_params(Some(json!("tok-disconnect")), Revision::Modern),
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.header("x-request-id", "req-modern-disconnect")
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.expect("the stream opens before the call finishes");
|
||||||
|
assert_eq!(response.status(), reqwest::StatusCode::OK);
|
||||||
|
fixture.wait_until_dispatched().await;
|
||||||
|
|
||||||
|
// The pinned `2026-07-28` cancellation signal: closing the request's own response stream.
|
||||||
|
drop(response);
|
||||||
|
|
||||||
|
tokio::time::sleep(Duration::from_millis(CANCEL_GRACE_MS)).await;
|
||||||
|
assert_eq!(
|
||||||
|
fixture.upstream.completed.load(Ordering::SeqCst),
|
||||||
|
0,
|
||||||
|
"the closed stream must stop the dispatched call instead of letting it finish"
|
||||||
|
);
|
||||||
|
assert_eq!(fixture.upstream.started.load(Ordering::SeqCst), 1);
|
||||||
|
|
||||||
|
let history = fixture.history("req-modern-disconnect").await;
|
||||||
|
assert!(
|
||||||
|
history.iter().all(|row| row.status != InvocationStatus::Ok),
|
||||||
|
"a cancelled call must never be recorded as completed, got {history:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
//! AT-3.4-05: the client-visible smoke of both supported revisions.
|
||||||
|
//!
|
||||||
|
//! A representative client of each revision performs the whole flow a real MCP client performs —
|
||||||
|
//! discovery, then a `tools/call` that asks for progress and reads the request's own stream to the
|
||||||
|
//! terminal response — against the real endpoint. The harness of the suite lives in `super`.
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn at_3_4_05_representative_client_smoke_of_both_revisions() {
|
||||||
|
let fixture = fixture("lifecycle-client-smoke", HOLD_MS, 5_000).await;
|
||||||
|
|
||||||
|
// Legacy client: initialize → tools/list → tools/call with progress.
|
||||||
|
let session = initialize_session(&fixture.client, &fixture.mcp_url, &fixture.api_key).await;
|
||||||
|
let tools = post_jsonrpc(
|
||||||
|
&fixture.client,
|
||||||
|
&fixture.mcp_url,
|
||||||
|
&fixture.api_key,
|
||||||
|
Some(&session),
|
||||||
|
json!({ "jsonrpc": "2.0", "id": 700, "method": "tools/list", "params": {} }),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(tools["result"]["tools"][0]["name"], json!(TOOL));
|
||||||
|
|
||||||
|
let legacy_call = fixture
|
||||||
|
.call_stream(
|
||||||
|
Revision::Legacy,
|
||||||
|
701,
|
||||||
|
fixture.call_params(Some(json!("tok-smoke-legacy")), Revision::Legacy),
|
||||||
|
Some(&session),
|
||||||
|
"req-smoke-legacy",
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
legacy_call.assert_stream();
|
||||||
|
assert_eq!(
|
||||||
|
legacy_call.terminal()["result"]["structuredContent"],
|
||||||
|
json!({ "id": "lead_123" })
|
||||||
|
);
|
||||||
|
|
||||||
|
// Modern client: `tools/list` and `tools/call` of the stateless revision, progress on the stream.
|
||||||
|
let modern_list = post_jsonrpc_with_headers(
|
||||||
|
&fixture.client,
|
||||||
|
&fixture.mcp_url,
|
||||||
|
&fixture.api_key,
|
||||||
|
&[
|
||||||
|
("MCP-Protocol-Version", MODERN),
|
||||||
|
("Mcp-Method", "tools/list"),
|
||||||
|
],
|
||||||
|
json!({
|
||||||
|
"jsonrpc": "2.0",
|
||||||
|
"id": 710,
|
||||||
|
"method": "tools/list",
|
||||||
|
"params": { "_meta": {
|
||||||
|
META_PROTOCOL_VERSION: MODERN,
|
||||||
|
META_CLIENT_CAPABILITIES: {},
|
||||||
|
META_CLIENT_INFO: { "name": "crank-3.4-smoke", "version": "0.1.0" },
|
||||||
|
}}
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
let modern_list = modern_list.json::<Value>().await.unwrap();
|
||||||
|
assert_eq!(modern_list["result"]["tools"][0]["name"], json!(TOOL));
|
||||||
|
|
||||||
|
let modern_call = fixture
|
||||||
|
.call_stream(
|
||||||
|
Revision::Modern,
|
||||||
|
711,
|
||||||
|
fixture.call_params(Some(json!("tok-smoke-modern")), Revision::Modern),
|
||||||
|
None,
|
||||||
|
"req-smoke-modern",
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
modern_call.assert_stream();
|
||||||
|
assert!(!modern_call.progress_frames().is_empty());
|
||||||
|
assert_eq!(
|
||||||
|
modern_call.terminal()["result"]["structuredContent"],
|
||||||
|
json!({ "id": "lead_123" })
|
||||||
|
);
|
||||||
|
}
|
||||||
+1
-1
@@ -10,7 +10,7 @@ COPY crank-community.png ./crank-community.png
|
|||||||
|
|
||||||
RUN npm run build
|
RUN npm run build
|
||||||
|
|
||||||
FROM nginx:1.30.4-alpine3.24-slim
|
FROM nginx:1.30.6-alpine3.24-slim
|
||||||
|
|
||||||
RUN apk add --no-cache --upgrade \
|
RUN apk add --no-cache --upgrade \
|
||||||
'pcre2>=10.49-r0' \
|
'pcre2>=10.49-r0' \
|
||||||
|
|||||||
@@ -30,6 +30,7 @@ mod approval_policy;
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
pub(crate) mod dispatch_observer;
|
pub(crate) mod dispatch_observer;
|
||||||
mod invocation_history;
|
mod invocation_history;
|
||||||
|
pub(crate) mod lifecycle;
|
||||||
mod metrics;
|
mod metrics;
|
||||||
mod request;
|
mod request;
|
||||||
mod response;
|
mod response;
|
||||||
@@ -49,6 +50,7 @@ mod approvals;
|
|||||||
mod auth_resolution;
|
mod auth_resolution;
|
||||||
mod dispatch;
|
mod dispatch;
|
||||||
mod endpoint;
|
mod endpoint;
|
||||||
|
mod legacy_dispatch;
|
||||||
|
|
||||||
use self::approvals::{
|
use self::approvals::{
|
||||||
approve_request, deny_request, get_approval_request, list_pending_approvals,
|
approve_request, deny_request, get_approval_request, list_pending_approvals,
|
||||||
@@ -85,6 +87,11 @@ pub(super) struct AppState {
|
|||||||
/// Story 3.18: the bounded in-memory `logging/setLevel` opt-in of the legacy sessions. It is a
|
/// Story 3.18: the bounded in-memory `logging/setLevel` opt-in of the legacy sessions. It is a
|
||||||
/// client-scoped level, never a process-global one, and it needs no schema migration.
|
/// client-scoped level, never a process-global one, and it needs no schema migration.
|
||||||
pub(super) logging_levels: Arc<crate::protocol::LogLevelStore>,
|
pub(super) logging_levels: Arc<crate::protocol::LogLevelStore>,
|
||||||
|
/// Story 3.19: the bounded table of the legacy session that currently owns the notification
|
||||||
|
/// stream, so one session never broadcasts the same list-change signal into two streams.
|
||||||
|
pub(super) signal_streams: Arc<crate::protocol::StreamRegistry>,
|
||||||
|
/// Story 3.4: the bounded table of the `tools/call` requests a legacy client can still cancel.
|
||||||
|
pub(super) in_flight: Arc<self::lifecycle::InFlightCalls>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
@@ -252,6 +259,10 @@ fn build_app_inner(
|
|||||||
credential_verifier,
|
credential_verifier,
|
||||||
allowed_origins: AllowedOrigins::new(public_base_url),
|
allowed_origins: AllowedOrigins::new(public_base_url),
|
||||||
logging_levels: Arc::new(crate::protocol::LogLevelStore::new()),
|
logging_levels: Arc::new(crate::protocol::LogLevelStore::new()),
|
||||||
|
signal_streams: Arc::new(crate::protocol::StreamRegistry::new()),
|
||||||
|
in_flight: Arc::new(lifecycle::InFlightCalls::new(
|
||||||
|
lifecycle::MAX_IN_FLIGHT_CALLS,
|
||||||
|
)),
|
||||||
});
|
});
|
||||||
if start_background_workers {
|
if start_background_workers {
|
||||||
spawn_approval_recovery(Arc::clone(&state));
|
spawn_approval_recovery(Arc::clone(&state));
|
||||||
|
|||||||
@@ -23,7 +23,9 @@ use crate::{
|
|||||||
},
|
},
|
||||||
session::SessionState,
|
session::SessionState,
|
||||||
tool_error::execution_locale,
|
tool_error::execution_locale,
|
||||||
transport::{ResponseMode, json_response, session_id_from_headers, transport_response},
|
transport::{
|
||||||
|
ResponseMode, json_response, session_id_from_headers, sse_response, transport_response,
|
||||||
|
},
|
||||||
};
|
};
|
||||||
use axum::{
|
use axum::{
|
||||||
http::{HeaderMap, StatusCode},
|
http::{HeaderMap, StatusCode},
|
||||||
@@ -37,8 +39,7 @@ use time::OffsetDateTime;
|
|||||||
use super::response::{
|
use super::response::{
|
||||||
completion_result, internal_jsonrpc_error, prompt_arguments_error_response, prompt_get_result,
|
completion_result, internal_jsonrpc_error, prompt_arguments_error_response, prompt_get_result,
|
||||||
prompts_list_result, resource_error_response, resource_read_result,
|
prompts_list_result, resource_error_response, resource_read_result,
|
||||||
resource_templates_list_result, resources_list_result, tool_command_response,
|
resource_templates_list_result, resources_list_result, tools_list_result,
|
||||||
tools_list_result,
|
|
||||||
};
|
};
|
||||||
use super::{AgentRoutePath, AppState, TRANSPORT_SESSION_TTL_MS};
|
use super::{AgentRoutePath, AppState, TRANSPORT_SESSION_TTL_MS};
|
||||||
use crate::protocol::{ResourceTemplatesListError, list_resource_templates};
|
use crate::protocol::{ResourceTemplatesListError, list_resource_templates};
|
||||||
@@ -154,6 +155,8 @@ pub(super) async fn handle_modern_request(
|
|||||||
locale: execution_locale(message),
|
locale: execution_locale(message),
|
||||||
},
|
},
|
||||||
ToolsCommand::List(list_command),
|
ToolsCommand::List(list_command),
|
||||||
|
// A list command has no progress or cancellation lifecycle (Story 3.4).
|
||||||
|
None,
|
||||||
)
|
)
|
||||||
.await;
|
.await;
|
||||||
match outcome {
|
match outcome {
|
||||||
@@ -218,30 +221,35 @@ pub(super) async fn handle_modern_request(
|
|||||||
// session-less, so its calls cannot advertise elicitation support.
|
// session-less, so its calls cannot advertise elicitation support.
|
||||||
let mut arguments = tool_call_params.arguments.unwrap_or_else(|| json!({}));
|
let mut arguments = tool_call_params.arguments.unwrap_or_else(|| json!({}));
|
||||||
let confirmation_token = take_confirmation_token(&mut arguments);
|
let confirmation_token = take_confirmation_token(&mut arguments);
|
||||||
let outcome = handle_tools_command(
|
// Story 3.4: the client's own `_meta.progressToken` of this request, validated and bounded.
|
||||||
state,
|
let progress = crate::app::lifecycle::token_from_meta(tool_call_params.meta.as_ref());
|
||||||
ServiceContext {
|
super::lifecycle::run_tool_call(
|
||||||
workspace_slug: &path.workspace_slug,
|
Arc::clone(state),
|
||||||
agent_slug: &path.agent_slug,
|
crate::app::lifecycle::ToolCallRequest {
|
||||||
credential,
|
workspace_slug: path.workspace_slug.clone(),
|
||||||
correlation: transport_correlation,
|
agent_slug: path.agent_slug.clone(),
|
||||||
|
credential: credential.clone(),
|
||||||
|
correlation: transport_correlation.clone(),
|
||||||
continuation: ContinuationSupport::ElicitationUnsupported,
|
continuation: ContinuationSupport::ElicitationUnsupported,
|
||||||
locale: execution_locale(message),
|
locale: execution_locale(message),
|
||||||
},
|
},
|
||||||
ToolsCommand::Call(ToolCallCommand {
|
crate::app::lifecycle::ToolCallWire {
|
||||||
|
message: message.clone(),
|
||||||
|
protocol_version: version.to_owned(),
|
||||||
|
response_mode,
|
||||||
|
progress,
|
||||||
|
session_id: None,
|
||||||
|
// The modern revision cancels by closing this request's response stream, so no
|
||||||
|
// session-scoped cancellation table is involved.
|
||||||
|
in_flight: None,
|
||||||
|
},
|
||||||
|
ToolCallCommand {
|
||||||
tool_name: tool_call_params.name,
|
tool_name: tool_call_params.name,
|
||||||
arguments,
|
arguments,
|
||||||
confirmation_token,
|
confirmation_token,
|
||||||
}),
|
},
|
||||||
)
|
|
||||||
.await;
|
|
||||||
tool_command_response(
|
|
||||||
message,
|
|
||||||
response_mode,
|
|
||||||
version,
|
|
||||||
transport_correlation,
|
|
||||||
outcome,
|
|
||||||
)
|
)
|
||||||
|
.await
|
||||||
}
|
}
|
||||||
DispatchDecision::Allowed {
|
DispatchDecision::Allowed {
|
||||||
handler: MethodHandler::ResourceList,
|
handler: MethodHandler::ResourceList,
|
||||||
@@ -658,6 +666,80 @@ pub(super) async fn handle_modern_request(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// Story 3.19: the modern long-lived notification stream. The response is itself the SSE
|
||||||
|
// stream that stays open, so it is built here instead of going through the one-shot
|
||||||
|
// response helpers: the acknowledgment is its first frame, then the coalesced list-change
|
||||||
|
// signals, and closing the HTTP stream ends the producer.
|
||||||
|
DispatchDecision::Allowed {
|
||||||
|
handler: MethodHandler::SubscriptionsListen,
|
||||||
|
..
|
||||||
|
} => {
|
||||||
|
// A notification stream is an SSE body by construction: a client that did not offer
|
||||||
|
// `text/event-stream` could not receive it.
|
||||||
|
if !crate::transport::accepts_event_stream(headers) {
|
||||||
|
return StatusCode::NOT_ACCEPTABLE.into_response();
|
||||||
|
}
|
||||||
|
let filter: crate::protocol::ListenParams =
|
||||||
|
match serde_json::from_value(params(message)) {
|
||||||
|
Ok(filter) => filter,
|
||||||
|
Err(_) => {
|
||||||
|
return transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
jsonrpc_error(
|
||||||
|
request_id(message),
|
||||||
|
-32602,
|
||||||
|
crate::protocol::INVALID_LISTEN_FILTER,
|
||||||
|
),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
Some(version),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let accepted = match filter.notifications.accepted() {
|
||||||
|
crate::protocol::FilterOutcome::Accepted(accepted) => accepted,
|
||||||
|
crate::protocol::FilterOutcome::Invalid(detail) => {
|
||||||
|
return transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
jsonrpc_error(request_id(message), -32602, detail),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
Some(version),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
// The subscription id is the JSON-RPC id of this request; a value whose encoding is not
|
||||||
|
// bounded cannot be a frame identity carrier and is refused before the stream opens.
|
||||||
|
let Some(subscription_id) = crate::protocol::subscription_id(&request_id(message))
|
||||||
|
else {
|
||||||
|
return transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
jsonrpc_error(request_id(message), -32600, "invalid JSON-RPC message"),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
Some(version),
|
||||||
|
);
|
||||||
|
};
|
||||||
|
let Ok(permit) = super::metrics::ActiveStreamGuard::try_acquire(&state.session_slots)
|
||||||
|
else {
|
||||||
|
return StatusCode::TOO_MANY_REQUESTS.into_response();
|
||||||
|
};
|
||||||
|
let acknowledged = crate::protocol::acknowledged_frame(&subscription_id, accepted);
|
||||||
|
let receiver = crate::protocol::spawn_signal_watch(
|
||||||
|
Arc::clone(state),
|
||||||
|
crate::protocol::Watch {
|
||||||
|
workspace_slug: path.workspace_slug.clone(),
|
||||||
|
agent_slug: path.agent_slug.clone(),
|
||||||
|
signals: accepted,
|
||||||
|
wire: crate::protocol::Wire::Modern(subscription_id),
|
||||||
|
legacy_stream: None,
|
||||||
|
deadline: None,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
let stream = crate::protocol::frames_stream(vec![acknowledged], receiver, permit);
|
||||||
|
|
||||||
|
sse_response(StatusCode::OK, stream, None, Some(version))
|
||||||
|
}
|
||||||
// The standard Prompt requests are registered capabilities now; any other
|
// The standard Prompt requests are registered capabilities now; any other
|
||||||
// unregistered/wrong-era method goes straight to the era-correct unsupported answer.
|
// unregistered/wrong-era method goes straight to the era-correct unsupported answer.
|
||||||
_ => crate::protocol::modern_method_not_found_response(message),
|
_ => crate::protocol::modern_method_not_found_response(message),
|
||||||
|
|||||||
@@ -3,32 +3,22 @@
|
|||||||
//!
|
//!
|
||||||
//! Moved verbatim out of `app.rs` (Story 3.6, kanban t_987bf309); `mcp_post_response` is reached from
|
//! Moved verbatim out of `app.rs` (Story 3.6, kanban t_987bf309); `mcp_post_response` is reached from
|
||||||
//! `build_app_inner` via `mcp_post`, hence `pub(super)`. No behaviour changed.
|
//! `build_app_inner` via `mcp_post`, hence `pub(super)`. No behaviour changed.
|
||||||
|
//!
|
||||||
|
//! The legacy-era dispatch itself lives in `super::legacy_dispatch` (Story 3.18 code-health, kanban
|
||||||
|
//! t_d1b45ddc) to keep this transport entry file inside the 1000-line limit.
|
||||||
|
|
||||||
use super::metrics::{ActiveStreamGuard, McpRequestMetrics};
|
use super::metrics::{ActiveStreamGuard, McpRequestMetrics};
|
||||||
use super::request::ToolCallParams;
|
|
||||||
use super::response::take_confirmation_token;
|
|
||||||
use super::stages::{enforce_traced_rate_limit, require_traced_machine_access};
|
use super::stages::{enforce_traced_rate_limit, require_traced_machine_access};
|
||||||
use crate::{
|
use crate::{
|
||||||
jsonrpc::{
|
jsonrpc::{jsonrpc_error, method_name, request_id},
|
||||||
LEGACY_PROTOCOL_VERSION, is_notification, is_request, jsonrpc_error, jsonrpc_result,
|
|
||||||
method_name, params, request_id,
|
|
||||||
},
|
|
||||||
protocol::{
|
protocol::{
|
||||||
CompletionCommand, CompletionOutcome, ContinuationSupport, DispatchDecision,
|
EnvelopeKind, RequestEra, ambiguous_session_carrier_response, resolve_request_identity,
|
||||||
EVENT_LEVEL_APPLIED, EnvelopeKind, INVALID_LEVEL, Kind, LoggingOutcome, MethodHandler,
|
|
||||||
PromptGetCommand, PromptsCommand, PromptsListCommand, PromptsOutcome, RequestEra,
|
|
||||||
ResourceReadCommand, ResourcesCommand, ResourcesListCommand, ResourcesOutcome,
|
|
||||||
ServiceContext, SetLevelCommand, ToolCallCommand, ToolsCommand, ToolsListCommand,
|
|
||||||
ToolsOutcome, ambiguous_session_carrier_response, handle_completion_command,
|
|
||||||
handle_logging_command, handle_prompts_command, handle_resources_command,
|
|
||||||
handle_tools_command, resolve_request_identity,
|
|
||||||
},
|
},
|
||||||
rate_limit::{rate_limited_jsonrpc_response, rate_limited_status_response},
|
rate_limit::{rate_limited_jsonrpc_response, rate_limited_status_response},
|
||||||
request_context::RequestContext,
|
request_context::RequestContext,
|
||||||
tool_error::execution_locale,
|
|
||||||
transport::{
|
transport::{
|
||||||
accepts_event_stream, negotiate_post_response_mode, session_id_from_headers, sse_response,
|
ResponseMode, accepts_event_stream, negotiate_post_response_mode, session_id_from_headers,
|
||||||
transport_response, validate_get_accept_header, validate_origin,
|
sse_response, transport_response, validate_get_accept_header, validate_origin,
|
||||||
validate_session_protocol_version, with_request_id_header,
|
validate_session_protocol_version, with_request_id_header,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
@@ -36,24 +26,14 @@ use axum::{
|
|||||||
Json,
|
Json,
|
||||||
extract::{Extension, Path, State, rejection::JsonRejection},
|
extract::{Extension, Path, State, rejection::JsonRejection},
|
||||||
http::{HeaderMap, StatusCode},
|
http::{HeaderMap, StatusCode},
|
||||||
response::{IntoResponse, Response, sse::Event},
|
response::{IntoResponse, Response},
|
||||||
};
|
};
|
||||||
use crank_core::{CorrelationContext, PlatformApiKeyScope};
|
use crank_core::{CorrelationContext, PlatformApiKeyScope};
|
||||||
use futures_util::stream;
|
use serde_json::Value;
|
||||||
use serde_json::{Value, json};
|
use std::{sync::Arc, time::Duration, time::Instant};
|
||||||
use std::{convert::Infallible, sync::Arc, time::Duration};
|
|
||||||
use tracing::info;
|
use tracing::info;
|
||||||
|
|
||||||
use super::dispatch::{
|
use super::dispatch::handle_modern_request;
|
||||||
handle_initialize, handle_initialized_notification, handle_modern_request,
|
|
||||||
require_initialized_session,
|
|
||||||
};
|
|
||||||
use super::response::{
|
|
||||||
completion_result, internal_jsonrpc_error, prompt_arguments_error_response, prompt_get_result,
|
|
||||||
prompts_list_result, resource_error_response, resource_read_result,
|
|
||||||
resource_templates_list_result, resources_list_result, tool_command_response,
|
|
||||||
tools_list_result,
|
|
||||||
};
|
|
||||||
use super::{AgentRoutePath, AppState, TRANSPORT_SESSION_TTL_MS};
|
use super::{AgentRoutePath, AppState, TRANSPORT_SESSION_TTL_MS};
|
||||||
pub(super) async fn mcp_get(
|
pub(super) async fn mcp_get(
|
||||||
Path(path): Path<AgentRoutePath>,
|
Path(path): Path<AgentRoutePath>,
|
||||||
@@ -122,11 +102,32 @@ pub(super) async fn mcp_get(
|
|||||||
return StatusCode::TOO_MANY_REQUESTS.into_response();
|
return StatusCode::TOO_MANY_REQUESTS.into_response();
|
||||||
};
|
};
|
||||||
|
|
||||||
let stream = stream::unfold(permit, |permit| async move {
|
// Story 3.19: the pinned legacy transport forbids broadcasting one JSON-RPC message across the
|
||||||
tokio::time::sleep(Duration::from_millis(TRANSPORT_SESSION_TTL_MS)).await;
|
// SSE streams of a session, so exactly one admitted `GET` receives the Resource/Prompt/Tool
|
||||||
drop(permit);
|
// list-change signals. A newer `GET` takes them over and the older stream simply ends; a
|
||||||
None::<(Result<Event, Infallible>, _)>
|
// `DELETE` retires the producer, so a stale generation never writes into a reconnect.
|
||||||
});
|
let Some(generation) = state.signal_streams.admit(&session_id) else {
|
||||||
|
// The bounded owner table is contended: refuse this admission instead of waiting.
|
||||||
|
return StatusCode::TOO_MANY_REQUESTS.into_response();
|
||||||
|
};
|
||||||
|
let receiver = crate::protocol::spawn_signal_watch(
|
||||||
|
Arc::clone(&state),
|
||||||
|
crate::protocol::Watch {
|
||||||
|
workspace_slug: path.workspace_slug.clone(),
|
||||||
|
agent_slug: path.agent_slug.clone(),
|
||||||
|
signals: crate::protocol::Signals::ALL,
|
||||||
|
wire: crate::protocol::Wire::Legacy,
|
||||||
|
legacy_stream: Some((
|
||||||
|
Arc::clone(&state.signal_streams),
|
||||||
|
session_id.clone(),
|
||||||
|
generation,
|
||||||
|
)),
|
||||||
|
deadline: Some(Instant::now() + Duration::from_millis(TRANSPORT_SESSION_TTL_MS)),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
// The stream permit lives in the response stream: a client that closes the SSE connection ends
|
||||||
|
// the producer and releases the slot, and no signal is queued for a reader that is gone.
|
||||||
|
let stream = crate::protocol::frames_stream(Vec::new(), receiver, permit);
|
||||||
|
|
||||||
sse_response(
|
sse_response(
|
||||||
StatusCode::OK,
|
StatusCode::OK,
|
||||||
@@ -179,6 +180,7 @@ pub(super) async fn mcp_delete(
|
|||||||
|
|
||||||
match state.sessions.delete(&session_id).await {
|
match state.sessions.delete(&session_id).await {
|
||||||
Ok(true) => {
|
Ok(true) => {
|
||||||
|
state.signal_streams.retire(&session_id);
|
||||||
state.session_metrics.refresh();
|
state.session_metrics.refresh();
|
||||||
StatusCode::NO_CONTENT.into_response()
|
StatusCode::NO_CONTENT.into_response()
|
||||||
}
|
}
|
||||||
@@ -254,7 +256,7 @@ async fn mcp_post_response(
|
|||||||
return status.into_response();
|
return status.into_response();
|
||||||
}
|
}
|
||||||
|
|
||||||
let response_mode = match negotiate_post_response_mode(headers) {
|
let mut response_mode = match negotiate_post_response_mode(headers) {
|
||||||
Ok(mode) => mode,
|
Ok(mode) => mode,
|
||||||
Err(status) => return status.into_response(),
|
Err(status) => return status.into_response(),
|
||||||
};
|
};
|
||||||
@@ -363,6 +365,19 @@ async fn mcp_post_response(
|
|||||||
Err(error) => return error.into_response(),
|
Err(error) => return error.into_response(),
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Story 3.4 correction: the official SDK lists the media types JSON-first. For a `tools/call`
|
||||||
|
// that carries a validated progress token and offered `text/event-stream`, the stream is the only
|
||||||
|
// carrier that can deliver the progress the client asked for, so the media-type order is not a
|
||||||
|
// preference for the JSON body here. Every other request — another method, no token, an unusable
|
||||||
|
// token, a JSON-only `Accept` — keeps the negotiated mode, and no admission check moved.
|
||||||
|
if matches!(response_mode, ResponseMode::Json)
|
||||||
|
&& method_name(message) == Some("tools/call")
|
||||||
|
&& accepts_event_stream(headers)
|
||||||
|
&& crate::app::lifecycle::token_from_meta(message.pointer("/params/_meta")).is_some()
|
||||||
|
{
|
||||||
|
response_mode = ResponseMode::Sse;
|
||||||
|
}
|
||||||
|
|
||||||
if matches!(identity.era, RequestEra::Modern) {
|
if matches!(identity.era, RequestEra::Modern) {
|
||||||
// ERA_MODERN_ENTER (spec section 7.2): this request entered the modern era-adapter.
|
// ERA_MODERN_ENTER (spec section 7.2): this request entered the modern era-adapter.
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
@@ -384,675 +399,17 @@ async fn mcp_post_response(
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
crate::app::dispatch_observer::era_legacy_enter();
|
crate::app::dispatch_observer::era_legacy_enter();
|
||||||
|
|
||||||
// R5/F5: the owning registration decides *which handler* serves this method in the request's
|
// R5/F5: the owning registration decides which handler serves this method in the request's
|
||||||
// revision. The adapter holds no method list of its own — the method-to-handler mapping lives in
|
// revision; that legacy dispatch lives in `super::legacy_dispatch`.
|
||||||
// `protocol::registry` and is read through `dispatch_decision`, so a newly registered method
|
super::legacy_dispatch::handle_legacy_request(
|
||||||
// really reaches its handler and removing a descriptor removes the dispatch.
|
state,
|
||||||
let registration_revision = protocol_version
|
path,
|
||||||
.as_deref()
|
headers,
|
||||||
.unwrap_or(LEGACY_PROTOCOL_VERSION);
|
message,
|
||||||
let dispatch = crate::protocol::dispatch_decision(
|
response_mode,
|
||||||
method_name(message).unwrap_or_default(),
|
&identity,
|
||||||
registration_revision,
|
&credential,
|
||||||
);
|
transport_correlation,
|
||||||
match dispatch {
|
)
|
||||||
// G2: the *registered kind* of the matched method, not the envelope shape, decides which
|
.await
|
||||||
// legacy lifecycle action runs. `initialize` is a request and `notifications/initialized` is a
|
|
||||||
// notification: the two share one handler but are not interchangeable, so an `initialize`
|
|
||||||
// notification may not initialize an existing session and a `notifications/initialized`
|
|
||||||
// request may not create one.
|
|
||||||
DispatchDecision::Allowed {
|
|
||||||
handler: MethodHandler::Lifecycle,
|
|
||||||
kind: Kind::Method,
|
|
||||||
} if is_request(message) => handle_initialize(state, path, message, response_mode).await,
|
|
||||||
DispatchDecision::Allowed {
|
|
||||||
handler: MethodHandler::Lifecycle,
|
|
||||||
kind: Kind::Notification,
|
|
||||||
} if is_notification(message) => {
|
|
||||||
handle_initialized_notification(state, path, headers).await
|
|
||||||
}
|
|
||||||
DispatchDecision::Allowed {
|
|
||||||
handler: MethodHandler::Ping,
|
|
||||||
..
|
|
||||||
} if is_request(message) => {
|
|
||||||
let session = match require_initialized_session(&state, path, headers, message).await {
|
|
||||||
Ok(session) => session,
|
|
||||||
Err(response) => return response,
|
|
||||||
};
|
|
||||||
|
|
||||||
transport_response(
|
|
||||||
StatusCode::OK,
|
|
||||||
jsonrpc_result(
|
|
||||||
request_id(message),
|
|
||||||
json!({ "protocolVersion": session.protocol_version }),
|
|
||||||
),
|
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
Some(&session.protocol_version),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
DispatchDecision::Allowed {
|
|
||||||
handler: MethodHandler::ToolList,
|
|
||||||
..
|
|
||||||
} if is_request(message) => {
|
|
||||||
let session = match require_initialized_session(&state, path, headers, message).await {
|
|
||||||
Ok(session) => session,
|
|
||||||
Err(response) => return response,
|
|
||||||
};
|
|
||||||
|
|
||||||
// The adapter parses the wire form and maps the neutral outcome back; the shared Tools
|
|
||||||
// service never sees the envelope, the response mode or the protocol revision.
|
|
||||||
let list_command: ToolsListCommand = match serde_json::from_value(params(message)) {
|
|
||||||
Ok(value) => value,
|
|
||||||
Err(_) => {
|
|
||||||
return transport_response(
|
|
||||||
StatusCode::OK,
|
|
||||||
jsonrpc_error(request_id(message), -32602, "invalid tools/list parameters"),
|
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
Some(&session.protocol_version),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let outcome = handle_tools_command(
|
|
||||||
&state,
|
|
||||||
ServiceContext {
|
|
||||||
workspace_slug: &session.workspace_slug,
|
|
||||||
agent_slug: &session.agent_slug,
|
|
||||||
credential: &credential,
|
|
||||||
correlation: transport_correlation,
|
|
||||||
continuation: ContinuationSupport::from_supported(session.supports_elicitation),
|
|
||||||
locale: execution_locale(message),
|
|
||||||
},
|
|
||||||
ToolsCommand::List(list_command),
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
match outcome {
|
|
||||||
ToolsOutcome::List { tools, next_cursor } => transport_response(
|
|
||||||
StatusCode::OK,
|
|
||||||
jsonrpc_result(request_id(message), tools_list_result(tools, next_cursor)),
|
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
Some(&session.protocol_version),
|
|
||||||
),
|
|
||||||
ToolsOutcome::InvalidParams(message_text) => transport_response(
|
|
||||||
StatusCode::OK,
|
|
||||||
jsonrpc_error(request_id(message), -32602, message_text),
|
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
Some(&session.protocol_version),
|
|
||||||
),
|
|
||||||
ToolsOutcome::CatalogUnavailable => {
|
|
||||||
internal_jsonrpc_error(message, "published catalog is unavailable")
|
|
||||||
}
|
|
||||||
// A list command never produces a call outcome; it is answered with the adapter's
|
|
||||||
// internal error instead of being silently ignored.
|
|
||||||
ToolsOutcome::Call(_) => internal_jsonrpc_error(
|
|
||||||
message,
|
|
||||||
"unexpected shared tools outcome for a tools/list",
|
|
||||||
),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
DispatchDecision::Allowed {
|
|
||||||
handler: MethodHandler::ToolCall,
|
|
||||||
..
|
|
||||||
} if is_request(message) => {
|
|
||||||
let session = match require_initialized_session(&state, path, headers, message).await {
|
|
||||||
Ok(session) => session,
|
|
||||||
Err(response) => return response,
|
|
||||||
};
|
|
||||||
let tool_call_params: ToolCallParams = match serde_json::from_value(params(message)) {
|
|
||||||
Ok(value) => value,
|
|
||||||
Err(_) => {
|
|
||||||
return transport_response(
|
|
||||||
StatusCode::OK,
|
|
||||||
jsonrpc_error(request_id(message), -32602, "invalid tool call parameters"),
|
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
Some(&session.protocol_version),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// The adapter owns the wire form: it parses the call parameters, removes the reserved
|
|
||||||
// confirmation marker and the shared Tools service never sees the envelope, the
|
|
||||||
// response mode or the protocol revision (spec section 6.2).
|
|
||||||
let mut arguments = tool_call_params.arguments.unwrap_or_else(|| json!({}));
|
|
||||||
let confirmation_token = take_confirmation_token(&mut arguments);
|
|
||||||
let outcome = handle_tools_command(
|
|
||||||
&state,
|
|
||||||
ServiceContext {
|
|
||||||
workspace_slug: &session.workspace_slug,
|
|
||||||
agent_slug: &session.agent_slug,
|
|
||||||
credential: &credential,
|
|
||||||
correlation: transport_correlation,
|
|
||||||
continuation: ContinuationSupport::from_supported(session.supports_elicitation),
|
|
||||||
locale: execution_locale(message),
|
|
||||||
},
|
|
||||||
ToolsCommand::Call(ToolCallCommand {
|
|
||||||
tool_name: tool_call_params.name,
|
|
||||||
arguments,
|
|
||||||
confirmation_token,
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
tool_command_response(
|
|
||||||
message,
|
|
||||||
response_mode,
|
|
||||||
&session.protocol_version,
|
|
||||||
transport_correlation,
|
|
||||||
outcome,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
DispatchDecision::Allowed {
|
|
||||||
handler: MethodHandler::ResourceList,
|
|
||||||
..
|
|
||||||
} if is_request(message) => {
|
|
||||||
let session = match require_initialized_session(&state, path, headers, message).await {
|
|
||||||
Ok(session) => session,
|
|
||||||
Err(response) => return response,
|
|
||||||
};
|
|
||||||
let list_command: ResourcesListCommand = match serde_json::from_value(params(message)) {
|
|
||||||
Ok(value) => value,
|
|
||||||
Err(_) => {
|
|
||||||
return transport_response(
|
|
||||||
StatusCode::OK,
|
|
||||||
jsonrpc_error(
|
|
||||||
request_id(message),
|
|
||||||
-32602,
|
|
||||||
"invalid resources/list parameters",
|
|
||||||
),
|
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
Some(&session.protocol_version),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let outcome = handle_resources_command(
|
|
||||||
&state,
|
|
||||||
ServiceContext {
|
|
||||||
workspace_slug: &session.workspace_slug,
|
|
||||||
agent_slug: &session.agent_slug,
|
|
||||||
credential: &credential,
|
|
||||||
correlation: transport_correlation,
|
|
||||||
continuation: ContinuationSupport::from_supported(session.supports_elicitation),
|
|
||||||
locale: execution_locale(message),
|
|
||||||
},
|
|
||||||
&session.protocol_version,
|
|
||||||
ResourcesCommand::List(list_command),
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
match outcome {
|
|
||||||
ResourcesOutcome::Listed {
|
|
||||||
resources,
|
|
||||||
next_cursor,
|
|
||||||
} => transport_response(
|
|
||||||
StatusCode::OK,
|
|
||||||
jsonrpc_result(
|
|
||||||
request_id(message),
|
|
||||||
resources_list_result(resources, next_cursor),
|
|
||||||
),
|
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
Some(&session.protocol_version),
|
|
||||||
),
|
|
||||||
ResourcesOutcome::InvalidParams(detail) => transport_response(
|
|
||||||
StatusCode::OK,
|
|
||||||
jsonrpc_error(request_id(message), -32602, detail),
|
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
Some(&session.protocol_version),
|
|
||||||
),
|
|
||||||
_ => internal_jsonrpc_error(message, "published resources are unavailable"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
DispatchDecision::Allowed {
|
|
||||||
handler: MethodHandler::ResourceRead,
|
|
||||||
..
|
|
||||||
} if is_request(message) => {
|
|
||||||
let session = match require_initialized_session(&state, path, headers, message).await {
|
|
||||||
Ok(session) => session,
|
|
||||||
Err(response) => return response,
|
|
||||||
};
|
|
||||||
let read_command: ResourceReadCommand = match serde_json::from_value(params(message)) {
|
|
||||||
Ok(value) => value,
|
|
||||||
Err(_) => {
|
|
||||||
return transport_response(
|
|
||||||
StatusCode::OK,
|
|
||||||
jsonrpc_error(
|
|
||||||
request_id(message),
|
|
||||||
-32602,
|
|
||||||
"invalid resources/read parameters",
|
|
||||||
),
|
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
Some(&session.protocol_version),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let outcome = handle_resources_command(
|
|
||||||
&state,
|
|
||||||
ServiceContext {
|
|
||||||
workspace_slug: &session.workspace_slug,
|
|
||||||
agent_slug: &session.agent_slug,
|
|
||||||
credential: &credential,
|
|
||||||
correlation: transport_correlation,
|
|
||||||
continuation: ContinuationSupport::from_supported(session.supports_elicitation),
|
|
||||||
locale: execution_locale(message),
|
|
||||||
},
|
|
||||||
&session.protocol_version,
|
|
||||||
ResourcesCommand::Read(read_command),
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
match outcome {
|
|
||||||
ResourcesOutcome::Read { contents } => transport_response(
|
|
||||||
StatusCode::OK,
|
|
||||||
jsonrpc_result(request_id(message), resource_read_result(contents)),
|
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
Some(&session.protocol_version),
|
|
||||||
),
|
|
||||||
ResourcesOutcome::NotAvailable => transport_response(
|
|
||||||
StatusCode::OK,
|
|
||||||
jsonrpc_error(
|
|
||||||
request_id(message),
|
|
||||||
-32602,
|
|
||||||
"the requested resource is not available",
|
|
||||||
),
|
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
Some(&session.protocol_version),
|
|
||||||
),
|
|
||||||
ResourcesOutcome::InvalidParams(detail) => transport_response(
|
|
||||||
StatusCode::OK,
|
|
||||||
jsonrpc_error(request_id(message), -32602, detail),
|
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
Some(&session.protocol_version),
|
|
||||||
),
|
|
||||||
ResourcesOutcome::ExecutionError(contract) => resource_error_response(
|
|
||||||
message,
|
|
||||||
response_mode,
|
|
||||||
&session.protocol_version,
|
|
||||||
contract,
|
|
||||||
),
|
|
||||||
_ => internal_jsonrpc_error(message, "published resources are unavailable"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Story 3.11: the shared service returns exact bound Published templates; the legacy adapter
|
|
||||||
// retains its earlier result shape and still requires the initialized session.
|
|
||||||
DispatchDecision::Allowed {
|
|
||||||
handler: MethodHandler::ResourceTemplateList,
|
|
||||||
..
|
|
||||||
} if is_request(message) => {
|
|
||||||
let session = match require_initialized_session(&state, path, headers, message).await {
|
|
||||||
Ok(session) => session,
|
|
||||||
Err(response) => return response,
|
|
||||||
};
|
|
||||||
|
|
||||||
let command: ResourcesListCommand = match serde_json::from_value(params(message)) {
|
|
||||||
Ok(command) => command,
|
|
||||||
Err(_) => {
|
|
||||||
return transport_response(
|
|
||||||
StatusCode::OK,
|
|
||||||
jsonrpc_error(
|
|
||||||
request_id(message),
|
|
||||||
-32602,
|
|
||||||
"invalid resources/templates/list parameters",
|
|
||||||
),
|
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
Some(&session.protocol_version),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let (templates, next_cursor) = match crate::protocol::list_resource_templates(
|
|
||||||
&state,
|
|
||||||
&path.workspace_slug,
|
|
||||||
&path.agent_slug,
|
|
||||||
&session.protocol_version,
|
|
||||||
command,
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
{
|
|
||||||
Ok(page) => page,
|
|
||||||
Err(crate::protocol::ResourceTemplatesListError::InvalidCursor) => {
|
|
||||||
return transport_response(
|
|
||||||
StatusCode::OK,
|
|
||||||
jsonrpc_error(
|
|
||||||
request_id(message),
|
|
||||||
-32602,
|
|
||||||
"invalid resources/templates/list cursor",
|
|
||||||
),
|
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
Some(&session.protocol_version),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
Err(crate::protocol::ResourceTemplatesListError::Unavailable) => {
|
|
||||||
return internal_jsonrpc_error(message, "published templates are unavailable");
|
|
||||||
}
|
|
||||||
};
|
|
||||||
transport_response(
|
|
||||||
StatusCode::OK,
|
|
||||||
jsonrpc_result(
|
|
||||||
request_id(message),
|
|
||||||
resource_templates_list_result(templates, next_cursor),
|
|
||||||
),
|
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
Some(&session.protocol_version),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
// Story 3.14: `prompts/list` / `prompts/get` of the initialized legacy session, served from
|
|
||||||
// the same exact bound Published Prompt Versions as the modern era.
|
|
||||||
DispatchDecision::Allowed {
|
|
||||||
handler: MethodHandler::PromptList,
|
|
||||||
..
|
|
||||||
} if is_request(message) => {
|
|
||||||
let session = match require_initialized_session(&state, path, headers, message).await {
|
|
||||||
Ok(session) => session,
|
|
||||||
Err(response) => return response,
|
|
||||||
};
|
|
||||||
let command: PromptsListCommand = match serde_json::from_value(params(message)) {
|
|
||||||
Ok(command) => command,
|
|
||||||
Err(_) => {
|
|
||||||
return transport_response(
|
|
||||||
StatusCode::OK,
|
|
||||||
jsonrpc_error(
|
|
||||||
request_id(message),
|
|
||||||
-32602,
|
|
||||||
"invalid prompts/list parameters",
|
|
||||||
),
|
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
Some(&session.protocol_version),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let outcome = handle_prompts_command(
|
|
||||||
&state,
|
|
||||||
ServiceContext {
|
|
||||||
workspace_slug: &session.workspace_slug,
|
|
||||||
agent_slug: &session.agent_slug,
|
|
||||||
credential: &credential,
|
|
||||||
correlation: transport_correlation,
|
|
||||||
continuation: ContinuationSupport::from_supported(session.supports_elicitation),
|
|
||||||
locale: execution_locale(message),
|
|
||||||
},
|
|
||||||
&session.protocol_version,
|
|
||||||
PromptsCommand::List(command),
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
match outcome {
|
|
||||||
PromptsOutcome::Listed {
|
|
||||||
prompts,
|
|
||||||
next_cursor,
|
|
||||||
} => transport_response(
|
|
||||||
StatusCode::OK,
|
|
||||||
jsonrpc_result(
|
|
||||||
request_id(message),
|
|
||||||
prompts_list_result(prompts, next_cursor),
|
|
||||||
),
|
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
Some(&session.protocol_version),
|
|
||||||
),
|
|
||||||
PromptsOutcome::InvalidParams(detail) => transport_response(
|
|
||||||
StatusCode::OK,
|
|
||||||
jsonrpc_error(request_id(message), -32602, detail),
|
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
Some(&session.protocol_version),
|
|
||||||
),
|
|
||||||
_ => internal_jsonrpc_error(message, "published prompts are unavailable"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
DispatchDecision::Allowed {
|
|
||||||
handler: MethodHandler::PromptGet,
|
|
||||||
..
|
|
||||||
} if is_request(message) => {
|
|
||||||
let session = match require_initialized_session(&state, path, headers, message).await {
|
|
||||||
Ok(session) => session,
|
|
||||||
Err(response) => return response,
|
|
||||||
};
|
|
||||||
let command: PromptGetCommand = match serde_json::from_value(params(message)) {
|
|
||||||
Ok(command) => command,
|
|
||||||
Err(_) => {
|
|
||||||
return transport_response(
|
|
||||||
StatusCode::OK,
|
|
||||||
jsonrpc_error(
|
|
||||||
request_id(message),
|
|
||||||
-32602,
|
|
||||||
"invalid prompts/get parameters",
|
|
||||||
),
|
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
Some(&session.protocol_version),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let outcome = handle_prompts_command(
|
|
||||||
&state,
|
|
||||||
ServiceContext {
|
|
||||||
workspace_slug: &session.workspace_slug,
|
|
||||||
agent_slug: &session.agent_slug,
|
|
||||||
credential: &credential,
|
|
||||||
correlation: transport_correlation,
|
|
||||||
continuation: ContinuationSupport::from_supported(session.supports_elicitation),
|
|
||||||
locale: execution_locale(message),
|
|
||||||
},
|
|
||||||
&session.protocol_version,
|
|
||||||
PromptsCommand::Get(command),
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
match outcome {
|
|
||||||
PromptsOutcome::Got {
|
|
||||||
description,
|
|
||||||
messages,
|
|
||||||
} => transport_response(
|
|
||||||
StatusCode::OK,
|
|
||||||
jsonrpc_result(
|
|
||||||
request_id(message),
|
|
||||||
prompt_get_result(description, messages),
|
|
||||||
),
|
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
Some(&session.protocol_version),
|
|
||||||
),
|
|
||||||
PromptsOutcome::NotAvailable => transport_response(
|
|
||||||
StatusCode::OK,
|
|
||||||
jsonrpc_error(
|
|
||||||
request_id(message),
|
|
||||||
-32602,
|
|
||||||
"the requested prompt is not available",
|
|
||||||
),
|
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
Some(&session.protocol_version),
|
|
||||||
),
|
|
||||||
PromptsOutcome::ArgumentsRejected { reason, argument } => {
|
|
||||||
prompt_arguments_error_response(
|
|
||||||
message,
|
|
||||||
response_mode,
|
|
||||||
&session.protocol_version,
|
|
||||||
reason,
|
|
||||||
argument,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
PromptsOutcome::DependencyUnavailable { position } => transport_response(
|
|
||||||
StatusCode::OK,
|
|
||||||
jsonrpc_error(
|
|
||||||
request_id(message),
|
|
||||||
-32603,
|
|
||||||
format!("the pinned dependency at dependencies[{position}] is unavailable"),
|
|
||||||
),
|
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
Some(&session.protocol_version),
|
|
||||||
),
|
|
||||||
PromptsOutcome::InvalidParams(detail) => transport_response(
|
|
||||||
StatusCode::OK,
|
|
||||||
jsonrpc_error(request_id(message), -32602, detail),
|
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
Some(&session.protocol_version),
|
|
||||||
),
|
|
||||||
_ => internal_jsonrpc_error(message, "published prompts are unavailable"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Story 3.17: `completion/complete` of the initialized legacy session. The shared service is
|
|
||||||
// the same one the modern era uses; only the result envelope differs (no `resultType`).
|
|
||||||
DispatchDecision::Allowed {
|
|
||||||
handler: MethodHandler::Completion,
|
|
||||||
..
|
|
||||||
} if is_request(message) => {
|
|
||||||
let session = match require_initialized_session(&state, path, headers, message).await {
|
|
||||||
Ok(session) => session,
|
|
||||||
Err(response) => return response,
|
|
||||||
};
|
|
||||||
let command: CompletionCommand = match serde_json::from_value(params(message)) {
|
|
||||||
Ok(command) => command,
|
|
||||||
Err(_) => {
|
|
||||||
return transport_response(
|
|
||||||
StatusCode::OK,
|
|
||||||
jsonrpc_error(
|
|
||||||
request_id(message),
|
|
||||||
-32602,
|
|
||||||
"invalid completion/complete parameters",
|
|
||||||
),
|
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
Some(&session.protocol_version),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let outcome = handle_completion_command(
|
|
||||||
&state,
|
|
||||||
ServiceContext {
|
|
||||||
workspace_slug: &session.workspace_slug,
|
|
||||||
agent_slug: &session.agent_slug,
|
|
||||||
credential: &credential,
|
|
||||||
correlation: transport_correlation,
|
|
||||||
continuation: ContinuationSupport::from_supported(session.supports_elicitation),
|
|
||||||
locale: execution_locale(message),
|
|
||||||
},
|
|
||||||
&session.protocol_version,
|
|
||||||
command,
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
match outcome {
|
|
||||||
CompletionOutcome::Completed {
|
|
||||||
values,
|
|
||||||
total,
|
|
||||||
has_more,
|
|
||||||
} => transport_response(
|
|
||||||
StatusCode::OK,
|
|
||||||
jsonrpc_result(
|
|
||||||
request_id(message),
|
|
||||||
completion_result(values, total, has_more),
|
|
||||||
),
|
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
Some(&session.protocol_version),
|
|
||||||
),
|
|
||||||
CompletionOutcome::InvalidParams(detail) => transport_response(
|
|
||||||
StatusCode::OK,
|
|
||||||
jsonrpc_error(request_id(message), -32602, detail),
|
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
Some(&session.protocol_version),
|
|
||||||
),
|
|
||||||
CompletionOutcome::NotAvailable => transport_response(
|
|
||||||
StatusCode::OK,
|
|
||||||
jsonrpc_error(
|
|
||||||
request_id(message),
|
|
||||||
-32602,
|
|
||||||
"the completion reference is not available",
|
|
||||||
),
|
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
Some(&session.protocol_version),
|
|
||||||
),
|
|
||||||
CompletionOutcome::CatalogUnavailable => {
|
|
||||||
internal_jsonrpc_error(message, "published completion sources are unavailable")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Story 3.18: the pinned legacy `logging/setLevel`. The level belongs to the initialized
|
|
||||||
// session of this request, so setting it can never change another client's level. The request
|
|
||||||
// answers an empty result; the acknowledgment event is filtered by the level it just set.
|
|
||||||
DispatchDecision::Allowed {
|
|
||||||
handler: MethodHandler::LoggingSetLevel,
|
|
||||||
..
|
|
||||||
} if is_request(message) => {
|
|
||||||
let session = match require_initialized_session(&state, path, headers, message).await {
|
|
||||||
Ok(session) => session,
|
|
||||||
Err(response) => return response,
|
|
||||||
};
|
|
||||||
let command: SetLevelCommand = match serde_json::from_value(params(message)) {
|
|
||||||
Ok(command) => command,
|
|
||||||
// A non-string, missing or otherwise unparsable level shares the one safe detail of a
|
|
||||||
// value outside the pinned union: nothing the client sent is echoed back.
|
|
||||||
Err(_) => {
|
|
||||||
return transport_response(
|
|
||||||
StatusCode::OK,
|
|
||||||
jsonrpc_error(request_id(message), -32602, INVALID_LEVEL),
|
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
Some(&session.protocol_version),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
match handle_logging_command(&state.logging_levels, &session.id, command) {
|
|
||||||
LoggingOutcome::Applied(level) => {
|
|
||||||
crate::protocol::set_active_level(Some(level));
|
|
||||||
crate::protocol::note(
|
|
||||||
crate::protocol::LogLevel::Notice,
|
|
||||||
EVENT_LEVEL_APPLIED,
|
|
||||||
"applied",
|
|
||||||
);
|
|
||||||
transport_response(
|
|
||||||
StatusCode::OK,
|
|
||||||
jsonrpc_result(request_id(message), json!({})),
|
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
Some(&session.protocol_version),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
LoggingOutcome::InvalidParams(detail) => transport_response(
|
|
||||||
StatusCode::OK,
|
|
||||||
jsonrpc_error(request_id(message), -32602, detail),
|
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
Some(&session.protocol_version),
|
|
||||||
),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// A notification whose method the registration does not map to this adapter's handlers is
|
|
||||||
// acknowledged without being dispatched, exactly as before.
|
|
||||||
_ if is_notification(message) => StatusCode::ACCEPTED.into_response(),
|
|
||||||
// Every remaining decision (unregistered, wrong era, or a handler this adapter does not
|
|
||||||
// serve) is a method-level rejection: no handler, no service entry, no outbound call.
|
|
||||||
_ => match method_name(message) {
|
|
||||||
Some(method) => transport_response(
|
|
||||||
StatusCode::OK,
|
|
||||||
jsonrpc_error(
|
|
||||||
request_id(message),
|
|
||||||
-32601,
|
|
||||||
format!("method {method} is not supported"),
|
|
||||||
),
|
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
protocol_version.as_deref(),
|
|
||||||
),
|
|
||||||
None => transport_response(
|
|
||||||
StatusCode::BAD_REQUEST,
|
|
||||||
jsonrpc_error(Value::Null, -32600, "invalid JSON-RPC message"),
|
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
protocol_version.as_deref(),
|
|
||||||
),
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,794 @@
|
|||||||
|
//! Legacy-era JSON-RPC dispatch: the registered method-to-handler mapping, the
|
||||||
|
//! initialized-session guard and every legacy envelope the transport endpoint answers.
|
||||||
|
//!
|
||||||
|
//! Moved verbatim out of `app/endpoint.rs` (Story 3.18 code-health, kanban t_d1b45ddc) so the
|
||||||
|
//! transport entry file stays inside the 1000-line limit; the entry point is `pub(super)`.
|
||||||
|
//! No behaviour changed.
|
||||||
|
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use axum::{
|
||||||
|
http::{HeaderMap, StatusCode},
|
||||||
|
response::{IntoResponse, Response},
|
||||||
|
};
|
||||||
|
use crank_core::CorrelationContext;
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
|
||||||
|
use super::dispatch::{
|
||||||
|
handle_initialize, handle_initialized_notification, require_initialized_session,
|
||||||
|
};
|
||||||
|
use super::request::ToolCallParams;
|
||||||
|
use super::response::{
|
||||||
|
completion_result, internal_jsonrpc_error, prompt_arguments_error_response, prompt_get_result,
|
||||||
|
prompts_list_result, resource_error_response, resource_read_result,
|
||||||
|
resource_templates_list_result, resources_list_result, take_confirmation_token,
|
||||||
|
tools_list_result,
|
||||||
|
};
|
||||||
|
use super::{AgentRoutePath, AppState};
|
||||||
|
use crate::{
|
||||||
|
auth::VerifiedMachineCredential,
|
||||||
|
jsonrpc::{
|
||||||
|
LEGACY_PROTOCOL_VERSION, is_notification, is_request, jsonrpc_error, jsonrpc_result,
|
||||||
|
method_name, params, request_id,
|
||||||
|
},
|
||||||
|
protocol::{
|
||||||
|
CompletionCommand, CompletionOutcome, ContinuationSupport, DispatchDecision,
|
||||||
|
EVENT_LEVEL_APPLIED, INVALID_LEVEL, Kind, LoggingOutcome, MethodHandler, PromptGetCommand,
|
||||||
|
PromptsCommand, PromptsListCommand, PromptsOutcome, RequestIdentity, ResourceReadCommand,
|
||||||
|
ResourcesCommand, ResourcesListCommand, ResourcesOutcome, ServiceContext, SetLevelCommand,
|
||||||
|
ToolCallCommand, ToolsCommand, ToolsListCommand, ToolsOutcome, handle_completion_command,
|
||||||
|
handle_logging_command, handle_prompts_command, handle_resources_command,
|
||||||
|
handle_tools_command,
|
||||||
|
},
|
||||||
|
tool_error::execution_locale,
|
||||||
|
transport::{ResponseMode, session_id_from_headers, transport_response},
|
||||||
|
};
|
||||||
|
|
||||||
|
// The transport invariants of one request travel together here; a parameter struct would only
|
||||||
|
// duplicate them (the same shape every other dispatch entry point in this crate uses).
|
||||||
|
#[allow(clippy::too_many_arguments)]
|
||||||
|
pub(super) async fn handle_legacy_request(
|
||||||
|
state: Arc<AppState>,
|
||||||
|
path: &AgentRoutePath,
|
||||||
|
headers: &HeaderMap,
|
||||||
|
message: &Value,
|
||||||
|
response_mode: ResponseMode,
|
||||||
|
identity: &RequestIdentity,
|
||||||
|
credential: &VerifiedMachineCredential,
|
||||||
|
transport_correlation: &CorrelationContext,
|
||||||
|
) -> Response {
|
||||||
|
let protocol_version = identity.version.as_deref();
|
||||||
|
|
||||||
|
// R5/F5: the owning registration decides *which handler* serves this method in the request's
|
||||||
|
// revision. The adapter holds no method list of its own — the method-to-handler mapping lives in
|
||||||
|
// `protocol::registry` and is read through `dispatch_decision`, so a newly registered method
|
||||||
|
// really reaches its handler and removing a descriptor removes the dispatch.
|
||||||
|
let registration_revision = protocol_version.unwrap_or(LEGACY_PROTOCOL_VERSION);
|
||||||
|
let dispatch = crate::protocol::dispatch_decision(
|
||||||
|
method_name(message).unwrap_or_default(),
|
||||||
|
registration_revision,
|
||||||
|
);
|
||||||
|
match dispatch {
|
||||||
|
// G2: the *registered kind* of the matched method, not the envelope shape, decides which
|
||||||
|
// legacy lifecycle action runs. `initialize` is a request and `notifications/initialized` is a
|
||||||
|
// notification: the two share one handler but are not interchangeable, so an `initialize`
|
||||||
|
// notification may not initialize an existing session and a `notifications/initialized`
|
||||||
|
// request may not create one.
|
||||||
|
DispatchDecision::Allowed {
|
||||||
|
handler: MethodHandler::Lifecycle,
|
||||||
|
kind: Kind::Method,
|
||||||
|
} if is_request(message) => handle_initialize(state, path, message, response_mode).await,
|
||||||
|
DispatchDecision::Allowed {
|
||||||
|
handler: MethodHandler::Lifecycle,
|
||||||
|
kind: Kind::Notification,
|
||||||
|
} if is_notification(message) => {
|
||||||
|
handle_initialized_notification(state, path, headers).await
|
||||||
|
}
|
||||||
|
DispatchDecision::Allowed {
|
||||||
|
handler: MethodHandler::Ping,
|
||||||
|
..
|
||||||
|
} if is_request(message) => {
|
||||||
|
let session = match require_initialized_session(&state, path, headers, message).await {
|
||||||
|
Ok(session) => session,
|
||||||
|
Err(response) => return response,
|
||||||
|
};
|
||||||
|
|
||||||
|
transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
jsonrpc_result(
|
||||||
|
request_id(message),
|
||||||
|
json!({ "protocolVersion": session.protocol_version }),
|
||||||
|
),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
Some(&session.protocol_version),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
DispatchDecision::Allowed {
|
||||||
|
handler: MethodHandler::ToolList,
|
||||||
|
..
|
||||||
|
} if is_request(message) => {
|
||||||
|
let session = match require_initialized_session(&state, path, headers, message).await {
|
||||||
|
Ok(session) => session,
|
||||||
|
Err(response) => return response,
|
||||||
|
};
|
||||||
|
|
||||||
|
// The adapter parses the wire form and maps the neutral outcome back; the shared Tools
|
||||||
|
// service never sees the envelope, the response mode or the protocol revision.
|
||||||
|
let list_command: ToolsListCommand = match serde_json::from_value(params(message)) {
|
||||||
|
Ok(value) => value,
|
||||||
|
Err(_) => {
|
||||||
|
return transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
jsonrpc_error(request_id(message), -32602, "invalid tools/list parameters"),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
Some(&session.protocol_version),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let outcome = handle_tools_command(
|
||||||
|
&state,
|
||||||
|
ServiceContext {
|
||||||
|
workspace_slug: &session.workspace_slug,
|
||||||
|
agent_slug: &session.agent_slug,
|
||||||
|
credential,
|
||||||
|
correlation: transport_correlation,
|
||||||
|
continuation: ContinuationSupport::from_supported(session.supports_elicitation),
|
||||||
|
locale: execution_locale(message),
|
||||||
|
},
|
||||||
|
ToolsCommand::List(list_command),
|
||||||
|
// A list command has no progress or cancellation lifecycle (Story 3.4).
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
match outcome {
|
||||||
|
ToolsOutcome::List { tools, next_cursor } => transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
jsonrpc_result(request_id(message), tools_list_result(tools, next_cursor)),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
Some(&session.protocol_version),
|
||||||
|
),
|
||||||
|
ToolsOutcome::InvalidParams(message_text) => transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
jsonrpc_error(request_id(message), -32602, message_text),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
Some(&session.protocol_version),
|
||||||
|
),
|
||||||
|
ToolsOutcome::CatalogUnavailable => {
|
||||||
|
internal_jsonrpc_error(message, "published catalog is unavailable")
|
||||||
|
}
|
||||||
|
// A list command never produces a call outcome; it is answered with the adapter's
|
||||||
|
// internal error instead of being silently ignored.
|
||||||
|
ToolsOutcome::Call(_) => internal_jsonrpc_error(
|
||||||
|
message,
|
||||||
|
"unexpected shared tools outcome for a tools/list",
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
DispatchDecision::Allowed {
|
||||||
|
handler: MethodHandler::ToolCall,
|
||||||
|
..
|
||||||
|
} if is_request(message) => {
|
||||||
|
let session = match require_initialized_session(&state, path, headers, message).await {
|
||||||
|
Ok(session) => session,
|
||||||
|
Err(response) => return response,
|
||||||
|
};
|
||||||
|
let tool_call_params: ToolCallParams = match serde_json::from_value(params(message)) {
|
||||||
|
Ok(value) => value,
|
||||||
|
Err(_) => {
|
||||||
|
return transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
jsonrpc_error(request_id(message), -32602, "invalid tool call parameters"),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
Some(&session.protocol_version),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// The adapter owns the wire form: it parses the call parameters, removes the reserved
|
||||||
|
// confirmation marker and the shared Tools service never sees the envelope, the
|
||||||
|
// response mode or the protocol revision (spec section 6.2).
|
||||||
|
let mut arguments = tool_call_params.arguments.unwrap_or_else(|| json!({}));
|
||||||
|
let confirmation_token = take_confirmation_token(&mut arguments);
|
||||||
|
// Story 3.4: the client's own `_meta.progressToken`, validated and bounded, and the
|
||||||
|
// session/credential ownership of the in-flight cancellation table.
|
||||||
|
let progress = crate::app::lifecycle::token_from_meta(tool_call_params.meta.as_ref());
|
||||||
|
super::lifecycle::run_tool_call(
|
||||||
|
Arc::clone(&state),
|
||||||
|
crate::app::lifecycle::ToolCallRequest {
|
||||||
|
workspace_slug: session.workspace_slug.clone(),
|
||||||
|
agent_slug: session.agent_slug.clone(),
|
||||||
|
credential: credential.clone(),
|
||||||
|
correlation: transport_correlation.clone(),
|
||||||
|
continuation: ContinuationSupport::from_supported(session.supports_elicitation),
|
||||||
|
locale: execution_locale(message),
|
||||||
|
},
|
||||||
|
crate::app::lifecycle::ToolCallWire {
|
||||||
|
message: message.clone(),
|
||||||
|
protocol_version: session.protocol_version.clone(),
|
||||||
|
response_mode,
|
||||||
|
progress,
|
||||||
|
session_id: Some(session.id.clone()),
|
||||||
|
in_flight: Some(crate::app::lifecycle::InFlightScope {
|
||||||
|
session_id: session.id.clone(),
|
||||||
|
owner: in_flight_owner(credential),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
ToolCallCommand {
|
||||||
|
tool_name: tool_call_params.name,
|
||||||
|
arguments,
|
||||||
|
confirmation_token,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
DispatchDecision::Allowed {
|
||||||
|
handler: MethodHandler::Cancelled,
|
||||||
|
kind: Kind::Notification,
|
||||||
|
} if is_notification(message) => {
|
||||||
|
handle_cancelled_notification(&state, path, headers, message, credential).await
|
||||||
|
}
|
||||||
|
DispatchDecision::Allowed {
|
||||||
|
handler: MethodHandler::ResourceList,
|
||||||
|
..
|
||||||
|
} if is_request(message) => {
|
||||||
|
let session = match require_initialized_session(&state, path, headers, message).await {
|
||||||
|
Ok(session) => session,
|
||||||
|
Err(response) => return response,
|
||||||
|
};
|
||||||
|
let list_command: ResourcesListCommand = match serde_json::from_value(params(message)) {
|
||||||
|
Ok(value) => value,
|
||||||
|
Err(_) => {
|
||||||
|
return transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
jsonrpc_error(
|
||||||
|
request_id(message),
|
||||||
|
-32602,
|
||||||
|
"invalid resources/list parameters",
|
||||||
|
),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
Some(&session.protocol_version),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let outcome = handle_resources_command(
|
||||||
|
&state,
|
||||||
|
ServiceContext {
|
||||||
|
workspace_slug: &session.workspace_slug,
|
||||||
|
agent_slug: &session.agent_slug,
|
||||||
|
credential,
|
||||||
|
correlation: transport_correlation,
|
||||||
|
continuation: ContinuationSupport::from_supported(session.supports_elicitation),
|
||||||
|
locale: execution_locale(message),
|
||||||
|
},
|
||||||
|
&session.protocol_version,
|
||||||
|
ResourcesCommand::List(list_command),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
match outcome {
|
||||||
|
ResourcesOutcome::Listed {
|
||||||
|
resources,
|
||||||
|
next_cursor,
|
||||||
|
} => transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
jsonrpc_result(
|
||||||
|
request_id(message),
|
||||||
|
resources_list_result(resources, next_cursor),
|
||||||
|
),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
Some(&session.protocol_version),
|
||||||
|
),
|
||||||
|
ResourcesOutcome::InvalidParams(detail) => transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
jsonrpc_error(request_id(message), -32602, detail),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
Some(&session.protocol_version),
|
||||||
|
),
|
||||||
|
_ => internal_jsonrpc_error(message, "published resources are unavailable"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
DispatchDecision::Allowed {
|
||||||
|
handler: MethodHandler::ResourceRead,
|
||||||
|
..
|
||||||
|
} if is_request(message) => {
|
||||||
|
let session = match require_initialized_session(&state, path, headers, message).await {
|
||||||
|
Ok(session) => session,
|
||||||
|
Err(response) => return response,
|
||||||
|
};
|
||||||
|
let read_command: ResourceReadCommand = match serde_json::from_value(params(message)) {
|
||||||
|
Ok(value) => value,
|
||||||
|
Err(_) => {
|
||||||
|
return transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
jsonrpc_error(
|
||||||
|
request_id(message),
|
||||||
|
-32602,
|
||||||
|
"invalid resources/read parameters",
|
||||||
|
),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
Some(&session.protocol_version),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let outcome = handle_resources_command(
|
||||||
|
&state,
|
||||||
|
ServiceContext {
|
||||||
|
workspace_slug: &session.workspace_slug,
|
||||||
|
agent_slug: &session.agent_slug,
|
||||||
|
credential,
|
||||||
|
correlation: transport_correlation,
|
||||||
|
continuation: ContinuationSupport::from_supported(session.supports_elicitation),
|
||||||
|
locale: execution_locale(message),
|
||||||
|
},
|
||||||
|
&session.protocol_version,
|
||||||
|
ResourcesCommand::Read(read_command),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
match outcome {
|
||||||
|
ResourcesOutcome::Read { contents } => transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
jsonrpc_result(request_id(message), resource_read_result(contents)),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
Some(&session.protocol_version),
|
||||||
|
),
|
||||||
|
ResourcesOutcome::NotAvailable => transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
jsonrpc_error(
|
||||||
|
request_id(message),
|
||||||
|
-32602,
|
||||||
|
"the requested resource is not available",
|
||||||
|
),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
Some(&session.protocol_version),
|
||||||
|
),
|
||||||
|
ResourcesOutcome::InvalidParams(detail) => transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
jsonrpc_error(request_id(message), -32602, detail),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
Some(&session.protocol_version),
|
||||||
|
),
|
||||||
|
ResourcesOutcome::ExecutionError(contract) => resource_error_response(
|
||||||
|
message,
|
||||||
|
response_mode,
|
||||||
|
&session.protocol_version,
|
||||||
|
contract,
|
||||||
|
),
|
||||||
|
_ => internal_jsonrpc_error(message, "published resources are unavailable"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Story 3.11: the shared service returns exact bound Published templates; the legacy adapter
|
||||||
|
// retains its earlier result shape and still requires the initialized session.
|
||||||
|
DispatchDecision::Allowed {
|
||||||
|
handler: MethodHandler::ResourceTemplateList,
|
||||||
|
..
|
||||||
|
} if is_request(message) => {
|
||||||
|
let session = match require_initialized_session(&state, path, headers, message).await {
|
||||||
|
Ok(session) => session,
|
||||||
|
Err(response) => return response,
|
||||||
|
};
|
||||||
|
|
||||||
|
let command: ResourcesListCommand = match serde_json::from_value(params(message)) {
|
||||||
|
Ok(command) => command,
|
||||||
|
Err(_) => {
|
||||||
|
return transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
jsonrpc_error(
|
||||||
|
request_id(message),
|
||||||
|
-32602,
|
||||||
|
"invalid resources/templates/list parameters",
|
||||||
|
),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
Some(&session.protocol_version),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let (templates, next_cursor) = match crate::protocol::list_resource_templates(
|
||||||
|
&state,
|
||||||
|
&path.workspace_slug,
|
||||||
|
&path.agent_slug,
|
||||||
|
&session.protocol_version,
|
||||||
|
command,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(page) => page,
|
||||||
|
Err(crate::protocol::ResourceTemplatesListError::InvalidCursor) => {
|
||||||
|
return transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
jsonrpc_error(
|
||||||
|
request_id(message),
|
||||||
|
-32602,
|
||||||
|
"invalid resources/templates/list cursor",
|
||||||
|
),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
Some(&session.protocol_version),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Err(crate::protocol::ResourceTemplatesListError::Unavailable) => {
|
||||||
|
return internal_jsonrpc_error(message, "published templates are unavailable");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
jsonrpc_result(
|
||||||
|
request_id(message),
|
||||||
|
resource_templates_list_result(templates, next_cursor),
|
||||||
|
),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
Some(&session.protocol_version),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
// Story 3.14: `prompts/list` / `prompts/get` of the initialized legacy session, served from
|
||||||
|
// the same exact bound Published Prompt Versions as the modern era.
|
||||||
|
DispatchDecision::Allowed {
|
||||||
|
handler: MethodHandler::PromptList,
|
||||||
|
..
|
||||||
|
} if is_request(message) => {
|
||||||
|
let session = match require_initialized_session(&state, path, headers, message).await {
|
||||||
|
Ok(session) => session,
|
||||||
|
Err(response) => return response,
|
||||||
|
};
|
||||||
|
let command: PromptsListCommand = match serde_json::from_value(params(message)) {
|
||||||
|
Ok(command) => command,
|
||||||
|
Err(_) => {
|
||||||
|
return transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
jsonrpc_error(
|
||||||
|
request_id(message),
|
||||||
|
-32602,
|
||||||
|
"invalid prompts/list parameters",
|
||||||
|
),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
Some(&session.protocol_version),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let outcome = handle_prompts_command(
|
||||||
|
&state,
|
||||||
|
ServiceContext {
|
||||||
|
workspace_slug: &session.workspace_slug,
|
||||||
|
agent_slug: &session.agent_slug,
|
||||||
|
credential,
|
||||||
|
correlation: transport_correlation,
|
||||||
|
continuation: ContinuationSupport::from_supported(session.supports_elicitation),
|
||||||
|
locale: execution_locale(message),
|
||||||
|
},
|
||||||
|
&session.protocol_version,
|
||||||
|
PromptsCommand::List(command),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
match outcome {
|
||||||
|
PromptsOutcome::Listed {
|
||||||
|
prompts,
|
||||||
|
next_cursor,
|
||||||
|
} => transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
jsonrpc_result(
|
||||||
|
request_id(message),
|
||||||
|
prompts_list_result(prompts, next_cursor),
|
||||||
|
),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
Some(&session.protocol_version),
|
||||||
|
),
|
||||||
|
PromptsOutcome::InvalidParams(detail) => transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
jsonrpc_error(request_id(message), -32602, detail),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
Some(&session.protocol_version),
|
||||||
|
),
|
||||||
|
_ => internal_jsonrpc_error(message, "published prompts are unavailable"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
DispatchDecision::Allowed {
|
||||||
|
handler: MethodHandler::PromptGet,
|
||||||
|
..
|
||||||
|
} if is_request(message) => {
|
||||||
|
let session = match require_initialized_session(&state, path, headers, message).await {
|
||||||
|
Ok(session) => session,
|
||||||
|
Err(response) => return response,
|
||||||
|
};
|
||||||
|
let command: PromptGetCommand = match serde_json::from_value(params(message)) {
|
||||||
|
Ok(command) => command,
|
||||||
|
Err(_) => {
|
||||||
|
return transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
jsonrpc_error(
|
||||||
|
request_id(message),
|
||||||
|
-32602,
|
||||||
|
"invalid prompts/get parameters",
|
||||||
|
),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
Some(&session.protocol_version),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let outcome = handle_prompts_command(
|
||||||
|
&state,
|
||||||
|
ServiceContext {
|
||||||
|
workspace_slug: &session.workspace_slug,
|
||||||
|
agent_slug: &session.agent_slug,
|
||||||
|
credential,
|
||||||
|
correlation: transport_correlation,
|
||||||
|
continuation: ContinuationSupport::from_supported(session.supports_elicitation),
|
||||||
|
locale: execution_locale(message),
|
||||||
|
},
|
||||||
|
&session.protocol_version,
|
||||||
|
PromptsCommand::Get(command),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
match outcome {
|
||||||
|
PromptsOutcome::Got {
|
||||||
|
description,
|
||||||
|
messages,
|
||||||
|
} => transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
jsonrpc_result(
|
||||||
|
request_id(message),
|
||||||
|
prompt_get_result(description, messages),
|
||||||
|
),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
Some(&session.protocol_version),
|
||||||
|
),
|
||||||
|
PromptsOutcome::NotAvailable => transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
jsonrpc_error(
|
||||||
|
request_id(message),
|
||||||
|
-32602,
|
||||||
|
"the requested prompt is not available",
|
||||||
|
),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
Some(&session.protocol_version),
|
||||||
|
),
|
||||||
|
PromptsOutcome::ArgumentsRejected { reason, argument } => {
|
||||||
|
prompt_arguments_error_response(
|
||||||
|
message,
|
||||||
|
response_mode,
|
||||||
|
&session.protocol_version,
|
||||||
|
reason,
|
||||||
|
argument,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
PromptsOutcome::DependencyUnavailable { position } => transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
jsonrpc_error(
|
||||||
|
request_id(message),
|
||||||
|
-32603,
|
||||||
|
format!("the pinned dependency at dependencies[{position}] is unavailable"),
|
||||||
|
),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
Some(&session.protocol_version),
|
||||||
|
),
|
||||||
|
PromptsOutcome::InvalidParams(detail) => transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
jsonrpc_error(request_id(message), -32602, detail),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
Some(&session.protocol_version),
|
||||||
|
),
|
||||||
|
_ => internal_jsonrpc_error(message, "published prompts are unavailable"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Story 3.17: `completion/complete` of the initialized legacy session. The shared service is
|
||||||
|
// the same one the modern era uses; only the result envelope differs (no `resultType`).
|
||||||
|
DispatchDecision::Allowed {
|
||||||
|
handler: MethodHandler::Completion,
|
||||||
|
..
|
||||||
|
} if is_request(message) => {
|
||||||
|
let session = match require_initialized_session(&state, path, headers, message).await {
|
||||||
|
Ok(session) => session,
|
||||||
|
Err(response) => return response,
|
||||||
|
};
|
||||||
|
let command: CompletionCommand = match serde_json::from_value(params(message)) {
|
||||||
|
Ok(command) => command,
|
||||||
|
Err(_) => {
|
||||||
|
return transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
jsonrpc_error(
|
||||||
|
request_id(message),
|
||||||
|
-32602,
|
||||||
|
"invalid completion/complete parameters",
|
||||||
|
),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
Some(&session.protocol_version),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let outcome = handle_completion_command(
|
||||||
|
&state,
|
||||||
|
ServiceContext {
|
||||||
|
workspace_slug: &session.workspace_slug,
|
||||||
|
agent_slug: &session.agent_slug,
|
||||||
|
credential,
|
||||||
|
correlation: transport_correlation,
|
||||||
|
continuation: ContinuationSupport::from_supported(session.supports_elicitation),
|
||||||
|
locale: execution_locale(message),
|
||||||
|
},
|
||||||
|
&session.protocol_version,
|
||||||
|
command,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
match outcome {
|
||||||
|
CompletionOutcome::Completed {
|
||||||
|
values,
|
||||||
|
total,
|
||||||
|
has_more,
|
||||||
|
} => transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
jsonrpc_result(
|
||||||
|
request_id(message),
|
||||||
|
completion_result(values, total, has_more),
|
||||||
|
),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
Some(&session.protocol_version),
|
||||||
|
),
|
||||||
|
CompletionOutcome::InvalidParams(detail) => transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
jsonrpc_error(request_id(message), -32602, detail),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
Some(&session.protocol_version),
|
||||||
|
),
|
||||||
|
CompletionOutcome::NotAvailable => transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
jsonrpc_error(
|
||||||
|
request_id(message),
|
||||||
|
-32602,
|
||||||
|
"the completion reference is not available",
|
||||||
|
),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
Some(&session.protocol_version),
|
||||||
|
),
|
||||||
|
CompletionOutcome::CatalogUnavailable => {
|
||||||
|
internal_jsonrpc_error(message, "published completion sources are unavailable")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Story 3.18: the pinned legacy `logging/setLevel`. The level belongs to the initialized
|
||||||
|
// session of this request, so setting it can never change another client's level. The request
|
||||||
|
// answers an empty result; the acknowledgment event is filtered by the level it just set.
|
||||||
|
DispatchDecision::Allowed {
|
||||||
|
handler: MethodHandler::LoggingSetLevel,
|
||||||
|
..
|
||||||
|
} if is_request(message) => {
|
||||||
|
let session = match require_initialized_session(&state, path, headers, message).await {
|
||||||
|
Ok(session) => session,
|
||||||
|
Err(response) => return response,
|
||||||
|
};
|
||||||
|
let command: SetLevelCommand = match serde_json::from_value(params(message)) {
|
||||||
|
Ok(command) => command,
|
||||||
|
// A non-string, missing or otherwise unparsable level shares the one safe detail of a
|
||||||
|
// value outside the pinned union: nothing the client sent is echoed back.
|
||||||
|
Err(_) => {
|
||||||
|
return transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
jsonrpc_error(request_id(message), -32602, INVALID_LEVEL),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
Some(&session.protocol_version),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
match handle_logging_command(&state.logging_levels, &session.id, command) {
|
||||||
|
LoggingOutcome::Applied(level) => {
|
||||||
|
crate::protocol::set_active_level(Some(level));
|
||||||
|
crate::protocol::note(
|
||||||
|
crate::protocol::LogLevel::Notice,
|
||||||
|
EVENT_LEVEL_APPLIED,
|
||||||
|
"applied",
|
||||||
|
);
|
||||||
|
transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
jsonrpc_result(request_id(message), json!({})),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
Some(&session.protocol_version),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
LoggingOutcome::InvalidParams(detail) => transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
jsonrpc_error(request_id(message), -32602, detail),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
Some(&session.protocol_version),
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// A notification whose method the registration does not map to this adapter's handlers is
|
||||||
|
// acknowledged without being dispatched, exactly as before.
|
||||||
|
_ if is_notification(message) => StatusCode::ACCEPTED.into_response(),
|
||||||
|
// Every remaining decision (unregistered, wrong era, or a handler this adapter does not
|
||||||
|
// serve) is a method-level rejection: no handler, no service entry, no outbound call.
|
||||||
|
_ => match method_name(message) {
|
||||||
|
Some(method) => transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
jsonrpc_error(
|
||||||
|
request_id(message),
|
||||||
|
-32601,
|
||||||
|
format!("method {method} is not supported"),
|
||||||
|
),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
protocol_version,
|
||||||
|
),
|
||||||
|
None => transport_response(
|
||||||
|
StatusCode::BAD_REQUEST,
|
||||||
|
jsonrpc_error(Value::Null, -32600, "invalid JSON-RPC message"),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
protocol_version,
|
||||||
|
),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The credential half of the cancellation ownership of one call (Story 3.4). The progress token is
|
||||||
|
/// deliberately not part of it: a token never authorizes a cancellation.
|
||||||
|
fn in_flight_owner(credential: &VerifiedMachineCredential) -> String {
|
||||||
|
credential
|
||||||
|
.platform_api_key_id
|
||||||
|
.as_ref()
|
||||||
|
.map_or_else(String::new, |id| id.as_str().to_owned())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Route one legacy `notifications/cancelled` to the call it names, then acknowledge it.
|
||||||
|
///
|
||||||
|
/// The pinned rules of a cancelled request are all "ignore": an unknown or already finished request,
|
||||||
|
/// a foreign session or credential, a malformed `requestId` and an unknown session are acknowledged
|
||||||
|
/// without any effect. That is also why this handler never fails the transport — a client that
|
||||||
|
/// cancels must not learn anything about another client's calls.
|
||||||
|
async fn handle_cancelled_notification(
|
||||||
|
state: &Arc<AppState>,
|
||||||
|
path: &AgentRoutePath,
|
||||||
|
headers: &HeaderMap,
|
||||||
|
message: &Value,
|
||||||
|
credential: &VerifiedMachineCredential,
|
||||||
|
) -> Response {
|
||||||
|
let request_id = params(message).get("requestId").cloned();
|
||||||
|
let session_id = session_id_from_headers(headers).ok().flatten();
|
||||||
|
if let (Some(request_id), Some(session_id)) = (request_id, session_id) {
|
||||||
|
// Only a string or a number is a pinned `RequestId`; anything else cannot name a call.
|
||||||
|
if matches!(request_id, Value::String(_) | Value::Number(_)) {
|
||||||
|
let owned_by_session = match state.sessions.get(&session_id).await {
|
||||||
|
Ok(Some(session)) => {
|
||||||
|
session.workspace_slug == path.workspace_slug
|
||||||
|
&& session.agent_slug == path.agent_slug
|
||||||
|
}
|
||||||
|
_ => false,
|
||||||
|
};
|
||||||
|
if owned_by_session {
|
||||||
|
state.in_flight.cancel(
|
||||||
|
&crate::app::lifecycle::InFlightScope {
|
||||||
|
session_id,
|
||||||
|
owner: in_flight_owner(credential),
|
||||||
|
},
|
||||||
|
&request_id,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
StatusCode::ACCEPTED.into_response()
|
||||||
|
}
|
||||||
@@ -0,0 +1,566 @@
|
|||||||
|
//! Story 3.4 (FR-14): request-scoped progress and cancellation of one synchronous `tools/call`.
|
||||||
|
//!
|
||||||
|
//! The pinned `RequestMetaObject` of *both* supported revisions carries an optional opaque
|
||||||
|
//! `progressToken`; a request that has one asks for out-of-band `notifications/progress` messages
|
||||||
|
//! about that request. Such a message only has a carrier on the request's own SSE response stream, so
|
||||||
|
//! a token is honoured only when the client negotiated `text/event-stream`. Without a token — or
|
||||||
|
//! without the stream — the call runs exactly as before: the receiver of a progress token is never
|
||||||
|
//! obligated to send progress, so the execution result cannot change.
|
||||||
|
//!
|
||||||
|
//! Cancellation follows the revision-specific rule of the pinned specification:
|
||||||
|
//! * `2025-11-25`: the client POSTs `notifications/cancelled` with the id of the request it issued.
|
||||||
|
//! The bounded in-flight table routes it to that call. Ownership is the session *and* the platform
|
||||||
|
//! credential of the call, never the progress token: a foreign session or key cancels nothing.
|
||||||
|
//! * `2026-07-28`: closing the request's SSE response stream *is* the cancellation signal, so there is
|
||||||
|
//! no notification to route; dropping the response stream drops the call future.
|
||||||
|
//!
|
||||||
|
//! Either way a cancelled call never becomes a false `completed`: no further message is sent for it
|
||||||
|
//! (the pinned rule for a cancelled request), and the call never reaches its terminal outcome, so no
|
||||||
|
//! Invocation History row claims a completion. The record contract only admits a *closed* execution
|
||||||
|
//! error code for a non-`ok` row and a cancellation is not one of them, so the honest state of a
|
||||||
|
//! stopped call is "no terminal record" rather than an invented error code; a dedicated cancellation
|
||||||
|
//! code would be a schema/vocabulary decision of its own.
|
||||||
|
|
||||||
|
use std::{
|
||||||
|
collections::{HashMap, VecDeque},
|
||||||
|
future::Future,
|
||||||
|
pin::Pin,
|
||||||
|
sync::{Arc, Mutex},
|
||||||
|
};
|
||||||
|
|
||||||
|
use axum::{
|
||||||
|
http::StatusCode,
|
||||||
|
response::{IntoResponse, Response, sse::Event},
|
||||||
|
};
|
||||||
|
use crank_core::{CorrelationContext, ExecutionLocale, VerifiedMachineCredential};
|
||||||
|
use futures_util::stream;
|
||||||
|
use serde_json::{Number, Value, json};
|
||||||
|
use tokio::sync::{mpsc, watch};
|
||||||
|
|
||||||
|
use super::{
|
||||||
|
AppState,
|
||||||
|
response::{ToolCommandPayload, tool_command_payload, tool_command_response},
|
||||||
|
};
|
||||||
|
use crate::{
|
||||||
|
jsonrpc::request_id,
|
||||||
|
protocol::{
|
||||||
|
ContinuationSupport, ServiceContext, ToolCallCommand, ToolsCommand, ToolsOutcome,
|
||||||
|
handle_tools_command,
|
||||||
|
},
|
||||||
|
transport::{ResponseMode, sse_response},
|
||||||
|
};
|
||||||
|
|
||||||
|
/// The bounded progress queue of one call. A client that reads its stream slowly can never block the
|
||||||
|
/// call: a full queue drops the event instead of waiting, and the remaining events stay monotonic.
|
||||||
|
pub(crate) const PROGRESS_CAPACITY: usize = 8;
|
||||||
|
/// The pinned `ProgressToken` bound this server accepts. A longer token is not rejected as an error:
|
||||||
|
/// progress is simply disabled for that request, exactly as for a malformed one.
|
||||||
|
pub(crate) const MAX_PROGRESS_TOKEN_LEN: usize = 128;
|
||||||
|
/// The bounded table of calls that can still be cancelled. A call that finds the table full runs
|
||||||
|
/// without cancellation instead of growing the table.
|
||||||
|
pub(crate) const MAX_IN_FLIGHT_CALLS: usize = 256;
|
||||||
|
|
||||||
|
/// A validated `RequestMetaObject.progressToken`: the pinned opaque token is a string or a number.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub(crate) enum ProgressToken {
|
||||||
|
Text(String),
|
||||||
|
Number(Number),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ProgressToken {
|
||||||
|
/// `None` means "disable progress", never "fail the call": the pinned schema declares the token
|
||||||
|
/// as an opaque client value the receiver may simply ignore.
|
||||||
|
fn parse(value: &Value) -> Option<Self> {
|
||||||
|
match value {
|
||||||
|
Value::String(text)
|
||||||
|
if !text.is_empty()
|
||||||
|
&& text.len() <= MAX_PROGRESS_TOKEN_LEN
|
||||||
|
&& !text.chars().any(char::is_control) =>
|
||||||
|
{
|
||||||
|
Some(Self::Text(text.clone()))
|
||||||
|
}
|
||||||
|
Value::Number(number) => Some(Self::Number(number.clone())),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn as_value(&self) -> Value {
|
||||||
|
match self {
|
||||||
|
Self::Text(text) => Value::String(text.clone()),
|
||||||
|
Self::Number(number) => Value::Number(number.clone()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The progress token of one request parameters object, already validated and bounded. The adapters
|
||||||
|
/// read the `_meta` object they already parsed ([`token_from_meta`]); this is the test seam of the
|
||||||
|
/// same rule.
|
||||||
|
#[cfg(test)]
|
||||||
|
pub(crate) fn progress_token(params: &Value) -> Option<ProgressToken> {
|
||||||
|
token_from_meta(params.get("_meta"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The validated token of one `RequestMetaObject`. A non-object `_meta` has no token.
|
||||||
|
pub(crate) fn token_from_meta(meta: Option<&Value>) -> Option<ProgressToken> {
|
||||||
|
meta.and_then(|meta| meta.get("progressToken"))
|
||||||
|
.and_then(ProgressToken::parse)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One real, already reached execution step: the shared Tools service emits these at the stage
|
||||||
|
/// boundaries it actually crosses, so no percentage is invented and no timer drives them.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub(crate) enum Phase {
|
||||||
|
Resolved,
|
||||||
|
Authorized,
|
||||||
|
Dispatching,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Phase {
|
||||||
|
const fn message(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Self::Resolved => "tool_resolved",
|
||||||
|
Self::Authorized => "authorization_resolved",
|
||||||
|
Self::Dispatching => "execution_dispatched",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub(crate) struct ProgressEvent {
|
||||||
|
progress: u64,
|
||||||
|
message: &'static str,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The pinned `notifications/progress` frame. Both supported revisions declare the same parameters,
|
||||||
|
/// so the projection is shared; the token is echoed verbatim and never validated as a credential.
|
||||||
|
fn progress_frame(token: &ProgressToken, event: &ProgressEvent) -> Value {
|
||||||
|
json!({
|
||||||
|
"jsonrpc": "2.0",
|
||||||
|
"method": "notifications/progress",
|
||||||
|
"params": {
|
||||||
|
"progressToken": token.as_value(),
|
||||||
|
"progress": event.progress,
|
||||||
|
"message": event.message,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
struct ProgressSink {
|
||||||
|
events: mpsc::Sender<ProgressEvent>,
|
||||||
|
produced: Arc<std::sync::atomic::AtomicU64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ProgressSink {
|
||||||
|
fn emit(&self, message: &'static str) {
|
||||||
|
let progress = self
|
||||||
|
.produced
|
||||||
|
.fetch_add(1, std::sync::atomic::Ordering::SeqCst)
|
||||||
|
+ 1;
|
||||||
|
let _ = self.events.try_send(ProgressEvent { progress, message });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A cooperative cancellation signal of one call. It is set at most once; a signal whose only sender
|
||||||
|
/// is gone simply never fires.
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub(crate) struct CancelSignal {
|
||||||
|
receiver: watch::Receiver<bool>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CancelSignal {
|
||||||
|
fn never() -> Self {
|
||||||
|
let (_sender, receiver) = watch::channel(false);
|
||||||
|
Self { receiver }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) async fn cancelled(&mut self) {
|
||||||
|
if self
|
||||||
|
.receiver
|
||||||
|
.wait_for(|cancelled| *cancelled)
|
||||||
|
.await
|
||||||
|
.is_err()
|
||||||
|
{
|
||||||
|
// The owning call is gone, so nothing can cancel it any more.
|
||||||
|
std::future::pending::<()>().await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The request-scoped lifecycle of one `tools/call`: its progress sink (when the client asked for
|
||||||
|
/// progress *and* offered the stream carrier) and its cancellation signal.
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub(crate) struct ToolCallLifecycle {
|
||||||
|
progress: Option<ProgressSink>,
|
||||||
|
cancel: CancelSignal,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ToolCallLifecycle {
|
||||||
|
pub(crate) fn new(
|
||||||
|
token: Option<ProgressToken>,
|
||||||
|
) -> (Self, Option<mpsc::Receiver<ProgressEvent>>) {
|
||||||
|
match token {
|
||||||
|
Some(_) => {
|
||||||
|
let (sender, receiver) = mpsc::channel(PROGRESS_CAPACITY);
|
||||||
|
(
|
||||||
|
Self {
|
||||||
|
progress: Some(ProgressSink {
|
||||||
|
events: sender,
|
||||||
|
produced: Arc::new(std::sync::atomic::AtomicU64::new(0)),
|
||||||
|
}),
|
||||||
|
cancel: CancelSignal::never(),
|
||||||
|
},
|
||||||
|
Some(receiver),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
None => (
|
||||||
|
Self {
|
||||||
|
progress: None,
|
||||||
|
cancel: CancelSignal::never(),
|
||||||
|
},
|
||||||
|
None,
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn with_cancel(mut self, cancel: CancelSignal) -> Self {
|
||||||
|
self.cancel = cancel;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Record one real execution step. Without a progress sink this is a no-op, so the shared service
|
||||||
|
/// does not branch on the presence of a token.
|
||||||
|
pub(crate) fn advance(&self, phase: Phase) {
|
||||||
|
if let Some(progress) = &self.progress {
|
||||||
|
progress.emit(phase.message());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn cancelled(&mut self) -> impl Future<Output = ()> + '_ {
|
||||||
|
self.cancel.cancelled()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The owned identity of one call, so the call future can be driven by the response stream itself.
|
||||||
|
pub(crate) struct ToolCallRequest {
|
||||||
|
pub(crate) workspace_slug: String,
|
||||||
|
pub(crate) agent_slug: String,
|
||||||
|
pub(crate) credential: VerifiedMachineCredential,
|
||||||
|
pub(crate) correlation: CorrelationContext,
|
||||||
|
pub(crate) continuation: ContinuationSupport,
|
||||||
|
pub(crate) locale: ExecutionLocale,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The wire facts the adapter owns: the envelope, the negotiated revision and response mode, the
|
||||||
|
/// validated token and — for the legacy revision — the session-scoped in-flight ownership.
|
||||||
|
pub(crate) struct ToolCallWire {
|
||||||
|
pub(crate) message: Value,
|
||||||
|
pub(crate) protocol_version: String,
|
||||||
|
pub(crate) response_mode: ResponseMode,
|
||||||
|
pub(crate) progress: Option<ProgressToken>,
|
||||||
|
pub(crate) session_id: Option<String>,
|
||||||
|
pub(crate) in_flight: Option<InFlightScope>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Who owns a cancellable call. The session and the platform credential are the ownership of the
|
||||||
|
/// legacy revision; the progress token is deliberately not part of it.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub(crate) struct InFlightScope {
|
||||||
|
pub(crate) session_id: String,
|
||||||
|
pub(crate) owner: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The bounded table of the calls a legacy client can still cancel.
|
||||||
|
pub(crate) struct InFlightCalls {
|
||||||
|
entries: Mutex<HashMap<String, watch::Sender<bool>>>,
|
||||||
|
capacity: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl InFlightCalls {
|
||||||
|
pub(crate) fn new(capacity: usize) -> Self {
|
||||||
|
Self {
|
||||||
|
entries: Mutex::new(HashMap::new()),
|
||||||
|
capacity,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn entries(&self) -> std::sync::MutexGuard<'_, HashMap<String, watch::Sender<bool>>> {
|
||||||
|
// A panic of another request must not make the cancellation table unusable.
|
||||||
|
self.entries
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(|poisoned| poisoned.into_inner())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn key(scope: &InFlightScope, request_id: &Value) -> String {
|
||||||
|
// The pinned `RequestId` is a string or a number; the two must not collapse into one key.
|
||||||
|
format!(
|
||||||
|
"{}\u{1f}{}\u{1f}{request_id}",
|
||||||
|
scope.session_id, scope.owner
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Register one call as cancellable. `None` means the table is full (or the id is already live),
|
||||||
|
/// and the call then runs without cancellation instead of evicting someone else's entry.
|
||||||
|
pub(crate) fn register(
|
||||||
|
self: &Arc<Self>,
|
||||||
|
scope: &InFlightScope,
|
||||||
|
request_id: &Value,
|
||||||
|
) -> Option<InFlightEntry> {
|
||||||
|
let key = Self::key(scope, request_id);
|
||||||
|
let (sender, receiver) = watch::channel(false);
|
||||||
|
{
|
||||||
|
let mut entries = self.entries();
|
||||||
|
if entries.len() >= self.capacity || entries.contains_key(&key) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
entries.insert(key.clone(), sender);
|
||||||
|
}
|
||||||
|
Some(InFlightEntry {
|
||||||
|
registry: Arc::clone(self),
|
||||||
|
key,
|
||||||
|
cancel: CancelSignal { receiver },
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Route one `notifications/cancelled` to the call it names. `false` means there is no such
|
||||||
|
/// in-flight call of this owner, which the specification requires to be ignored.
|
||||||
|
pub(crate) fn cancel(&self, scope: &InFlightScope, request_id: &Value) -> bool {
|
||||||
|
let entries = self.entries();
|
||||||
|
entries
|
||||||
|
.get(&Self::key(scope, request_id))
|
||||||
|
.is_some_and(|sender| sender.send(true).is_ok())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The live registration of one call: dropping it (terminal response, cancellation or a dropped
|
||||||
|
/// response stream) releases the table slot.
|
||||||
|
pub(crate) struct InFlightEntry {
|
||||||
|
registry: Arc<InFlightCalls>,
|
||||||
|
key: String,
|
||||||
|
cancel: CancelSignal,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl InFlightEntry {
|
||||||
|
pub(crate) fn cancel_signal(&self) -> CancelSignal {
|
||||||
|
self.cancel.clone()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for InFlightEntry {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
self.registry.entries().remove(&self.key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Run one `tools/call` through the shared Tools service with the lifecycle of this request.
|
||||||
|
///
|
||||||
|
/// Without a progress token — or without the SSE carrier the client negotiated — the response is the
|
||||||
|
/// unchanged single JSON (or single-event SSE) response. With both, the response is the request's own
|
||||||
|
/// bounded stream: the real progress events of this call, then the terminal response as the last
|
||||||
|
/// event. Dropping that stream (a `2026-07-28` cancellation) or setting the signal of a legacy
|
||||||
|
/// `notifications/cancelled` drops the call future, which is the cooperative stop.
|
||||||
|
pub(crate) async fn run_tool_call(
|
||||||
|
state: Arc<AppState>,
|
||||||
|
request: ToolCallRequest,
|
||||||
|
wire: ToolCallWire,
|
||||||
|
command: ToolCallCommand,
|
||||||
|
) -> Response {
|
||||||
|
// A token is only honoured when the client offered the only carrier a notification has: the
|
||||||
|
// request's own SSE stream. Otherwise the call runs unchanged (a receiver is never obligated).
|
||||||
|
let token = match (&wire.response_mode, &wire.progress) {
|
||||||
|
(ResponseMode::Sse, Some(token)) => Some(token.clone()),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
let (mut lifecycle, progress_events) = ToolCallLifecycle::new(token.clone());
|
||||||
|
let in_flight = wire.in_flight.as_ref().and_then(|scope| {
|
||||||
|
let entry = state.in_flight.register(scope, &request_id(&wire.message));
|
||||||
|
if let Some(entry) = &entry {
|
||||||
|
lifecycle = lifecycle.clone().with_cancel(entry.cancel_signal());
|
||||||
|
}
|
||||||
|
entry
|
||||||
|
});
|
||||||
|
|
||||||
|
let message = wire.message.clone();
|
||||||
|
let correlation = request.correlation.clone();
|
||||||
|
let protocol_version = wire.protocol_version.clone();
|
||||||
|
let response_mode = wire.response_mode;
|
||||||
|
|
||||||
|
let mut call = Box::pin(call_future(
|
||||||
|
Arc::clone(&state),
|
||||||
|
request,
|
||||||
|
lifecycle.clone(),
|
||||||
|
command,
|
||||||
|
));
|
||||||
|
|
||||||
|
let Some(progress_events) = progress_events else {
|
||||||
|
// No notification carrier for this call: run it as before, still cancellable.
|
||||||
|
let outcome = tokio::select! {
|
||||||
|
biased;
|
||||||
|
outcome = &mut call => outcome,
|
||||||
|
_ = lifecycle.cancelled() => return cancelled_response(),
|
||||||
|
};
|
||||||
|
return tool_command_response(
|
||||||
|
&message,
|
||||||
|
response_mode,
|
||||||
|
&protocol_version,
|
||||||
|
&correlation,
|
||||||
|
outcome,
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
debug_assert!(matches!(response_mode, ResponseMode::Sse));
|
||||||
|
let token = token.expect("a progress receiver implies a validated token");
|
||||||
|
let stream = stream::unfold(
|
||||||
|
CallStream {
|
||||||
|
call,
|
||||||
|
events: progress_events,
|
||||||
|
cancel: lifecycle.cancel.clone(),
|
||||||
|
token,
|
||||||
|
message,
|
||||||
|
protocol_version: protocol_version.clone(),
|
||||||
|
correlation,
|
||||||
|
pending: VecDeque::new(),
|
||||||
|
finished: false,
|
||||||
|
logging: crate::protocol::carry_scope(),
|
||||||
|
_in_flight: in_flight,
|
||||||
|
},
|
||||||
|
next_event,
|
||||||
|
);
|
||||||
|
sse_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
stream,
|
||||||
|
wire.session_id.as_deref(),
|
||||||
|
Some(&protocol_version),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn call_future(
|
||||||
|
state: Arc<AppState>,
|
||||||
|
request: ToolCallRequest,
|
||||||
|
lifecycle: ToolCallLifecycle,
|
||||||
|
command: ToolCallCommand,
|
||||||
|
) -> ToolsOutcome {
|
||||||
|
handle_tools_command(
|
||||||
|
&state,
|
||||||
|
ServiceContext {
|
||||||
|
workspace_slug: &request.workspace_slug,
|
||||||
|
agent_slug: &request.agent_slug,
|
||||||
|
credential: &request.credential,
|
||||||
|
correlation: &request.correlation,
|
||||||
|
continuation: request.continuation,
|
||||||
|
locale: request.locale,
|
||||||
|
},
|
||||||
|
ToolsCommand::Call(command),
|
||||||
|
Some(lifecycle),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A cancelled call is not answered: the pinned rule for a cancelled request is that no further
|
||||||
|
/// message is sent for it, and the client that cancelled it ignores a late response anyway. Nothing
|
||||||
|
/// here claims that an outbound side effect did or did not happen — and nothing else claims the
|
||||||
|
/// opposite either: the call is stopped before its terminal outcome, so its Invocation History holds
|
||||||
|
/// no row for this call at all (see the module docs for why there is no invented cancellation code).
|
||||||
|
fn cancelled_response() -> Response {
|
||||||
|
StatusCode::OK.into_response()
|
||||||
|
}
|
||||||
|
|
||||||
|
struct CallStream {
|
||||||
|
call: Pin<Box<dyn Future<Output = ToolsOutcome> + Send>>,
|
||||||
|
events: mpsc::Receiver<ProgressEvent>,
|
||||||
|
cancel: CancelSignal,
|
||||||
|
token: ProgressToken,
|
||||||
|
message: Value,
|
||||||
|
protocol_version: String,
|
||||||
|
correlation: CorrelationContext,
|
||||||
|
pending: VecDeque<Event>,
|
||||||
|
finished: bool,
|
||||||
|
/// The request's logging context, so the terminal event of the stream is projected exactly as the
|
||||||
|
/// single response of the same call would be (Story 3.18 carried across the stream, Story 3.4).
|
||||||
|
logging: crate::protocol::CarriedScope,
|
||||||
|
/// Held for the lifetime of the stream: the slot is released when the call is over, however it ends.
|
||||||
|
_in_flight: Option<InFlightEntry>,
|
||||||
|
}
|
||||||
|
|
||||||
|
enum Step {
|
||||||
|
Progress(ProgressEvent),
|
||||||
|
Outcome(ToolsOutcome),
|
||||||
|
Cancelled,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One stream item: a queued frame, the next real progress event, the terminal response, or the end of
|
||||||
|
/// a cancelled stream. A cancelled call sends no terminal frame at all.
|
||||||
|
async fn next_event(
|
||||||
|
call: CallStream,
|
||||||
|
) -> Option<(Result<Event, std::convert::Infallible>, CallStream)> {
|
||||||
|
let scope = call.logging;
|
||||||
|
crate::protocol::in_carried_scope(scope, next_event_in_scope(call)).await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn next_event_in_scope(
|
||||||
|
mut call: CallStream,
|
||||||
|
) -> Option<(Result<Event, std::convert::Infallible>, CallStream)> {
|
||||||
|
if let Some(frame) = call.pending.pop_front() {
|
||||||
|
return Some((Ok(frame), call));
|
||||||
|
}
|
||||||
|
if call.finished {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
let step = {
|
||||||
|
let CallStream {
|
||||||
|
call,
|
||||||
|
events,
|
||||||
|
cancel,
|
||||||
|
..
|
||||||
|
} = &mut call;
|
||||||
|
tokio::select! {
|
||||||
|
biased;
|
||||||
|
Some(event) = events.recv() => Step::Progress(event),
|
||||||
|
outcome = call => Step::Outcome(outcome),
|
||||||
|
_ = cancel.cancelled() => Step::Cancelled,
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
match step {
|
||||||
|
Step::Progress(event) => {
|
||||||
|
let frame = progress_frame(&call.token, &event);
|
||||||
|
Some((Ok(Event::default().data(frame.to_string())), call))
|
||||||
|
}
|
||||||
|
Step::Outcome(outcome) => {
|
||||||
|
call.finished = true;
|
||||||
|
let payload = match tool_command_payload(
|
||||||
|
&call.message,
|
||||||
|
&call.protocol_version,
|
||||||
|
&call.correlation,
|
||||||
|
outcome,
|
||||||
|
) {
|
||||||
|
ToolCommandPayload::Ok(payload) => payload,
|
||||||
|
ToolCommandPayload::Internal(_) => jsonrpc_internal_error(&call.message),
|
||||||
|
};
|
||||||
|
// The same projection point the single response uses, so a streamed answer delivers the
|
||||||
|
// same closed `notifications/message` (Story 3.18) before its terminal frame.
|
||||||
|
crate::transport::note_logging_outcome(&payload);
|
||||||
|
for notification in crate::protocol::take_notifications() {
|
||||||
|
call.pending
|
||||||
|
.push_back(Event::default().data(notification.to_string()));
|
||||||
|
}
|
||||||
|
call.pending
|
||||||
|
.push_back(Event::default().data(payload.to_string()));
|
||||||
|
Some((Ok(call.pending.pop_front().expect("queued frame")), call))
|
||||||
|
}
|
||||||
|
Step::Cancelled => {
|
||||||
|
call.finished = true;
|
||||||
|
call.pending.clear();
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn jsonrpc_internal_error(message: &Value) -> Value {
|
||||||
|
crate::jsonrpc::jsonrpc_error(request_id(message), -32603, "internal server error")
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
#[path = "lifecycle_tests.rs"]
|
||||||
|
mod tests;
|
||||||
@@ -0,0 +1,170 @@
|
|||||||
|
//! Story 3.4 bounds that do not need the HTTP surface: token validation, the monotonic bounded
|
||||||
|
//! progress queue, the pinned frame shape and the ownership of the in-flight cancellation table.
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn token(value: Value) -> Option<ProgressToken> {
|
||||||
|
progress_token(&json!({ "_meta": { "progressToken": value } }))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_pinned_progress_token_is_a_bounded_string_or_a_number() {
|
||||||
|
assert_eq!(
|
||||||
|
token(json!("tok-1")),
|
||||||
|
Some(ProgressToken::Text("tok-1".to_owned()))
|
||||||
|
);
|
||||||
|
assert!(matches!(token(json!(7)), Some(ProgressToken::Number(_))));
|
||||||
|
assert!(matches!(token(json!(1.5)), Some(ProgressToken::Number(_))));
|
||||||
|
|
||||||
|
// Malformed and out-of-bound tokens disable progress instead of failing the call.
|
||||||
|
assert_eq!(token(json!("")), None);
|
||||||
|
assert_eq!(token(json!("x".repeat(MAX_PROGRESS_TOKEN_LEN + 1))), None);
|
||||||
|
assert_eq!(token(json!("line\nbreak")), None);
|
||||||
|
assert_eq!(token(json!(null)), None);
|
||||||
|
assert_eq!(token(json!(true)), None);
|
||||||
|
assert_eq!(token(json!({ "nested": 1 })), None);
|
||||||
|
assert_eq!(token(json!([1, 2])), None);
|
||||||
|
// A token at the bound is still accepted.
|
||||||
|
assert!(token(json!("x".repeat(MAX_PROGRESS_TOKEN_LEN))).is_some());
|
||||||
|
// Absent `_meta`, absent token and a non-object `_meta` are all "no progress".
|
||||||
|
assert_eq!(progress_token(&json!({})), None);
|
||||||
|
assert_eq!(progress_token(&json!({ "_meta": { "other": 1 } })), None);
|
||||||
|
assert_eq!(progress_token(&json!({ "_meta": "not-an-object" })), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn real_steps_produce_strictly_increasing_bounded_progress_events() {
|
||||||
|
let (lifecycle, events) = ToolCallLifecycle::new(token(json!("tok-monotonic")));
|
||||||
|
let mut events = events.expect("a validated token opens the progress queue");
|
||||||
|
for phase in [Phase::Resolved, Phase::Authorized, Phase::Dispatching] {
|
||||||
|
lifecycle.advance(phase);
|
||||||
|
}
|
||||||
|
drop(lifecycle);
|
||||||
|
|
||||||
|
let mut observed = Vec::new();
|
||||||
|
while let Some(event) = events.recv().await {
|
||||||
|
observed.push((event.progress, event.message));
|
||||||
|
}
|
||||||
|
assert_eq!(
|
||||||
|
observed,
|
||||||
|
vec![
|
||||||
|
(1, "tool_resolved"),
|
||||||
|
(2, "authorization_resolved"),
|
||||||
|
(3, "execution_dispatched"),
|
||||||
|
]
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
observed.windows(2).all(|pair| pair[0].0 < pair[1].0),
|
||||||
|
"progress must increase monotonically, got {observed:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_full_progress_queue_drops_events_instead_of_blocking_the_call() {
|
||||||
|
let (lifecycle, events) = ToolCallLifecycle::new(token(json!(9)));
|
||||||
|
let mut events = events.expect("a validated token opens the progress queue");
|
||||||
|
// Many more steps than the queue holds: the call must never wait for the reader.
|
||||||
|
for _ in 0..(PROGRESS_CAPACITY * 4) {
|
||||||
|
lifecycle.advance(Phase::Resolved);
|
||||||
|
}
|
||||||
|
let mut delivered = 0;
|
||||||
|
while events.try_recv().is_ok() {
|
||||||
|
delivered += 1;
|
||||||
|
}
|
||||||
|
assert_eq!(delivered, PROGRESS_CAPACITY);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn without_a_token_no_progress_is_produced_at_all() {
|
||||||
|
let (lifecycle, events) = ToolCallLifecycle::new(None);
|
||||||
|
assert!(events.is_none());
|
||||||
|
lifecycle.advance(Phase::Resolved);
|
||||||
|
lifecycle.advance(Phase::Dispatching);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The pinned `notifications/progress` frame (schema `ProgressNotification`, both supported
|
||||||
|
/// revisions): `progressToken` echoed verbatim, `progress` increasing, `message` optional and
|
||||||
|
/// `total` absent because this server never invents one.
|
||||||
|
#[test]
|
||||||
|
fn the_progress_frame_matches_the_pinned_notification_shape() {
|
||||||
|
let event = ProgressEvent {
|
||||||
|
progress: 2,
|
||||||
|
message: Phase::Authorized.message(),
|
||||||
|
};
|
||||||
|
assert_eq!(
|
||||||
|
progress_frame(&ProgressToken::Text("tok-2".to_owned()), &event),
|
||||||
|
json!({
|
||||||
|
"jsonrpc": "2.0",
|
||||||
|
"method": "notifications/progress",
|
||||||
|
"params": {
|
||||||
|
"progressToken": "tok-2",
|
||||||
|
"progress": 2,
|
||||||
|
"message": "authorization_resolved"
|
||||||
|
}
|
||||||
|
})
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
progress_frame(&ProgressToken::Number(7.into()), &event)["params"]["progressToken"],
|
||||||
|
json!(7)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_cancellation_only_reaches_the_call_of_the_same_session_and_credential() {
|
||||||
|
let registry = Arc::new(InFlightCalls::new(MAX_IN_FLIGHT_CALLS));
|
||||||
|
let scope = InFlightScope {
|
||||||
|
session_id: "sess-1".to_owned(),
|
||||||
|
owner: "pk_a".to_owned(),
|
||||||
|
};
|
||||||
|
let entry = registry
|
||||||
|
.register(&scope, &json!(42))
|
||||||
|
.expect("the table has room");
|
||||||
|
let mut signal = entry.cancel_signal();
|
||||||
|
|
||||||
|
// A foreign credential, a foreign session and a different request id cancel nothing.
|
||||||
|
for foreign in [
|
||||||
|
InFlightScope {
|
||||||
|
session_id: "sess-1".to_owned(),
|
||||||
|
owner: "pk_b".to_owned(),
|
||||||
|
},
|
||||||
|
InFlightScope {
|
||||||
|
session_id: "sess-2".to_owned(),
|
||||||
|
owner: "pk_a".to_owned(),
|
||||||
|
},
|
||||||
|
] {
|
||||||
|
assert!(!registry.cancel(&foreign, &json!(42)));
|
||||||
|
}
|
||||||
|
assert!(!registry.cancel(&scope, &json!(43)));
|
||||||
|
assert!(
|
||||||
|
tokio::time::timeout(std::time::Duration::from_millis(50), signal.cancelled())
|
||||||
|
.await
|
||||||
|
.is_err(),
|
||||||
|
"a foreign cancellation must not fire the signal"
|
||||||
|
);
|
||||||
|
|
||||||
|
assert!(registry.cancel(&scope, &json!(42)));
|
||||||
|
tokio::time::timeout(std::time::Duration::from_millis(50), signal.cancelled())
|
||||||
|
.await
|
||||||
|
.expect("the owner's cancellation fires the signal");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_released_call_releases_its_slot_and_the_table_is_bounded() {
|
||||||
|
let registry = Arc::new(InFlightCalls::new(1));
|
||||||
|
let scope = InFlightScope {
|
||||||
|
session_id: "sess-1".to_owned(),
|
||||||
|
owner: "pk_a".to_owned(),
|
||||||
|
};
|
||||||
|
let entry = registry.register(&scope, &json!(1)).expect("first slot");
|
||||||
|
assert!(
|
||||||
|
registry.register(&scope, &json!(2)).is_none(),
|
||||||
|
"the table refuses a call beyond its bound instead of evicting the live one"
|
||||||
|
);
|
||||||
|
assert!(registry.cancel(&scope, &json!(1)));
|
||||||
|
drop(entry);
|
||||||
|
assert!(
|
||||||
|
!registry.cancel(&scope, &json!(1)),
|
||||||
|
"a terminal call is no longer cancellable"
|
||||||
|
);
|
||||||
|
assert!(registry.register(&scope, &json!(2)).is_some());
|
||||||
|
}
|
||||||
@@ -14,6 +14,11 @@ pub(super) struct ToolCallParams {
|
|||||||
pub(super) name: String,
|
pub(super) name: String,
|
||||||
#[serde(default, deserialize_with = "deserialize_arguments_object")]
|
#[serde(default, deserialize_with = "deserialize_arguments_object")]
|
||||||
pub(super) arguments: Option<Value>,
|
pub(super) arguments: Option<Value>,
|
||||||
|
/// Story 3.4: the pinned `RequestMetaObject` of this request. Only the validated
|
||||||
|
/// `progressToken` of it is read, and only to decide whether the client asked for out-of-band
|
||||||
|
/// progress; a malformed or foreign `_meta` never fails the call.
|
||||||
|
#[serde(default, rename = "_meta")]
|
||||||
|
pub(super) meta: Option<Value>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The pinned `CallToolRequest.params.arguments` is an **optional object**. Omitting it stays valid
|
/// The pinned `CallToolRequest.params.arguments` is an **optional object**. Omitting it stays valid
|
||||||
|
|||||||
@@ -23,71 +23,75 @@ pub(crate) fn take_confirmation_token(arguments: &mut Value) -> Option<String> {
|
|||||||
.filter(|value| !value.trim().is_empty())
|
.filter(|value| !value.trim().is_empty())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn success_tool_response(
|
/// The era-neutral success payload of one `tools/call` (Story 3.4: the streamed response needs the
|
||||||
|
/// payload itself, because the terminal response is the last event of the request's stream).
|
||||||
|
pub(super) fn success_tool_payload(
|
||||||
message: &Value,
|
message: &Value,
|
||||||
response_mode: ResponseMode,
|
|
||||||
protocol_version: &str,
|
protocol_version: &str,
|
||||||
output: Value,
|
output: Value,
|
||||||
) -> Response {
|
) -> Value {
|
||||||
transport_response(
|
jsonrpc_result(
|
||||||
StatusCode::OK,
|
request_id(message),
|
||||||
jsonrpc_result(
|
project_modern_result(
|
||||||
request_id(message),
|
protocol_version,
|
||||||
project_modern_result(
|
json!({
|
||||||
protocol_version,
|
"content": [
|
||||||
json!({
|
{
|
||||||
"content": [
|
"type": "text",
|
||||||
{
|
"text": serde_json::to_string_pretty(&output).unwrap_or_else(|_| "{}".to_owned())
|
||||||
"type": "text",
|
}
|
||||||
"text": serde_json::to_string_pretty(&output).unwrap_or_else(|_| "{}".to_owned())
|
],
|
||||||
}
|
"structuredContent": output,
|
||||||
],
|
"isError": false
|
||||||
"structuredContent": output,
|
}),
|
||||||
"isError": false
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
Some(protocol_version),
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
pub(crate) fn tool_error_response(
|
pub(crate) fn tool_error_response(
|
||||||
message: &Value,
|
message: &Value,
|
||||||
response_mode: ResponseMode,
|
response_mode: ResponseMode,
|
||||||
protocol_version: &str,
|
protocol_version: &str,
|
||||||
error: ToolErrorContract,
|
error: ToolErrorContract,
|
||||||
) -> Response {
|
) -> Response {
|
||||||
let error_message = tool_error_text(&error);
|
|
||||||
let error_value = tool_error_value(&error);
|
|
||||||
|
|
||||||
transport_response(
|
transport_response(
|
||||||
StatusCode::OK,
|
StatusCode::OK,
|
||||||
jsonrpc_result(
|
tool_error_payload(message, protocol_version, error),
|
||||||
request_id(message),
|
|
||||||
project_modern_result(
|
|
||||||
protocol_version,
|
|
||||||
json!({
|
|
||||||
"content": [
|
|
||||||
{
|
|
||||||
"type": "text",
|
|
||||||
"text": error_message
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"structuredContent": {
|
|
||||||
"error": error_value
|
|
||||||
},
|
|
||||||
"isError": true
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
response_mode,
|
response_mode,
|
||||||
None,
|
None,
|
||||||
Some(protocol_version),
|
Some(protocol_version),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub(super) fn tool_error_payload(
|
||||||
|
message: &Value,
|
||||||
|
protocol_version: &str,
|
||||||
|
error: ToolErrorContract,
|
||||||
|
) -> Value {
|
||||||
|
let error_message = tool_error_text(&error);
|
||||||
|
let error_value = tool_error_value(&error);
|
||||||
|
|
||||||
|
jsonrpc_result(
|
||||||
|
request_id(message),
|
||||||
|
project_modern_result(
|
||||||
|
protocol_version,
|
||||||
|
json!({
|
||||||
|
"content": [
|
||||||
|
{
|
||||||
|
"type": "text",
|
||||||
|
"text": error_message
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"structuredContent": {
|
||||||
|
"error": error_value
|
||||||
|
},
|
||||||
|
"isError": true
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
/// The era-neutral `tools/list` result shape built from the shared command outcome. Object keys end
|
/// The era-neutral `tools/list` result shape built from the shared command outcome. Object keys end
|
||||||
/// up byte-lexicographically ordered, exactly as before the extraction.
|
/// up byte-lexicographically ordered, exactly as before the extraction.
|
||||||
pub(super) fn tools_list_result(tools: Vec<Value>, next_cursor: Option<String>) -> Value {
|
pub(super) fn tools_list_result(tools: Vec<Value>, next_cursor: Option<String>) -> Value {
|
||||||
@@ -193,28 +197,35 @@ pub(super) fn prompt_arguments_error_response(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Map one shared Tools-command outcome back to the era-specific wire response (spec section 6.2).
|
/// One `tools/call` wire frame, or the adapter's own internal-error detail.
|
||||||
///
|
///
|
||||||
/// This adapter function is the only place that turns a neutral outcome into a response: the shared
|
/// Story 3.4: the same projection serves the single response and the terminal event of a streamed
|
||||||
|
/// response, so both forms of one outcome can never drift apart.
|
||||||
|
pub(super) enum ToolCommandPayload {
|
||||||
|
Ok(Value),
|
||||||
|
Internal(&'static str),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Map one shared Tools-command outcome back to its era-specific wire payload (spec section 6.2).
|
||||||
|
///
|
||||||
|
/// This adapter function is the only place that turns a neutral outcome into a wire value: the shared
|
||||||
/// service never sees `ResponseMode`, the protocol revision, the request envelope or an
|
/// service never sees `ResponseMode`, the protocol revision, the request envelope or an
|
||||||
/// `axum::Response`. `ApprovalPending` is a success for the client (it still has to answer), while
|
/// `axum::Response`. `ApprovalPending` is a success for the client (it still has to answer), while
|
||||||
/// an unavailable elicitation and a failing call keep their era-correct tool-error shape.
|
/// an unavailable elicitation and a failing call keep their era-correct tool-error shape.
|
||||||
pub(super) fn tool_command_response(
|
pub(super) fn tool_command_payload(
|
||||||
message: &Value,
|
message: &Value,
|
||||||
response_mode: ResponseMode,
|
|
||||||
protocol_version: &str,
|
protocol_version: &str,
|
||||||
correlation: &CorrelationContext,
|
correlation: &CorrelationContext,
|
||||||
outcome: ToolsOutcome,
|
outcome: ToolsOutcome,
|
||||||
) -> Response {
|
) -> ToolCommandPayload {
|
||||||
match outcome {
|
match outcome {
|
||||||
ToolsOutcome::Call(ToolCallOutcome::Completed(output))
|
ToolsOutcome::Call(ToolCallOutcome::Completed(output))
|
||||||
| ToolsOutcome::Call(ToolCallOutcome::ApprovalPending(output)) => {
|
| ToolsOutcome::Call(ToolCallOutcome::ApprovalPending(output)) => {
|
||||||
success_tool_response(message, response_mode, protocol_version, output)
|
ToolCommandPayload::Ok(success_tool_payload(message, protocol_version, output))
|
||||||
}
|
}
|
||||||
ToolsOutcome::Call(ToolCallOutcome::ApprovalUnavailable(control_error)) => {
|
ToolsOutcome::Call(ToolCallOutcome::ApprovalUnavailable(control_error)) => {
|
||||||
tool_error_response(
|
ToolCommandPayload::Ok(tool_error_payload(
|
||||||
message,
|
message,
|
||||||
response_mode,
|
|
||||||
protocol_version,
|
protocol_version,
|
||||||
control_tool_error_contract(
|
control_tool_error_contract(
|
||||||
control_error,
|
control_error,
|
||||||
@@ -222,34 +233,49 @@ pub(super) fn tool_command_response(
|
|||||||
correlation.trace_id().as_str(),
|
correlation.trace_id().as_str(),
|
||||||
execution_locale(message),
|
execution_locale(message),
|
||||||
),
|
),
|
||||||
)
|
))
|
||||||
|
}
|
||||||
|
ToolsOutcome::Call(ToolCallOutcome::InvalidParams(detail)) => {
|
||||||
|
ToolCommandPayload::Ok(jsonrpc_error(request_id(message), -32602, detail))
|
||||||
}
|
}
|
||||||
ToolsOutcome::Call(ToolCallOutcome::InvalidParams(detail)) => transport_response(
|
|
||||||
StatusCode::OK,
|
|
||||||
jsonrpc_error(request_id(message), -32602, detail),
|
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
Some(protocol_version),
|
|
||||||
),
|
|
||||||
ToolsOutcome::Call(ToolCallOutcome::Error(contract)) => {
|
ToolsOutcome::Call(ToolCallOutcome::Error(contract)) => {
|
||||||
tool_error_response(message, response_mode, protocol_version, contract)
|
ToolCommandPayload::Ok(tool_error_payload(message, protocol_version, contract))
|
||||||
}
|
}
|
||||||
// The pending approval could not be persisted: the adapter answers its internal error shape,
|
// The pending approval could not be persisted: the adapter answers its internal error shape,
|
||||||
// as the previous wire path did.
|
// as the previous wire path did.
|
||||||
ToolsOutcome::Call(ToolCallOutcome::InternalFailure) => internal_jsonrpc_error(
|
ToolsOutcome::Call(ToolCallOutcome::InternalFailure) => {
|
||||||
message,
|
ToolCommandPayload::Internal("the pending approval request could not be persisted")
|
||||||
"the pending approval request could not be persisted",
|
}
|
||||||
),
|
|
||||||
// A call command never produces these variants; they are answered with the adapter's
|
// A call command never produces these variants; they are answered with the adapter's
|
||||||
// internal error instead of being silently ignored.
|
// internal error instead of being silently ignored.
|
||||||
ToolsOutcome::List { .. }
|
ToolsOutcome::List { .. }
|
||||||
| ToolsOutcome::InvalidParams(_)
|
| ToolsOutcome::InvalidParams(_)
|
||||||
| ToolsOutcome::CatalogUnavailable => {
|
| ToolsOutcome::CatalogUnavailable => {
|
||||||
internal_jsonrpc_error(message, "unexpected shared tools outcome for a tools/call")
|
ToolCommandPayload::Internal("unexpected shared tools outcome for a tools/call")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The single-response form of [`tool_command_payload`].
|
||||||
|
pub(super) fn tool_command_response(
|
||||||
|
message: &Value,
|
||||||
|
response_mode: ResponseMode,
|
||||||
|
protocol_version: &str,
|
||||||
|
correlation: &CorrelationContext,
|
||||||
|
outcome: ToolsOutcome,
|
||||||
|
) -> Response {
|
||||||
|
match tool_command_payload(message, protocol_version, correlation, outcome) {
|
||||||
|
ToolCommandPayload::Ok(payload) => transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
payload,
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
Some(protocol_version),
|
||||||
|
),
|
||||||
|
ToolCommandPayload::Internal(detail) => internal_jsonrpc_error(message, detail),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub(super) fn resource_error_response(
|
pub(super) fn resource_error_response(
|
||||||
message: &Value,
|
message: &Value,
|
||||||
response_mode: ResponseMode,
|
response_mode: ResponseMode,
|
||||||
|
|||||||
@@ -33,6 +33,7 @@ use crate::{
|
|||||||
access::credential_allows_security_level,
|
access::credential_allows_security_level,
|
||||||
app::{
|
app::{
|
||||||
AppState, ApprovalPolicyContext, ApprovalPolicyDecision, InvocationRecord,
|
AppState, ApprovalPolicyContext, ApprovalPolicyDecision, InvocationRecord,
|
||||||
|
lifecycle::{Phase, ToolCallLifecycle},
|
||||||
maybe_handle_approval_policy, persist_invocation_for_key, resolve_generated_tool,
|
maybe_handle_approval_policy, persist_invocation_for_key, resolve_generated_tool,
|
||||||
resolve_operation_auth, runtime_operation, take_confirmation_token,
|
resolve_operation_auth, runtime_operation, take_confirmation_token,
|
||||||
},
|
},
|
||||||
@@ -140,10 +141,15 @@ pub(crate) enum ToolCallOutcome {
|
|||||||
|
|
||||||
/// Handle one shared Tools command. No wire envelope, `ResponseMode`, `axum::Response`, session or
|
/// Handle one shared Tools command. No wire envelope, `ResponseMode`, `axum::Response`, session or
|
||||||
/// protocol revision crosses this boundary.
|
/// protocol revision crosses this boundary.
|
||||||
|
///
|
||||||
|
/// `lifecycle` is the request-scoped progress/cancellation handle of a `tools/call` (Story 3.4);
|
||||||
|
/// a command that cannot have one (`tools/list`) passes `None`, and the service then simply never
|
||||||
|
/// produces a progress event.
|
||||||
pub(crate) async fn handle_tools_command(
|
pub(crate) async fn handle_tools_command(
|
||||||
state: &Arc<AppState>,
|
state: &Arc<AppState>,
|
||||||
context: ServiceContext<'_>,
|
context: ServiceContext<'_>,
|
||||||
command: ToolsCommand,
|
command: ToolsCommand,
|
||||||
|
lifecycle: Option<ToolCallLifecycle>,
|
||||||
) -> ToolsOutcome {
|
) -> ToolsOutcome {
|
||||||
// One marker per entered owning Tools service/handler (Story 3.1 section 7.2). It is a
|
// One marker per entered owning Tools service/handler (Story 3.1 section 7.2). It is a
|
||||||
// `#[cfg(test)]`-only, request-scoped counter and has no production effect.
|
// `#[cfg(test)]`-only, request-scoped counter and has no production effect.
|
||||||
@@ -166,9 +172,9 @@ pub(crate) async fn handle_tools_command(
|
|||||||
Err(message) => ToolsOutcome::InvalidParams(message.to_owned()),
|
Err(message) => ToolsOutcome::InvalidParams(message.to_owned()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
ToolsCommand::Call(call) => {
|
ToolsCommand::Call(call) => ToolsOutcome::Call(
|
||||||
ToolsOutcome::Call(execute_tool_command(state, &context, call, &catalog).await)
|
execute_tool_command(state, &context, call, &catalog, lifecycle.as_ref()).await,
|
||||||
}
|
),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -178,6 +184,7 @@ async fn execute_tool_command(
|
|||||||
context: &ServiceContext<'_>,
|
context: &ServiceContext<'_>,
|
||||||
command: ToolCallCommand,
|
command: ToolCallCommand,
|
||||||
catalog: &PublishedAgentCatalog,
|
catalog: &PublishedAgentCatalog,
|
||||||
|
lifecycle: Option<&ToolCallLifecycle>,
|
||||||
) -> ToolCallOutcome {
|
) -> ToolCallOutcome {
|
||||||
match catalog.tool_selection_policy.mode {
|
match catalog.tool_selection_policy.mode {
|
||||||
ToolAccessMode::Direct => {
|
ToolAccessMode::Direct => {
|
||||||
@@ -188,6 +195,7 @@ async fn execute_tool_command(
|
|||||||
&command.tool_name,
|
&command.tool_name,
|
||||||
command.arguments,
|
command.arguments,
|
||||||
command.confirmation_token,
|
command.confirmation_token,
|
||||||
|
lifecycle,
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
@@ -222,6 +230,7 @@ async fn execute_tool_command(
|
|||||||
&proxy.name,
|
&proxy.name,
|
||||||
arguments,
|
arguments,
|
||||||
confirmation_token,
|
confirmation_token,
|
||||||
|
lifecycle,
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
@@ -240,6 +249,7 @@ async fn execute_resolved_tool(
|
|||||||
tool_name: &str,
|
tool_name: &str,
|
||||||
arguments: Value,
|
arguments: Value,
|
||||||
confirmation_token: Option<String>,
|
confirmation_token: Option<String>,
|
||||||
|
lifecycle: Option<&ToolCallLifecycle>,
|
||||||
) -> ToolCallOutcome {
|
) -> ToolCallOutcome {
|
||||||
let correlation = context.correlation;
|
let correlation = context.correlation;
|
||||||
let transport_request_id = correlation.request_id().as_str();
|
let transport_request_id = correlation.request_id().as_str();
|
||||||
@@ -250,6 +260,10 @@ async fn execute_resolved_tool(
|
|||||||
Some(resolved) => {
|
Some(resolved) => {
|
||||||
StageOutcome::Success.record(&resolve_span);
|
StageOutcome::Success.record(&resolve_span);
|
||||||
drop(resolve_span);
|
drop(resolve_span);
|
||||||
|
// First real execution step: the addressed tool of the published catalog is resolved.
|
||||||
|
if let Some(lifecycle) = lifecycle {
|
||||||
|
lifecycle.advance(Phase::Resolved);
|
||||||
|
}
|
||||||
resolved.tool
|
resolved.tool
|
||||||
}
|
}
|
||||||
None => {
|
None => {
|
||||||
@@ -349,8 +363,14 @@ async fn execute_resolved_tool(
|
|||||||
let resolved_auth =
|
let resolved_auth =
|
||||||
resolve_operation_auth(state, &tool.workspace_id, &operation.execution_config).await;
|
resolve_operation_auth(state, &tool.workspace_id, &operation.execution_config).await;
|
||||||
|
|
||||||
|
// A cancellation can only stop the call before it reaches its terminal outcome: nothing is
|
||||||
|
// persisted for a stopped call, so Invocation History can never claim a false `completed`.
|
||||||
let result = match resolved_auth {
|
let result = match resolved_auth {
|
||||||
Ok(resolved_auth) => {
|
Ok(resolved_auth) => {
|
||||||
|
// Second real step: the operation's own authorization is resolved, so the runtime may run.
|
||||||
|
if let Some(lifecycle) = lifecycle {
|
||||||
|
lifecycle.advance(Phase::Authorized);
|
||||||
|
}
|
||||||
match RuntimeExecutionRequest::try_new(
|
match RuntimeExecutionRequest::try_new(
|
||||||
&tool.workspace_id,
|
&tool.workspace_id,
|
||||||
ExecutionOrigin::AgentSnapshot,
|
ExecutionOrigin::AgentSnapshot,
|
||||||
@@ -365,7 +385,15 @@ async fn execute_resolved_tool(
|
|||||||
operation.execution_config.timeout_ms.max(1),
|
operation.execution_config.timeout_ms.max(1),
|
||||||
),
|
),
|
||||||
) {
|
) {
|
||||||
Ok(request) => state.runtime.execute_outcome(request).await,
|
Ok(request) => {
|
||||||
|
// Third real step: the request is about to enter the runtime, so from here on an
|
||||||
|
// outbound side effect may happen and a cancellation can no longer promise that
|
||||||
|
// nothing was sent.
|
||||||
|
if let Some(lifecycle) = lifecycle {
|
||||||
|
lifecycle.advance(Phase::Dispatching);
|
||||||
|
}
|
||||||
|
state.runtime.execute_outcome(request).await
|
||||||
|
}
|
||||||
Err(_) => Err(ExecutionFailure::new(
|
Err(_) => Err(ExecutionFailure::new(
|
||||||
ExecutionErrorCode::RuntimeInternal,
|
ExecutionErrorCode::RuntimeInternal,
|
||||||
correlation.clone(),
|
correlation.clone(),
|
||||||
|
|||||||
@@ -192,6 +192,46 @@ pub(crate) fn set_active_level(level: Option<LogLevel>) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The request's logging context, carried into a streamed response body (Story 3.4).
|
||||||
|
///
|
||||||
|
/// A streamed `tools/call` response is assembled after the request handler returned, so its terminal
|
||||||
|
/// event would be projected outside the task-local scope of the request. This snapshot carries the
|
||||||
|
/// only two facts the projection needs — the level the client opted in to and whether the request
|
||||||
|
/// offered the SSE carrier — and never a request value.
|
||||||
|
#[derive(Clone, Copy, Default)]
|
||||||
|
pub(crate) struct CarriedScope {
|
||||||
|
active: Option<LogLevel>,
|
||||||
|
sse_acceptable: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Snapshot the scope of the request that is being served now. Outside a scope the snapshot is
|
||||||
|
/// "not opted in", which delivers nothing.
|
||||||
|
pub(crate) fn carry_scope() -> CarriedScope {
|
||||||
|
REQUEST_LOG
|
||||||
|
.try_with(|log| {
|
||||||
|
let log = log.borrow();
|
||||||
|
CarriedScope {
|
||||||
|
active: log.active,
|
||||||
|
sse_acceptable: log.sse_acceptable,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Run one step of the streamed response inside a scope carrying the request's logging context.
|
||||||
|
pub(crate) async fn in_carried_scope<F: Future>(scope: CarriedScope, future: F) -> F::Output {
|
||||||
|
REQUEST_LOG
|
||||||
|
.scope(
|
||||||
|
RefCell::new(RequestLog {
|
||||||
|
active: scope.active,
|
||||||
|
sse_acceptable: scope.sse_acceptable,
|
||||||
|
pending: Vec::new(),
|
||||||
|
}),
|
||||||
|
future,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
/// Remember that this request offered `text/event-stream`, the only carrier of a notification.
|
/// Remember that this request offered `text/event-stream`, the only carrier of a notification.
|
||||||
pub(crate) fn set_sse_acceptable() {
|
pub(crate) fn set_sse_acceptable() {
|
||||||
let _ = REQUEST_LOG.try_with(|log| {
|
let _ = REQUEST_LOG.try_with(|log| {
|
||||||
|
|||||||
@@ -30,6 +30,7 @@ mod logging;
|
|||||||
mod prompts;
|
mod prompts;
|
||||||
mod registry;
|
mod registry;
|
||||||
mod resources;
|
mod resources;
|
||||||
|
mod signals;
|
||||||
|
|
||||||
pub(crate) use command::{
|
pub(crate) use command::{
|
||||||
ContinuationSupport, ServiceContext, ToolCallCommand, ToolCallOutcome, ToolsCommand,
|
ContinuationSupport, ServiceContext, ToolCallCommand, ToolCallOutcome, ToolsCommand,
|
||||||
@@ -37,9 +38,10 @@ pub(crate) use command::{
|
|||||||
};
|
};
|
||||||
pub(crate) use completion::{CompletionCommand, CompletionOutcome, handle_completion_command};
|
pub(crate) use completion::{CompletionCommand, CompletionOutcome, handle_completion_command};
|
||||||
pub(crate) use logging::{
|
pub(crate) use logging::{
|
||||||
EVENT_FAILED, EVENT_LEVEL_APPLIED, EVENT_REJECTED, EVENT_SERVED, INVALID_LEVEL, LogLevel,
|
CarriedScope, EVENT_FAILED, EVENT_LEVEL_APPLIED, EVENT_REJECTED, EVENT_SERVED, INVALID_LEVEL,
|
||||||
LogLevelStore, LoggingOutcome, SetLevelCommand, handle_logging_command, modern_request_level,
|
LogLevel, LogLevelStore, LoggingOutcome, SetLevelCommand, carry_scope, handle_logging_command,
|
||||||
note, scoped as logging_scope, set_active_level, set_sse_acceptable, take_notifications,
|
in_carried_scope, modern_request_level, note, scoped as logging_scope, set_active_level,
|
||||||
|
set_sse_acceptable, take_notifications,
|
||||||
};
|
};
|
||||||
pub(crate) use prompts::{
|
pub(crate) use prompts::{
|
||||||
PromptGetCommand, PromptsCommand, PromptsListCommand, PromptsOutcome, handle_prompts_command,
|
PromptGetCommand, PromptsCommand, PromptsListCommand, PromptsOutcome, handle_prompts_command,
|
||||||
@@ -48,6 +50,10 @@ pub(crate) use resources::{
|
|||||||
ResourceReadCommand, ResourceTemplatesListError, ResourcesCommand, ResourcesListCommand,
|
ResourceReadCommand, ResourceTemplatesListError, ResourcesCommand, ResourcesListCommand,
|
||||||
ResourcesOutcome, handle_resources_command, list_resource_templates,
|
ResourcesOutcome, handle_resources_command, list_resource_templates,
|
||||||
};
|
};
|
||||||
|
pub(crate) use signals::{
|
||||||
|
FilterOutcome, INVALID_LISTEN_FILTER, ListenParams, Signals, StreamRegistry, Watch, Wire,
|
||||||
|
acknowledged_frame, frames_stream, spawn as spawn_signal_watch, subscription_id,
|
||||||
|
};
|
||||||
|
|
||||||
/// Resolved era of an incoming POST request.
|
/// Resolved era of an incoming POST request.
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
|||||||
@@ -22,6 +22,11 @@ pub(crate) enum CapabilityId {
|
|||||||
Prompts,
|
Prompts,
|
||||||
/// Bounded argument completion for bound Published Prompts and Resource templates (Story 3.17).
|
/// Bounded argument completion for bound Published Prompts and Resource templates (Story 3.17).
|
||||||
Completions,
|
Completions,
|
||||||
|
/// `subscriptions/listen` of the modern revision: a *client-sent* request that opens the
|
||||||
|
/// notification stream (Story 3.19). It is a dispatch-only registration without an advertisement
|
||||||
|
/// fragment because the pinned modern schema has no server `subscriptions` capability object;
|
||||||
|
/// there is no such method in the legacy revision at all.
|
||||||
|
Subscriptions,
|
||||||
/// `logging` server capability: safe structured `notifications/message` events of the negotiated
|
/// `logging` server capability: safe structured `notifications/message` events of the negotiated
|
||||||
/// client context (Story 3.18). Advertised in both revisions; the pinned modern revision carries
|
/// client context (Story 3.18). Advertised in both revisions; the pinned modern revision carries
|
||||||
/// the level per request in `_meta` and marks the capability deprecated (SEP-2577).
|
/// the level per request in `_meta` and marks the capability deprecated (SEP-2577).
|
||||||
@@ -90,6 +95,9 @@ pub(crate) enum MethodHandler {
|
|||||||
/// `completion/complete`: bounded suggestions from the typed schema of one exact bound Prompt
|
/// `completion/complete`: bounded suggestions from the typed schema of one exact bound Prompt
|
||||||
/// argument or one exact bound Resource template parameter (Story 3.17).
|
/// argument or one exact bound Resource template parameter (Story 3.17).
|
||||||
Completion,
|
Completion,
|
||||||
|
/// `subscriptions/listen`: open the long-lived modern notification stream and deliver the
|
||||||
|
/// Resource/Prompt list-change signals the client opted in to (Story 3.19).
|
||||||
|
SubscriptionsListen,
|
||||||
/// `logging/setLevel`: validate the pinned level and record it for this legacy session, so the
|
/// `logging/setLevel`: validate the pinned level and record it for this legacy session, so the
|
||||||
/// adapter can deliver safe structured `notifications/message` events of that context
|
/// adapter can deliver safe structured `notifications/message` events of that context
|
||||||
/// (Story 3.18). The handler never widens the accepted vocabulary and never echoes the input.
|
/// (Story 3.18). The handler never widens the accepted vocabulary and never echoes the input.
|
||||||
@@ -97,6 +105,10 @@ pub(crate) enum MethodHandler {
|
|||||||
Ping,
|
Ping,
|
||||||
Discover,
|
Discover,
|
||||||
Lifecycle,
|
Lifecycle,
|
||||||
|
/// `notifications/cancelled`: the legacy client cancels a `tools/call` it already issued
|
||||||
|
/// (Story 3.4). The handler only routes the id to the owner's in-flight call; it never widens
|
||||||
|
/// what may be cancelled and never authorizes by the progress token.
|
||||||
|
Cancelled,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug)]
|
#[derive(Clone, Copy, Debug)]
|
||||||
@@ -361,7 +373,9 @@ pub(crate) const CAPABILITY_DESCRIPTORS: &[CapabilityIdDescriptor] = &[
|
|||||||
extension: None,
|
extension: None,
|
||||||
deprecated: None,
|
deprecated: None,
|
||||||
sub_features: FeatureSet(&["listChanged"]),
|
sub_features: FeatureSet(&["listChanged"]),
|
||||||
advertised: Some(("tools", &[("listChanged", false)])),
|
// Story 3.5: the adapter emits `notifications/tools/list_changed` from the committed
|
||||||
|
// published Tool bindings of the Agent snapshot, so the declaration is now true.
|
||||||
|
advertised: Some(("tools", &[("listChanged", true)])),
|
||||||
revisions: MODERN_AND_LEGACY,
|
revisions: MODERN_AND_LEGACY,
|
||||||
},
|
},
|
||||||
CapabilityIdDescriptor {
|
CapabilityIdDescriptor {
|
||||||
@@ -371,7 +385,9 @@ pub(crate) const CAPABILITY_DESCRIPTORS: &[CapabilityIdDescriptor] = &[
|
|||||||
extension: None,
|
extension: None,
|
||||||
deprecated: None,
|
deprecated: None,
|
||||||
sub_features: FeatureSet(&["subscribe", "listChanged"]),
|
sub_features: FeatureSet(&["subscribe", "listChanged"]),
|
||||||
advertised: Some(("resources", &[("subscribe", false), ("listChanged", false)])),
|
// Story 3.19: the server really emits `notifications/resources/list_changed`; URI-content
|
||||||
|
// subscriptions (`subscribe`) remain unimplemented and are still advertised as false.
|
||||||
|
advertised: Some(("resources", &[("subscribe", false), ("listChanged", true)])),
|
||||||
revisions: MODERN_AND_LEGACY,
|
revisions: MODERN_AND_LEGACY,
|
||||||
},
|
},
|
||||||
CapabilityIdDescriptor {
|
CapabilityIdDescriptor {
|
||||||
@@ -381,7 +397,8 @@ pub(crate) const CAPABILITY_DESCRIPTORS: &[CapabilityIdDescriptor] = &[
|
|||||||
extension: None,
|
extension: None,
|
||||||
deprecated: None,
|
deprecated: None,
|
||||||
sub_features: FeatureSet(&["listChanged"]),
|
sub_features: FeatureSet(&["listChanged"]),
|
||||||
advertised: Some(("prompts", &[("listChanged", false)])),
|
// Story 3.19: the server really emits `notifications/prompts/list_changed`.
|
||||||
|
advertised: Some(("prompts", &[("listChanged", true)])),
|
||||||
revisions: MODERN_AND_LEGACY,
|
revisions: MODERN_AND_LEGACY,
|
||||||
},
|
},
|
||||||
CapabilityIdDescriptor {
|
CapabilityIdDescriptor {
|
||||||
@@ -422,6 +439,19 @@ pub(crate) const CAPABILITY_DESCRIPTORS: &[CapabilityIdDescriptor] = &[
|
|||||||
advertised: None,
|
advertised: None,
|
||||||
revisions: LEGACY_ONLY,
|
revisions: LEGACY_ONLY,
|
||||||
},
|
},
|
||||||
|
CapabilityIdDescriptor {
|
||||||
|
// Story 3.19: dispatch-only registration of the modern `subscriptions/listen` request. The
|
||||||
|
// client sends it; the pinned modern schema declares no server `subscriptions` capability
|
||||||
|
// object, so it carries no advertisement fragment. The legacy revision has no such method.
|
||||||
|
id: CapabilityId::Subscriptions,
|
||||||
|
roster: Roster::Client,
|
||||||
|
kind: Kind::Method,
|
||||||
|
extension: None,
|
||||||
|
deprecated: None,
|
||||||
|
sub_features: FeatureSet(&[]),
|
||||||
|
advertised: None,
|
||||||
|
revisions: MODERN_ONLY,
|
||||||
|
},
|
||||||
CapabilityIdDescriptor {
|
CapabilityIdDescriptor {
|
||||||
id: CapabilityId::Ping,
|
id: CapabilityId::Ping,
|
||||||
roster: Roster::Server,
|
roster: Roster::Server,
|
||||||
@@ -536,6 +566,17 @@ pub(crate) const METHOD_DESCRIPTORS: &[MethodDescriptor] = &[
|
|||||||
required_headers: HEADERS_METHOD_ONLY,
|
required_headers: HEADERS_METHOD_ONLY,
|
||||||
handler: MethodHandler::LoggingSetLevel,
|
handler: MethodHandler::LoggingSetLevel,
|
||||||
},
|
},
|
||||||
|
MethodDescriptor {
|
||||||
|
// Story 3.19: the modern long-lived notification stream. It declares the notification filter
|
||||||
|
// in its params, not a server-side name, so only the method header applies. The legacy
|
||||||
|
// revision opens its notification stream with `GET` instead, so this name is a wrong-era
|
||||||
|
// request there and must never be served.
|
||||||
|
name: "subscriptions/listen",
|
||||||
|
capability: CapabilityId::Subscriptions,
|
||||||
|
kind: Kind::Method,
|
||||||
|
required_headers: HEADERS_METHOD_ONLY,
|
||||||
|
handler: MethodHandler::SubscriptionsListen,
|
||||||
|
},
|
||||||
MethodDescriptor {
|
MethodDescriptor {
|
||||||
name: "ping",
|
name: "ping",
|
||||||
capability: CapabilityId::Ping,
|
capability: CapabilityId::Ping,
|
||||||
@@ -564,6 +605,17 @@ pub(crate) const METHOD_DESCRIPTORS: &[MethodDescriptor] = &[
|
|||||||
required_headers: HEADERS_NONE,
|
required_headers: HEADERS_NONE,
|
||||||
handler: MethodHandler::Lifecycle,
|
handler: MethodHandler::Lifecycle,
|
||||||
},
|
},
|
||||||
|
MethodDescriptor {
|
||||||
|
// Story 3.4: the legacy revision's client-side cancellation of a request it issued. The
|
||||||
|
// pinned modern revision has no client-to-server notification over Streamable HTTP (closing
|
||||||
|
// the response stream is its cancellation signal), so this name exists in the legacy era
|
||||||
|
// only. It is a dispatch-only notification registration and advertises nothing.
|
||||||
|
name: "notifications/cancelled",
|
||||||
|
capability: CapabilityId::LegacyLifecycle,
|
||||||
|
kind: Kind::Notification,
|
||||||
|
required_headers: HEADERS_NONE,
|
||||||
|
handler: MethodHandler::Cancelled,
|
||||||
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
|
|||||||
@@ -37,9 +37,9 @@ fn static_registration_is_unique_and_advertises_only_the_registered_capability()
|
|||||||
json!({
|
json!({
|
||||||
"completions": {},
|
"completions": {},
|
||||||
"logging": {},
|
"logging": {},
|
||||||
"prompts": {"listChanged": false},
|
"prompts": {"listChanged": true},
|
||||||
"resources": {"listChanged": false, "subscribe": false},
|
"resources": {"listChanged": true, "subscribe": false},
|
||||||
"tools": {"listChanged": false}
|
"tools": {"listChanged": true}
|
||||||
}),
|
}),
|
||||||
"the registered advertisement must be the same reviewed object in {revision}"
|
"the registered advertisement must be the same reviewed object in {revision}"
|
||||||
);
|
);
|
||||||
@@ -48,9 +48,9 @@ fn static_registration_is_unique_and_advertises_only_the_registered_capability()
|
|||||||
json!({
|
json!({
|
||||||
"completions": {},
|
"completions": {},
|
||||||
"logging": {},
|
"logging": {},
|
||||||
"prompts": {"listChanged": false},
|
"prompts": {"listChanged": true},
|
||||||
"resources": {"listChanged": false, "subscribe": false},
|
"resources": {"listChanged": true, "subscribe": false},
|
||||||
"tools": {"listChanged": false}
|
"tools": {"listChanged": true}
|
||||||
}),
|
}),
|
||||||
"the production advertisement entry point must serve {revision}"
|
"the production advertisement entry point must serve {revision}"
|
||||||
);
|
);
|
||||||
@@ -262,9 +262,9 @@ fn an_inert_test_descriptor_changes_both_projections_and_is_never_registered_in_
|
|||||||
json!({
|
json!({
|
||||||
"completions": {},
|
"completions": {},
|
||||||
"logging": {},
|
"logging": {},
|
||||||
"prompts": {"listChanged": false},
|
"prompts": {"listChanged": true},
|
||||||
"resources": {"listChanged": false, "subscribe": false},
|
"resources": {"listChanged": true, "subscribe": false},
|
||||||
"tools": {"listChanged": false}
|
"tools": {"listChanged": true}
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
@@ -273,9 +273,9 @@ fn an_inert_test_descriptor_changes_both_projections_and_is_never_registered_in_
|
|||||||
"inert_test_capability": {"enabled": true},
|
"inert_test_capability": {"enabled": true},
|
||||||
"completions": {},
|
"completions": {},
|
||||||
"logging": {},
|
"logging": {},
|
||||||
"prompts": {"listChanged": false},
|
"prompts": {"listChanged": true},
|
||||||
"resources": {"listChanged": false, "subscribe": false},
|
"resources": {"listChanged": true, "subscribe": false},
|
||||||
"tools": {"listChanged": false}
|
"tools": {"listChanged": true}
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
@@ -284,9 +284,9 @@ fn an_inert_test_descriptor_changes_both_projections_and_is_never_registered_in_
|
|||||||
"inert_test_capability": {"enabled": true},
|
"inert_test_capability": {"enabled": true},
|
||||||
"completions": {},
|
"completions": {},
|
||||||
"logging": {},
|
"logging": {},
|
||||||
"prompts": {"listChanged": false},
|
"prompts": {"listChanged": true},
|
||||||
"resources": {"listChanged": false, "subscribe": false},
|
"resources": {"listChanged": true, "subscribe": false},
|
||||||
"tools": {"listChanged": false}
|
"tools": {"listChanged": true}
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -468,9 +468,9 @@ fn a_single_era_descriptor_never_leaks_into_the_other_era_advertisement() {
|
|||||||
json!({
|
json!({
|
||||||
"completions": {},
|
"completions": {},
|
||||||
"logging": {},
|
"logging": {},
|
||||||
"prompts": {"listChanged": false},
|
"prompts": {"listChanged": true},
|
||||||
"resources": {"listChanged": false, "subscribe": false},
|
"resources": {"listChanged": true, "subscribe": false},
|
||||||
"tools": {"listChanged": false}
|
"tools": {"listChanged": true}
|
||||||
}),
|
}),
|
||||||
"the other era advertisement stays the reviewed object"
|
"the other era advertisement stays the reviewed object"
|
||||||
);
|
);
|
||||||
@@ -759,9 +759,9 @@ fn adding_and_removing_a_method_descriptor_changes_the_dispatch_decision() {
|
|||||||
"inert_test_capability": {"enabled": true},
|
"inert_test_capability": {"enabled": true},
|
||||||
"completions": {},
|
"completions": {},
|
||||||
"logging": {},
|
"logging": {},
|
||||||
"prompts": {"listChanged": false},
|
"prompts": {"listChanged": true},
|
||||||
"resources": {"listChanged": false, "subscribe": false},
|
"resources": {"listChanged": true, "subscribe": false},
|
||||||
"tools": {"listChanged": false}
|
"tools": {"listChanged": true}
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,501 @@
|
|||||||
|
//! Story 3.19: Resource and Prompt list-change signals (FR-19); Story 3.5 adds the Tools signal of
|
||||||
|
//! the same seam (FR-14).
|
||||||
|
//!
|
||||||
|
//! The positive result of the story is that a client which asked for the list-change signal of its
|
||||||
|
//! revision learns that the *committed* Resource, Prompt or Tool catalog changed, and that the
|
||||||
|
//! ordinary `resources/list`, `resources/read`, `resources/templates/list`, `prompts/list`,
|
||||||
|
//! `prompts/get` and `tools/list` stay authoritative for a client that misses the notification.
|
||||||
|
//!
|
||||||
|
//! Shape of the chosen seam (ARC decision, kanban t_c12863fb): a **stream-local watcher**. One open
|
||||||
|
//! notification stream owns one bounded periodic read of the published Agent catalog the stream is
|
||||||
|
//! scoped to; a change of the visible Resource/Prompt/Tool projection of that snapshot (the Resource
|
||||||
|
//! and Prompt bindings plus the exact Tool definitions `tools/list` serves) produces the revision's
|
||||||
|
//! list-change notification. There is no post-commit hook, no cross-process bus and no durable
|
||||||
|
//! queue: the committed catalog is the source of truth, so a signal can never be produced before its
|
||||||
|
//! commit, and a failed read can never roll the commit back — it only skips that tick and stays
|
||||||
|
//! observable in tracing.
|
||||||
|
//!
|
||||||
|
//! Bounds (issue requirement: bounded queues/frequency/bytes):
|
||||||
|
//! * one in-flight read per stream, one fixed poll interval, a read timeout and skipped ticks;
|
||||||
|
//! * at most one frame per change type per tick, so a burst coalesces by the latest observed
|
||||||
|
//! revision instead of queueing every intermediate commit;
|
||||||
|
//! * the queue is a fixed-capacity channel; a slow reader drops the newest frame instead of blocking
|
||||||
|
//! the producer or growing memory, and recovers through the authoritative list methods;
|
||||||
|
//! * every frame has a fixed shape — a closed method name plus the request id of the subscription —
|
||||||
|
//! so the byte bound follows from the id bound ([`MAX_SUBSCRIPTION_ID_BYTES`]).
|
||||||
|
//!
|
||||||
|
//! Scope boundary: this module serves list-change signals only. URI-content subscriptions
|
||||||
|
//! (`resources/subscribe` / `notifications/resources/updated`) stay unimplemented and are never
|
||||||
|
//! acknowledged or emitted here.
|
||||||
|
|
||||||
|
use std::{
|
||||||
|
collections::{HashMap, VecDeque},
|
||||||
|
future::Future,
|
||||||
|
pin::Pin,
|
||||||
|
sync::{
|
||||||
|
Arc, Mutex, MutexGuard,
|
||||||
|
atomic::{AtomicU64, Ordering},
|
||||||
|
},
|
||||||
|
time::{Duration, Instant},
|
||||||
|
};
|
||||||
|
|
||||||
|
use axum::response::sse::Event;
|
||||||
|
use crank_registry::PublishedAgentCatalog;
|
||||||
|
use futures_util::stream;
|
||||||
|
use serde::Deserialize;
|
||||||
|
use serde_json::{Map, Value, json};
|
||||||
|
use tokio::sync::mpsc;
|
||||||
|
use tracing::warn;
|
||||||
|
|
||||||
|
use crate::app::AppState;
|
||||||
|
|
||||||
|
/// The pinned key that correlates every message of one subscription stream with its
|
||||||
|
/// `subscriptions/listen` request id.
|
||||||
|
pub(crate) const SUBSCRIPTION_ID_KEY: &str = "io.modelcontextprotocol/subscriptionId";
|
||||||
|
|
||||||
|
/// `notifications/resources/list_changed` (both approved revisions).
|
||||||
|
pub(crate) const RESOURCE_LIST_CHANGED: &str = "notifications/resources/list_changed";
|
||||||
|
/// `notifications/prompts/list_changed` (both approved revisions).
|
||||||
|
pub(crate) const PROMPT_LIST_CHANGED: &str = "notifications/prompts/list_changed";
|
||||||
|
/// `notifications/tools/list_changed` (both approved revisions, Story 3.5).
|
||||||
|
pub(crate) const TOOL_LIST_CHANGED: &str = "notifications/tools/list_changed";
|
||||||
|
/// `notifications/subscriptions/acknowledged` (modern revision only).
|
||||||
|
pub(crate) const SUBSCRIPTIONS_ACKNOWLEDGED: &str = "notifications/subscriptions/acknowledged";
|
||||||
|
|
||||||
|
/// Engineering default of the watcher tick. It is not a measured latency SLO: the story only needs
|
||||||
|
/// "after commit", and the client always keeps the authoritative list methods for recovery.
|
||||||
|
pub(crate) const POLL_INTERVAL: Duration = Duration::from_secs(1);
|
||||||
|
/// Upper bound of one watcher read. A read that exceeds it is a skipped tick, exactly like a failed
|
||||||
|
/// read: no signal, no rollback, one safe tracing event.
|
||||||
|
pub(crate) const READ_TIMEOUT: Duration = Duration::from_secs(5);
|
||||||
|
/// Frames a slow reader may fall behind before the newest frame is dropped (`coalescing`).
|
||||||
|
pub(crate) const SIGNAL_QUEUE_CAPACITY: usize = 4;
|
||||||
|
/// Bound of the encoded `subscriptions/listen` id carried by every frame of one stream.
|
||||||
|
pub(crate) const MAX_SUBSCRIPTION_ID_BYTES: usize = 64;
|
||||||
|
/// Bound of the legacy session stream table (memory bound; see [`StreamRegistry`]).
|
||||||
|
pub(crate) const MAX_TRACKED_STREAMS: usize = 1_024;
|
||||||
|
/// Bound of the URIs a modern filter may name. The server does not implement URI subscriptions, so
|
||||||
|
/// this many names is already far more than a well-behaved client asks for.
|
||||||
|
pub(crate) const MAX_FILTER_URIS: usize = 32;
|
||||||
|
/// Bound of one URI in the modern filter: longer values are rejected without being echoed back.
|
||||||
|
pub(crate) const MAX_FILTER_URI_BYTES: usize = 2_048;
|
||||||
|
|
||||||
|
/// The one safe detail of a malformed or oversized `subscriptions/listen` filter.
|
||||||
|
pub(crate) const INVALID_LISTEN_FILTER: &str = "invalid subscriptions/listen notification filter";
|
||||||
|
|
||||||
|
/// The three list-change signal types this server implements.
|
||||||
|
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||||
|
pub(crate) struct Signals {
|
||||||
|
pub(crate) resources: bool,
|
||||||
|
pub(crate) prompts: bool,
|
||||||
|
pub(crate) tools: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Signals {
|
||||||
|
/// All types: the legacy revision defines no client opt-in, so its stream carries every type.
|
||||||
|
pub(crate) const ALL: Self = Self {
|
||||||
|
resources: true,
|
||||||
|
prompts: true,
|
||||||
|
tools: true,
|
||||||
|
};
|
||||||
|
|
||||||
|
#[cfg_attr(not(test), allow(dead_code))] // read by the unit oracle of the projection
|
||||||
|
pub(crate) fn any(self) -> bool {
|
||||||
|
self.resources || self.prompts || self.tools
|
||||||
|
}
|
||||||
|
|
||||||
|
fn intersect(self, other: Self) -> Self {
|
||||||
|
Self {
|
||||||
|
resources: self.resources && other.resources,
|
||||||
|
prompts: self.prompts && other.prompts,
|
||||||
|
tools: self.tools && other.tools,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The pinned modern `SubscriptionFilter`, as far as this server reads it.
|
||||||
|
///
|
||||||
|
/// Unknown members are ignored and a malformed shape is a deserialization error, so a client cannot
|
||||||
|
/// reach the watcher with anything but the reviewed field set.
|
||||||
|
#[derive(Debug, Default, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub(crate) struct ListenFilter {
|
||||||
|
#[serde(default)]
|
||||||
|
tools_list_changed: bool,
|
||||||
|
#[serde(default)]
|
||||||
|
prompts_list_changed: bool,
|
||||||
|
#[serde(default)]
|
||||||
|
resources_list_changed: bool,
|
||||||
|
#[serde(default)]
|
||||||
|
resource_subscriptions: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The pinned `SubscriptionsListenRequestParams`: the notification filter is a required member.
|
||||||
|
///
|
||||||
|
/// Only the reviewed member is read; `_meta` and any other member of the request params is not part
|
||||||
|
/// of this contract.
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
pub(crate) struct ListenParams {
|
||||||
|
pub(crate) notifications: ListenFilter,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The bounded input contract of a `subscriptions/listen` filter.
|
||||||
|
pub(crate) enum FilterOutcome {
|
||||||
|
/// The list-change subset this server honours for the stream.
|
||||||
|
Accepted(Signals),
|
||||||
|
/// One safe detail: no URI, name or value the client sent is echoed back.
|
||||||
|
Invalid(&'static str),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ListenFilter {
|
||||||
|
/// Validate the bounded inputs and keep only the honoured types.
|
||||||
|
///
|
||||||
|
/// `resourceSubscriptions` is not implemented in the current scope, which is what the
|
||||||
|
/// acknowledgment reports: it is simply not honoured, and the pinned schema forbids the server
|
||||||
|
/// from sending a type it did not agree to.
|
||||||
|
pub(crate) fn accepted(&self) -> FilterOutcome {
|
||||||
|
if self.resource_subscriptions.len() > MAX_FILTER_URIS
|
||||||
|
|| self
|
||||||
|
.resource_subscriptions
|
||||||
|
.iter()
|
||||||
|
.any(|uri| uri.len() > MAX_FILTER_URI_BYTES)
|
||||||
|
{
|
||||||
|
return FilterOutcome::Invalid(INVALID_LISTEN_FILTER);
|
||||||
|
}
|
||||||
|
FilterOutcome::Accepted(Signals {
|
||||||
|
resources: self.resources_list_changed,
|
||||||
|
prompts: self.prompts_list_changed,
|
||||||
|
tools: self.tools_list_changed,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The `notifications` object of the acknowledgment: exactly the subset that will be delivered.
|
||||||
|
fn acknowledged_filter_wire(accepted: Signals) -> Value {
|
||||||
|
let mut filter = Map::new();
|
||||||
|
if accepted.prompts {
|
||||||
|
filter.insert("promptsListChanged".to_owned(), Value::Bool(true));
|
||||||
|
}
|
||||||
|
if accepted.resources {
|
||||||
|
filter.insert("resourcesListChanged".to_owned(), Value::Bool(true));
|
||||||
|
}
|
||||||
|
if accepted.tools {
|
||||||
|
filter.insert("toolsListChanged".to_owned(), Value::Bool(true));
|
||||||
|
}
|
||||||
|
Value::Object(filter)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The exact bound Resource/Prompt/Tool projection of one published Agent catalog.
|
||||||
|
///
|
||||||
|
/// The projection is derived from the same committed catalog read that already feeds
|
||||||
|
/// `resources/list`, `resources/templates/list`, `prompts/list`, `prompts/get` and `tools/list`: the
|
||||||
|
/// exact Resource and Prompt bindings of the published Agent snapshot, in deterministic binding
|
||||||
|
/// order, and the exact Tool definitions that `tools/list` would serve. The Tool part is taken from
|
||||||
|
/// [`crate::manifest::catalog_tool_definitions`] rather than from the bindings, because that is the
|
||||||
|
/// projection the client sees: it also depends on the Tool selection policy (mode, groups, search
|
||||||
|
/// settings), and in `Search` mode it does not depend on the bindings at all. `catalog_revision`
|
||||||
|
/// alone is *not* the comparison key — a commit that only changes Tools must not produce a Resource
|
||||||
|
/// or Prompt signal, and vice versa — so the three projections are compared on their own.
|
||||||
|
///
|
||||||
|
/// shortcut: a Resource revocation invalidates a bound publication without a new Agent snapshot, so
|
||||||
|
/// it does not change this projection and produces no list-change signal; the revocation gate at
|
||||||
|
/// read time (Story 3.8) still fails closed, and a faithful revocation signal needs a bounded
|
||||||
|
/// registry read that the current scope does not have.
|
||||||
|
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||||
|
pub(crate) struct CatalogFingerprint {
|
||||||
|
resources: Vec<(String, u32)>,
|
||||||
|
prompts: Vec<(String, u32)>,
|
||||||
|
/// Canonical JSON of every definition `tools/list` serves, sorted so a re-ordered read is not a
|
||||||
|
/// false change.
|
||||||
|
tools: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CatalogFingerprint {
|
||||||
|
pub(crate) fn of(catalog: &PublishedAgentCatalog) -> Self {
|
||||||
|
fn sorted<T: Ord>(values: impl Iterator<Item = T>) -> Vec<T> {
|
||||||
|
let mut sorted = values.collect::<Vec<_>>();
|
||||||
|
sorted.sort_unstable();
|
||||||
|
sorted
|
||||||
|
}
|
||||||
|
Self {
|
||||||
|
resources: sorted(catalog.resources.iter().map(|binding| {
|
||||||
|
(
|
||||||
|
binding.resource_id.as_str().to_owned(),
|
||||||
|
binding.resource_version,
|
||||||
|
)
|
||||||
|
})),
|
||||||
|
prompts: sorted(catalog.prompts.iter().map(|binding| {
|
||||||
|
(
|
||||||
|
binding.prompt_id.as_str().to_owned(),
|
||||||
|
binding.prompt_version,
|
||||||
|
)
|
||||||
|
})),
|
||||||
|
tools: sorted(
|
||||||
|
crate::manifest::catalog_tool_definitions(catalog)
|
||||||
|
.into_iter()
|
||||||
|
.map(|definition| definition.to_string()),
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The list-change types whose visible projection differs between `previous` and `self`.
|
||||||
|
pub(crate) fn changes_since(&self, previous: &Self) -> Signals {
|
||||||
|
Signals {
|
||||||
|
resources: self.resources != previous.resources,
|
||||||
|
prompts: self.prompts != previous.prompts,
|
||||||
|
tools: self.tools != previous.tools,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The wire contract of one stream.
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub(crate) enum Wire {
|
||||||
|
/// `2025-11-25`: a bare server notification without parameters.
|
||||||
|
Legacy,
|
||||||
|
/// `2026-07-28`: every message carries the subscription id of its `subscriptions/listen` request.
|
||||||
|
Modern(Value),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Wire {
|
||||||
|
fn signal_frames(&self, signals: Signals) -> Vec<String> {
|
||||||
|
let mut frames = Vec::with_capacity(3);
|
||||||
|
for (changed, method) in [
|
||||||
|
(signals.resources, RESOURCE_LIST_CHANGED),
|
||||||
|
(signals.prompts, PROMPT_LIST_CHANGED),
|
||||||
|
(signals.tools, TOOL_LIST_CHANGED),
|
||||||
|
] {
|
||||||
|
if !changed {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let frame = match self {
|
||||||
|
Wire::Legacy => json!({ "jsonrpc": "2.0", "method": method }),
|
||||||
|
Wire::Modern(subscription_id) => json!({
|
||||||
|
"jsonrpc": "2.0",
|
||||||
|
"method": method,
|
||||||
|
"params": { "_meta": { SUBSCRIPTION_ID_KEY: subscription_id } }
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
frames.push(frame.to_string());
|
||||||
|
}
|
||||||
|
frames
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The first modern frame: the accepted subset, before any list-change notification of the stream.
|
||||||
|
pub(crate) fn acknowledged_frame(subscription_id: &Value, accepted: Signals) -> String {
|
||||||
|
json!({
|
||||||
|
"jsonrpc": "2.0",
|
||||||
|
"method": SUBSCRIPTIONS_ACKNOWLEDGED,
|
||||||
|
"params": {
|
||||||
|
"_meta": { SUBSCRIPTION_ID_KEY: subscription_id },
|
||||||
|
"notifications": acknowledged_filter_wire(accepted),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.to_string()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The subscription id of a `subscriptions/listen` request, or `None` when its encoding is not a
|
||||||
|
/// bounded identity carrier.
|
||||||
|
pub(crate) fn subscription_id(request_id: &Value) -> Option<Value> {
|
||||||
|
let encoded = request_id.to_string();
|
||||||
|
(encoded.len() <= MAX_SUBSCRIPTION_ID_BYTES).then(|| request_id.clone())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Bounded table of the legacy session that currently owns the notification stream.
|
||||||
|
///
|
||||||
|
/// The pinned legacy transport forbids broadcasting one message across several SSE streams of the
|
||||||
|
/// same session, and the community scope keeps exactly one producer per session: the newest admitted
|
||||||
|
/// `GET` takes the signals over and the older stream ends. A retired stream (session `DELETE`) or a
|
||||||
|
/// superseded generation never writes into a reconnect.
|
||||||
|
#[derive(Default)]
|
||||||
|
pub(crate) struct StreamRegistry {
|
||||||
|
next_generation: AtomicU64,
|
||||||
|
owners: Mutex<HashMap<String, u64>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl StreamRegistry {
|
||||||
|
pub(crate) fn new() -> Self {
|
||||||
|
Self::default()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Admit the notification stream of one session and return its generation.
|
||||||
|
pub(crate) fn admit(&self, session_id: &str) -> Option<u64> {
|
||||||
|
let generation = self.next_generation.fetch_add(1, Ordering::Relaxed) + 1;
|
||||||
|
let mut owners = self.lock()?;
|
||||||
|
if owners.len() >= MAX_TRACKED_STREAMS && !owners.contains_key(session_id) {
|
||||||
|
// Bounded table: forget the whole owner set instead of growing without a limit. Each
|
||||||
|
// running producer still holds its own generation, so the worst case is a stream that
|
||||||
|
// can no longer be told apart from a newer one — never unbounded memory.
|
||||||
|
owners.clear();
|
||||||
|
}
|
||||||
|
owners.insert(session_id.to_owned(), generation);
|
||||||
|
Some(generation)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether `generation` still owns the stream of `session_id`.
|
||||||
|
pub(crate) fn is_current(&self, session_id: &str, generation: u64) -> bool {
|
||||||
|
self.lock()
|
||||||
|
.and_then(|owners| owners.get(session_id).copied())
|
||||||
|
.is_some_and(|current| current == generation)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Stop the producer of one session (`DELETE`, or a session that no longer exists).
|
||||||
|
pub(crate) fn retire(&self, session_id: &str) {
|
||||||
|
if let Some(mut owners) = self.lock() {
|
||||||
|
owners.remove(session_id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn lock(&self) -> Option<MutexGuard<'_, HashMap<String, u64>>> {
|
||||||
|
self.owners.try_lock().ok()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Everything one watcher needs.
|
||||||
|
pub(crate) struct Watch {
|
||||||
|
pub(crate) workspace_slug: String,
|
||||||
|
pub(crate) agent_slug: String,
|
||||||
|
/// The signal types this stream may deliver.
|
||||||
|
pub(crate) signals: Signals,
|
||||||
|
pub(crate) wire: Wire,
|
||||||
|
/// The legacy session lease: the producer stops when the stream is superseded or retired.
|
||||||
|
pub(crate) legacy_stream: Option<(Arc<StreamRegistry>, String, u64)>,
|
||||||
|
/// Lifetime bound inherited from the legacy transport session TTL.
|
||||||
|
pub(crate) deadline: Option<Instant>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One committed-catalog read of a watcher tick.
|
||||||
|
///
|
||||||
|
/// The reader is a closure so the failure path is driveable in a unit oracle without a live
|
||||||
|
/// registry: production passes [`read`] over the shared [`AppState`], and the oracle passes a
|
||||||
|
/// scripted sequence.
|
||||||
|
pub(crate) type ReadFuture =
|
||||||
|
Pin<Box<dyn Future<Output = Result<CatalogFingerprint, ReadError>> + Send>>;
|
||||||
|
/// A source of committed-catalog reads. One call per tick.
|
||||||
|
pub(crate) type Reader = Box<dyn FnMut() -> ReadFuture + Send>;
|
||||||
|
|
||||||
|
/// Start the stream-local watcher and return the bounded frame queue of the response stream.
|
||||||
|
///
|
||||||
|
/// The first read is the baseline taken **before** the acknowledgment is written; it is never reset
|
||||||
|
/// afterwards, so a publication between the baseline and the acknowledgment is still delivered.
|
||||||
|
pub(crate) fn spawn(state: Arc<AppState>, watch: Watch) -> mpsc::Receiver<String> {
|
||||||
|
let scope = (watch.workspace_slug.clone(), watch.agent_slug.clone());
|
||||||
|
let reader: Reader = Box::new(move || {
|
||||||
|
let state = Arc::clone(&state);
|
||||||
|
let scope = scope.clone();
|
||||||
|
Box::pin(async move { read(&state, &scope).await })
|
||||||
|
});
|
||||||
|
let (sender, receiver) = mpsc::channel(SIGNAL_QUEUE_CAPACITY);
|
||||||
|
tokio::spawn(run(watch, sender, reader));
|
||||||
|
receiver
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn run(watch: Watch, sender: mpsc::Sender<String>, mut read: Reader) {
|
||||||
|
let mut baseline = match read().await {
|
||||||
|
Ok(fingerprint) => Some(fingerprint),
|
||||||
|
Err(ReadError::Gone) => return,
|
||||||
|
Err(ReadError::Retry) => {
|
||||||
|
observe_failure();
|
||||||
|
None
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
loop {
|
||||||
|
if !still_owned(&watch) || sender.is_closed() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if watch
|
||||||
|
.deadline
|
||||||
|
.is_some_and(|deadline| Instant::now() >= deadline)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
tokio::time::sleep(POLL_INTERVAL).await;
|
||||||
|
if !still_owned(&watch) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
match read().await {
|
||||||
|
Ok(fingerprint) => {
|
||||||
|
if let Some(previous) = baseline.as_ref() {
|
||||||
|
let changes = fingerprint.changes_since(previous).intersect(watch.signals);
|
||||||
|
for frame in watch.wire.signal_frames(changes) {
|
||||||
|
// A slow reader coalesces: the newest frame is dropped instead of blocking
|
||||||
|
// the producer or growing a queue, and the client recovers through the
|
||||||
|
// authoritative list methods.
|
||||||
|
let _ = sender.try_send(frame);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
baseline = Some(fingerprint);
|
||||||
|
}
|
||||||
|
// The Agent is no longer published: fail closed by ending the stream instead of serving a
|
||||||
|
// catalog nobody may read any more.
|
||||||
|
Err(ReadError::Gone) => return,
|
||||||
|
// The committed catalog is untouched: the failure is observable and this tick is skipped.
|
||||||
|
Err(_) => observe_failure(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) enum ReadError {
|
||||||
|
/// The published Agent behind this stream is gone: the producer ends.
|
||||||
|
Gone,
|
||||||
|
/// The catalog could not be read this tick: skip it, keep the committed state.
|
||||||
|
Retry,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn still_owned(watch: &Watch) -> bool {
|
||||||
|
match &watch.legacy_stream {
|
||||||
|
Some((registry, session_id, generation)) => registry.is_current(session_id, *generation),
|
||||||
|
None => true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn read(state: &AppState, scope: &(String, String)) -> Result<CatalogFingerprint, ReadError> {
|
||||||
|
let catalog = tokio::time::timeout(READ_TIMEOUT, state.catalog.get_catalog(&scope.0, &scope.1))
|
||||||
|
.await
|
||||||
|
.map_err(|_| ReadError::Retry)?
|
||||||
|
.map_err(|error| match error {
|
||||||
|
crank_registry::RegistryError::PublishedAgentNotFound { .. } => ReadError::Gone,
|
||||||
|
_ => ReadError::Retry,
|
||||||
|
})?;
|
||||||
|
Ok(CatalogFingerprint::of(&catalog))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One safe, closed-vocabulary observation of a skipped tick: no URI, Agent name, credential or raw
|
||||||
|
/// error text is read here.
|
||||||
|
fn observe_failure() {
|
||||||
|
warn!(
|
||||||
|
name: "mcp.signals.read_failed",
|
||||||
|
error_category = "catalog",
|
||||||
|
"catalog change signal read failed"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The bounded SSE body of one signal stream: the leading frames (acknowledgment), then the queue,
|
||||||
|
/// ending when the producer ends. The caller's stream permit lives in `guard` and is released when
|
||||||
|
/// the response stream is dropped.
|
||||||
|
pub(crate) fn frames_stream<G: Send + 'static>(
|
||||||
|
first: Vec<String>,
|
||||||
|
receiver: mpsc::Receiver<String>,
|
||||||
|
guard: G,
|
||||||
|
) -> impl stream::Stream<Item = Result<Event, std::convert::Infallible>> {
|
||||||
|
let pending: VecDeque<String> = first.into();
|
||||||
|
stream::unfold(
|
||||||
|
(pending, receiver, guard),
|
||||||
|
|(mut pending, mut receiver, guard)| async move {
|
||||||
|
loop {
|
||||||
|
if let Some(frame) = pending.pop_front() {
|
||||||
|
return Some((Ok(Event::default().data(frame)), (pending, receiver, guard)));
|
||||||
|
}
|
||||||
|
let frame = receiver.recv().await?;
|
||||||
|
pending.push_back(frame);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
#[path = "signals_tests.rs"]
|
||||||
|
mod tests;
|
||||||
@@ -0,0 +1,740 @@
|
|||||||
|
//! Unit oracles of the Story 3.19 signal seam: the catalog projection, the bounded filter, the exact
|
||||||
|
//! wire frames of both approved revisions and the bounded legacy stream ownership.
|
||||||
|
|
||||||
|
use std::{
|
||||||
|
collections::BTreeMap,
|
||||||
|
io,
|
||||||
|
sync::{Arc, Mutex},
|
||||||
|
time::{Duration, Instant},
|
||||||
|
};
|
||||||
|
|
||||||
|
use crank_core::ids::{PromptId, ResourceId};
|
||||||
|
use crank_core::{
|
||||||
|
ExecutionConfig, HttpMethod, Operation, OperationId, OperationSecurityLevel, OperationStatus,
|
||||||
|
Protocol, RestTarget, Target, ToolAccessMode, ToolDescription, ToolGroup, ToolSearchSettings,
|
||||||
|
ToolSelectionPolicy, WorkspaceId,
|
||||||
|
};
|
||||||
|
use crank_mapping::MappingSet;
|
||||||
|
use crank_registry::PublishedAgentCatalog;
|
||||||
|
use crank_registry::model::{AgentPromptBinding, AgentResourceBinding, PublishedAgentTool};
|
||||||
|
use crank_schema::{Schema, SchemaKind};
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
use time::OffsetDateTime;
|
||||||
|
use tokio::sync::mpsc;
|
||||||
|
|
||||||
|
use super::{
|
||||||
|
CatalogFingerprint, FilterOutcome, INVALID_LISTEN_FILTER, ListenFilter, MAX_FILTER_URIS,
|
||||||
|
MAX_SUBSCRIPTION_ID_BYTES, PROMPT_LIST_CHANGED, RESOURCE_LIST_CHANGED, ReadError, Reader,
|
||||||
|
SIGNAL_QUEUE_CAPACITY, SUBSCRIPTION_ID_KEY, SUBSCRIPTIONS_ACKNOWLEDGED, Signals,
|
||||||
|
StreamRegistry, TOOL_LIST_CHANGED, Watch, Wire, acknowledged_frame, run, subscription_id,
|
||||||
|
};
|
||||||
|
|
||||||
|
fn catalog(
|
||||||
|
resources: &[(&str, u32)],
|
||||||
|
prompts: &[(&str, u32)],
|
||||||
|
catalog_revision: &str,
|
||||||
|
) -> PublishedAgentCatalog {
|
||||||
|
catalog_with(
|
||||||
|
ToolSelectionPolicy::default(),
|
||||||
|
Vec::new(),
|
||||||
|
resources,
|
||||||
|
prompts,
|
||||||
|
catalog_revision,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn catalog_with(
|
||||||
|
tool_selection_policy: ToolSelectionPolicy,
|
||||||
|
tools: Vec<PublishedAgentTool>,
|
||||||
|
resources: &[(&str, u32)],
|
||||||
|
prompts: &[(&str, u32)],
|
||||||
|
catalog_revision: &str,
|
||||||
|
) -> PublishedAgentCatalog {
|
||||||
|
PublishedAgentCatalog {
|
||||||
|
agent_version: 1,
|
||||||
|
catalog_revision: catalog_revision.to_owned(),
|
||||||
|
tool_selection_policy,
|
||||||
|
tools,
|
||||||
|
resources: resources
|
||||||
|
.iter()
|
||||||
|
.map(|(id, version)| AgentResourceBinding {
|
||||||
|
resource_id: ResourceId::new(*id),
|
||||||
|
resource_version: *version,
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
prompts: prompts
|
||||||
|
.iter()
|
||||||
|
.map(|(id, version)| AgentPromptBinding {
|
||||||
|
prompt_id: PromptId::new(*id),
|
||||||
|
prompt_version: *version,
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn search_policy(tool_names: &[&str]) -> ToolSelectionPolicy {
|
||||||
|
ToolSelectionPolicy {
|
||||||
|
mode: ToolAccessMode::Search,
|
||||||
|
groups: vec![ToolGroup {
|
||||||
|
id: "crm".to_owned(),
|
||||||
|
name: "CRM".to_owned(),
|
||||||
|
description: "CRM operations".to_owned(),
|
||||||
|
tool_names: tool_names.iter().map(|name| (*name).to_owned()).collect(),
|
||||||
|
}],
|
||||||
|
search: ToolSearchSettings::default(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn empty_object_schema() -> Schema {
|
||||||
|
Schema {
|
||||||
|
kind: SchemaKind::Object,
|
||||||
|
format: None,
|
||||||
|
description: None,
|
||||||
|
required: false,
|
||||||
|
nullable: false,
|
||||||
|
default_value: None,
|
||||||
|
fields: BTreeMap::new(),
|
||||||
|
items: None,
|
||||||
|
enum_values: Vec::new(),
|
||||||
|
variants: Vec::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One published Tool binding whose served definition is exactly `title`/`description`.
|
||||||
|
fn published_tool(name: &str, title: &str, description: &str, version: u32) -> PublishedAgentTool {
|
||||||
|
PublishedAgentTool {
|
||||||
|
workspace_id: WorkspaceId::new("ws_test"),
|
||||||
|
workspace_slug: "ws-test".to_owned(),
|
||||||
|
agent_id: "agent_test".into(),
|
||||||
|
agent_slug: "agent".to_owned(),
|
||||||
|
operation: Operation {
|
||||||
|
id: OperationId::new(format!("op_{name}")),
|
||||||
|
name: name.to_owned(),
|
||||||
|
display_name: title.to_owned(),
|
||||||
|
category: "test".to_owned(),
|
||||||
|
protocol: Protocol::Rest,
|
||||||
|
security_level: OperationSecurityLevel::Standard,
|
||||||
|
status: OperationStatus::Published,
|
||||||
|
version,
|
||||||
|
target: Target::Rest(RestTarget {
|
||||||
|
base_url: "https://example.test".to_owned(),
|
||||||
|
method: HttpMethod::Get,
|
||||||
|
path_template: "/leads".to_owned(),
|
||||||
|
static_headers: BTreeMap::new(),
|
||||||
|
request_contract: None,
|
||||||
|
response_contract: Vec::new(),
|
||||||
|
multipart_field_mime_types: BTreeMap::new(),
|
||||||
|
}),
|
||||||
|
input_schema: empty_object_schema(),
|
||||||
|
output_schema: empty_object_schema(),
|
||||||
|
input_mapping: MappingSet { rules: Vec::new() },
|
||||||
|
output_mapping: MappingSet { rules: Vec::new() },
|
||||||
|
execution_config: ExecutionConfig {
|
||||||
|
timeout_ms: 10_000,
|
||||||
|
retry_policy: None,
|
||||||
|
response_cache: None,
|
||||||
|
idempotency: None,
|
||||||
|
safety: None,
|
||||||
|
approval_policy: None,
|
||||||
|
auth_profile_ref: None,
|
||||||
|
headers: BTreeMap::new(),
|
||||||
|
},
|
||||||
|
tool_description: ToolDescription {
|
||||||
|
title: title.to_owned(),
|
||||||
|
description: description.to_owned(),
|
||||||
|
tags: Vec::new(),
|
||||||
|
examples: Vec::new(),
|
||||||
|
},
|
||||||
|
samples: None,
|
||||||
|
generated_draft: None,
|
||||||
|
config_export: None,
|
||||||
|
wizard_state: None,
|
||||||
|
created_at: OffsetDateTime::UNIX_EPOCH,
|
||||||
|
updated_at: OffsetDateTime::UNIX_EPOCH,
|
||||||
|
published_at: None,
|
||||||
|
},
|
||||||
|
tool_name: name.to_owned(),
|
||||||
|
tool_title: title.to_owned(),
|
||||||
|
tool_description: description.to_owned(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_committed_resource_binding_is_a_resource_change_only() {
|
||||||
|
let before = CatalogFingerprint::of(&catalog(&[("res_a", 1)], &[("prm_a", 1)], "rev-1"));
|
||||||
|
let after = CatalogFingerprint::of(&catalog(
|
||||||
|
&[("res_a", 1), ("res_b", 1)],
|
||||||
|
&[("prm_a", 1)],
|
||||||
|
"rev-2",
|
||||||
|
));
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
after.changes_since(&before),
|
||||||
|
Signals {
|
||||||
|
resources: true,
|
||||||
|
prompts: false,
|
||||||
|
tools: false
|
||||||
|
}
|
||||||
|
);
|
||||||
|
assert!(!before.changes_since(&after).prompts);
|
||||||
|
assert_eq!(
|
||||||
|
before.changes_since(&after),
|
||||||
|
Signals {
|
||||||
|
resources: true,
|
||||||
|
prompts: false,
|
||||||
|
tools: false
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_committed_prompt_binding_is_a_prompt_change_only() {
|
||||||
|
let before = CatalogFingerprint::of(&catalog(&[], &[("prm_a", 1)], "rev-1"));
|
||||||
|
let after = CatalogFingerprint::of(&catalog(&[], &[("prm_a", 1), ("prm_b", 2)], "rev-2"));
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
after.changes_since(&before),
|
||||||
|
Signals {
|
||||||
|
resources: false,
|
||||||
|
prompts: true,
|
||||||
|
tools: false
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_pinned_version_bump_is_a_change_even_when_the_binding_names_are_stable() {
|
||||||
|
let before = CatalogFingerprint::of(&catalog(&[("res_a", 1)], &[("prm_a", 1)], "rev-1"));
|
||||||
|
let after = CatalogFingerprint::of(&catalog(&[("res_a", 2)], &[("prm_a", 1)], "rev-1"));
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
after.changes_since(&before),
|
||||||
|
Signals {
|
||||||
|
resources: true,
|
||||||
|
prompts: false,
|
||||||
|
tools: false
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_committed_tool_definition_change_is_a_tool_change_only() {
|
||||||
|
let lead = || published_tool("crm_create_lead", "Create Lead", "Creates a lead", 1);
|
||||||
|
let before = CatalogFingerprint::of(&catalog_with(
|
||||||
|
ToolSelectionPolicy::default(),
|
||||||
|
vec![lead()],
|
||||||
|
&[("res_a", 1)],
|
||||||
|
&[("prm_a", 1)],
|
||||||
|
"rev-1",
|
||||||
|
));
|
||||||
|
let added = CatalogFingerprint::of(&catalog_with(
|
||||||
|
ToolSelectionPolicy::default(),
|
||||||
|
vec![
|
||||||
|
lead(),
|
||||||
|
published_tool(
|
||||||
|
"crm_create_second",
|
||||||
|
"Create Second",
|
||||||
|
"Creates a second lead",
|
||||||
|
1,
|
||||||
|
),
|
||||||
|
],
|
||||||
|
&[("res_a", 1)],
|
||||||
|
&[("prm_a", 1)],
|
||||||
|
"rev-2",
|
||||||
|
));
|
||||||
|
let retitled = CatalogFingerprint::of(&catalog_with(
|
||||||
|
ToolSelectionPolicy::default(),
|
||||||
|
vec![published_tool(
|
||||||
|
"crm_create_lead",
|
||||||
|
"Create a lead",
|
||||||
|
"Creates a lead",
|
||||||
|
1,
|
||||||
|
)],
|
||||||
|
&[("res_a", 1)],
|
||||||
|
&[("prm_a", 1)],
|
||||||
|
"rev-2",
|
||||||
|
));
|
||||||
|
|
||||||
|
let tools_only = Signals {
|
||||||
|
resources: false,
|
||||||
|
prompts: false,
|
||||||
|
tools: true,
|
||||||
|
};
|
||||||
|
assert_eq!(added.changes_since(&before), tools_only);
|
||||||
|
assert_eq!(
|
||||||
|
retitled.changes_since(&before),
|
||||||
|
tools_only,
|
||||||
|
"a retitled binding changes the visible Tool projection without a new Operation version"
|
||||||
|
);
|
||||||
|
// The reverse direction is a Tool change as well: a removed binding is a real change.
|
||||||
|
assert!(before.changes_since(&added).tools);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_republished_operation_version_with_an_identical_definition_is_silent() {
|
||||||
|
// `tools/list` serves the definition, not the Operation version: a version bump that leaves the
|
||||||
|
// served definition unchanged is not a client-visible Tool catalog change.
|
||||||
|
let before = CatalogFingerprint::of(&catalog_with(
|
||||||
|
ToolSelectionPolicy::default(),
|
||||||
|
vec![published_tool(
|
||||||
|
"crm_create_lead",
|
||||||
|
"Create Lead",
|
||||||
|
"Creates a lead",
|
||||||
|
1,
|
||||||
|
)],
|
||||||
|
&[("res_a", 1)],
|
||||||
|
&[("prm_a", 1)],
|
||||||
|
"rev-1",
|
||||||
|
));
|
||||||
|
let after = CatalogFingerprint::of(&catalog_with(
|
||||||
|
ToolSelectionPolicy::default(),
|
||||||
|
vec![published_tool(
|
||||||
|
"crm_create_lead",
|
||||||
|
"Create Lead",
|
||||||
|
"Creates a lead",
|
||||||
|
2,
|
||||||
|
)],
|
||||||
|
&[("res_a", 1)],
|
||||||
|
&[("prm_a", 1)],
|
||||||
|
"rev-2",
|
||||||
|
));
|
||||||
|
|
||||||
|
assert!(!after.changes_since(&before).any());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_policy_only_commit_that_changes_tools_list_is_a_tool_change_only() {
|
||||||
|
// The Tool selection policy is part of the served `tools/list` projection: switching the same
|
||||||
|
// bindings from direct to search mode replaces the served tools with `search_tools`/`call_tool`.
|
||||||
|
let tool = published_tool("crm_create_lead", "Create Lead", "Creates a lead", 1);
|
||||||
|
let direct = CatalogFingerprint::of(&catalog_with(
|
||||||
|
ToolSelectionPolicy::default(),
|
||||||
|
vec![tool.clone()],
|
||||||
|
&[("res_a", 1)],
|
||||||
|
&[("prm_a", 1)],
|
||||||
|
"rev-1",
|
||||||
|
));
|
||||||
|
let search = CatalogFingerprint::of(&catalog_with(
|
||||||
|
search_policy(&["crm_create_lead"]),
|
||||||
|
vec![tool],
|
||||||
|
&[("res_a", 1)],
|
||||||
|
&[("prm_a", 1)],
|
||||||
|
"rev-2",
|
||||||
|
));
|
||||||
|
|
||||||
|
let tools_only = Signals {
|
||||||
|
resources: false,
|
||||||
|
prompts: false,
|
||||||
|
tools: true,
|
||||||
|
};
|
||||||
|
assert_eq!(search.changes_since(&direct), tools_only);
|
||||||
|
assert_eq!(direct.changes_since(&search), tools_only);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_policy_field_invisible_to_tools_list_is_silent() {
|
||||||
|
// `search.max_results` is only served inside the search-mode definitions: in direct mode it
|
||||||
|
// changes nothing the client receives.
|
||||||
|
let tool = || published_tool("crm_create_lead", "Create Lead", "Creates a lead", 1);
|
||||||
|
let before = CatalogFingerprint::of(&catalog_with(
|
||||||
|
ToolSelectionPolicy::default(),
|
||||||
|
vec![tool()],
|
||||||
|
&[],
|
||||||
|
&[],
|
||||||
|
"rev-1",
|
||||||
|
));
|
||||||
|
let after = CatalogFingerprint::of(&catalog_with(
|
||||||
|
ToolSelectionPolicy {
|
||||||
|
search: ToolSearchSettings { max_results: 5 },
|
||||||
|
..ToolSelectionPolicy::default()
|
||||||
|
},
|
||||||
|
vec![tool()],
|
||||||
|
&[],
|
||||||
|
&[],
|
||||||
|
"rev-2",
|
||||||
|
));
|
||||||
|
|
||||||
|
assert!(!after.changes_since(&before).any());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_search_mode_binding_change_is_silent_when_tools_list_is_unchanged() {
|
||||||
|
// In search mode the served list is `search_tools`/`call_tool`; the bindings behind it are not
|
||||||
|
// part of `tools/list`, so a binding-only commit must not claim a visible Tool change.
|
||||||
|
let policy = search_policy(&["crm_create_lead"]);
|
||||||
|
let before = CatalogFingerprint::of(&catalog_with(
|
||||||
|
policy.clone(),
|
||||||
|
vec![published_tool(
|
||||||
|
"crm_create_lead",
|
||||||
|
"Create Lead",
|
||||||
|
"Creates a lead",
|
||||||
|
1,
|
||||||
|
)],
|
||||||
|
&[],
|
||||||
|
&[],
|
||||||
|
"rev-1",
|
||||||
|
));
|
||||||
|
let after = CatalogFingerprint::of(&catalog_with(
|
||||||
|
policy,
|
||||||
|
vec![
|
||||||
|
published_tool("crm_create_lead", "Create Lead", "Creates a lead", 1),
|
||||||
|
published_tool(
|
||||||
|
"crm_create_second",
|
||||||
|
"Create Second",
|
||||||
|
"Creates a second lead",
|
||||||
|
1,
|
||||||
|
),
|
||||||
|
],
|
||||||
|
&[],
|
||||||
|
&[],
|
||||||
|
"rev-2",
|
||||||
|
));
|
||||||
|
|
||||||
|
assert!(!after.changes_since(&before).any());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_resource_or_prompt_change_is_not_a_tool_change() {
|
||||||
|
let tool = || published_tool("crm_create_lead", "Create Lead", "Creates a lead", 1);
|
||||||
|
let before = CatalogFingerprint::of(&catalog_with(
|
||||||
|
ToolSelectionPolicy::default(),
|
||||||
|
vec![tool()],
|
||||||
|
&[("res_a", 1)],
|
||||||
|
&[("prm_a", 1)],
|
||||||
|
"rev-1",
|
||||||
|
));
|
||||||
|
let changed = CatalogFingerprint::of(&catalog_with(
|
||||||
|
ToolSelectionPolicy::default(),
|
||||||
|
vec![tool()],
|
||||||
|
&[("res_a", 2)],
|
||||||
|
&[("prm_a", 1), ("prm_b", 1)],
|
||||||
|
"rev-1",
|
||||||
|
));
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
changed.changes_since(&before),
|
||||||
|
Signals {
|
||||||
|
resources: true,
|
||||||
|
prompts: true,
|
||||||
|
tools: false
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_catalog_revision_bump_without_a_visible_change_is_silent() {
|
||||||
|
// `catalog_revision` moved, but no visible Resource/Prompt/Tool projection did: no signal.
|
||||||
|
let before = CatalogFingerprint::of(&catalog(&[("res_a", 1)], &[("prm_a", 1)], "rev-1"));
|
||||||
|
let after = CatalogFingerprint::of(&catalog(&[("res_a", 1)], &[("prm_a", 1)], "rev-2"));
|
||||||
|
|
||||||
|
assert!(!after.changes_since(&before).any());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_projection_is_order_independent_and_has_no_duplicate_growth() {
|
||||||
|
let forward = CatalogFingerprint::of(&catalog(
|
||||||
|
&[("res_a", 1), ("res_b", 2)],
|
||||||
|
&[("prm_a", 1), ("prm_b", 2)],
|
||||||
|
"rev-1",
|
||||||
|
));
|
||||||
|
let reversed = CatalogFingerprint::of(&catalog(
|
||||||
|
&[("res_b", 2), ("res_a", 1)],
|
||||||
|
&[("prm_b", 2), ("prm_a", 1)],
|
||||||
|
"rev-1",
|
||||||
|
));
|
||||||
|
|
||||||
|
assert!(!reversed.changes_since(&forward).any());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_legacy_frames_carry_a_closed_method_name_and_no_parameters() {
|
||||||
|
let frames = Wire::Legacy.signal_frames(Signals::ALL);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
frames,
|
||||||
|
vec![
|
||||||
|
json!({"jsonrpc": "2.0", "method": RESOURCE_LIST_CHANGED}).to_string(),
|
||||||
|
json!({"jsonrpc": "2.0", "method": PROMPT_LIST_CHANGED}).to_string(),
|
||||||
|
json!({"jsonrpc": "2.0", "method": TOOL_LIST_CHANGED}).to_string(),
|
||||||
|
]
|
||||||
|
);
|
||||||
|
// No URI, name or payload of a changed object is part of a list-change notification.
|
||||||
|
assert!(frames.iter().all(|frame| !frame.contains("uri")));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_modern_frames_carry_the_subscription_id_of_their_listen_request() {
|
||||||
|
let id = json!(41);
|
||||||
|
let frames = Wire::Modern(id.clone()).signal_frames(Signals::ALL);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
frames,
|
||||||
|
vec![
|
||||||
|
json!({
|
||||||
|
"jsonrpc": "2.0",
|
||||||
|
"method": RESOURCE_LIST_CHANGED,
|
||||||
|
"params": { "_meta": { SUBSCRIPTION_ID_KEY: 41 } }
|
||||||
|
})
|
||||||
|
.to_string(),
|
||||||
|
json!({
|
||||||
|
"jsonrpc": "2.0",
|
||||||
|
"method": PROMPT_LIST_CHANGED,
|
||||||
|
"params": { "_meta": { SUBSCRIPTION_ID_KEY: 41 } }
|
||||||
|
})
|
||||||
|
.to_string(),
|
||||||
|
json!({
|
||||||
|
"jsonrpc": "2.0",
|
||||||
|
"method": TOOL_LIST_CHANGED,
|
||||||
|
"params": { "_meta": { SUBSCRIPTION_ID_KEY: 41 } }
|
||||||
|
})
|
||||||
|
.to_string(),
|
||||||
|
]
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
serde_json::from_str::<Value>(&frames[0]).unwrap()["params"]["_meta"][SUBSCRIPTION_ID_KEY],
|
||||||
|
id
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn only_the_requested_and_honoured_types_are_encoded() {
|
||||||
|
let frames = Wire::Modern(json!(1)).signal_frames(Signals {
|
||||||
|
resources: false,
|
||||||
|
prompts: true,
|
||||||
|
tools: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
assert_eq!(frames.len(), 1);
|
||||||
|
assert!(frames[0].contains(PROMPT_LIST_CHANGED));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_acknowledgment_reports_exactly_the_honoured_subset() {
|
||||||
|
let frame: Value = serde_json::from_str(&acknowledged_frame(
|
||||||
|
&json!(7),
|
||||||
|
Signals {
|
||||||
|
resources: true,
|
||||||
|
prompts: false,
|
||||||
|
tools: true,
|
||||||
|
},
|
||||||
|
))
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
assert_eq!(frame["method"], SUBSCRIPTIONS_ACKNOWLEDGED);
|
||||||
|
assert_eq!(frame["params"]["_meta"][SUBSCRIPTION_ID_KEY], json!(7));
|
||||||
|
assert_eq!(
|
||||||
|
frame["params"]["notifications"],
|
||||||
|
json!({ "resourcesListChanged": true, "toolsListChanged": true })
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_empty_honoured_subset_is_an_empty_filter_object() {
|
||||||
|
let frame: Value =
|
||||||
|
serde_json::from_str(&acknowledged_frame(&json!("sub-1"), Signals::default())).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(frame["params"]["notifications"], json!({}));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_filter_keeps_only_the_implemented_list_change_types() {
|
||||||
|
let filter: ListenFilter = serde_json::from_value(json!({
|
||||||
|
"toolsListChanged": true,
|
||||||
|
"promptsListChanged": true,
|
||||||
|
"resourcesListChanged": false,
|
||||||
|
"resourceSubscriptions": ["file:///project/config.json"]
|
||||||
|
}))
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
match filter.accepted() {
|
||||||
|
FilterOutcome::Accepted(signals) => assert_eq!(
|
||||||
|
signals,
|
||||||
|
Signals {
|
||||||
|
resources: false,
|
||||||
|
prompts: true,
|
||||||
|
tools: true
|
||||||
|
},
|
||||||
|
"the honoured set is the requested list-change subset: {signals:?}"
|
||||||
|
),
|
||||||
|
FilterOutcome::Invalid(detail) => panic!("a bounded filter must be accepted: {detail}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_absent_filter_field_means_not_subscribed() {
|
||||||
|
let filter: ListenFilter = serde_json::from_value(json!({})).unwrap();
|
||||||
|
|
||||||
|
match filter.accepted() {
|
||||||
|
FilterOutcome::Accepted(signals) => assert!(!signals.any()),
|
||||||
|
FilterOutcome::Invalid(detail) => panic!("an empty filter must be accepted: {detail}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_oversized_uri_filter_is_refused_without_echoing_it() {
|
||||||
|
let filter: ListenFilter = serde_json::from_value(json!({
|
||||||
|
"resourceSubscriptions": (0..=MAX_FILTER_URIS)
|
||||||
|
.map(|index| format!("file:///resource-{index}"))
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
}))
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
match filter.accepted() {
|
||||||
|
FilterOutcome::Invalid(detail) => assert_eq!(detail, INVALID_LISTEN_FILTER),
|
||||||
|
FilterOutcome::Accepted(_) => panic!("an oversized filter must be refused"),
|
||||||
|
}
|
||||||
|
|
||||||
|
let oversized: ListenFilter = serde_json::from_value(json!({
|
||||||
|
"resourceSubscriptions": ["u".repeat(super::MAX_FILTER_URI_BYTES + 1)]
|
||||||
|
}))
|
||||||
|
.unwrap();
|
||||||
|
assert!(matches!(
|
||||||
|
oversized.accepted(),
|
||||||
|
FilterOutcome::Invalid(INVALID_LISTEN_FILTER)
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_non_object_filter_is_a_deserialization_error() {
|
||||||
|
assert!(serde_json::from_value::<ListenFilter>(json!(["toolsListChanged"])).is_err());
|
||||||
|
assert!(serde_json::from_value::<ListenFilter>(json!({"promptsListChanged": "yes"})).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_subscription_id_is_bound_by_its_encoded_size() {
|
||||||
|
assert_eq!(subscription_id(&json!(1)), Some(json!(1)));
|
||||||
|
assert_eq!(subscription_id(&json!("sub-1")), Some(json!("sub-1")));
|
||||||
|
assert_eq!(
|
||||||
|
subscription_id(&json!("x".repeat(MAX_SUBSCRIPTION_ID_BYTES))),
|
||||||
|
None,
|
||||||
|
"an id longer than the frame bound must not be used as a subscription id"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_newer_legacy_stream_supersedes_the_previous_one() {
|
||||||
|
let streams = StreamRegistry::new();
|
||||||
|
let first = streams.admit("session-1").unwrap();
|
||||||
|
let second = streams.admit("session-1").unwrap();
|
||||||
|
|
||||||
|
assert!(!streams.is_current("session-1", first));
|
||||||
|
assert!(streams.is_current("session-1", second));
|
||||||
|
// Another session is unaffected.
|
||||||
|
let other = streams.admit("session-2").unwrap();
|
||||||
|
assert!(streams.is_current("session-2", other));
|
||||||
|
|
||||||
|
streams.retire("session-1");
|
||||||
|
assert!(!streams.is_current("session-1", second));
|
||||||
|
assert!(streams.is_current("session-2", other));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Default)]
|
||||||
|
struct SharedLogWriter {
|
||||||
|
buffer: Arc<Mutex<Vec<u8>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SharedLogWriter {
|
||||||
|
fn output(&self) -> String {
|
||||||
|
String::from_utf8(self.buffer.lock().unwrap().clone()).unwrap()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for SharedLogWriter {
|
||||||
|
type Writer = SharedLogGuard;
|
||||||
|
|
||||||
|
fn make_writer(&'a self) -> Self::Writer {
|
||||||
|
SharedLogGuard {
|
||||||
|
buffer: Arc::clone(&self.buffer),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct SharedLogGuard {
|
||||||
|
buffer: Arc<Mutex<Vec<u8>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl io::Write for SharedLogGuard {
|
||||||
|
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
|
||||||
|
self.buffer.lock().unwrap().extend_from_slice(bytes);
|
||||||
|
Ok(bytes.len())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn flush(&mut self) -> io::Result<()> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// AC-2: a failed committed-catalog read is observable and loses nothing — the tick is skipped (no
|
||||||
|
/// fabricated signal, no write path that could roll the catalog back) while the baseline survives, so
|
||||||
|
/// the next successful read still reports the change of the committed catalog.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_failed_catalog_read_is_observable_and_loses_no_committed_change() {
|
||||||
|
let writer = SharedLogWriter::default();
|
||||||
|
let subscriber = crank_observability::build_subscriber(
|
||||||
|
crank_observability::ObservabilityConfig::new(
|
||||||
|
crank_observability::ServiceIdentity::try_new("mcp-server", "test", "test").unwrap(),
|
||||||
|
"info",
|
||||||
|
crank_observability::RedactionLimits::default(),
|
||||||
|
),
|
||||||
|
writer.clone(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let dispatch = tracing::Dispatch::new(subscriber);
|
||||||
|
let _guard = tracing::dispatcher::set_default(&dispatch);
|
||||||
|
|
||||||
|
let baseline = CatalogFingerprint::of(&catalog(&[], &[("prm_a", 1)], "rev-1"));
|
||||||
|
let committed = CatalogFingerprint::of(&catalog(&[], &[("prm_a", 1), ("prm_b", 1)], "rev-2"));
|
||||||
|
let script = Arc::new(Mutex::new(
|
||||||
|
vec![Ok(baseline), Err(ReadError::Retry), Ok(committed)].into_iter(),
|
||||||
|
));
|
||||||
|
let reader: Reader = Box::new(move || {
|
||||||
|
let next = script
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
|
.next()
|
||||||
|
.unwrap_or(Err(ReadError::Retry));
|
||||||
|
Box::pin(async move { next })
|
||||||
|
});
|
||||||
|
|
||||||
|
let (sender, mut receiver) = mpsc::channel(SIGNAL_QUEUE_CAPACITY);
|
||||||
|
tokio::spawn(run(
|
||||||
|
Watch {
|
||||||
|
workspace_slug: "workspace-canary".to_owned(),
|
||||||
|
agent_slug: "agent-canary".to_owned(),
|
||||||
|
signals: Signals::ALL,
|
||||||
|
wire: Wire::Legacy,
|
||||||
|
legacy_stream: None,
|
||||||
|
deadline: Some(Instant::now() + Duration::from_millis(2_100)),
|
||||||
|
},
|
||||||
|
sender,
|
||||||
|
reader,
|
||||||
|
));
|
||||||
|
|
||||||
|
let mut frames = Vec::new();
|
||||||
|
while let Some(frame) = receiver.recv().await {
|
||||||
|
frames.push(frame);
|
||||||
|
}
|
||||||
|
|
||||||
|
// The failed tick produced no frame; the committed change of the next successful read did.
|
||||||
|
assert_eq!(
|
||||||
|
frames,
|
||||||
|
vec![json!({"jsonrpc": "2.0", "method": PROMPT_LIST_CHANGED}).to_string()]
|
||||||
|
);
|
||||||
|
|
||||||
|
let output = writer.output();
|
||||||
|
let failures: Vec<Value> = output
|
||||||
|
.lines()
|
||||||
|
.filter_map(|line| serde_json::from_str::<Value>(line).ok())
|
||||||
|
.filter(|event| event["event"] == "mcp.signals.read_failed")
|
||||||
|
.collect();
|
||||||
|
assert!(
|
||||||
|
!failures.is_empty(),
|
||||||
|
"a skipped tick must be observable: {output}"
|
||||||
|
);
|
||||||
|
for event in &failures {
|
||||||
|
assert_eq!(event["fields"]["error_category"], "catalog");
|
||||||
|
}
|
||||||
|
// Closed vocabulary: no workspace, Agent, URI or raw database text is read into the event.
|
||||||
|
assert!(!output.contains("workspace-canary"));
|
||||||
|
assert!(!output.contains("agent-canary"));
|
||||||
|
}
|
||||||
@@ -313,12 +313,15 @@ pub(super) fn transport_response(
|
|||||||
/// Record the closed safe event of one response: served, rejected as invalid, failed, or a tool-level
|
/// Record the closed safe event of one response: served, rejected as invalid, failed, or a tool-level
|
||||||
/// error. Every label is a fixed string of the closed vocabulary; nothing from the payload or the
|
/// error. Every label is a fixed string of the closed vocabulary; nothing from the payload or the
|
||||||
/// request is copied into it.
|
/// request is copied into it.
|
||||||
fn note_logging_outcome(payload: &Value) {
|
pub(super) fn note_logging_outcome(payload: &Value) {
|
||||||
use crate::protocol::{EVENT_FAILED, EVENT_REJECTED, EVENT_SERVED, LogLevel, note};
|
use crate::protocol::{EVENT_FAILED, EVENT_REJECTED, EVENT_SERVED, LogLevel, note};
|
||||||
if payload.get("error").is_some() {
|
if payload.get("error").is_some() {
|
||||||
match payload.pointer("/error/code").and_then(Value::as_i64) {
|
match payload.pointer("/error/code").and_then(Value::as_i64) {
|
||||||
// The pinned client-error codes of a malformed request.
|
// The pinned client-error codes: a malformed request, a method that this era does not
|
||||||
Some(-32600 | -32602) => note(LogLevel::Warning, EVENT_REJECTED, "invalid_params"),
|
// implement, and invalid params. The client can correct all three, so they are a
|
||||||
|
// rejection rather than a server failure; the closed label stays the one client-error
|
||||||
|
// label of the vocabulary instead of growing a new one.
|
||||||
|
Some(-32602..=-32600) => note(LogLevel::Warning, EVENT_REJECTED, "invalid_params"),
|
||||||
_ => note(LogLevel::Error, EVENT_FAILED, "internal"),
|
_ => note(LogLevel::Error, EVENT_FAILED, "internal"),
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
{
|
{
|
||||||
"kind": "inventory",
|
"kind": "inventory",
|
||||||
"path": "docs/capability-inventory.json",
|
"path": "docs/capability-inventory.json",
|
||||||
"sha256": "85970569edd1b658a6cea4444c796efabe166a6833787c7e98249f20a1eaf29d"
|
"sha256": "98b1f3a7f3c8e9ca1bc15bef8b73b360fbd47a42acaef2e0dffb149e2f46687d"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"kind": "required_surfaces",
|
"kind": "required_surfaces",
|
||||||
|
|||||||
@@ -932,7 +932,7 @@
|
|||||||
{
|
{
|
||||||
"advertised": {
|
"advertised": {
|
||||||
"prompts": {
|
"prompts": {
|
||||||
"listChanged": false
|
"listChanged": true
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"applicability": "stable",
|
"applicability": "stable",
|
||||||
@@ -941,6 +941,7 @@
|
|||||||
"kind": "capability",
|
"kind": "capability",
|
||||||
"open_subfeatures": false,
|
"open_subfeatures": false,
|
||||||
"owner": "community-release",
|
"owner": "community-release",
|
||||||
|
"reason": "the adapter emits `notifications/prompts/list_changed` from the committed published Prompt bindings of the Agent snapshot since Story 3.19",
|
||||||
"requirement": "FR-17",
|
"requirement": "FR-17",
|
||||||
"revisions": [
|
"revisions": [
|
||||||
"2026-07-28",
|
"2026-07-28",
|
||||||
@@ -956,7 +957,7 @@
|
|||||||
{
|
{
|
||||||
"advertised": {
|
"advertised": {
|
||||||
"resources": {
|
"resources": {
|
||||||
"listChanged": false,
|
"listChanged": true,
|
||||||
"subscribe": false
|
"subscribe": false
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -966,6 +967,7 @@
|
|||||||
"kind": "capability",
|
"kind": "capability",
|
||||||
"open_subfeatures": false,
|
"open_subfeatures": false,
|
||||||
"owner": "community-release",
|
"owner": "community-release",
|
||||||
|
"reason": "the adapter emits `notifications/resources/list_changed` from the committed published Resource bindings of the Agent snapshot since Story 3.19; URI-content subscriptions remain unimplemented",
|
||||||
"requirement": "FR-15",
|
"requirement": "FR-15",
|
||||||
"revisions": [
|
"revisions": [
|
||||||
"2026-07-28",
|
"2026-07-28",
|
||||||
@@ -982,7 +984,7 @@
|
|||||||
{
|
{
|
||||||
"advertised": {
|
"advertised": {
|
||||||
"tools": {
|
"tools": {
|
||||||
"listChanged": false
|
"listChanged": true
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"applicability": "stable",
|
"applicability": "stable",
|
||||||
@@ -991,6 +993,7 @@
|
|||||||
"kind": "capability",
|
"kind": "capability",
|
||||||
"open_subfeatures": false,
|
"open_subfeatures": false,
|
||||||
"owner": "community-release",
|
"owner": "community-release",
|
||||||
|
"reason": "the adapter emits `notifications/tools/list_changed` from the committed published Tool bindings of the Agent snapshot since Story 3.5; `tools/list` stays authoritative for a client that misses the notification",
|
||||||
"requirement": "FR-13",
|
"requirement": "FR-13",
|
||||||
"revisions": [
|
"revisions": [
|
||||||
"2026-07-28",
|
"2026-07-28",
|
||||||
@@ -1438,13 +1441,13 @@
|
|||||||
"kind": "method",
|
"kind": "method",
|
||||||
"open_subfeatures": false,
|
"open_subfeatures": false,
|
||||||
"owner": "community-release",
|
"owner": "community-release",
|
||||||
"reason": "the community scope serves no subscription stream, so the modern listen request is not served",
|
"reason": "served since Story 3.19 (FR-19) as the modern long-lived notification stream; the acknowledged filter carries only the implemented Resource/Prompt list-change types",
|
||||||
"requirement": "FR-13",
|
"requirement": "FR-13",
|
||||||
"revisions": [
|
"revisions": [
|
||||||
"2026-07-28"
|
"2026-07-28"
|
||||||
],
|
],
|
||||||
"role": "client",
|
"role": "client",
|
||||||
"status": "not_applicable",
|
"status": "supported",
|
||||||
"subfeatures": [],
|
"subfeatures": [],
|
||||||
"surface": "subscriptions/listen"
|
"surface": "subscriptions/listen"
|
||||||
},
|
},
|
||||||
@@ -1613,15 +1616,15 @@
|
|||||||
"fallback": "capability not advertised, request not dispatched",
|
"fallback": "capability not advertised, request not dispatched",
|
||||||
"kind": "notification",
|
"kind": "notification",
|
||||||
"open_subfeatures": false,
|
"open_subfeatures": false,
|
||||||
"owner": "story 3.19",
|
"owner": "community-release",
|
||||||
"reason": "Resource and Prompt change signals are owned by story 3.19",
|
"reason": "emitted since Story 3.19 (FR-19) from the committed published Resource bindings of the Agent snapshot; carries no parameters, so no URI, name or content is disclosed",
|
||||||
"requirement": "FR-19",
|
"requirement": "FR-19",
|
||||||
"revisions": [
|
"revisions": [
|
||||||
"2026-07-28",
|
"2026-07-28",
|
||||||
"2025-11-25"
|
"2025-11-25"
|
||||||
],
|
],
|
||||||
"role": "server",
|
"role": "server",
|
||||||
"status": "deferred",
|
"status": "supported",
|
||||||
"subfeatures": [],
|
"subfeatures": [],
|
||||||
"surface": "notifications/resources/list_changed"
|
"surface": "notifications/resources/list_changed"
|
||||||
},
|
},
|
||||||
@@ -1632,15 +1635,15 @@
|
|||||||
"fallback": "capability not advertised, request not dispatched",
|
"fallback": "capability not advertised, request not dispatched",
|
||||||
"kind": "notification",
|
"kind": "notification",
|
||||||
"open_subfeatures": false,
|
"open_subfeatures": false,
|
||||||
"owner": "story 3.19",
|
"owner": "community-release",
|
||||||
"reason": "Resource and Prompt change signals are owned by story 3.19",
|
"reason": "emitted since Story 3.19 (FR-19) from the committed published Prompt bindings of the Agent snapshot; carries no parameters, so no Prompt name or content is disclosed",
|
||||||
"requirement": "FR-19",
|
"requirement": "FR-19",
|
||||||
"revisions": [
|
"revisions": [
|
||||||
"2026-07-28",
|
"2026-07-28",
|
||||||
"2025-11-25"
|
"2025-11-25"
|
||||||
],
|
],
|
||||||
"role": "server",
|
"role": "server",
|
||||||
"status": "deferred",
|
"status": "supported",
|
||||||
"subfeatures": [],
|
"subfeatures": [],
|
||||||
"surface": "notifications/prompts/list_changed"
|
"surface": "notifications/prompts/list_changed"
|
||||||
},
|
},
|
||||||
@@ -1719,13 +1722,13 @@
|
|||||||
"kind": "notification",
|
"kind": "notification",
|
||||||
"open_subfeatures": false,
|
"open_subfeatures": false,
|
||||||
"owner": "community-release",
|
"owner": "community-release",
|
||||||
"reason": "the community scope serves no subscription stream",
|
"reason": "sent since Story 3.19 (FR-19) as the first frame of a `subscriptions/listen` stream, carrying the request id as the subscription id and the honoured filter subset",
|
||||||
"requirement": "FR-13",
|
"requirement": "FR-13",
|
||||||
"revisions": [
|
"revisions": [
|
||||||
"2026-07-28"
|
"2026-07-28"
|
||||||
],
|
],
|
||||||
"role": "server",
|
"role": "server",
|
||||||
"status": "not_applicable",
|
"status": "supported",
|
||||||
"subfeatures": [],
|
"subfeatures": [],
|
||||||
"surface": "notifications/subscriptions/acknowledged"
|
"surface": "notifications/subscriptions/acknowledged"
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -18,8 +18,9 @@ feature jobs должны быть `skipped` для story и `success` для fe
|
|||||||
У Crank и FreeHub полный Rust clippy/workspace test и тяжёлые feature/security
|
У Crank и FreeHub полный Rust clippy/workspace test и тяжёлые feature/security
|
||||||
проверки выполняются только на feature. UI build и быстрые UI unit tests остаются
|
проверки выполняются только на feature. UI build и быстрые UI unit tests остаются
|
||||||
на story, Playwright E2E — на feature. Crank image build/scan/compose smoke — на
|
на story, Playwright E2E — на feature. Crank image build/scan/compose smoke — на
|
||||||
feature; фактический Deploy остаётся отдельным push-main job со своими build,
|
feature; фактический Deploy запускается только явным workflow_dispatch на main
|
||||||
scan, health и требованием успешного SHA. Тег релиза по умолчанию запускает story
|
с validation_level=feature и deploy_target=production после успешных feature gates.
|
||||||
|
Обычный merge/push не выкатывает production. Порядок: delivery-and-deploy.md. Тег релиза по умолчанию запускает story
|
||||||
ATDD, сборку бинарных/UI артефактов, security audit и image scan. Полный release
|
ATDD, сборку бинарных/UI артефактов, security audit и image scan. Полный release
|
||||||
clippy/workspace/E2E доступен через ручной dispatch с `validation_level: feature`;
|
clippy/workspace/E2E доступен через ручной dispatch с `validation_level: feature`;
|
||||||
отчёт evidence прикладывается только если такой E2E был выполнен. FreeHub
|
отчёт evidence прикладывается только если такой E2E был выполнен. FreeHub
|
||||||
|
|||||||
@@ -0,0 +1,60 @@
|
|||||||
|
# Delivery и production deploy
|
||||||
|
|
||||||
|
## Разделение merge и выкатки
|
||||||
|
|
||||||
|
Push в `main` запускает только source CI: story-проверки, UI build и
|
||||||
|
`Required Checks`. Он не запускает production deploy и не загружает секреты
|
||||||
|
OpenBao. PR, метка `feature-ready`, story dispatch и dispatch без явно выбранного
|
||||||
|
production также не выкатывают production.
|
||||||
|
|
||||||
|
Production deploy выполняет только job `Deploy` workflow `CI` и только при
|
||||||
|
одновременном выполнении условий:
|
||||||
|
|
||||||
|
- событие `workflow_dispatch`;
|
||||||
|
- ref `refs/heads/main`;
|
||||||
|
- `validation_level: feature`;
|
||||||
|
- `deploy_target: production`;
|
||||||
|
- успешный `Required Checks`, включая feature jobs `Rust Feature Validation`,
|
||||||
|
`Frontend E2E` и `Community Image Smoke`.
|
||||||
|
|
||||||
|
Любая другая комбинация оставляет deploy пропущенным, поэтому принятый merge в
|
||||||
|
`main` больше не блокируется ожиданием production-выкатки.
|
||||||
|
|
||||||
|
## Ручной запуск
|
||||||
|
|
||||||
|
В Gitea UI: `Actions` -> workflow `CI` -> `Run workflow`.
|
||||||
|
|
||||||
|
Указать точные входные значения:
|
||||||
|
|
||||||
|
| Input | Значение | Обязателен |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| Branch / ref | `main` | да |
|
||||||
|
| `validation_level` | `feature` | да |
|
||||||
|
| `deploy_target` | `production` | да |
|
||||||
|
|
||||||
|
`validation_level: story`, `deploy_target: none` или отсутствие `deploy_target`
|
||||||
|
дают только source CI либо feature-проверки без deploy. Нельзя запускать
|
||||||
|
production deploy из PR, с другой ветки или через push в `main`.
|
||||||
|
|
||||||
|
## Approval и runbook
|
||||||
|
|
||||||
|
Сам по себе ручной dispatch не является автоматическим разрешением на
|
||||||
|
production. Перед запуском release owner или DevOps явно подтверждает:
|
||||||
|
|
||||||
|
1. SHA совпадает с принятым и проверенным коммитом в `main`.
|
||||||
|
2. `Required Checks` для этого SHA успешны, включая feature jobs.
|
||||||
|
3. Пройдены [production checklist](../production-checklist.md) и актуальный
|
||||||
|
[deploy and staging smoke](../deploy-and-staging-smoke.md); известен порядок
|
||||||
|
rollback и проверено наличие backup.
|
||||||
|
4. Нет незапланированных изменений секретов, миграций или инфраструктуры.
|
||||||
|
|
||||||
|
После deploy проверить health endpoints и authenticated product smoke, затем
|
||||||
|
зафиксировать результат в staging/production regression notes. Секреты OpenBao
|
||||||
|
загружаются только внутри уже разрешённого job `Deploy`; не выводить их в логи и
|
||||||
|
не передавать в PR или dispatch story.
|
||||||
|
|
||||||
|
## Ограничения
|
||||||
|
|
||||||
|
Workflow `Community Release` для тегов остаётся отдельным процессом публикации
|
||||||
|
release-образов и не является заменой этому ручному production deploy. Изменение
|
||||||
|
`ci.yml` не даёт постоянного разрешения на выкатку и не меняет приложение.
|
||||||
@@ -29,7 +29,29 @@ run_atdd() {
|
|||||||
return 1
|
return 1
|
||||||
}
|
}
|
||||||
|
|
||||||
# Initial accepted recovery scope for Crank Story 3.17. Update with the story
|
# Keep Story 3.16 prompt ATDD with Story 3.17 completion and its bound-template regression.
|
||||||
# being published and add only AC-required affected security/contract cases.
|
run_atdd "MCP prompt composition" -p mcp-server --test integration mcp_prompts::composition -- --test-threads=1
|
||||||
run_atdd "MCP completion" -p mcp-server --test integration mcp_completion -- --test-threads=1
|
run_atdd "MCP completion" -p mcp-server --test integration mcp_completion -- --test-threads=1
|
||||||
run_atdd "static resource list" -p mcp-server --test integration static_resources::list -- --test-threads=1
|
run_atdd "bound template resources/list regression" -p mcp-server --test integration static_resources::list::list_stays_available_when_a_published_template_is_bound -- --test-threads=1
|
||||||
|
|
||||||
|
# Story 3.18: safe structured logging — the closed level vocabulary, the endpoint ATDD, and the
|
||||||
|
# capability projection the `logging` surface changes.
|
||||||
|
run_atdd "MCP log level vocabulary" -p crank-community-mcp --lib protocol::logging -- --test-threads=1
|
||||||
|
run_atdd "MCP safe logging" -p mcp-server --test integration mcp_logging -- --test-threads=1
|
||||||
|
run_atdd "capability inventory projection" -p mcp-server --test integration inventory_projection -- --test-threads=1
|
||||||
|
|
||||||
|
# Story 3.19 (FR-19) and Story 3.5 (FR-14): a committed Resource/Prompt/Tool catalog change is
|
||||||
|
# announced to the client that asked for the signal, in both revisions, and the authoritative list
|
||||||
|
# methods (including `tools/list`) stay the recovery path. The advertisement projection is covered by
|
||||||
|
# the `inventory_projection` entry above.
|
||||||
|
run_atdd "Resource/Prompt/Tool change signals" -p mcp-server --test integration mcp_signals -- --test-threads=1
|
||||||
|
run_atdd "change signal wire oracles" -p crank-community-mcp --lib protocol::signals -- --test-threads=1
|
||||||
|
run_atdd "capability advertisement registry" -p crank-community-mcp --lib protocol::registry -- --test-threads=1
|
||||||
|
|
||||||
|
# Story 3.4 (FR-14): progress and cancellation of one synchronous tools/call, on both supported
|
||||||
|
# revisions. The lifecycle bounds (token vocabulary, monotonic bounded queue, pinned frame shape,
|
||||||
|
# cancellation ownership) are unit-level; the end-to-end behaviour (real progress stream, no token,
|
||||||
|
# malformed/oversized/reused token, owner/foreign/late cancellation, ambiguous outbound, client
|
||||||
|
# smoke) runs against the real endpoint, a real published catalog and a real counted upstream.
|
||||||
|
run_atdd "tool call lifecycle bounds" -p crank-community-mcp --lib app::lifecycle -- --test-threads=1
|
||||||
|
run_atdd "tool call progress and cancellation" -p mcp-server --test integration tools_lifecycle -- --test-threads=1
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Attach the packaged release artifacts to the Gitea release of one tag.
|
||||||
|
|
||||||
|
The release workflow builds the archives, the checksums file and the SBOM into `dist/`; this script
|
||||||
|
is what makes them durable: it upserts the release entry of the tag and uploads every artifact to it,
|
||||||
|
so a published version keeps its artifacts and checksums after the runner workspace is gone.
|
||||||
|
|
||||||
|
The token is read from `GITEA_TOKEN` only; it is never printed, logged or written to disk.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
import mimetypes
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import urllib.error
|
||||||
|
import urllib.request
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
TIMEOUT_SECONDS = 120
|
||||||
|
|
||||||
|
|
||||||
|
def _json(url: str, token: str, method: str = "GET", payload: dict | None = None) -> dict:
|
||||||
|
headers = {"Authorization": f"token {token}", "Accept": "application/json"}
|
||||||
|
data = None
|
||||||
|
if payload is not None:
|
||||||
|
data = json.dumps(payload).encode("utf-8")
|
||||||
|
headers["Content-Type"] = "application/json"
|
||||||
|
request = urllib.request.Request(url, data=data, headers=headers, method=method)
|
||||||
|
with urllib.request.urlopen(request, timeout=TIMEOUT_SECONDS) as response:
|
||||||
|
return json.loads(response.read() or b"{}")
|
||||||
|
|
||||||
|
|
||||||
|
def _upload(url: str, token: str, path: Path) -> dict:
|
||||||
|
headers = {
|
||||||
|
"Authorization": f"token {token}",
|
||||||
|
"Content-Type": mimetypes.guess_type(path.name)[0] or "application/octet-stream",
|
||||||
|
}
|
||||||
|
request = urllib.request.Request(url, data=path.read_bytes(), headers=headers, method="POST")
|
||||||
|
with urllib.request.urlopen(request, timeout=TIMEOUT_SECONDS) as response:
|
||||||
|
return json.loads(response.read() or b"{}")
|
||||||
|
|
||||||
|
|
||||||
|
def release_artifacts(dist: Path) -> list[Path]:
|
||||||
|
"""Every regular file directly in `dist/`, in a stable order; nested build dirs are ignored."""
|
||||||
|
return sorted(path for path in dist.iterdir() if path.is_file() and not path.name.startswith("."))
|
||||||
|
|
||||||
|
|
||||||
|
def publish(api: str, repo: str, tag: str, title: str, notes: Path, dist: Path, prerelease: bool, token: str) -> int:
|
||||||
|
base = f"{api.rstrip('/')}/repos/{repo}"
|
||||||
|
# The notes file is the release body, not an artifact of the release.
|
||||||
|
artifacts = [path for path in release_artifacts(dist) if path.name != notes.name]
|
||||||
|
if not artifacts:
|
||||||
|
print(f"no release artifacts in {dist}", file=sys.stderr)
|
||||||
|
return 2
|
||||||
|
try:
|
||||||
|
release = _json(f"{base}/releases/tags/{tag}", token)
|
||||||
|
except urllib.error.HTTPError as error:
|
||||||
|
if error.code != 404:
|
||||||
|
raise
|
||||||
|
release = _json(
|
||||||
|
f"{base}/releases",
|
||||||
|
token,
|
||||||
|
"POST",
|
||||||
|
{
|
||||||
|
"tag_name": tag,
|
||||||
|
"name": title,
|
||||||
|
"body": notes.read_text(encoding="utf-8"),
|
||||||
|
"draft": False,
|
||||||
|
"prerelease": prerelease,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
existing = {asset["name"] for asset in release.get("assets") or []}
|
||||||
|
for path in artifacts:
|
||||||
|
if path.name in existing:
|
||||||
|
print(f"skip existing asset {path.name}")
|
||||||
|
continue
|
||||||
|
uploaded = _upload(f"{base}/releases/{release['id']}/assets?name={path.name}", token, path)
|
||||||
|
print(f"uploaded {path.name} -> {uploaded.get('browser_download_url', 'ok')}")
|
||||||
|
print(f"release {tag} id={release['id']} artifacts={len(artifacts)}")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__)
|
||||||
|
parser.add_argument("--api", required=True, help="API root, e.g. https://git.itexp.me/api/v1")
|
||||||
|
parser.add_argument("--repo", required=True, help="owner/name")
|
||||||
|
parser.add_argument("--tag", required=True)
|
||||||
|
parser.add_argument("--title", required=True)
|
||||||
|
parser.add_argument("--notes-file", type=Path, required=True)
|
||||||
|
parser.add_argument("--dist", type=Path, required=True)
|
||||||
|
parser.add_argument("--prerelease", action="store_true")
|
||||||
|
args = parser.parse_args()
|
||||||
|
token = os.environ.get("GITEA_TOKEN", "")
|
||||||
|
if not token:
|
||||||
|
print("GITEA_TOKEN is required to publish release artifacts", file=sys.stderr)
|
||||||
|
return 2
|
||||||
|
return publish(args.api, args.repo, args.tag, args.title, args.notes_file, args.dist, args.prerelease, token)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
+1
-1
@@ -1 +1 @@
|
|||||||
{"completions":{},"logging":{},"prompts":{"listChanged":false},"resources":{"listChanged":false,"subscribe":false},"tools":{"listChanged":false}}
|
{"completions":{},"logging":{},"prompts":{"listChanged":true},"resources":{"listChanged":true,"subscribe":false},"tools":{"listChanged":true}}
|
||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"revision": "2025-11-25",
|
"revision": "2025-11-25",
|
||||||
"inventory_path": "docs/capability-inventory.json",
|
"inventory_path": "docs/capability-inventory.json",
|
||||||
"inventory_sha256": "85970569edd1b658a6cea4444c796efabe166a6833787c7e98249f20a1eaf29d",
|
"inventory_sha256": "98b1f3a7f3c8e9ca1bc15bef8b73b360fbd47a42acaef2e0dffb149e2f46687d",
|
||||||
"rule": "remaining-ac-spec.md#5-server-only-projection-rules-1-4",
|
"rule": "remaining-ac-spec.md#5-server-only-projection-rules-1-4",
|
||||||
"projection_inputs": [
|
"projection_inputs": [
|
||||||
{
|
{
|
||||||
|
|||||||
+1
-1
@@ -1 +1 @@
|
|||||||
{"completions":{},"logging":{},"prompts":{"listChanged":false},"resources":{"listChanged":false,"subscribe":false},"tools":{"listChanged":false}}
|
{"completions":{},"logging":{},"prompts":{"listChanged":true},"resources":{"listChanged":true,"subscribe":false},"tools":{"listChanged":true}}
|
||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"revision": "2026-07-28",
|
"revision": "2026-07-28",
|
||||||
"inventory_path": "docs/capability-inventory.json",
|
"inventory_path": "docs/capability-inventory.json",
|
||||||
"inventory_sha256": "85970569edd1b658a6cea4444c796efabe166a6833787c7e98249f20a1eaf29d",
|
"inventory_sha256": "98b1f3a7f3c8e9ca1bc15bef8b73b360fbd47a42acaef2e0dffb149e2f46687d",
|
||||||
"rule": "remaining-ac-spec.md#5-server-only-projection-rules-1-4",
|
"rule": "remaining-ac-spec.md#5-server-only-projection-rules-1-4",
|
||||||
"projection_inputs": [
|
"projection_inputs": [
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,24 +1,24 @@
|
|||||||
{
|
{
|
||||||
"oracle": "crank-current-scope-advertised-capabilities",
|
"oracle": "crank-current-scope-advertised-capabilities",
|
||||||
"note": "Independent expected projection of the capability descriptor the CURRENT scope is allowed to advertise: advertisement equals what is implemented. Later capabilities are deferred and must not appear until their owning story implements them. This is a scoped projection, not the official MCP capability list.",
|
"note": "Independent expected projection of the capability descriptor the CURRENT scope is allowed to advertise: advertisement equals what is implemented. Later capabilities are deferred and must not appear until their owning story implements them. This is a scoped projection, not the official MCP capability list. Story 3.19 implements the Resource/Prompt list-change signals and Story 3.5 the Tools one, so every listChanged leaf is advertised; URI-content subscriptions stay unimplemented.",
|
||||||
"expected_keys": ["completions", "logging", "prompts", "resources", "tools"],
|
"expected_keys": ["completions", "logging", "prompts", "resources", "tools"],
|
||||||
"expected_descriptor": {
|
"expected_descriptor": {
|
||||||
"completions": {},
|
"completions": {},
|
||||||
"logging": {},
|
"logging": {},
|
||||||
"prompts": {
|
"prompts": {
|
||||||
"listChanged": false
|
"listChanged": true
|
||||||
},
|
},
|
||||||
"resources": {
|
"resources": {
|
||||||
"listChanged": false,
|
"listChanged": true,
|
||||||
"subscribe": false
|
"subscribe": false
|
||||||
},
|
},
|
||||||
"tools": {
|
"tools": {
|
||||||
"listChanged": false
|
"listChanged": true
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"must_not_be_advertised": ["experimental", "extensions"],
|
"must_not_be_advertised": ["experimental", "extensions"],
|
||||||
"deferred_with_owner": {
|
"deferred_with_owner": {
|
||||||
"change_signals": "story 3.19 (FR-19)",
|
"resource_content_subscriptions": "story 3.19 scope boundary (URI-content subscriptions deferred)",
|
||||||
"io.modelcontextprotocol/tasks": "story 4.7"
|
"io.modelcontextprotocol/tasks": "story 4.7"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,201 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
|
import unittest
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[2]
|
||||||
|
WORKFLOW = ROOT / ".gitea" / "workflows" / "ci.yml"
|
||||||
|
|
||||||
|
|
||||||
|
def workflow_text() -> str:
|
||||||
|
return WORKFLOW.read_text(encoding="utf-8")
|
||||||
|
|
||||||
|
|
||||||
|
def job_block(name: str) -> str:
|
||||||
|
lines = workflow_text().splitlines()
|
||||||
|
start = None
|
||||||
|
for index, line in enumerate(lines):
|
||||||
|
if line == f" {name}:":
|
||||||
|
start = index
|
||||||
|
break
|
||||||
|
if start is None:
|
||||||
|
raise AssertionError(f"job {name!r} not found")
|
||||||
|
end = len(lines)
|
||||||
|
for index in range(start + 1, len(lines)):
|
||||||
|
if re.match(r"^ [A-Za-z0-9_-]+:\s*$", lines[index]):
|
||||||
|
end = index
|
||||||
|
break
|
||||||
|
return "\n".join(lines[start:end])
|
||||||
|
|
||||||
|
|
||||||
|
def deploy_guard() -> str:
|
||||||
|
match = re.search(r"(?m)^ if:\s*(.+)$", job_block("deploy"))
|
||||||
|
if match is None:
|
||||||
|
raise AssertionError("deploy job has no guard")
|
||||||
|
return match.group(1).strip()
|
||||||
|
|
||||||
|
|
||||||
|
def guard_conditions() -> dict[str, str]:
|
||||||
|
expression = deploy_guard()
|
||||||
|
if expression.startswith("${{") and expression.endswith("}}"):
|
||||||
|
expression = expression[3:-2].strip()
|
||||||
|
conditions: dict[str, str] = {}
|
||||||
|
for part in expression.split("&&"):
|
||||||
|
match = re.fullmatch(
|
||||||
|
r"([A-Za-z0-9_.]+)\s*==\s*['\"]([^'\"]+)['\"]", part.strip()
|
||||||
|
)
|
||||||
|
if match is None:
|
||||||
|
raise AssertionError(f"unsupported deploy guard condition: {part!r}")
|
||||||
|
conditions[match.group(1)] = match.group(2)
|
||||||
|
return conditions
|
||||||
|
|
||||||
|
|
||||||
|
def deploys(context: dict[str, str | None]) -> bool:
|
||||||
|
return all(
|
||||||
|
context.get(condition) == expected
|
||||||
|
for condition, expected in guard_conditions().items()
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def dispatch_input(name: str) -> str:
|
||||||
|
match = re.search(
|
||||||
|
rf"(?m)^ {re.escape(name)}:\n((?: .*\n)+)", workflow_text()
|
||||||
|
)
|
||||||
|
if match is None:
|
||||||
|
raise AssertionError(f"workflow_dispatch input {name!r} not found")
|
||||||
|
return match.group(0)
|
||||||
|
|
||||||
|
|
||||||
|
class DeployPolicyTests(unittest.TestCase):
|
||||||
|
def test_guard_allows_only_manual_production_feature_on_main(self):
|
||||||
|
self.assertEqual(
|
||||||
|
guard_conditions(),
|
||||||
|
{
|
||||||
|
"gitea.event_name": "workflow_dispatch",
|
||||||
|
"gitea.ref": "refs/heads/main",
|
||||||
|
"inputs.validation_level": "feature",
|
||||||
|
"inputs.deploy_target": "production",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_manual_production_feature_on_main_deploys(self):
|
||||||
|
self.assertTrue(
|
||||||
|
deploys(
|
||||||
|
{
|
||||||
|
"gitea.event_name": "workflow_dispatch",
|
||||||
|
"gitea.ref": "refs/heads/main",
|
||||||
|
"inputs.validation_level": "feature",
|
||||||
|
"inputs.deploy_target": "production",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_push_to_main_does_not_deploy(self):
|
||||||
|
self.assertFalse(
|
||||||
|
deploys(
|
||||||
|
{
|
||||||
|
"gitea.event_name": "push",
|
||||||
|
"gitea.ref": "refs/heads/main",
|
||||||
|
"inputs.validation_level": "feature",
|
||||||
|
"inputs.deploy_target": "production",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_pull_request_with_feature_label_does_not_deploy(self):
|
||||||
|
self.assertFalse(
|
||||||
|
deploys(
|
||||||
|
{
|
||||||
|
"gitea.event_name": "pull_request",
|
||||||
|
"gitea.ref": "refs/pull/42/head",
|
||||||
|
"inputs.validation_level": "feature",
|
||||||
|
"inputs.deploy_target": "production",
|
||||||
|
"gitea.event.pull_request.labels.*.name": "feature-ready",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_missing_or_none_deploy_target_does_not_deploy(self):
|
||||||
|
base = {
|
||||||
|
"gitea.event_name": "workflow_dispatch",
|
||||||
|
"gitea.ref": "refs/heads/main",
|
||||||
|
"inputs.validation_level": "feature",
|
||||||
|
}
|
||||||
|
self.assertFalse(deploys(base))
|
||||||
|
self.assertFalse(deploys({**base, "inputs.deploy_target": "none"}))
|
||||||
|
|
||||||
|
def test_story_dispatch_does_not_deploy(self):
|
||||||
|
self.assertFalse(
|
||||||
|
deploys(
|
||||||
|
{
|
||||||
|
"gitea.event_name": "workflow_dispatch",
|
||||||
|
"gitea.ref": "refs/heads/main",
|
||||||
|
"inputs.validation_level": "story",
|
||||||
|
"inputs.deploy_target": "production",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_dispatch_on_other_ref_does_not_deploy(self):
|
||||||
|
self.assertFalse(
|
||||||
|
deploys(
|
||||||
|
{
|
||||||
|
"gitea.event_name": "workflow_dispatch",
|
||||||
|
"gitea.ref": "refs/heads/release",
|
||||||
|
"inputs.validation_level": "feature",
|
||||||
|
"inputs.deploy_target": "production",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_deploy_target_is_explicit_choice_defaulting_to_none(self):
|
||||||
|
block = dispatch_input("deploy_target")
|
||||||
|
self.assertIn("type: choice", block)
|
||||||
|
self.assertIn("options: [none, production]", block)
|
||||||
|
self.assertIn("default: none", block)
|
||||||
|
self.assertIn("required: true", block)
|
||||||
|
|
||||||
|
def test_push_main_source_ci_stays_enabled(self):
|
||||||
|
self.assertRegex(
|
||||||
|
workflow_text(),
|
||||||
|
r"(?m)^ push:\n branches:\n - main$",
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_deploy_requires_successful_required_checks(self):
|
||||||
|
deploy = job_block("deploy")
|
||||||
|
self.assertRegex(deploy, r"(?ms)^ needs:\n - required-checks$")
|
||||||
|
|
||||||
|
def test_required_checks_gate_feature_jobs(self):
|
||||||
|
block = job_block("required-checks")
|
||||||
|
for job in ("rust-feature", "frontend-e2e", "deployment"):
|
||||||
|
self.assertIn(f" - {job}", block)
|
||||||
|
for variable in ("RUST_FEATURE_RESULT", "E2E_RESULT", "IMAGE_RESULT"):
|
||||||
|
self.assertIn(variable, block)
|
||||||
|
|
||||||
|
def test_only_deploy_loads_production_secrets(self):
|
||||||
|
text = workflow_text()
|
||||||
|
self.assertEqual(text.count("scripts/load-openbao-env.sh"), 1)
|
||||||
|
self.assertIn("scripts/load-openbao-env.sh", job_block("deploy"))
|
||||||
|
self.assertNotIn("openbao", job_block("deployment").lower())
|
||||||
|
|
||||||
|
def test_deploy_keeps_build_scan_backup_health_and_smoke_steps(self):
|
||||||
|
deploy = job_block("deploy")
|
||||||
|
for step in (
|
||||||
|
"Load deployment secrets from OpenBao",
|
||||||
|
"Build and push images",
|
||||||
|
"Save deploy image scan evidence",
|
||||||
|
"Sync deployment files to server",
|
||||||
|
"Write environment file",
|
||||||
|
"Validate required environment variables",
|
||||||
|
"Deploy with Docker Compose",
|
||||||
|
"Verify health endpoints",
|
||||||
|
"Run authenticated product smoke",
|
||||||
|
):
|
||||||
|
self.assertIn(f"name: {step}", deploy)
|
||||||
|
self.assertIn("scripts/scan-images.sh", deploy)
|
||||||
|
self.assertIn("deploy-community.sh", deploy)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -47,12 +47,14 @@ EXPECTED_FROZEN = (
|
|||||||
b'{"resources":{"listChanged":false,"subscribe":false},"tools":{"listChanged":false}}'
|
b'{"resources":{"listChanged":false,"subscribe":false},"tools":{"listChanged":false}}'
|
||||||
)
|
)
|
||||||
EXPECTED_SHA256 = "e38c795fc28fee74168cb045427df55d882f8f7ace206af5c9a3ca4df5892c9a"
|
EXPECTED_SHA256 = "e38c795fc28fee74168cb045427df55d882f8f7ace206af5c9a3ca4df5892c9a"
|
||||||
# The canonical inventory also implements the logging surface (Story 3.18, FR-19), so the committed
|
# The canonical inventory also implements the logging surface (Story 3.18, FR-19), the
|
||||||
# oracle and the canonical projection carry `logging` next to `completions`/`prompts`/`resources`/`tools`.
|
# Resource/Prompt list-change signals (Story 3.19, FR-19) and the Tools list-change signal
|
||||||
|
# (Story 3.5, FR-14), so the committed oracle and the canonical projection carry `logging` next to
|
||||||
|
# `completions`/`prompts`/`resources`/`tools`, and every `listChanged` leaf is now implemented.
|
||||||
COMMITTED_FROZEN = (
|
COMMITTED_FROZEN = (
|
||||||
b'{"completions":{},"logging":{},"prompts":{"listChanged":false},"resources":{"listChanged":false,"subscribe":false},"tools":{"listChanged":false}}'
|
b'{"completions":{},"logging":{},"prompts":{"listChanged":true},"resources":{"listChanged":true,"subscribe":false},"tools":{"listChanged":true}}'
|
||||||
)
|
)
|
||||||
COMMITTED_SHA256 = "f806e750402d418b8a3784eff200338cd8fd91b69c2f99e9d564cb08217b84d2"
|
COMMITTED_SHA256 = "7ffa56029595fc84b6ee29930d65eada2b4d7cffd7d76f72a945fe795cabfe0f"
|
||||||
|
|
||||||
|
|
||||||
class AdvertisedCapabilitiesProjectionTests(unittest.TestCase):
|
class AdvertisedCapabilitiesProjectionTests(unittest.TestCase):
|
||||||
|
|||||||
@@ -0,0 +1,138 @@
|
|||||||
|
"""AT-3 (release durability): the artifacts of a tag land on the Gitea release, idempotently."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import contextlib
|
||||||
|
import importlib.util
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import threading
|
||||||
|
import unittest
|
||||||
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[2]
|
||||||
|
SCRIPT = ROOT / "scripts" / "publish-gitea-release.py"
|
||||||
|
|
||||||
|
|
||||||
|
def load_module():
|
||||||
|
spec = importlib.util.spec_from_file_location("publish_gitea_release", SCRIPT)
|
||||||
|
assert spec is not None and spec.loader is not None
|
||||||
|
module = importlib.util.module_from_spec(spec)
|
||||||
|
sys.modules[spec.name] = module
|
||||||
|
spec.loader.exec_module(module)
|
||||||
|
return module
|
||||||
|
|
||||||
|
|
||||||
|
class Stub:
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self.release_assets: list[dict] = []
|
||||||
|
self.created = False
|
||||||
|
self.uploaded: list[str] = []
|
||||||
|
self.created_payload: dict = {}
|
||||||
|
|
||||||
|
def handler(self):
|
||||||
|
stub = self
|
||||||
|
|
||||||
|
class Handler(BaseHTTPRequestHandler):
|
||||||
|
def log_message(self, format, *args): # noqa: A002 - base class signature
|
||||||
|
return
|
||||||
|
|
||||||
|
def _reply(self, status: int, payload: dict) -> None:
|
||||||
|
body = json.dumps(payload).encode("utf-8")
|
||||||
|
self.send_response(status)
|
||||||
|
self.send_header("Content-Type", "application/json")
|
||||||
|
self.send_header("Content-Length", str(len(body)))
|
||||||
|
self.end_headers()
|
||||||
|
self.wfile.write(body)
|
||||||
|
|
||||||
|
def do_GET(self):
|
||||||
|
if self.path.endswith("/releases/tags/v1.2.3") and stub.created:
|
||||||
|
self._reply(200, {"id": 7, "assets": stub.release_assets})
|
||||||
|
else:
|
||||||
|
self._reply(404, {"message": "not found"})
|
||||||
|
|
||||||
|
def do_POST(self):
|
||||||
|
length = int(self.headers.get("Content-Length") or 0)
|
||||||
|
body = self.rfile.read(length)
|
||||||
|
if self.path.endswith("/releases"):
|
||||||
|
stub.created = True
|
||||||
|
stub.created_payload = json.loads(body)
|
||||||
|
self._reply(201, {"id": 7, "assets": []})
|
||||||
|
return
|
||||||
|
if "/releases/7/assets?name=" in self.path:
|
||||||
|
name = self.path.rsplit("name=", 1)[1]
|
||||||
|
stub.uploaded.append(name)
|
||||||
|
stub.release_assets.append(
|
||||||
|
{"name": name, "browser_download_url": f"http://stub/assets/{name}"}
|
||||||
|
)
|
||||||
|
self._reply(201, {"name": name, "browser_download_url": f"http://stub/assets/{name}"})
|
||||||
|
return
|
||||||
|
self._reply(404, {"message": "not found"})
|
||||||
|
|
||||||
|
return Handler
|
||||||
|
|
||||||
|
|
||||||
|
class PublishGiteaReleaseTests(unittest.TestCase):
|
||||||
|
def setUp(self) -> None:
|
||||||
|
self.module = load_module()
|
||||||
|
self.stub = Stub()
|
||||||
|
self.server = ThreadingHTTPServer(("127.0.0.1", 0), self.stub.handler())
|
||||||
|
self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
|
||||||
|
self.thread.start()
|
||||||
|
self.api = f"http://127.0.0.1:{self.server.server_address[1]}"
|
||||||
|
self.tmp = tempfile.TemporaryDirectory()
|
||||||
|
self.dist = Path(self.tmp.name)
|
||||||
|
(self.dist / "crank-community-admin-api-v1.2.3.tar.gz").write_bytes(b"admin")
|
||||||
|
(self.dist / "crank-community-v1.2.3-checksums.txt").write_text("deadbeef admin.tar.gz\n")
|
||||||
|
(self.dist / "nested").mkdir()
|
||||||
|
(self.dist / "nested" / "admin-api").write_bytes(b"raw")
|
||||||
|
self.notes = self.dist / "RELEASE-NOTES.md"
|
||||||
|
self.notes.write_text("## v1.2.3\n", encoding="utf-8")
|
||||||
|
|
||||||
|
def tearDown(self) -> None:
|
||||||
|
self.server.shutdown()
|
||||||
|
self.server.server_close()
|
||||||
|
self.tmp.cleanup()
|
||||||
|
|
||||||
|
def publish(self) -> tuple[int, str]:
|
||||||
|
output = io.StringIO()
|
||||||
|
with contextlib.redirect_stdout(output), contextlib.redirect_stderr(output):
|
||||||
|
code = self.module.publish(
|
||||||
|
self.api,
|
||||||
|
"bsodfather/crank",
|
||||||
|
"v1.2.3",
|
||||||
|
"Crank Community v1.2.3",
|
||||||
|
self.notes,
|
||||||
|
self.dist,
|
||||||
|
True,
|
||||||
|
"stub-token-never-printed",
|
||||||
|
)
|
||||||
|
return code, output.getvalue()
|
||||||
|
|
||||||
|
def test_release_is_created_with_notes_and_every_top_level_artifact(self) -> None:
|
||||||
|
code, output = self.publish()
|
||||||
|
self.assertEqual(code, 0, output)
|
||||||
|
self.assertEqual(self.stub.created_payload["tag_name"], "v1.2.3")
|
||||||
|
self.assertTrue(self.stub.created_payload["prerelease"])
|
||||||
|
self.assertEqual(self.stub.created_payload["body"], "## v1.2.3\n")
|
||||||
|
self.assertEqual(
|
||||||
|
self.stub.uploaded,
|
||||||
|
["crank-community-admin-api-v1.2.3.tar.gz", "crank-community-v1.2.3-checksums.txt"],
|
||||||
|
"every top-level artifact and nothing from the nested build dir",
|
||||||
|
)
|
||||||
|
self.assertNotIn("stub-token-never-printed", output, "the token must never reach the log")
|
||||||
|
|
||||||
|
def test_second_run_reuses_the_release_and_skips_existing_assets(self) -> None:
|
||||||
|
self.assertEqual(self.publish()[0], 0)
|
||||||
|
uploaded_first = list(self.stub.uploaded)
|
||||||
|
code, output = self.publish()
|
||||||
|
self.assertEqual(code, 0, output)
|
||||||
|
self.assertEqual(self.stub.uploaded, uploaded_first, "a rerun must not upload duplicates")
|
||||||
|
self.assertEqual(output.count("skip existing asset"), 2, output)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -1276,9 +1276,9 @@ class Story31FoundationProjectionBoundaryTests(unittest.TestCase):
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
EXPECTED_FROZEN = (
|
EXPECTED_FROZEN = (
|
||||||
b'{"completions":{},"logging":{},"prompts":{"listChanged":false},"resources":{"listChanged":false,"subscribe":false},"tools":{"listChanged":false}}'
|
b'{"completions":{},"logging":{},"prompts":{"listChanged":true},"resources":{"listChanged":true,"subscribe":false},"tools":{"listChanged":true}}'
|
||||||
)
|
)
|
||||||
EXPECTED_FROZEN_SHA256 = "f806e750402d418b8a3784eff200338cd8fd91b69c2f99e9d564cb08217b84d2"
|
EXPECTED_FROZEN_SHA256 = "7ffa56029595fc84b6ee29930d65eada2b4d7cffd7d76f72a945fe795cabfe0f"
|
||||||
|
|
||||||
def test_control_committed_frozen_oracle_is_the_canonical_projection(self) -> None:
|
def test_control_committed_frozen_oracle_is_the_canonical_projection(self) -> None:
|
||||||
"""Positive control (existing GREEN, AT-13): the committed frozen bytes are canonical."""
|
"""Positive control (existing GREEN, AT-13): the committed frozen bytes are canonical."""
|
||||||
|
|||||||
Reference in new issue
Block a user