Compare commits

..
Author SHA1 Message Date
hermes-dev 47a6e54660 fix(ui): bump nginx runtime base to 1.30.6 for the image scan gate
CI / Rust Checks (pull_request) Successful in 6m33s
CI / Rust Feature Validation (pull_request) Skipped
CI / UI Checks (pull_request) Successful in 16m36s
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Required Checks (pull_request) Successful in 1s
CI / Deploy (pull_request) Skipped
Community Release / release (push) Failing after 16m35s
2026-10-25 16:19:11 +00:00
bsodfather 206ca784f7 fix(epic3): уложить endpoint.rs Story 3.18 в лимит 1000 строк
CI / UI Checks (pull_request) Successful in 11s
CI / Rust Checks (pull_request) Successful in 9m2s
CI / Rust Feature Validation (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Required Checks (pull_request) Successful in 1s
CI / Deploy (pull_request) Skipped
The Story 3.18 logging arm pushed `crates/crank-community-mcp/src/app/endpoint.rs`
to 1058 lines, so `scripts/check-rust-code-health.sh` failed the Required CI
(Rust Checks, run 870 / job 2408) at the pinned 1000-line default.

Move the whole legacy-era dispatch of `mcp_post_response` verbatim into
`app/legacy_dispatch.rs` (`handle_legacy_request`), leaving the endpoint as the
transport/admission layer it documents itself to be. endpoint.rs is now 381
lines and the new module 731, both inside the limit; no baseline pin and no
check was touched.

Behaviour is unchanged: the moved match keeps every arm, envelope, status code
and safe detail as-is (legacy-only logging/setLevel, -32602 INVALID_LEVEL,
EVENT_LEVEL_APPLIED Notice acknowledgment, per-session level isolation), the
pre-dispatch legacy level read stays in `mcp_post_response`, and the only edits
to the moved text are the mechanical `&credential` -> `credential` (the
credential now arrives as a reference) and `protocol_version` already being
`Option<&str>`.
2026-10-25 15:45:01 +00:00
bsodfather a438c1df42 feat(epic3): безопасное structured logging MCP (Story 3.18)
CI / UI Checks (pull_request) Successful in 11s
CI / Rust Checks (pull_request) Failing after 4m11s
CI / Rust Feature Validation (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Required Checks (pull_request) Failing after 1s
CI / Deploy (pull_request) Skipped
Story 3.18 (#25) surface: клиент получает только закрытые structured
`notifications/message` выбранного уровня, без запросов, секретов и
internal causes.

- `logging` capability advertising в обеих поддерживаемых revisions;
  `logging/setLevel` — legacy-only dispatch (modern — `_meta` per request);
- закрытый словарь LoggingLevel (RFC 5424), malformed → -32602 с одним
  safe detail; закрытый набор safe events, task-local request scope;
  bounded in-memory opt-in, без миграций;
- `notifications/message` идут перед ответом в SSE; JSON-режим их не несёт;
- ATDD в `scripts/ci-story-checks.sh`: mcp_logging (10), inventory projection (3),
  protocol::logging unit (12);
- проекция capability inventory/frozen oracle переведена на `logging`.

Story ATDD и affected проверки пройдены на этом дереве (fmt, clippy,
python oracle 56 OK, capability inventory valid). Полный `just verify` —
NOT_RUN на story по validation-policy, остаётся на собранной фиче.
2026-10-25 12:50:00 +00:00
bsodfather aed83268a0 fix(release): publish assets to the public HTTPS Gitea origin
CI / UI Checks (pull_request) Successful in 8s
CI / Rust Checks (pull_request) Successful in 6m53s
CI / Rust Feature Validation (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Required Checks (pull_request) Successful in 1s
CI / Deploy (pull_request) Skipped
Community Release / release (push) Failing after 38m13s
The release job container sees gitea.server_url as the internal
http://gitea:3000 origin, so scripts/ci-release-assets.py refused to
forward its token (run 865 failed at the publish step after packaging).
Point the publisher at https://git.itexp.me, the origin the repository
already uses for the public URL.
2026-10-25 11:37:27 +00:00
Hermes DevOps 12d8a3d490 fix(test): isolate Valkey in the CI job network and bound readiness
CI / UI Checks (pull_request) Successful in 8s
CI / Rust Checks (pull_request) Successful in 6m1s
CI / Rust Feature Validation (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Required Checks (pull_request) Successful in 1s
CI / Deploy (pull_request) Skipped
Community Release / release (push) Failing after 18m56s
2026-10-25 10:59:18 +00:00
bsodfather e57ab47c05 ci: run the Story 3.16 composite-prompt ATDD in the story gate
CI / UI Checks (pull_request) Successful in 8s
CI / Rust Checks (pull_request) Canceled after 19m49s
CI / Rust Feature Validation (pull_request) Canceled after 0s
CI / Frontend E2E (pull_request) Canceled after 0s
CI / Community Image Smoke (pull_request) Canceled after 0s
CI / Deploy (pull_request) Canceled after 0s
CI / Required Checks (pull_request) Failing after 1s
The recovery branch publishes Story 3.16 together with Story 3.17, so the targeted story gate
must exercise both accepted user outcomes: composite Prompts with published Resources and the
bounded completion/resources-list admission of 3.17.
2026-10-25 10:32:28 +00:00
Hermes DevOps 1baeefe889 ci: validate accepted stories with targeted ATDD and gate feature checks
CI / UI Checks (pull_request) Successful in 10s
CI / Rust Checks (pull_request) Failing after 25m35s
CI / Rust Feature Validation (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Required Checks (pull_request) Failing after 1s
CI / Deploy (pull_request) Skipped
2026-10-25 10:18:09 +00:00
bsodfather 9567bbf3aa fix(ci): pass the community scope guard and publish release artifacts before registry steps
CI / Rust Checks (pull_request) Canceled after 38m52s
CI / UI Checks (pull_request) Canceled after 0s
Community Release / release (push) Canceled after 38m39s
CI / Frontend E2E (pull_request) Canceled after 0s
CI / Community Image Smoke (pull_request) Canceled after 0s
CI / Deploy (pull_request) Canceled after 0s
- the community scope guard rejected the innocuous English comment 'One timed
  resources/list' in the Story 3.8 discovery diagnostic (its 'one-time-token'
  marker matches any 'one time' phrase). Reword the comment; no behaviour change.
- move the release artifact publication ahead of the registry/OpenBao steps, so a
  credential problem cannot leave the archives, checksums and SBOM unpublished.
2026-10-25 09:27:55 +00:00
bsodfather 54ce770682 feat(epic3): deliver the accepted Epic 3 scope through Story 3.17
CI / Rust Checks (pull_request) Failing after 13m41s
CI / UI Checks (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Deploy (pull_request) Skipped
Community Release / release (push) Failing after 13m33s
Recovery delivery of the accumulated, TL-accepted Epic 3 work that had never been
committed to Git (stories 3.6-3.17, see the crank board). Story 3.18 is not accepted
yet and is deliberately excluded: its logging surface, its capability registration,
its oracle projections and its tests are not part of this tree.

Accepted scope
- 3.6 typed static Resource Drafts; 3.7 publication and exact binding of static
  Resource Versions; 3.8 MCP discovery/read and revocation of static Resources;
- 3.9 Resource import/export in API and UI plus TLS dependency maintenance;
  3.10 REST-backed Resource templates; 3.11 shared REST read runtime and the MCP
  revision/capability foundation;
- 3.12 parameterised Prompt Drafts with preview; 3.13 Prompt publication and exact
  version binding to Agents; 3.14 MCP prompts; 3.15 Prompt import/export;
- 3.16 composite Prompts with published Resources (dependency content scan plus
  dynamic read through the accepted 3.11 runtime, admin preview and MCP prompts/get);
- 3.17 bounded MCP completion suggestions from typed published schemas and the
  resources/list admission fix for bound template publications.

Accepted evidence being reused (unchanged code paths)
- 3.16 candidate: core 7, admin-api 22, registry 4, mcp-server 4, UI 6; one final
  `just verify` run 1651 passed / 0 failed / 2 ignored.
- 3.17 candidate: full run 1672 passed / 0 failed / 2 ignored, QA targeted reruns and
  a real MCP Inspector 2.12.0 client smoke.

Delivery engineering in this commit
- CI: one event per change (feature branches are gated by their pull request, push
  runs only on main), story events run the changed packages, the full workspace suite
  stays the feature/release gate; no cache/sharding without a measured runner check.
- Release: the packaged archives, checksums and SBOM are now uploaded to the Gitea
  release entry of the tag instead of dying with the runner workspace.

Not included on purpose: Story 3.18 work, build caches, runtime databases, local
credentials and scratch evidence.

Refs: crank kanban t_e39d7263; baseline 1b6db09bd1.
2026-10-25 09:08:22 +00:00
13 changed files with 1165 additions and 732 deletions

No files matched your search

+3 -1
View File
@@ -212,7 +212,9 @@ jobs:
- name: Publish release bundles, checksums, evidence, and SBOM to Gitea
if: startsWith(gitea.ref, 'refs/tags/v')
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_TOKEN: ${{ secrets.GITEA_TOKEN }}
RELEASE_TAG: ${{ gitea.ref_name }}
@@ -241,6 +241,11 @@ async fn inventory_projection_sidecar_is_provenance_only_and_names_the_projectio
assert_eq!(
triples,
vec![
(
"server".to_owned(),
"capability".to_owned(),
"logging".to_owned()
),
(
"server".to_owned(),
"capability".to_owned(),
@@ -262,7 +267,7 @@ async fn inventory_projection_sidecar_is_provenance_only_and_names_the_projectio
"tools".to_owned()
)
],
"the advertised server capabilities of the current scope are `completions`, `prompts`, `resources` and `tools`"
"the advertised server capabilities of the current scope are `logging`, `completions`, `prompts`, `resources` and `tools`"
);
// The sidecar is not the payload: byte comparison is against the frozen file only.
@@ -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:?}"
);
// Positive control on delivery: the event is really delivered and its body is exactly the
// closed one for a rejected request, so the canary assertions below cannot pass vacuously.
assert_eq!(
reply.notifications,
vec![expected_notification(
"warning",
"mcp.request.rejected",
"invalid_params"
)],
"a rejected request must deliver exactly one safe warning event"
);
// The delivered notification is exactly the closed safe body: no canary, no argument value.
for notification in &reply.notifications {
assert_eq!(
@@ -724,6 +736,45 @@ async fn the_modern_era_has_no_set_level_method() {
assert!(after.notifications.is_empty());
}
/// AT-3.18-01/03: a method this era does not implement is a pinned client error, so the safe event
/// of an opted-in client describes a client-side rejection, never an internal server failure.
#[tokio::test]
async fn an_unknown_method_is_a_rejection_not_an_internal_failure() {
let endpoint = logging_endpoint().await;
let session = endpoint.legacy_session(AGENT_SLUG, &endpoint.api_key).await;
endpoint.set_level(&session, json!("info")).await;
// `server/discover` is a modern-era method, so the legacy adapter answers it with -32601.
let reply = endpoint
.legacy_post(
AGENT_SLUG,
&endpoint.api_key,
&session,
json!({
"jsonrpc": "2.0",
"id": 71,
"method": "server/discover",
"params": {}
}),
)
.await;
assert_eq!(
reply.error().0,
-32601,
"an unimplemented method is a pinned client error: {}",
reply.response
);
assert_eq!(
reply.notifications,
vec![expected_notification(
"warning",
"mcp.request.rejected",
"invalid_params"
)],
"a pinned client error must not be reported as an internal failure"
);
}
/// AT-3.18-01/03 (independence): a level belongs to one client context, so a second session and a
/// second Agent keep their own (or no) level.
#[tokio::test]
@@ -114,8 +114,8 @@ fn now_rfc3339() -> String {
.unwrap_or_else(|error| format!("unformatted-utc ({error})"))
}
/// A single timed `resources/list`, built directly on `reqwest` so transport/timeout/HTTP failures are
/// recorded as outcomes instead of aborting the run.
/// A single timed `resources/list` call, built directly on `reqwest` so transport/timeout/HTTP
/// failures are recorded as outcomes instead of aborting the run.
async fn timed_list(
endpoint: &ResourceEndpoint,
revision: &'static str,
@@ -1,18 +1,56 @@
use super::*;
use std::process::Command;
use std::{
env,
io::{Read, Write},
net::{TcpListener, TcpStream, ToSocketAddrs},
process::Command,
thread,
time::{Duration, Instant},
};
pub(super) struct TestValkey(String);
impl TestValkey {
pub(super) fn start() -> (Self, u16) {
let output = Command::new("docker")
.args([
"run",
"--detach",
"--publish",
"127.0.0.1::6379",
"valkey/valkey:8-alpine",
])
let in_docker_job = if std::path::Path::new("/.dockerenv").exists() {
let hostname = env::var("HOSTNAME").unwrap_or_default();
assert!(
matches!(hostname.len(), 12 | 64)
&& hostname.bytes().all(|byte| byte.is_ascii_hexdigit()),
"Docker job hostname must be a full 12- or 64-character container ID"
);
Some(hostname)
} else {
None
};
let port = if in_docker_job.is_some() {
let listener = TcpListener::bind(("127.0.0.1", 0))
.expect("test-owned Valkey loopback port must be available");
let port = listener.local_addr().unwrap().port();
drop(listener);
Some(port)
} else {
None
};
let mut docker = Command::new("docker");
docker.args([
"run",
"--detach",
"--label",
"crank.test.fixture=static-resources-valkey",
]);
if let (Some(hostname), Some(port)) = (&in_docker_job, port) {
docker
.arg("--network")
.arg(format!("container:{hostname}"))
.arg("valkey/valkey:8-alpine")
.args(["valkey-server", "--port", &port.to_string()]);
} else {
docker.args(["--publish", "127.0.0.1::6379", "valkey/valkey:8-alpine"]);
}
let output = docker
.output()
.expect("Docker CLI must start the test-owned Valkey container");
assert!(
@@ -25,22 +63,29 @@ impl TestValkey {
.trim()
.to_owned();
let valkey = Self(id);
let port_output = Command::new("docker")
.args(["port", &valkey.0, "6379/tcp"])
.output()
.expect("Docker CLI must report the test-owned port");
assert!(
port_output.status.success(),
"test-owned Valkey port must be available"
);
let address = String::from_utf8(port_output.stdout).expect("Docker port must be UTF-8");
let port = address
.trim()
.rsplit(':')
.next()
.unwrap()
.parse()
.expect("Docker mapped port must be numeric");
let port = match port {
Some(port) => port,
None => {
let port_output = Command::new("docker")
.args(["port", &valkey.0, "6379/tcp"])
.output()
.expect("Docker CLI must report the test-owned port");
assert!(
port_output.status.success(),
"test-owned Valkey port must be available"
);
let address =
String::from_utf8(port_output.stdout).expect("Docker port must be UTF-8");
address
.trim()
.rsplit(':')
.next()
.unwrap()
.parse()
.expect("Docker mapped port must be numeric")
}
};
wait_for_valkey(port);
(valkey, port)
}
@@ -53,6 +98,30 @@ impl TestValkey {
}
}
fn wait_for_valkey(port: u16) {
let address = ("127.0.0.1", port)
.to_socket_addrs()
.expect("test-owned Valkey loopback address must resolve")
.next()
.unwrap();
let deadline = Instant::now() + Duration::from_secs(10);
while Instant::now() < deadline {
if let Ok(mut stream) = TcpStream::connect_timeout(&address, Duration::from_millis(250)) {
let _ = stream.set_read_timeout(Some(Duration::from_millis(250)));
let _ = stream.set_write_timeout(Some(Duration::from_millis(250)));
let mut reply = [0_u8; 7];
if stream.write_all(b"*1\r\n$4\r\nPING\r\n").is_ok()
&& stream.read_exact(&mut reply).is_ok()
&& &reply == b"+PONG\r\n"
{
return;
}
}
thread::sleep(Duration::from_millis(100));
}
panic!("test-owned Valkey did not answer PING on 127.0.0.1:{port} within 10 seconds");
}
impl Drop for TestValkey {
fn drop(&mut self) {
let _ = Command::new("docker").args(["rm", "-f", &self.0]).output();
+1 -1
View File
@@ -10,7 +10,7 @@ COPY crank-community.png ./crank-community.png
RUN npm run build
FROM nginx:1.30.4-alpine3.24-slim
FROM nginx:1.30.6-alpine3.24-slim
RUN apk add --no-cache --upgrade \
'pcre2>=10.49-r0' \
+1
View File
@@ -49,6 +49,7 @@ mod approvals;
mod auth_resolution;
mod dispatch;
mod endpoint;
mod legacy_dispatch;
use self::approvals::{
approve_request, deny_request, get_approval_request, list_pending_approvals,
+20 -697
View File
@@ -3,29 +3,19 @@
//!
//! Moved verbatim out of `app.rs` (Story 3.6, kanban t_987bf309); `mcp_post_response` is reached from
//! `build_app_inner` via `mcp_post`, hence `pub(super)`. No behaviour changed.
//!
//! The legacy-era dispatch itself lives in `super::legacy_dispatch` (Story 3.18 code-health, kanban
//! t_d1b45ddc) to keep this transport entry file inside the 1000-line limit.
use super::metrics::{ActiveStreamGuard, McpRequestMetrics};
use super::request::ToolCallParams;
use super::response::take_confirmation_token;
use super::stages::{enforce_traced_rate_limit, require_traced_machine_access};
use crate::{
jsonrpc::{
LEGACY_PROTOCOL_VERSION, is_notification, is_request, jsonrpc_error, jsonrpc_result,
method_name, params, request_id,
},
jsonrpc::{jsonrpc_error, method_name, request_id},
protocol::{
CompletionCommand, CompletionOutcome, ContinuationSupport, DispatchDecision,
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,
EnvelopeKind, RequestEra, ambiguous_session_carrier_response, resolve_request_identity,
},
rate_limit::{rate_limited_jsonrpc_response, rate_limited_status_response},
request_context::RequestContext,
tool_error::execution_locale,
transport::{
accepts_event_stream, negotiate_post_response_mode, session_id_from_headers, sse_response,
transport_response, validate_get_accept_header, validate_origin,
@@ -40,20 +30,11 @@ use axum::{
};
use crank_core::{CorrelationContext, PlatformApiKeyScope};
use futures_util::stream;
use serde_json::{Value, json};
use serde_json::Value;
use std::{convert::Infallible, sync::Arc, time::Duration};
use tracing::info;
use super::dispatch::{
handle_initialize, handle_initialized_notification, handle_modern_request,
require_initialized_session,
};
use super::response::{
completion_result, internal_jsonrpc_error, prompt_arguments_error_response, prompt_get_result,
prompts_list_result, resource_error_response, resource_read_result,
resource_templates_list_result, resources_list_result, tool_command_response,
tools_list_result,
};
use super::dispatch::handle_modern_request;
use super::{AgentRoutePath, AppState, TRANSPORT_SESSION_TTL_MS};
pub(super) async fn mcp_get(
Path(path): Path<AgentRoutePath>,
@@ -384,675 +365,17 @@ async fn mcp_post_response(
#[cfg(test)]
crate::app::dispatch_observer::era_legacy_enter();
// R5/F5: the owning registration decides *which handler* serves this method in the request's
// revision. The adapter holds no method list of its own — the method-to-handler mapping lives in
// `protocol::registry` and is read through `dispatch_decision`, so a newly registered method
// really reaches its handler and removing a descriptor removes the dispatch.
let registration_revision = protocol_version
.as_deref()
.unwrap_or(LEGACY_PROTOCOL_VERSION);
let dispatch = crate::protocol::dispatch_decision(
method_name(message).unwrap_or_default(),
registration_revision,
);
match dispatch {
// G2: the *registered kind* of the matched method, not the envelope shape, decides which
// legacy lifecycle action runs. `initialize` is a request and `notifications/initialized` is a
// notification: the two share one handler but are not interchangeable, so an `initialize`
// notification may not initialize an existing session and a `notifications/initialized`
// request may not create one.
DispatchDecision::Allowed {
handler: MethodHandler::Lifecycle,
kind: Kind::Method,
} if is_request(message) => handle_initialize(state, path, message, response_mode).await,
DispatchDecision::Allowed {
handler: MethodHandler::Lifecycle,
kind: Kind::Notification,
} if is_notification(message) => {
handle_initialized_notification(state, path, headers).await
}
DispatchDecision::Allowed {
handler: MethodHandler::Ping,
..
} if is_request(message) => {
let session = match require_initialized_session(&state, path, headers, message).await {
Ok(session) => session,
Err(response) => return response,
};
transport_response(
StatusCode::OK,
jsonrpc_result(
request_id(message),
json!({ "protocolVersion": session.protocol_version }),
),
response_mode,
None,
Some(&session.protocol_version),
)
}
DispatchDecision::Allowed {
handler: MethodHandler::ToolList,
..
} if is_request(message) => {
let session = match require_initialized_session(&state, path, headers, message).await {
Ok(session) => session,
Err(response) => return response,
};
// The adapter parses the wire form and maps the neutral outcome back; the shared Tools
// service never sees the envelope, the response mode or the protocol revision.
let list_command: ToolsListCommand = match serde_json::from_value(params(message)) {
Ok(value) => value,
Err(_) => {
return transport_response(
StatusCode::OK,
jsonrpc_error(request_id(message), -32602, "invalid tools/list parameters"),
response_mode,
None,
Some(&session.protocol_version),
);
}
};
let outcome = handle_tools_command(
&state,
ServiceContext {
workspace_slug: &session.workspace_slug,
agent_slug: &session.agent_slug,
credential: &credential,
correlation: transport_correlation,
continuation: ContinuationSupport::from_supported(session.supports_elicitation),
locale: execution_locale(message),
},
ToolsCommand::List(list_command),
)
.await;
match outcome {
ToolsOutcome::List { tools, next_cursor } => transport_response(
StatusCode::OK,
jsonrpc_result(request_id(message), tools_list_result(tools, next_cursor)),
response_mode,
None,
Some(&session.protocol_version),
),
ToolsOutcome::InvalidParams(message_text) => transport_response(
StatusCode::OK,
jsonrpc_error(request_id(message), -32602, message_text),
response_mode,
None,
Some(&session.protocol_version),
),
ToolsOutcome::CatalogUnavailable => {
internal_jsonrpc_error(message, "published catalog is unavailable")
}
// A list command never produces a call outcome; it is answered with the adapter's
// internal error instead of being silently ignored.
ToolsOutcome::Call(_) => internal_jsonrpc_error(
message,
"unexpected shared tools outcome for a tools/list",
),
}
}
DispatchDecision::Allowed {
handler: MethodHandler::ToolCall,
..
} if is_request(message) => {
let session = match require_initialized_session(&state, path, headers, message).await {
Ok(session) => session,
Err(response) => return response,
};
let tool_call_params: ToolCallParams = match serde_json::from_value(params(message)) {
Ok(value) => value,
Err(_) => {
return transport_response(
StatusCode::OK,
jsonrpc_error(request_id(message), -32602, "invalid tool call parameters"),
response_mode,
None,
Some(&session.protocol_version),
);
}
};
// The adapter owns the wire form: it parses the call parameters, removes the reserved
// confirmation marker and the shared Tools service never sees the envelope, the
// response mode or the protocol revision (spec section 6.2).
let mut arguments = tool_call_params.arguments.unwrap_or_else(|| json!({}));
let confirmation_token = take_confirmation_token(&mut arguments);
let outcome = handle_tools_command(
&state,
ServiceContext {
workspace_slug: &session.workspace_slug,
agent_slug: &session.agent_slug,
credential: &credential,
correlation: transport_correlation,
continuation: ContinuationSupport::from_supported(session.supports_elicitation),
locale: execution_locale(message),
},
ToolsCommand::Call(ToolCallCommand {
tool_name: tool_call_params.name,
arguments,
confirmation_token,
}),
)
.await;
tool_command_response(
message,
response_mode,
&session.protocol_version,
transport_correlation,
outcome,
)
}
DispatchDecision::Allowed {
handler: MethodHandler::ResourceList,
..
} if is_request(message) => {
let session = match require_initialized_session(&state, path, headers, message).await {
Ok(session) => session,
Err(response) => return response,
};
let list_command: ResourcesListCommand = match serde_json::from_value(params(message)) {
Ok(value) => value,
Err(_) => {
return transport_response(
StatusCode::OK,
jsonrpc_error(
request_id(message),
-32602,
"invalid resources/list parameters",
),
response_mode,
None,
Some(&session.protocol_version),
);
}
};
let outcome = handle_resources_command(
&state,
ServiceContext {
workspace_slug: &session.workspace_slug,
agent_slug: &session.agent_slug,
credential: &credential,
correlation: transport_correlation,
continuation: ContinuationSupport::from_supported(session.supports_elicitation),
locale: execution_locale(message),
},
&session.protocol_version,
ResourcesCommand::List(list_command),
)
.await;
match outcome {
ResourcesOutcome::Listed {
resources,
next_cursor,
} => transport_response(
StatusCode::OK,
jsonrpc_result(
request_id(message),
resources_list_result(resources, next_cursor),
),
response_mode,
None,
Some(&session.protocol_version),
),
ResourcesOutcome::InvalidParams(detail) => transport_response(
StatusCode::OK,
jsonrpc_error(request_id(message), -32602, detail),
response_mode,
None,
Some(&session.protocol_version),
),
_ => internal_jsonrpc_error(message, "published resources are unavailable"),
}
}
DispatchDecision::Allowed {
handler: MethodHandler::ResourceRead,
..
} if is_request(message) => {
let session = match require_initialized_session(&state, path, headers, message).await {
Ok(session) => session,
Err(response) => return response,
};
let read_command: ResourceReadCommand = match serde_json::from_value(params(message)) {
Ok(value) => value,
Err(_) => {
return transport_response(
StatusCode::OK,
jsonrpc_error(
request_id(message),
-32602,
"invalid resources/read parameters",
),
response_mode,
None,
Some(&session.protocol_version),
);
}
};
let outcome = handle_resources_command(
&state,
ServiceContext {
workspace_slug: &session.workspace_slug,
agent_slug: &session.agent_slug,
credential: &credential,
correlation: transport_correlation,
continuation: ContinuationSupport::from_supported(session.supports_elicitation),
locale: execution_locale(message),
},
&session.protocol_version,
ResourcesCommand::Read(read_command),
)
.await;
match outcome {
ResourcesOutcome::Read { contents } => transport_response(
StatusCode::OK,
jsonrpc_result(request_id(message), resource_read_result(contents)),
response_mode,
None,
Some(&session.protocol_version),
),
ResourcesOutcome::NotAvailable => transport_response(
StatusCode::OK,
jsonrpc_error(
request_id(message),
-32602,
"the requested resource is not available",
),
response_mode,
None,
Some(&session.protocol_version),
),
ResourcesOutcome::InvalidParams(detail) => transport_response(
StatusCode::OK,
jsonrpc_error(request_id(message), -32602, detail),
response_mode,
None,
Some(&session.protocol_version),
),
ResourcesOutcome::ExecutionError(contract) => resource_error_response(
message,
response_mode,
&session.protocol_version,
contract,
),
_ => internal_jsonrpc_error(message, "published resources are unavailable"),
}
}
// Story 3.11: the shared service returns exact bound Published templates; the legacy adapter
// retains its earlier result shape and still requires the initialized session.
DispatchDecision::Allowed {
handler: MethodHandler::ResourceTemplateList,
..
} if is_request(message) => {
let session = match require_initialized_session(&state, path, headers, message).await {
Ok(session) => session,
Err(response) => return response,
};
let command: ResourcesListCommand = match serde_json::from_value(params(message)) {
Ok(command) => command,
Err(_) => {
return transport_response(
StatusCode::OK,
jsonrpc_error(
request_id(message),
-32602,
"invalid resources/templates/list parameters",
),
response_mode,
None,
Some(&session.protocol_version),
);
}
};
let (templates, next_cursor) = match crate::protocol::list_resource_templates(
&state,
&path.workspace_slug,
&path.agent_slug,
&session.protocol_version,
command,
)
.await
{
Ok(page) => page,
Err(crate::protocol::ResourceTemplatesListError::InvalidCursor) => {
return transport_response(
StatusCode::OK,
jsonrpc_error(
request_id(message),
-32602,
"invalid resources/templates/list cursor",
),
response_mode,
None,
Some(&session.protocol_version),
);
}
Err(crate::protocol::ResourceTemplatesListError::Unavailable) => {
return internal_jsonrpc_error(message, "published templates are unavailable");
}
};
transport_response(
StatusCode::OK,
jsonrpc_result(
request_id(message),
resource_templates_list_result(templates, next_cursor),
),
response_mode,
None,
Some(&session.protocol_version),
)
}
// Story 3.14: `prompts/list` / `prompts/get` of the initialized legacy session, served from
// the same exact bound Published Prompt Versions as the modern era.
DispatchDecision::Allowed {
handler: MethodHandler::PromptList,
..
} if is_request(message) => {
let session = match require_initialized_session(&state, path, headers, message).await {
Ok(session) => session,
Err(response) => return response,
};
let command: PromptsListCommand = match serde_json::from_value(params(message)) {
Ok(command) => command,
Err(_) => {
return transport_response(
StatusCode::OK,
jsonrpc_error(
request_id(message),
-32602,
"invalid prompts/list parameters",
),
response_mode,
None,
Some(&session.protocol_version),
);
}
};
let outcome = handle_prompts_command(
&state,
ServiceContext {
workspace_slug: &session.workspace_slug,
agent_slug: &session.agent_slug,
credential: &credential,
correlation: transport_correlation,
continuation: ContinuationSupport::from_supported(session.supports_elicitation),
locale: execution_locale(message),
},
&session.protocol_version,
PromptsCommand::List(command),
)
.await;
match outcome {
PromptsOutcome::Listed {
prompts,
next_cursor,
} => transport_response(
StatusCode::OK,
jsonrpc_result(
request_id(message),
prompts_list_result(prompts, next_cursor),
),
response_mode,
None,
Some(&session.protocol_version),
),
PromptsOutcome::InvalidParams(detail) => transport_response(
StatusCode::OK,
jsonrpc_error(request_id(message), -32602, detail),
response_mode,
None,
Some(&session.protocol_version),
),
_ => internal_jsonrpc_error(message, "published prompts are unavailable"),
}
}
DispatchDecision::Allowed {
handler: MethodHandler::PromptGet,
..
} if is_request(message) => {
let session = match require_initialized_session(&state, path, headers, message).await {
Ok(session) => session,
Err(response) => return response,
};
let command: PromptGetCommand = match serde_json::from_value(params(message)) {
Ok(command) => command,
Err(_) => {
return transport_response(
StatusCode::OK,
jsonrpc_error(
request_id(message),
-32602,
"invalid prompts/get parameters",
),
response_mode,
None,
Some(&session.protocol_version),
);
}
};
let outcome = handle_prompts_command(
&state,
ServiceContext {
workspace_slug: &session.workspace_slug,
agent_slug: &session.agent_slug,
credential: &credential,
correlation: transport_correlation,
continuation: ContinuationSupport::from_supported(session.supports_elicitation),
locale: execution_locale(message),
},
&session.protocol_version,
PromptsCommand::Get(command),
)
.await;
match outcome {
PromptsOutcome::Got {
description,
messages,
} => transport_response(
StatusCode::OK,
jsonrpc_result(
request_id(message),
prompt_get_result(description, messages),
),
response_mode,
None,
Some(&session.protocol_version),
),
PromptsOutcome::NotAvailable => transport_response(
StatusCode::OK,
jsonrpc_error(
request_id(message),
-32602,
"the requested prompt is not available",
),
response_mode,
None,
Some(&session.protocol_version),
),
PromptsOutcome::ArgumentsRejected { reason, argument } => {
prompt_arguments_error_response(
message,
response_mode,
&session.protocol_version,
reason,
argument,
)
}
PromptsOutcome::DependencyUnavailable { position } => transport_response(
StatusCode::OK,
jsonrpc_error(
request_id(message),
-32603,
format!("the pinned dependency at dependencies[{position}] is unavailable"),
),
response_mode,
None,
Some(&session.protocol_version),
),
PromptsOutcome::InvalidParams(detail) => transport_response(
StatusCode::OK,
jsonrpc_error(request_id(message), -32602, detail),
response_mode,
None,
Some(&session.protocol_version),
),
_ => internal_jsonrpc_error(message, "published prompts are unavailable"),
}
}
// Story 3.17: `completion/complete` of the initialized legacy session. The shared service is
// the same one the modern era uses; only the result envelope differs (no `resultType`).
DispatchDecision::Allowed {
handler: MethodHandler::Completion,
..
} if is_request(message) => {
let session = match require_initialized_session(&state, path, headers, message).await {
Ok(session) => session,
Err(response) => return response,
};
let command: CompletionCommand = match serde_json::from_value(params(message)) {
Ok(command) => command,
Err(_) => {
return transport_response(
StatusCode::OK,
jsonrpc_error(
request_id(message),
-32602,
"invalid completion/complete parameters",
),
response_mode,
None,
Some(&session.protocol_version),
);
}
};
let outcome = handle_completion_command(
&state,
ServiceContext {
workspace_slug: &session.workspace_slug,
agent_slug: &session.agent_slug,
credential: &credential,
correlation: transport_correlation,
continuation: ContinuationSupport::from_supported(session.supports_elicitation),
locale: execution_locale(message),
},
&session.protocol_version,
command,
)
.await;
match outcome {
CompletionOutcome::Completed {
values,
total,
has_more,
} => transport_response(
StatusCode::OK,
jsonrpc_result(
request_id(message),
completion_result(values, total, has_more),
),
response_mode,
None,
Some(&session.protocol_version),
),
CompletionOutcome::InvalidParams(detail) => transport_response(
StatusCode::OK,
jsonrpc_error(request_id(message), -32602, detail),
response_mode,
None,
Some(&session.protocol_version),
),
CompletionOutcome::NotAvailable => transport_response(
StatusCode::OK,
jsonrpc_error(
request_id(message),
-32602,
"the completion reference is not available",
),
response_mode,
None,
Some(&session.protocol_version),
),
CompletionOutcome::CatalogUnavailable => {
internal_jsonrpc_error(message, "published completion sources are unavailable")
}
}
}
// 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(),
),
},
}
// R5/F5: the owning registration decides which handler serves this method in the request's
// revision; that legacy dispatch lives in `super::legacy_dispatch`.
super::legacy_dispatch::handle_legacy_request(
state,
path,
headers,
message,
response_mode,
&identity,
&credential,
transport_correlation,
)
.await
}
@@ -0,0 +1,731 @@
//! Legacy-era JSON-RPC dispatch: the registered method-to-handler mapping, the
//! initialized-session guard and every legacy envelope the transport endpoint answers.
//!
//! Moved verbatim out of `app/endpoint.rs` (Story 3.18 code-health, kanban t_d1b45ddc) so the
//! transport entry file stays inside the 1000-line limit; the entry point is `pub(super)`.
//! No behaviour changed.
use std::sync::Arc;
use axum::{
http::{HeaderMap, StatusCode},
response::{IntoResponse, Response},
};
use crank_core::CorrelationContext;
use serde_json::{Value, json};
use super::dispatch::{
handle_initialize, handle_initialized_notification, require_initialized_session,
};
use super::request::ToolCallParams;
use super::response::{
completion_result, internal_jsonrpc_error, prompt_arguments_error_response, prompt_get_result,
prompts_list_result, resource_error_response, resource_read_result,
resource_templates_list_result, resources_list_result, take_confirmation_token,
tool_command_response, tools_list_result,
};
use super::{AgentRoutePath, AppState};
use crate::{
auth::VerifiedMachineCredential,
jsonrpc::{
LEGACY_PROTOCOL_VERSION, is_notification, is_request, jsonrpc_error, jsonrpc_result,
method_name, params, request_id,
},
protocol::{
CompletionCommand, CompletionOutcome, ContinuationSupport, DispatchDecision,
EVENT_LEVEL_APPLIED, INVALID_LEVEL, Kind, LoggingOutcome, MethodHandler, PromptGetCommand,
PromptsCommand, PromptsListCommand, PromptsOutcome, RequestIdentity, ResourceReadCommand,
ResourcesCommand, ResourcesListCommand, ResourcesOutcome, ServiceContext, SetLevelCommand,
ToolCallCommand, ToolsCommand, ToolsListCommand, ToolsOutcome, handle_completion_command,
handle_logging_command, handle_prompts_command, handle_resources_command,
handle_tools_command,
},
tool_error::execution_locale,
transport::{ResponseMode, transport_response},
};
// The transport invariants of one request travel together here; a parameter struct would only
// duplicate them (the same shape every other dispatch entry point in this crate uses).
#[allow(clippy::too_many_arguments)]
pub(super) async fn handle_legacy_request(
state: Arc<AppState>,
path: &AgentRoutePath,
headers: &HeaderMap,
message: &Value,
response_mode: ResponseMode,
identity: &RequestIdentity,
credential: &VerifiedMachineCredential,
transport_correlation: &CorrelationContext,
) -> Response {
let protocol_version = identity.version.as_deref();
// R5/F5: the owning registration decides *which handler* serves this method in the request's
// revision. The adapter holds no method list of its own — the method-to-handler mapping lives in
// `protocol::registry` and is read through `dispatch_decision`, so a newly registered method
// really reaches its handler and removing a descriptor removes the dispatch.
let registration_revision = protocol_version.unwrap_or(LEGACY_PROTOCOL_VERSION);
let dispatch = crate::protocol::dispatch_decision(
method_name(message).unwrap_or_default(),
registration_revision,
);
match dispatch {
// G2: the *registered kind* of the matched method, not the envelope shape, decides which
// legacy lifecycle action runs. `initialize` is a request and `notifications/initialized` is a
// notification: the two share one handler but are not interchangeable, so an `initialize`
// notification may not initialize an existing session and a `notifications/initialized`
// request may not create one.
DispatchDecision::Allowed {
handler: MethodHandler::Lifecycle,
kind: Kind::Method,
} if is_request(message) => handle_initialize(state, path, message, response_mode).await,
DispatchDecision::Allowed {
handler: MethodHandler::Lifecycle,
kind: Kind::Notification,
} if is_notification(message) => {
handle_initialized_notification(state, path, headers).await
}
DispatchDecision::Allowed {
handler: MethodHandler::Ping,
..
} if is_request(message) => {
let session = match require_initialized_session(&state, path, headers, message).await {
Ok(session) => session,
Err(response) => return response,
};
transport_response(
StatusCode::OK,
jsonrpc_result(
request_id(message),
json!({ "protocolVersion": session.protocol_version }),
),
response_mode,
None,
Some(&session.protocol_version),
)
}
DispatchDecision::Allowed {
handler: MethodHandler::ToolList,
..
} if is_request(message) => {
let session = match require_initialized_session(&state, path, headers, message).await {
Ok(session) => session,
Err(response) => return response,
};
// The adapter parses the wire form and maps the neutral outcome back; the shared Tools
// service never sees the envelope, the response mode or the protocol revision.
let list_command: ToolsListCommand = match serde_json::from_value(params(message)) {
Ok(value) => value,
Err(_) => {
return transport_response(
StatusCode::OK,
jsonrpc_error(request_id(message), -32602, "invalid tools/list parameters"),
response_mode,
None,
Some(&session.protocol_version),
);
}
};
let outcome = handle_tools_command(
&state,
ServiceContext {
workspace_slug: &session.workspace_slug,
agent_slug: &session.agent_slug,
credential,
correlation: transport_correlation,
continuation: ContinuationSupport::from_supported(session.supports_elicitation),
locale: execution_locale(message),
},
ToolsCommand::List(list_command),
)
.await;
match outcome {
ToolsOutcome::List { tools, next_cursor } => transport_response(
StatusCode::OK,
jsonrpc_result(request_id(message), tools_list_result(tools, next_cursor)),
response_mode,
None,
Some(&session.protocol_version),
),
ToolsOutcome::InvalidParams(message_text) => transport_response(
StatusCode::OK,
jsonrpc_error(request_id(message), -32602, message_text),
response_mode,
None,
Some(&session.protocol_version),
),
ToolsOutcome::CatalogUnavailable => {
internal_jsonrpc_error(message, "published catalog is unavailable")
}
// A list command never produces a call outcome; it is answered with the adapter's
// internal error instead of being silently ignored.
ToolsOutcome::Call(_) => internal_jsonrpc_error(
message,
"unexpected shared tools outcome for a tools/list",
),
}
}
DispatchDecision::Allowed {
handler: MethodHandler::ToolCall,
..
} if is_request(message) => {
let session = match require_initialized_session(&state, path, headers, message).await {
Ok(session) => session,
Err(response) => return response,
};
let tool_call_params: ToolCallParams = match serde_json::from_value(params(message)) {
Ok(value) => value,
Err(_) => {
return transport_response(
StatusCode::OK,
jsonrpc_error(request_id(message), -32602, "invalid tool call parameters"),
response_mode,
None,
Some(&session.protocol_version),
);
}
};
// The adapter owns the wire form: it parses the call parameters, removes the reserved
// confirmation marker and the shared Tools service never sees the envelope, the
// response mode or the protocol revision (spec section 6.2).
let mut arguments = tool_call_params.arguments.unwrap_or_else(|| json!({}));
let confirmation_token = take_confirmation_token(&mut arguments);
let outcome = handle_tools_command(
&state,
ServiceContext {
workspace_slug: &session.workspace_slug,
agent_slug: &session.agent_slug,
credential,
correlation: transport_correlation,
continuation: ContinuationSupport::from_supported(session.supports_elicitation),
locale: execution_locale(message),
},
ToolsCommand::Call(ToolCallCommand {
tool_name: tool_call_params.name,
arguments,
confirmation_token,
}),
)
.await;
tool_command_response(
message,
response_mode,
&session.protocol_version,
transport_correlation,
outcome,
)
}
DispatchDecision::Allowed {
handler: MethodHandler::ResourceList,
..
} if is_request(message) => {
let session = match require_initialized_session(&state, path, headers, message).await {
Ok(session) => session,
Err(response) => return response,
};
let list_command: ResourcesListCommand = match serde_json::from_value(params(message)) {
Ok(value) => value,
Err(_) => {
return transport_response(
StatusCode::OK,
jsonrpc_error(
request_id(message),
-32602,
"invalid resources/list parameters",
),
response_mode,
None,
Some(&session.protocol_version),
);
}
};
let outcome = handle_resources_command(
&state,
ServiceContext {
workspace_slug: &session.workspace_slug,
agent_slug: &session.agent_slug,
credential,
correlation: transport_correlation,
continuation: ContinuationSupport::from_supported(session.supports_elicitation),
locale: execution_locale(message),
},
&session.protocol_version,
ResourcesCommand::List(list_command),
)
.await;
match outcome {
ResourcesOutcome::Listed {
resources,
next_cursor,
} => transport_response(
StatusCode::OK,
jsonrpc_result(
request_id(message),
resources_list_result(resources, next_cursor),
),
response_mode,
None,
Some(&session.protocol_version),
),
ResourcesOutcome::InvalidParams(detail) => transport_response(
StatusCode::OK,
jsonrpc_error(request_id(message), -32602, detail),
response_mode,
None,
Some(&session.protocol_version),
),
_ => internal_jsonrpc_error(message, "published resources are unavailable"),
}
}
DispatchDecision::Allowed {
handler: MethodHandler::ResourceRead,
..
} if is_request(message) => {
let session = match require_initialized_session(&state, path, headers, message).await {
Ok(session) => session,
Err(response) => return response,
};
let read_command: ResourceReadCommand = match serde_json::from_value(params(message)) {
Ok(value) => value,
Err(_) => {
return transport_response(
StatusCode::OK,
jsonrpc_error(
request_id(message),
-32602,
"invalid resources/read parameters",
),
response_mode,
None,
Some(&session.protocol_version),
);
}
};
let outcome = handle_resources_command(
&state,
ServiceContext {
workspace_slug: &session.workspace_slug,
agent_slug: &session.agent_slug,
credential,
correlation: transport_correlation,
continuation: ContinuationSupport::from_supported(session.supports_elicitation),
locale: execution_locale(message),
},
&session.protocol_version,
ResourcesCommand::Read(read_command),
)
.await;
match outcome {
ResourcesOutcome::Read { contents } => transport_response(
StatusCode::OK,
jsonrpc_result(request_id(message), resource_read_result(contents)),
response_mode,
None,
Some(&session.protocol_version),
),
ResourcesOutcome::NotAvailable => transport_response(
StatusCode::OK,
jsonrpc_error(
request_id(message),
-32602,
"the requested resource is not available",
),
response_mode,
None,
Some(&session.protocol_version),
),
ResourcesOutcome::InvalidParams(detail) => transport_response(
StatusCode::OK,
jsonrpc_error(request_id(message), -32602, detail),
response_mode,
None,
Some(&session.protocol_version),
),
ResourcesOutcome::ExecutionError(contract) => resource_error_response(
message,
response_mode,
&session.protocol_version,
contract,
),
_ => internal_jsonrpc_error(message, "published resources are unavailable"),
}
}
// Story 3.11: the shared service returns exact bound Published templates; the legacy adapter
// retains its earlier result shape and still requires the initialized session.
DispatchDecision::Allowed {
handler: MethodHandler::ResourceTemplateList,
..
} if is_request(message) => {
let session = match require_initialized_session(&state, path, headers, message).await {
Ok(session) => session,
Err(response) => return response,
};
let command: ResourcesListCommand = match serde_json::from_value(params(message)) {
Ok(command) => command,
Err(_) => {
return transport_response(
StatusCode::OK,
jsonrpc_error(
request_id(message),
-32602,
"invalid resources/templates/list parameters",
),
response_mode,
None,
Some(&session.protocol_version),
);
}
};
let (templates, next_cursor) = match crate::protocol::list_resource_templates(
&state,
&path.workspace_slug,
&path.agent_slug,
&session.protocol_version,
command,
)
.await
{
Ok(page) => page,
Err(crate::protocol::ResourceTemplatesListError::InvalidCursor) => {
return transport_response(
StatusCode::OK,
jsonrpc_error(
request_id(message),
-32602,
"invalid resources/templates/list cursor",
),
response_mode,
None,
Some(&session.protocol_version),
);
}
Err(crate::protocol::ResourceTemplatesListError::Unavailable) => {
return internal_jsonrpc_error(message, "published templates are unavailable");
}
};
transport_response(
StatusCode::OK,
jsonrpc_result(
request_id(message),
resource_templates_list_result(templates, next_cursor),
),
response_mode,
None,
Some(&session.protocol_version),
)
}
// Story 3.14: `prompts/list` / `prompts/get` of the initialized legacy session, served from
// the same exact bound Published Prompt Versions as the modern era.
DispatchDecision::Allowed {
handler: MethodHandler::PromptList,
..
} if is_request(message) => {
let session = match require_initialized_session(&state, path, headers, message).await {
Ok(session) => session,
Err(response) => return response,
};
let command: PromptsListCommand = match serde_json::from_value(params(message)) {
Ok(command) => command,
Err(_) => {
return transport_response(
StatusCode::OK,
jsonrpc_error(
request_id(message),
-32602,
"invalid prompts/list parameters",
),
response_mode,
None,
Some(&session.protocol_version),
);
}
};
let outcome = handle_prompts_command(
&state,
ServiceContext {
workspace_slug: &session.workspace_slug,
agent_slug: &session.agent_slug,
credential,
correlation: transport_correlation,
continuation: ContinuationSupport::from_supported(session.supports_elicitation),
locale: execution_locale(message),
},
&session.protocol_version,
PromptsCommand::List(command),
)
.await;
match outcome {
PromptsOutcome::Listed {
prompts,
next_cursor,
} => transport_response(
StatusCode::OK,
jsonrpc_result(
request_id(message),
prompts_list_result(prompts, next_cursor),
),
response_mode,
None,
Some(&session.protocol_version),
),
PromptsOutcome::InvalidParams(detail) => transport_response(
StatusCode::OK,
jsonrpc_error(request_id(message), -32602, detail),
response_mode,
None,
Some(&session.protocol_version),
),
_ => internal_jsonrpc_error(message, "published prompts are unavailable"),
}
}
DispatchDecision::Allowed {
handler: MethodHandler::PromptGet,
..
} if is_request(message) => {
let session = match require_initialized_session(&state, path, headers, message).await {
Ok(session) => session,
Err(response) => return response,
};
let command: PromptGetCommand = match serde_json::from_value(params(message)) {
Ok(command) => command,
Err(_) => {
return transport_response(
StatusCode::OK,
jsonrpc_error(
request_id(message),
-32602,
"invalid prompts/get parameters",
),
response_mode,
None,
Some(&session.protocol_version),
);
}
};
let outcome = handle_prompts_command(
&state,
ServiceContext {
workspace_slug: &session.workspace_slug,
agent_slug: &session.agent_slug,
credential,
correlation: transport_correlation,
continuation: ContinuationSupport::from_supported(session.supports_elicitation),
locale: execution_locale(message),
},
&session.protocol_version,
PromptsCommand::Get(command),
)
.await;
match outcome {
PromptsOutcome::Got {
description,
messages,
} => transport_response(
StatusCode::OK,
jsonrpc_result(
request_id(message),
prompt_get_result(description, messages),
),
response_mode,
None,
Some(&session.protocol_version),
),
PromptsOutcome::NotAvailable => transport_response(
StatusCode::OK,
jsonrpc_error(
request_id(message),
-32602,
"the requested prompt is not available",
),
response_mode,
None,
Some(&session.protocol_version),
),
PromptsOutcome::ArgumentsRejected { reason, argument } => {
prompt_arguments_error_response(
message,
response_mode,
&session.protocol_version,
reason,
argument,
)
}
PromptsOutcome::DependencyUnavailable { position } => transport_response(
StatusCode::OK,
jsonrpc_error(
request_id(message),
-32603,
format!("the pinned dependency at dependencies[{position}] is unavailable"),
),
response_mode,
None,
Some(&session.protocol_version),
),
PromptsOutcome::InvalidParams(detail) => transport_response(
StatusCode::OK,
jsonrpc_error(request_id(message), -32602, detail),
response_mode,
None,
Some(&session.protocol_version),
),
_ => internal_jsonrpc_error(message, "published prompts are unavailable"),
}
}
// Story 3.17: `completion/complete` of the initialized legacy session. The shared service is
// the same one the modern era uses; only the result envelope differs (no `resultType`).
DispatchDecision::Allowed {
handler: MethodHandler::Completion,
..
} if is_request(message) => {
let session = match require_initialized_session(&state, path, headers, message).await {
Ok(session) => session,
Err(response) => return response,
};
let command: CompletionCommand = match serde_json::from_value(params(message)) {
Ok(command) => command,
Err(_) => {
return transport_response(
StatusCode::OK,
jsonrpc_error(
request_id(message),
-32602,
"invalid completion/complete parameters",
),
response_mode,
None,
Some(&session.protocol_version),
);
}
};
let outcome = handle_completion_command(
&state,
ServiceContext {
workspace_slug: &session.workspace_slug,
agent_slug: &session.agent_slug,
credential,
correlation: transport_correlation,
continuation: ContinuationSupport::from_supported(session.supports_elicitation),
locale: execution_locale(message),
},
&session.protocol_version,
command,
)
.await;
match outcome {
CompletionOutcome::Completed {
values,
total,
has_more,
} => transport_response(
StatusCode::OK,
jsonrpc_result(
request_id(message),
completion_result(values, total, has_more),
),
response_mode,
None,
Some(&session.protocol_version),
),
CompletionOutcome::InvalidParams(detail) => transport_response(
StatusCode::OK,
jsonrpc_error(request_id(message), -32602, detail),
response_mode,
None,
Some(&session.protocol_version),
),
CompletionOutcome::NotAvailable => transport_response(
StatusCode::OK,
jsonrpc_error(
request_id(message),
-32602,
"the completion reference is not available",
),
response_mode,
None,
Some(&session.protocol_version),
),
CompletionOutcome::CatalogUnavailable => {
internal_jsonrpc_error(message, "published completion sources are unavailable")
}
}
}
// Story 3.18: the pinned legacy `logging/setLevel`. The level belongs to the initialized
// session of this request, so setting it can never change another client's level. The request
// answers an empty result; the acknowledgment event is filtered by the level it just set.
DispatchDecision::Allowed {
handler: MethodHandler::LoggingSetLevel,
..
} if is_request(message) => {
let session = match require_initialized_session(&state, path, headers, message).await {
Ok(session) => session,
Err(response) => return response,
};
let command: SetLevelCommand = match serde_json::from_value(params(message)) {
Ok(command) => command,
// A non-string, missing or otherwise unparsable level shares the one safe detail of a
// value outside the pinned union: nothing the client sent is echoed back.
Err(_) => {
return transport_response(
StatusCode::OK,
jsonrpc_error(request_id(message), -32602, INVALID_LEVEL),
response_mode,
None,
Some(&session.protocol_version),
);
}
};
match handle_logging_command(&state.logging_levels, &session.id, command) {
LoggingOutcome::Applied(level) => {
crate::protocol::set_active_level(Some(level));
crate::protocol::note(
crate::protocol::LogLevel::Notice,
EVENT_LEVEL_APPLIED,
"applied",
);
transport_response(
StatusCode::OK,
jsonrpc_result(request_id(message), json!({})),
response_mode,
None,
Some(&session.protocol_version),
)
}
LoggingOutcome::InvalidParams(detail) => transport_response(
StatusCode::OK,
jsonrpc_error(request_id(message), -32602, detail),
response_mode,
None,
Some(&session.protocol_version),
),
}
}
// A notification whose method the registration does not map to this adapter's handlers is
// acknowledged without being dispatched, exactly as before.
_ if is_notification(message) => StatusCode::ACCEPTED.into_response(),
// Every remaining decision (unregistered, wrong era, or a handler this adapter does not
// serve) is a method-level rejection: no handler, no service entry, no outbound call.
_ => match method_name(message) {
Some(method) => transport_response(
StatusCode::OK,
jsonrpc_error(
request_id(message),
-32601,
format!("method {method} is not supported"),
),
response_mode,
None,
protocol_version,
),
None => transport_response(
StatusCode::BAD_REQUEST,
jsonrpc_error(Value::Null, -32600, "invalid JSON-RPC message"),
response_mode,
None,
protocol_version,
),
},
}
}
+5 -2
View File
@@ -317,8 +317,11 @@ fn note_logging_outcome(payload: &Value) {
use crate::protocol::{EVENT_FAILED, EVENT_REJECTED, EVENT_SERVED, LogLevel, note};
if payload.get("error").is_some() {
match payload.pointer("/error/code").and_then(Value::as_i64) {
// The pinned client-error codes of a malformed request.
Some(-32600 | -32602) => note(LogLevel::Warning, EVENT_REJECTED, "invalid_params"),
// The pinned client-error codes: a malformed request, a method that this era does not
// implement, and invalid params. The client can correct all three, so they are a
// rejection rather than a server failure; the closed label stays the one client-error
// label of the vocabulary instead of growing a new one.
Some(-32602..=-32600) => note(LogLevel::Warning, EVENT_REJECTED, "invalid_params"),
_ => note(LogLevel::Error, EVENT_FAILED, "internal"),
}
return;
+9 -3
View File
@@ -29,7 +29,13 @@ run_atdd() {
return 1
}
# Initial accepted recovery scope for Crank Story 3.17. Update with the story
# being published and add only AC-required affected security/contract cases.
# Keep Story 3.16 prompt ATDD with Story 3.17 completion and its bound-template regression.
run_atdd "MCP prompt composition" -p mcp-server --test integration mcp_prompts::composition -- --test-threads=1
run_atdd "MCP completion" -p mcp-server --test integration mcp_completion -- --test-threads=1
run_atdd "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
+104
View File
@@ -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())
+138
View File
@@ -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()