feat(epic3): deliver the accepted Epic 3 scope through Story 3.17
CI / Rust Checks (pull_request) Failing after 13m41s
CI / UI Checks (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Deploy (pull_request) Skipped
Community Release / release (push) Failing after 13m33s
CI / Rust Checks (pull_request) Failing after 13m41s
CI / UI Checks (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Deploy (pull_request) Skipped
Community Release / release (push) Failing after 13m33s
Recovery delivery of the accumulated, TL-accepted Epic 3 work that had never been
committed to Git (stories 3.6-3.17, see the crank board). Story 3.18 is not accepted
yet and is deliberately excluded: its logging surface, its capability registration,
its oracle projections and its tests are not part of this tree.
Accepted scope
- 3.6 typed static Resource Drafts; 3.7 publication and exact binding of static
Resource Versions; 3.8 MCP discovery/read and revocation of static Resources;
- 3.9 Resource import/export in API and UI plus TLS dependency maintenance;
3.10 REST-backed Resource templates; 3.11 shared REST read runtime and the MCP
revision/capability foundation;
- 3.12 parameterised Prompt Drafts with preview; 3.13 Prompt publication and exact
version binding to Agents; 3.14 MCP prompts; 3.15 Prompt import/export;
- 3.16 composite Prompts with published Resources (dependency content scan plus
dynamic read through the accepted 3.11 runtime, admin preview and MCP prompts/get);
- 3.17 bounded MCP completion suggestions from typed published schemas and the
resources/list admission fix for bound template publications.
Accepted evidence being reused (unchanged code paths)
- 3.16 candidate: core 7, admin-api 22, registry 4, mcp-server 4, UI 6; one final
`just verify` run 1651 passed / 0 failed / 2 ignored.
- 3.17 candidate: full run 1672 passed / 0 failed / 2 ignored, QA targeted reruns and
a real MCP Inspector 2.12.0 client smoke.
Delivery engineering in this commit
- CI: one event per change (feature branches are gated by their pull request, push
runs only on main), story events run the changed packages, the full workspace suite
stays the feature/release gate; no cache/sharding without a measured runner check.
- Release: the packaged archives, checksums and SBOM are now uploaded to the Gitea
release entry of the tag instead of dying with the runner workspace.
Not included on purpose: Story 3.18 work, build caches, runtime databases, local
credentials and scratch evidence.
Refs: crank kanban t_e39d7263; baseline 1b6db09bd1.
This commit is contained in:
1 parent
1b6db09bd1
commit
54ce770682
357 files changed
+117394
-5115
No files matched your search
@@ -1,6 +1,5 @@
|
||||
use std::{sync::Arc, time::Duration};
|
||||
|
||||
use axum::response::Response;
|
||||
use crank_core::{
|
||||
ApprovalRequest, ApprovalRequestId, ApprovalRequestStatus, CorrelationContext, InvocationLevel,
|
||||
InvocationStatus, OperationApprovalMode,
|
||||
@@ -10,39 +9,45 @@ use crank_trace::{DbOperation, observe_db_query};
|
||||
use serde_json::{Value, json};
|
||||
use time::OffsetDateTime;
|
||||
|
||||
use super::{
|
||||
AppState, InvocationRecord, internal_jsonrpc_error, persist_invocation_for_key,
|
||||
response::{success_tool_response, tool_error_response},
|
||||
};
|
||||
use super::{AppState, InvocationRecord, persist_invocation_for_key};
|
||||
use crate::{
|
||||
approval_response::{
|
||||
approval_history_request_preview, approval_history_response_preview,
|
||||
approval_required_response,
|
||||
},
|
||||
session::SessionState,
|
||||
tool_error::{McpControlError, control_tool_error_contract, execution_locale},
|
||||
transport::ResponseMode,
|
||||
protocol::ContinuationSupport,
|
||||
};
|
||||
|
||||
pub(super) enum ApprovalPolicyResult {
|
||||
Required(Response),
|
||||
Error(Response),
|
||||
/// Era-neutral outcome of the approval policy of one Tools call (R8, spec section 6.2).
|
||||
///
|
||||
/// The policy no longer builds a wire response: `Pending` carries the domain payload that the
|
||||
/// adapter turns into its era-correct success shape, and the two failure cases are named so the
|
||||
/// adapter — the only place that knows the response mode, the protocol revision and the request
|
||||
/// envelope — can answer with the shape it owns.
|
||||
pub(crate) enum ApprovalPolicyDecision {
|
||||
/// The operation waits for a human decision; the payload is the approval disclosure.
|
||||
Pending(Value),
|
||||
/// The client cannot complete the elicitation the policy requires; the adapter answers the
|
||||
/// era-correct tool error for `McpControlError::ApprovalElicitationNotSupported`.
|
||||
ElicitationUnavailable,
|
||||
/// The pending approval could not be persisted; the adapter answers its internal error shape.
|
||||
StorageFailed,
|
||||
}
|
||||
|
||||
pub(super) struct ApprovalPolicyContext<'a> {
|
||||
/// Verified, wire-free inputs of one approval decision.
|
||||
pub(crate) struct ApprovalPolicyContext<'a> {
|
||||
pub state: &'a Arc<AppState>,
|
||||
pub session: &'a SessionState,
|
||||
pub message: &'a Value,
|
||||
pub response_mode: ResponseMode,
|
||||
pub tool: &'a PublishedAgentTool,
|
||||
pub arguments: &'a Value,
|
||||
pub platform_api_key_id: Option<&'a crank_core::PlatformApiKeyId>,
|
||||
pub transport_correlation: &'a CorrelationContext,
|
||||
pub correlation: &'a CorrelationContext,
|
||||
pub continuation: ContinuationSupport,
|
||||
}
|
||||
|
||||
pub(super) async fn maybe_handle_approval_policy(
|
||||
/// `None` means "no approval is required, the call may proceed".
|
||||
pub(crate) async fn maybe_handle_approval_policy(
|
||||
context: ApprovalPolicyContext<'_>,
|
||||
) -> Option<ApprovalPolicyResult> {
|
||||
) -> Option<ApprovalPolicyDecision> {
|
||||
let policy = context
|
||||
.tool
|
||||
.operation
|
||||
@@ -55,32 +60,22 @@ pub(super) async fn maybe_handle_approval_policy(
|
||||
|
||||
match policy.mode {
|
||||
OperationApprovalMode::Custom => maybe_create_custom_pending_approval(&context).await,
|
||||
OperationApprovalMode::Elicitation => Some(handle_elicitation_approval(
|
||||
context.session,
|
||||
context.message,
|
||||
context.response_mode,
|
||||
context.tool,
|
||||
context.arguments,
|
||||
policy.elicitation_message.as_deref(),
|
||||
context.transport_correlation,
|
||||
)),
|
||||
OperationApprovalMode::Elicitation => Some(handle_elicitation_approval(&context)),
|
||||
}
|
||||
}
|
||||
|
||||
async fn maybe_create_custom_pending_approval(
|
||||
context: &ApprovalPolicyContext<'_>,
|
||||
) -> Option<ApprovalPolicyResult> {
|
||||
) -> Option<ApprovalPolicyDecision> {
|
||||
let ApprovalPolicyContext {
|
||||
state,
|
||||
session,
|
||||
message,
|
||||
response_mode,
|
||||
tool,
|
||||
arguments,
|
||||
platform_api_key_id,
|
||||
transport_correlation,
|
||||
correlation,
|
||||
..
|
||||
} = context;
|
||||
let transport_request_id = transport_correlation.request_id().as_str();
|
||||
let transport_request_id = correlation.request_id().as_str();
|
||||
let policy = tool.operation.execution_config.approval_policy.as_ref()?;
|
||||
|
||||
let approval_id = ApprovalRequestId::new(format!("approval_{}", uuid::Uuid::now_v7().simple()));
|
||||
@@ -94,8 +89,8 @@ async fn maybe_create_custom_pending_approval(
|
||||
operation_version: tool.operation.version,
|
||||
status: ApprovalRequestStatus::Pending,
|
||||
risk_level: policy.risk_level,
|
||||
request_id: Some(transport_correlation.request_id().as_str().to_owned()),
|
||||
trace_id: Some(transport_correlation.trace_id().as_str().to_owned()),
|
||||
request_id: Some(correlation.request_id().as_str().to_owned()),
|
||||
trace_id: Some(correlation.trace_id().as_str().to_owned()),
|
||||
request_payload: (*arguments).clone(),
|
||||
response_payload: None,
|
||||
created_at: now,
|
||||
@@ -116,11 +111,7 @@ async fn maybe_create_custom_pending_approval(
|
||||
.await
|
||||
{
|
||||
Ok(approval) => approval,
|
||||
Err(error) => {
|
||||
return Some(ApprovalPolicyResult::Error(internal_jsonrpc_error(
|
||||
message, error,
|
||||
)));
|
||||
}
|
||||
Err(_error) => return Some(ApprovalPolicyDecision::StorageFailed),
|
||||
};
|
||||
let response_payload = approval_required_response(tool, &persisted_approval.approval, policy);
|
||||
|
||||
@@ -130,7 +121,7 @@ async fn maybe_create_custom_pending_approval(
|
||||
*platform_api_key_id,
|
||||
InvocationRecord {
|
||||
request_id: Some(transport_request_id),
|
||||
trace_id: Some(transport_correlation.trace_id().as_str()),
|
||||
trace_id: Some(correlation.trace_id().as_str()),
|
||||
tool_name: &tool.tool_name,
|
||||
status: InvocationStatus::Ok,
|
||||
level: InvocationLevel::Info,
|
||||
@@ -148,56 +139,33 @@ async fn maybe_create_custom_pending_approval(
|
||||
)
|
||||
.await;
|
||||
|
||||
Some(ApprovalPolicyResult::Required(success_tool_response(
|
||||
message,
|
||||
*response_mode,
|
||||
&session.protocol_version,
|
||||
response_payload,
|
||||
)))
|
||||
Some(ApprovalPolicyDecision::Pending(response_payload))
|
||||
}
|
||||
|
||||
fn handle_elicitation_approval(
|
||||
session: &SessionState,
|
||||
message: &Value,
|
||||
response_mode: ResponseMode,
|
||||
tool: &PublishedAgentTool,
|
||||
arguments: &Value,
|
||||
elicitation_message: Option<&str>,
|
||||
transport_correlation: &CorrelationContext,
|
||||
) -> ApprovalPolicyResult {
|
||||
let transport_request_id = transport_correlation.request_id().as_str();
|
||||
if !session.supports_elicitation {
|
||||
return ApprovalPolicyResult::Error(tool_error_response(
|
||||
message,
|
||||
response_mode,
|
||||
&session.protocol_version,
|
||||
control_tool_error_contract(
|
||||
McpControlError::ApprovalElicitationNotSupported,
|
||||
transport_request_id,
|
||||
transport_correlation.trace_id().as_str(),
|
||||
execution_locale(message),
|
||||
),
|
||||
));
|
||||
fn handle_elicitation_approval(context: &ApprovalPolicyContext<'_>) -> ApprovalPolicyDecision {
|
||||
let ApprovalPolicyContext {
|
||||
tool,
|
||||
arguments,
|
||||
continuation,
|
||||
..
|
||||
} = context;
|
||||
if !continuation.supports_elicitation() {
|
||||
return ApprovalPolicyDecision::ElicitationUnavailable;
|
||||
}
|
||||
|
||||
let payload_preview = tool
|
||||
.operation
|
||||
.execution_config
|
||||
.approval_policy
|
||||
.as_ref()
|
||||
.and_then(|policy| policy.show_payload_preview.then(|| arguments.clone()))
|
||||
let policy = tool.operation.execution_config.approval_policy.as_ref();
|
||||
let payload_preview = policy
|
||||
.and_then(|policy| policy.show_payload_preview.then(|| (*arguments).clone()))
|
||||
.unwrap_or(Value::Null);
|
||||
let elicitation_message = policy
|
||||
.and_then(|policy| policy.elicitation_message.clone())
|
||||
.unwrap_or_else(|| "Confirm operation execution.".to_owned());
|
||||
|
||||
ApprovalPolicyResult::Required(success_tool_response(
|
||||
message,
|
||||
response_mode,
|
||||
&session.protocol_version,
|
||||
json!({
|
||||
"status": "elicitation_required",
|
||||
"message": elicitation_message.unwrap_or("Confirm operation execution."),
|
||||
"tool": tool.tool_name,
|
||||
"payload_preview": payload_preview,
|
||||
"note": "This MCP client advertised elicitation support. Full elicitation/create continuation is handled by compatible client integrations.",
|
||||
}),
|
||||
))
|
||||
ApprovalPolicyDecision::Pending(json!({
|
||||
"status": "elicitation_required",
|
||||
"message": elicitation_message,
|
||||
"tool": tool.tool_name,
|
||||
"payload_preview": payload_preview,
|
||||
"note": "This MCP client advertised elicitation support. Full elicitation/create continuation is handled by compatible client integrations.",
|
||||
}))
|
||||
}
|
||||
@@ -0,0 +1,350 @@
|
||||
//! Approval HTTP surface: listing/reading pending approvals and the approve/deny decisions,
|
||||
//! including the era-neutral decision projections.
|
||||
//!
|
||||
//! Moved verbatim out of `app.rs` (Story 3.6, kanban t_987bf309); it is wired only from
|
||||
//! `build_app_inner`, so every handler here is `pub(super)`. No behaviour, status code, header or
|
||||
//! payload changed.
|
||||
|
||||
use super::request::ApprovalDecisionPayload;
|
||||
use super::stages::{enforce_traced_rate_limit, require_traced_approval_access};
|
||||
use crate::{
|
||||
approval_execution::execute_approved_request, rate_limit::rate_limited_status_response,
|
||||
request_context::RequestContext,
|
||||
};
|
||||
use axum::{
|
||||
Json,
|
||||
extract::{Extension, Path, State},
|
||||
http::{HeaderMap, StatusCode},
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
use crank_core::{
|
||||
ApprovalRequestId, ApprovalRequestStatus, CorrelationContext, PlatformApiKeyScope,
|
||||
};
|
||||
use crank_registry::{ApprovalRequestRecord, DecideApprovalRequest, ExpireApprovalRequest};
|
||||
use crank_trace::{DbOperation, observe_db_query};
|
||||
use serde_json::json;
|
||||
use std::sync::Arc;
|
||||
use time::OffsetDateTime;
|
||||
|
||||
use super::{AgentRoutePath, AppState, ApprovalRoutePath};
|
||||
pub(super) async fn list_pending_approvals(
|
||||
Path(path): Path<AgentRoutePath>,
|
||||
State(state): State<Arc<AppState>>,
|
||||
headers: HeaderMap,
|
||||
) -> Response {
|
||||
if let Err(rejection) = enforce_traced_rate_limit(&state, &path, &headers).await {
|
||||
return rate_limited_status_response(rejection);
|
||||
}
|
||||
|
||||
let key = match require_traced_approval_access(
|
||||
&state,
|
||||
&path,
|
||||
&headers,
|
||||
PlatformApiKeyScope::ReadPending,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(key) => key,
|
||||
Err(status) => return status.into_response(),
|
||||
};
|
||||
|
||||
let Some(agent_id) = key.api_key.agent_id.as_ref() else {
|
||||
return StatusCode::FORBIDDEN.into_response();
|
||||
};
|
||||
|
||||
match observe_db_query(
|
||||
DbOperation::ApprovalRead,
|
||||
state
|
||||
.registry
|
||||
.list_pending_approval_requests_for_agent(&key.api_key.workspace_id, agent_id),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(items) => Json(json!({
|
||||
"items": items.into_iter().map(safe_approval_record).collect::<Vec<_>>()
|
||||
}))
|
||||
.into_response(),
|
||||
Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn approve_request(
|
||||
Path(path): Path<ApprovalRoutePath>,
|
||||
State(state): State<Arc<AppState>>,
|
||||
Extension(request_context): Extension<RequestContext>,
|
||||
headers: HeaderMap,
|
||||
Json(payload): Json<ApprovalDecisionPayload>,
|
||||
) -> Response {
|
||||
decide_approval_request(
|
||||
path,
|
||||
state,
|
||||
headers,
|
||||
payload,
|
||||
PlatformApiKeyScope::Approve,
|
||||
ApprovalRequestStatus::Approved,
|
||||
Some(request_context.correlation),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub(super) async fn get_approval_request(
|
||||
Path(path): Path<ApprovalRoutePath>,
|
||||
State(state): State<Arc<AppState>>,
|
||||
headers: HeaderMap,
|
||||
) -> Response {
|
||||
let agent_path = AgentRoutePath {
|
||||
workspace_slug: path.workspace_slug,
|
||||
agent_slug: path.agent_slug,
|
||||
};
|
||||
if let Err(rejection) = enforce_traced_rate_limit(&state, &agent_path, &headers).await {
|
||||
return rate_limited_status_response(rejection);
|
||||
}
|
||||
|
||||
let key = match require_traced_approval_access(
|
||||
&state,
|
||||
&agent_path,
|
||||
&headers,
|
||||
PlatformApiKeyScope::ReadPending,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(key) => key,
|
||||
Err(status) => return status.into_response(),
|
||||
};
|
||||
let Some(agent_id) = key.api_key.agent_id.as_ref() else {
|
||||
return StatusCode::FORBIDDEN.into_response();
|
||||
};
|
||||
let approval_id = ApprovalRequestId::new(path.approval_id);
|
||||
|
||||
approval_record_response(&state, &key.api_key.workspace_id, agent_id, &approval_id).await
|
||||
}
|
||||
|
||||
pub(super) async fn deny_request(
|
||||
Path(path): Path<ApprovalRoutePath>,
|
||||
State(state): State<Arc<AppState>>,
|
||||
headers: HeaderMap,
|
||||
Json(payload): Json<ApprovalDecisionPayload>,
|
||||
) -> Response {
|
||||
decide_approval_request(
|
||||
path,
|
||||
state,
|
||||
headers,
|
||||
payload,
|
||||
PlatformApiKeyScope::Deny,
|
||||
ApprovalRequestStatus::Denied,
|
||||
None,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn decide_approval_request(
|
||||
path: ApprovalRoutePath,
|
||||
state: Arc<AppState>,
|
||||
headers: HeaderMap,
|
||||
payload: ApprovalDecisionPayload,
|
||||
required_scope: PlatformApiKeyScope,
|
||||
status: ApprovalRequestStatus,
|
||||
execution_correlation: Option<CorrelationContext>,
|
||||
) -> Response {
|
||||
let agent_path = AgentRoutePath {
|
||||
workspace_slug: path.workspace_slug,
|
||||
agent_slug: path.agent_slug,
|
||||
};
|
||||
if let Err(rejection) = enforce_traced_rate_limit(&state, &agent_path, &headers).await {
|
||||
return rate_limited_status_response(rejection);
|
||||
}
|
||||
|
||||
let key =
|
||||
match require_traced_approval_access(&state, &agent_path, &headers, required_scope).await {
|
||||
Ok(key) => key,
|
||||
Err(status) => return status.into_response(),
|
||||
};
|
||||
|
||||
if (status == ApprovalRequestStatus::Approved && !payload.approve.eq_ignore_ascii_case("yes"))
|
||||
|| (status == ApprovalRequestStatus::Denied && !payload.approve.eq_ignore_ascii_case("no"))
|
||||
{
|
||||
return (
|
||||
StatusCode::BAD_REQUEST,
|
||||
Json(json!({
|
||||
"error": "invalid_decision_payload",
|
||||
"message": "approve must be yes for approve endpoint and no for deny endpoint"
|
||||
})),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
|
||||
let Some(agent_id) = key.api_key.agent_id.as_ref() else {
|
||||
return StatusCode::FORBIDDEN.into_response();
|
||||
};
|
||||
let approval_id = ApprovalRequestId::new(path.approval_id);
|
||||
|
||||
let expected_record = match observe_db_query(
|
||||
DbOperation::ApprovalRead,
|
||||
state.registry.get_approval_request_for_agent(
|
||||
&key.api_key.workspace_id,
|
||||
agent_id,
|
||||
&approval_id,
|
||||
),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(Some(record)) => record,
|
||||
Ok(None) => return StatusCode::NOT_FOUND.into_response(),
|
||||
Err(_) => return StatusCode::INTERNAL_SERVER_ERROR.into_response(),
|
||||
};
|
||||
|
||||
match observe_db_query(
|
||||
DbOperation::ApprovalWrite,
|
||||
state
|
||||
.registry
|
||||
.decide_approval_request(DecideApprovalRequest {
|
||||
workspace_id: &key.api_key.workspace_id,
|
||||
agent_id,
|
||||
approval_id: &approval_id,
|
||||
operation_id: &expected_record.approval.operation_id,
|
||||
operation_version: expected_record.approval.operation_version,
|
||||
request_payload: &expected_record.approval.request_payload,
|
||||
status,
|
||||
decided_at: OffsetDateTime::now_utc(),
|
||||
decided_by_key_id: Some(&key.api_key.id),
|
||||
response_payload: Some(json!({ "approve": payload.approve })),
|
||||
decision_note: payload.note.as_deref(),
|
||||
}),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(Some(record)) if status == ApprovalRequestStatus::Approved => {
|
||||
let claimed = match observe_db_query(
|
||||
DbOperation::ApprovalWrite,
|
||||
state.registry.claim_approval_request(
|
||||
&record.approval.workspace_id,
|
||||
&record.approval.agent_id,
|
||||
&record.approval.id,
|
||||
OffsetDateTime::now_utc(),
|
||||
),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(Some(claimed)) => claimed,
|
||||
Ok(None) => return StatusCode::CONFLICT.into_response(),
|
||||
Err(_) => return StatusCode::INTERNAL_SERVER_ERROR.into_response(),
|
||||
};
|
||||
match execute_approved_request(
|
||||
&state,
|
||||
&agent_path,
|
||||
claimed,
|
||||
execution_correlation.as_ref(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(record) => Json(json!(safe_approval_record(record))).into_response(),
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
Ok(Some(record)) => Json(json!(safe_approval_record(record))).into_response(),
|
||||
Ok(None) => {
|
||||
terminal_decision_response(&state, &key.api_key.workspace_id, agent_id, &approval_id)
|
||||
.await
|
||||
}
|
||||
Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
async fn approval_record_response(
|
||||
state: &Arc<AppState>,
|
||||
workspace_id: &crank_core::WorkspaceId,
|
||||
agent_id: &crank_core::AgentId,
|
||||
approval_id: &ApprovalRequestId,
|
||||
) -> Response {
|
||||
match observe_db_query(
|
||||
DbOperation::ApprovalRead,
|
||||
state
|
||||
.registry
|
||||
.get_approval_request_for_agent(workspace_id, agent_id, approval_id),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(Some(record))
|
||||
if record.approval.status == ApprovalRequestStatus::Pending
|
||||
&& record.approval.expires_at <= OffsetDateTime::now_utc() =>
|
||||
{
|
||||
expire_approval_response(state, workspace_id, agent_id, approval_id).await
|
||||
}
|
||||
Ok(Some(record)) => Json(json!(safe_approval_record(record))).into_response(),
|
||||
Ok(None) => StatusCode::NOT_FOUND.into_response(),
|
||||
Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
async fn terminal_decision_response(
|
||||
state: &Arc<AppState>,
|
||||
workspace_id: &crank_core::WorkspaceId,
|
||||
agent_id: &crank_core::AgentId,
|
||||
approval_id: &ApprovalRequestId,
|
||||
) -> Response {
|
||||
match observe_db_query(
|
||||
DbOperation::ApprovalRead,
|
||||
state
|
||||
.registry
|
||||
.get_approval_request_for_agent(workspace_id, agent_id, approval_id),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(Some(record))
|
||||
if record.approval.status == ApprovalRequestStatus::Pending
|
||||
&& record.approval.expires_at <= OffsetDateTime::now_utc() =>
|
||||
{
|
||||
expire_approval_response(state, workspace_id, agent_id, approval_id).await
|
||||
}
|
||||
Ok(Some(record))
|
||||
if matches!(
|
||||
record.approval.status,
|
||||
ApprovalRequestStatus::Completed
|
||||
| ApprovalRequestStatus::Failed
|
||||
| ApprovalRequestStatus::Denied
|
||||
| ApprovalRequestStatus::Expired
|
||||
) =>
|
||||
{
|
||||
Json(json!(safe_approval_record(record))).into_response()
|
||||
}
|
||||
Ok(Some(_)) => StatusCode::CONFLICT.into_response(),
|
||||
Ok(None) => StatusCode::NOT_FOUND.into_response(),
|
||||
Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
fn safe_approval_record(mut record: ApprovalRequestRecord) -> ApprovalRequestRecord {
|
||||
record.approval.request_payload =
|
||||
crank_core::sanitize_invocation_preview(&record.approval.request_payload);
|
||||
record.approval.response_payload = record
|
||||
.approval
|
||||
.response_payload
|
||||
.as_ref()
|
||||
.map(crank_core::sanitize_invocation_preview);
|
||||
record
|
||||
}
|
||||
|
||||
async fn expire_approval_response(
|
||||
state: &Arc<AppState>,
|
||||
workspace_id: &crank_core::WorkspaceId,
|
||||
agent_id: &crank_core::AgentId,
|
||||
approval_id: &ApprovalRequestId,
|
||||
) -> Response {
|
||||
match observe_db_query(
|
||||
DbOperation::ApprovalWrite,
|
||||
state
|
||||
.registry
|
||||
.expire_approval_request(ExpireApprovalRequest {
|
||||
workspace_id,
|
||||
agent_id,
|
||||
approval_id,
|
||||
expired_at: OffsetDateTime::now_utc(),
|
||||
}),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(Some(record)) => Json(json!(safe_approval_record(record))).into_response(),
|
||||
Ok(None) => StatusCode::CONFLICT.into_response(),
|
||||
Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
//! Auth-profile resolution for a tool call: which profile applies to the operation/agent pair, and
|
||||
//! the runtime auth projection derived from it.
|
||||
//!
|
||||
//! Moved verbatim out of `app.rs` (Story 3.6, kanban t_987bf309). `resolve_operation_auth` keeps its
|
||||
//! crate-visible path through a targeted `pub(super) use` in `app.rs`; the other two stay private to
|
||||
//! this module. No behaviour changed.
|
||||
|
||||
use crank_core::{AuthProfile, SecretId, SecretStatus};
|
||||
use crank_registry::PostgresRegistry;
|
||||
use crank_runtime::{ResolvedAuth, RuntimeError, SecretCrypto};
|
||||
use crank_trace::{DbOperation, ErrorCategory, Stage, StageOutcome, observe_db_query};
|
||||
use std::{collections::BTreeMap, sync::Arc};
|
||||
use time::OffsetDateTime;
|
||||
use tracing::{Instrument, warn};
|
||||
|
||||
use super::AppState;
|
||||
pub(crate) async fn resolve_operation_auth(
|
||||
state: &Arc<AppState>,
|
||||
workspace_id: &crank_core::WorkspaceId,
|
||||
execution_config: &crank_core::ExecutionConfig,
|
||||
) -> Result<Option<ResolvedAuth>, RuntimeError> {
|
||||
if execution_config.auth_profile_ref.is_none() {
|
||||
return Ok(None);
|
||||
}
|
||||
let span = Stage::AuthResolve.span();
|
||||
let result = resolve_runtime_auth_for_task(
|
||||
&state.registry,
|
||||
&state.secret_crypto,
|
||||
workspace_id,
|
||||
execution_config,
|
||||
)
|
||||
.instrument(span.clone())
|
||||
.await;
|
||||
match &result {
|
||||
Ok(_) => StageOutcome::Success.record(&span),
|
||||
Err(_) => {
|
||||
StageOutcome::Error.record(&span);
|
||||
ErrorCategory::Configuration.record(&span);
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
async fn resolve_runtime_auth_for_task(
|
||||
registry: &PostgresRegistry,
|
||||
secret_crypto: &SecretCrypto,
|
||||
workspace_id: &crank_core::WorkspaceId,
|
||||
execution_config: &crank_core::ExecutionConfig,
|
||||
) -> Result<Option<ResolvedAuth>, RuntimeError> {
|
||||
let Some(auth_profile_id) = execution_config.auth_profile_ref.as_ref() else {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
let auth_profile = observe_db_query(
|
||||
DbOperation::AuthProfileRead,
|
||||
registry.get_auth_profile(workspace_id, auth_profile_id),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| RuntimeError::AuthorizationStoreUnavailable)?
|
||||
.ok_or_else(|| RuntimeError::MissingAuthProfile {
|
||||
auth_profile_id: auth_profile_id.as_str().to_owned(),
|
||||
})?;
|
||||
|
||||
resolve_auth_profile(registry, secret_crypto, workspace_id, &auth_profile)
|
||||
.await
|
||||
.map(Some)
|
||||
}
|
||||
|
||||
async fn resolve_auth_profile(
|
||||
registry: &PostgresRegistry,
|
||||
secret_crypto: &SecretCrypto,
|
||||
workspace_id: &crank_core::WorkspaceId,
|
||||
auth_profile: &AuthProfile,
|
||||
) -> Result<ResolvedAuth, RuntimeError> {
|
||||
let mut secrets = BTreeMap::new();
|
||||
let used_at = OffsetDateTime::now_utc();
|
||||
|
||||
for secret_id in auth_profile.config.secret_ids() {
|
||||
let secret = observe_db_query(
|
||||
DbOperation::SecretRead,
|
||||
registry.get_secret(workspace_id, secret_id),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| RuntimeError::AuthorizationStoreUnavailable)?
|
||||
.ok_or_else(|| RuntimeError::MissingSecret {
|
||||
secret_id: secret_id.as_str().to_owned(),
|
||||
})?;
|
||||
if secret.secret.status != SecretStatus::Active {
|
||||
return Err(RuntimeError::InvalidAuthSecretValue {
|
||||
secret_id: secret_id.as_str().to_owned(),
|
||||
reason: "secret is not active".to_owned(),
|
||||
});
|
||||
}
|
||||
let version = observe_db_query(
|
||||
DbOperation::SecretRead,
|
||||
registry.get_current_secret_version(workspace_id, secret_id),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| RuntimeError::AuthorizationStoreUnavailable)?
|
||||
.ok_or_else(|| RuntimeError::MissingSecretVersion {
|
||||
secret_id: secret_id.as_str().to_owned(),
|
||||
version: secret.secret.current_version,
|
||||
})?;
|
||||
let plaintext = secret_crypto.decrypt_for_epoch(
|
||||
&version.secret_version.key_version,
|
||||
version.master_key_epoch,
|
||||
&version.secret_version.ciphertext,
|
||||
)?;
|
||||
if observe_db_query(
|
||||
DbOperation::SecretTouch,
|
||||
registry.touch_secret(workspace_id, secret_id, &used_at),
|
||||
)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
warn!(
|
||||
target: "crank::audit",
|
||||
action = "credential.secret.touch_failed",
|
||||
credential_type = "secret",
|
||||
credential_ref = %secret_id.as_str(),
|
||||
outcome = "metadata_touch_failed",
|
||||
"secret last-used metadata was not updated"
|
||||
);
|
||||
}
|
||||
secrets.insert(SecretId::new(secret_id.as_str()), plaintext);
|
||||
}
|
||||
|
||||
ResolvedAuth::from_profile(auth_profile, &secrets)
|
||||
}
|
||||
@@ -0,0 +1,831 @@
|
||||
//! 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, 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, tool_command_response,
|
||||
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);
|
||||
|
||||
// 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),
|
||||
)
|
||||
.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);
|
||||
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::Call(ToolCallCommand {
|
||||
tool_name: tool_call_params.name,
|
||||
arguments,
|
||||
confirmation_token,
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
tool_command_response(
|
||||
message,
|
||||
response_mode,
|
||||
version,
|
||||
transport_correlation,
|
||||
outcome,
|
||||
)
|
||||
}
|
||||
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")
|
||||
}
|
||||
}
|
||||
}
|
||||
// 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
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
//! Private, request-scoped semantic observer of the BUILD-internal harness (Story 3.1 section 7.2).
|
||||
//!
|
||||
//! The endpoint integration tests of `apps/mcp-server` cannot see `#[cfg(test)]` markers of this
|
||||
//! crate, so the observing behavioural test lives inside the crate, with the same in-crate access as
|
||||
//! `protocol::registry::tests::`. This module is `#[cfg(test)]`-only: it is absent from every
|
||||
//! production build and exposes no public API.
|
||||
//!
|
||||
//! The observer is **request-scoped**: the counters live in a `tokio::task_local!` slot that the
|
||||
//! test installs around one request, so two concurrently served requests never share a counter and
|
||||
//! no global racing state exists. A marker without an installed scope is a no-op, which is what
|
||||
//! happens in every other test of this crate.
|
||||
//!
|
||||
//! The markers are honest names, not one dispatch total (section 7.2): `ADMISSION_ENTER` is the
|
||||
//! external request entry, `ERA_MODERN_ENTER`/`ERA_LEGACY_ENTER` mean the request actually entered
|
||||
//! that era-adapter, and `TOOLS_SERVICE_ENTER` means the request entered the owning Tools
|
||||
//! service/handler. They prove "no reroute" (a pre-admission reject yields zero era and zero service
|
||||
//! entries; an in-adapter reject yields exactly its own era and no service entry) and they never
|
||||
//! claim "no residual state" on their own.
|
||||
//!
|
||||
//! Only the markers, the request scope and the counters live here. The behavioural harness that
|
||||
//! drives real observed requests through the real app is the `tests` child module below, whose file
|
||||
//! sits at `crates/crank-community-mcp/src/dispatch_observer_harness.rs`: `scripts/
|
||||
//! check-execution-boundaries.py` reserves the whole `crates/crank-community-mcp/src/app/` prefix
|
||||
//! for service modules without an HTTP client or a persistence dependency, while the harness needs
|
||||
//! both. The module *path* stays `app::dispatch_observer::tests`, so the selector
|
||||
//! `cargo test -p crank-community-mcp --lib app::dispatch_observer::` still selects the whole
|
||||
//! section 7.2 delta table.
|
||||
|
||||
use std::{
|
||||
future::Future,
|
||||
sync::{
|
||||
Arc,
|
||||
atomic::{AtomicUsize, Ordering},
|
||||
},
|
||||
};
|
||||
|
||||
use tokio::task_local;
|
||||
|
||||
task_local! {
|
||||
static OBSERVER: Arc<CounterSet>;
|
||||
}
|
||||
|
||||
task_local! {
|
||||
static REGISTRATION: Arc<crate::protocol::CapabilityRegistry>;
|
||||
}
|
||||
|
||||
/// The per-request counters of one observed request.
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct CounterSet {
|
||||
admission: AtomicUsize,
|
||||
era_modern: AtomicUsize,
|
||||
era_legacy: AtomicUsize,
|
||||
tools_service: AtomicUsize,
|
||||
}
|
||||
|
||||
impl CounterSet {
|
||||
/// Read the counters of one observed request as one comparable snapshot.
|
||||
pub(crate) fn snapshot(&self) -> Snapshot {
|
||||
Snapshot {
|
||||
admission: self.admission.load(Ordering::SeqCst),
|
||||
era_modern: self.era_modern.load(Ordering::SeqCst),
|
||||
era_legacy: self.era_legacy.load(Ordering::SeqCst),
|
||||
tools_service: self.tools_service.load(Ordering::SeqCst),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One comparable set of marker deltas of a single observed request.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) struct Snapshot {
|
||||
pub(crate) admission: usize,
|
||||
pub(crate) era_modern: usize,
|
||||
pub(crate) era_legacy: usize,
|
||||
pub(crate) tools_service: usize,
|
||||
}
|
||||
|
||||
impl Snapshot {
|
||||
/// The expected deltas of one case (section 7.2 table) as one comparable value.
|
||||
pub(crate) const fn new(
|
||||
admission: usize,
|
||||
era_modern: usize,
|
||||
era_legacy: usize,
|
||||
tools_service: usize,
|
||||
) -> Self {
|
||||
Self {
|
||||
admission,
|
||||
era_modern,
|
||||
era_legacy,
|
||||
tools_service,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Run one observed request: every marker increment inside `future` is recorded on `counters`.
|
||||
pub(crate) async fn observe<F: Future>(counters: Arc<CounterSet>, future: F) -> F::Output {
|
||||
OBSERVER.scope(counters, future).await
|
||||
}
|
||||
|
||||
/// Run one observed request with an explicit registration snapshot (F5 add/remove proof).
|
||||
///
|
||||
/// The snapshot is request-scoped like the counters: a request served inside `future` asks *this*
|
||||
/// registration for its dispatch decision and its advertisement, so one test can prove that adding or
|
||||
/// removing a private inert descriptor changes what the real router does, without touching the
|
||||
/// production table and without a process-global override that other tests could observe.
|
||||
pub(crate) async fn observe_with_registration<F: Future>(
|
||||
registration: Arc<crate::protocol::CapabilityRegistry>,
|
||||
future: F,
|
||||
) -> F::Output {
|
||||
REGISTRATION.scope(registration, future).await
|
||||
}
|
||||
|
||||
/// The registration installed for the current request, if the observing test installed one.
|
||||
pub(crate) fn installed_registration() -> Option<Arc<crate::protocol::CapabilityRegistry>> {
|
||||
REGISTRATION.try_with(Arc::clone).ok()
|
||||
}
|
||||
|
||||
/// `ADMISSION_ENTER`: the external request entry, not a dispatch.
|
||||
pub(crate) fn admission_enter() {
|
||||
increment(|counters| &counters.admission);
|
||||
}
|
||||
|
||||
/// `ERA_MODERN_ENTER`: the request was served by the modern era-adapter.
|
||||
pub(crate) fn era_modern_enter() {
|
||||
increment(|counters| &counters.era_modern);
|
||||
}
|
||||
|
||||
/// `ERA_LEGACY_ENTER`: the request was served by the legacy era-adapter.
|
||||
pub(crate) fn era_legacy_enter() {
|
||||
increment(|counters| &counters.era_legacy);
|
||||
}
|
||||
|
||||
/// `TOOLS_SERVICE_ENTER`: the request entered the owning Tools service/handler.
|
||||
pub(crate) fn tools_service_enter() {
|
||||
increment(|counters| &counters.tools_service);
|
||||
}
|
||||
|
||||
fn increment(counter: impl Fn(&CounterSet) -> &AtomicUsize) {
|
||||
let _ = OBSERVER.try_with(|counters| {
|
||||
counter(counters).fetch_add(1, Ordering::SeqCst);
|
||||
});
|
||||
}
|
||||
|
||||
/// Fixtures and helpers of the section 7.2 test seam (its file lives outside `src/app/` for the same
|
||||
/// execution-boundary reason as the tests below).
|
||||
#[cfg(test)]
|
||||
#[path = "../dispatch_observer_support.rs"]
|
||||
mod support;
|
||||
|
||||
/// The behavioural section 7.2 harness: real app, real PostgreSQL, one counted loopback upstream and
|
||||
/// one request-scoped observer per request. Its file lives outside `src/app/` only because the
|
||||
/// repository's execution-boundary check owns that prefix (see the module documentation above); the
|
||||
/// module path stays `app::dispatch_observer::tests`.
|
||||
#[cfg(test)]
|
||||
#[path = "../dispatch_observer_harness.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,982 @@
|
||||
//! The MCP transport endpoint: `GET`/`DELETE`/`POST` on the agent route, the session and
|
||||
//! response-mode negotiation at the HTTP level and the entry into the modern dispatch.
|
||||
//!
|
||||
//! 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.
|
||||
|
||||
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,
|
||||
},
|
||||
protocol::{
|
||||
CompletionCommand, CompletionOutcome, ContinuationSupport, DispatchDecision, EnvelopeKind,
|
||||
Kind, MethodHandler, PromptGetCommand, PromptsCommand, PromptsListCommand, PromptsOutcome,
|
||||
RequestEra, ResourceReadCommand, ResourcesCommand, ResourcesListCommand, ResourcesOutcome,
|
||||
ServiceContext, ToolCallCommand, ToolsCommand, ToolsListCommand, ToolsOutcome,
|
||||
ambiguous_session_carrier_response, handle_completion_command, handle_prompts_command,
|
||||
handle_resources_command, handle_tools_command, resolve_request_identity,
|
||||
},
|
||||
rate_limit::{rate_limited_jsonrpc_response, rate_limited_status_response},
|
||||
request_context::RequestContext,
|
||||
tool_error::execution_locale,
|
||||
transport::{
|
||||
negotiate_post_response_mode, session_id_from_headers, sse_response, transport_response,
|
||||
validate_get_accept_header, validate_origin, validate_session_protocol_version,
|
||||
with_request_id_header,
|
||||
},
|
||||
};
|
||||
use axum::{
|
||||
Json,
|
||||
extract::{Extension, Path, State, rejection::JsonRejection},
|
||||
http::{HeaderMap, StatusCode},
|
||||
response::{IntoResponse, Response, sse::Event},
|
||||
};
|
||||
use crank_core::{CorrelationContext, PlatformApiKeyScope};
|
||||
use futures_util::stream;
|
||||
use serde_json::{Value, json};
|
||||
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::{AgentRoutePath, AppState, TRANSPORT_SESSION_TTL_MS};
|
||||
pub(super) async fn mcp_get(
|
||||
Path(path): Path<AgentRoutePath>,
|
||||
State(state): State<Arc<AppState>>,
|
||||
headers: HeaderMap,
|
||||
) -> Response {
|
||||
if let Err(status) = validate_origin(&state.allowed_origins, &headers) {
|
||||
return status.into_response();
|
||||
}
|
||||
|
||||
if let Err(status) = validate_get_accept_header(&headers) {
|
||||
return status.into_response();
|
||||
}
|
||||
|
||||
if let Err(status) =
|
||||
require_traced_machine_access(&state, &path, &headers, PlatformApiKeyScope::Read).await
|
||||
{
|
||||
return status.into_response();
|
||||
}
|
||||
|
||||
// Identity admission runs before the session-keyed rate accounting: an explicit modern identity has
|
||||
// no session to stream (matrix row 20 answers `405`), and an unknown, withdrawn or ambiguous
|
||||
// revision — including a conflicting duplicate session carrier — is a safe admission error. A
|
||||
// rejected request must not consume the legitimate legacy bucket or reach the session store.
|
||||
if let Err(response) = crate::protocol::session_lifecycle_admission(&headers) {
|
||||
return *response;
|
||||
}
|
||||
|
||||
let session_id = match session_id_from_headers(&headers) {
|
||||
Ok(Some(session_id)) => session_id,
|
||||
Ok(None) => return StatusCode::BAD_REQUEST.into_response(),
|
||||
Err(status) => return status.into_response(),
|
||||
};
|
||||
|
||||
if let Err(rejection) = enforce_traced_rate_limit(&state, &path, &headers).await {
|
||||
return rate_limited_status_response(rejection);
|
||||
}
|
||||
|
||||
let Some(session) = (match state.sessions.get(&session_id).await {
|
||||
Ok(session) => session,
|
||||
Err(_) => return StatusCode::INTERNAL_SERVER_ERROR.into_response(),
|
||||
}) else {
|
||||
return StatusCode::NOT_FOUND.into_response();
|
||||
};
|
||||
|
||||
if session.workspace_slug != path.workspace_slug || session.agent_slug != path.agent_slug {
|
||||
return StatusCode::NOT_FOUND.into_response();
|
||||
}
|
||||
|
||||
// A persisted session whose negotiated revision is no longer supported is never served, even when
|
||||
// the request carries no version header (protocol era matrix row 15: safe error, `405` belongs to
|
||||
// the modern identity of row 20). The session state stays intact.
|
||||
if let Err(status) = crate::protocol::validate_session_revision(&session) {
|
||||
return status.into_response();
|
||||
}
|
||||
|
||||
if !session.initialized {
|
||||
return StatusCode::BAD_REQUEST.into_response();
|
||||
}
|
||||
|
||||
if let Err(status) = validate_session_protocol_version(&headers, &session.protocol_version) {
|
||||
return status.into_response();
|
||||
}
|
||||
|
||||
let Ok(permit) = ActiveStreamGuard::try_acquire(&state.session_slots) else {
|
||||
return StatusCode::TOO_MANY_REQUESTS.into_response();
|
||||
};
|
||||
|
||||
let stream = stream::unfold(permit, |permit| async move {
|
||||
tokio::time::sleep(Duration::from_millis(TRANSPORT_SESSION_TTL_MS)).await;
|
||||
drop(permit);
|
||||
None::<(Result<Event, Infallible>, _)>
|
||||
});
|
||||
|
||||
sse_response(
|
||||
StatusCode::OK,
|
||||
stream,
|
||||
Some(&session_id),
|
||||
Some(&session.protocol_version),
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) async fn mcp_delete(
|
||||
Path(path): Path<AgentRoutePath>,
|
||||
State(state): State<Arc<AppState>>,
|
||||
headers: HeaderMap,
|
||||
) -> Response {
|
||||
if let Err(status) =
|
||||
require_traced_machine_access(&state, &path, &headers, PlatformApiKeyScope::Read).await
|
||||
{
|
||||
return status.into_response();
|
||||
}
|
||||
|
||||
// Identity admission and carrier validation run before the session-keyed rate accounting: a modern
|
||||
// identity must never terminate a legacy session, and a rejected request must not consume the
|
||||
// legitimate legacy bucket or reach the session store.
|
||||
if let Err(response) = crate::protocol::session_lifecycle_admission(&headers) {
|
||||
return *response;
|
||||
}
|
||||
|
||||
let session_id = match session_id_from_headers(&headers) {
|
||||
Ok(Some(session_id)) => session_id,
|
||||
Ok(None) => return StatusCode::BAD_REQUEST.into_response(),
|
||||
Err(status) => return status.into_response(),
|
||||
};
|
||||
|
||||
if let Err(rejection) = enforce_traced_rate_limit(&state, &path, &headers).await {
|
||||
return rate_limited_status_response(rejection);
|
||||
}
|
||||
|
||||
match state.sessions.get(&session_id).await {
|
||||
Ok(Some(session)) => {
|
||||
if session.workspace_slug != path.workspace_slug
|
||||
|| session.agent_slug != path.agent_slug
|
||||
{
|
||||
return StatusCode::NOT_FOUND.into_response();
|
||||
}
|
||||
|
||||
// An unsupported persisted revision is never terminated as a live legacy session.
|
||||
if let Err(status) = crate::protocol::validate_session_revision(&session) {
|
||||
return status.into_response();
|
||||
}
|
||||
|
||||
match state.sessions.delete(&session_id).await {
|
||||
Ok(true) => {
|
||||
state.session_metrics.refresh();
|
||||
StatusCode::NO_CONTENT.into_response()
|
||||
}
|
||||
Ok(false) => StatusCode::NOT_FOUND.into_response(),
|
||||
Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
|
||||
}
|
||||
}
|
||||
Ok(None) => StatusCode::NOT_FOUND.into_response(),
|
||||
Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn mcp_post(
|
||||
Path(path): Path<AgentRoutePath>,
|
||||
State(state): State<Arc<AppState>>,
|
||||
Extension(request_context): Extension<RequestContext>,
|
||||
headers: HeaderMap,
|
||||
payload: Result<Json<Value>, JsonRejection>,
|
||||
) -> Response {
|
||||
let message = match payload {
|
||||
Ok(Json(message)) => message,
|
||||
Err(rejection) => {
|
||||
let mut request_metrics = McpRequestMetrics::invalid(
|
||||
request_context.started_at(),
|
||||
request_context.exemplar(),
|
||||
);
|
||||
let response = rejection.into_response();
|
||||
request_metrics.complete(&response);
|
||||
return with_request_id_header(response, request_context.request_id());
|
||||
}
|
||||
};
|
||||
let mut request_metrics = McpRequestMetrics::new(
|
||||
&message,
|
||||
request_context.started_at(),
|
||||
request_context.exemplar(),
|
||||
);
|
||||
let transport_correlation = request_context.correlation;
|
||||
let transport_request_id = transport_correlation.request_id().to_string();
|
||||
info!(
|
||||
name: "mcp.request.received",
|
||||
request_id = %transport_request_id,
|
||||
workspace_slug = %path.workspace_slug,
|
||||
agent_slug = %path.agent_slug,
|
||||
jsonrpc_method = method_name(&message).unwrap_or("<unknown>"),
|
||||
"mcp request received"
|
||||
);
|
||||
|
||||
let response =
|
||||
mcp_post_response(&path, state, &headers, &message, &transport_correlation).await;
|
||||
request_metrics.complete(&response);
|
||||
with_request_id_header(response, &transport_request_id)
|
||||
}
|
||||
|
||||
async fn mcp_post_response(
|
||||
path: &AgentRoutePath,
|
||||
state: Arc<AppState>,
|
||||
headers: &HeaderMap,
|
||||
message: &Value,
|
||||
transport_correlation: &CorrelationContext,
|
||||
) -> Response {
|
||||
// ADMISSION_ENTER (spec section 7.2): the external request entry, before any era resolution,
|
||||
// dispatch, service entry or outbound call. Test-only counter, no production effect.
|
||||
#[cfg(test)]
|
||||
crate::app::dispatch_observer::admission_enter();
|
||||
|
||||
if let Err(status) = validate_origin(&state.allowed_origins, headers) {
|
||||
return status.into_response();
|
||||
}
|
||||
|
||||
let response_mode = match negotiate_post_response_mode(headers) {
|
||||
Ok(mode) => mode,
|
||||
Err(status) => return status.into_response(),
|
||||
};
|
||||
// A conflicting duplicate session carrier is an ambiguous identity: it must not be resolved to
|
||||
// one of its values. The carrier itself cannot tell which era the request belongs to, so the
|
||||
// diagnostic is read from the non-ambiguous part of the request (matrix row 17) — a consumer of
|
||||
// the identity never has to guess and never sees a bare `400`. The precedence of this check is
|
||||
// unchanged (it still runs before era resolution and dispatch). `GET`/`DELETE` keep their own
|
||||
// session-lifecycle admission and are untouched.
|
||||
let request_session_id = match session_id_from_headers(headers) {
|
||||
Ok(session_id) => session_id,
|
||||
Err(_status) => return ambiguous_session_carrier_response(headers, message),
|
||||
};
|
||||
|
||||
// Single JSON-RPC envelope guard: only a well-formed message reaches era resolution, dispatch,
|
||||
// approval or any outbound request. Syntactically valid JSON is not the same as a valid envelope.
|
||||
let envelope = match crate::protocol::validate_jsonrpc_envelope(message) {
|
||||
Ok(envelope) => envelope,
|
||||
Err(response) => return *response,
|
||||
};
|
||||
if matches!(envelope, EnvelopeKind::Response) {
|
||||
return StatusCode::ACCEPTED.into_response();
|
||||
}
|
||||
|
||||
let identity = match resolve_request_identity(headers, message) {
|
||||
Ok(identity) => identity,
|
||||
Err(response) => return *response,
|
||||
};
|
||||
let protocol_version = identity.version.clone();
|
||||
|
||||
// The modern revision is stateless: a session carrier is a conflicting identity and is rejected
|
||||
// here — before the rate-limit accounting, the session store and any dispatch — instead of being
|
||||
// silently ignored.
|
||||
if matches!(identity.era, RequestEra::Modern) && request_session_id.is_some() {
|
||||
return crate::protocol::modern_carrier_conflict_response(message);
|
||||
}
|
||||
|
||||
let rate_limit_result = enforce_traced_rate_limit(&state, path, headers).await;
|
||||
if let Err(error) = rate_limit_result {
|
||||
return rate_limited_jsonrpc_response(
|
||||
message,
|
||||
response_mode,
|
||||
protocol_version
|
||||
.as_deref()
|
||||
.unwrap_or(crate::jsonrpc::LEGACY_PROTOCOL_VERSION),
|
||||
error,
|
||||
);
|
||||
}
|
||||
if let Some(session_id) = request_session_id.as_deref() {
|
||||
let session = match state.sessions.get(session_id).await {
|
||||
Ok(session) => session,
|
||||
Err(_) => return StatusCode::INTERNAL_SERVER_ERROR.into_response(),
|
||||
};
|
||||
if let Some(session) = session {
|
||||
// Same contract as the session-lifecycle methods: a persisted session that is no longer
|
||||
// operational under the supported legacy revision — because the request names another
|
||||
// revision, or because the session itself was negotiated on a withdrawn revision — is never
|
||||
// served, not even when the request omits the version header. The rejected request is
|
||||
// answered with the era-correct *legacy* structured error (matrix rows 15/16) instead of a
|
||||
// bare `400`: the modern `-32020`/`-32022` diagnostics describe a modern identity and are
|
||||
// not imposed on this legacy-sourced rejection (row 14). The persisted session stays
|
||||
// intact and no outbound call is made.
|
||||
if validate_session_protocol_version(headers, &session.protocol_version).is_err()
|
||||
|| crate::protocol::validate_session_revision(&session).is_err()
|
||||
{
|
||||
return transport_response(
|
||||
StatusCode::BAD_REQUEST,
|
||||
jsonrpc_error(
|
||||
request_id(message),
|
||||
-32602,
|
||||
"the negotiated session revision is no longer supported",
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
None,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let required_scope = match method_name(message) {
|
||||
Some("tools/call") => PlatformApiKeyScope::Write,
|
||||
_ => PlatformApiKeyScope::Read,
|
||||
};
|
||||
let access_result = require_traced_machine_access(&state, path, headers, required_scope).await;
|
||||
let credential = match access_result {
|
||||
Ok(credential) => credential,
|
||||
Err(error) => return error.into_response(),
|
||||
};
|
||||
|
||||
if matches!(identity.era, RequestEra::Modern) {
|
||||
// ERA_MODERN_ENTER (spec section 7.2): this request entered the modern era-adapter.
|
||||
#[cfg(test)]
|
||||
crate::app::dispatch_observer::era_modern_enter();
|
||||
return handle_modern_request(
|
||||
&state,
|
||||
path,
|
||||
headers,
|
||||
message,
|
||||
response_mode,
|
||||
&identity,
|
||||
&credential,
|
||||
transport_correlation,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
// ERA_LEGACY_ENTER (spec section 7.2): this request entered the legacy era-adapter.
|
||||
#[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")
|
||||
}
|
||||
}
|
||||
}
|
||||
// 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(),
|
||||
),
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
use serde_json::Value;
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub(super) struct InitializeParams {
|
||||
@@ -12,44 +12,19 @@ pub(super) struct InitializeParams {
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub(super) struct ToolCallParams {
|
||||
pub(super) name: String,
|
||||
#[serde(default)]
|
||||
pub(super) arguments: Value,
|
||||
#[serde(default, deserialize_with = "deserialize_arguments_object")]
|
||||
pub(super) arguments: Option<Value>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub(super) struct ToolsListParams {
|
||||
#[serde(default)]
|
||||
pub(super) cursor: Option<String>,
|
||||
#[serde(default)]
|
||||
pub(super) limit: Option<usize>,
|
||||
}
|
||||
|
||||
pub(super) fn paginate_tools_list(
|
||||
definitions: Vec<Value>,
|
||||
params: ToolsListParams,
|
||||
) -> Result<Value, &'static str> {
|
||||
const MAX_TOOLS_LIST_LIMIT: usize = 100;
|
||||
let start = match params.cursor {
|
||||
Some(cursor) if cursor.is_empty() => 0,
|
||||
Some(cursor) => cursor
|
||||
.parse::<usize>()
|
||||
.map_err(|_| "invalid tools/list cursor")?,
|
||||
None => 0,
|
||||
};
|
||||
if start > definitions.len() {
|
||||
return Err("tools/list cursor is out of range");
|
||||
}
|
||||
let limit = params
|
||||
.limit
|
||||
.unwrap_or(definitions.len())
|
||||
.clamp(1, MAX_TOOLS_LIST_LIMIT);
|
||||
let end = start.saturating_add(limit).min(definitions.len());
|
||||
let page = definitions[start..end].to_vec();
|
||||
let mut result = json!({ "tools": page });
|
||||
if end < definitions.len() {
|
||||
result["nextCursor"] = json!(end.to_string());
|
||||
}
|
||||
Ok(result)
|
||||
/// The pinned `CallToolRequest.params.arguments` is an **optional object**. Omitting it stays valid
|
||||
/// (and keeps its previous behaviour), while an explicit `null`, array or scalar is invalid params — so
|
||||
/// the two cases must not collapse into one another during deserialization. The object shape check
|
||||
/// itself is shared with the `call_tool` proxy's nested `arguments` (`protocol::deserialize_object_only`).
|
||||
fn deserialize_arguments_object<'de, D>(deserializer: D) -> Result<Option<Value>, D::Error>
|
||||
where
|
||||
D: serde::Deserializer<'de>,
|
||||
{
|
||||
crate::protocol::deserialize_object_only(deserializer).map(Some)
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
|
||||
@@ -3,10 +3,16 @@ 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;
|
||||
@@ -27,16 +33,19 @@ pub(crate) fn success_tool_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
json!({
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": serde_json::to_string_pretty(&output).unwrap_or_else(|_| "{}".to_owned())
|
||||
}
|
||||
],
|
||||
"structuredContent": output,
|
||||
"isError": false
|
||||
}),
|
||||
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,
|
||||
@@ -57,21 +66,221 @@ pub(crate) fn tool_error_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
json!({
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": error_message
|
||||
}
|
||||
],
|
||||
"structuredContent": {
|
||||
"error": error_value
|
||||
},
|
||||
"isError": true
|
||||
}),
|
||||
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,
|
||||
)
|
||||
}
|
||||
Reference in new issue
Block a user