Files
crank/crates/crank-community-mcp/src/app/response.rs
T
Hermes DevOps 75fe5a123c [skip ci] wip: preserve Hermes crank development checkpoint
Owner-authorized recovery of accumulated source changes.
Includes accepted work and in-progress changes; NOT a release or acceptance.
Parent baseline 1b6db09bd1. Runtime data, build caches and local credentials excluded.
2026-10-25 10:00:22 +00:00

287 lines
9.8 KiB
Rust

use axum::{http::StatusCode, response::Response};
use serde_json::{Value, json};
use crate::{
jsonrpc::{jsonrpc_result, request_id},
protocol::project_modern_result,
tool_error::{ToolErrorContract, tool_error_text, tool_error_value},
transport::{ResponseMode, transport_response},
};
use crate::jsonrpc::jsonrpc_error;
use crate::protocol::{ToolCallOutcome, ToolsOutcome};
use crate::tool_error::{control_tool_error_contract, execution_locale};
use crank_core::CorrelationContext;
pub(crate) fn take_confirmation_token(arguments: &mut Value) -> Option<String> {
let Value::Object(object) = arguments else {
return None;
};
object
.remove("_crank_confirmation_token")
.and_then(|value| value.as_str().map(str::to_owned))
.filter(|value| !value.trim().is_empty())
}
pub(crate) fn success_tool_response(
message: &Value,
response_mode: ResponseMode,
protocol_version: &str,
output: Value,
) -> Response {
transport_response(
StatusCode::OK,
jsonrpc_result(
request_id(message),
project_modern_result(
protocol_version,
json!({
"content": [
{
"type": "text",
"text": serde_json::to_string_pretty(&output).unwrap_or_else(|_| "{}".to_owned())
}
],
"structuredContent": output,
"isError": false
}),
),
),
response_mode,
None,
Some(protocol_version),
)
}
pub(crate) fn tool_error_response(
message: &Value,
response_mode: ResponseMode,
protocol_version: &str,
error: ToolErrorContract,
) -> Response {
let error_message = tool_error_text(&error);
let error_value = tool_error_value(&error);
transport_response(
StatusCode::OK,
jsonrpc_result(
request_id(message),
project_modern_result(
protocol_version,
json!({
"content": [
{
"type": "text",
"text": error_message
}
],
"structuredContent": {
"error": error_value
},
"isError": true
}),
),
),
response_mode,
None,
Some(protocol_version),
)
}
/// The era-neutral `tools/list` result shape built from the shared command outcome. Object keys end
/// up byte-lexicographically ordered, exactly as before the extraction.
pub(super) fn tools_list_result(tools: Vec<Value>, next_cursor: Option<String>) -> Value {
let mut result = json!({ "tools": tools });
if let Some(next_cursor) = next_cursor {
result["nextCursor"] = Value::String(next_cursor);
}
result
}
/// The era-neutral `resources/list` result shape (Story 3.8). Same pagination wire keys as
/// `tools/list`; `nextCursor` is absent on the last page.
pub(super) fn resources_list_result(resources: Vec<Value>, next_cursor: Option<String>) -> Value {
let mut result = json!({ "resources": resources });
if let Some(next_cursor) = next_cursor {
result["nextCursor"] = Value::String(next_cursor);
}
result
}
/// The era-neutral `resources/read` result shape: exactly the typed `contents[]` the revision
/// converter produced.
pub(super) fn resource_read_result(contents: Value) -> Value {
json!({ "contents": contents })
}
/// The era-neutral `resources/templates/list` result shape.
pub(super) fn resource_templates_list_result(
templates: Vec<Value>,
next_cursor: Option<String>,
) -> Value {
let mut result = json!({ "resourceTemplates": templates });
if let Some(cursor) = next_cursor {
result["nextCursor"] = Value::String(cursor);
}
result
}
/// The era-neutral `prompts/list` result shape (Story 3.14). Same pagination wire keys as
/// `resources/list`; `nextCursor` is absent on the last page.
pub(super) fn prompts_list_result(prompts: Vec<Value>, next_cursor: Option<String>) -> Value {
let mut result = json!({ "prompts": prompts });
if let Some(cursor) = next_cursor {
result["nextCursor"] = Value::String(cursor);
}
result
}
/// The era-neutral `prompts/get` result shape: the rendered `messages[]` and the description of the
/// exact bound Published Prompt Version it came from.
pub(super) fn prompt_get_result(description: Option<String>, messages: Vec<Value>) -> Value {
let mut result = json!({ "messages": messages });
if let Some(description) = description {
result["description"] = Value::String(description);
}
result
}
/// The era-neutral `completion/complete` result shape (Story 3.17): the bounded `values[]`, the
/// option count where it is known exactly, and whether more options exist. Both supported revisions
/// declare the same `completion` object, so this shape is shared.
pub(super) fn completion_result(
values: Vec<String>,
total: Option<usize>,
has_more: bool,
) -> Value {
let mut completion = json!({ "values": values });
if let Some(total) = total {
completion["total"] = json!(total);
}
if has_more {
completion["hasMore"] = json!(true);
}
json!({ "completion": completion })
}
/// The structured `prompts/get` argument rejection (AT-3.14-02): a `-32602` error whose `data`
/// carries the typed reason and the argument name of the bound Prompt. No rendered message,
/// dependency content or other Prompt metadata is attached — the rejection happens before rendering.
pub(super) fn prompt_arguments_error_response(
message: &Value,
response_mode: ResponseMode,
protocol_version: &str,
reason: &str,
argument: Option<String>,
) -> Response {
let mut error = jsonrpc_error(
request_id(message),
-32602,
"the prompt arguments were rejected".to_owned(),
);
error["error"]["data"] = crate::jsonrpc::correlated_error_data(json!({
"reason": reason,
"argument": argument,
}));
transport_response(
StatusCode::OK,
error,
response_mode,
None,
Some(protocol_version),
)
}
/// Map one shared Tools-command outcome back to the era-specific wire response (spec section 6.2).
///
/// This adapter function is the only place that turns a neutral outcome into a response: the shared
/// service never sees `ResponseMode`, the protocol revision, the request envelope or an
/// `axum::Response`. `ApprovalPending` is a success for the client (it still has to answer), while
/// an unavailable elicitation and a failing call keep their era-correct tool-error shape.
pub(super) fn tool_command_response(
message: &Value,
response_mode: ResponseMode,
protocol_version: &str,
correlation: &CorrelationContext,
outcome: ToolsOutcome,
) -> Response {
match outcome {
ToolsOutcome::Call(ToolCallOutcome::Completed(output))
| ToolsOutcome::Call(ToolCallOutcome::ApprovalPending(output)) => {
success_tool_response(message, response_mode, protocol_version, output)
}
ToolsOutcome::Call(ToolCallOutcome::ApprovalUnavailable(control_error)) => {
tool_error_response(
message,
response_mode,
protocol_version,
control_tool_error_contract(
control_error,
correlation.request_id().as_str(),
correlation.trace_id().as_str(),
execution_locale(message),
),
)
}
ToolsOutcome::Call(ToolCallOutcome::InvalidParams(detail)) => transport_response(
StatusCode::OK,
jsonrpc_error(request_id(message), -32602, detail),
response_mode,
None,
Some(protocol_version),
),
ToolsOutcome::Call(ToolCallOutcome::Error(contract)) => {
tool_error_response(message, response_mode, protocol_version, contract)
}
// The pending approval could not be persisted: the adapter answers its internal error shape,
// as the previous wire path did.
ToolsOutcome::Call(ToolCallOutcome::InternalFailure) => internal_jsonrpc_error(
message,
"the pending approval request could not be persisted",
),
// A call command never produces these variants; they are answered with the adapter's
// internal error instead of being silently ignored.
ToolsOutcome::List { .. }
| ToolsOutcome::InvalidParams(_)
| ToolsOutcome::CatalogUnavailable => {
internal_jsonrpc_error(message, "unexpected shared tools outcome for a tools/call")
}
}
}
pub(super) fn resource_error_response(
message: &Value,
response_mode: ResponseMode,
protocol_version: &str,
contract: ToolErrorContract,
) -> Response {
let mut error = jsonrpc_error(request_id(message), -32000, contract.message.clone());
error["error"]["data"] = json!({
"code": contract.code,
"error_code": contract.error_code,
"stage": contract.stage,
"retryability": contract.retryability,
"outcome_certainty": contract.outcome_certainty,
"request_id": contract.request_id,
"trace_id": contract.trace_id,
});
transport_response(
StatusCode::OK,
error,
response_mode,
None,
Some(protocol_version),
)
}
pub(super) fn internal_jsonrpc_error(message: &Value, _error: impl std::fmt::Display) -> Response {
transport_response(
StatusCode::INTERNAL_SERVER_ERROR,
jsonrpc_error(request_id(message), -32603, "internal server error"),
ResponseMode::Json,
None,
None,
)
}