//! Legacy-era JSON-RPC dispatch: the registered method-to-handler mapping, the //! initialized-session guard and every legacy envelope the transport endpoint answers. //! //! Moved verbatim out of `app/endpoint.rs` (Story 3.18 code-health, kanban t_d1b45ddc) so the //! transport entry file stays inside the 1000-line limit; the entry point is `pub(super)`. //! No behaviour changed. use std::sync::Arc; use axum::{ http::{HeaderMap, StatusCode}, response::{IntoResponse, Response}, }; use crank_core::CorrelationContext; use serde_json::{Value, json}; use super::dispatch::{ handle_initialize, handle_initialized_notification, require_initialized_session, }; use super::request::ToolCallParams; use super::response::{ completion_result, internal_jsonrpc_error, prompt_arguments_error_response, prompt_get_result, prompts_list_result, resource_error_response, resource_read_result, resource_templates_list_result, resources_list_result, take_confirmation_token, tools_list_result, }; use super::rmcp_dispatch::{ handle_resources_command, handle_tools_command, list_resource_templates, }; use super::{AgentRoutePath, AppState}; use crate::{ auth::VerifiedMachineCredential, jsonrpc::{LEGACY_PROTOCOL_VERSION, jsonrpc_error, jsonrpc_result, 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_logging_command, }, tool_error::execution_locale, transport::{ResponseMode, session_id_from_headers, transport_response}, }; // The transport invariants of one request travel together here; a parameter struct would only // duplicate them (the same shape every other dispatch entry point in this crate uses). #[allow(clippy::too_many_arguments)] pub(super) async fn handle_legacy_request( state: Arc, 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 envelope = match crate::protocol::decode_dispatch_envelope(message) { Ok(Some(envelope)) => envelope, _ => { return internal_jsonrpc_error( message, "admitted dispatch envelope could not be decoded", ); } }; let method = envelope.method(); let dispatch = crate::protocol::dispatch_decision(method.unwrap_or_default(), registration_revision); #[cfg(test)] super::dispatch_observer::sdk_dispatch_envelope_consumed(); 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 envelope.is_request() => handle_initialize(state, path, message, response_mode).await, DispatchDecision::Allowed { handler: MethodHandler::Lifecycle, kind: Kind::Notification, } if envelope.is_notification() => { handle_initialized_notification( state, path, headers, crate::protocol::initialized_notification(message), ) .await } DispatchDecision::Allowed { handler: MethodHandler::Ping, .. } if envelope.is_request() => { 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), crate::protocol::ping_result( &json!({"method": "ping"}), &session.protocol_version, ), ), response_mode, None, Some(&session.protocol_version), ) } DispatchDecision::Allowed { handler: MethodHandler::ToolList, .. } if envelope.is_request() => { let session = match require_initialized_session(&state, path, headers, message).await { Ok(session) => session, Err(response) => return response, }; // The adapter parses the wire form and maps the neutral outcome back; the shared Tools // service never sees the envelope, the response mode or the protocol revision. let list_command: ToolsListCommand = match serde_json::from_value(params(message)) { Ok(value) => value, Err(_) => { return transport_response( StatusCode::OK, jsonrpc_error(request_id(message), -32602, "invalid tools/list parameters"), response_mode, None, Some(&session.protocol_version), ); } }; let outcome = handle_tools_command( &state, ServiceContext { workspace_slug: &session.workspace_slug, agent_slug: &session.agent_slug, credential, correlation: transport_correlation, continuation: ContinuationSupport::from_supported(session.supports_elicitation), locale: execution_locale(message), }, ToolsCommand::List(list_command), // A list command has no progress or cancellation lifecycle (Story 3.4). None, ) .await; match outcome { ToolsOutcome::List { tools, next_cursor } => { match tools_list_result(tools, next_cursor, &session.protocol_version) { Ok(result) => transport_response( StatusCode::OK, jsonrpc_result(request_id(message), result), response_mode, None, Some(&session.protocol_version), ), Err(error) => internal_jsonrpc_error(message, error), } } 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 envelope.is_request() => { let session = match require_initialized_session(&state, path, headers, message).await { Ok(session) => session, Err(response) => return response, }; let tool_call_params: ToolCallParams = match serde_json::from_value(params(message)) { Ok(value) => value, Err(_) => { return transport_response( StatusCode::OK, jsonrpc_error(request_id(message), -32602, "invalid tool call parameters"), response_mode, None, Some(&session.protocol_version), ); } }; // The adapter owns the wire form: it parses the call parameters, removes the reserved // confirmation marker and the shared Tools service never sees the envelope, the // response mode or the protocol revision (spec section 6.2). let mut arguments = tool_call_params.arguments.unwrap_or_else(|| json!({})); let confirmation_token = take_confirmation_token(&mut arguments); // Story 3.4: the client's own `_meta.progressToken`, validated and bounded, and the // session/credential ownership of the in-flight cancellation table. let progress = crate::app::lifecycle::token_from_meta(tool_call_params.meta.as_ref()); super::lifecycle::run_tool_call( Arc::clone(&state), crate::app::lifecycle::ToolCallRequest { workspace_slug: session.workspace_slug.clone(), agent_slug: session.agent_slug.clone(), credential: credential.clone(), correlation: transport_correlation.clone(), continuation: ContinuationSupport::from_supported(session.supports_elicitation), locale: execution_locale(message), }, crate::app::lifecycle::ToolCallWire { message: message.clone(), protocol_version: session.protocol_version.clone(), response_mode, progress, session_id: Some(session.id.clone()), in_flight: Some(crate::app::lifecycle::InFlightScope { session_id: session.id.clone(), owner: in_flight_owner(credential), }), }, ToolCallCommand { tool_name: tool_call_params.name, arguments, confirmation_token, }, ) .await } DispatchDecision::Allowed { handler: MethodHandler::Cancelled, kind: Kind::Notification, } if envelope.is_notification() => { handle_cancelled_notification(&state, path, headers, message, credential).await } DispatchDecision::Allowed { handler: MethodHandler::ResourceList, .. } if envelope.is_request() => { 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), match resources_list_result( resources, next_cursor, &session.protocol_version, ) { Ok(result) => result, Err(error) => return internal_jsonrpc_error(message, error), }, ), 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 envelope.is_request() => { 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), match resource_read_result(contents, &session.protocol_version) { Ok(result) => result, Err(error) => return internal_jsonrpc_error(message, error), }, ), 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 envelope.is_request() => { 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 list_resource_templates( &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 { 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), match resource_templates_list_result( templates, next_cursor, &session.protocol_version, ) { Ok(result) => result, Err(error) => return internal_jsonrpc_error(message, error), }, ), 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 envelope.is_request() => { 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 = super::rmcp_dispatch::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), match prompts_list_result(prompts, next_cursor) { Ok(result) => result, Err(error) => return internal_jsonrpc_error(message, error), }, ), 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 envelope.is_request() => { 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 = super::rmcp_dispatch::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), match prompt_get_result(description, messages) { Ok(result) => result, Err(error) => return internal_jsonrpc_error(message, error), }, ), 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 envelope.is_request() => { 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 = super::rmcp_dispatch::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 envelope.is_request() => { 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 envelope.is_notification() => 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 { Some(method) => transport_response( StatusCode::OK, jsonrpc_error( request_id(message), -32601, format!("method {method} is not supported"), ), response_mode, None, protocol_version, ), None => transport_response( StatusCode::BAD_REQUEST, jsonrpc_error(Value::Null, -32600, "invalid JSON-RPC message"), response_mode, None, protocol_version, ), }, } } /// The credential half of the cancellation ownership of one call (Story 3.4). The progress token is /// deliberately not part of it: a token never authorizes a cancellation. fn in_flight_owner(credential: &VerifiedMachineCredential) -> String { credential .platform_api_key_id .as_ref() .map_or_else(String::new, |id| id.as_str().to_owned()) } /// Route one legacy `notifications/cancelled` to the call it names, then acknowledge it. /// /// The pinned rules of a cancelled request are all "ignore": an unknown or already finished request, /// a foreign session or credential, a malformed `requestId` and an unknown session are acknowledged /// without any effect. That is also why this handler never fails the transport — a client that /// cancels must not learn anything about another client's calls. async fn handle_cancelled_notification( state: &Arc, path: &AgentRoutePath, headers: &HeaderMap, message: &Value, credential: &VerifiedMachineCredential, ) -> Response { let request_id = super::rmcp_progress_cancel::decode_cancelled_request_id(¶ms(message)); let session_id = session_id_from_headers(headers).ok().flatten(); if let (Some(request_id), Some(session_id)) = (request_id, session_id) { let owned_by_session = match state.sessions.get(&session_id).await { Ok(Some(session)) => { session.workspace_slug == path.workspace_slug && session.agent_slug == path.agent_slug } _ => false, }; if owned_by_session { state.in_flight.cancel( &crate::app::lifecycle::InFlightScope { session_id, owner: in_flight_owner(credential), }, &request_id, ); } } StatusCode::ACCEPTED.into_response() }