- request-scoped lifecycle одного tools/call: валидированный `_meta.progressToken` (строковый/числовой, 1..=128 байт) и bounded очередь реальных этапов (tool_resolved → authorization_resolved → execution_dispatched) в собственный SSE-stream запроса; без token или без stream-carrier результат не меняется; - сериализация `notifications/progress` по pinned схеме обеих revisions (progressToken/progress/message, total не изобретается); - отмена по revision: 2025-11-25 — `notifications/cancelled` через bounded in-flight таблицу (владение = session + platform credential, не progress token); 2026-07-28 — закрытие response stream; в обоих случаях drop будущего вызова = кооперативная остановка, terminal-сообщение не отправляется; - streamed ответ сохраняет проекцию Story 3.18: closed `notifications/message` перед финальным кадром (перенос logging-scope в тело стрима); - ATDD: 12 end-to-end тестов на реальном endpoint/каталоге/counted upstream (обе revisions, malformed/oversized/reused token, owner/foreign/late cancel, disconnect, ambiguous outbound, representative client smoke) + 7 unit-тестов границ lifecycle; entry в scripts/ci-story-checks.sh.
920 lines
37 KiB
Rust
920 lines
37 KiB
Rust
//! Modern JSON-RPC dispatch: required `Mcp-Name`/method checks, `initialize`, the
|
|
//! initialized-notification handshake, the required-initialized-session guard and the era-neutral
|
|
//! result helpers it needs locally (`add_millis` is used only by `handle_initialize`).
|
|
//!
|
|
//! Moved verbatim out of `app.rs` (Story 3.6, kanban t_987bf309); it is called from
|
|
//! `app/endpoint.rs`, so the entry points are `pub(super)`. No behaviour changed.
|
|
|
|
use super::request::{InitializeParams, ToolCallParams};
|
|
use super::response::take_confirmation_token;
|
|
use crate::{
|
|
auth::VerifiedMachineCredential,
|
|
jsonrpc::{
|
|
is_notification, jsonrpc_error, jsonrpc_result, method_name, negotiated_protocol_version,
|
|
params, request_id,
|
|
},
|
|
protocol::{
|
|
CompletionCommand, CompletionOutcome, ContinuationSupport, DispatchDecision, MethodHandler,
|
|
PromptGetCommand, PromptsCommand, PromptsListCommand, PromptsOutcome, RequestIdentity,
|
|
ResourceReadCommand, ResourcesCommand, ResourcesListCommand, ResourcesOutcome,
|
|
ServiceContext, ToolCallCommand, ToolsCommand, ToolsListCommand, ToolsOutcome,
|
|
declared_mcp_method, discover_result, handle_completion_command, handle_prompts_command,
|
|
handle_resources_command, handle_tools_command, validate_modern_request_name,
|
|
},
|
|
session::SessionState,
|
|
tool_error::execution_locale,
|
|
transport::{
|
|
ResponseMode, json_response, session_id_from_headers, sse_response, transport_response,
|
|
},
|
|
};
|
|
use axum::{
|
|
http::{HeaderMap, StatusCode},
|
|
response::{IntoResponse, Response},
|
|
};
|
|
use crank_core::CorrelationContext;
|
|
use serde_json::{Value, json};
|
|
use std::sync::Arc;
|
|
use time::OffsetDateTime;
|
|
|
|
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, tools_list_result,
|
|
};
|
|
use super::{AgentRoutePath, AppState, TRANSPORT_SESSION_TTL_MS};
|
|
use crate::protocol::{ResourceTemplatesListError, list_resource_templates};
|
|
const SERVER_NAME: &str = "crank-mcp-server";
|
|
const SERVER_VERSION: &str = env!("CARGO_PKG_VERSION");
|
|
|
|
/// Serve a request of the modern stateless era.
|
|
/// No session is created, read or required; identity comes from the per-request `_meta` metadata that
|
|
/// the era resolver already validated, and the advertised capabilities come from the single static
|
|
/// registration. The era answers the same business result as the legacy path through the shared tool
|
|
/// transport, methods that are not implemented answer with an era-correct `-32601`, and a
|
|
/// notification (no `id`) is acknowledged without being dispatched.
|
|
#[allow(clippy::too_many_arguments)]
|
|
pub(super) async fn handle_modern_request(
|
|
state: &Arc<AppState>,
|
|
path: &AgentRoutePath,
|
|
headers: &HeaderMap,
|
|
message: &Value,
|
|
response_mode: ResponseMode,
|
|
identity: &RequestIdentity,
|
|
credential: &VerifiedMachineCredential,
|
|
transport_correlation: &CorrelationContext,
|
|
) -> Response {
|
|
let version = identity
|
|
.version
|
|
.as_deref()
|
|
.unwrap_or(crate::jsonrpc::MODERN_PROTOCOL_VERSION);
|
|
|
|
// Story 3.18: the modern revision carries the log level of this request in
|
|
// `_meta["io.modelcontextprotocol/logLevel"]` (SEP-2577); the former `logging/setLevel` request
|
|
// does not exist here. Absent, non-string or unknown values mean "not opted in", so no
|
|
// `notifications/message` is emitted for this request.
|
|
crate::protocol::set_active_level(crate::protocol::modern_request_level(message));
|
|
|
|
// A notification carries no `id`. It is acknowledged before the request-only header rules: the
|
|
// mandatory `Mcp-Method`/`Mcp-Name` pair applies to requests, not to notifications (protocol era
|
|
// matrix row 18). The envelope, identity and mixed-carrier checks — and authentication — have
|
|
// already run at this point, so this early return cannot admit a malformed identity or a session
|
|
// conflict, and the notification is never dispatched.
|
|
if is_notification(message) {
|
|
return crate::protocol::modern_notification_response();
|
|
}
|
|
|
|
let declared_method = match declared_mcp_method(headers, message) {
|
|
Ok(declared_method) => declared_method,
|
|
Err(response) => return *response,
|
|
};
|
|
if declared_method != method_name(message) {
|
|
return crate::protocol::modern_header_mismatch_response(message);
|
|
}
|
|
|
|
// R5/F5: the same registration-backed dispatch as the legacy adapter. The handler is decided by
|
|
// the owning registration (not by a literal method list inside this adapter), and a method whose
|
|
// capability is not eligible in this revision is never served here.
|
|
let dispatch =
|
|
crate::protocol::dispatch_decision(method_name(message).unwrap_or_default(), version);
|
|
match dispatch {
|
|
DispatchDecision::Allowed {
|
|
handler: MethodHandler::Discover,
|
|
..
|
|
} => transport_response(
|
|
StatusCode::OK,
|
|
jsonrpc_result(
|
|
request_id(message),
|
|
discover_result(version, SERVER_NAME, SERVER_VERSION),
|
|
),
|
|
response_mode,
|
|
None,
|
|
Some(version),
|
|
),
|
|
DispatchDecision::Allowed {
|
|
handler: MethodHandler::Ping,
|
|
..
|
|
} => transport_response(
|
|
StatusCode::OK,
|
|
jsonrpc_result(
|
|
request_id(message),
|
|
crate::protocol::project_modern_result(
|
|
version,
|
|
json!({ "protocolVersion": version }),
|
|
),
|
|
),
|
|
response_mode,
|
|
None,
|
|
Some(version),
|
|
),
|
|
DispatchDecision::Allowed {
|
|
handler: MethodHandler::ToolList,
|
|
..
|
|
} => {
|
|
// Same shared command boundary as the legacy era: the adapter keeps the modern cache
|
|
// projection, the shared service stays wire-free.
|
|
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(version),
|
|
);
|
|
}
|
|
};
|
|
let outcome = handle_tools_command(
|
|
state,
|
|
ServiceContext {
|
|
workspace_slug: &path.workspace_slug,
|
|
agent_slug: &path.agent_slug,
|
|
credential,
|
|
correlation: transport_correlation,
|
|
continuation: ContinuationSupport::ElicitationUnsupported,
|
|
locale: execution_locale(message),
|
|
},
|
|
ToolsCommand::List(list_command),
|
|
// A list command has no progress or cancellation lifecycle (Story 3.4).
|
|
None,
|
|
)
|
|
.await;
|
|
match outcome {
|
|
ToolsOutcome::List { tools, next_cursor } => transport_response(
|
|
StatusCode::OK,
|
|
jsonrpc_result(
|
|
request_id(message),
|
|
crate::protocol::project_modern_cacheable_result(
|
|
version,
|
|
tools_list_result(tools, next_cursor),
|
|
),
|
|
),
|
|
response_mode,
|
|
None,
|
|
Some(version),
|
|
),
|
|
ToolsOutcome::InvalidParams(message_text) => transport_response(
|
|
StatusCode::OK,
|
|
jsonrpc_error(request_id(message), -32602, message_text),
|
|
response_mode,
|
|
None,
|
|
Some(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,
|
|
..
|
|
} => {
|
|
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(version),
|
|
);
|
|
}
|
|
};
|
|
|
|
// Validate the required name header against the body before anything is dispatched.
|
|
if let Err(response) =
|
|
validate_modern_request_name(message, headers, &tool_call_params.name)
|
|
{
|
|
return *response;
|
|
}
|
|
|
|
// 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). The modern era is
|
|
// session-less, so its calls cannot advertise elicitation support.
|
|
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` of this request, validated and bounded.
|
|
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: path.workspace_slug.clone(),
|
|
agent_slug: path.agent_slug.clone(),
|
|
credential: credential.clone(),
|
|
correlation: transport_correlation.clone(),
|
|
continuation: ContinuationSupport::ElicitationUnsupported,
|
|
locale: execution_locale(message),
|
|
},
|
|
crate::app::lifecycle::ToolCallWire {
|
|
message: message.clone(),
|
|
protocol_version: version.to_owned(),
|
|
response_mode,
|
|
progress,
|
|
session_id: None,
|
|
// The modern revision cancels by closing this request's response stream, so no
|
|
// session-scoped cancellation table is involved.
|
|
in_flight: None,
|
|
},
|
|
ToolCallCommand {
|
|
tool_name: tool_call_params.name,
|
|
arguments,
|
|
confirmation_token,
|
|
},
|
|
)
|
|
.await
|
|
}
|
|
DispatchDecision::Allowed {
|
|
handler: MethodHandler::ResourceList,
|
|
..
|
|
} => {
|
|
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(version),
|
|
);
|
|
}
|
|
};
|
|
let outcome = handle_resources_command(
|
|
state,
|
|
resource_service_context(path, credential, transport_correlation, message),
|
|
version,
|
|
ResourcesCommand::List(list_command),
|
|
)
|
|
.await;
|
|
match outcome {
|
|
ResourcesOutcome::Listed {
|
|
resources,
|
|
next_cursor,
|
|
} => transport_response(
|
|
StatusCode::OK,
|
|
jsonrpc_result(
|
|
request_id(message),
|
|
crate::protocol::project_modern_cacheable_result(
|
|
version,
|
|
resources_list_result(resources, next_cursor),
|
|
),
|
|
),
|
|
response_mode,
|
|
None,
|
|
Some(version),
|
|
),
|
|
ResourcesOutcome::InvalidParams(detail) => transport_response(
|
|
StatusCode::OK,
|
|
jsonrpc_error(request_id(message), -32602, detail),
|
|
response_mode,
|
|
None,
|
|
Some(version),
|
|
),
|
|
// A list command never produces these variants; a bound snapshot that cannot be
|
|
// verified is answered with the adapter's internal error instead of a partial page.
|
|
_ => internal_jsonrpc_error(message, "published resources are unavailable"),
|
|
}
|
|
}
|
|
DispatchDecision::Allowed {
|
|
handler: MethodHandler::ResourceRead,
|
|
..
|
|
} => {
|
|
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(version),
|
|
);
|
|
}
|
|
};
|
|
// The required `Mcp-Name` (the requested resource URI) is validated before the Resource
|
|
// handler runs, exactly as for `tools/call`.
|
|
if let Err(response) = validate_modern_request_name(message, headers, &read_command.uri)
|
|
{
|
|
return *response;
|
|
}
|
|
let outcome = handle_resources_command(
|
|
state,
|
|
resource_service_context(path, credential, transport_correlation, message),
|
|
version,
|
|
ResourcesCommand::Read(read_command),
|
|
)
|
|
.await;
|
|
match outcome {
|
|
ResourcesOutcome::Read { contents } => transport_response(
|
|
StatusCode::OK,
|
|
jsonrpc_result(
|
|
request_id(message),
|
|
crate::protocol::project_modern_cacheable_result(
|
|
version,
|
|
resource_read_result(contents),
|
|
),
|
|
),
|
|
response_mode,
|
|
None,
|
|
Some(version),
|
|
),
|
|
// One indistinguishable safe outcome for unknown/Draft/unbound/foreign URIs: no
|
|
// Resource metadata, digest, MIME or content is disclosed.
|
|
ResourcesOutcome::NotAvailable => transport_response(
|
|
StatusCode::OK,
|
|
jsonrpc_error(
|
|
request_id(message),
|
|
-32602,
|
|
"the requested resource is not available",
|
|
),
|
|
response_mode,
|
|
None,
|
|
Some(version),
|
|
),
|
|
ResourcesOutcome::InvalidParams(detail) => transport_response(
|
|
StatusCode::OK,
|
|
jsonrpc_error(request_id(message), -32602, detail),
|
|
response_mode,
|
|
None,
|
|
Some(version),
|
|
),
|
|
ResourcesOutcome::ExecutionError(contract) => {
|
|
resource_error_response(message, response_mode, version, contract)
|
|
}
|
|
_ => internal_jsonrpc_error(message, "published resources are unavailable"),
|
|
}
|
|
}
|
|
// Story 3.11: `resources/templates/list` comes from the shared service and contains only exact
|
|
// Published template versions bound to the active Agent snapshot. The modern revision receives
|
|
// its cacheable result envelope; the request declares no name, so only `Mcp-Method` is checked.
|
|
DispatchDecision::Allowed {
|
|
handler: MethodHandler::ResourceTemplateList,
|
|
..
|
|
} => {
|
|
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(version),
|
|
);
|
|
}
|
|
};
|
|
let (templates, next_cursor) = match list_resource_templates(
|
|
state,
|
|
&path.workspace_slug,
|
|
&path.agent_slug,
|
|
version,
|
|
command,
|
|
)
|
|
.await
|
|
{
|
|
Ok(page) => page,
|
|
Err(ResourceTemplatesListError::InvalidCursor) => {
|
|
return transport_response(
|
|
StatusCode::OK,
|
|
jsonrpc_error(
|
|
request_id(message),
|
|
-32602,
|
|
"invalid resources/templates/list cursor",
|
|
),
|
|
response_mode,
|
|
None,
|
|
Some(version),
|
|
);
|
|
}
|
|
Err(ResourceTemplatesListError::Unavailable) => {
|
|
return internal_jsonrpc_error(message, "published templates are unavailable");
|
|
}
|
|
};
|
|
transport_response(
|
|
StatusCode::OK,
|
|
jsonrpc_result(
|
|
request_id(message),
|
|
crate::protocol::project_modern_cacheable_result(
|
|
version,
|
|
resource_templates_list_result(templates, next_cursor),
|
|
),
|
|
),
|
|
response_mode,
|
|
None,
|
|
Some(version),
|
|
)
|
|
}
|
|
// Story 3.14: the standard Prompt requests. Missing name/header on `prompts/get` is a
|
|
// header-validation failure; the page is served only from exact bound Published versions.
|
|
DispatchDecision::Allowed {
|
|
handler: MethodHandler::PromptList,
|
|
..
|
|
} => {
|
|
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(version),
|
|
);
|
|
}
|
|
};
|
|
let outcome = handle_prompts_command(
|
|
state,
|
|
resource_service_context(path, credential, transport_correlation, message),
|
|
version,
|
|
PromptsCommand::List(command),
|
|
)
|
|
.await;
|
|
match outcome {
|
|
PromptsOutcome::Listed {
|
|
prompts,
|
|
next_cursor,
|
|
} => transport_response(
|
|
StatusCode::OK,
|
|
jsonrpc_result(
|
|
request_id(message),
|
|
crate::protocol::project_modern_cacheable_result(
|
|
version,
|
|
prompts_list_result(prompts, next_cursor),
|
|
),
|
|
),
|
|
response_mode,
|
|
None,
|
|
Some(version),
|
|
),
|
|
PromptsOutcome::InvalidParams(detail) => transport_response(
|
|
StatusCode::OK,
|
|
jsonrpc_error(request_id(message), -32602, detail),
|
|
response_mode,
|
|
None,
|
|
Some(version),
|
|
),
|
|
_ => internal_jsonrpc_error(message, "published prompts are unavailable"),
|
|
}
|
|
}
|
|
DispatchDecision::Allowed {
|
|
handler: MethodHandler::PromptGet,
|
|
..
|
|
} => {
|
|
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(version),
|
|
);
|
|
}
|
|
};
|
|
// The required `Mcp-Name` (the requested prompt name) is validated before the Prompt
|
|
// handler runs, exactly as for `resources/read` (matrix row 6).
|
|
if let Err(response) = validate_modern_request_name(message, headers, &command.name) {
|
|
return *response;
|
|
}
|
|
let outcome = handle_prompts_command(
|
|
state,
|
|
resource_service_context(path, credential, transport_correlation, message),
|
|
version,
|
|
PromptsCommand::Get(command),
|
|
)
|
|
.await;
|
|
match outcome {
|
|
PromptsOutcome::Got {
|
|
description,
|
|
messages,
|
|
} => transport_response(
|
|
StatusCode::OK,
|
|
jsonrpc_result(
|
|
request_id(message),
|
|
crate::protocol::project_modern_result(
|
|
version,
|
|
prompt_get_result(description, messages),
|
|
),
|
|
),
|
|
response_mode,
|
|
None,
|
|
Some(version),
|
|
),
|
|
// Unknown, Draft, foreign and unbound Prompt names share one safe outcome: no
|
|
// Prompt metadata and no message content is disclosed.
|
|
PromptsOutcome::NotAvailable => transport_response(
|
|
StatusCode::OK,
|
|
jsonrpc_error(
|
|
request_id(message),
|
|
-32602,
|
|
"the requested prompt is not available",
|
|
),
|
|
response_mode,
|
|
None,
|
|
Some(version),
|
|
),
|
|
PromptsOutcome::ArgumentsRejected { reason, argument } => {
|
|
prompt_arguments_error_response(
|
|
message,
|
|
response_mode,
|
|
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(version),
|
|
),
|
|
PromptsOutcome::InvalidParams(detail) => transport_response(
|
|
StatusCode::OK,
|
|
jsonrpc_error(request_id(message), -32602, detail),
|
|
response_mode,
|
|
None,
|
|
Some(version),
|
|
),
|
|
_ => internal_jsonrpc_error(message, "published prompts are unavailable"),
|
|
}
|
|
}
|
|
// Story 3.17: `completion/complete` answers from the same exact bound Published Prompt
|
|
// arguments and Resource template parameters the two listing methods serve. Its `ref` is a
|
|
// union of a Prompt name and a URI template, so the pinned era matrix requires only
|
|
// `Mcp-Method` here (`Mcp-Name` is required for `tools/call`, `resources/read`, `prompts/get`).
|
|
DispatchDecision::Allowed {
|
|
handler: MethodHandler::Completion,
|
|
..
|
|
} => {
|
|
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(version),
|
|
);
|
|
}
|
|
};
|
|
let outcome = handle_completion_command(
|
|
state,
|
|
resource_service_context(path, credential, transport_correlation, message),
|
|
version,
|
|
command,
|
|
)
|
|
.await;
|
|
match outcome {
|
|
CompletionOutcome::Completed {
|
|
values,
|
|
total,
|
|
has_more,
|
|
} => transport_response(
|
|
StatusCode::OK,
|
|
jsonrpc_result(
|
|
request_id(message),
|
|
crate::protocol::project_modern_result(
|
|
version,
|
|
completion_result(values, total, has_more),
|
|
),
|
|
),
|
|
response_mode,
|
|
None,
|
|
Some(version),
|
|
),
|
|
CompletionOutcome::InvalidParams(detail) => transport_response(
|
|
StatusCode::OK,
|
|
jsonrpc_error(request_id(message), -32602, detail),
|
|
response_mode,
|
|
None,
|
|
Some(version),
|
|
),
|
|
// Unknown, Draft, foreign and unbound references (and unknown argument names) share
|
|
// one safe answer: no Prompt name, URI template or option count is disclosed.
|
|
CompletionOutcome::NotAvailable => transport_response(
|
|
StatusCode::OK,
|
|
jsonrpc_error(
|
|
request_id(message),
|
|
-32602,
|
|
"the completion reference is not available",
|
|
),
|
|
response_mode,
|
|
None,
|
|
Some(version),
|
|
),
|
|
CompletionOutcome::CatalogUnavailable => {
|
|
internal_jsonrpc_error(message, "published completion sources are unavailable")
|
|
}
|
|
}
|
|
}
|
|
// Story 3.19: the modern long-lived notification stream. The response is itself the SSE
|
|
// stream that stays open, so it is built here instead of going through the one-shot
|
|
// response helpers: the acknowledgment is its first frame, then the coalesced list-change
|
|
// signals, and closing the HTTP stream ends the producer.
|
|
DispatchDecision::Allowed {
|
|
handler: MethodHandler::SubscriptionsListen,
|
|
..
|
|
} => {
|
|
// A notification stream is an SSE body by construction: a client that did not offer
|
|
// `text/event-stream` could not receive it.
|
|
if !crate::transport::accepts_event_stream(headers) {
|
|
return StatusCode::NOT_ACCEPTABLE.into_response();
|
|
}
|
|
let filter: crate::protocol::ListenParams =
|
|
match serde_json::from_value(params(message)) {
|
|
Ok(filter) => filter,
|
|
Err(_) => {
|
|
return transport_response(
|
|
StatusCode::OK,
|
|
jsonrpc_error(
|
|
request_id(message),
|
|
-32602,
|
|
crate::protocol::INVALID_LISTEN_FILTER,
|
|
),
|
|
response_mode,
|
|
None,
|
|
Some(version),
|
|
);
|
|
}
|
|
};
|
|
let accepted = match filter.notifications.accepted() {
|
|
crate::protocol::FilterOutcome::Accepted(accepted) => accepted,
|
|
crate::protocol::FilterOutcome::Invalid(detail) => {
|
|
return transport_response(
|
|
StatusCode::OK,
|
|
jsonrpc_error(request_id(message), -32602, detail),
|
|
response_mode,
|
|
None,
|
|
Some(version),
|
|
);
|
|
}
|
|
};
|
|
// The subscription id is the JSON-RPC id of this request; a value whose encoding is not
|
|
// bounded cannot be a frame identity carrier and is refused before the stream opens.
|
|
let Some(subscription_id) = crate::protocol::subscription_id(&request_id(message))
|
|
else {
|
|
return transport_response(
|
|
StatusCode::OK,
|
|
jsonrpc_error(request_id(message), -32600, "invalid JSON-RPC message"),
|
|
response_mode,
|
|
None,
|
|
Some(version),
|
|
);
|
|
};
|
|
let Ok(permit) = super::metrics::ActiveStreamGuard::try_acquire(&state.session_slots)
|
|
else {
|
|
return StatusCode::TOO_MANY_REQUESTS.into_response();
|
|
};
|
|
let acknowledged = crate::protocol::acknowledged_frame(&subscription_id, accepted);
|
|
let receiver = crate::protocol::spawn_signal_watch(
|
|
Arc::clone(state),
|
|
crate::protocol::Watch {
|
|
workspace_slug: path.workspace_slug.clone(),
|
|
agent_slug: path.agent_slug.clone(),
|
|
signals: accepted,
|
|
wire: crate::protocol::Wire::Modern(subscription_id),
|
|
legacy_stream: None,
|
|
deadline: None,
|
|
},
|
|
);
|
|
let stream = crate::protocol::frames_stream(vec![acknowledged], receiver, permit);
|
|
|
|
sse_response(StatusCode::OK, stream, None, Some(version))
|
|
}
|
|
// The standard Prompt requests are registered capabilities now; any other
|
|
// unregistered/wrong-era method goes straight to the era-correct unsupported answer.
|
|
_ => crate::protocol::modern_method_not_found_response(message),
|
|
}
|
|
}
|
|
|
|
/// The verified, era-neutral context of a Resource command: the same workspace/Agent/credential/
|
|
/// correlation the Tools service receives.
|
|
fn resource_service_context<'a>(
|
|
path: &'a AgentRoutePath,
|
|
credential: &'a VerifiedMachineCredential,
|
|
correlation: &'a CorrelationContext,
|
|
message: &Value,
|
|
) -> crate::protocol::ServiceContext<'a> {
|
|
crate::protocol::ServiceContext {
|
|
workspace_slug: &path.workspace_slug,
|
|
agent_slug: &path.agent_slug,
|
|
credential,
|
|
correlation,
|
|
continuation: crate::protocol::ContinuationSupport::ElicitationUnsupported,
|
|
locale: execution_locale(message),
|
|
}
|
|
}
|
|
|
|
pub(super) async fn handle_initialize(
|
|
state: Arc<AppState>,
|
|
path: &AgentRoutePath,
|
|
message: &Value,
|
|
response_mode: ResponseMode,
|
|
) -> Response {
|
|
let initialize_params: InitializeParams = match serde_json::from_value(params(message)) {
|
|
Ok(value) => value,
|
|
Err(_error) => {
|
|
return transport_response(
|
|
StatusCode::OK,
|
|
jsonrpc_error(request_id(message), -32602, "invalid initialize parameters"),
|
|
response_mode,
|
|
None,
|
|
None,
|
|
);
|
|
}
|
|
};
|
|
let Some(protocol_version) = negotiated_protocol_version(&initialize_params.protocol_version)
|
|
else {
|
|
// A revision outside the approved window is rejected without minting a session and without
|
|
// echoing any withdrawn revision as the served identity.
|
|
return transport_response(
|
|
StatusCode::BAD_REQUEST,
|
|
jsonrpc_error(
|
|
request_id(message),
|
|
-32602,
|
|
format!(
|
|
"unsupported protocol version {}",
|
|
initialize_params.protocol_version
|
|
),
|
|
),
|
|
response_mode,
|
|
None,
|
|
None,
|
|
);
|
|
};
|
|
let now = OffsetDateTime::now_utc();
|
|
let expires_at = add_millis(now, TRANSPORT_SESSION_TTL_MS);
|
|
let supports_elicitation = initialize_params
|
|
.capabilities
|
|
.get("elicitation")
|
|
.is_some_and(Value::is_object);
|
|
let session_id = match state
|
|
.sessions
|
|
.create(
|
|
protocol_version,
|
|
&path.workspace_slug,
|
|
&path.agent_slug,
|
|
supports_elicitation,
|
|
now,
|
|
Some(expires_at),
|
|
)
|
|
.await
|
|
{
|
|
Ok(session_id) => session_id,
|
|
Err(error) => return internal_jsonrpc_error(message, error),
|
|
};
|
|
state.session_metrics.refresh();
|
|
|
|
transport_response(
|
|
StatusCode::OK,
|
|
jsonrpc_result(
|
|
request_id(message),
|
|
json!( {
|
|
"protocolVersion": protocol_version,
|
|
"capabilities": crate::protocol::advertised_server_capabilities(protocol_version),
|
|
"serverInfo": {
|
|
"name": SERVER_NAME,
|
|
"version": SERVER_VERSION
|
|
}
|
|
}),
|
|
),
|
|
response_mode,
|
|
Some(&session_id),
|
|
Some(protocol_version),
|
|
)
|
|
}
|
|
|
|
pub(super) async fn handle_initialized_notification(
|
|
state: Arc<AppState>,
|
|
path: &AgentRoutePath,
|
|
headers: &HeaderMap,
|
|
) -> Response {
|
|
match session_id_from_headers(headers) {
|
|
Ok(Some(session_id)) => match state.sessions.get(&session_id).await {
|
|
Ok(Some(session))
|
|
if session.workspace_slug == path.workspace_slug
|
|
&& session.agent_slug == path.agent_slug =>
|
|
{
|
|
match state
|
|
.sessions
|
|
.mark_initialized(&session_id, OffsetDateTime::now_utc())
|
|
.await
|
|
{
|
|
Ok(true) => StatusCode::ACCEPTED.into_response(),
|
|
Ok(false) => StatusCode::NOT_FOUND.into_response(),
|
|
Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
|
|
}
|
|
}
|
|
Ok(Some(_)) => StatusCode::NOT_FOUND.into_response(),
|
|
Ok(None) => StatusCode::NOT_FOUND.into_response(),
|
|
Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
|
|
},
|
|
Ok(None) => StatusCode::BAD_REQUEST.into_response(),
|
|
Err(status) => status.into_response(),
|
|
}
|
|
}
|
|
|
|
pub(super) async fn require_initialized_session(
|
|
state: &Arc<AppState>,
|
|
path: &AgentRoutePath,
|
|
headers: &HeaderMap,
|
|
message: &Value,
|
|
) -> Result<SessionState, Response> {
|
|
let session_id = match session_id_from_headers(headers) {
|
|
Ok(Some(session_id)) => session_id,
|
|
Ok(None) => return Err(StatusCode::BAD_REQUEST.into_response()),
|
|
Err(status) => return Err(status.into_response()),
|
|
};
|
|
|
|
let Some(session) = (match state.sessions.get(&session_id).await {
|
|
Ok(session) => session,
|
|
Err(_) => return Err(StatusCode::INTERNAL_SERVER_ERROR.into_response()),
|
|
}) else {
|
|
return Err(StatusCode::NOT_FOUND.into_response());
|
|
};
|
|
|
|
if session.workspace_slug != path.workspace_slug || session.agent_slug != path.agent_slug {
|
|
return Err(StatusCode::NOT_FOUND.into_response());
|
|
}
|
|
|
|
if let Err(status) = crate::protocol::validate_session_revision(&session) {
|
|
return Err(status.into_response());
|
|
}
|
|
|
|
if !session.initialized {
|
|
return Err(json_response(
|
|
StatusCode::OK,
|
|
jsonrpc_error(request_id(message), -32002, "session is not initialized"),
|
|
None,
|
|
Some(&session.protocol_version),
|
|
));
|
|
}
|
|
|
|
Ok(session)
|
|
}
|
|
|
|
fn add_millis(timestamp: OffsetDateTime, millis: u64) -> OffsetDateTime {
|
|
let delta = time::Duration::milliseconds(i64::try_from(millis).unwrap_or(i64::MAX));
|
|
|
|
timestamp + delta
|
|
}
|