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>`.
This commit is contained in:
bsodfather committed 2026-10-25 15:45:01 +00:00
1 parent a438c1df42
commit 206ca784f7
3 files changed
+752 -697

No files matched your search

+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,
),
},
}
}