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
File diff suppressed because it is too large.
Load diff
@@ -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,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,678 @@
|
||||
//! Behavioural tests of the BUILD-internal semantic observer (Story 3.1 section 7.2).
|
||||
//!
|
||||
//! This file is the `tests` child module of `crate::app::dispatch_observer` (wired with `#[path]`
|
||||
//! there), so the module path — and therefore the sanctioned selector
|
||||
//! `cargo test -p crank-community-mcp --lib app::dispatch_observer::` — is unchanged. The fixtures
|
||||
//! and helpers live in the sibling `support` module of the same parent.
|
||||
|
||||
use super::support::*;
|
||||
use serde_json::json;
|
||||
use std::sync::Arc;
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// §7.2 pre-admission rejects: zero era-adapter entries, zero Tools-service entries, zero outbound
|
||||
// calls — the admission marker itself is the only increment.
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
#[tokio::test]
|
||||
async fn dispatch_observer_pre_admission_rejects_never_enter_an_era_adapter_or_the_service() {
|
||||
let harness = Harness::started().await;
|
||||
let session = harness.initialize_legacy_session().await;
|
||||
|
||||
// F7/G6: each reject below is an individual triple — a valid control of the same era, one
|
||||
// one-factor mutation of the chosen field, the reject with its exact marker/store/outbound
|
||||
// deltas, and an immediate valid follow-up with its own scoped output. One shared follow-up at
|
||||
// the end of the test would say nothing about the state a single reject left behind.
|
||||
|
||||
// 1. malformed envelope: a session-bearing valid legacy call with only the envelope version
|
||||
// field mutated, so a zero era/service delta is a property of that one field.
|
||||
run_valid_legacy_call(
|
||||
&harness,
|
||||
&session,
|
||||
11,
|
||||
"control-envelope@example.com",
|
||||
"control before the malformed envelope",
|
||||
)
|
||||
.await;
|
||||
|
||||
let before = harness.snapshot();
|
||||
let ops_before = harness.session_ops();
|
||||
let arrivals = harness.upstream_calls();
|
||||
let mut malformed_body = legacy_tool_call(12, "envelope@example.com");
|
||||
malformed_body["jsonrpc"] = json!("1.0");
|
||||
let malformed = harness
|
||||
.post(&header_refs(&legacy_headers(&session)), &malformed_body)
|
||||
.await;
|
||||
assert_eq!(
|
||||
malformed.status().as_u16(),
|
||||
400,
|
||||
"a malformed envelope is a rejection"
|
||||
);
|
||||
assert_no_result("malformed envelope", &json_body(malformed).await);
|
||||
assert_deltas(
|
||||
"malformed envelope",
|
||||
before,
|
||||
harness.snapshot(),
|
||||
Snapshot::new(1, 0, 0, 0),
|
||||
);
|
||||
assert_eq!(harness.upstream_calls(), arrivals);
|
||||
// F7: a reject before admission must not touch the session store at all — an extra `get` here is
|
||||
// invisible to the markers and to the outbound counter, so it is counted explicitly.
|
||||
assert_session_ops(
|
||||
"malformed envelope",
|
||||
ops_before,
|
||||
harness.session_ops(),
|
||||
SessionOps {
|
||||
get: 0,
|
||||
create: 0,
|
||||
mark_initialized: 0,
|
||||
},
|
||||
);
|
||||
run_valid_legacy_call(
|
||||
&harness,
|
||||
&session,
|
||||
13,
|
||||
"follow-up-envelope@example.com",
|
||||
"follow-up after the malformed envelope",
|
||||
)
|
||||
.await;
|
||||
|
||||
// 2. ambiguous session carrier: the same valid legacy call with one conflicting session header.
|
||||
run_valid_legacy_call(
|
||||
&harness,
|
||||
&session,
|
||||
21,
|
||||
"control-ambiguous@example.com",
|
||||
"control before the ambiguous session carrier",
|
||||
)
|
||||
.await;
|
||||
|
||||
let before = harness.snapshot();
|
||||
let ops_before = harness.session_ops();
|
||||
let arrivals = harness.upstream_calls();
|
||||
let ambiguous = harness
|
||||
.post(
|
||||
&[
|
||||
("MCP-Protocol-Version", LEGACY_REVISION),
|
||||
("MCP-Session-Id", session.as_str()),
|
||||
("MCP-Session-Id", "session-of-another-era"),
|
||||
],
|
||||
&legacy_tool_call(22, "ambiguous@example.com"),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
ambiguous.status().as_u16(),
|
||||
400,
|
||||
"an ambiguous carrier is a rejection"
|
||||
);
|
||||
assert_no_result("ambiguous session carrier", &json_body(ambiguous).await);
|
||||
assert_deltas(
|
||||
"ambiguous session carrier",
|
||||
before,
|
||||
harness.snapshot(),
|
||||
Snapshot::new(1, 0, 0, 0),
|
||||
);
|
||||
assert_eq!(harness.upstream_calls(), arrivals);
|
||||
assert_session_ops(
|
||||
"ambiguous session carrier",
|
||||
ops_before,
|
||||
harness.session_ops(),
|
||||
SessionOps {
|
||||
get: 0,
|
||||
create: 0,
|
||||
mark_initialized: 0,
|
||||
},
|
||||
);
|
||||
run_valid_legacy_call(
|
||||
&harness,
|
||||
&session,
|
||||
23,
|
||||
"follow-up-ambiguous@example.com",
|
||||
"follow-up after the ambiguous session carrier",
|
||||
)
|
||||
.await;
|
||||
|
||||
// 3. unresolvable identity: the same session-bearing legacy call with a modern `_meta` added, so
|
||||
// the header and the body name two different revisions.
|
||||
run_valid_legacy_call(
|
||||
&harness,
|
||||
&session,
|
||||
31,
|
||||
"control-identity@example.com",
|
||||
"control before the unresolvable identity",
|
||||
)
|
||||
.await;
|
||||
|
||||
let before = harness.snapshot();
|
||||
let ops_before = harness.session_ops();
|
||||
let arrivals = harness.upstream_calls();
|
||||
let mut unresolvable_body = legacy_tool_call(32, "unresolvable@example.com");
|
||||
unresolvable_body["params"]["_meta"] = modern_meta();
|
||||
let unresolvable = harness
|
||||
.post(&header_refs(&legacy_headers(&session)), &unresolvable_body)
|
||||
.await;
|
||||
assert_eq!(
|
||||
unresolvable.status().as_u16(),
|
||||
400,
|
||||
"an unresolvable identity is a rejection"
|
||||
);
|
||||
assert_no_result("unresolvable identity", &json_body(unresolvable).await);
|
||||
assert_deltas(
|
||||
"unresolvable identity",
|
||||
before,
|
||||
harness.snapshot(),
|
||||
Snapshot::new(1, 0, 0, 0),
|
||||
);
|
||||
assert_eq!(harness.upstream_calls(), arrivals);
|
||||
assert_session_ops(
|
||||
"unresolvable identity",
|
||||
ops_before,
|
||||
harness.session_ops(),
|
||||
SessionOps {
|
||||
get: 0,
|
||||
create: 0,
|
||||
mark_initialized: 0,
|
||||
},
|
||||
);
|
||||
run_valid_legacy_call(
|
||||
&harness,
|
||||
&session,
|
||||
33,
|
||||
"follow-up-identity@example.com",
|
||||
"follow-up after the unresolvable identity",
|
||||
)
|
||||
.await;
|
||||
|
||||
// 4. modern carrier conflict: a valid modern call that also carries the legacy session — the same
|
||||
// request with one extra carrier header.
|
||||
run_valid_modern_call(
|
||||
&harness,
|
||||
41,
|
||||
"control-conflict@example.com",
|
||||
"control before the modern carrier conflict",
|
||||
)
|
||||
.await;
|
||||
|
||||
let before = harness.snapshot();
|
||||
let ops_before = harness.session_ops();
|
||||
let arrivals = harness.upstream_calls();
|
||||
let mut conflicting = modern_headers();
|
||||
conflicting.push(("MCP-Session-Id", session.clone()));
|
||||
let conflict = harness
|
||||
.post(
|
||||
&header_refs(&conflicting),
|
||||
&modern_tool_call(42, "conflict@example.com"),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(conflict.status().as_u16(), 400);
|
||||
assert_no_result("modern carrier conflict", &json_body(conflict).await);
|
||||
assert_deltas(
|
||||
"modern carrier conflict",
|
||||
before,
|
||||
harness.snapshot(),
|
||||
Snapshot::new(1, 0, 0, 0),
|
||||
);
|
||||
assert_eq!(harness.upstream_calls(), arrivals);
|
||||
assert_session_ops(
|
||||
"modern carrier conflict",
|
||||
ops_before,
|
||||
harness.session_ops(),
|
||||
SessionOps {
|
||||
get: 0,
|
||||
create: 0,
|
||||
mark_initialized: 0,
|
||||
},
|
||||
);
|
||||
run_valid_modern_call(
|
||||
&harness,
|
||||
43,
|
||||
"follow-up-conflict@example.com",
|
||||
"follow-up after the modern carrier conflict",
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// §7.2 in-adapter rejects: exactly the own era-adapter, never the other one, no service entry.
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
#[tokio::test]
|
||||
async fn dispatch_observer_in_adapter_rejects_enter_exactly_their_own_era_and_no_service() {
|
||||
let harness = Harness::started().await;
|
||||
let session = harness.initialize_legacy_session().await;
|
||||
|
||||
// F7: every in-adapter reject gets its own control → one-factor negative → follow-up triple, so a
|
||||
// reject can never be confused with a broken endpoint and the state after the reject is proven to
|
||||
// serve the very next request.
|
||||
run_valid_legacy_call(
|
||||
&harness,
|
||||
&session,
|
||||
30,
|
||||
"control-legacy@example.com",
|
||||
"control before the legacy reject",
|
||||
)
|
||||
.await;
|
||||
|
||||
// Legacy unknown method: a rejection inside the legacy adapter. The negative is the valid legacy
|
||||
// call body of this era with exactly one factor changed - the method identifier - so the same
|
||||
// `params`/`name`/`arguments` payload is proven not to reach the owning Tools service.
|
||||
let before = harness.snapshot();
|
||||
let ops_before = harness.session_ops();
|
||||
let arrivals = harness.upstream_calls();
|
||||
let mut legacy_unknown_request = legacy_tool_call(31, "unknown-legacy@example.com");
|
||||
legacy_unknown_request["method"] = json!("tools/not-a-method");
|
||||
let legacy_unknown = harness
|
||||
.post(
|
||||
&header_refs(&legacy_headers(&session)),
|
||||
&legacy_unknown_request,
|
||||
)
|
||||
.await;
|
||||
let legacy_unknown_body = json_body(legacy_unknown).await;
|
||||
assert_eq!(
|
||||
legacy_unknown_body["error"]["code"], -32601,
|
||||
"an unregistered legacy method is an unsupported-method error, got {legacy_unknown_body}"
|
||||
);
|
||||
assert_deltas(
|
||||
"legacy unknown method",
|
||||
before,
|
||||
harness.snapshot(),
|
||||
Snapshot::new(1, 0, 1, 0),
|
||||
);
|
||||
assert_eq!(harness.upstream_calls(), arrivals);
|
||||
// The legacy carrier is still resolved by the admission's revision check (one read), and the
|
||||
// reject neither creates nor mutates a session.
|
||||
assert_session_ops(
|
||||
"legacy unknown method",
|
||||
ops_before,
|
||||
harness.session_ops(),
|
||||
SessionOps {
|
||||
get: 1,
|
||||
create: 0,
|
||||
mark_initialized: 0,
|
||||
},
|
||||
);
|
||||
run_valid_legacy_call(
|
||||
&harness,
|
||||
&session,
|
||||
31,
|
||||
"follow-up-legacy@example.com",
|
||||
"follow-up after the legacy reject",
|
||||
)
|
||||
.await;
|
||||
|
||||
// Modern unknown method: the control is a valid modern call of the same era, the negative is that
|
||||
// same valid call with only the method identifier changed - the body method and its coherent
|
||||
// `Mcp-Method` wire carrier, both denoting the one logical field - and the follow-up is an
|
||||
// independent modern success on a session store that must still be untouched.
|
||||
run_valid_modern_call(
|
||||
&harness,
|
||||
33,
|
||||
"control-modern@example.com",
|
||||
"control before the modern reject",
|
||||
)
|
||||
.await;
|
||||
|
||||
let before = harness.snapshot();
|
||||
let ops_before = harness.session_ops();
|
||||
let arrivals = harness.upstream_calls();
|
||||
let mut modern_unknown_request = modern_tool_call(34, "unknown-modern@example.com");
|
||||
modern_unknown_request["method"] = json!("tools/not-a-method");
|
||||
let modern_unknown = harness
|
||||
.post(
|
||||
&[
|
||||
("MCP-Protocol-Version", MODERN_REVISION),
|
||||
("Mcp-Method", "tools/not-a-method"),
|
||||
("Mcp-Name", TOOL_NAME),
|
||||
],
|
||||
&modern_unknown_request,
|
||||
)
|
||||
.await;
|
||||
let modern_unknown_body = json_body(modern_unknown).await;
|
||||
assert_eq!(
|
||||
modern_unknown_body["error"]["code"], -32601,
|
||||
"an unregistered modern method is an unsupported-method error, got {modern_unknown_body}"
|
||||
);
|
||||
assert_deltas(
|
||||
"modern unknown method",
|
||||
before,
|
||||
harness.snapshot(),
|
||||
Snapshot::new(1, 1, 0, 0),
|
||||
);
|
||||
assert_eq!(harness.upstream_calls(), arrivals);
|
||||
assert_session_ops(
|
||||
"modern unknown method",
|
||||
ops_before,
|
||||
harness.session_ops(),
|
||||
SessionOps {
|
||||
get: 0,
|
||||
create: 0,
|
||||
mark_initialized: 0,
|
||||
},
|
||||
);
|
||||
// The independent modern follow-up after the reject: its own era, its own scoped output, and a
|
||||
// session store that is still untouched.
|
||||
run_valid_modern_call(
|
||||
&harness,
|
||||
35,
|
||||
"follow-up-modern@example.com",
|
||||
"follow-up after the modern reject",
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// G2: the registered kind of the two legacy lifecycle operations — an envelope of the wrong kind may
|
||||
// not be served as the other action.
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
#[tokio::test]
|
||||
async fn dispatch_observer_lifecycle_envelope_kind_cannot_swap_the_two_legacy_actions() {
|
||||
let harness = Harness::started().await;
|
||||
let session = harness.initialize_legacy_session().await;
|
||||
|
||||
// Form 1: `initialize` written as a notification — the valid request control with only its `id`
|
||||
// removed. `initialize` is registered as a request, so this form must neither initialize the live
|
||||
// session nor mint a new one.
|
||||
run_valid_legacy_initialize(&harness, 61, "control initialize request").await;
|
||||
|
||||
let mut initialize_notification = legacy_initialize(62);
|
||||
initialize_notification
|
||||
.as_object_mut()
|
||||
.expect("the initialize request is an object")
|
||||
.remove("id");
|
||||
assert!(initialize_notification.get("id").is_none());
|
||||
|
||||
let before = harness.snapshot();
|
||||
let ops_before = harness.session_ops();
|
||||
let arrivals = harness.upstream_calls();
|
||||
let notification = harness
|
||||
.post(
|
||||
&header_refs(&legacy_headers(&session)),
|
||||
&initialize_notification,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
notification.status().as_u16(),
|
||||
202,
|
||||
"an initialize notification is acknowledged, never served as an initialize request"
|
||||
);
|
||||
assert_deltas(
|
||||
"initialize as a notification",
|
||||
before,
|
||||
harness.snapshot(),
|
||||
Snapshot::new(1, 0, 1, 0),
|
||||
);
|
||||
assert_eq!(harness.upstream_calls(), arrivals);
|
||||
// The admission's revision check reads the carried session once; the wrong-kind form creates no
|
||||
// session and marks none initialized.
|
||||
assert_session_ops(
|
||||
"initialize as a notification",
|
||||
ops_before,
|
||||
harness.session_ops(),
|
||||
SessionOps {
|
||||
get: 1,
|
||||
create: 0,
|
||||
mark_initialized: 0,
|
||||
},
|
||||
);
|
||||
run_valid_legacy_call(
|
||||
&harness,
|
||||
&session,
|
||||
63,
|
||||
"follow-up-initialize-notification@example.com",
|
||||
"follow-up after the initialize notification",
|
||||
)
|
||||
.await;
|
||||
|
||||
// Form 2: `notifications/initialized` written as a request — the valid notification control with
|
||||
// only an `id` added. It must not create a session: the registered kind is a notification.
|
||||
run_valid_initialized_notification(&harness, &session, "control initialized notification")
|
||||
.await;
|
||||
|
||||
let mut initialized_request = initialized_notification();
|
||||
initialized_request["id"] = json!(72);
|
||||
assert!(initialized_request.get("id").is_some());
|
||||
|
||||
let before = harness.snapshot();
|
||||
let ops_before = harness.session_ops();
|
||||
let arrivals = harness.upstream_calls();
|
||||
let request = harness
|
||||
.post(
|
||||
&header_refs(&legacy_headers(&session)),
|
||||
&initialized_request,
|
||||
)
|
||||
.await;
|
||||
let request_body = json_body(request).await;
|
||||
assert_eq!(
|
||||
request_body["error"]["code"], -32601,
|
||||
"a request-shaped initialized notification is an unsupported method, got {request_body}"
|
||||
);
|
||||
assert_deltas(
|
||||
"initialized as a request",
|
||||
before,
|
||||
harness.snapshot(),
|
||||
Snapshot::new(1, 0, 1, 0),
|
||||
);
|
||||
assert_eq!(harness.upstream_calls(), arrivals);
|
||||
assert_session_ops(
|
||||
"initialized as a request",
|
||||
ops_before,
|
||||
harness.session_ops(),
|
||||
SessionOps {
|
||||
get: 1,
|
||||
create: 0,
|
||||
mark_initialized: 0,
|
||||
},
|
||||
);
|
||||
run_valid_legacy_call(
|
||||
&harness,
|
||||
&session,
|
||||
73,
|
||||
"follow-up-initialized-request@example.com",
|
||||
"follow-up after the initialized request",
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// §7.2 valid calls: the own era-adapter, the owning Tools service and exactly one outbound call per
|
||||
// call, with scoped outputs.
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
#[tokio::test]
|
||||
async fn dispatch_observer_valid_calls_enter_the_own_era_and_the_owning_tools_service() {
|
||||
let harness = Harness::started().await;
|
||||
let session = harness.initialize_legacy_session().await;
|
||||
|
||||
run_valid_legacy_call(
|
||||
&harness,
|
||||
&session,
|
||||
41,
|
||||
"legacy@example.com",
|
||||
"valid legacy tools/call",
|
||||
)
|
||||
.await;
|
||||
run_valid_modern_call(
|
||||
&harness,
|
||||
42,
|
||||
"modern@example.com",
|
||||
"valid modern tools/call",
|
||||
)
|
||||
.await;
|
||||
|
||||
// The legacy session never served the modern call: the legacy follow-up still works, with its own
|
||||
// scoped output, and the modern call did not consume it.
|
||||
run_valid_legacy_call(
|
||||
&harness,
|
||||
&session,
|
||||
43,
|
||||
"legacy-after-modern@example.com",
|
||||
"legacy follow-up after the modern call",
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// F5: the registration drives the *real* endpoint. One private inert method descriptor is added to a
|
||||
// copy of the production tables and served with this router; removing it again restores the rejection.
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
#[tokio::test]
|
||||
async fn dispatch_observer_registration_add_remove_changes_the_real_endpoint_dispatch() {
|
||||
// "Removed": the inert method is not registered, so both eras answer the era-correct -32601 and
|
||||
// nothing enters an era handler beyond the rejection, the service or the upstream.
|
||||
let without =
|
||||
Harness::started_with_registration(Some(Arc::new(registration_without_inert_method())))
|
||||
.await;
|
||||
let session = without.initialize_legacy_session().await;
|
||||
|
||||
let before = without.snapshot();
|
||||
let arrivals = without.upstream_calls();
|
||||
let unregistered = without
|
||||
.post(
|
||||
&header_refs(&legacy_headers(&session)),
|
||||
&json!({ "jsonrpc": "2.0", "id": 51, "method": INERT_METHOD_NAME, "params": {} }),
|
||||
)
|
||||
.await;
|
||||
let unregistered_body = json_body(unregistered).await;
|
||||
assert_eq!(
|
||||
unregistered_body["error"]["code"], -32601,
|
||||
"an unregistered method must stay unsupported, got {unregistered_body}"
|
||||
);
|
||||
assert_deltas(
|
||||
"inert method without a registration (legacy)",
|
||||
before,
|
||||
without.snapshot(),
|
||||
Snapshot::new(1, 0, 1, 0),
|
||||
);
|
||||
assert_eq!(without.upstream_calls(), arrivals);
|
||||
|
||||
let before = without.snapshot();
|
||||
let unregistered_modern = without
|
||||
.post(
|
||||
&[
|
||||
("MCP-Protocol-Version", MODERN_REVISION),
|
||||
("Mcp-Method", INERT_METHOD_NAME),
|
||||
("Mcp-Name", TOOL_NAME),
|
||||
],
|
||||
&json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": 52,
|
||||
"method": INERT_METHOD_NAME,
|
||||
"params": { "_meta": modern_meta() }
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
json_body(unregistered_modern).await["error"]["code"],
|
||||
-32601,
|
||||
"an unregistered modern method must stay unsupported"
|
||||
);
|
||||
assert_deltas(
|
||||
"inert method without a registration (modern)",
|
||||
before,
|
||||
without.snapshot(),
|
||||
Snapshot::new(1, 1, 0, 0),
|
||||
);
|
||||
|
||||
// "Added": the very same request now reaches the handler the registration maps it to — in both
|
||||
// eras, through the real router, with no change to the production tables.
|
||||
let with =
|
||||
Harness::started_with_registration(Some(Arc::new(registration_with_inert_method()))).await;
|
||||
let session = with.initialize_legacy_session().await;
|
||||
|
||||
let before = with.snapshot();
|
||||
let arrivals = with.upstream_calls();
|
||||
let dispatched = with
|
||||
.post(
|
||||
&header_refs(&legacy_headers(&session)),
|
||||
&json!({ "jsonrpc": "2.0", "id": 53, "method": INERT_METHOD_NAME, "params": {} }),
|
||||
)
|
||||
.await;
|
||||
let dispatched_body = json_body(dispatched).await;
|
||||
assert_eq!(
|
||||
dispatched_body["result"]["protocolVersion"], LEGACY_REVISION,
|
||||
"the registered method must reach its registered handler (legacy), got {dispatched_body}"
|
||||
);
|
||||
assert_deltas(
|
||||
"inert method with a registration (legacy)",
|
||||
before,
|
||||
with.snapshot(),
|
||||
Snapshot::new(1, 0, 1, 0),
|
||||
);
|
||||
assert_eq!(
|
||||
with.upstream_calls(),
|
||||
arrivals,
|
||||
"the inert handler is not the Tools service: no outbound call is made"
|
||||
);
|
||||
|
||||
let before = with.snapshot();
|
||||
let dispatched_modern = with
|
||||
.post(
|
||||
&[
|
||||
("MCP-Protocol-Version", MODERN_REVISION),
|
||||
("Mcp-Method", INERT_METHOD_NAME),
|
||||
("Mcp-Name", TOOL_NAME),
|
||||
],
|
||||
&json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": 54,
|
||||
"method": INERT_METHOD_NAME,
|
||||
"params": { "_meta": modern_meta() }
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
let dispatched_modern_body = json_body(dispatched_modern).await;
|
||||
assert_eq!(
|
||||
dispatched_modern_body["result"]["protocolVersion"], MODERN_REVISION,
|
||||
"the registered method must reach its registered handler (modern), got {dispatched_modern_body}"
|
||||
);
|
||||
assert_deltas(
|
||||
"inert method with a registration (modern)",
|
||||
before,
|
||||
with.snapshot(),
|
||||
Snapshot::new(1, 1, 0, 0),
|
||||
);
|
||||
|
||||
// The advertisement moves with the same registration snapshot: the inert capability is declared
|
||||
// by the observed registration and appears in the modern discovery result it serves.
|
||||
let discover = with
|
||||
.post(
|
||||
&[
|
||||
("MCP-Protocol-Version", MODERN_REVISION),
|
||||
("Mcp-Method", "server/discover"),
|
||||
],
|
||||
&json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": 55,
|
||||
"method": "server/discover",
|
||||
"params": { "_meta": modern_meta() }
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
let discover_body = json_body(discover).await;
|
||||
assert_eq!(
|
||||
discover_body["result"]["capabilities"]["inert_test_capability"]["enabled"], true,
|
||||
"the observed registration owns the advertisement too, got {discover_body}"
|
||||
);
|
||||
|
||||
let discover_without = without
|
||||
.post(
|
||||
&[
|
||||
("MCP-Protocol-Version", MODERN_REVISION),
|
||||
("Mcp-Method", "server/discover"),
|
||||
],
|
||||
&json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": 56,
|
||||
"method": "server/discover",
|
||||
"params": { "_meta": modern_meta() }
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
assert!(
|
||||
json_body(discover_without).await["result"]["capabilities"]
|
||||
.get("inert_test_capability")
|
||||
.is_none(),
|
||||
"a capability that is not registered in this snapshot must not be advertised"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,962 @@
|
||||
//! Fixtures and helpers of the in-crate section 7.2 test seam (`app::dispatch_observer`).
|
||||
//!
|
||||
//! This file is the `support` child module of `crate::app::dispatch_observer` (wired with `#[path]`
|
||||
//! there). It holds everything the observed tests need but no test itself: the real router harness,
|
||||
//! the counted session store, the counted loopback upstream, the registry/operation/agent fixtures
|
||||
//! and the shared assertions. It lives one directory above `src/app/` for the same reason the
|
||||
//! `tests` module does — `scripts/check-execution-boundaries.py` reserves that prefix for service
|
||||
//! modules without an HTTP client or a persistence dependency. Everything here is `#[cfg(test)]`.
|
||||
|
||||
//! Behavioural harness of the BUILD-internal semantic observer (Story 3.1 section 7.2).
|
||||
//!
|
||||
//! This file is the `tests` child module of `crate::app::dispatch_observer` (wired with `#[path]`
|
||||
//! there), so the module path — and therefore the sanctioned selector
|
||||
//! `cargo test -p crank-community-mcp --lib app::dispatch_observer::` — is unchanged. It is not a
|
||||
//! separate crate target and it is `#[cfg(test)]`-only.
|
||||
//!
|
||||
//! Why the file is not under `src/app/`: `scripts/check-execution-boundaries.py` treats the whole
|
||||
//! `crates/crank-community-mcp/src/app/` prefix as service-module scope and forbids an HTTP-client
|
||||
//! (`reqwest`) or persistence (`sqlx`/migration) dependency there. This harness needs both — a real
|
||||
//! PostgreSQL schema through `crank_test_support::postgres_schema_url` and a real request through the
|
||||
//! served router — so the harness sits one directory above the scoped prefix while the observer
|
||||
//! itself (markers, scope, counters, no dependency) stays at the approved `src/app/` path.
|
||||
|
||||
use std::{
|
||||
collections::BTreeMap,
|
||||
sync::{
|
||||
Arc,
|
||||
atomic::{AtomicUsize, Ordering},
|
||||
},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use axum::{Json, Router, extract::State, http::header, routing::post};
|
||||
use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
|
||||
use crank_core::{
|
||||
Agent, AgentId, AgentOperationBinding, AgentStatus, AgentVersion, ExecutionConfig, HttpMethod,
|
||||
Operation, OperationId, OperationStatus, PlatformApiKey, PlatformApiKeyId, PlatformApiKeyKind,
|
||||
PlatformApiKeyScope, PlatformApiKeyStatus, Protocol, RestTarget, Target, ToolDescription,
|
||||
ToolSelectionPolicy, WorkspaceId,
|
||||
};
|
||||
use crank_mapping::{MappingRule, MappingSet};
|
||||
use crank_registry::{
|
||||
CreateAgentRequest, CreatePlatformApiKeyRequest, PostgresRegistry, PublishAgentRequest,
|
||||
PublishRequest,
|
||||
};
|
||||
use crank_runtime::{
|
||||
InMemoryCoordinationStateStore, RequestRateLimitConfig, RequestRateLimiter, SecretCrypto,
|
||||
};
|
||||
use crank_schema::{Schema, SchemaKind};
|
||||
use serde_json::{Value, json};
|
||||
use sha2::{Digest, Sha256};
|
||||
use time::{OffsetDateTime, format_description::well_known::Rfc3339};
|
||||
use tokio::net::TcpListener;
|
||||
|
||||
use super::{observe, observe_with_registration};
|
||||
use crate::{
|
||||
auth::CommunityMachineCredentialVerifier,
|
||||
build_app,
|
||||
protocol::{
|
||||
CAPABILITY_DESCRIPTORS, CapabilityId, CapabilityIdDescriptor, CapabilityRegistry,
|
||||
FeatureSet, HeaderSet, Kind, METHOD_DESCRIPTORS, MethodDescriptor, MethodHandler, Roster,
|
||||
},
|
||||
session::{InMemorySessionStore, SessionState, SessionStoreError, TransportSessionStore},
|
||||
};
|
||||
|
||||
pub(super) const LEGACY_REVISION: &str = "2025-11-25";
|
||||
pub(super) const MODERN_REVISION: &str = "2026-07-28";
|
||||
pub(super) const TOOL_NAME: &str = "create_lead";
|
||||
pub(super) const WORKSPACE_SLUG: &str = "default";
|
||||
pub(super) const AGENT_SLUG: &str = "dispatch-observer";
|
||||
pub(super) const META_PROTOCOL_VERSION: &str = "io.modelcontextprotocol/protocolVersion";
|
||||
pub(super) const META_CLIENT_CAPABILITIES: &str = "io.modelcontextprotocol/clientCapabilities";
|
||||
pub(super) const META_CLIENT_INFO: &str = "io.modelcontextprotocol/clientInfo";
|
||||
|
||||
/// One observed endpoint: the real router, the observer that counts its own requests and the counted
|
||||
/// loopback upstream that every real tool execution must reach.
|
||||
pub(super) struct Harness {
|
||||
client: reqwest::Client,
|
||||
mcp_url: String,
|
||||
api_key: String,
|
||||
counters: Arc<CounterSet>,
|
||||
session_counters: Arc<SessionCounters>,
|
||||
upstream_calls: Arc<AtomicUsize>,
|
||||
}
|
||||
|
||||
pub(super) struct Upstream {
|
||||
base_url: String,
|
||||
calls: Arc<AtomicUsize>,
|
||||
}
|
||||
|
||||
/// The session-store operations of the observed requests (section 7.2 honest naming: these count
|
||||
/// *session-store operations*, never dispatch, era or service entries).
|
||||
#[derive(Debug, Default)]
|
||||
pub(super) struct SessionCounters {
|
||||
get: AtomicUsize,
|
||||
create: AtomicUsize,
|
||||
mark_initialized: AtomicUsize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(super) struct SessionOps {
|
||||
pub(super) get: usize,
|
||||
pub(super) create: usize,
|
||||
pub(super) mark_initialized: usize,
|
||||
}
|
||||
|
||||
impl SessionCounters {
|
||||
pub(super) fn snapshot(&self) -> SessionOps {
|
||||
SessionOps {
|
||||
get: self.get.load(Ordering::SeqCst),
|
||||
create: self.create.load(Ordering::SeqCst),
|
||||
mark_initialized: self.mark_initialized.load(Ordering::SeqCst),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The observed session store: one real `InMemorySessionStore` plus per-operation counters, so a
|
||||
/// request that touches the session store before (or instead of) the expected path is visible.
|
||||
#[derive(Default)]
|
||||
pub(super) struct CountedSessionStore {
|
||||
inner: InMemorySessionStore,
|
||||
counters: Arc<SessionCounters>,
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl TransportSessionStore for CountedSessionStore {
|
||||
async fn create(
|
||||
&self,
|
||||
protocol_version: &str,
|
||||
workspace_slug: &str,
|
||||
agent_slug: &str,
|
||||
supports_elicitation: bool,
|
||||
now: OffsetDateTime,
|
||||
expires_at: Option<OffsetDateTime>,
|
||||
) -> Result<String, SessionStoreError> {
|
||||
self.counters.create.fetch_add(1, Ordering::SeqCst);
|
||||
self.inner
|
||||
.create(
|
||||
protocol_version,
|
||||
workspace_slug,
|
||||
agent_slug,
|
||||
supports_elicitation,
|
||||
now,
|
||||
expires_at,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn get(&self, session_id: &str) -> Result<Option<SessionState>, SessionStoreError> {
|
||||
self.counters.get.fetch_add(1, Ordering::SeqCst);
|
||||
self.inner.get(session_id).await
|
||||
}
|
||||
|
||||
async fn mark_initialized(
|
||||
&self,
|
||||
session_id: &str,
|
||||
now: OffsetDateTime,
|
||||
) -> Result<bool, SessionStoreError> {
|
||||
self.counters
|
||||
.mark_initialized
|
||||
.fetch_add(1, Ordering::SeqCst);
|
||||
self.inner.mark_initialized(session_id, now).await
|
||||
}
|
||||
|
||||
async fn delete(&self, session_id: &str) -> Result<bool, SessionStoreError> {
|
||||
self.inner.delete(session_id).await
|
||||
}
|
||||
|
||||
async fn cleanup_expired(&self, now: OffsetDateTime) -> Result<u64, SessionStoreError> {
|
||||
self.inner.cleanup_expired(now).await
|
||||
}
|
||||
|
||||
async fn active_count(&self, now: OffsetDateTime) -> Result<u64, SessionStoreError> {
|
||||
self.inner.active_count(now).await
|
||||
}
|
||||
}
|
||||
|
||||
impl Harness {
|
||||
pub(super) async fn started() -> Self {
|
||||
Self::started_with_registration(None).await
|
||||
}
|
||||
|
||||
/// One observed endpoint, optionally served with an explicit registration snapshot (F5: the
|
||||
/// add/remove proof runs against this real router, not against a registry unit query).
|
||||
pub(super) async fn started_with_registration(
|
||||
registration: Option<Arc<CapabilityRegistry>>,
|
||||
) -> Self {
|
||||
let registry = test_registry().await;
|
||||
let upstream = spawn_counted_upstream().await;
|
||||
let operation = test_operation(&upstream.base_url);
|
||||
let workspace_id = workspace_id();
|
||||
registry
|
||||
.create_operation(&workspace_id, &operation, Some("alice"))
|
||||
.await
|
||||
.expect("the operation must be created");
|
||||
registry
|
||||
.publish_operation(PublishRequest {
|
||||
workspace_id: &workspace_id,
|
||||
operation_id: &operation.id,
|
||||
version: 1,
|
||||
published_at: &test_time(),
|
||||
published_by: Some("alice"),
|
||||
})
|
||||
.await
|
||||
.expect("the operation must be published");
|
||||
publish_agent(®istry, &operation).await;
|
||||
let api_key = create_api_key(®istry).await;
|
||||
|
||||
let counters = Arc::new(CounterSet::default());
|
||||
let session_counters = Arc::new(SessionCounters::default());
|
||||
let sessions = Arc::new(CountedSessionStore {
|
||||
inner: InMemorySessionStore::default(),
|
||||
counters: Arc::clone(&session_counters),
|
||||
});
|
||||
let app = observe_requests(
|
||||
build_app(
|
||||
registry,
|
||||
Duration::from_millis(0),
|
||||
Some("https://crank.example.com".to_owned()),
|
||||
SecretCrypto::new("test-master-key-00000000000000000000000000000000")
|
||||
.expect("a valid test master key"),
|
||||
crank_runtime::community_with_outbound_policy(
|
||||
crank_runtime::OutboundHttpPolicy::allowing_hosts(["127.0.0.1"]),
|
||||
)
|
||||
.build(),
|
||||
RequestRateLimiter::new(
|
||||
RequestRateLimitConfig::new(10_000, 10_000).expect("a valid rate limit"),
|
||||
),
|
||||
Arc::new(InMemoryCoordinationStateStore::default()),
|
||||
sessions,
|
||||
Arc::new(CommunityMachineCredentialVerifier),
|
||||
),
|
||||
Arc::clone(&counters),
|
||||
registration,
|
||||
);
|
||||
let base_url = spawn_server(app).await;
|
||||
|
||||
Self {
|
||||
client: reqwest::Client::new(),
|
||||
mcp_url: format!("{base_url}/v1/{WORKSPACE_SLUG}/{AGENT_SLUG}"),
|
||||
api_key,
|
||||
counters,
|
||||
session_counters,
|
||||
upstream_calls: upstream.calls,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn snapshot(&self) -> Snapshot {
|
||||
self.counters.snapshot()
|
||||
}
|
||||
|
||||
pub(super) fn session_ops(&self) -> SessionOps {
|
||||
self.session_counters.snapshot()
|
||||
}
|
||||
|
||||
pub(super) fn upstream_calls(&self) -> usize {
|
||||
self.upstream_calls.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
pub(super) async fn post(&self, headers: &[(&str, &str)], body: &Value) -> reqwest::Response {
|
||||
let mut request = self
|
||||
.client
|
||||
.post(&self.mcp_url)
|
||||
.header(header::ACCEPT, "application/json, text/event-stream")
|
||||
.header(header::AUTHORIZATION, format!("Bearer {}", self.api_key));
|
||||
for (name, value) in headers {
|
||||
request = request.header(*name, *value);
|
||||
}
|
||||
request
|
||||
.json(body)
|
||||
.send()
|
||||
.await
|
||||
.expect("the observed request must complete")
|
||||
}
|
||||
|
||||
/// A legacy session, primed through the real lifecycle methods.
|
||||
pub(super) async fn initialize_legacy_session(&self) -> String {
|
||||
let response = self
|
||||
.post(
|
||||
&[("MCP-Protocol-Version", LEGACY_REVISION)],
|
||||
&json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": 1,
|
||||
"method": "initialize",
|
||||
"params": { "protocolVersion": LEGACY_REVISION, "capabilities": {} }
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
response.status().as_u16(),
|
||||
200,
|
||||
"the legacy initialize must succeed"
|
||||
);
|
||||
let session_id = response
|
||||
.headers()
|
||||
.get("MCP-Session-Id")
|
||||
.expect("initialize must mint a session")
|
||||
.to_str()
|
||||
.expect("the session id must be a header string")
|
||||
.to_owned();
|
||||
|
||||
let initialized = self
|
||||
.post(
|
||||
&[
|
||||
("MCP-Protocol-Version", LEGACY_REVISION),
|
||||
("MCP-Session-Id", session_id.as_str()),
|
||||
],
|
||||
&json!({
|
||||
"jsonrpc": "2.0",
|
||||
"method": "notifications/initialized",
|
||||
"params": {}
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
initialized.status().as_u16(),
|
||||
202,
|
||||
"the initialized notification must be acknowledged"
|
||||
);
|
||||
session_id
|
||||
}
|
||||
}
|
||||
|
||||
/// Install the request-scoped observer (and, when given, the F5 registration snapshot) around every
|
||||
/// request of this router.
|
||||
///
|
||||
/// The layer runs inside the request task and awaits the inner service, so the markers deep in the
|
||||
/// handler see exactly this request's counters and the dispatch asks exactly this request's
|
||||
/// registration. Nothing global is mutated.
|
||||
pub(super) fn observe_requests(
|
||||
app: Router,
|
||||
counters: Arc<CounterSet>,
|
||||
registration: Option<Arc<CapabilityRegistry>>,
|
||||
) -> Router {
|
||||
app.layer(axum::middleware::from_fn(
|
||||
move |request: axum::extract::Request, next: axum::middleware::Next| {
|
||||
let counters = Arc::clone(&counters);
|
||||
let registration = registration.clone();
|
||||
async move {
|
||||
match registration {
|
||||
Some(registration) => {
|
||||
observe_with_registration(
|
||||
registration,
|
||||
observe(counters, next.run(request)),
|
||||
)
|
||||
.await
|
||||
}
|
||||
None => observe(counters, next.run(request)).await,
|
||||
}
|
||||
}
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) async fn spawn_server(app: Router) -> String {
|
||||
let listener = TcpListener::bind("127.0.0.1:0")
|
||||
.await
|
||||
.expect("a loopback listener must bind");
|
||||
let address = listener
|
||||
.local_addr()
|
||||
.expect("a bound listener has an address");
|
||||
tokio::spawn(async move {
|
||||
let _ = axum::serve(listener, app).await;
|
||||
});
|
||||
format!("http://{address}")
|
||||
}
|
||||
|
||||
/// The counted loopback upstream: every arrival is one real outbound tool execution.
|
||||
pub(super) async fn spawn_counted_upstream() -> Upstream {
|
||||
let calls = Arc::new(AtomicUsize::new(0));
|
||||
let state = Arc::clone(&calls);
|
||||
let app = Router::new()
|
||||
.route("/crm/leads", post(create_lead))
|
||||
.with_state(state);
|
||||
Upstream {
|
||||
base_url: spawn_server(app).await,
|
||||
calls,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn create_lead(
|
||||
State(calls): State<Arc<AtomicUsize>>,
|
||||
Json(payload): Json<Value>,
|
||||
) -> Json<Value> {
|
||||
calls.fetch_add(1, Ordering::SeqCst);
|
||||
// The fixture echoes the request's own payload in its identifier, so every valid call has a
|
||||
// *distinguishable* scoped output: two valid calls can never be confused with one another
|
||||
// (section 7.2 requires a scoped output per case, not one shared constant).
|
||||
let email = payload["email"].as_str().unwrap_or("unknown").to_owned();
|
||||
Json(json!({ "id": format!("lead_for_{email}"), "email": payload["email"] }))
|
||||
}
|
||||
|
||||
pub(super) async fn test_registry() -> PostgresRegistry {
|
||||
let database_url = crank_test_support::postgres_schema_url("crank_dispatch_observer").await;
|
||||
let pool = sqlx::PgPool::connect(&database_url)
|
||||
.await
|
||||
.expect("the test PostgreSQL must accept connections");
|
||||
crank_registry::MigrationAuthority::apply(&pool)
|
||||
.await
|
||||
.expect("the migrations must apply");
|
||||
PostgresRegistry::connect(&database_url)
|
||||
.await
|
||||
.expect("the registry must connect")
|
||||
}
|
||||
|
||||
pub(super) fn test_time() -> OffsetDateTime {
|
||||
OffsetDateTime::parse("2026-03-26T10:00:00Z", &Rfc3339).expect("a pinned timestamp")
|
||||
}
|
||||
|
||||
pub(super) fn workspace_id() -> WorkspaceId {
|
||||
WorkspaceId::new("ws_default")
|
||||
}
|
||||
|
||||
pub(super) fn agent_id() -> AgentId {
|
||||
AgentId::new(format!("agent_{AGENT_SLUG}"))
|
||||
}
|
||||
|
||||
pub(super) async fn publish_agent(
|
||||
registry: &PostgresRegistry,
|
||||
operation: &Operation<Schema, MappingSet>,
|
||||
) {
|
||||
let agent = Agent {
|
||||
id: agent_id(),
|
||||
workspace_id: workspace_id(),
|
||||
slug: AGENT_SLUG.to_owned(),
|
||||
display_name: "Dispatch observer agent".to_owned(),
|
||||
description: "Curated MCP toolset".to_owned(),
|
||||
status: AgentStatus::Draft,
|
||||
current_draft_version: 1,
|
||||
latest_published_version: None,
|
||||
created_at: test_time(),
|
||||
updated_at: test_time(),
|
||||
published_at: None,
|
||||
};
|
||||
let version = AgentVersion {
|
||||
agent_id: agent_id(),
|
||||
version: 1,
|
||||
status: AgentStatus::Draft,
|
||||
instructions: json!({}),
|
||||
tool_selection_policy: ToolSelectionPolicy::default(),
|
||||
created_at: test_time(),
|
||||
};
|
||||
let bindings = vec![AgentOperationBinding {
|
||||
operation_id: operation.id.clone(),
|
||||
operation_version: 1,
|
||||
tool_name: operation.name.clone(),
|
||||
tool_title: operation.tool_description.title.clone(),
|
||||
tool_description_override: None,
|
||||
enabled: true,
|
||||
}];
|
||||
|
||||
registry
|
||||
.create_agent(CreateAgentRequest {
|
||||
agent: &agent,
|
||||
version: &version,
|
||||
bindings: &bindings,
|
||||
})
|
||||
.await
|
||||
.expect("the agent must be created");
|
||||
registry
|
||||
.publish_agent(PublishAgentRequest {
|
||||
workspace_id: &workspace_id(),
|
||||
agent_id: &agent_id(),
|
||||
version: 1,
|
||||
published_at: &test_time(),
|
||||
published_by: Some("alice"),
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.expect("the agent must be published");
|
||||
}
|
||||
|
||||
pub(super) async fn create_api_key(registry: &PostgresRegistry) -> String {
|
||||
let secret = format!("crk_dispatch_observer_{}", uuid::Uuid::now_v7().simple());
|
||||
let api_key = PlatformApiKey {
|
||||
id: PlatformApiKeyId::new("pk_dispatch_observer"),
|
||||
workspace_id: workspace_id(),
|
||||
agent_id: Some(agent_id()),
|
||||
key_kind: PlatformApiKeyKind::McpClient,
|
||||
name: "dispatch-observer".to_owned(),
|
||||
prefix: secret.chars().take(16).collect(),
|
||||
scopes: vec![PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
|
||||
status: PlatformApiKeyStatus::Active,
|
||||
created_at: test_time(),
|
||||
last_used_at: None,
|
||||
expires_at: None,
|
||||
allowed_origins: Vec::new(),
|
||||
};
|
||||
registry
|
||||
.create_platform_api_key(CreatePlatformApiKeyRequest {
|
||||
api_key: &api_key,
|
||||
secret_hash: &hash_access_secret(&secret),
|
||||
})
|
||||
.await
|
||||
.expect("the API key must be created");
|
||||
secret
|
||||
}
|
||||
|
||||
pub(super) fn hash_access_secret(secret: &str) -> String {
|
||||
URL_SAFE_NO_PAD.encode(Sha256::digest(secret.as_bytes()))
|
||||
}
|
||||
|
||||
pub(super) fn test_operation(base_url: &str) -> Operation<Schema, MappingSet> {
|
||||
Operation {
|
||||
id: OperationId::new(format!("op_{TOOL_NAME}")),
|
||||
name: TOOL_NAME.to_owned(),
|
||||
display_name: "Create Lead".to_owned(),
|
||||
category: "sales".to_owned(),
|
||||
protocol: Protocol::Rest,
|
||||
security_level: crank_core::OperationSecurityLevel::Standard,
|
||||
status: OperationStatus::Published,
|
||||
version: 1,
|
||||
target: Target::Rest(RestTarget {
|
||||
base_url: base_url.to_owned(),
|
||||
method: HttpMethod::Post,
|
||||
path_template: "/crm/leads".to_owned(),
|
||||
static_headers: BTreeMap::new(),
|
||||
request_contract: None,
|
||||
response_contract: Vec::new(),
|
||||
multipart_field_mime_types: BTreeMap::new(),
|
||||
}),
|
||||
input_schema: object_schema("email"),
|
||||
output_schema: object_schema("id"),
|
||||
input_mapping: MappingSet {
|
||||
rules: vec![MappingRule {
|
||||
source: "$.mcp.email".to_owned(),
|
||||
target: "$.request.body.email".to_owned(),
|
||||
required: true,
|
||||
default_value: None,
|
||||
transform: None,
|
||||
condition: None,
|
||||
notes: None,
|
||||
}],
|
||||
},
|
||||
output_mapping: MappingSet {
|
||||
rules: vec![MappingRule {
|
||||
source: "$.response.body.id".to_owned(),
|
||||
target: "$.output.id".to_owned(),
|
||||
required: true,
|
||||
default_value: None,
|
||||
transform: None,
|
||||
condition: None,
|
||||
notes: None,
|
||||
}],
|
||||
},
|
||||
execution_config: ExecutionConfig {
|
||||
timeout_ms: 1_000,
|
||||
retry_policy: None,
|
||||
response_cache: None,
|
||||
idempotency: None,
|
||||
safety: None,
|
||||
approval_policy: None,
|
||||
auth_profile_ref: None,
|
||||
headers: BTreeMap::new(),
|
||||
},
|
||||
tool_description: ToolDescription {
|
||||
title: "Create Lead".to_owned(),
|
||||
description: "Creates a CRM lead".to_owned(),
|
||||
tags: Vec::new(),
|
||||
examples: Vec::new(),
|
||||
},
|
||||
samples: None,
|
||||
generated_draft: None,
|
||||
config_export: None,
|
||||
wizard_state: None,
|
||||
created_at: test_time(),
|
||||
updated_at: test_time(),
|
||||
published_at: Some(test_time()),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn object_schema(field_name: &str) -> Schema {
|
||||
Schema {
|
||||
kind: SchemaKind::Object,
|
||||
format: None,
|
||||
description: None,
|
||||
required: true,
|
||||
nullable: false,
|
||||
default_value: None,
|
||||
fields: BTreeMap::from([(
|
||||
field_name.to_owned(),
|
||||
Schema {
|
||||
kind: SchemaKind::String,
|
||||
format: None,
|
||||
description: None,
|
||||
required: true,
|
||||
nullable: false,
|
||||
default_value: None,
|
||||
fields: BTreeMap::new(),
|
||||
items: None,
|
||||
enum_values: Vec::new(),
|
||||
variants: Vec::new(),
|
||||
},
|
||||
)]),
|
||||
items: None,
|
||||
enum_values: Vec::new(),
|
||||
variants: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn modern_meta() -> Value {
|
||||
json!({
|
||||
META_PROTOCOL_VERSION: MODERN_REVISION,
|
||||
META_CLIENT_CAPABILITIES: {},
|
||||
META_CLIENT_INFO: { "name": "crank-dispatch-observer", "version": "0.1.0" }
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn legacy_tool_call(id: u64, email: &str) -> Value {
|
||||
json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": id,
|
||||
"method": "tools/call",
|
||||
"params": { "name": TOOL_NAME, "arguments": { "email": email } }
|
||||
})
|
||||
}
|
||||
|
||||
/// One legacy `initialize` request body (the valid request form of the lifecycle operation).
|
||||
pub(super) fn legacy_initialize(id: u64) -> Value {
|
||||
json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": id,
|
||||
"method": "initialize",
|
||||
"params": { "protocolVersion": LEGACY_REVISION, "capabilities": {} }
|
||||
})
|
||||
}
|
||||
|
||||
/// One legacy `notifications/initialized` notification body (the valid notification form).
|
||||
///
|
||||
/// The `params` carry a valid `InitializeParams` payload so that the *only* difference from its
|
||||
/// request-shaped negative is the presence of `id`: a wire name must never be served as the other
|
||||
/// lifecycle action because of the envelope kind (G2).
|
||||
pub(super) fn initialized_notification() -> Value {
|
||||
json!({
|
||||
"jsonrpc": "2.0",
|
||||
"method": "notifications/initialized",
|
||||
"params": { "protocolVersion": LEGACY_REVISION, "capabilities": {} }
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn modern_tool_call(id: u64, email: &str) -> Value {
|
||||
json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": id,
|
||||
"method": "tools/call",
|
||||
"params": {
|
||||
"_meta": modern_meta(),
|
||||
"name": TOOL_NAME,
|
||||
"arguments": { "email": email }
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn legacy_headers(session_id: &str) -> Vec<(&'static str, String)> {
|
||||
vec![
|
||||
("MCP-Protocol-Version", LEGACY_REVISION.to_owned()),
|
||||
("MCP-Session-Id", session_id.to_owned()),
|
||||
]
|
||||
}
|
||||
|
||||
pub(super) fn modern_headers() -> Vec<(&'static str, String)> {
|
||||
vec![
|
||||
("MCP-Protocol-Version", MODERN_REVISION.to_owned()),
|
||||
("Mcp-Method", "tools/call".to_owned()),
|
||||
("Mcp-Name", TOOL_NAME.to_owned()),
|
||||
]
|
||||
}
|
||||
|
||||
pub(super) fn header_refs<'a>(
|
||||
headers: &'a [(&'static str, String)],
|
||||
) -> Vec<(&'static str, &'a str)> {
|
||||
headers
|
||||
.iter()
|
||||
.map(|(name, value)| (*name, value.as_str()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(super) async fn json_body(response: reqwest::Response) -> Value {
|
||||
let status = response.status();
|
||||
let body = response
|
||||
.text()
|
||||
.await
|
||||
.expect("the observed response body must be readable");
|
||||
serde_json::from_str(&body).unwrap_or_else(|error| {
|
||||
panic!("expected a JSON-RPC body, got status {status} body {body:?}: {error}")
|
||||
})
|
||||
}
|
||||
|
||||
/// Compare the marker deltas of one observed request with the section 7.2 table row.
|
||||
pub(super) fn assert_deltas(case: &str, before: Snapshot, after: Snapshot, expected: Snapshot) {
|
||||
let actual = Snapshot::new(
|
||||
after.admission - before.admission,
|
||||
after.era_modern - before.era_modern,
|
||||
after.era_legacy - before.era_legacy,
|
||||
after.tools_service - before.tools_service,
|
||||
);
|
||||
assert_eq!(
|
||||
actual, expected,
|
||||
"{case}: admission/era-modern/era-legacy/tools-service deltas must be \
|
||||
(admission, era_modern, era_legacy, tools_service) = {expected:?}, got {actual:?}"
|
||||
);
|
||||
}
|
||||
|
||||
pub(super) fn assert_no_result(case: &str, body: &Value) {
|
||||
assert!(
|
||||
body.get("result").is_none(),
|
||||
"{case}: a rejected request must not return a result, got {body}"
|
||||
);
|
||||
assert!(
|
||||
!body["error"].is_null(),
|
||||
"{case}: a rejected request must return a JSON-RPC error, got {body}"
|
||||
);
|
||||
}
|
||||
|
||||
/// Compare the session-store operation deltas of one observed request.
|
||||
///
|
||||
/// Section 7.2 honest naming: these counters count *session-store operations* (`get`/`create`/
|
||||
/// `mark_initialized`), never dispatch, era-adapter or service entries — an in-service branch can
|
||||
/// reject before any outbound call, so no conclusion about a service entry is drawn from them.
|
||||
pub(super) fn assert_session_ops(
|
||||
case: &str,
|
||||
before: SessionOps,
|
||||
after: SessionOps,
|
||||
expected: SessionOps,
|
||||
) {
|
||||
let actual = SessionOps {
|
||||
get: after.get - before.get,
|
||||
create: after.create - before.create,
|
||||
mark_initialized: after.mark_initialized - before.mark_initialized,
|
||||
};
|
||||
assert_eq!(
|
||||
actual, expected,
|
||||
"{case}: session-store operation deltas (get, create, mark_initialized) must be {expected:?}, \
|
||||
got {actual:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// The scoped output of one valid call: the fixture echoes the request's own payload.
|
||||
pub(super) fn assert_scoped_output(case: &str, body: &Value, email: &str) {
|
||||
assert_eq!(
|
||||
body["result"]["structuredContent"]["id"],
|
||||
format!("lead_for_{email}"),
|
||||
"{case}: the valid call must return *its own* scoped output, got {body}"
|
||||
);
|
||||
}
|
||||
|
||||
/// One valid legacy `tools/call`: its own era-adapter, the owning Tools service, exactly one outbound
|
||||
/// call, the request's own scoped output and the admission's session reads.
|
||||
pub(super) async fn run_valid_legacy_call(
|
||||
harness: &Harness,
|
||||
session: &str,
|
||||
id: u64,
|
||||
email: &str,
|
||||
case: &str,
|
||||
) {
|
||||
let before = harness.snapshot();
|
||||
let ops_before = harness.session_ops();
|
||||
let arrivals = harness.upstream_calls();
|
||||
let response = harness
|
||||
.post(
|
||||
&header_refs(&legacy_headers(session)),
|
||||
&legacy_tool_call(id, email),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
response.status().as_u16(),
|
||||
200,
|
||||
"{case}: a valid legacy call must be served"
|
||||
);
|
||||
let body = json_body(response).await;
|
||||
assert_scoped_output(case, &body, email);
|
||||
assert_deltas(case, before, harness.snapshot(), Snapshot::new(1, 0, 1, 1));
|
||||
assert_eq!(
|
||||
harness.upstream_calls() - arrivals,
|
||||
1,
|
||||
"{case}: a valid call makes exactly one outbound call"
|
||||
);
|
||||
// A legacy request that carries a session is read by the admission (revision check) and again by
|
||||
// the adapter's session requirement: two reads, no creation and no mutation of the session.
|
||||
assert_session_ops(
|
||||
case,
|
||||
ops_before,
|
||||
harness.session_ops(),
|
||||
SessionOps {
|
||||
get: 2,
|
||||
create: 0,
|
||||
mark_initialized: 0,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// One valid legacy `initialize` request: mints its own session, enters its own era-adapter, never
|
||||
/// touches the Tools service and makes no outbound call (the request-form control of G2).
|
||||
pub(super) async fn run_valid_legacy_initialize(harness: &Harness, id: u64, case: &str) {
|
||||
let before = harness.snapshot();
|
||||
let ops_before = harness.session_ops();
|
||||
let arrivals = harness.upstream_calls();
|
||||
let response = harness
|
||||
.post(
|
||||
&[("MCP-Protocol-Version", LEGACY_REVISION)],
|
||||
&legacy_initialize(id),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
response.status().as_u16(),
|
||||
200,
|
||||
"{case}: a valid legacy initialize must be served"
|
||||
);
|
||||
let session_id = response
|
||||
.headers()
|
||||
.get("MCP-Session-Id")
|
||||
.expect("a valid initialize must mint a session")
|
||||
.to_str()
|
||||
.expect("the session id must be a header string")
|
||||
.to_owned();
|
||||
assert!(
|
||||
!session_id.is_empty(),
|
||||
"{case}: the minted session id must not be empty"
|
||||
);
|
||||
let body = json_body(response).await;
|
||||
assert_eq!(
|
||||
body["result"]["protocolVersion"], LEGACY_REVISION,
|
||||
"{case}: the initialize result must name the negotiated revision, got {body}"
|
||||
);
|
||||
assert_deltas(case, before, harness.snapshot(), Snapshot::new(1, 0, 1, 0));
|
||||
assert_eq!(harness.upstream_calls(), arrivals);
|
||||
// The initialize request itself carries no session carrier, so the admission never reads the
|
||||
// store: the one operation is the session creation of the lifecycle handler.
|
||||
assert_session_ops(
|
||||
case,
|
||||
ops_before,
|
||||
harness.session_ops(),
|
||||
SessionOps {
|
||||
get: 0,
|
||||
create: 1,
|
||||
mark_initialized: 0,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// One valid legacy `notifications/initialized` on an existing session: acknowledged, its own
|
||||
/// era-adapter, no Tools service, no outbound call, exactly one session initialization (G2 control).
|
||||
pub(super) async fn run_valid_initialized_notification(
|
||||
harness: &Harness,
|
||||
session: &str,
|
||||
case: &str,
|
||||
) {
|
||||
let before = harness.snapshot();
|
||||
let ops_before = harness.session_ops();
|
||||
let arrivals = harness.upstream_calls();
|
||||
let response = harness
|
||||
.post(
|
||||
&header_refs(&legacy_headers(session)),
|
||||
&initialized_notification(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
response.status().as_u16(),
|
||||
202,
|
||||
"{case}: the initialized notification must be acknowledged"
|
||||
);
|
||||
assert_deltas(case, before, harness.snapshot(), Snapshot::new(1, 0, 1, 0));
|
||||
assert_eq!(harness.upstream_calls(), arrivals);
|
||||
// The admission's revision check reads the carried session, and the lifecycle handler reads it
|
||||
// once more before marking it initialized.
|
||||
assert_session_ops(
|
||||
case,
|
||||
ops_before,
|
||||
harness.session_ops(),
|
||||
SessionOps {
|
||||
get: 2,
|
||||
create: 0,
|
||||
mark_initialized: 1,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// One valid modern `tools/call`: its own era-adapter, the owning Tools service, exactly one outbound
|
||||
/// call, its own scoped output and *no* session-store operation at all (the modern era is stateless).
|
||||
pub(super) async fn run_valid_modern_call(harness: &Harness, id: u64, email: &str, case: &str) {
|
||||
let before = harness.snapshot();
|
||||
let ops_before = harness.session_ops();
|
||||
let arrivals = harness.upstream_calls();
|
||||
let response = harness
|
||||
.post(
|
||||
&header_refs(&modern_headers()),
|
||||
&modern_tool_call(id, email),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
response.status().as_u16(),
|
||||
200,
|
||||
"{case}: a valid modern call must be served"
|
||||
);
|
||||
let body = json_body(response).await;
|
||||
assert_scoped_output(case, &body, email);
|
||||
assert_eq!(body["result"]["resultType"], "complete");
|
||||
assert_deltas(case, before, harness.snapshot(), Snapshot::new(1, 1, 0, 1));
|
||||
assert_eq!(
|
||||
harness.upstream_calls() - arrivals,
|
||||
1,
|
||||
"{case}: a valid call makes exactly one outbound call"
|
||||
);
|
||||
assert_session_ops(
|
||||
case,
|
||||
ops_before,
|
||||
harness.session_ops(),
|
||||
SessionOps {
|
||||
get: 0,
|
||||
create: 0,
|
||||
mark_initialized: 0,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// The inert private registration used by the F5 add/remove proof (never registered in production).
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
/// The inert private capability and method used only by the F5 proof (never registered in production).
|
||||
pub(super) fn inert_registration_extra() -> (CapabilityIdDescriptor, MethodDescriptor) {
|
||||
(
|
||||
CapabilityIdDescriptor {
|
||||
id: CapabilityId::InertTest,
|
||||
roster: Roster::Server,
|
||||
kind: Kind::Capability,
|
||||
extension: None,
|
||||
deprecated: None,
|
||||
sub_features: FeatureSet(&["enabled"]),
|
||||
advertised: Some(("inert_test_capability", &[("enabled", true)])),
|
||||
revisions: &[MODERN_REVISION, LEGACY_REVISION],
|
||||
},
|
||||
MethodDescriptor {
|
||||
name: INERT_METHOD_NAME,
|
||||
capability: CapabilityId::InertTest,
|
||||
kind: Kind::Method,
|
||||
required_headers: HeaderSet(&[]),
|
||||
handler: MethodHandler::Ping,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) const INERT_METHOD_NAME: &str = "inert/echo";
|
||||
|
||||
/// See [`inert_registration_extra`]: the "remove" case is the production registration itself (no inert
|
||||
/// capability, no inert method); the "add" case is the same tables plus the inert descriptor pair.
|
||||
pub(super) fn registration_without_inert_method() -> CapabilityRegistry {
|
||||
CapabilityRegistry::new(CAPABILITY_DESCRIPTORS, METHOD_DESCRIPTORS)
|
||||
.expect("the production tables are a valid registration")
|
||||
}
|
||||
|
||||
pub(super) fn registration_with_inert_method() -> CapabilityRegistry {
|
||||
let mut capabilities = CAPABILITY_DESCRIPTORS.to_vec();
|
||||
capabilities.push(inert_registration_extra().0);
|
||||
let mut methods = METHOD_DESCRIPTORS.to_vec();
|
||||
methods.push(inert_registration_extra().1);
|
||||
CapabilityRegistry::new(&capabilities, &methods)
|
||||
.expect("the inert method descriptor is a valid registration")
|
||||
}
|
||||
|
||||
// Re-exported for the sibling `tests` module.
|
||||
pub(super) use super::{CounterSet, Snapshot};
|
||||
@@ -1,12 +1,33 @@
|
||||
use serde_json::{Value, json};
|
||||
|
||||
pub const CURRENT_PROTOCOL_VERSION: &str = "2025-11-25";
|
||||
pub const DEFAULT_PROTOCOL_VERSION: &str = "2025-03-26";
|
||||
pub const SUPPORTED_PROTOCOL_VERSIONS: &[&str] = &[
|
||||
DEFAULT_PROTOCOL_VERSION,
|
||||
"2025-06-18",
|
||||
CURRENT_PROTOCOL_VERSION,
|
||||
];
|
||||
/// The two approved MCP revisions (`docs/`-approved window of 2026-10-11).
|
||||
pub const MODERN_PROTOCOL_VERSION: &str = "2026-07-28";
|
||||
pub const LEGACY_PROTOCOL_VERSION: &str = "2025-11-25";
|
||||
|
||||
/// Revisions that stay in the code base but are no longer advertised or served.
|
||||
pub const WITHDRAWN_PROTOCOL_VERSIONS: &[&str] = &["2025-06-18", "2025-03-26"];
|
||||
|
||||
pub const SUPPORTED_PROTOCOL_VERSIONS: &[&str] =
|
||||
&[MODERN_PROTOCOL_VERSION, LEGACY_PROTOCOL_VERSION];
|
||||
|
||||
/// Backwards-compatible name for the legacy session revision, kept because existing in-crate tests
|
||||
/// and call sites refer to it. It is *not* an implicit default for an unidentified request.
|
||||
pub const CURRENT_PROTOCOL_VERSION: &str = LEGACY_PROTOCOL_VERSION;
|
||||
|
||||
/// Request `_meta` keys used by the modern stateless era.
|
||||
pub const META_PROTOCOL_VERSION_KEY: &str = "io.modelcontextprotocol/protocolVersion";
|
||||
pub const META_CLIENT_CAPABILITIES_KEY: &str = "io.modelcontextprotocol/clientCapabilities";
|
||||
pub const META_CLIENT_INFO_KEY: &str = "io.modelcontextprotocol/clientInfo";
|
||||
|
||||
/// Result `_meta` key carrying the self-reported server identity (pinned `DiscoverResult`).
|
||||
pub const META_SERVER_INFO_KEY: &str = "io.modelcontextprotocol/serverInfo";
|
||||
|
||||
/// JSON-RPC error codes of the pinned modern revision.
|
||||
pub const HEADER_MISMATCH_ERROR_CODE: i64 = -32020;
|
||||
pub const UNSUPPORTED_PROTOCOL_VERSION_ERROR_CODE: i64 = -32022;
|
||||
|
||||
/// Header name carrying the negotiated revision on HTTP requests.
|
||||
pub const HEADER_PROTOCOL_VERSION_NAME: &str = "MCP-Protocol-Version";
|
||||
|
||||
pub fn request_id(message: &Value) -> Value {
|
||||
message.get("id").cloned().unwrap_or(Value::Null)
|
||||
|
||||
@@ -6,13 +6,16 @@ pub mod auth;
|
||||
pub mod catalog;
|
||||
pub mod jsonrpc;
|
||||
pub mod manifest;
|
||||
mod protocol;
|
||||
mod rate_limit;
|
||||
mod request_context;
|
||||
pub mod resource_wire;
|
||||
pub mod session;
|
||||
pub mod tool_error;
|
||||
mod tool_search;
|
||||
mod transport;
|
||||
|
||||
pub use app::{
|
||||
build_app, build_app_with_background_workers, build_app_with_background_workers_and_limits,
|
||||
build_app, build_app_with_artifacts, build_app_with_background_workers,
|
||||
build_app_with_background_workers_and_limits,
|
||||
};
|
||||
@@ -0,0 +1,562 @@
|
||||
//! Narrow shared Tools-service boundary (Story 3.1, decision D-4).
|
||||
//!
|
||||
//! Both protocol eras use the same Tools service: the adapters parse their wire form into a command,
|
||||
//! build the verified context and map the neutral outcome back. The wire envelope, `ResponseMode`,
|
||||
//! an `axum::Response`, the session carrier and the protocol revision never cross this boundary, and
|
||||
//! the reserved `_crank_confirmation_token` marker is removed from the wire arguments by the adapter
|
||||
//! (the `call_tool` proxy arm additionally removes the marker of its own nested arguments, exactly
|
||||
//! as the previous shared implementation did).
|
||||
//!
|
||||
//! Advertisement is not per-call authorization: the credential security level check, the approval
|
||||
//! policy, the runtime execution and the invocation history stay part of the shared service, and the
|
||||
//! adapter is the only place that turns an outcome into an era-specific response.
|
||||
//!
|
||||
//! The proposed command shape carried a `catalog_revision` field; it is deliberately not adopted:
|
||||
//! the adapter has no revision of its own to declare (it would need a second catalog read just to
|
||||
//! duplicate the published revision), and the service checks the `call_tool` proxy's declared
|
||||
//! revision against the single published catalog it already reads.
|
||||
|
||||
use std::{sync::Arc, time::Instant};
|
||||
|
||||
use crank_core::{
|
||||
CorrelationContext, ExecutionErrorCode, ExecutionFailure, ExecutionLocale, ExecutionOrigin,
|
||||
InvocationLevel, InvocationSource, InvocationStatus, ToolAccessMode,
|
||||
};
|
||||
use crank_registry::PublishedAgentCatalog;
|
||||
use crank_runtime::{ExecutionAuthorization, RuntimeExecutionRequest, RuntimeRequestContext};
|
||||
use crank_trace::{ErrorCategory, Stage, StageOutcome};
|
||||
use serde::Deserialize;
|
||||
use serde_json::Value;
|
||||
use tracing::Instrument;
|
||||
|
||||
use crate::{
|
||||
access::credential_allows_security_level,
|
||||
app::{
|
||||
AppState, ApprovalPolicyContext, ApprovalPolicyDecision, InvocationRecord,
|
||||
maybe_handle_approval_policy, persist_invocation_for_key, resolve_generated_tool,
|
||||
resolve_operation_auth, runtime_operation, take_confirmation_token,
|
||||
},
|
||||
auth::VerifiedMachineCredential,
|
||||
manifest::{CALL_TOOL_NAME, SEARCH_TOOLS_NAME, catalog_tool_definitions},
|
||||
tool_error::{
|
||||
McpControlError, ToolErrorContract, control_tool_error_contract,
|
||||
tool_error_contract_from_failure,
|
||||
},
|
||||
};
|
||||
|
||||
/// Era-neutral continuation capability of one Tools command.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum ContinuationSupport {
|
||||
ElicitationSupported,
|
||||
ElicitationUnsupported,
|
||||
}
|
||||
|
||||
impl ContinuationSupport {
|
||||
pub(crate) fn from_supported(supported: bool) -> Self {
|
||||
if supported {
|
||||
Self::ElicitationSupported
|
||||
} else {
|
||||
Self::ElicitationUnsupported
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn supports_elicitation(self) -> bool {
|
||||
matches!(self, Self::ElicitationSupported)
|
||||
}
|
||||
}
|
||||
|
||||
/// Verified, era-neutral context of one shared Tools command.
|
||||
///
|
||||
/// `workspace_slug`/`agent_slug` address the published catalog; the credential, the correlation and
|
||||
/// the continuation capability are the verified inputs of the tools/call arm. `locale` is the
|
||||
/// adapter-derived presentation preference of the request: the service composes the neutral error
|
||||
/// contract, but it never sees the envelope the preference was read from.
|
||||
pub(crate) struct ServiceContext<'a> {
|
||||
pub(crate) workspace_slug: &'a str,
|
||||
pub(crate) agent_slug: &'a str,
|
||||
pub(crate) credential: &'a VerifiedMachineCredential,
|
||||
pub(crate) correlation: &'a CorrelationContext,
|
||||
pub(crate) continuation: ContinuationSupport,
|
||||
pub(crate) locale: ExecutionLocale,
|
||||
}
|
||||
|
||||
/// Parameters of a `tools/list` command, already parsed by the adapter from the wire form.
|
||||
#[derive(Debug, Default, Deserialize)]
|
||||
pub(crate) struct ToolsListCommand {
|
||||
#[serde(default)]
|
||||
pub(crate) cursor: Option<String>,
|
||||
#[serde(default)]
|
||||
pub(crate) limit: Option<usize>,
|
||||
}
|
||||
|
||||
/// Parameters of a `tools/call` command.
|
||||
///
|
||||
/// `arguments` is the domain-only (object-shape validated) payload of the addressed tool and the
|
||||
/// confirmation marker has already been removed by the adapter.
|
||||
pub(crate) struct ToolCallCommand {
|
||||
pub(crate) tool_name: String,
|
||||
pub(crate) arguments: Value,
|
||||
pub(crate) confirmation_token: Option<String>,
|
||||
}
|
||||
|
||||
/// A command the shared Tools service accepts.
|
||||
pub(crate) enum ToolsCommand {
|
||||
List(ToolsListCommand),
|
||||
Call(ToolCallCommand),
|
||||
}
|
||||
|
||||
/// A neutral outcome of a shared Tools command.
|
||||
pub(crate) enum ToolsOutcome {
|
||||
List {
|
||||
tools: Vec<Value>,
|
||||
next_cursor: Option<String>,
|
||||
},
|
||||
Call(ToolCallOutcome),
|
||||
/// The requested page is not representable: the adapter answers era-correct invalid params.
|
||||
InvalidParams(String),
|
||||
/// The published catalog could not be read: the adapter answers its internal-error shape.
|
||||
CatalogUnavailable,
|
||||
}
|
||||
|
||||
/// A neutral outcome of one `tools/call`, never an `axum::Response`.
|
||||
pub(crate) enum ToolCallOutcome {
|
||||
/// The operation completed; the adapter turns the output into its success tool response.
|
||||
Completed(Value),
|
||||
/// The operation waits for a human decision; the adapter turns the payload into its success
|
||||
/// tool response.
|
||||
ApprovalPending(Value),
|
||||
/// The required elicitation cannot be completed by this client; the adapter builds the
|
||||
/// era-correct tool error contract.
|
||||
ApprovalUnavailable(McpControlError),
|
||||
/// The payload is not a valid command for this catalog; the adapter answers era-correct
|
||||
/// invalid params.
|
||||
InvalidParams(String),
|
||||
/// A failing tool call; the adapter turns the contract into its error tool response.
|
||||
Error(ToolErrorContract),
|
||||
/// The service could not complete its own bookkeeping; the adapter answers its internal error
|
||||
/// shape.
|
||||
InternalFailure,
|
||||
}
|
||||
|
||||
/// Handle one shared Tools command. No wire envelope, `ResponseMode`, `axum::Response`, session or
|
||||
/// protocol revision crosses this boundary.
|
||||
pub(crate) async fn handle_tools_command(
|
||||
state: &Arc<AppState>,
|
||||
context: ServiceContext<'_>,
|
||||
command: ToolsCommand,
|
||||
) -> ToolsOutcome {
|
||||
// One marker per entered owning Tools service/handler (Story 3.1 section 7.2). It is a
|
||||
// `#[cfg(test)]`-only, request-scoped counter and has no production effect.
|
||||
#[cfg(test)]
|
||||
crate::app::dispatch_observer::tools_service_enter();
|
||||
|
||||
let catalog = match state
|
||||
.catalog
|
||||
.get_catalog(context.workspace_slug, context.agent_slug)
|
||||
.await
|
||||
{
|
||||
Ok(catalog) => catalog,
|
||||
Err(_error) => return ToolsOutcome::CatalogUnavailable,
|
||||
};
|
||||
|
||||
match command {
|
||||
ToolsCommand::List(list) => {
|
||||
match paginate_tools_list(catalog_tool_definitions(&catalog), list) {
|
||||
Ok((tools, next_cursor)) => ToolsOutcome::List { tools, next_cursor },
|
||||
Err(message) => ToolsOutcome::InvalidParams(message.to_owned()),
|
||||
}
|
||||
}
|
||||
ToolsCommand::Call(call) => {
|
||||
ToolsOutcome::Call(execute_tool_command(state, &context, call, &catalog).await)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The access-mode policy of the catalog decides what one `tools/call` command means.
|
||||
async fn execute_tool_command(
|
||||
state: &Arc<AppState>,
|
||||
context: &ServiceContext<'_>,
|
||||
command: ToolCallCommand,
|
||||
catalog: &PublishedAgentCatalog,
|
||||
) -> ToolCallOutcome {
|
||||
match catalog.tool_selection_policy.mode {
|
||||
ToolAccessMode::Direct => {
|
||||
execute_resolved_tool(
|
||||
state,
|
||||
context,
|
||||
catalog,
|
||||
&command.tool_name,
|
||||
command.arguments,
|
||||
command.confirmation_token,
|
||||
)
|
||||
.await
|
||||
}
|
||||
ToolAccessMode::Search if command.tool_name == SEARCH_TOOLS_NAME => {
|
||||
match crate::tool_search::search_tools_outcome(catalog, command.arguments) {
|
||||
Ok(result) => ToolCallOutcome::Completed(result),
|
||||
Err(detail) => ToolCallOutcome::InvalidParams(detail),
|
||||
}
|
||||
}
|
||||
ToolAccessMode::Search if command.tool_name == CALL_TOOL_NAME => {
|
||||
let proxy: ProxyToolCallArguments = match serde_json::from_value(command.arguments) {
|
||||
Ok(proxy) => proxy,
|
||||
Err(error) => return ToolCallOutcome::InvalidParams(error.to_string()),
|
||||
};
|
||||
if proxy.catalog_revision != catalog.catalog_revision {
|
||||
return ToolCallOutcome::Error(control_tool_error_contract(
|
||||
McpControlError::CatalogRevisionChanged,
|
||||
context.correlation.request_id().as_str(),
|
||||
context.correlation.trace_id().as_str(),
|
||||
context.locale,
|
||||
));
|
||||
}
|
||||
let mut arguments = proxy.arguments;
|
||||
// The proxied call carries its own arguments: its marker is the one that belonged to
|
||||
// that call, so it wins over the adapter-level marker of the proxy request itself.
|
||||
let confirmation_token =
|
||||
take_confirmation_token(&mut arguments).or(command.confirmation_token);
|
||||
execute_resolved_tool(
|
||||
state,
|
||||
context,
|
||||
catalog,
|
||||
&proxy.name,
|
||||
arguments,
|
||||
confirmation_token,
|
||||
)
|
||||
.await
|
||||
}
|
||||
ToolAccessMode::Search => {
|
||||
ToolCallOutcome::InvalidParams(tool_not_found_text(&command.tool_name))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve the owning tool of the addressed catalog, then run the real call: authorization, approval
|
||||
/// policy, runtime execution and invocation history.
|
||||
async fn execute_resolved_tool(
|
||||
state: &Arc<AppState>,
|
||||
context: &ServiceContext<'_>,
|
||||
catalog: &PublishedAgentCatalog,
|
||||
tool_name: &str,
|
||||
arguments: Value,
|
||||
confirmation_token: Option<String>,
|
||||
) -> ToolCallOutcome {
|
||||
let correlation = context.correlation;
|
||||
let transport_request_id = correlation.request_id().as_str();
|
||||
|
||||
let resolve_span = Stage::McpToolsResolve.span();
|
||||
let resolved = resolve_span.in_scope(|| resolve_generated_tool(&catalog.tools, tool_name));
|
||||
let tool = match resolved {
|
||||
Some(resolved) => {
|
||||
StageOutcome::Success.record(&resolve_span);
|
||||
drop(resolve_span);
|
||||
resolved.tool
|
||||
}
|
||||
None => {
|
||||
StageOutcome::Error.record(&resolve_span);
|
||||
ErrorCategory::Catalog.record(&resolve_span);
|
||||
drop(resolve_span);
|
||||
return ToolCallOutcome::InvalidParams(tool_not_found_text(tool_name));
|
||||
}
|
||||
};
|
||||
|
||||
let platform_api_key_id = context.credential.platform_api_key_id.clone();
|
||||
if !credential_allows_security_level(context.credential, tool.operation.security_level) {
|
||||
let failure =
|
||||
ExecutionFailure::new(ExecutionErrorCode::AuthorizationDenied, correlation.clone());
|
||||
persist_invocation_for_key(
|
||||
state,
|
||||
&tool,
|
||||
platform_api_key_id.as_ref(),
|
||||
InvocationRecord {
|
||||
request_id: Some(transport_request_id),
|
||||
trace_id: Some(correlation.trace_id().as_str()),
|
||||
tool_name: &tool.tool_name,
|
||||
status: InvocationStatus::Error,
|
||||
level: InvocationLevel::Warn,
|
||||
message: failure.error_code().as_str(),
|
||||
status_code: None,
|
||||
error_kind: Some(failure.error_code().as_str()),
|
||||
execution_stage: Some(failure.stage()),
|
||||
execution_error_code: Some(failure.error_code()),
|
||||
retryability: Some(failure.retryability()),
|
||||
outcome_certainty: Some(failure.outcome_certainty()),
|
||||
duration: std::time::Duration::ZERO,
|
||||
request_preview: crank_core::sanitize_invocation_preview(&arguments),
|
||||
response_preview: Value::Null,
|
||||
},
|
||||
)
|
||||
.await;
|
||||
return ToolCallOutcome::Error(tool_error_contract_from_failure(&failure, context.locale));
|
||||
}
|
||||
|
||||
let operation = runtime_operation(&tool);
|
||||
if tool
|
||||
.operation
|
||||
.execution_config
|
||||
.approval_policy
|
||||
.as_ref()
|
||||
.is_some_and(|policy| policy.required)
|
||||
{
|
||||
let approval_span = Stage::ApprovalCheck.span();
|
||||
let decision = maybe_handle_approval_policy(ApprovalPolicyContext {
|
||||
state,
|
||||
tool: &tool,
|
||||
arguments: &arguments,
|
||||
platform_api_key_id: platform_api_key_id.as_ref(),
|
||||
correlation,
|
||||
continuation: context.continuation,
|
||||
})
|
||||
.instrument(approval_span.clone())
|
||||
.await;
|
||||
if let Some(decision) = decision {
|
||||
return match decision {
|
||||
ApprovalPolicyDecision::Pending(payload) => {
|
||||
StageOutcome::Required.record(&approval_span);
|
||||
ToolCallOutcome::ApprovalPending(payload)
|
||||
}
|
||||
ApprovalPolicyDecision::ElicitationUnavailable => {
|
||||
StageOutcome::Error.record(&approval_span);
|
||||
ErrorCategory::Approval.record(&approval_span);
|
||||
ToolCallOutcome::ApprovalUnavailable(
|
||||
McpControlError::ApprovalElicitationNotSupported,
|
||||
)
|
||||
}
|
||||
ApprovalPolicyDecision::StorageFailed => {
|
||||
StageOutcome::Error.record(&approval_span);
|
||||
ErrorCategory::Approval.record(&approval_span);
|
||||
ToolCallOutcome::InternalFailure
|
||||
}
|
||||
};
|
||||
}
|
||||
StageOutcome::Allowed.record(&approval_span);
|
||||
}
|
||||
|
||||
let mut runtime_request_context = RuntimeRequestContext::from_correlation(correlation)
|
||||
.with_response_cache_scope(
|
||||
tool.workspace_id.as_str().to_owned(),
|
||||
tool.agent_id.as_str().to_owned(),
|
||||
)
|
||||
.with_metering_context(
|
||||
tool.workspace_id.clone(),
|
||||
Some(tool.agent_id.clone()),
|
||||
InvocationSource::AgentToolCall,
|
||||
);
|
||||
if let Some(token) = confirmation_token {
|
||||
runtime_request_context = runtime_request_context.with_confirmation_token(token);
|
||||
}
|
||||
let started_at = Instant::now();
|
||||
let resolved_auth =
|
||||
resolve_operation_auth(state, &tool.workspace_id, &operation.execution_config).await;
|
||||
|
||||
let result = match resolved_auth {
|
||||
Ok(resolved_auth) => {
|
||||
match RuntimeExecutionRequest::try_new(
|
||||
&tool.workspace_id,
|
||||
ExecutionOrigin::AgentSnapshot,
|
||||
Some(&tool.agent_id),
|
||||
&operation,
|
||||
&arguments,
|
||||
ExecutionAuthorization::Authorized,
|
||||
resolved_auth.as_ref(),
|
||||
&runtime_request_context,
|
||||
Instant::now()
|
||||
+ std::time::Duration::from_millis(
|
||||
operation.execution_config.timeout_ms.max(1),
|
||||
),
|
||||
) {
|
||||
Ok(request) => state.runtime.execute_outcome(request).await,
|
||||
Err(_) => Err(ExecutionFailure::new(
|
||||
ExecutionErrorCode::RuntimeInternal,
|
||||
correlation.clone(),
|
||||
)),
|
||||
}
|
||||
}
|
||||
Err(error) => Err(crank_runtime::normalize_runtime_error(&error, correlation)),
|
||||
};
|
||||
|
||||
match result {
|
||||
Ok(success) => {
|
||||
let request_preview = success.request_preview;
|
||||
let output = success.output;
|
||||
persist_invocation_for_key(
|
||||
state,
|
||||
&tool,
|
||||
platform_api_key_id.as_ref(),
|
||||
InvocationRecord {
|
||||
request_id: Some(transport_request_id),
|
||||
trace_id: Some(correlation.trace_id().as_str()),
|
||||
tool_name: &tool.tool_name,
|
||||
status: InvocationStatus::Ok,
|
||||
level: InvocationLevel::Info,
|
||||
message: "agent tool call completed",
|
||||
status_code: None,
|
||||
error_kind: None,
|
||||
execution_stage: Some(crank_core::ExecutionStage::Runtime),
|
||||
execution_error_code: None,
|
||||
retryability: Some(crank_core::Retryability::Never),
|
||||
outcome_certainty: Some(crank_core::OutcomeCertainty::Certain),
|
||||
duration: started_at.elapsed(),
|
||||
request_preview,
|
||||
response_preview: output.clone(),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
ToolCallOutcome::Completed(output)
|
||||
}
|
||||
Err(failure) => {
|
||||
persist_invocation_for_key(
|
||||
state,
|
||||
&tool,
|
||||
platform_api_key_id.as_ref(),
|
||||
InvocationRecord {
|
||||
request_id: Some(transport_request_id),
|
||||
trace_id: Some(correlation.trace_id().as_str()),
|
||||
tool_name: &tool.tool_name,
|
||||
status: InvocationStatus::Error,
|
||||
level: InvocationLevel::Error,
|
||||
message: failure.error_code().as_str(),
|
||||
status_code: failure.upstream_status(),
|
||||
error_kind: Some(failure.error_code().as_str()),
|
||||
execution_stage: Some(failure.stage()),
|
||||
execution_error_code: Some(failure.error_code()),
|
||||
retryability: Some(failure.retryability()),
|
||||
outcome_certainty: Some(failure.outcome_certainty()),
|
||||
duration: started_at.elapsed(),
|
||||
request_preview: Value::Null,
|
||||
response_preview: Value::Null,
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
ToolCallOutcome::Error(tool_error_contract_from_failure(&failure, context.locale))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct ProxyToolCallArguments {
|
||||
name: String,
|
||||
#[serde(deserialize_with = "crate::protocol::deserialize_object_only")]
|
||||
arguments: Value,
|
||||
catalog_revision: String,
|
||||
}
|
||||
|
||||
fn tool_not_found_text(tool_name: &str) -> String {
|
||||
format!("tool {tool_name} was not found")
|
||||
}
|
||||
|
||||
/// Pagination of the advertised tool definitions. Domain-only: it never sees the request envelope.
|
||||
fn paginate_tools_list(
|
||||
definitions: Vec<Value>,
|
||||
command: ToolsListCommand,
|
||||
) -> Result<(Vec<Value>, Option<String>), &'static str> {
|
||||
const MAX_TOOLS_LIST_LIMIT: usize = 100;
|
||||
let start = match command.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 = command
|
||||
.limit
|
||||
.unwrap_or(definitions.len())
|
||||
.clamp(1, MAX_TOOLS_LIST_LIMIT);
|
||||
let end = start.saturating_add(limit).min(definitions.len());
|
||||
let tools = definitions[start..end].to_vec();
|
||||
let next_cursor = (end < definitions.len()).then(|| end.to_string());
|
||||
Ok((tools, next_cursor))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn definitions(count: usize) -> Vec<Value> {
|
||||
(0..count)
|
||||
.map(|index| json!({"name": format!("tool-{index}")}))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_page_reports_the_next_cursor_only_when_more_tools_remain() {
|
||||
let (tools, next_cursor) =
|
||||
paginate_tools_list(definitions(3), ToolsListCommand::default()).expect("valid page");
|
||||
assert_eq!(tools.len(), 3);
|
||||
assert_eq!(next_cursor, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bounded_page_reports_the_following_cursor() {
|
||||
let (tools, next_cursor) = paginate_tools_list(
|
||||
definitions(5),
|
||||
ToolsListCommand {
|
||||
cursor: None,
|
||||
limit: Some(2),
|
||||
},
|
||||
)
|
||||
.expect("valid page");
|
||||
assert_eq!(tools, definitions(2));
|
||||
assert_eq!(next_cursor.as_deref(), Some("2"));
|
||||
|
||||
let (tools, next_cursor) = paginate_tools_list(
|
||||
definitions(5),
|
||||
ToolsListCommand {
|
||||
cursor: Some("2".to_owned()),
|
||||
limit: Some(2),
|
||||
},
|
||||
)
|
||||
.expect("valid page");
|
||||
assert_eq!(
|
||||
tools,
|
||||
vec![json!({"name": "tool-2"}), json!({"name": "tool-3"})]
|
||||
);
|
||||
assert_eq!(next_cursor.as_deref(), Some("4"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_malformed_cursor_is_invalid_params_and_never_a_default_page() {
|
||||
assert_eq!(
|
||||
paginate_tools_list(
|
||||
definitions(3),
|
||||
ToolsListCommand {
|
||||
cursor: Some("not-a-cursor".to_owned()),
|
||||
limit: None,
|
||||
},
|
||||
)
|
||||
.unwrap_err(),
|
||||
"invalid tools/list cursor"
|
||||
);
|
||||
assert_eq!(
|
||||
paginate_tools_list(
|
||||
definitions(3),
|
||||
ToolsListCommand {
|
||||
cursor: Some("9".to_owned()),
|
||||
limit: None,
|
||||
},
|
||||
)
|
||||
.unwrap_err(),
|
||||
"tools/list cursor is out of range"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn continuation_support_is_an_era_neutral_value_object() {
|
||||
assert!(ContinuationSupport::from_supported(true).supports_elicitation());
|
||||
assert!(!ContinuationSupport::from_supported(false).supports_elicitation());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unknown_tool_name_is_reported_verbatim() {
|
||||
assert_eq!(
|
||||
tool_not_found_text("create_lead"),
|
||||
"tool create_lead was not found"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,371 @@
|
||||
//! Story 3.17: the era-neutral `completion/complete` service boundary.
|
||||
//!
|
||||
//! Both supported revisions share this one service; the wire envelope, the response mode and the
|
||||
//! `axum::Response` stay in the era adapters, exactly as for the Tools/Resources/Prompts services.
|
||||
//!
|
||||
//! Scope of the answer (AC1): a suggestion list is derived *only* from the typed schema of one exact
|
||||
//! Published Prompt argument, or of one exact parameter of one exact Published Resource template,
|
||||
//! that is already bound to the active published Agent snapshot. There is no lookup by a
|
||||
//! client-supplied id, no scan of draft/foreign/unbound rows and no search over arbitrary database
|
||||
//! values: a `ref` that is not part of the bound snapshot is answered with the same indistinguishable
|
||||
//! refusal as an unknown argument, so neither foreign Prompt names nor foreign template URIs can be
|
||||
//! probed through this method. Schemas without an enumeration produce an empty suggestion list
|
||||
//! instead of an invented one.
|
||||
//!
|
||||
//! Bounds (AC2): the argument name/value, the reference and the optional completion context are
|
||||
//! length/count-bounded before any catalog read, and the schema enumeration itself is read through a
|
||||
//! fixed cap. A truncated scan is reported honestly (`total` omitted, `hasMore: true`) rather than as
|
||||
//! an exact count. Every telemetry field is a count, a fixed label or the served revision — never a
|
||||
//! Prompt name, a URI template, an argument name or a client-supplied value, so the bounded metric
|
||||
//! label set cannot be widened by a request.
|
||||
|
||||
use std::{collections::HashSet, sync::Arc};
|
||||
|
||||
use crank_core::resource::TemplateSource;
|
||||
use crank_schema::Schema;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Map, Value};
|
||||
use tracing::info;
|
||||
|
||||
use crate::{app::AppState, protocol::ServiceContext};
|
||||
|
||||
/// Pinned `CompleteResult.completion.values` bound (`@maxItems 100`).
|
||||
const MAX_COMPLETION_VALUES: usize = 100;
|
||||
/// Schema enumeration values inspected per request: the bound that keeps a hostile or corrupted
|
||||
/// schema from turning one completion request into unbounded work.
|
||||
const MAX_SCHEMA_VALUES: usize = 1_024;
|
||||
/// Bound of a completion argument name (`params.argument.name`).
|
||||
const MAX_ARGUMENT_NAME_BYTES: usize = 128;
|
||||
/// Bound of the partial token a client sends (`params.argument.value`); the pinned schema types it as
|
||||
/// an opaque string, so an oversized token is a malformed request, not a matching challenge.
|
||||
const MAX_ARGUMENT_VALUE_BYTES: usize = 1_024;
|
||||
/// Bound of `ref/prompt.name`.
|
||||
const MAX_REFERENCE_NAME_BYTES: usize = 256;
|
||||
/// Bound of `ref/resource.uri` (a URI template as served by `resources/templates/list`).
|
||||
const MAX_REFERENCE_URI_BYTES: usize = 2_048;
|
||||
/// Bound of the optional previously-resolved `context.arguments` map.
|
||||
const MAX_CONTEXT_ARGUMENTS: usize = 32;
|
||||
|
||||
/// The one safe detail of a malformed completion request: it never echoes the offending value.
|
||||
const INVALID_PARAMS: &str = "invalid completion/complete parameters";
|
||||
|
||||
/// Parameters of a `completion/complete` command, already parsed by the adapter from the wire form.
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub(crate) struct CompletionCommand {
|
||||
/// `ref` of the pinned schema: `{type: "ref/prompt", ...}` or `{type: "ref/resource", ...}`.
|
||||
#[serde(rename = "ref")]
|
||||
pub(crate) reference: CompletionReference,
|
||||
/// The argument whose value is being completed.
|
||||
pub(crate) argument: CompletionArgument,
|
||||
/// Optional previously-resolved variables. The typed schema of the addressed argument is the only
|
||||
/// suggestion source, so this context is validated and otherwise not used: it never widens the
|
||||
/// answer beyond the published enumeration.
|
||||
#[serde(default)]
|
||||
pub(crate) context: Option<CompletionContext>,
|
||||
}
|
||||
|
||||
/// The typed `ref` union of the pinned completion request.
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(tag = "type")]
|
||||
pub(crate) enum CompletionReference {
|
||||
/// One Prompt, addressed by the name it is listed under in `prompts/list`.
|
||||
#[serde(rename = "ref/prompt")]
|
||||
Prompt { name: String },
|
||||
/// One Resource template, addressed by the URI template served by `resources/templates/list`.
|
||||
#[serde(rename = "ref/resource")]
|
||||
Resource { uri: String },
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub(crate) struct CompletionArgument {
|
||||
pub(crate) name: String,
|
||||
pub(crate) value: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Deserialize)]
|
||||
pub(crate) struct CompletionContext {
|
||||
#[serde(default)]
|
||||
pub(crate) arguments: Option<Map<String, Value>>,
|
||||
}
|
||||
|
||||
/// A neutral outcome of the shared completion service.
|
||||
pub(crate) enum CompletionOutcome {
|
||||
/// Bounded suggestions in schema order. `total` is absent when the enumeration scan was
|
||||
/// truncated, because then only a lower bound of the option count is known.
|
||||
Completed {
|
||||
values: Vec<String>,
|
||||
total: Option<usize>,
|
||||
has_more: bool,
|
||||
},
|
||||
/// The request is malformed or exceeds a fixed bound: one safe detail, no echoed input.
|
||||
InvalidParams(&'static str),
|
||||
/// Unknown, Draft, foreign, unbound or archived-out reference, or an argument the addressed
|
||||
/// schema does not declare. One outcome that cannot distinguish these cases.
|
||||
NotAvailable,
|
||||
/// The bound snapshot or the addressed typed schema could not be read safely.
|
||||
CatalogUnavailable,
|
||||
}
|
||||
|
||||
/// Serve one `completion/complete` command for the revision the adapter negotiated (AC1/AC3).
|
||||
pub(crate) async fn handle_completion_command(
|
||||
state: &Arc<AppState>,
|
||||
context: ServiceContext<'_>,
|
||||
revision: &str,
|
||||
command: CompletionCommand,
|
||||
) -> CompletionOutcome {
|
||||
if command.validate().is_some() {
|
||||
return CompletionOutcome::InvalidParams(INVALID_PARAMS);
|
||||
}
|
||||
let catalog = match state
|
||||
.catalog
|
||||
.get_catalog(context.workspace_slug, context.agent_slug)
|
||||
.await
|
||||
{
|
||||
Ok(catalog) => catalog,
|
||||
Err(_error) => {
|
||||
return refused(revision, command.reference_label(), "catalog_unavailable");
|
||||
}
|
||||
};
|
||||
let workspace_id = match state
|
||||
.registry
|
||||
.published_agent_workspace_id(context.workspace_slug, context.agent_slug)
|
||||
.await
|
||||
{
|
||||
Ok(workspace_id) => workspace_id,
|
||||
Err(_error) => {
|
||||
return refused(revision, command.reference_label(), "catalog_unavailable");
|
||||
}
|
||||
};
|
||||
|
||||
match &command.reference {
|
||||
CompletionReference::Prompt { name } => {
|
||||
// The same exact bound snapshot `prompts/list` and `prompts/get` serve, so a Draft,
|
||||
// foreign or unbound Prompt has no candidates at all.
|
||||
let publications = match state
|
||||
.registry
|
||||
.resolve_bound_prompt_publications(&workspace_id, &catalog.prompts)
|
||||
.await
|
||||
{
|
||||
Ok(publications) => publications,
|
||||
Err(_error) => {
|
||||
return refused(revision, "prompt", "catalog_unavailable");
|
||||
}
|
||||
};
|
||||
// Deterministic exact binding, identical to `prompts/get`: names are not constrained
|
||||
// unique, so the first bound publication in `prompt_id` order is addressed.
|
||||
let Some(publication) = publications
|
||||
.iter()
|
||||
.find(|publication| &publication.name == name)
|
||||
else {
|
||||
return not_available(revision, "prompt");
|
||||
};
|
||||
let Some(argument) = publication
|
||||
.definition
|
||||
.arguments()
|
||||
.iter()
|
||||
.find(|argument| argument.name() == command.argument.name)
|
||||
else {
|
||||
return not_available(revision, "prompt");
|
||||
};
|
||||
let candidates = argument
|
||||
.enumeration()
|
||||
.iter()
|
||||
.filter_map(value_text)
|
||||
.collect::<Vec<_>>();
|
||||
completed(revision, "prompt", &command.argument.value, candidates)
|
||||
}
|
||||
CompletionReference::Resource { uri } => {
|
||||
// The same admitted bound template array `resources/templates/list` serves: revoked,
|
||||
// foreign and unbound templates are already filtered out by the registry adapter.
|
||||
let admitted = match state
|
||||
.registry
|
||||
.list_admitted_resource_templates(workspace_id.as_str(), &catalog.resources)
|
||||
.await
|
||||
{
|
||||
Ok(admitted) => admitted,
|
||||
Err(_error) => {
|
||||
return refused(revision, "resource", "catalog_unavailable");
|
||||
}
|
||||
};
|
||||
let mut addressable = None;
|
||||
for template in &admitted {
|
||||
// A bound definition that no longer parses is simply not addressable here; it never
|
||||
// turns an unrelated completion request into an error.
|
||||
let Ok(definition) =
|
||||
serde_json::from_str::<Value>(&template.source.definition_json)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let Ok(source) = TemplateSource::parse(&definition) else {
|
||||
continue;
|
||||
};
|
||||
if &source.uri_template == uri {
|
||||
addressable = Some(source);
|
||||
break;
|
||||
}
|
||||
}
|
||||
let Some(source) = addressable else {
|
||||
return not_available(revision, "resource");
|
||||
};
|
||||
let Some(parameter) = source
|
||||
.parameters
|
||||
.iter()
|
||||
.find(|parameter| parameter.name == command.argument.name)
|
||||
else {
|
||||
return not_available(revision, "resource");
|
||||
};
|
||||
let Ok(schema) = serde_json::from_value::<Schema>(parameter.schema.clone()) else {
|
||||
return refused(revision, "resource", "schema_unavailable");
|
||||
};
|
||||
completed(
|
||||
revision,
|
||||
"resource",
|
||||
&command.argument.value,
|
||||
schema.enum_values,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl CompletionCommand {
|
||||
/// The bounded input contract of AC2: nothing here depends on catalog content, so a malformed or
|
||||
/// oversized request is refused before the first registry read.
|
||||
fn validate(&self) -> Option<&'static str> {
|
||||
match &self.reference {
|
||||
CompletionReference::Prompt { name } => {
|
||||
if name.is_empty() || name.len() > MAX_REFERENCE_NAME_BYTES {
|
||||
return Some(INVALID_PARAMS);
|
||||
}
|
||||
}
|
||||
CompletionReference::Resource { uri } => {
|
||||
if uri.is_empty() || uri.len() > MAX_REFERENCE_URI_BYTES {
|
||||
return Some(INVALID_PARAMS);
|
||||
}
|
||||
}
|
||||
}
|
||||
if self.argument.name.is_empty() || self.argument.name.len() > MAX_ARGUMENT_NAME_BYTES {
|
||||
return Some(INVALID_PARAMS);
|
||||
}
|
||||
if self.argument.value.len() > MAX_ARGUMENT_VALUE_BYTES {
|
||||
return Some(INVALID_PARAMS);
|
||||
}
|
||||
let arguments = self
|
||||
.context
|
||||
.as_ref()
|
||||
.and_then(|context| context.arguments.as_ref())?;
|
||||
if arguments.len() > MAX_CONTEXT_ARGUMENTS {
|
||||
return Some(INVALID_PARAMS);
|
||||
}
|
||||
// The pinned schema types the context values as strings; a non-string or oversized value is
|
||||
// malformed rather than something to coerce.
|
||||
for (name, value) in arguments {
|
||||
if name.len() > MAX_ARGUMENT_NAME_BYTES {
|
||||
return Some(INVALID_PARAMS);
|
||||
}
|
||||
let Some(text) = value.as_str() else {
|
||||
return Some(INVALID_PARAMS);
|
||||
};
|
||||
if text.len() > MAX_ARGUMENT_VALUE_BYTES {
|
||||
return Some(INVALID_PARAMS);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The fixed telemetry label of the reference kind (never the name or the URI itself).
|
||||
const fn reference_label(&self) -> &'static str {
|
||||
match self.reference {
|
||||
CompletionReference::Prompt { .. } => "prompt",
|
||||
CompletionReference::Resource { .. } => "resource",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One suggestion list from an already-authorized typed enumeration.
|
||||
///
|
||||
/// Matching is a case-insensitive prefix test over the schema order, so the answer is deterministic
|
||||
/// and independent of query timing. Duplicates are collapsed before counting, the response is capped
|
||||
/// at the pinned 100 values, and a truncated schema scan never claims an exact `total`.
|
||||
fn completed(
|
||||
revision: &str,
|
||||
reference: &'static str,
|
||||
value: &str,
|
||||
candidates: Vec<String>,
|
||||
) -> CompletionOutcome {
|
||||
let truncated = candidates.len() > MAX_SCHEMA_VALUES;
|
||||
let mut seen = HashSet::new();
|
||||
let mut matched = Vec::new();
|
||||
for candidate in candidates.into_iter().take(MAX_SCHEMA_VALUES) {
|
||||
if !prefix_match(&candidate, value) {
|
||||
continue;
|
||||
}
|
||||
if !seen.insert(candidate.clone()) {
|
||||
continue;
|
||||
}
|
||||
matched.push(candidate);
|
||||
}
|
||||
let total = matched.len();
|
||||
let values: Vec<String> = matched.into_iter().take(MAX_COMPLETION_VALUES).collect();
|
||||
let has_more = truncated || total > values.len();
|
||||
info!(
|
||||
name: "mcp.completion.complete",
|
||||
outcome = "ok",
|
||||
reference,
|
||||
suggestion_count = values.len(),
|
||||
has_more,
|
||||
total_known = !truncated,
|
||||
revision,
|
||||
"completion outcome"
|
||||
);
|
||||
CompletionOutcome::Completed {
|
||||
values,
|
||||
total: (!truncated).then_some(total),
|
||||
has_more,
|
||||
}
|
||||
}
|
||||
|
||||
/// `true` when `value` is an ASCII-case-insensitive prefix of `candidate`.
|
||||
///
|
||||
/// A `value` that does not end on a character boundary of `candidate` cannot be a prefix of it, so a
|
||||
/// non-ASCII token is matched exactly instead of being sliced mid-character.
|
||||
fn prefix_match(candidate: &str, value: &str) -> bool {
|
||||
candidate
|
||||
.get(..value.len())
|
||||
.is_some_and(|head| head.eq_ignore_ascii_case(value))
|
||||
}
|
||||
|
||||
/// The wire-visible text of one enum entry. Only scalars have a faithful string form; an object or
|
||||
/// array enumeration entry is not suggested instead of being rendered as an ad-hoc serialization.
|
||||
fn value_text(value: &Value) -> Option<String> {
|
||||
match value {
|
||||
Value::String(text) => Some(text.clone()),
|
||||
Value::Number(number) => Some(number.to_string()),
|
||||
Value::Bool(flag) => Some(flag.to_string()),
|
||||
Value::Null | Value::Array(_) | Value::Object(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// One safe, indistinguishable refusal: no Prompt name, URI template, argument name or option
|
||||
/// count is disclosed, and the reason never distinguishes unknown from foreign/unbound.
|
||||
fn not_available(revision: &str, reference: &'static str) -> CompletionOutcome {
|
||||
refused(revision, reference, "not_available")
|
||||
}
|
||||
|
||||
fn refused(revision: &str, reference: &'static str, outcome: &'static str) -> CompletionOutcome {
|
||||
info!(
|
||||
name: "mcp.completion.complete",
|
||||
outcome,
|
||||
reference,
|
||||
suggestion_count = 0usize,
|
||||
revision,
|
||||
"completion outcome"
|
||||
);
|
||||
match outcome {
|
||||
"catalog_unavailable" | "schema_unavailable" => CompletionOutcome::CatalogUnavailable,
|
||||
_ => CompletionOutcome::NotAvailable,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "completion_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,220 @@
|
||||
//! In-crate tests of `protocol::completion` (module path `protocol::completion::tests`).
|
||||
//!
|
||||
//! These cover the pure halves of the shared service: the bounded input contract of AC2 and the
|
||||
//! suggestion derivation of AC1. The real endpoint behaviour (both eras, real registry) is covered by
|
||||
//! `apps/mcp-server/tests/integration/mcp_completion.rs`.
|
||||
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
/// Any supported revision: the suggestion derivation is era-neutral.
|
||||
const MODERN: &str = crate::jsonrpc::MODERN_PROTOCOL_VERSION;
|
||||
|
||||
fn candidates(values: &[&str]) -> Vec<String> {
|
||||
values.iter().map(|value| (*value).to_owned()).collect()
|
||||
}
|
||||
|
||||
fn values_of(outcome: &CompletionOutcome) -> (&[String], Option<usize>, bool) {
|
||||
match outcome {
|
||||
CompletionOutcome::Completed {
|
||||
values,
|
||||
total,
|
||||
has_more,
|
||||
} => (values, *total, *has_more),
|
||||
_ => panic!("expected a completed outcome"),
|
||||
}
|
||||
}
|
||||
|
||||
fn command(params: Value) -> Result<CompletionCommand, serde_json::Error> {
|
||||
serde_json::from_value(params)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matching_is_a_case_insensitive_prefix_in_schema_order() {
|
||||
let outcome = completed(
|
||||
MODERN,
|
||||
"prompt",
|
||||
"W",
|
||||
candidates(&["warm", "dry", "wild", "warmest"]),
|
||||
);
|
||||
let (values, total, has_more) = values_of(&outcome);
|
||||
assert_eq!(values, ["warm", "wild", "warmest"]);
|
||||
assert_eq!(total, Some(3));
|
||||
assert!(!has_more);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_token_lists_the_bounded_enumeration() {
|
||||
let outcome = completed(MODERN, "prompt", "", candidates(&["a", "b", "c"]));
|
||||
let (values, total, has_more) = values_of(&outcome);
|
||||
assert_eq!(values, ["a", "b", "c"]);
|
||||
assert_eq!(total, Some(3));
|
||||
assert!(!has_more);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_token_without_a_match_returns_no_suggestions() {
|
||||
let outcome = completed(MODERN, "resource", "zzz", candidates(&["eu", "us"]));
|
||||
let (values, total, has_more) = values_of(&outcome);
|
||||
assert!(values.is_empty());
|
||||
assert_eq!(total, Some(0));
|
||||
assert!(!has_more);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_response_is_capped_at_the_pinned_maximum_and_reports_more() {
|
||||
let all: Vec<String> = (0..150).map(|index| format!("value-{index:03}")).collect();
|
||||
let outcome = completed(MODERN, "prompt", "value-", all);
|
||||
let (values, total, has_more) = values_of(&outcome);
|
||||
assert_eq!(values.len(), MAX_COMPLETION_VALUES);
|
||||
assert_eq!(values.first().map(String::as_str), Some("value-000"));
|
||||
assert_eq!(total, Some(150), "the exact option count is still reported");
|
||||
assert!(has_more);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_enumeration_entries_are_collapsed_before_counting() {
|
||||
let outcome = completed(MODERN, "prompt", "", candidates(&["eu", "eu", "us"]));
|
||||
let (values, total, has_more) = values_of(&outcome);
|
||||
assert_eq!(values, ["eu", "us"]);
|
||||
assert_eq!(total, Some(2));
|
||||
assert!(!has_more);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_truncated_schema_scan_never_claims_an_exact_total() {
|
||||
let all: Vec<String> = (0..=MAX_SCHEMA_VALUES)
|
||||
.map(|index| format!("item{index}"))
|
||||
.collect();
|
||||
let outcome = completed(MODERN, "resource", "item", all);
|
||||
let (values, total, has_more) = values_of(&outcome);
|
||||
assert_eq!(values.len(), MAX_COMPLETION_VALUES);
|
||||
assert_eq!(total, None, "a partial scan cannot name the option count");
|
||||
assert!(has_more);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_scalar_enumeration_entries_become_suggestions() {
|
||||
assert_eq!(value_text(&json!("eu")), Some("eu".to_owned()));
|
||||
assert_eq!(value_text(&json!(7)), Some("7".to_owned()));
|
||||
assert_eq!(value_text(&json!(true)), Some("true".to_owned()));
|
||||
assert_eq!(value_text(&json!(null)), None);
|
||||
assert_eq!(value_text(&json!(["eu"])), None);
|
||||
assert_eq!(value_text(&json!({"value": "eu"})), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_non_ascii_token_matches_exactly_and_never_slices_mid_character() {
|
||||
assert!(prefix_match("привет", "пр"));
|
||||
// A two-byte Cyrillic letter is one character, so it is a plain prefix.
|
||||
assert!(prefix_match("привет", "п"));
|
||||
assert!(prefix_match("Ärger", "Är"));
|
||||
// Two ASCII bytes end inside the multi-byte `é`: no prefix is claimed for a mid-character cut.
|
||||
assert!(!prefix_match("aé", "ab"));
|
||||
assert!(!prefix_match("warm", "warmest"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_refusal_discloses_neither_reason_nor_identifiers() {
|
||||
assert!(matches!(
|
||||
not_available(MODERN, "prompt"),
|
||||
CompletionOutcome::NotAvailable
|
||||
));
|
||||
assert!(matches!(
|
||||
refused(MODERN, "resource", "schema_unavailable"),
|
||||
CompletionOutcome::CatalogUnavailable
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn both_typed_references_parse_and_a_foreign_ref_type_is_rejected() {
|
||||
let prompt = command(json!({
|
||||
"ref": {"type": "ref/prompt", "name": "greeting"},
|
||||
"argument": {"name": "tone", "value": "w"}
|
||||
}))
|
||||
.expect("the prompt reference is the pinned shape");
|
||||
assert_eq!(prompt.reference_label(), "prompt");
|
||||
assert!(prompt.context.is_none());
|
||||
|
||||
let resource = command(json!({
|
||||
"ref": {"type": "ref/resource", "uri": "crank://orders/{order_id}"},
|
||||
"argument": {"name": "order_id", "value": "0"},
|
||||
"context": {"arguments": {"region": "eu"}}
|
||||
}))
|
||||
.expect("the resource reference with context is the pinned shape");
|
||||
assert_eq!(resource.reference_label(), "resource");
|
||||
assert!(resource.validate().is_none());
|
||||
|
||||
assert!(
|
||||
command(json!({
|
||||
"ref": {"type": "ref/tool", "name": "x"},
|
||||
"argument": {"name": "a", "value": ""}
|
||||
}))
|
||||
.is_err(),
|
||||
"an unknown reference type is not a completion reference"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oversized_and_malformed_requests_are_refused_before_any_catalog_read() {
|
||||
let long_value = "v".repeat(MAX_ARGUMENT_VALUE_BYTES + 1);
|
||||
let oversized = command(json!({
|
||||
"ref": {"type": "ref/prompt", "name": "greeting"},
|
||||
"argument": {"name": "tone", "value": long_value}
|
||||
}))
|
||||
.expect("the request shape parses; only its bound is exceeded");
|
||||
assert_eq!(oversized.validate(), Some(INVALID_PARAMS));
|
||||
|
||||
let long_name = "n".repeat(MAX_ARGUMENT_NAME_BYTES + 1);
|
||||
let oversized_name = command(json!({
|
||||
"ref": {"type": "ref/prompt", "name": "greeting"},
|
||||
"argument": {"name": long_name, "value": ""}
|
||||
}))
|
||||
.expect("the request shape parses");
|
||||
assert_eq!(oversized_name.validate(), Some(INVALID_PARAMS));
|
||||
|
||||
let empty_argument = command(json!({
|
||||
"ref": {"type": "ref/resource", "uri": "crank://orders/{order_id}"},
|
||||
"argument": {"name": "", "value": ""}
|
||||
}))
|
||||
.expect("the request shape parses");
|
||||
assert_eq!(empty_argument.validate(), Some(INVALID_PARAMS));
|
||||
|
||||
let empty_reference = command(json!({
|
||||
"ref": {"type": "ref/prompt", "name": ""},
|
||||
"argument": {"name": "tone", "value": ""}
|
||||
}))
|
||||
.expect("the request shape parses");
|
||||
assert_eq!(empty_reference.validate(), Some(INVALID_PARAMS));
|
||||
|
||||
let long_uri = "u".repeat(MAX_REFERENCE_URI_BYTES + 1);
|
||||
let oversized_uri = command(json!({
|
||||
"ref": {"type": "ref/resource", "uri": long_uri},
|
||||
"argument": {"name": "order_id", "value": ""}
|
||||
}))
|
||||
.expect("the request shape parses");
|
||||
assert_eq!(oversized_uri.validate(), Some(INVALID_PARAMS));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_optional_context_is_validated_as_the_pinned_string_map() {
|
||||
let non_string = command(json!({
|
||||
"ref": {"type": "ref/prompt", "name": "greeting"},
|
||||
"argument": {"name": "tone", "value": ""},
|
||||
"context": {"arguments": {"region": 7}}
|
||||
}))
|
||||
.expect("the request shape parses");
|
||||
assert_eq!(non_string.validate(), Some(INVALID_PARAMS));
|
||||
|
||||
let mut arguments = Map::new();
|
||||
for index in 0..=MAX_CONTEXT_ARGUMENTS {
|
||||
arguments.insert(format!("argument{index}"), json!("value"));
|
||||
}
|
||||
let too_many = command(json!({
|
||||
"ref": {"type": "ref/prompt", "name": "greeting"},
|
||||
"argument": {"name": "tone", "value": ""},
|
||||
"context": {"arguments": arguments}
|
||||
}))
|
||||
.expect("the request shape parses");
|
||||
assert_eq!(too_many.validate(), Some(INVALID_PARAMS));
|
||||
}
|
||||
@@ -0,0 +1,848 @@
|
||||
//! Era resolution and the small static server-capability registration for the MCP endpoint.
|
||||
//!
|
||||
//! Scope: exactly two approved revisions — `2026-07-28` (modern stateless) and `2025-11-25` (legacy
|
||||
//! session). Withdrawn revisions (`2025-06-18`, `2025-03-26`) are rejected safely and are never an
|
||||
//! implicit identity. There is no command bus, plugin surface or experimental configuration here: a
|
||||
//! single registration source feeds the advertised capability descriptor.
|
||||
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use axum::{
|
||||
http::{HeaderMap, StatusCode},
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
use base64::{Engine as _, engine::general_purpose::STANDARD};
|
||||
use serde::Deserialize as _;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::jsonrpc::{
|
||||
HEADER_MISMATCH_ERROR_CODE, LEGACY_PROTOCOL_VERSION, META_CLIENT_CAPABILITIES_KEY,
|
||||
META_CLIENT_INFO_KEY, META_PROTOCOL_VERSION_KEY, MODERN_PROTOCOL_VERSION,
|
||||
SUPPORTED_PROTOCOL_VERSIONS, UNSUPPORTED_PROTOCOL_VERSION_ERROR_CODE, correlated_error_data,
|
||||
jsonrpc_error, method_name, params, request_id,
|
||||
};
|
||||
use crate::session::SessionState;
|
||||
use crate::transport::{json_response, protocol_version_from_headers, singleton_header};
|
||||
|
||||
mod command;
|
||||
mod completion;
|
||||
mod prompts;
|
||||
mod registry;
|
||||
mod resources;
|
||||
|
||||
pub(crate) use command::{
|
||||
ContinuationSupport, ServiceContext, ToolCallCommand, ToolCallOutcome, ToolsCommand,
|
||||
ToolsListCommand, ToolsOutcome, handle_tools_command,
|
||||
};
|
||||
pub(crate) use completion::{CompletionCommand, CompletionOutcome, handle_completion_command};
|
||||
pub(crate) use prompts::{
|
||||
PromptGetCommand, PromptsCommand, PromptsListCommand, PromptsOutcome, handle_prompts_command,
|
||||
};
|
||||
pub(crate) use resources::{
|
||||
ResourceReadCommand, ResourceTemplatesListError, ResourcesCommand, ResourcesListCommand,
|
||||
ResourcesOutcome, handle_resources_command, list_resource_templates,
|
||||
};
|
||||
|
||||
/// Resolved era of an incoming POST request.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum RequestEra {
|
||||
Modern,
|
||||
Legacy,
|
||||
}
|
||||
|
||||
/// Envelope class of an incoming POST message, decided by the single JSON-RPC envelope guard.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum EnvelopeKind {
|
||||
/// A request: `method` plus a valid request id.
|
||||
Request,
|
||||
/// A notification: `method` without an id.
|
||||
Notification,
|
||||
/// A response to a server-initiated request: no `method`, a `result` or `error`.
|
||||
Response,
|
||||
}
|
||||
|
||||
/// The JSON-RPC literal that every message on both eras must carry.
|
||||
const JSONRPC_VERSION: &str = "2.0";
|
||||
|
||||
/// The pinned modern schema types a request id as `RequestId = string | number`.
|
||||
fn is_valid_request_id(id: &Value) -> bool {
|
||||
id.is_string() || id.is_number()
|
||||
}
|
||||
|
||||
/// The pinned error object: `Error { code: number; message: string; data?: unknown }`.
|
||||
fn is_valid_error_object(error: Option<&Value>) -> bool {
|
||||
let Some(Value::Object(error)) = error else {
|
||||
return false;
|
||||
};
|
||||
error.get("code").is_some_and(Value::is_number)
|
||||
&& error.get("message").is_some_and(Value::is_string)
|
||||
}
|
||||
|
||||
/// Classify a wire response (a message without `method`).
|
||||
///
|
||||
/// Pinned shapes are exclusive: a success response carries `result: Result` (an object) and a required
|
||||
/// `id: RequestId`, an error response carries `error: Error` and may omit the id (a present id must
|
||||
/// still be a `RequestId`). Both together, neither, a foreign id, a non-object `result` or a malformed
|
||||
/// error object are all invalid requests rather than an acknowledgement.
|
||||
///
|
||||
/// The `result` value is required to be an object because the pinned `JSONRPCResultResponse` types it as
|
||||
/// `Result`; the modern `resultType` member is deliberately **not** required here, because an incoming
|
||||
/// response may come from a client implementing an earlier revision.
|
||||
fn classify_wire_response(object: &serde_json::Map<String, Value>) -> Option<EnvelopeKind> {
|
||||
match (object.contains_key("result"), object.contains_key("error")) {
|
||||
(true, false) => {
|
||||
if !matches!(object.get("result"), Some(Value::Object(_))) {
|
||||
return None;
|
||||
}
|
||||
object
|
||||
.get("id")
|
||||
.filter(|id| is_valid_request_id(id))
|
||||
.map(|_| EnvelopeKind::Response)
|
||||
}
|
||||
(false, true) => {
|
||||
if !is_valid_error_object(object.get("error")) {
|
||||
return None;
|
||||
}
|
||||
match object.get("id") {
|
||||
None => Some(EnvelopeKind::Response),
|
||||
Some(id) if is_valid_request_id(id) => Some(EnvelopeKind::Response),
|
||||
Some(_) => None,
|
||||
}
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Pinned modern wire projection of a success result.
|
||||
///
|
||||
/// `JSONRPCResultResponse.result` is a `Result`, and this revision requires the `resultType` member
|
||||
/// ("Servers implementing this protocol version MUST include this field"). Every result this server
|
||||
/// produces is a synchronous, fully computed result, so the value is `complete`. The projection is a
|
||||
/// no-op for the legacy revision, whose earlier schema has no such member, and it only ever adds the
|
||||
/// required member — the business payload is passed through untouched.
|
||||
pub(crate) fn project_modern_result(protocol_version: &str, result: Value) -> Value {
|
||||
if protocol_version != MODERN_PROTOCOL_VERSION {
|
||||
return result;
|
||||
}
|
||||
let Value::Object(mut object) = result else {
|
||||
return result;
|
||||
};
|
||||
object
|
||||
.entry("resultType".to_owned())
|
||||
.or_insert_with(|| Value::String("complete".to_owned()));
|
||||
Value::Object(object)
|
||||
}
|
||||
|
||||
/// The same projection for a result that extends `CacheableResult` (`tools/list`): the pinned schema
|
||||
/// makes `ttlMs` and `cacheScope` mandatory there as well. No cache policy exists for this slice, so the
|
||||
/// conservative and honest hints are `0` (immediately stale) and `private` (scoped to the authorized
|
||||
/// agent); this adds no caching framework.
|
||||
pub(crate) fn project_modern_cacheable_result(protocol_version: &str, result: Value) -> Value {
|
||||
let result = project_modern_result(protocol_version, result);
|
||||
if protocol_version != MODERN_PROTOCOL_VERSION {
|
||||
return result;
|
||||
}
|
||||
let Value::Object(mut object) = result else {
|
||||
return result;
|
||||
};
|
||||
object.entry("ttlMs".to_owned()).or_insert_with(|| json!(0));
|
||||
object
|
||||
.entry("cacheScope".to_owned())
|
||||
.or_insert_with(|| Value::String("private".to_owned()));
|
||||
Value::Object(object)
|
||||
}
|
||||
|
||||
/// Minimal `serde` helper for a field the advertised schema types as an **object**: a JSON object is
|
||||
/// accepted as is, while a missing key, `null`, an array or a scalar is a deserialization error. It is
|
||||
/// the shared shape check for the tool-call parameter objects (the top-level `arguments` of `tools/call`
|
||||
/// and the nested `arguments` of the `call_tool` proxy), so both eras reject the same invalid shapes
|
||||
/// before any approval or outbound work.
|
||||
pub(crate) fn deserialize_object_only<'de, D>(deserializer: D) -> Result<Value, D::Error>
|
||||
where
|
||||
D: serde::Deserializer<'de>,
|
||||
{
|
||||
let value = Value::deserialize(deserializer)?;
|
||||
match value {
|
||||
Value::Object(map) => Ok(Value::Object(map)),
|
||||
other => Err(serde::de::Error::custom(format!(
|
||||
"`arguments` must be an object, got {}",
|
||||
json_type_name(&other)
|
||||
))),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn json_type_name(value: &Value) -> &'static str {
|
||||
match value {
|
||||
Value::Null => "null",
|
||||
Value::Bool(_) => "boolean",
|
||||
Value::Number(_) => "number",
|
||||
Value::String(_) => "string",
|
||||
Value::Array(_) => "array",
|
||||
Value::Object(_) => "object",
|
||||
}
|
||||
}
|
||||
|
||||
/// `400` + `-32600`. JSON-RPC requires the response id to be null for an invalid request, so a value
|
||||
/// that could not be validated is never echoed back.
|
||||
fn invalid_request_response() -> Response {
|
||||
let error = jsonrpc_error(Value::Null, -32600, "invalid JSON-RPC request".to_owned());
|
||||
|
||||
json_response(StatusCode::BAD_REQUEST, error, None, None)
|
||||
}
|
||||
|
||||
/// The response id for a message whose JSON-RPC envelope has **not** necessarily been validated yet.
|
||||
///
|
||||
/// The session-carrier projections (`ambiguous_session_carrier_response`,
|
||||
/// `malformed_carrier_response`) reject a request for its carrier and therefore run *before* the
|
||||
/// single envelope guard, so the body id they read may still be an invalid kind
|
||||
/// (`object`/`boolean`/`array`). JSON-RPC requires the response id to be null whenever the request
|
||||
/// could not be validated — the same convention `invalid_request_response` uses — so an id that is
|
||||
/// not a `RequestId` is never echoed back. A valid `string`/`number` id is preserved unchanged, an
|
||||
/// absent id stays null, and this changes nothing for a caller that already passed the guard (such a
|
||||
/// message can only carry a valid id or none at all).
|
||||
fn safe_response_id(message: &Value) -> Value {
|
||||
let id = request_id(message);
|
||||
if is_valid_request_id(&id) {
|
||||
id
|
||||
} else {
|
||||
Value::Null
|
||||
}
|
||||
}
|
||||
|
||||
/// The one JSON-RPC envelope guard: the body must be a well-formed JSON-RPC message before any era
|
||||
/// resolution, dispatch, approval or outbound request happens. JSON extraction succeeding only proves
|
||||
/// the body was syntactically valid JSON, which is a different property from envelope validity.
|
||||
pub(crate) fn validate_jsonrpc_envelope(message: &Value) -> Result<EnvelopeKind, Rejection> {
|
||||
let Some(object) = message.as_object() else {
|
||||
return Err(rejected(invalid_request_response()));
|
||||
};
|
||||
|
||||
match object.get("jsonrpc") {
|
||||
Some(Value::String(version)) if version == JSONRPC_VERSION => {}
|
||||
_ => return Err(rejected(invalid_request_response())),
|
||||
}
|
||||
|
||||
match object.get("method") {
|
||||
Some(Value::String(method)) if !method.trim().is_empty() => {
|
||||
if let Some(Value::Object(_)) | None = object.get("params") {
|
||||
} else {
|
||||
return Err(rejected(invalid_request_response()));
|
||||
}
|
||||
|
||||
match object.get("id") {
|
||||
None => Ok(EnvelopeKind::Notification),
|
||||
Some(id) if is_valid_request_id(id) => Ok(EnvelopeKind::Request),
|
||||
// A present but invalid id is neither a valid request nor a notification: it must
|
||||
// never be acknowledged as one.
|
||||
Some(_) => Err(rejected(invalid_request_response())),
|
||||
}
|
||||
}
|
||||
Some(_) => Err(rejected(invalid_request_response())),
|
||||
None => match classify_wire_response(object) {
|
||||
Some(kind) => Ok(kind),
|
||||
None => Err(rejected(invalid_request_response())),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// A live transport session is operational only under the supported legacy revision.
|
||||
///
|
||||
/// Sessions are persisted, so a session created under a withdrawn revision can still be found in the
|
||||
/// store. It must be rejected with a safe error instead of being served as a live legacy session,
|
||||
/// even when the request carries no version header.
|
||||
pub(crate) fn validate_session_revision(session: &SessionState) -> Result<(), StatusCode> {
|
||||
if session.protocol_version == LEGACY_PROTOCOL_VERSION {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(StatusCode::BAD_REQUEST)
|
||||
}
|
||||
}
|
||||
|
||||
/// Admit the session-lifecycle HTTP methods (`GET`/`DELETE`) only for the legacy era.
|
||||
///
|
||||
/// The modern revision removed the standalone GET stream endpoint and is stateless, so an explicit
|
||||
/// modern identity answers `405` instead of reaching the legacy session lifecycle. An unknown,
|
||||
/// withdrawn or unreadable revision is a safe admission error. Only a verified legacy session — a
|
||||
/// legacy revision header, or no header at all with the identity taken from the session itself — may
|
||||
/// continue into the session branch.
|
||||
pub(crate) fn session_lifecycle_admission(headers: &HeaderMap) -> Result<(), Rejection> {
|
||||
match protocol_version_from_headers(headers) {
|
||||
Err(status) => Err(rejected(status.into_response())),
|
||||
Ok(None) => Ok(()),
|
||||
Ok(Some(version)) if version == LEGACY_PROTOCOL_VERSION => Ok(()),
|
||||
Ok(Some(version)) if version == MODERN_PROTOCOL_VERSION => {
|
||||
Err(rejected(StatusCode::METHOD_NOT_ALLOWED.into_response()))
|
||||
}
|
||||
Ok(Some(_)) => Err(rejected(StatusCode::BAD_REQUEST.into_response())),
|
||||
}
|
||||
}
|
||||
|
||||
/// Identity resolved from the request before any method dispatch.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct RequestIdentity {
|
||||
pub(crate) era: RequestEra,
|
||||
/// Negotiated revision when the request itself carries one (modern requests and legacy
|
||||
/// `initialize`). Legacy subsequent requests identify the revision through their session instead.
|
||||
pub(crate) version: Option<String>,
|
||||
}
|
||||
|
||||
/// Ready-made rejection, boxed because a response is much larger than the identity it replaces.
|
||||
type Rejection = Box<Response>;
|
||||
|
||||
fn rejected(response: Response) -> Rejection {
|
||||
Box::new(response)
|
||||
}
|
||||
|
||||
/// The one registration source for the advertised server capabilities, indexed by the revision the
|
||||
/// caller serves. Advertisement equals what is implemented: later capabilities are added to the
|
||||
/// static registration by their owning story, not pre-declared here. Both the modern
|
||||
/// `discover_result` and the legacy `handle_initialize` pass the revision they serve, so a
|
||||
/// single-era declaration never leaks into the other era (R6).
|
||||
pub(crate) fn advertised_server_capabilities(revision: &str) -> Value {
|
||||
request_registration().map_or_else(
|
||||
|| Value::Object(serde_json::Map::new()),
|
||||
|registration| registration.registry().advertised_capabilities(revision),
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) use registry::{CapabilityRegistry, DispatchDecision, Kind, MethodHandler};
|
||||
|
||||
/// The descriptor vocabulary and tables of the static registration, re-exported for the
|
||||
/// BUILD-internal registration test seam (spec sections 6.3/7.2): the in-crate observer tests add one
|
||||
/// inert private descriptor to a copy of these tables and prove that the real dispatch and
|
||||
/// advertisement move with it. The production registration itself is unchanged.
|
||||
#[cfg(test)]
|
||||
pub(crate) use registry::{
|
||||
CAPABILITY_DESCRIPTORS, CapabilityId, CapabilityIdDescriptor, FeatureSet, HeaderSet,
|
||||
METHOD_DESCRIPTORS, MethodDescriptor, Roster,
|
||||
};
|
||||
|
||||
/// The one owning registration of this endpoint (R5/D-3), held by the protocol layer both era
|
||||
/// adapters go through.
|
||||
///
|
||||
/// The snapshot is validated once and then reused, so dispatch and advertisement are derived from
|
||||
/// the *same* registration and cannot drift; the adapters keep no method list of their own. An
|
||||
/// invalid static table registers nothing at all (fail-closed): every dispatch is refused instead of
|
||||
/// being served from a table that contradicts itself. The table itself is proven valid by
|
||||
/// `protocol::registry::tests::`.
|
||||
static CAPABILITY_REGISTRY: OnceLock<Option<CapabilityRegistry>> = OnceLock::new();
|
||||
|
||||
/// The validated registration snapshot of this endpoint.
|
||||
pub(crate) fn capability_registry() -> Option<&'static CapabilityRegistry> {
|
||||
CAPABILITY_REGISTRY
|
||||
.get_or_init(|| {
|
||||
CapabilityRegistry::new(
|
||||
registry::CAPABILITY_DESCRIPTORS,
|
||||
registry::METHOD_DESCRIPTORS,
|
||||
)
|
||||
.ok()
|
||||
})
|
||||
.as_ref()
|
||||
}
|
||||
|
||||
/// The registration a request is served with: the production snapshot, unless the in-crate observer
|
||||
/// test installed one for this request (`app::dispatch_observer`, `#[cfg(test)]` only). The seam
|
||||
/// exists so the add/remove proof runs against the *real* router instead of a registry unit query.
|
||||
fn request_registration() -> Option<RegistrationHandle> {
|
||||
#[cfg(test)]
|
||||
if let Some(registration) = crate::app::dispatch_observer::installed_registration() {
|
||||
return Some(RegistrationHandle::Test(registration));
|
||||
}
|
||||
capability_registry().map(RegistrationHandle::Production)
|
||||
}
|
||||
|
||||
enum RegistrationHandle {
|
||||
Production(&'static CapabilityRegistry),
|
||||
#[cfg(test)]
|
||||
Test(std::sync::Arc<CapabilityRegistry>),
|
||||
}
|
||||
|
||||
impl RegistrationHandle {
|
||||
fn registry(&self) -> &CapabilityRegistry {
|
||||
match self {
|
||||
Self::Production(registration) => registration,
|
||||
#[cfg(test)]
|
||||
Self::Test(registration) => registration,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The registration-backed dispatch entry point shared by both era adapters (R5/D-3).
|
||||
///
|
||||
/// A method no descriptor owns has no handler, and a method whose owning capability is not eligible
|
||||
/// in the requested revision is a wrong-era request: neither can reach a service or make an outbound
|
||||
/// call, because both adapters dispatch on this decision.
|
||||
pub(crate) fn dispatch_decision(method: &str, revision: &str) -> DispatchDecision {
|
||||
request_registration().map_or(DispatchDecision::Unregistered, |registration| {
|
||||
registration.registry().dispatch_decision(method, revision)
|
||||
})
|
||||
}
|
||||
|
||||
fn error_response(message: &Value, code: i64, text: String) -> Response {
|
||||
json_response(
|
||||
StatusCode::BAD_REQUEST,
|
||||
jsonrpc_error(safe_response_id(message), code, text),
|
||||
None,
|
||||
None,
|
||||
)
|
||||
}
|
||||
|
||||
/// Header carrying the invoked method on modern HTTP requests (required for every modern request).
|
||||
pub(crate) const HEADER_MCP_METHOD: &str = "Mcp-Method";
|
||||
|
||||
/// Declared `Mcp-Method` value of a modern request.
|
||||
///
|
||||
/// Conflicting duplicate values are an ambiguous method declaration and are rejected as a header
|
||||
/// mismatch instead of resolving to the first value; identical duplicates collapse to one value.
|
||||
pub(crate) fn declared_mcp_method<'a>(
|
||||
headers: &'a HeaderMap,
|
||||
message: &Value,
|
||||
) -> Result<Option<&'a str>, Rejection> {
|
||||
singleton_header(headers, HEADER_MCP_METHOD)
|
||||
.map_err(|_| rejected(modern_header_mismatch_response(message)))
|
||||
}
|
||||
|
||||
/// Header carrying `params.name` on modern `tools/call` requests.
|
||||
pub(crate) const HEADER_MCP_NAME: &str = "Mcp-Name";
|
||||
|
||||
const BASE64_SENTINEL_PREFIX: &str = "=?base64?";
|
||||
const BASE64_SENTINEL_SUFFIX: &str = "?=";
|
||||
|
||||
/// `400` + `-32020` for a modern request whose declared method header is missing or mismatched.
|
||||
pub(crate) fn modern_header_mismatch_response(message: &Value) -> Response {
|
||||
header_mismatch_response(message, "`Mcp-Method` must match the invoked method")
|
||||
}
|
||||
|
||||
/// `400` + `-32020` for a modern request that carries a session header. The modern revision is
|
||||
/// stateless, so a session carrier is a conflicting identity — it is rejected before any session
|
||||
/// lookup, rate-limit accounting or dispatch, and it is never silently ignored.
|
||||
pub(crate) fn modern_carrier_conflict_response(message: &Value) -> Response {
|
||||
header_mismatch_response(
|
||||
message,
|
||||
"the negotiated revision is stateless and does not accept a session header",
|
||||
)
|
||||
}
|
||||
|
||||
/// `202 Accepted` with no body: a notification carries no `id`, so nothing is dispatched.
|
||||
pub(crate) fn modern_notification_response() -> Response {
|
||||
StatusCode::ACCEPTED.into_response()
|
||||
}
|
||||
|
||||
/// Era-correct answer for a method that the modern era does not implement.
|
||||
pub(crate) fn modern_method_not_found_response(message: &Value) -> Response {
|
||||
json_response(
|
||||
StatusCode::NOT_FOUND,
|
||||
jsonrpc_error(
|
||||
request_id(message),
|
||||
-32601,
|
||||
"method not found for the negotiated revision".to_owned(),
|
||||
),
|
||||
None,
|
||||
None,
|
||||
)
|
||||
}
|
||||
|
||||
/// Decode a modern header value: the pinned sentinel `=?base64?…?=` is decoded, anything else is
|
||||
/// taken literally. An unreadable sentinel value yields `None` and is rejected as a mismatch.
|
||||
fn decode_header_value(raw: &str) -> Option<String> {
|
||||
let Some(encoded) = raw.strip_prefix(BASE64_SENTINEL_PREFIX) else {
|
||||
return Some(raw.to_owned());
|
||||
};
|
||||
let encoded = encoded.strip_suffix(BASE64_SENTINEL_SUFFIX)?;
|
||||
let bytes = STANDARD.decode(encoded).ok()?;
|
||||
|
||||
String::from_utf8(bytes).ok()
|
||||
}
|
||||
|
||||
/// Validate the required `Mcp-Name` header against the body value.
|
||||
///
|
||||
/// Pinned modern rules: the header is required for `tools/call`, the sentinel-encoded form must be
|
||||
/// decoded before the comparison, and the comparison is case-sensitive.
|
||||
pub(crate) fn validate_modern_request_name(
|
||||
message: &Value,
|
||||
headers: &HeaderMap,
|
||||
body_name: &str,
|
||||
) -> Result<(), Rejection> {
|
||||
let Some(raw) = singleton_header(headers, HEADER_MCP_NAME)
|
||||
.map_err(|_| header_mismatch_response(message, "the `Mcp-Name` header is ambiguous"))?
|
||||
else {
|
||||
return Err(rejected(header_mismatch_response(
|
||||
message,
|
||||
"the required `Mcp-Name` header is missing",
|
||||
)));
|
||||
};
|
||||
let Some(decoded) = decode_header_value(raw) else {
|
||||
return Err(rejected(header_mismatch_response(
|
||||
message,
|
||||
"the `Mcp-Name` header value cannot be decoded",
|
||||
)));
|
||||
};
|
||||
if decoded != body_name {
|
||||
return Err(rejected(header_mismatch_response(
|
||||
message,
|
||||
&format!(
|
||||
"the `Mcp-Name` header value '{decoded}' does not match the body value '{body_name}'"
|
||||
),
|
||||
)));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn unsupported_version_response(message: &Value, requested: &str) -> Response {
|
||||
let supported: Vec<&str> = SUPPORTED_PROTOCOL_VERSIONS.to_vec();
|
||||
let mut error = jsonrpc_error(
|
||||
request_id(message),
|
||||
UNSUPPORTED_PROTOCOL_VERSION_ERROR_CODE,
|
||||
format!("unsupported protocol version {requested}"),
|
||||
);
|
||||
error["error"]["data"] = correlated_error_data(json!({
|
||||
"requested": requested,
|
||||
"supported": supported,
|
||||
}));
|
||||
|
||||
json_response(StatusCode::BAD_REQUEST, error, None, None)
|
||||
}
|
||||
|
||||
fn header_mismatch_response(message: &Value, details: &str) -> Response {
|
||||
let mut error = jsonrpc_error(
|
||||
safe_response_id(message),
|
||||
HEADER_MISMATCH_ERROR_CODE,
|
||||
"protocol identity mismatch".to_owned(),
|
||||
);
|
||||
// Merge into the correlation data instead of replacing it: the request/trace correlation that
|
||||
// `jsonrpc_error` already attached must survive the added detail.
|
||||
error["error"]["data"] = correlated_error_data(json!({ "details": details }));
|
||||
|
||||
json_response(StatusCode::BAD_REQUEST, error, None, None)
|
||||
}
|
||||
|
||||
/// Era-correct structured rejection for a malformed or ambiguous `MCP-Protocol-Version` carrier
|
||||
/// (`protocol-era-matrix.md` row 17).
|
||||
///
|
||||
/// The carrier is exactly what failed to parse, so it cannot identify the era. The era is read from
|
||||
/// the rest of the request instead: a request carrying a modern identity marker is answered in the
|
||||
/// modern shape (`400` + `-32020` `HeaderMismatch`), anything else stays legacy and is answered with
|
||||
/// the legacy-shaped structured error. A malformed carrier is never re-labelled as a modern
|
||||
/// unsupported-revision answer (`-32022` is reserved for a well-formed but unknown *effective*
|
||||
/// identity), and no era is guessed from the malformed value itself.
|
||||
fn malformed_carrier_response(headers: &HeaderMap, message: &Value) -> Response {
|
||||
const DETAILS: &str = "the `MCP-Protocol-Version` header value is malformed or ambiguous";
|
||||
|
||||
if declares_modern_identity(headers, message) {
|
||||
header_mismatch_response(message, DETAILS)
|
||||
} else {
|
||||
error_response(message, -32602, DETAILS.to_owned())
|
||||
}
|
||||
}
|
||||
|
||||
/// Era-correct structured rejection for an ambiguous `MCP-Session-Id` carrier (matrix row 17).
|
||||
///
|
||||
/// A conflicting duplicate session carrier cannot identify the era, exactly like a malformed
|
||||
/// version carrier, and the callers that read it (`GET`/`DELETE`/`POST`) currently answer a bare
|
||||
/// `400` with an empty body. For a POST that carries a JSON-RPC envelope the request must instead be
|
||||
/// answered with the era-correct structured diagnostic: the era is read from the **non-ambiguous**
|
||||
/// part of the request, never guessed from (or resolved to) one of the conflicting values.
|
||||
///
|
||||
/// The session-lifecycle methods keep their own admission path (`GET`/`DELETE` stay HTTP) and never
|
||||
/// reach this projection.
|
||||
pub(crate) fn ambiguous_session_carrier_response(headers: &HeaderMap, message: &Value) -> Response {
|
||||
const DETAILS: &str = "the `MCP-Session-Id` header value is ambiguous";
|
||||
|
||||
if declares_modern_identity(headers, message) {
|
||||
header_mismatch_response(message, DETAILS)
|
||||
} else {
|
||||
error_response(message, -32602, DETAILS.to_owned())
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the non-carrier part of the request identifies the modern era.
|
||||
///
|
||||
/// Used only to pick the era-correct shape for a carrier diagnostic, never to admit a request. Any
|
||||
/// one of these markers is enough, because each is unambiguous on its own:
|
||||
/// - an unambiguously present, supported modern `MCP-Protocol-Version` header — a modern header never
|
||||
/// routes the request into the legacy branch (matrix row 3). A conflicting duplicate or an
|
||||
/// unreadable value resolves to `Err` and therefore cannot choose the era by one of its values
|
||||
/// (row 17);
|
||||
/// - the `Mcp-Method` request header (required by every modern request, absent on a legacy one);
|
||||
/// - a request-scoped `_meta` client identity (with or without its version field).
|
||||
fn declares_modern_identity(headers: &HeaderMap, message: &Value) -> bool {
|
||||
if matches!(
|
||||
protocol_version_from_headers(headers),
|
||||
Ok(Some(version)) if version == MODERN_PROTOCOL_VERSION
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if singleton_header(headers, HEADER_MCP_METHOD)
|
||||
.ok()
|
||||
.flatten()
|
||||
.is_some()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
let params = params(message);
|
||||
let meta = params.get("_meta");
|
||||
declares_modern_metadata(meta)
|
||||
|| matches!(meta, Some(Value::Object(meta)) if meta.contains_key(META_PROTOCOL_VERSION_KEY))
|
||||
}
|
||||
|
||||
/// Whether a request `_meta` object carries a modern-specific client identity key.
|
||||
///
|
||||
/// Used to recognise a modern identity that is missing its required version carrier (matrix row 4)
|
||||
/// and to pick the era-correct shape for a carrier diagnostic. It never admits a request: a modern
|
||||
/// identity still requires the version header and the complete request-scoped metadata.
|
||||
fn declares_modern_metadata(meta: Option<&Value>) -> bool {
|
||||
let Some(Value::Object(meta)) = meta else {
|
||||
return false;
|
||||
};
|
||||
|
||||
[META_CLIENT_CAPABILITIES_KEY, META_CLIENT_INFO_KEY]
|
||||
.iter()
|
||||
.any(|key| meta.contains_key(*key))
|
||||
}
|
||||
|
||||
/// The modern era requires the full per-request client identity in `params._meta`:
|
||||
/// `protocolVersion` (string), `clientCapabilities` (object) and `clientInfo` (object with a
|
||||
/// non-empty `name` and `version`). Every failure is a header/metadata mismatch (`-32020`).
|
||||
fn validate_modern_metadata(meta: Option<&Value>, message: &Value) -> Result<(), Rejection> {
|
||||
let Some(Value::Object(meta)) = meta else {
|
||||
return Err(rejected(header_mismatch_response(
|
||||
message,
|
||||
"modern requests require request `_meta` metadata",
|
||||
)));
|
||||
};
|
||||
|
||||
match meta.get(META_PROTOCOL_VERSION_KEY) {
|
||||
Some(Value::String(version)) if version == MODERN_PROTOCOL_VERSION => {}
|
||||
Some(Value::String(_)) | None => {
|
||||
return Err(rejected(header_mismatch_response(
|
||||
message,
|
||||
"modern requests require `_meta` protocolVersion",
|
||||
)));
|
||||
}
|
||||
Some(_) => {
|
||||
return Err(rejected(header_mismatch_response(
|
||||
message,
|
||||
"body protocol version must be a string",
|
||||
)));
|
||||
}
|
||||
}
|
||||
|
||||
if !meta
|
||||
.get(META_CLIENT_CAPABILITIES_KEY)
|
||||
.is_some_and(Value::is_object)
|
||||
{
|
||||
return Err(rejected(header_mismatch_response(
|
||||
message,
|
||||
"modern requests require request `_meta` client capabilities",
|
||||
)));
|
||||
}
|
||||
|
||||
// `clientInfo` is **optional** in the pinned `RequestMetaObject` (a client SHOULD send it, but an
|
||||
// absent value is valid), so an omitted value is accepted. A value that **is** present must still
|
||||
// satisfy its `Implementation` shape: an object with a non-empty `name` and `version`. The two
|
||||
// required metadata carriers above are not weakened by this.
|
||||
if let Some(client_info) = meta.get(META_CLIENT_INFO_KEY) {
|
||||
let Some(client_info) = client_info.as_object() else {
|
||||
return Err(rejected(header_mismatch_response(
|
||||
message,
|
||||
"modern request `_meta` clientInfo must be an object",
|
||||
)));
|
||||
};
|
||||
for key in ["name", "version"] {
|
||||
let present = client_info
|
||||
.get(key)
|
||||
.and_then(Value::as_str)
|
||||
.is_some_and(|value| !value.trim().is_empty());
|
||||
if !present {
|
||||
return Err(rejected(header_mismatch_response(
|
||||
message,
|
||||
"modern requests require `_meta` clientInfo name and version",
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Resolve the era and the request identity.
|
||||
///
|
||||
/// Rules (binding precedence rows of `protocol-era-matrix.md`):
|
||||
/// - header and body identity present but different → `-32020` (mismatch takes precedence);
|
||||
/// - a modern identity requires the version header and the full body `_meta` client identity,
|
||||
/// otherwise `-32020`;
|
||||
/// - an unknown or withdrawn identity → `-32022` with the supported list (never an implicit default),
|
||||
/// except on a session-based `initialize`, which is answered legacy-shaped;
|
||||
/// - `initialize` belongs to the legacy session era only: a modern revision in its parameters is
|
||||
/// rejected instead of minting a session;
|
||||
/// - a legacy `initialize` body version outside the approved window → rejected without minting a
|
||||
/// session and without echoing a withdrawn revision as the served identity;
|
||||
/// - `_meta` that already carries a modern-specific client identity key without any version carrier →
|
||||
/// `-32020` header validation failure, never a legacy admission;
|
||||
/// - no identity at all stays "no identity": the legacy session path decides, and nothing is guessed.
|
||||
pub(crate) fn resolve_request_identity(
|
||||
headers: &HeaderMap,
|
||||
message: &Value,
|
||||
) -> Result<RequestIdentity, Rejection> {
|
||||
let header_version = match protocol_version_from_headers(headers) {
|
||||
Ok(version) => version,
|
||||
// A conflicting duplicate carrier or an unreadable value means the request names no usable
|
||||
// revision; a present-but-blank value is the same class. Matrix row 17 requires the
|
||||
// era-correct structured diagnostic for that class instead of a bare `400`, and the epoch
|
||||
// cannot be read from the malformed value itself — only from the rest of the request.
|
||||
Err(_) => return Err(rejected(malformed_carrier_response(headers, message))),
|
||||
};
|
||||
if let Some(version) = header_version.as_deref()
|
||||
&& version.trim().is_empty()
|
||||
{
|
||||
return Err(rejected(malformed_carrier_response(headers, message)));
|
||||
}
|
||||
|
||||
let body_params = params(message);
|
||||
let meta = body_params.get("_meta");
|
||||
let meta_version = match meta {
|
||||
Some(Value::Object(meta)) => match meta.get(META_PROTOCOL_VERSION_KEY) {
|
||||
Some(Value::String(version)) => Some(version.clone()),
|
||||
Some(_) => {
|
||||
return Err(rejected(header_mismatch_response(
|
||||
message,
|
||||
"body protocol version must be a string",
|
||||
)));
|
||||
}
|
||||
None => None,
|
||||
},
|
||||
Some(_) => {
|
||||
return Err(rejected(header_mismatch_response(
|
||||
message,
|
||||
"request _meta must be an object",
|
||||
)));
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
|
||||
if let (Some(header), Some(meta_version)) = (header_version.as_deref(), meta_version.as_deref())
|
||||
&& header != meta_version
|
||||
{
|
||||
return Err(rejected(header_mismatch_response(
|
||||
message,
|
||||
"header and body protocol versions differ",
|
||||
)));
|
||||
}
|
||||
|
||||
// `initialize` mints a session, and only the legacy revision is session-based. A modern revision
|
||||
// here is rejected before any session is created, whichever carrier declares it.
|
||||
if matches!(method_name(message), Some("initialize"))
|
||||
&& body_params
|
||||
.get("protocolVersion")
|
||||
.and_then(Value::as_str)
|
||||
.is_some_and(|requested| requested == MODERN_PROTOCOL_VERSION)
|
||||
{
|
||||
return Err(rejected(error_response(
|
||||
message,
|
||||
-32602,
|
||||
format!(
|
||||
"revision {MODERN_PROTOCOL_VERSION} is not a session-based revision; it does not use initialize"
|
||||
),
|
||||
)));
|
||||
}
|
||||
|
||||
let effective = header_version.clone().or_else(|| meta_version.clone());
|
||||
|
||||
// `_meta` that already names a modern-specific client identity key is a modern request whose
|
||||
// required version carrier is missing, not a legacy request: admitting it as legacy would
|
||||
// execute it through the legacy session path (matrix row 4). This condition is independent of
|
||||
// whatever version the request header names — an explicit legacy version header does not turn
|
||||
// such a request into a legacy admission (matrix row 16, mixed carriers are rejected for the era
|
||||
// identified by the dominant carrier) — so the guard runs before the effective identity is
|
||||
// matched and is a header-validation failure before any adapter or session admission.
|
||||
if meta_version.is_none() && declares_modern_metadata(meta) {
|
||||
return Err(rejected(header_mismatch_response(
|
||||
message,
|
||||
"modern requests require `_meta` protocolVersion",
|
||||
)));
|
||||
}
|
||||
|
||||
let Some(effective) = effective else {
|
||||
if matches!(method_name(message), Some("initialize")) {
|
||||
let requested = body_params
|
||||
.get("protocolVersion")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default();
|
||||
if crate::jsonrpc::negotiated_protocol_version(requested).is_none() {
|
||||
return Err(rejected(error_response(
|
||||
message,
|
||||
-32602,
|
||||
format!("unsupported protocol version {requested}"),
|
||||
)));
|
||||
}
|
||||
return Ok(RequestIdentity {
|
||||
era: RequestEra::Legacy,
|
||||
version: Some(requested.to_owned()),
|
||||
});
|
||||
}
|
||||
|
||||
return Ok(RequestIdentity {
|
||||
era: RequestEra::Legacy,
|
||||
version: None,
|
||||
});
|
||||
};
|
||||
|
||||
match effective.as_str() {
|
||||
MODERN_PROTOCOL_VERSION => {
|
||||
// The modern era negotiates per request: the version header is required, and the body
|
||||
// metadata must carry the complete request-scoped client identity.
|
||||
if header_version.is_none() {
|
||||
return Err(rejected(header_mismatch_response(
|
||||
message,
|
||||
"modern requests require the negotiated protocol version header",
|
||||
)));
|
||||
}
|
||||
validate_modern_metadata(meta, message)?;
|
||||
|
||||
Ok(RequestIdentity {
|
||||
era: RequestEra::Modern,
|
||||
version: Some(MODERN_PROTOCOL_VERSION.to_owned()),
|
||||
})
|
||||
}
|
||||
LEGACY_PROTOCOL_VERSION => Ok(RequestIdentity {
|
||||
era: RequestEra::Legacy,
|
||||
version: Some(LEGACY_PROTOCOL_VERSION.to_owned()),
|
||||
}),
|
||||
// A legacy `initialize` negotiates its revision through `params.protocolVersion` and is
|
||||
// rejected **legacy-shaped**: the modern `-32022` contract describes a modern per-request
|
||||
// identity and must not be imposed on the session-based era (matrix row 14). The rejected
|
||||
// revision is still never served, echoed or minted, and no exact legacy code is invented —
|
||||
// this is the same answer the header-less `initialize` already receives.
|
||||
other => {
|
||||
if matches!(method_name(message), Some("initialize")) {
|
||||
return Err(rejected(error_response(
|
||||
message,
|
||||
-32602,
|
||||
format!("unsupported protocol version {other}"),
|
||||
)));
|
||||
}
|
||||
|
||||
Err(rejected(unsupported_version_response(message, other)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The pinned `DiscoverResult` for `server/discover` of the revision the caller serves.
|
||||
pub(crate) fn discover_result(revision: &str, server_name: &str, server_version: &str) -> Value {
|
||||
json!({
|
||||
"resultType": "complete",
|
||||
"supportedVersions": SUPPORTED_PROTOCOL_VERSIONS,
|
||||
"capabilities": advertised_server_capabilities(revision),
|
||||
"_meta": {
|
||||
crate::jsonrpc::META_SERVER_INFO_KEY: {
|
||||
"name": server_name,
|
||||
"version": server_version,
|
||||
}
|
||||
},
|
||||
"ttlMs": 0,
|
||||
"cacheScope": "private"
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,822 @@
|
||||
//! Story 3.14: the era-neutral `prompts/list` and `prompts/get` service boundary.
|
||||
//!
|
||||
//! Both requests are answered only from the exact Published Prompt Versions bound in the active
|
||||
//! published Agent snapshot (`agent_prompt_bindings`, read in the same catalog transaction). A Draft,
|
||||
//! a foreign workspace Prompt and an unbound Prompt are therefore not addressable at all: they are
|
||||
//! absent from the bound array, so nothing here looks a Prompt up by a client-supplied id.
|
||||
//!
|
||||
//! Rendering reuses the accepted typed renderer (`PromptDefinition::preview`): every argument error
|
||||
//! (missing, unknown, wrong type, oversized) is decided there *before* a single message is produced,
|
||||
//! and the error outcome carries only the typed reason and the argument name — never a message, a
|
||||
//! dependency payload or metadata of another Prompt (AT-3.14-02).
|
||||
//!
|
||||
//! Archive is a lifecycle state, not a revoke: the immutable publication row survives, so the exact
|
||||
//! bound version of an existing Agent snapshot stays listing/serving (AT-3.14-03). Security
|
||||
//! revocation and dependency invalidation remain separate fail-closed states and are not modelled
|
||||
//! here.
|
||||
//!
|
||||
//! The wire shape stays in the adapters; this module never sees the envelope, the response mode or an
|
||||
//! `axum::Response`.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::Instant;
|
||||
|
||||
use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
|
||||
use crank_core::ids::ResourceId;
|
||||
use crank_core::prompt::{MAX_TEXT_BYTES, PromptError, PromptMessage, PromptRole};
|
||||
use crank_core::prompt_composition::{
|
||||
self, PromptCompositionError, PromptDependencyPin, PromptDependencySourceClass,
|
||||
};
|
||||
use crank_core::resource::ResourceKind;
|
||||
use crank_core::{ExecutionOrigin, InvocationSource, OperationSafetyClass, OperationStatus};
|
||||
use crank_registry::model::PromptPublicationRecord;
|
||||
use crank_runtime::{
|
||||
ExecutionAuthorization, RuntimeExecutionRequest, RuntimeOperation, RuntimeRequestContext,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Map, Value, json};
|
||||
use tracing::info;
|
||||
|
||||
use crate::{app::AppState, protocol::ServiceContext};
|
||||
|
||||
/// Upper bound of one `prompts/list` page (same shape as `resources/list`).
|
||||
const MAX_PROMPTS_LIST_LIMIT: usize = 100;
|
||||
/// Cursor format version; independent of the shared Resource tokens by the `s` surface marker.
|
||||
const CURSOR_VERSION: u8 = 1;
|
||||
/// Surface marker that keeps a `resources/list` cursor from being replayed on `prompts/list`.
|
||||
const PROMPTS_SURFACE: u8 = 2;
|
||||
|
||||
/// Parameters of a `prompts/list` command, already parsed by the adapter from the wire form.
|
||||
#[derive(Debug, Default, Deserialize)]
|
||||
pub(crate) struct PromptsListCommand {
|
||||
#[serde(default)]
|
||||
pub(crate) cursor: Option<String>,
|
||||
#[serde(default)]
|
||||
pub(crate) limit: Option<usize>,
|
||||
}
|
||||
|
||||
/// Parameters of a `prompts/get` command.
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub(crate) struct PromptGetCommand {
|
||||
pub(crate) name: String,
|
||||
/// Typed arguments; a non-object shape is rejected by the adapter before dispatch.
|
||||
#[serde(default)]
|
||||
pub(crate) arguments: Option<Map<String, Value>>,
|
||||
}
|
||||
|
||||
/// A command the shared Prompts service accepts.
|
||||
pub(crate) enum PromptsCommand {
|
||||
List(PromptsListCommand),
|
||||
Get(PromptGetCommand),
|
||||
}
|
||||
|
||||
/// A neutral outcome of a shared Prompts command.
|
||||
pub(crate) enum PromptsOutcome {
|
||||
Listed {
|
||||
prompts: Vec<Value>,
|
||||
next_cursor: Option<String>,
|
||||
},
|
||||
Got {
|
||||
description: Option<String>,
|
||||
messages: Vec<Value>,
|
||||
},
|
||||
/// The request cannot be addressed as a page (malformed/stale/cross-scope cursor).
|
||||
InvalidParams(String),
|
||||
/// Unknown, Draft, foreign or unbound Prompt name: one safe outcome that carries no Prompt
|
||||
/// metadata and cannot distinguish the cases.
|
||||
NotAvailable,
|
||||
/// The bound definition rejected the supplied arguments before any rendering; only the typed
|
||||
/// reason and the argument name of the *bound* Prompt are carried.
|
||||
ArgumentsRejected {
|
||||
reason: &'static str,
|
||||
argument: Option<String>,
|
||||
},
|
||||
/// A pinned dependency of the bound Prompt cannot be read right now. The outcome carries only
|
||||
/// the declaration position: never dependency content, name or the pinned identity's metadata.
|
||||
DependencyUnavailable { position: usize },
|
||||
/// The bound snapshot could not be read or verified.
|
||||
CatalogUnavailable,
|
||||
}
|
||||
|
||||
/// Handle one shared Prompts command for the revision the adapter serves.
|
||||
pub(crate) async fn handle_prompts_command(
|
||||
state: &Arc<AppState>,
|
||||
context: ServiceContext<'_>,
|
||||
revision: &str,
|
||||
command: PromptsCommand,
|
||||
) -> PromptsOutcome {
|
||||
let catalog = match state
|
||||
.catalog
|
||||
.get_catalog(context.workspace_slug, context.agent_slug)
|
||||
.await
|
||||
{
|
||||
Ok(catalog) => catalog,
|
||||
Err(_error) => return PromptsOutcome::CatalogUnavailable,
|
||||
};
|
||||
let workspace_id = match state
|
||||
.registry
|
||||
.published_agent_workspace_id(context.workspace_slug, context.agent_slug)
|
||||
.await
|
||||
{
|
||||
Ok(workspace_id) => workspace_id,
|
||||
Err(_error) => return PromptsOutcome::CatalogUnavailable,
|
||||
};
|
||||
// The whole bound snapshot is resolved once: pagination addresses this immutable array, so a
|
||||
// page boundary cannot shift when a Draft changes underneath the request.
|
||||
let publications = match state
|
||||
.registry
|
||||
.resolve_bound_prompt_publications(&workspace_id, &catalog.prompts)
|
||||
.await
|
||||
{
|
||||
Ok(publications) => publications,
|
||||
Err(_error) => return PromptsOutcome::CatalogUnavailable,
|
||||
};
|
||||
let scope = CursorScope {
|
||||
workspace_slug: context.workspace_slug,
|
||||
agent_slug: context.agent_slug,
|
||||
catalog_revision: &catalog.catalog_revision,
|
||||
revision,
|
||||
};
|
||||
|
||||
match command {
|
||||
PromptsCommand::List(list) => list_prompts(&publications, &scope, list),
|
||||
PromptsCommand::Get(get) => {
|
||||
get_prompt(state, &context, &workspace_id, &publications, &get).await
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn list_prompts(
|
||||
publications: &[PromptPublicationRecord],
|
||||
scope: &CursorScope<'_>,
|
||||
command: PromptsListCommand,
|
||||
) -> PromptsOutcome {
|
||||
let start = match command.cursor.as_deref() {
|
||||
Some(cursor) => match decode_cursor(cursor, scope, publications.len()) {
|
||||
Some(offset) => offset,
|
||||
None => {
|
||||
return PromptsOutcome::InvalidParams("invalid prompts/list cursor".to_owned());
|
||||
}
|
||||
},
|
||||
None => 0,
|
||||
};
|
||||
let limit = command
|
||||
.limit
|
||||
.unwrap_or(publications.len())
|
||||
.clamp(1, MAX_PROMPTS_LIST_LIMIT);
|
||||
let end = start.saturating_add(limit).min(publications.len());
|
||||
|
||||
let prompts: Vec<Value> = publications[start..end]
|
||||
.iter()
|
||||
.map(|publication| {
|
||||
json!({
|
||||
"name": publication.name,
|
||||
"description": publication.description,
|
||||
"arguments": publication.definition.arguments_json(),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
// Discovery telemetry: counts and the served revision only — never a Prompt name or content.
|
||||
info!(
|
||||
name: "mcp.prompts.list",
|
||||
outcome = "ok",
|
||||
prompt_count = prompts.len(),
|
||||
bound_prompt_count = publications.len(),
|
||||
revision = scope.revision,
|
||||
"prompt list outcome"
|
||||
);
|
||||
|
||||
let next_cursor = (end < publications.len()).then(|| encode_cursor(scope, end));
|
||||
PromptsOutcome::Listed {
|
||||
prompts,
|
||||
next_cursor,
|
||||
}
|
||||
}
|
||||
|
||||
async fn get_prompt(
|
||||
state: &Arc<AppState>,
|
||||
context: &ServiceContext<'_>,
|
||||
workspace_id: &crank_core::WorkspaceId,
|
||||
publications: &[PromptPublicationRecord],
|
||||
command: &PromptGetCommand,
|
||||
) -> PromptsOutcome {
|
||||
// Deterministic exact binding: the bound snapshot is ordered by `prompt_id`, and MCP addresses a
|
||||
// Prompt by name only. The first exact bound publication of that name is served, so the answer
|
||||
// does not depend on query timing or map order.
|
||||
// shortcut: Prompt names are not constrained unique, so two bound Prompts sharing a name are
|
||||
// resolved by prompt_id order; upgrade to a workspace-unique name constraint if the product
|
||||
// needs to address both.
|
||||
let Some(publication) = publications
|
||||
.iter()
|
||||
.find(|publication| publication.name == command.name)
|
||||
else {
|
||||
return PromptsOutcome::NotAvailable;
|
||||
};
|
||||
let supplied = command.arguments.clone().unwrap_or_default();
|
||||
// Story 3.16: the pinned content of every declared dependency is read through the Resource
|
||||
// contract of 3.8/3.11 and composed by the same renderer the admin preview uses.
|
||||
let contents =
|
||||
dependency_contents(state, context, workspace_id, &publication.dependencies).await;
|
||||
render_publication(publication, &supplied, &contents)
|
||||
}
|
||||
|
||||
/// Pure rendering step: the accepted typed renderer plus pinned dependency insertion.
|
||||
fn render_publication(
|
||||
publication: &PromptPublicationRecord,
|
||||
supplied: &Map<String, Value>,
|
||||
contents: &[Option<Vec<u8>>],
|
||||
) -> PromptsOutcome {
|
||||
match prompt_composition::render(
|
||||
&publication.definition,
|
||||
&publication.dependencies,
|
||||
supplied,
|
||||
contents,
|
||||
) {
|
||||
Ok(messages) => {
|
||||
info!(
|
||||
name: "mcp.prompts.get",
|
||||
outcome = "ok",
|
||||
message_count = messages.len(),
|
||||
dependency_count = publication.dependencies.len(),
|
||||
"prompt get outcome"
|
||||
);
|
||||
PromptsOutcome::Got {
|
||||
description: Some(publication.description.clone()),
|
||||
messages: message_values(&messages),
|
||||
}
|
||||
}
|
||||
Err(PromptCompositionError::Template(error)) => reject_arguments(error, supplied),
|
||||
// A published definition that cannot produce its pinned content right now is a total
|
||||
// failure: no message list, only the declaration position (AC6, AT-3.14-02 invariant).
|
||||
Err(PromptCompositionError::DependencyUnavailable { position })
|
||||
| Err(PromptCompositionError::DependencyCredentialFinding { position })
|
||||
| Err(PromptCompositionError::DependencyAccessBypassFinding { position })
|
||||
| Err(PromptCompositionError::DependencyRepresentationUnsupported { position }) => {
|
||||
PromptsOutcome::DependencyUnavailable { position }
|
||||
}
|
||||
Err(PromptCompositionError::DependencyUnused { position, .. }) => {
|
||||
PromptsOutcome::DependencyUnavailable { position }
|
||||
}
|
||||
Err(PromptCompositionError::CredentialFinding { .. })
|
||||
| Err(PromptCompositionError::AccessBypassFinding { .. }) => {
|
||||
PromptsOutcome::CatalogUnavailable
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Pinned content of every dependency, indexed by declaration position.
|
||||
///
|
||||
/// The exact published version is re-checked at read time (revocation is a live gate), then read
|
||||
/// through the single immutable artifact root for a static dependency. A dynamic (template)
|
||||
/// dependency is read by the Story 3.11 Resource runtime — the same read path the agent uses for
|
||||
/// its bound templates — and is therefore never substituted with its definition text.
|
||||
async fn dependency_contents(
|
||||
state: &Arc<AppState>,
|
||||
context: &ServiceContext<'_>,
|
||||
workspace_id: &crank_core::WorkspaceId,
|
||||
pins: &[PromptDependencyPin],
|
||||
) -> Vec<Option<Vec<u8>>> {
|
||||
let mut contents = Vec::with_capacity(pins.len());
|
||||
for pin in pins {
|
||||
let resource_id = ResourceId::new(pin.resource_id.clone());
|
||||
let bytes = match pin.source_class {
|
||||
PromptDependencySourceClass::Static => {
|
||||
match state
|
||||
.registry
|
||||
.resource_is_revoked(workspace_id, &resource_id)
|
||||
.await
|
||||
{
|
||||
Ok(false) => match state
|
||||
.registry
|
||||
.resolve_resource_publication(
|
||||
workspace_id.as_str(),
|
||||
&resource_id,
|
||||
pin.version,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(resolved) => state
|
||||
.artifact_store
|
||||
.as_ref()
|
||||
.and_then(|store| store.read(&resolved.artifact_ref).ok()),
|
||||
Err(_) => None,
|
||||
},
|
||||
Ok(true) | Err(_) => None,
|
||||
}
|
||||
}
|
||||
PromptDependencySourceClass::Dynamic => {
|
||||
read_pinned_template_content(
|
||||
state,
|
||||
context,
|
||||
workspace_id,
|
||||
&resource_id,
|
||||
pin.version,
|
||||
)
|
||||
.await
|
||||
}
|
||||
};
|
||||
contents.push(bytes);
|
||||
}
|
||||
contents
|
||||
}
|
||||
|
||||
/// Story 3.16 §4/§6: content of one pinned dynamic (template) dependency.
|
||||
///
|
||||
/// A Prompt dependency names only the exact `(resource_id, version)` of the template, so the
|
||||
/// declared read Operation is executed through the accepted 3.11 Resource runtime with its own
|
||||
/// authorization, outbound, size and cache contract and the live revocation gate, using the
|
||||
/// template's own parameter defaults. A parameter without a default cannot be supplied by a
|
||||
/// Prompt. Every failure stays `None`: the caller turns that into the structured
|
||||
/// `prompt_dependency_unavailable` refusal instead of inserting definition text or stale content.
|
||||
async fn read_pinned_template_content(
|
||||
state: &Arc<AppState>,
|
||||
context: &ServiceContext<'_>,
|
||||
workspace_id: &crank_core::WorkspaceId,
|
||||
resource_id: &ResourceId,
|
||||
version: u32,
|
||||
) -> Option<Vec<u8>> {
|
||||
let (publication, stored) = state
|
||||
.registry
|
||||
.resolve_resource_template_publication(workspace_id.as_str(), resource_id, version)
|
||||
.await
|
||||
.ok()?;
|
||||
let kind = ResourceKind::parse(&publication.kind)?;
|
||||
if !kind.allows_mime_type(&publication.mime_type) {
|
||||
return None;
|
||||
}
|
||||
let definition: Value = serde_json::from_str(&stored.definition_json).ok()?;
|
||||
let source = crank_core::resource::TemplateSource::parse(&definition).ok()?;
|
||||
let operation_id = crank_core::OperationId::new(source.operation_id.clone());
|
||||
let operation_record = state
|
||||
.registry
|
||||
.get_operation_version(workspace_id, &operation_id, source.operation_version)
|
||||
.await
|
||||
.ok()??;
|
||||
if operation_record.status != OperationStatus::Published {
|
||||
return None;
|
||||
}
|
||||
match state
|
||||
.registry
|
||||
.get_operation_summary(workspace_id, &operation_id)
|
||||
.await
|
||||
{
|
||||
Ok(Some(summary)) if summary.status != OperationStatus::Archived => {}
|
||||
_ => return None,
|
||||
}
|
||||
if !crate::access::credential_allows_security_level(
|
||||
context.credential,
|
||||
operation_record.snapshot.security_level,
|
||||
) {
|
||||
return None;
|
||||
}
|
||||
let operation = RuntimeOperation::from(operation_record.snapshot.clone());
|
||||
let safety = operation
|
||||
.execution_config
|
||||
.safety
|
||||
.as_ref()
|
||||
.map(|policy| policy.class);
|
||||
if safety != Some(OperationSafetyClass::Read)
|
||||
|| operation
|
||||
.execution_config
|
||||
.approval_policy
|
||||
.as_ref()
|
||||
.is_some_and(|policy| policy.required)
|
||||
|| !matches!(&operation.target, crank_core::Target::Rest(target) if matches!(target.method, crank_core::HttpMethod::Get | crank_core::HttpMethod::Head))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let mut input = Map::new();
|
||||
for parameter in &source.parameters {
|
||||
let parameter_schema: crank_schema::Schema =
|
||||
serde_json::from_value(parameter.schema.clone()).ok()?;
|
||||
let value = parameter_schema.default_value.clone()?;
|
||||
crank_runtime::validate_resource_template_parameter(¶meter_schema, &value).ok()?;
|
||||
if !super::resources::set_input_path(&mut input, ¶meter.input_path, value) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
let agent_id = state
|
||||
.registry
|
||||
.published_agent_id(context.workspace_slug, context.agent_slug)
|
||||
.await
|
||||
.ok()?;
|
||||
let request_context = RuntimeRequestContext::from_correlation(context.correlation)
|
||||
.with_response_cache_scope(
|
||||
workspace_id.as_str().to_owned(),
|
||||
agent_id.as_str().to_owned(),
|
||||
)
|
||||
.with_resource_response_cache(
|
||||
resource_id.as_str(),
|
||||
publication.version,
|
||||
source.cache.ttl_ms,
|
||||
source.cache.max_bytes,
|
||||
)
|
||||
.with_metering_context(
|
||||
workspace_id.clone(),
|
||||
Some(agent_id.clone()),
|
||||
InvocationSource::AgentToolCall,
|
||||
);
|
||||
let auth = crate::app::resolve_operation_auth(state, workspace_id, &operation.execution_config)
|
||||
.await
|
||||
.ok()?;
|
||||
let input = Value::Object(input);
|
||||
let request = RuntimeExecutionRequest::try_new(
|
||||
workspace_id,
|
||||
ExecutionOrigin::AgentSnapshot,
|
||||
Some(&agent_id),
|
||||
&operation,
|
||||
&input,
|
||||
ExecutionAuthorization::Authorized,
|
||||
auth.as_ref(),
|
||||
&request_context,
|
||||
Instant::now()
|
||||
+ std::time::Duration::from_millis(operation.execution_config.timeout_ms.max(1)),
|
||||
)
|
||||
.ok()?;
|
||||
// The live Resource lock is acquired only after registry/auth lookups, then held through
|
||||
// dispatch: a revocation before this point closes the read.
|
||||
let guard = state
|
||||
.registry
|
||||
.begin_authorized_resource_template_read(
|
||||
workspace_id.as_str(),
|
||||
resource_id,
|
||||
publication.version,
|
||||
)
|
||||
.await
|
||||
.ok()?;
|
||||
let success = state.runtime.execute_outcome(request).await.ok()?;
|
||||
let max_bytes = usize::try_from(source.cache.max_bytes)
|
||||
.unwrap_or(crank_artifacts::MAX_ARTIFACT_BYTES)
|
||||
.min(crank_artifacts::MAX_ARTIFACT_BYTES);
|
||||
let bytes = match kind {
|
||||
ResourceKind::Text => success.output.as_str().map(|text| text.as_bytes().to_vec()),
|
||||
ResourceKind::Json if !success.output.is_null() => serde_json::to_vec(&success.output).ok(),
|
||||
_ => None,
|
||||
}?;
|
||||
if bytes.is_empty() || bytes.len() > max_bytes {
|
||||
return None;
|
||||
}
|
||||
guard.commit().await.ok()?;
|
||||
Some(bytes)
|
||||
}
|
||||
|
||||
/// Map a renderer rejection onto the typed reasons of AT-3.14-02 without re-validating: the renderer
|
||||
/// decided, this only classifies its verdict, and the argument name belongs to the bound Prompt the
|
||||
/// client is already allowed to see in `prompts/list`.
|
||||
fn reject_arguments(error: PromptError, supplied: &Map<String, Value>) -> PromptsOutcome {
|
||||
match error {
|
||||
PromptError::MissingArgument(argument) => PromptsOutcome::ArgumentsRejected {
|
||||
reason: "missing_argument",
|
||||
argument: Some(argument),
|
||||
},
|
||||
PromptError::UnknownArgument(argument) => PromptsOutcome::ArgumentsRejected {
|
||||
reason: "unknown_argument",
|
||||
argument: Some(argument),
|
||||
},
|
||||
PromptError::InvalidArgument(argument) => {
|
||||
let oversized = supplied
|
||||
.get(&argument)
|
||||
.and_then(Value::as_str)
|
||||
.is_some_and(|text| text.len() > MAX_TEXT_BYTES);
|
||||
PromptsOutcome::ArgumentsRejected {
|
||||
reason: if oversized {
|
||||
"argument_too_large"
|
||||
} else {
|
||||
"argument_invalid"
|
||||
},
|
||||
argument: Some(argument),
|
||||
}
|
||||
}
|
||||
// A stored definition that no longer parses or renders is corruption, not a client error:
|
||||
// it fails closed instead of being answered as an argument rejection.
|
||||
PromptError::InvalidDefinition | PromptError::InvalidTemplate => {
|
||||
PromptsOutcome::CatalogUnavailable
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn message_values(messages: &[PromptMessage]) -> Vec<Value> {
|
||||
messages
|
||||
.iter()
|
||||
.map(|message| {
|
||||
// Pinned `PromptMessage.content` is a `ContentBlock`, so the accepted renderer's text
|
||||
// becomes one `TextContent` block. `role` is served exactly as published: the accepted
|
||||
// product model allows `system|user|assistant`, while the pinned wire `Role` union is
|
||||
// `user|assistant`; a system message is therefore preserved rather than silently
|
||||
// remapped or dropped (flagged for the product decision in the story handoff).
|
||||
json!({
|
||||
"role": match message.role {
|
||||
PromptRole::System => "system",
|
||||
PromptRole::User => "user",
|
||||
PromptRole::Assistant => "assistant",
|
||||
},
|
||||
"content": {"type": "text", "text": message.content},
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The immutable scope a continuation token is bound to. A cursor from another workspace, Agent,
|
||||
/// catalog revision, protocol revision or surface is never mixed into a page.
|
||||
struct CursorScope<'a> {
|
||||
workspace_slug: &'a str,
|
||||
agent_slug: &'a str,
|
||||
catalog_revision: &'a str,
|
||||
revision: &'a str,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct CursorPayload {
|
||||
v: u8,
|
||||
s: u8,
|
||||
w: String,
|
||||
a: String,
|
||||
c: String,
|
||||
r: String,
|
||||
o: usize,
|
||||
}
|
||||
|
||||
fn encode_cursor(scope: &CursorScope<'_>, offset: usize) -> String {
|
||||
let payload = CursorPayload {
|
||||
v: CURSOR_VERSION,
|
||||
s: PROMPTS_SURFACE,
|
||||
w: scope.workspace_slug.to_owned(),
|
||||
a: scope.agent_slug.to_owned(),
|
||||
c: scope.catalog_revision.to_owned(),
|
||||
r: scope.revision.to_owned(),
|
||||
o: offset,
|
||||
};
|
||||
let encoded = serde_json::to_vec(&payload).unwrap_or_default();
|
||||
URL_SAFE_NO_PAD.encode(encoded)
|
||||
}
|
||||
|
||||
fn decode_cursor(raw: &str, scope: &CursorScope<'_>, len: usize) -> Option<usize> {
|
||||
let bytes = URL_SAFE_NO_PAD.decode(raw).ok()?;
|
||||
let payload: CursorPayload = serde_json::from_slice(&bytes).ok()?;
|
||||
let matches = payload.v == CURSOR_VERSION
|
||||
&& payload.s == PROMPTS_SURFACE
|
||||
&& payload.w == scope.workspace_slug
|
||||
&& payload.a == scope.agent_slug
|
||||
&& payload.c == scope.catalog_revision
|
||||
&& payload.r == scope.revision;
|
||||
(matches && payload.o <= len).then_some(payload.o)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crank_core::ids::PromptId;
|
||||
use crank_core::prompt::{PromptDefinition, PromptSensitivity};
|
||||
use time::OffsetDateTime;
|
||||
|
||||
fn publication(
|
||||
prompt_id: &str,
|
||||
name: &str,
|
||||
messages: &str,
|
||||
arguments: Value,
|
||||
) -> PromptPublicationRecord {
|
||||
let messages: Value = serde_json::from_str(messages).expect("message fixture is JSON");
|
||||
let definition = PromptDefinition::parse(&json!({
|
||||
"name": name,
|
||||
"description": "Description",
|
||||
"arguments": arguments,
|
||||
"messages": messages,
|
||||
}))
|
||||
.expect("definition parses");
|
||||
PromptPublicationRecord {
|
||||
prompt_id: PromptId::new(prompt_id),
|
||||
version: 1,
|
||||
name: name.to_owned(),
|
||||
description: "Description".to_owned(),
|
||||
sensitivity: PromptSensitivity::Internal,
|
||||
definition,
|
||||
dependencies: Vec::new(),
|
||||
published_at: OffsetDateTime::from_unix_timestamp(1_700_000_000).unwrap(),
|
||||
}
|
||||
}
|
||||
|
||||
fn greeting() -> PromptPublicationRecord {
|
||||
publication(
|
||||
"prm_greeting",
|
||||
"greeting",
|
||||
r#"[{"role":"system","content":"Be brief."},{"role":"user","content":"Hello {{name}}"}]"#,
|
||||
json!([
|
||||
{"name":"name","schema":{"type":"string"},"required":true},
|
||||
{"name":"tone","schema":{"type":"string","enum":["warm","dry"]},"required":false,"default":"warm"}
|
||||
]),
|
||||
)
|
||||
}
|
||||
|
||||
fn cursor_scope(revision: &str) -> CursorScope<'_> {
|
||||
CursorScope {
|
||||
workspace_slug: "default",
|
||||
agent_slug: "assistant",
|
||||
catalog_revision: "agent-version-1-catalog-revision-7",
|
||||
revision,
|
||||
}
|
||||
}
|
||||
|
||||
fn get(name: &str, arguments: Value) -> PromptsOutcome {
|
||||
let publications = [greeting()];
|
||||
let Some(publication) = publications
|
||||
.iter()
|
||||
.find(|publication| publication.name == name)
|
||||
else {
|
||||
return PromptsOutcome::NotAvailable;
|
||||
};
|
||||
render_publication(
|
||||
publication,
|
||||
&arguments.as_object().cloned().unwrap_or_default(),
|
||||
&[],
|
||||
)
|
||||
}
|
||||
|
||||
/// AT-3.14-01: the list item carries the typed argument metadata and no message content.
|
||||
#[test]
|
||||
fn list_item_carries_typed_arguments_and_no_messages() {
|
||||
let scope = cursor_scope("2026-07-28");
|
||||
let PromptsOutcome::Listed { prompts, .. } =
|
||||
list_prompts(&[greeting()], &scope, PromptsListCommand::default())
|
||||
else {
|
||||
panic!("a bound page must list");
|
||||
};
|
||||
assert_eq!(prompts.len(), 1);
|
||||
assert_eq!(prompts[0]["name"], json!("greeting"));
|
||||
assert_eq!(
|
||||
prompts[0]["arguments"][0]["schema"]["type"],
|
||||
json!("string")
|
||||
);
|
||||
assert_eq!(prompts[0]["arguments"][1]["default"], json!("warm"));
|
||||
assert!(
|
||||
prompts[0].get("messages").is_none(),
|
||||
"prompts/list must not disclose message content"
|
||||
);
|
||||
}
|
||||
|
||||
/// AT-3.14-04: a page is deterministic and its cursor is scoped to surface/context.
|
||||
#[test]
|
||||
fn pagination_is_deterministic_and_surface_scoped() {
|
||||
let items = vec![
|
||||
publication(
|
||||
"prm_a",
|
||||
"a",
|
||||
r#"[{"role":"user","content":"A"}]"#,
|
||||
json!([]),
|
||||
),
|
||||
publication(
|
||||
"prm_b",
|
||||
"b",
|
||||
r#"[{"role":"user","content":"B"}]"#,
|
||||
json!([]),
|
||||
),
|
||||
publication(
|
||||
"prm_c",
|
||||
"c",
|
||||
r#"[{"role":"user","content":"C"}]"#,
|
||||
json!([]),
|
||||
),
|
||||
];
|
||||
let scope = cursor_scope("2026-07-28");
|
||||
let PromptsOutcome::Listed {
|
||||
prompts,
|
||||
next_cursor,
|
||||
} = list_prompts(
|
||||
&items,
|
||||
&scope,
|
||||
PromptsListCommand {
|
||||
cursor: None,
|
||||
limit: Some(2),
|
||||
},
|
||||
)
|
||||
else {
|
||||
panic!("first page must list");
|
||||
};
|
||||
assert_eq!(prompts.len(), 2);
|
||||
let cursor = next_cursor.expect("a further page exists");
|
||||
let PromptsOutcome::Listed {
|
||||
prompts: second, ..
|
||||
} = list_prompts(
|
||||
&items,
|
||||
&scope,
|
||||
PromptsListCommand {
|
||||
cursor: Some(cursor.clone()),
|
||||
limit: Some(2),
|
||||
},
|
||||
)
|
||||
else {
|
||||
panic!("second page must list");
|
||||
};
|
||||
assert_eq!(second.len(), 1);
|
||||
assert_eq!(second[0]["name"], json!("c"));
|
||||
|
||||
// The same cursor is refused on another revision and on a replayed page boundary of a
|
||||
// different Agent: a page is never mixed across scopes.
|
||||
assert!(matches!(
|
||||
list_prompts(
|
||||
&items,
|
||||
&cursor_scope("2025-11-25"),
|
||||
PromptsListCommand {
|
||||
cursor: Some(cursor.clone()),
|
||||
limit: Some(2),
|
||||
},
|
||||
),
|
||||
PromptsOutcome::InvalidParams(_)
|
||||
));
|
||||
let mut other_agent = cursor_scope("2026-07-28");
|
||||
other_agent.agent_slug = "other-assistant";
|
||||
assert!(matches!(
|
||||
list_prompts(
|
||||
&items,
|
||||
&other_agent,
|
||||
PromptsListCommand {
|
||||
cursor: Some(cursor),
|
||||
limit: Some(2),
|
||||
},
|
||||
),
|
||||
PromptsOutcome::InvalidParams(_)
|
||||
));
|
||||
// Malformed token: invalid params, never a first page.
|
||||
assert!(matches!(
|
||||
list_prompts(
|
||||
&items,
|
||||
&scope,
|
||||
PromptsListCommand {
|
||||
cursor: Some("not-a-cursor".to_owned()),
|
||||
limit: None,
|
||||
},
|
||||
),
|
||||
PromptsOutcome::InvalidParams(_)
|
||||
));
|
||||
}
|
||||
|
||||
/// AT-3.14-02: typed arguments render deterministically, defaults included.
|
||||
#[test]
|
||||
fn get_renders_typed_arguments_with_defaults() {
|
||||
let PromptsOutcome::Got {
|
||||
description,
|
||||
messages,
|
||||
} = get("greeting", json!({"name": "Ada"}))
|
||||
else {
|
||||
panic!("valid arguments must render");
|
||||
};
|
||||
assert_eq!(description.as_deref(), Some("Description"));
|
||||
assert_eq!(messages.len(), 2);
|
||||
assert_eq!(messages[0]["role"], json!("system"));
|
||||
assert_eq!(
|
||||
messages[1]["content"],
|
||||
json!({"type": "text", "text": "Hello Ada"})
|
||||
);
|
||||
assert_eq!(
|
||||
get("greeting", json!({"name": "Ada"})).to_owned_messages(),
|
||||
messages
|
||||
);
|
||||
}
|
||||
|
||||
/// AT-3.14-02: every argument failure is a typed rejection with no rendered message.
|
||||
#[test]
|
||||
fn get_rejects_arguments_before_rendering() {
|
||||
for (arguments, reason) in [
|
||||
(json!({}), "missing_argument"),
|
||||
(json!({"name": "Ada", "extra": "x"}), "unknown_argument"),
|
||||
(json!({"name": 5}), "argument_invalid"),
|
||||
(json!({"name": "Ada", "tone": "loud"}), "argument_invalid"),
|
||||
(
|
||||
json!({"name": "x".repeat(MAX_TEXT_BYTES + 1)}),
|
||||
"argument_too_large",
|
||||
),
|
||||
] {
|
||||
match get("greeting", arguments) {
|
||||
PromptsOutcome::ArgumentsRejected {
|
||||
reason: observed,
|
||||
argument,
|
||||
} => {
|
||||
assert_eq!(observed, reason);
|
||||
assert!(argument.is_some(), "the bound argument name is named");
|
||||
}
|
||||
PromptsOutcome::Got { messages, .. } => {
|
||||
panic!("{reason}: no partial rendering is allowed, got {messages:?}");
|
||||
}
|
||||
_ => panic!("{reason}: expected a typed argument rejection"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// AT-3.14-01: an unknown name is indistinguishable from Draft/foreign/unbound.
|
||||
#[test]
|
||||
fn get_unknown_name_is_not_available() {
|
||||
assert!(matches!(
|
||||
get("not-bound", json!({"name": "Ada"})),
|
||||
PromptsOutcome::NotAvailable
|
||||
));
|
||||
}
|
||||
|
||||
impl PromptsOutcome {
|
||||
fn to_owned_messages(&self) -> Vec<Value> {
|
||||
match self {
|
||||
Self::Got { messages, .. } => messages.clone(),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,521 @@
|
||||
//! Static typed registration of the MCP capabilities this server actually implements.
|
||||
//!
|
||||
//! Story 3.1, decision D-3: one static snapshot describes every registered method and its owning
|
||||
//! capability, and a single predicate decides both whether a capability is advertised and whether a
|
||||
//! method may be dispatched. Duplicate or conflicting registrations are rejected with a typed error
|
||||
//! instead of being silently merged. Advertisement is not per-call authorization: the mandatory
|
||||
//! name/header/lifecycle validation and the per-call credential guard stay in the adapter.
|
||||
//!
|
||||
//! The names here are an internal decision of the team within the approved scope, not a public API:
|
||||
//! `protocol` stays a private module (`lib.rs`) and nothing in this file is exported.
|
||||
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
use crate::jsonrpc::{LEGACY_PROTOCOL_VERSION, MODERN_PROTOCOL_VERSION};
|
||||
|
||||
/// The owning capability of one or more wire methods.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum CapabilityId {
|
||||
Tools,
|
||||
Resources,
|
||||
/// Standard Prompt discovery/rendering of exact bound Published Prompt Versions (Story 3.14).
|
||||
Prompts,
|
||||
/// Bounded argument completion for bound Published Prompts and Resource templates (Story 3.17).
|
||||
Completions,
|
||||
Ping,
|
||||
Discovery,
|
||||
LegacyLifecycle,
|
||||
/// Inert descriptor used only by this module's tests; never registered in production.
|
||||
#[cfg(test)]
|
||||
InertTest,
|
||||
}
|
||||
|
||||
/// The protocol kind of a registered method or capability.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[allow(dead_code)] // the registration vocabulary; only kinds actually registered are constructed here
|
||||
pub(crate) enum Kind {
|
||||
Method,
|
||||
Capability,
|
||||
Notification,
|
||||
Extension,
|
||||
}
|
||||
|
||||
/// The side that declares or serves a capability.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[allow(dead_code)] // the registration vocabulary; only the server roster is registered here
|
||||
pub(crate) enum Roster {
|
||||
Server,
|
||||
Client,
|
||||
}
|
||||
|
||||
/// Transport-required header names declared by one method.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct HeaderSet(pub(crate) &'static [&'static str]);
|
||||
|
||||
/// Named sub-features declared by a capability descriptor.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct FeatureSet(pub(crate) &'static [&'static str]);
|
||||
|
||||
/// Identifier of a declared capability extension.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct ExtensionId(pub(crate) &'static str);
|
||||
|
||||
/// Reference to the deprecation tag of a surface that is still present.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct DeprecatedRef(pub(crate) &'static str);
|
||||
|
||||
/// The shared handler an owning capability routes a declared method to.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum MethodHandler {
|
||||
ToolList,
|
||||
ToolCall,
|
||||
ResourceList,
|
||||
ResourceRead,
|
||||
/// `resources/templates/list`: this server declares no dynamic Resource template, so the handler
|
||||
/// answers the fixed empty business result for the requested revision.
|
||||
ResourceTemplateList,
|
||||
/// `prompts/list`: bound Published Prompt Versions of the active Agent snapshot (Story 3.14).
|
||||
PromptList,
|
||||
/// `prompts/get`: deterministic typed rendering of one exact bound Prompt version.
|
||||
PromptGet,
|
||||
/// `completion/complete`: bounded suggestions from the typed schema of one exact bound Prompt
|
||||
/// argument or one exact bound Resource template parameter (Story 3.17).
|
||||
Completion,
|
||||
Ping,
|
||||
Discover,
|
||||
Lifecycle,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
#[allow(dead_code)] // descriptor fields the dispatch-side query reads once the router is driven by it
|
||||
pub(crate) struct MethodDescriptor {
|
||||
pub(crate) name: &'static str,
|
||||
pub(crate) capability: CapabilityId,
|
||||
pub(crate) kind: Kind,
|
||||
pub(crate) required_headers: HeaderSet,
|
||||
pub(crate) handler: MethodHandler,
|
||||
}
|
||||
|
||||
/// The advertisement fragment of a capability: the top-level capabilities key and the boolean values
|
||||
/// of its declared sub-features. `None` means the capability is not advertised at all.
|
||||
pub(crate) type AdvertisementFragment = (&'static str, &'static [(&'static str, bool)]);
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
#[allow(dead_code)] // descriptor fields the dispatch-side query reads once the router is driven by it
|
||||
pub(crate) struct CapabilityIdDescriptor {
|
||||
pub(crate) id: CapabilityId,
|
||||
pub(crate) roster: Roster,
|
||||
pub(crate) kind: Kind,
|
||||
pub(crate) extension: Option<ExtensionId>,
|
||||
pub(crate) deprecated: Option<DeprecatedRef>,
|
||||
pub(crate) sub_features: FeatureSet,
|
||||
pub(crate) advertised: Option<AdvertisementFragment>,
|
||||
pub(crate) revisions: &'static [&'static str],
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub(crate) enum RegistrationError {
|
||||
/// The same method name is registered twice with the same owning capability and kind.
|
||||
DuplicateMethod { name: &'static str },
|
||||
/// The same method name is registered with a different capability or kind.
|
||||
ConflictingMethod { name: &'static str },
|
||||
/// The same owning capability is described twice.
|
||||
DuplicateCapability { capability: CapabilityId },
|
||||
/// Two capabilities claim the same top-level advertisement key: the merged JSON object would
|
||||
/// silently lose one of the two fragments.
|
||||
ConflictingAdvertisement { key: &'static str },
|
||||
/// A server declaration/extension of an advertisable kind carries no advertisement fragment: its
|
||||
/// methods would be dispatchable while the capability is advertised nowhere (F6).
|
||||
MissingAdvertisement { capability: CapabilityId },
|
||||
/// A registration that is not advertisable by contract carries an advertisement fragment: the
|
||||
/// dispatch-only `method`/`notification` registrations (`ping`, `server/discover`, the legacy
|
||||
/// lifecycle) must never claim to be advertised.
|
||||
MisdeclaredAdvertisement { capability: CapabilityId },
|
||||
}
|
||||
|
||||
/// The registration-backed dispatch decision for one wire method in one requested revision (R5/D-3).
|
||||
///
|
||||
/// The router holds no method list of its own: it asks the registration what to do with a method and
|
||||
/// whether the owning capability exists in the requested revision at all. A method that is not
|
||||
/// registered never reaches a handler, so it can neither enter the owning service nor produce an
|
||||
/// outbound call. The registered `kind` is part of the decision: the two legacy lifecycle wire names
|
||||
/// share one handler but are *not* interchangeable, so the adapter needs the registered kind to serve
|
||||
/// `initialize` as a request and `notifications/initialized` as a notification (G2).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum DispatchDecision {
|
||||
/// Registered and available in the requested revision; routes to this handler with this kind.
|
||||
Allowed { handler: MethodHandler, kind: Kind },
|
||||
/// Registered, but its owning capability does not exist in the requested revision.
|
||||
WrongEra { handler: MethodHandler, kind: Kind },
|
||||
/// No registration owns this method name.
|
||||
Unregistered,
|
||||
}
|
||||
|
||||
/// The one static registration snapshot.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct CapabilityRegistry {
|
||||
capabilities: Vec<CapabilityIdDescriptor>,
|
||||
/// Registered methods. The dispatch-side query over this table is a separate bounded change; the
|
||||
/// table is retained (and validated) here so registration cannot drift from advertisement.
|
||||
#[allow(dead_code)]
|
||||
methods: Vec<MethodDescriptor>,
|
||||
}
|
||||
|
||||
impl CapabilityRegistry {
|
||||
/// Build the registry from descriptor tables. Duplicate or conflicting entries are rejected with
|
||||
/// [`RegistrationError`] — a registration error is never a panic and never a silently merged list.
|
||||
pub(crate) fn new(
|
||||
capabilities: &[CapabilityIdDescriptor],
|
||||
methods: &[MethodDescriptor],
|
||||
) -> Result<Self, RegistrationError> {
|
||||
let mut seen_capabilities: Vec<CapabilityId> = Vec::new();
|
||||
for descriptor in capabilities {
|
||||
if seen_capabilities.contains(&descriptor.id) {
|
||||
return Err(RegistrationError::DuplicateCapability {
|
||||
capability: descriptor.id,
|
||||
});
|
||||
}
|
||||
seen_capabilities.push(descriptor.id);
|
||||
}
|
||||
|
||||
let mut seen_methods: Vec<(&'static str, CapabilityId, Kind)> = Vec::new();
|
||||
for descriptor in methods {
|
||||
if let Some((_, capability, kind)) = seen_methods
|
||||
.iter()
|
||||
.find(|(name, _, _)| *name == descriptor.name)
|
||||
{
|
||||
let same_owner = *capability == descriptor.capability && *kind == descriptor.kind;
|
||||
let error = if same_owner {
|
||||
RegistrationError::DuplicateMethod {
|
||||
name: descriptor.name,
|
||||
}
|
||||
} else {
|
||||
RegistrationError::ConflictingMethod {
|
||||
name: descriptor.name,
|
||||
}
|
||||
};
|
||||
return Err(error);
|
||||
}
|
||||
seen_methods.push((descriptor.name, descriptor.capability, descriptor.kind));
|
||||
}
|
||||
|
||||
// Two capabilities must never claim the same top-level advertisement key: the merged
|
||||
// advertisement object is a map, so a silent overwrite would drop one fragment (R7).
|
||||
let mut seen_advertisement_keys: Vec<&'static str> = Vec::new();
|
||||
for descriptor in capabilities {
|
||||
if let Some((key, _sub_features)) = descriptor.advertised {
|
||||
if seen_advertisement_keys.contains(&key) {
|
||||
return Err(RegistrationError::ConflictingAdvertisement { key });
|
||||
}
|
||||
seen_advertisement_keys.push(key);
|
||||
}
|
||||
}
|
||||
|
||||
// F6: the two projections of a registration must not drift apart. A server declaration of an
|
||||
// advertisable kind without a fragment would keep dispatching methods while advertising
|
||||
// nothing, and a dispatch-only method/notification registration must not claim a fragment.
|
||||
for descriptor in capabilities {
|
||||
let advertisable_kind = matches!(descriptor.kind, Kind::Capability | Kind::Extension);
|
||||
if advertisable_kind && descriptor.advertised.is_none() {
|
||||
return Err(RegistrationError::MissingAdvertisement {
|
||||
capability: descriptor.id,
|
||||
});
|
||||
}
|
||||
if !advertisable_kind && descriptor.advertised.is_some() {
|
||||
return Err(RegistrationError::MisdeclaredAdvertisement {
|
||||
capability: descriptor.id,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
capabilities: capabilities.to_vec(),
|
||||
methods: methods.to_vec(),
|
||||
})
|
||||
}
|
||||
|
||||
fn descriptor(&self, capability: CapabilityId) -> Option<&CapabilityIdDescriptor> {
|
||||
self.capabilities
|
||||
.iter()
|
||||
.find(|descriptor| descriptor.id == capability)
|
||||
}
|
||||
|
||||
/// Availability of an owning capability in one revision: the registered revision window.
|
||||
///
|
||||
/// This is the shared eligibility half of both projections: a capability that is not registered
|
||||
/// for the requested revision can neither be advertised nor have its methods dispatched.
|
||||
fn registered_for(&self, capability: CapabilityId, revision: &str) -> bool {
|
||||
self.descriptor(capability)
|
||||
.is_some_and(|descriptor| descriptor.revisions.contains(&revision))
|
||||
}
|
||||
|
||||
/// The single advertisement predicate: a capability is advertised in `revision` when it is a
|
||||
/// registered server declaration/extension, available in that revision, with a declared fragment.
|
||||
pub(crate) fn advertise_for(&self, capability: CapabilityId, revision: &str) -> bool {
|
||||
let Some(descriptor) = self.descriptor(capability) else {
|
||||
return false;
|
||||
};
|
||||
descriptor.roster == Roster::Server
|
||||
&& matches!(descriptor.kind, Kind::Capability | Kind::Extension)
|
||||
&& descriptor.advertised.is_some()
|
||||
&& self.registered_for(capability, revision)
|
||||
}
|
||||
|
||||
/// Dispatch eligibility of a capability-owned method (D-3/F6).
|
||||
///
|
||||
/// For every capability that is advertised by design this is [`Self::advertise_for`] itself, so a
|
||||
/// declaration that stops being advertised — a fragment-less advertisable kind, or a client-roster
|
||||
/// declaration — can never keep dispatching its methods: the constructor rejects such a
|
||||
/// registration outright ([`RegistrationError::MissingAdvertisement`]). The only registrations
|
||||
/// that are dispatchable without being advertised are the explicitly non-advertised method-kind
|
||||
/// ones (`ping`, `server/discover`, the legacy lifecycle), which carry no fragment by contract.
|
||||
pub(crate) fn dispatchable_for(&self, capability: CapabilityId, revision: &str) -> bool {
|
||||
if !self.registered_for(capability, revision) {
|
||||
return false;
|
||||
}
|
||||
match self.descriptor(capability) {
|
||||
Some(descriptor) => match descriptor.kind {
|
||||
Kind::Capability | Kind::Extension => self.advertise_for(capability, revision),
|
||||
Kind::Method | Kind::Notification => descriptor.advertised.is_none(),
|
||||
},
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The registration-backed dispatch decision of one wire method in one requested revision (R5).
|
||||
///
|
||||
/// The method-to-handler mapping lives here, not in the router: an unknown method has no handler
|
||||
/// and a method whose owning capability is not eligible in the requested revision is a wrong-era
|
||||
/// request, so neither can reach a service or make an outbound call.
|
||||
pub(crate) fn dispatch_decision(&self, method: &str, revision: &str) -> DispatchDecision {
|
||||
let Some(descriptor) = self
|
||||
.methods
|
||||
.iter()
|
||||
.find(|descriptor| descriptor.name == method)
|
||||
else {
|
||||
return DispatchDecision::Unregistered;
|
||||
};
|
||||
if self.dispatchable_for(descriptor.capability, revision) {
|
||||
DispatchDecision::Allowed {
|
||||
handler: descriptor.handler,
|
||||
kind: descriptor.kind,
|
||||
}
|
||||
} else {
|
||||
DispatchDecision::WrongEra {
|
||||
handler: descriptor.handler,
|
||||
kind: descriptor.kind,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The single advertisement JSON source, indexed by the requested revision (R6): only the
|
||||
/// fragments of the capabilities available in *that* revision are merged, so a single-era
|
||||
/// declaration never leaks into the other era and an empty revision window is eligible nowhere.
|
||||
pub(crate) fn advertised_capabilities(&self, revision: &str) -> Value {
|
||||
let mut merged = Map::new();
|
||||
for descriptor in &self.capabilities {
|
||||
if !self.advertise_for(descriptor.id, revision) {
|
||||
continue;
|
||||
}
|
||||
if let Some((key, sub_features)) = descriptor.advertised {
|
||||
let values = sub_features
|
||||
.iter()
|
||||
.map(|(name, enabled)| ((*name).to_owned(), Value::Bool(*enabled)))
|
||||
.collect::<Map<String, Value>>();
|
||||
merged.insert(key.to_owned(), Value::Object(values));
|
||||
}
|
||||
}
|
||||
Value::Object(merged)
|
||||
}
|
||||
|
||||
/// The registered methods with their owning capability: used by the tests that prove an inert
|
||||
/// descriptor changes both projections.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn methods(&self) -> &[MethodDescriptor] {
|
||||
&self.methods
|
||||
}
|
||||
}
|
||||
|
||||
const MODERN_AND_LEGACY: &[&str] = &[MODERN_PROTOCOL_VERSION, LEGACY_PROTOCOL_VERSION];
|
||||
const MODERN_ONLY: &[&str] = &[MODERN_PROTOCOL_VERSION];
|
||||
const LEGACY_ONLY: &[&str] = &[LEGACY_PROTOCOL_VERSION];
|
||||
|
||||
pub(crate) const CAPABILITY_DESCRIPTORS: &[CapabilityIdDescriptor] = &[
|
||||
CapabilityIdDescriptor {
|
||||
id: CapabilityId::Tools,
|
||||
roster: Roster::Server,
|
||||
kind: Kind::Capability,
|
||||
extension: None,
|
||||
deprecated: None,
|
||||
sub_features: FeatureSet(&["listChanged"]),
|
||||
advertised: Some(("tools", &[("listChanged", false)])),
|
||||
revisions: MODERN_AND_LEGACY,
|
||||
},
|
||||
CapabilityIdDescriptor {
|
||||
id: CapabilityId::Resources,
|
||||
roster: Roster::Server,
|
||||
kind: Kind::Capability,
|
||||
extension: None,
|
||||
deprecated: None,
|
||||
sub_features: FeatureSet(&["subscribe", "listChanged"]),
|
||||
advertised: Some(("resources", &[("subscribe", false), ("listChanged", false)])),
|
||||
revisions: MODERN_AND_LEGACY,
|
||||
},
|
||||
CapabilityIdDescriptor {
|
||||
id: CapabilityId::Prompts,
|
||||
roster: Roster::Server,
|
||||
kind: Kind::Capability,
|
||||
extension: None,
|
||||
deprecated: None,
|
||||
sub_features: FeatureSet(&["listChanged"]),
|
||||
advertised: Some(("prompts", &[("listChanged", false)])),
|
||||
revisions: MODERN_AND_LEGACY,
|
||||
},
|
||||
CapabilityIdDescriptor {
|
||||
id: CapabilityId::Completions,
|
||||
roster: Roster::Server,
|
||||
kind: Kind::Capability,
|
||||
extension: None,
|
||||
deprecated: None,
|
||||
// The pinned schema declares `completions` as an object with no sub-features.
|
||||
sub_features: FeatureSet(&[]),
|
||||
advertised: Some(("completions", &[])),
|
||||
revisions: MODERN_AND_LEGACY,
|
||||
},
|
||||
CapabilityIdDescriptor {
|
||||
id: CapabilityId::Ping,
|
||||
roster: Roster::Server,
|
||||
kind: Kind::Method,
|
||||
extension: None,
|
||||
deprecated: None,
|
||||
sub_features: FeatureSet(&[]),
|
||||
advertised: None,
|
||||
revisions: MODERN_AND_LEGACY,
|
||||
},
|
||||
CapabilityIdDescriptor {
|
||||
id: CapabilityId::Discovery,
|
||||
roster: Roster::Server,
|
||||
kind: Kind::Method,
|
||||
extension: None,
|
||||
deprecated: None,
|
||||
sub_features: FeatureSet(&[]),
|
||||
advertised: None,
|
||||
revisions: MODERN_ONLY,
|
||||
},
|
||||
CapabilityIdDescriptor {
|
||||
id: CapabilityId::LegacyLifecycle,
|
||||
roster: Roster::Server,
|
||||
kind: Kind::Method,
|
||||
extension: None,
|
||||
deprecated: None,
|
||||
sub_features: FeatureSet(&[]),
|
||||
advertised: None,
|
||||
revisions: LEGACY_ONLY,
|
||||
},
|
||||
];
|
||||
|
||||
/// Transport-required header names of the modern request rules: the declared method and name pair.
|
||||
const HEADERS_METHOD_AND_NAME: HeaderSet = HeaderSet(&["Mcp-Method", "Mcp-Name"]);
|
||||
/// Methods that declare only the method header: `resources/list` carries no per-request name.
|
||||
const HEADERS_METHOD_ONLY: HeaderSet = HeaderSet(&["Mcp-Method"]);
|
||||
/// Lifecycle and ping requests declare no additional required header beyond the envelope.
|
||||
const HEADERS_NONE: HeaderSet = HeaderSet(&[]);
|
||||
|
||||
pub(crate) const METHOD_DESCRIPTORS: &[MethodDescriptor] = &[
|
||||
MethodDescriptor {
|
||||
name: "tools/list",
|
||||
capability: CapabilityId::Tools,
|
||||
kind: Kind::Method,
|
||||
required_headers: HEADERS_METHOD_AND_NAME,
|
||||
handler: MethodHandler::ToolList,
|
||||
},
|
||||
MethodDescriptor {
|
||||
name: "tools/call",
|
||||
capability: CapabilityId::Tools,
|
||||
kind: Kind::Method,
|
||||
required_headers: HEADERS_METHOD_AND_NAME,
|
||||
handler: MethodHandler::ToolCall,
|
||||
},
|
||||
MethodDescriptor {
|
||||
name: "resources/list",
|
||||
capability: CapabilityId::Resources,
|
||||
kind: Kind::Method,
|
||||
required_headers: HEADERS_METHOD_ONLY,
|
||||
handler: MethodHandler::ResourceList,
|
||||
},
|
||||
MethodDescriptor {
|
||||
name: "resources/read",
|
||||
capability: CapabilityId::Resources,
|
||||
kind: Kind::Method,
|
||||
required_headers: HEADERS_METHOD_AND_NAME,
|
||||
handler: MethodHandler::ResourceRead,
|
||||
},
|
||||
MethodDescriptor {
|
||||
// Story 3.8: the standard client companion of `resources/list`. This server has no dynamic
|
||||
// template, so the answer is a fixed empty list; the request declares no name, so only the
|
||||
// method header is required.
|
||||
name: "resources/templates/list",
|
||||
capability: CapabilityId::Resources,
|
||||
kind: Kind::Method,
|
||||
required_headers: HEADERS_METHOD_ONLY,
|
||||
handler: MethodHandler::ResourceTemplateList,
|
||||
},
|
||||
MethodDescriptor {
|
||||
name: "prompts/list",
|
||||
capability: CapabilityId::Prompts,
|
||||
kind: Kind::Method,
|
||||
required_headers: HEADERS_METHOD_ONLY,
|
||||
handler: MethodHandler::PromptList,
|
||||
},
|
||||
MethodDescriptor {
|
||||
// `prompts/get` declares its Prompt name, so the modern era requires `Mcp-Name` too.
|
||||
name: "prompts/get",
|
||||
capability: CapabilityId::Prompts,
|
||||
kind: Kind::Method,
|
||||
required_headers: HEADERS_METHOD_AND_NAME,
|
||||
handler: MethodHandler::PromptGet,
|
||||
},
|
||||
MethodDescriptor {
|
||||
// Story 3.17: the standard client companion of the Prompts/Resources declarations. Its `ref`
|
||||
// is a union of a Prompt name and a Resource URI template, so no single `Mcp-Name` value can
|
||||
// describe it; the pinned era matrix requires `Mcp-Name` only for `tools/call`,
|
||||
// `resources/read` and `prompts/get`.
|
||||
name: "completion/complete",
|
||||
capability: CapabilityId::Completions,
|
||||
kind: Kind::Method,
|
||||
required_headers: HEADERS_METHOD_ONLY,
|
||||
handler: MethodHandler::Completion,
|
||||
},
|
||||
MethodDescriptor {
|
||||
name: "ping",
|
||||
capability: CapabilityId::Ping,
|
||||
kind: Kind::Method,
|
||||
required_headers: HEADERS_NONE,
|
||||
handler: MethodHandler::Ping,
|
||||
},
|
||||
MethodDescriptor {
|
||||
name: "server/discover",
|
||||
capability: CapabilityId::Discovery,
|
||||
kind: Kind::Method,
|
||||
required_headers: HEADERS_NONE,
|
||||
handler: MethodHandler::Discover,
|
||||
},
|
||||
MethodDescriptor {
|
||||
name: "initialize",
|
||||
capability: CapabilityId::LegacyLifecycle,
|
||||
kind: Kind::Method,
|
||||
required_headers: HEADERS_NONE,
|
||||
handler: MethodHandler::Lifecycle,
|
||||
},
|
||||
MethodDescriptor {
|
||||
name: "notifications/initialized",
|
||||
capability: CapabilityId::LegacyLifecycle,
|
||||
kind: Kind::Notification,
|
||||
required_headers: HEADERS_NONE,
|
||||
handler: MethodHandler::Lifecycle,
|
||||
},
|
||||
];
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "registry_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,743 @@
|
||||
//! In-crate tests of `protocol::registry` (module path `protocol::registry::tests`).
|
||||
//!
|
||||
//! Kept as a `#[path]` module to stay inside the repository code-health caps (an inline test
|
||||
//! module may not exceed 500 lines and `registry.rs` may not exceed 1000 lines). The module path,
|
||||
//! and therefore the sanctioned selector
|
||||
//! `cargo test -p crank-community-mcp --lib protocol::registry::`, is identical to the inline
|
||||
//! module it replaces, and every test name is unchanged.
|
||||
|
||||
use super::*;
|
||||
use crate::protocol::{advertised_server_capabilities, dispatch_decision};
|
||||
use serde_json::json;
|
||||
|
||||
fn production_registry() -> CapabilityRegistry {
|
||||
CapabilityRegistry::new(CAPABILITY_DESCRIPTORS, METHOD_DESCRIPTORS)
|
||||
.expect("the static capability table is valid")
|
||||
}
|
||||
|
||||
fn inert_descriptor() -> CapabilityIdDescriptor {
|
||||
CapabilityIdDescriptor {
|
||||
id: CapabilityId::InertTest,
|
||||
roster: Roster::Server,
|
||||
kind: Kind::Capability,
|
||||
extension: None,
|
||||
deprecated: None,
|
||||
sub_features: FeatureSet(&["enabled"]),
|
||||
advertised: Some(("inert_test_capability", &[("enabled", true)])),
|
||||
revisions: MODERN_AND_LEGACY,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn static_registration_is_unique_and_advertises_only_the_registered_capability() {
|
||||
let registry = production_registry();
|
||||
for revision in [MODERN_PROTOCOL_VERSION, LEGACY_PROTOCOL_VERSION] {
|
||||
assert_eq!(
|
||||
registry.advertised_capabilities(revision),
|
||||
json!({
|
||||
"completions": {},
|
||||
"prompts": {"listChanged": false},
|
||||
"resources": {"listChanged": false, "subscribe": false},
|
||||
"tools": {"listChanged": false}
|
||||
}),
|
||||
"the registered advertisement must be the same reviewed object in {revision}"
|
||||
);
|
||||
assert_eq!(
|
||||
advertised_server_capabilities(revision),
|
||||
json!({
|
||||
"completions": {},
|
||||
"prompts": {"listChanged": false},
|
||||
"resources": {"listChanged": false, "subscribe": false},
|
||||
"tools": {"listChanged": false}
|
||||
}),
|
||||
"the production advertisement entry point must serve {revision}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn advertisement_and_dispatch_share_one_eligibility_predicate() {
|
||||
// F6: for every capability that is *advertised by design* advertisement and dispatch are the
|
||||
// same predicate, and dispatch eligibility follows the registered revision window. The only
|
||||
// registrations that are dispatchable without being advertised are the explicit method-kind
|
||||
// ones (`ping`, `server/discover`, the legacy lifecycle).
|
||||
let registry = production_registry();
|
||||
for descriptor in ®istry.capabilities {
|
||||
let advertised_by_design = matches!(descriptor.kind, Kind::Capability | Kind::Extension);
|
||||
for revision in [MODERN_PROTOCOL_VERSION, LEGACY_PROTOCOL_VERSION] {
|
||||
let eligible = registry.dispatchable_for(descriptor.id, revision);
|
||||
assert_eq!(
|
||||
eligible,
|
||||
descriptor.revisions.contains(&revision),
|
||||
"dispatch eligibility must follow the revision window of {:?}",
|
||||
descriptor.id
|
||||
);
|
||||
if advertised_by_design {
|
||||
assert_eq!(
|
||||
registry.advertise_for(descriptor.id, revision),
|
||||
eligible,
|
||||
"advertisement and dispatch drifted for {:?} in {revision}",
|
||||
descriptor.id
|
||||
);
|
||||
} else {
|
||||
assert!(
|
||||
!registry.advertise_for(descriptor.id, revision),
|
||||
"a dispatch-only registration {:?} must never be advertised in {revision}",
|
||||
descriptor.id
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
assert!(registry.advertise_for(CapabilityId::Tools, MODERN_PROTOCOL_VERSION));
|
||||
assert!(registry.dispatchable_for(CapabilityId::Tools, MODERN_PROTOCOL_VERSION));
|
||||
assert!(registry.advertise_for(CapabilityId::Tools, LEGACY_PROTOCOL_VERSION));
|
||||
// `ping` is dispatched in both eras but advertised nowhere: it declares no fragment by
|
||||
// contract, and the advertisement object carries no `ping` key.
|
||||
for revision in [MODERN_PROTOCOL_VERSION, LEGACY_PROTOCOL_VERSION] {
|
||||
assert!(registry.dispatchable_for(CapabilityId::Ping, revision));
|
||||
assert!(!registry.advertise_for(CapabilityId::Ping, revision));
|
||||
assert!(
|
||||
registry
|
||||
.advertised_capabilities(revision)
|
||||
.as_object()
|
||||
.is_some_and(|object| !object.contains_key("ping")),
|
||||
"the advertisement of {revision} must not grow a `ping` key"
|
||||
);
|
||||
}
|
||||
assert!(registry.dispatchable_for(CapabilityId::Discovery, MODERN_PROTOCOL_VERSION));
|
||||
assert!(!registry.dispatchable_for(CapabilityId::Discovery, LEGACY_PROTOCOL_VERSION));
|
||||
assert!(registry.dispatchable_for(CapabilityId::LegacyLifecycle, LEGACY_PROTOCOL_VERSION));
|
||||
assert!(!registry.dispatchable_for(CapabilityId::LegacyLifecycle, MODERN_PROTOCOL_VERSION));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fragment_less_advertisable_capability_is_rejected_at_registration() {
|
||||
// F6: without this invariant a capability-owned method could stay `Allowed` while its
|
||||
// capability is advertised nowhere, which is exactly the drift the reviewer measured.
|
||||
let mut capabilities = CAPABILITY_DESCRIPTORS.to_vec();
|
||||
capabilities.push(CapabilityIdDescriptor {
|
||||
id: CapabilityId::InertTest,
|
||||
roster: Roster::Server,
|
||||
kind: Kind::Capability,
|
||||
extension: None,
|
||||
deprecated: None,
|
||||
sub_features: FeatureSet(&[]),
|
||||
advertised: None,
|
||||
revisions: MODERN_AND_LEGACY,
|
||||
});
|
||||
assert_eq!(
|
||||
CapabilityRegistry::new(&capabilities, METHOD_DESCRIPTORS).err(),
|
||||
Some(RegistrationError::MissingAdvertisement {
|
||||
capability: CapabilityId::InertTest
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dispatch_only_registration_cannot_claim_an_advertisement_fragment() {
|
||||
let mut capabilities = CAPABILITY_DESCRIPTORS.to_vec();
|
||||
capabilities.push(CapabilityIdDescriptor {
|
||||
id: CapabilityId::InertTest,
|
||||
roster: Roster::Server,
|
||||
kind: Kind::Method,
|
||||
extension: None,
|
||||
deprecated: None,
|
||||
sub_features: FeatureSet(&[]),
|
||||
advertised: Some(("inert_method_advertisement", &[("enabled", true)])),
|
||||
revisions: MODERN_AND_LEGACY,
|
||||
});
|
||||
assert_eq!(
|
||||
CapabilityRegistry::new(&capabilities, METHOD_DESCRIPTORS).err(),
|
||||
Some(RegistrationError::MisdeclaredAdvertisement {
|
||||
capability: CapabilityId::InertTest
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_client_roster_declaration_never_dispatches_its_methods() {
|
||||
const INERT_METHOD: MethodDescriptor = MethodDescriptor {
|
||||
name: "inert/client-only",
|
||||
capability: CapabilityId::InertTest,
|
||||
kind: Kind::Method,
|
||||
required_headers: HEADERS_NONE,
|
||||
handler: MethodHandler::Ping,
|
||||
};
|
||||
let mut capabilities = CAPABILITY_DESCRIPTORS.to_vec();
|
||||
capabilities.push(CapabilityIdDescriptor {
|
||||
id: CapabilityId::InertTest,
|
||||
roster: Roster::Client,
|
||||
kind: Kind::Capability,
|
||||
extension: None,
|
||||
deprecated: None,
|
||||
sub_features: FeatureSet(&["enabled"]),
|
||||
advertised: Some(("inert_client_capability", &[("enabled", true)])),
|
||||
revisions: MODERN_AND_LEGACY,
|
||||
});
|
||||
let mut methods = METHOD_DESCRIPTORS.to_vec();
|
||||
methods.push(INERT_METHOD);
|
||||
let registry =
|
||||
CapabilityRegistry::new(&capabilities, &methods).expect("a client declaration registers");
|
||||
|
||||
assert!(!registry.advertise_for(CapabilityId::InertTest, MODERN_PROTOCOL_VERSION));
|
||||
assert!(!registry.dispatchable_for(CapabilityId::InertTest, MODERN_PROTOCOL_VERSION));
|
||||
assert_eq!(
|
||||
registry.dispatch_decision(INERT_METHOD.name, MODERN_PROTOCOL_VERSION),
|
||||
DispatchDecision::WrongEra {
|
||||
handler: MethodHandler::Ping,
|
||||
kind: Kind::Method,
|
||||
},
|
||||
"a client-side declaration must never be Allowed for a server dispatch"
|
||||
);
|
||||
assert!(
|
||||
registry
|
||||
.advertised_capabilities(MODERN_PROTOCOL_VERSION)
|
||||
.as_object()
|
||||
.is_some_and(|object| !object.contains_key("inert_client_capability")),
|
||||
"a client declaration is never advertised by this server"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_method_registration_is_rejected() {
|
||||
let duplicate = [
|
||||
METHOD_DESCRIPTORS[0],
|
||||
MethodDescriptor {
|
||||
name: METHOD_DESCRIPTORS[0].name,
|
||||
capability: METHOD_DESCRIPTORS[0].capability,
|
||||
kind: METHOD_DESCRIPTORS[0].kind,
|
||||
required_headers: HEADERS_NONE,
|
||||
handler: MethodHandler::Discover,
|
||||
},
|
||||
];
|
||||
assert_eq!(
|
||||
CapabilityRegistry::new(CAPABILITY_DESCRIPTORS, &duplicate).unwrap_err(),
|
||||
RegistrationError::DuplicateMethod { name: "tools/list" }
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conflicting_method_registration_is_rejected() {
|
||||
let conflicting = [
|
||||
METHOD_DESCRIPTORS[0],
|
||||
MethodDescriptor {
|
||||
name: METHOD_DESCRIPTORS[0].name,
|
||||
capability: CapabilityId::Ping,
|
||||
kind: METHOD_DESCRIPTORS[0].kind,
|
||||
required_headers: HEADERS_NONE,
|
||||
handler: MethodHandler::Ping,
|
||||
},
|
||||
];
|
||||
assert_eq!(
|
||||
CapabilityRegistry::new(CAPABILITY_DESCRIPTORS, &conflicting).unwrap_err(),
|
||||
RegistrationError::ConflictingMethod { name: "tools/list" }
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_capability_registration_is_rejected() {
|
||||
let mut duplicated = CAPABILITY_DESCRIPTORS.to_vec();
|
||||
duplicated.push(CAPABILITY_DESCRIPTORS[0]);
|
||||
assert_eq!(
|
||||
CapabilityRegistry::new(&duplicated, METHOD_DESCRIPTORS).unwrap_err(),
|
||||
RegistrationError::DuplicateCapability {
|
||||
capability: CapabilityId::Tools
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_inert_test_descriptor_changes_both_projections_and_is_never_registered_in_production() {
|
||||
let without = production_registry();
|
||||
let mut with_capabilities = CAPABILITY_DESCRIPTORS.to_vec();
|
||||
with_capabilities.push(inert_descriptor());
|
||||
let with = CapabilityRegistry::new(&with_capabilities, METHOD_DESCRIPTORS)
|
||||
.expect("the inert descriptor is a valid capability entry");
|
||||
|
||||
assert_eq!(
|
||||
without.advertised_capabilities(MODERN_PROTOCOL_VERSION),
|
||||
json!({
|
||||
"completions": {},
|
||||
"prompts": {"listChanged": false},
|
||||
"resources": {"listChanged": false, "subscribe": false},
|
||||
"tools": {"listChanged": false}
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
with.advertised_capabilities(MODERN_PROTOCOL_VERSION),
|
||||
json!({
|
||||
"inert_test_capability": {"enabled": true},
|
||||
"completions": {},
|
||||
"prompts": {"listChanged": false},
|
||||
"resources": {"listChanged": false, "subscribe": false},
|
||||
"tools": {"listChanged": false}
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
with.advertised_capabilities(LEGACY_PROTOCOL_VERSION),
|
||||
json!({
|
||||
"inert_test_capability": {"enabled": true},
|
||||
"completions": {},
|
||||
"prompts": {"listChanged": false},
|
||||
"resources": {"listChanged": false, "subscribe": false},
|
||||
"tools": {"listChanged": false}
|
||||
})
|
||||
);
|
||||
|
||||
// Both projections move together: the inert capability is advertisable *and* dispatchable.
|
||||
assert!(!without.advertise_for(CapabilityId::InertTest, MODERN_PROTOCOL_VERSION));
|
||||
assert!(with.advertise_for(CapabilityId::InertTest, MODERN_PROTOCOL_VERSION));
|
||||
assert_eq!(
|
||||
with.advertise_for(CapabilityId::InertTest, MODERN_PROTOCOL_VERSION),
|
||||
with.dispatchable_for(CapabilityId::InertTest, MODERN_PROTOCOL_VERSION)
|
||||
);
|
||||
|
||||
// The inert descriptor stays a test-only object: it is absent from the production table.
|
||||
assert!(
|
||||
CAPABILITY_DESCRIPTORS
|
||||
.iter()
|
||||
.all(|descriptor| descriptor.id != CapabilityId::InertTest)
|
||||
);
|
||||
let _ = with.methods();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_advertised_revision_window_is_exactly_the_two_approved_revisions() {
|
||||
let registry = production_registry();
|
||||
for descriptor in ®istry.capabilities {
|
||||
for revision in descriptor.revisions {
|
||||
assert!(
|
||||
[MODERN_PROTOCOL_VERSION, LEGACY_PROTOCOL_VERSION].contains(revision),
|
||||
"capability {:?} declares an unapproved revision {revision}",
|
||||
descriptor.id
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- Story 3.1 #8 remaining-foundation regressions (R6 era window, R7 advertisement conflict) --
|
||||
|
||||
/// A test-only descriptor that declares no revision at all, so every revision is ineligible.
|
||||
fn empty_window_descriptor() -> CapabilityIdDescriptor {
|
||||
CapabilityIdDescriptor {
|
||||
id: CapabilityId::InertTest,
|
||||
roster: Roster::Server,
|
||||
kind: Kind::Capability,
|
||||
extension: None,
|
||||
deprecated: None,
|
||||
sub_features: FeatureSet(&["enabled"]),
|
||||
advertised: Some(("inert_empty_window_capability", &[("enabled", true)])),
|
||||
revisions: &[],
|
||||
}
|
||||
}
|
||||
|
||||
/// A test-only descriptor that claims the top-level advertisement key already owned by `Tools`.
|
||||
fn conflicting_advertisement_descriptor() -> CapabilityIdDescriptor {
|
||||
CapabilityIdDescriptor {
|
||||
id: CapabilityId::InertTest,
|
||||
roster: Roster::Server,
|
||||
kind: Kind::Capability,
|
||||
extension: None,
|
||||
deprecated: None,
|
||||
sub_features: FeatureSet(&["listChanged"]),
|
||||
advertised: Some(("tools", &[("listChanged", true)])),
|
||||
revisions: MODERN_AND_LEGACY,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_revision_window_is_not_vacuously_advertisable() {
|
||||
// R6 (empty-window half): `revisions: &[]` must not make a capability eligible for every
|
||||
// revision through a vacuously true `all()`.
|
||||
let mut capabilities = CAPABILITY_DESCRIPTORS.to_vec();
|
||||
capabilities.push(empty_window_descriptor());
|
||||
let registry = match CapabilityRegistry::new(&capabilities, METHOD_DESCRIPTORS) {
|
||||
Ok(registry) => registry,
|
||||
// Rejecting a revision-less capability at registration is an equivalent, stronger
|
||||
// resolution of the same defect (a typed error, never a panic).
|
||||
Err(_rejected_at_registration) => return,
|
||||
};
|
||||
|
||||
assert!(
|
||||
!registry.advertise_for(CapabilityId::InertTest, MODERN_PROTOCOL_VERSION),
|
||||
"a capability with an empty revision window is eligible in no revision"
|
||||
);
|
||||
assert!(
|
||||
!registry.advertise_for(CapabilityId::InertTest, LEGACY_PROTOCOL_VERSION),
|
||||
"a capability with an empty revision window is eligible in no revision"
|
||||
);
|
||||
for revision in [MODERN_PROTOCOL_VERSION, LEGACY_PROTOCOL_VERSION] {
|
||||
let advertised = registry.advertised_capabilities(revision);
|
||||
assert!(
|
||||
advertised
|
||||
.as_object()
|
||||
.is_some_and(|object| !object.contains_key("inert_empty_window_capability")),
|
||||
"an empty revision window must not be advertised in {revision}: {advertised}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_conflicting_advertisement_key_is_rejected_not_silently_overwritten() {
|
||||
// R7: the constructor validates duplicate capability ids and duplicate method names but not
|
||||
// a conflicting top-level advertisement key, so `Value::Object::insert` silently overwrites.
|
||||
let mut capabilities = CAPABILITY_DESCRIPTORS.to_vec();
|
||||
capabilities.push(conflicting_advertisement_descriptor());
|
||||
let outcome = CapabilityRegistry::new(&capabilities, METHOD_DESCRIPTORS);
|
||||
assert_eq!(
|
||||
outcome.err(),
|
||||
Some(RegistrationError::ConflictingAdvertisement { key: "tools" }),
|
||||
"two capabilities claiming the same top-level advertisement key must be rejected with a \
|
||||
typed registration error instead of being silently overwritten"
|
||||
);
|
||||
}
|
||||
|
||||
// --- R6: the advertisement is indexed by the requested era, not by every declared revision ------
|
||||
|
||||
/// A test-only server capability available in the modern revision only.
|
||||
fn modern_only_descriptor() -> CapabilityIdDescriptor {
|
||||
CapabilityIdDescriptor {
|
||||
id: CapabilityId::InertTest,
|
||||
roster: Roster::Server,
|
||||
kind: Kind::Capability,
|
||||
extension: None,
|
||||
deprecated: None,
|
||||
sub_features: FeatureSet(&["enabled"]),
|
||||
advertised: Some(("inert_modern_capability", &[("enabled", true)])),
|
||||
revisions: MODERN_ONLY,
|
||||
}
|
||||
}
|
||||
|
||||
/// A test-only server capability available in the legacy revision only.
|
||||
fn legacy_only_descriptor() -> CapabilityIdDescriptor {
|
||||
CapabilityIdDescriptor {
|
||||
id: CapabilityId::InertTest,
|
||||
roster: Roster::Server,
|
||||
kind: Kind::Capability,
|
||||
extension: None,
|
||||
deprecated: None,
|
||||
sub_features: FeatureSet(&["enabled"]),
|
||||
advertised: Some(("inert_legacy_capability", &[("enabled", true)])),
|
||||
revisions: LEGACY_ONLY,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_single_era_descriptor_never_leaks_into_the_other_era_advertisement() {
|
||||
for (inert, this_era, other_era, key) in [
|
||||
(
|
||||
modern_only_descriptor(),
|
||||
MODERN_PROTOCOL_VERSION,
|
||||
LEGACY_PROTOCOL_VERSION,
|
||||
"inert_modern_capability",
|
||||
),
|
||||
(
|
||||
legacy_only_descriptor(),
|
||||
LEGACY_PROTOCOL_VERSION,
|
||||
MODERN_PROTOCOL_VERSION,
|
||||
"inert_legacy_capability",
|
||||
),
|
||||
] {
|
||||
let mut capabilities = CAPABILITY_DESCRIPTORS.to_vec();
|
||||
capabilities.push(inert);
|
||||
let registry = CapabilityRegistry::new(&capabilities, METHOD_DESCRIPTORS)
|
||||
.expect("a single-era inert capability is a valid registration");
|
||||
|
||||
let this_era_advertisement = registry.advertised_capabilities(this_era);
|
||||
assert!(
|
||||
this_era_advertisement
|
||||
.as_object()
|
||||
.is_some_and(|object| object.contains_key(key)),
|
||||
"{key} must be advertised in its own era {this_era}: {this_era_advertisement}"
|
||||
);
|
||||
let other_era_advertisement = registry.advertised_capabilities(other_era);
|
||||
assert!(
|
||||
other_era_advertisement
|
||||
.as_object()
|
||||
.is_some_and(|object| !object.contains_key(key)),
|
||||
"{key} must never leak into {other_era}: {other_era_advertisement}"
|
||||
);
|
||||
assert_eq!(
|
||||
other_era_advertisement,
|
||||
json!({
|
||||
"completions": {},
|
||||
"prompts": {"listChanged": false},
|
||||
"resources": {"listChanged": false, "subscribe": false},
|
||||
"tools": {"listChanged": false}
|
||||
}),
|
||||
"the other era advertisement stays the reviewed object"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// --- R5: the router's dispatch decision is the registration, never a handler list --------------
|
||||
|
||||
#[test]
|
||||
fn the_production_registration_routes_every_declared_method_in_its_own_era() {
|
||||
for (method, era, handler, kind) in [
|
||||
(
|
||||
"tools/list",
|
||||
MODERN_PROTOCOL_VERSION,
|
||||
MethodHandler::ToolList,
|
||||
Kind::Method,
|
||||
),
|
||||
(
|
||||
"tools/call",
|
||||
MODERN_PROTOCOL_VERSION,
|
||||
MethodHandler::ToolCall,
|
||||
Kind::Method,
|
||||
),
|
||||
(
|
||||
"tools/list",
|
||||
LEGACY_PROTOCOL_VERSION,
|
||||
MethodHandler::ToolList,
|
||||
Kind::Method,
|
||||
),
|
||||
(
|
||||
"tools/call",
|
||||
LEGACY_PROTOCOL_VERSION,
|
||||
MethodHandler::ToolCall,
|
||||
Kind::Method,
|
||||
),
|
||||
(
|
||||
"ping",
|
||||
MODERN_PROTOCOL_VERSION,
|
||||
MethodHandler::Ping,
|
||||
Kind::Method,
|
||||
),
|
||||
(
|
||||
"resources/templates/list",
|
||||
MODERN_PROTOCOL_VERSION,
|
||||
MethodHandler::ResourceTemplateList,
|
||||
Kind::Method,
|
||||
),
|
||||
(
|
||||
"resources/templates/list",
|
||||
LEGACY_PROTOCOL_VERSION,
|
||||
MethodHandler::ResourceTemplateList,
|
||||
Kind::Method,
|
||||
),
|
||||
(
|
||||
"ping",
|
||||
LEGACY_PROTOCOL_VERSION,
|
||||
MethodHandler::Ping,
|
||||
Kind::Method,
|
||||
),
|
||||
(
|
||||
"server/discover",
|
||||
MODERN_PROTOCOL_VERSION,
|
||||
MethodHandler::Discover,
|
||||
Kind::Method,
|
||||
),
|
||||
(
|
||||
"initialize",
|
||||
LEGACY_PROTOCOL_VERSION,
|
||||
MethodHandler::Lifecycle,
|
||||
Kind::Method,
|
||||
),
|
||||
(
|
||||
"notifications/initialized",
|
||||
LEGACY_PROTOCOL_VERSION,
|
||||
MethodHandler::Lifecycle,
|
||||
Kind::Notification,
|
||||
),
|
||||
] {
|
||||
assert_eq!(
|
||||
dispatch_decision(method, era),
|
||||
DispatchDecision::Allowed { handler, kind },
|
||||
"{method} must route to its registered handler with its registered kind in {era}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_lifecycle_dispatch_decision_carries_the_registered_method_kind() {
|
||||
// G2: `initialize` (a request) and `notifications/initialized` (a notification) share the
|
||||
// Lifecycle handler but are not interchangeable. The decision must carry the registered kind, or
|
||||
// the adapter can only tell them apart by the envelope shape and would serve one as the other.
|
||||
assert_eq!(
|
||||
dispatch_decision("initialize", LEGACY_PROTOCOL_VERSION),
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::Lifecycle,
|
||||
kind: Kind::Method,
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
dispatch_decision("notifications/initialized", LEGACY_PROTOCOL_VERSION),
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::Lifecycle,
|
||||
kind: Kind::Notification,
|
||||
}
|
||||
);
|
||||
assert_ne!(
|
||||
dispatch_decision("initialize", LEGACY_PROTOCOL_VERSION),
|
||||
dispatch_decision("notifications/initialized", LEGACY_PROTOCOL_VERSION),
|
||||
"the two lifecycle wire names must never collapse into the same dispatch decision"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_method_of_the_other_era_is_a_wrong_era_decision() {
|
||||
assert_eq!(
|
||||
dispatch_decision("server/discover", LEGACY_PROTOCOL_VERSION),
|
||||
DispatchDecision::WrongEra {
|
||||
handler: MethodHandler::Discover,
|
||||
kind: Kind::Method,
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
dispatch_decision("initialize", MODERN_PROTOCOL_VERSION),
|
||||
DispatchDecision::WrongEra {
|
||||
handler: MethodHandler::Lifecycle,
|
||||
kind: Kind::Method,
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
dispatch_decision("notifications/initialized", MODERN_PROTOCOL_VERSION),
|
||||
DispatchDecision::WrongEra {
|
||||
handler: MethodHandler::Lifecycle,
|
||||
kind: Kind::Notification,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unregistered_method_has_no_handler_and_no_service() {
|
||||
let registry = production_registry();
|
||||
for method in [
|
||||
"resources/subscribe",
|
||||
"logging/setLogLevel",
|
||||
"tasks/list",
|
||||
"frobnicate",
|
||||
] {
|
||||
for revision in [MODERN_PROTOCOL_VERSION, LEGACY_PROTOCOL_VERSION] {
|
||||
assert_eq!(
|
||||
registry.dispatch_decision(method, revision),
|
||||
DispatchDecision::Unregistered,
|
||||
"{method} is not registered and must never reach a handler in {revision}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn story317_completion_is_advertised_and_dispatchable_in_both_revisions() {
|
||||
let registry = production_registry();
|
||||
for revision in [MODERN_PROTOCOL_VERSION, LEGACY_PROTOCOL_VERSION] {
|
||||
assert!(
|
||||
registry.advertise_for(CapabilityId::Completions, revision),
|
||||
"the implemented completion surface must be advertised in {revision}"
|
||||
);
|
||||
assert_eq!(
|
||||
registry.dispatch_decision("completion/complete", revision),
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::Completion,
|
||||
kind: Kind::Method,
|
||||
},
|
||||
"`completion/complete` must reach its handler in {revision}"
|
||||
);
|
||||
assert_eq!(
|
||||
registry.advertised_capabilities(revision)["completions"],
|
||||
json!({}),
|
||||
"the pinned advertisement is an empty `completions` object in {revision}"
|
||||
);
|
||||
}
|
||||
let descriptor = METHOD_DESCRIPTORS
|
||||
.iter()
|
||||
.find(|descriptor| descriptor.name == "completion/complete")
|
||||
.expect("completion/complete is a registered method");
|
||||
assert_eq!(
|
||||
descriptor.required_headers.0,
|
||||
&["Mcp-Method"],
|
||||
"the `ref` union declares no single `Mcp-Name` value for the modern header rule"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adding_and_removing_a_method_descriptor_changes_the_dispatch_decision() {
|
||||
// The inert capability owns one inert method. With the method descriptor registered the
|
||||
// router routes it; without it the same request has no handler at all - the decision is the
|
||||
// registration, not a fixed list inside the router.
|
||||
const INERT_METHOD: MethodDescriptor = MethodDescriptor {
|
||||
name: "inert/echo",
|
||||
capability: CapabilityId::InertTest,
|
||||
kind: Kind::Method,
|
||||
required_headers: HEADERS_NONE,
|
||||
handler: MethodHandler::Ping,
|
||||
};
|
||||
let mut capabilities = CAPABILITY_DESCRIPTORS.to_vec();
|
||||
capabilities.push(inert_descriptor());
|
||||
let mut methods = METHOD_DESCRIPTORS.to_vec();
|
||||
|
||||
let without = CapabilityRegistry::new(&capabilities, &methods)
|
||||
.expect("the production method table stays valid");
|
||||
assert_eq!(
|
||||
without.dispatch_decision(INERT_METHOD.name, MODERN_PROTOCOL_VERSION),
|
||||
DispatchDecision::Unregistered
|
||||
);
|
||||
|
||||
methods.push(INERT_METHOD);
|
||||
let with = CapabilityRegistry::new(&capabilities, &methods)
|
||||
.expect("the inert method descriptor is a valid registration");
|
||||
assert_eq!(
|
||||
with.dispatch_decision(INERT_METHOD.name, MODERN_PROTOCOL_VERSION),
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::Ping,
|
||||
kind: Kind::Method,
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
with.dispatch_decision(INERT_METHOD.name, LEGACY_PROTOCOL_VERSION),
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::Ping,
|
||||
kind: Kind::Method,
|
||||
}
|
||||
);
|
||||
|
||||
// The advertisement projection is unaffected by a method descriptor: only capability
|
||||
// declarations advertise.
|
||||
assert_eq!(
|
||||
with.advertised_capabilities(MODERN_PROTOCOL_VERSION),
|
||||
json!({
|
||||
"inert_test_capability": {"enabled": true},
|
||||
"completions": {},
|
||||
"prompts": {"listChanged": false},
|
||||
"resources": {"listChanged": false, "subscribe": false},
|
||||
"tools": {"listChanged": false}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_method_of_an_unavailable_capability_is_never_dispatched() {
|
||||
// The inert capability is modern-only; its method must not be reachable in the legacy era.
|
||||
const INERT_METHOD: MethodDescriptor = MethodDescriptor {
|
||||
name: "inert/echo",
|
||||
capability: CapabilityId::InertTest,
|
||||
kind: Kind::Method,
|
||||
required_headers: HEADERS_NONE,
|
||||
handler: MethodHandler::Ping,
|
||||
};
|
||||
let mut capabilities = CAPABILITY_DESCRIPTORS.to_vec();
|
||||
capabilities.push(modern_only_descriptor());
|
||||
let mut methods = METHOD_DESCRIPTORS.to_vec();
|
||||
methods.push(INERT_METHOD);
|
||||
let registry =
|
||||
CapabilityRegistry::new(&capabilities, &methods).expect("valid inert registration");
|
||||
|
||||
assert_eq!(
|
||||
registry.dispatch_decision(INERT_METHOD.name, MODERN_PROTOCOL_VERSION),
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::Ping,
|
||||
kind: Kind::Method,
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
registry.dispatch_decision(INERT_METHOD.name, LEGACY_PROTOCOL_VERSION),
|
||||
DispatchDecision::WrongEra {
|
||||
handler: MethodHandler::Ping,
|
||||
kind: Kind::Method,
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,926 @@
|
||||
//! Story 3.8/3.11: the era-neutral `resources/list`, `resources/read` and
|
||||
//! `resources/templates/list` service boundary. Static Resource content is read from its exact Published
|
||||
//! artifact; dynamic templates use their exact Agent binding and shared runtime.
|
||||
//!
|
||||
//! The wire shape stays in the adapters and in the pinned per-revision converters
|
||||
//! (`crate::resource_wire`); this module never sees the envelope, the response mode or an
|
||||
//! `axum::Response`. Advertisement is not per-call authorization: the credential guard stays in the
|
||||
//! transport adapter and runs before any handler here.
|
||||
//!
|
||||
//! AC04: archive keeps the immutable publication row and therefore keeps the exact bound snapshot
|
||||
//! readable; new bindings are refused in the registry transition, not here.
|
||||
|
||||
use std::{sync::Arc, time::Instant};
|
||||
|
||||
use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
|
||||
use crank_artifacts::MAX_ARTIFACT_BYTES;
|
||||
use crank_core::resource::{ResourceError, ResourceKind};
|
||||
use crank_core::{ExecutionOrigin, InvocationSource, OperationSafetyClass, OperationStatus};
|
||||
use crank_registry::AgentResourceBinding;
|
||||
use crank_registry::BoundResourceAdmission;
|
||||
use crank_registry::model::ResolvedResourcePublication;
|
||||
use crank_runtime::{
|
||||
ExecutionAuthorization, RuntimeExecutionRequest, RuntimeOperation, RuntimeRequestContext,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
use tracing::info;
|
||||
|
||||
use crate::{
|
||||
app::AppState,
|
||||
jsonrpc::MODERN_PROTOCOL_VERSION,
|
||||
protocol::ServiceContext,
|
||||
resource_wire::{resource_contents_2025_11_25, resource_contents_2026_07_28},
|
||||
};
|
||||
|
||||
/// Upper bound of one `resources/list` page (same shape as `tools/list`).
|
||||
const MAX_RESOURCES_LIST_LIMIT: usize = 100;
|
||||
/// Marker that makes a cursor value non-Resource-shaped: it is an opaque continuation token, never a
|
||||
/// URI, Resource id or raw offset.
|
||||
const CURSOR_VERSION: u8 = 1;
|
||||
|
||||
/// Parameters of a `resources/list` command, already parsed by the adapter from the wire form.
|
||||
#[derive(Debug, Default, Deserialize)]
|
||||
pub(crate) struct ResourcesListCommand {
|
||||
#[serde(default)]
|
||||
pub(crate) cursor: Option<String>,
|
||||
#[serde(default)]
|
||||
pub(crate) limit: Option<usize>,
|
||||
}
|
||||
|
||||
/// Parameters of a `resources/read` command.
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub(crate) struct ResourceReadCommand {
|
||||
pub(crate) uri: String,
|
||||
}
|
||||
|
||||
/// A command the shared Resources service accepts.
|
||||
pub(crate) enum ResourcesCommand {
|
||||
List(ResourcesListCommand),
|
||||
Read(ResourceReadCommand),
|
||||
}
|
||||
|
||||
/// A neutral outcome of a shared Resources command.
|
||||
pub(crate) enum ResourcesOutcome {
|
||||
Listed {
|
||||
resources: Vec<Value>,
|
||||
next_cursor: Option<String>,
|
||||
},
|
||||
Read {
|
||||
contents: Value,
|
||||
},
|
||||
/// The requested page is not representable (malformed/stale/cross-scope cursor): the adapter
|
||||
/// answers era-correct invalid params without mixing pages.
|
||||
InvalidParams(String),
|
||||
/// Unknown, Draft, foreign or unbound URI: one safe outcome that cannot distinguish them and
|
||||
/// carries no Resource metadata.
|
||||
NotAvailable,
|
||||
/// The published catalog could not be read.
|
||||
CatalogUnavailable,
|
||||
/// A bound publication could not be served safely, without disclosing content or metadata.
|
||||
ArtifactUnavailable,
|
||||
/// A sanitized correlated failure from the shared runtime.
|
||||
ExecutionError(crate::tool_error::ToolErrorContract),
|
||||
}
|
||||
|
||||
pub(crate) enum ResourceTemplatesListError {
|
||||
InvalidCursor,
|
||||
Unavailable,
|
||||
}
|
||||
|
||||
/// List exact Published template definitions bound to the active published Agent snapshot.
|
||||
pub(crate) async fn list_resource_templates(
|
||||
state: &Arc<AppState>,
|
||||
workspace_slug: &str,
|
||||
agent_slug: &str,
|
||||
revision: &str,
|
||||
command: ResourcesListCommand,
|
||||
) -> Result<(Vec<Value>, Option<String>), ResourceTemplatesListError> {
|
||||
let catalog = state
|
||||
.catalog
|
||||
.get_catalog(workspace_slug, agent_slug)
|
||||
.await
|
||||
.map_err(|_| ResourceTemplatesListError::Unavailable)?;
|
||||
let workspace_id = state
|
||||
.registry
|
||||
.published_agent_workspace_id(workspace_slug, agent_slug)
|
||||
.await
|
||||
.map_err(|_| ResourceTemplatesListError::Unavailable)?;
|
||||
let scope = CursorScope {
|
||||
workspace_slug,
|
||||
agent_slug,
|
||||
catalog_revision: &catalog.catalog_revision,
|
||||
revision,
|
||||
};
|
||||
let start = command
|
||||
.cursor
|
||||
.as_deref()
|
||||
.map(|cursor| {
|
||||
decode_cursor(cursor, &scope, catalog.resources.len())
|
||||
.ok_or(ResourceTemplatesListError::InvalidCursor)
|
||||
})
|
||||
.transpose()?
|
||||
.unwrap_or(0);
|
||||
let limit = command
|
||||
.limit
|
||||
.unwrap_or(MAX_RESOURCES_LIST_LIMIT)
|
||||
.clamp(1, MAX_RESOURCES_LIST_LIMIT);
|
||||
let end = start.saturating_add(limit).min(catalog.resources.len());
|
||||
let admitted = state
|
||||
.registry
|
||||
.list_admitted_resource_templates(workspace_id.as_str(), &catalog.resources[start..end])
|
||||
.await
|
||||
.map_err(|_| ResourceTemplatesListError::Unavailable)?;
|
||||
let mut templates = Vec::new();
|
||||
for item in admitted {
|
||||
let definition: Value = serde_json::from_str(&item.source.definition_json)
|
||||
.map_err(|_| ResourceTemplatesListError::Unavailable)?;
|
||||
let source = crank_core::resource::TemplateSource::parse(&definition)
|
||||
.map_err(|_| ResourceTemplatesListError::Unavailable)?;
|
||||
templates.push(json!({
|
||||
"uriTemplate": source.uri_template,
|
||||
"name": item.publication.name,
|
||||
"description": item.publication.description,
|
||||
"mimeType": item.publication.mime_type,
|
||||
"parameters": source.parameters
|
||||
}));
|
||||
}
|
||||
let next_cursor = (end < catalog.resources.len()).then(|| encode_cursor(&scope, end));
|
||||
Ok((templates, next_cursor))
|
||||
}
|
||||
|
||||
/// Handle one shared Resources command for the revision the adapter serves.
|
||||
pub(crate) async fn handle_resources_command(
|
||||
state: &Arc<AppState>,
|
||||
context: ServiceContext<'_>,
|
||||
revision: &str,
|
||||
command: ResourcesCommand,
|
||||
) -> ResourcesOutcome {
|
||||
let catalog = match state
|
||||
.catalog
|
||||
.get_catalog(context.workspace_slug, context.agent_slug)
|
||||
.await
|
||||
{
|
||||
Ok(catalog) => catalog,
|
||||
Err(_error) => return ResourcesOutcome::CatalogUnavailable,
|
||||
};
|
||||
let workspace_id = match state
|
||||
.registry
|
||||
.published_agent_workspace_id(context.workspace_slug, context.agent_slug)
|
||||
.await
|
||||
{
|
||||
Ok(workspace_id) => workspace_id,
|
||||
Err(_error) => return ResourcesOutcome::CatalogUnavailable,
|
||||
};
|
||||
let scope = CursorScope {
|
||||
workspace_slug: context.workspace_slug,
|
||||
agent_slug: context.agent_slug,
|
||||
catalog_revision: &catalog.catalog_revision,
|
||||
revision,
|
||||
};
|
||||
|
||||
match command {
|
||||
ResourcesCommand::List(list) => {
|
||||
list_resources(state, &workspace_id, &catalog.resources, &scope, list).await
|
||||
}
|
||||
ResourcesCommand::Read(read) => {
|
||||
read_resource(
|
||||
state,
|
||||
context,
|
||||
&workspace_id,
|
||||
&catalog.resources,
|
||||
revision,
|
||||
&read,
|
||||
)
|
||||
.await
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn list_resources(
|
||||
state: &Arc<AppState>,
|
||||
workspace_id: &crank_core::WorkspaceId,
|
||||
bindings: &[AgentResourceBinding],
|
||||
scope: &CursorScope<'_>,
|
||||
command: ResourcesListCommand,
|
||||
) -> ResourcesOutcome {
|
||||
let start = match command.cursor.as_deref() {
|
||||
Some(cursor) => match decode_cursor(cursor, scope, bindings.len()) {
|
||||
Some(offset) => offset,
|
||||
None => {
|
||||
return ResourcesOutcome::InvalidParams("invalid resources/list cursor".to_owned());
|
||||
}
|
||||
},
|
||||
None => 0,
|
||||
};
|
||||
let limit = command
|
||||
.limit
|
||||
.unwrap_or(bindings.len())
|
||||
.clamp(1, MAX_RESOURCES_LIST_LIMIT);
|
||||
let end = start.saturating_add(limit).min(bindings.len());
|
||||
|
||||
let mut resources = Vec::with_capacity(end - start);
|
||||
let mut revoked_omitted = 0usize;
|
||||
// Story 3.8: живой PostgreSQL-gate страницы. Shared-блокировки берутся на
|
||||
// исходный диапазон [start, end) в порядке resource_id ASC, затем читаются
|
||||
// свежие tombstones; offset/cursor продолжают адресовать исходный immutable
|
||||
// bindings-массив, поэтому отзыв между страницами не сдвигает и не дублирует
|
||||
// элементы. Отозванный Resource — единственное, что пропускается: corruption
|
||||
// или storage-сбой не маскируются успешной partial-страницей.
|
||||
let admitted = match state
|
||||
.registry
|
||||
.list_admitted_resource_publications(workspace_id.as_str(), &bindings[start..end])
|
||||
.await
|
||||
{
|
||||
Ok(admitted) => admitted,
|
||||
Err(_error) => return ResourcesOutcome::ArtifactUnavailable,
|
||||
};
|
||||
for admission in admitted {
|
||||
let resolved = match admission {
|
||||
BoundResourceAdmission::Revoked => {
|
||||
revoked_omitted += 1;
|
||||
continue;
|
||||
}
|
||||
BoundResourceAdmission::Admitted(resolved) => *resolved,
|
||||
// A published template is not an artifact-backed concrete Resource: its concrete URIs
|
||||
// are the expanded ones and its definition is discovered through
|
||||
// `resources/templates/list`. Listing its identity URI here would advertise an
|
||||
// unreadable Resource, so the admitted binding only keeps the page alive.
|
||||
BoundResourceAdmission::Template => continue,
|
||||
};
|
||||
resources.push(json!({
|
||||
"uri": resolved.publication.uri,
|
||||
"name": resolved.publication.name,
|
||||
"mimeType": resolved.publication.mime_type,
|
||||
}));
|
||||
}
|
||||
if revoked_omitted > 0 {
|
||||
// Only the number of omitted entries: no URI, name, MIME or digest of a denied Resource.
|
||||
info!(
|
||||
name: "mcp.resources.list",
|
||||
request_id = %resolved_request_id(),
|
||||
trace_id = %resolved_trace_id(),
|
||||
outcome = "filtered",
|
||||
revoked_omitted,
|
||||
"resource list page omitted revoked resources"
|
||||
);
|
||||
}
|
||||
|
||||
let next_cursor = (end < bindings.len()).then(|| encode_cursor(scope, end));
|
||||
ResourcesOutcome::Listed {
|
||||
resources,
|
||||
next_cursor,
|
||||
}
|
||||
}
|
||||
|
||||
async fn read_resource(
|
||||
state: &Arc<AppState>,
|
||||
context: ServiceContext<'_>,
|
||||
workspace_id: &crank_core::WorkspaceId,
|
||||
bindings: &[AgentResourceBinding],
|
||||
revision: &str,
|
||||
command: &ResourceReadCommand,
|
||||
) -> ResourcesOutcome {
|
||||
if let Some(outcome) = match_template_read(
|
||||
state,
|
||||
&context,
|
||||
workspace_id,
|
||||
bindings,
|
||||
revision,
|
||||
&command.uri,
|
||||
)
|
||||
.await
|
||||
{
|
||||
return outcome;
|
||||
}
|
||||
// Resolve the requested static URI against the exact bound snapshot only. Nothing is looked up by the
|
||||
// client-supplied URI, so an unknown/Draft/unbound URI cannot even prove that it exists.
|
||||
// A corrupt/missing publication or a storage failure is *not* the same answer: it must not be
|
||||
// disguised as an unknown URI (the typed error is preserved instead of being dropped).
|
||||
let mut matched: Option<AgentResourceBinding> = None;
|
||||
for binding in bindings {
|
||||
match resolve_binding(state, workspace_id, binding).await {
|
||||
Ok(Some(resolved)) => {
|
||||
if resolved.publication.uri == command.uri {
|
||||
matched = Some(binding.clone());
|
||||
break;
|
||||
}
|
||||
}
|
||||
// No exact publication for this bound version: the URI simply cannot match.
|
||||
Ok(None) => {}
|
||||
Err(_error) => return ResourcesOutcome::ArtifactUnavailable,
|
||||
}
|
||||
}
|
||||
let Some(binding) = matched else {
|
||||
log_read_denied("not_available");
|
||||
return ResourcesOutcome::NotAvailable;
|
||||
};
|
||||
|
||||
// Story 3.8: живой PostgreSQL-gate, не cache. `FOR SHARE` на строке Resource
|
||||
// удерживается до успешного commit, поэтому revoke-first закрывает чтение до
|
||||
// artifact bytes (0 чтений), а read-first линеаризует чтение до отзыва.
|
||||
// Revoked неотличим от unknown/Draft/unbound: тот же безопасный NotAvailable.
|
||||
let guard = match state
|
||||
.registry
|
||||
.begin_authorized_resource_read(
|
||||
workspace_id.as_str(),
|
||||
&binding.resource_id,
|
||||
binding.resource_version,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(guard) => guard,
|
||||
Err(ResourceError::Revoked) => {
|
||||
log_read_denied("denied");
|
||||
return ResourcesOutcome::NotAvailable;
|
||||
}
|
||||
Err(_error) => return ResourcesOutcome::ArtifactUnavailable,
|
||||
};
|
||||
let resolved = guard.publication();
|
||||
|
||||
// Access (binding + credential, enforced by the adapter) is decided. Size is decided from the
|
||||
// immutable publication metadata *before* any artifact byte is opened.
|
||||
let Ok(size_bytes) = usize::try_from(resolved.publication.size_bytes) else {
|
||||
return ResourcesOutcome::ArtifactUnavailable;
|
||||
};
|
||||
if size_bytes == 0 || size_bytes > MAX_ARTIFACT_BYTES {
|
||||
return ResourcesOutcome::ArtifactUnavailable;
|
||||
}
|
||||
let Some(store) = state.artifact_store.as_ref() else {
|
||||
return ResourcesOutcome::ArtifactUnavailable;
|
||||
};
|
||||
let bytes = match store.read(&resolved.artifact_ref) {
|
||||
Ok(bytes) => bytes,
|
||||
Err(_error) => return ResourcesOutcome::ArtifactUnavailable,
|
||||
};
|
||||
let Some(kind) = ResourceKind::parse(&resolved.publication.kind) else {
|
||||
return ResourcesOutcome::ArtifactUnavailable;
|
||||
};
|
||||
|
||||
let contents = match revision {
|
||||
MODERN_PROTOCOL_VERSION => resource_contents_2026_07_28(
|
||||
&resolved.publication.uri,
|
||||
kind,
|
||||
&resolved.publication.mime_type,
|
||||
&bytes,
|
||||
),
|
||||
_ => resource_contents_2025_11_25(
|
||||
&resolved.publication.uri,
|
||||
kind,
|
||||
&resolved.publication.mime_type,
|
||||
&bytes,
|
||||
),
|
||||
};
|
||||
|
||||
// Транзакция завершается до выдачи готового outcome: ошибка commit — безопасный
|
||||
// отказ, а не выдача подготовленного content.
|
||||
if guard.commit().await.is_err() {
|
||||
return ResourcesOutcome::ArtifactUnavailable;
|
||||
}
|
||||
|
||||
// Read outcome telemetry: correlation identity and the byte count only — never the URI, the MIME
|
||||
// payload or any content.
|
||||
info!(
|
||||
name: "mcp.resources.read",
|
||||
request_id = %resolved_request_id(),
|
||||
trace_id = %resolved_trace_id(),
|
||||
outcome = "ok",
|
||||
content_bytes = bytes.len(),
|
||||
resource_kind = kind.as_str(),
|
||||
"resource read outcome"
|
||||
);
|
||||
|
||||
ResourcesOutcome::Read {
|
||||
contents: json!([contents]),
|
||||
}
|
||||
}
|
||||
|
||||
async fn match_template_read(
|
||||
state: &Arc<AppState>,
|
||||
context: &ServiceContext<'_>,
|
||||
workspace_id: &crank_core::WorkspaceId,
|
||||
bindings: &[AgentResourceBinding],
|
||||
revision: &str,
|
||||
uri: &str,
|
||||
) -> Option<ResourcesOutcome> {
|
||||
macro_rules! fail_closed {
|
||||
($stage:literal) => {{
|
||||
tracing::warn!(name: "mcp.resource_template.read", stage = $stage, "template read unavailable");
|
||||
let failure = crank_core::ExecutionFailure::new(
|
||||
crank_core::ExecutionErrorCode::RuntimeInternal,
|
||||
context.correlation.clone(),
|
||||
);
|
||||
return Some(ResourcesOutcome::ExecutionError(
|
||||
crate::tool_error::tool_error_contract_from_failure(&failure, context.locale),
|
||||
));
|
||||
}};
|
||||
}
|
||||
let admitted = match state
|
||||
.registry
|
||||
.list_admitted_resource_templates(workspace_id.as_str(), bindings)
|
||||
.await
|
||||
{
|
||||
Ok(bindings) => bindings,
|
||||
Err(_) => {
|
||||
tracing::warn!(
|
||||
name: "mcp.resource_template.read",
|
||||
stage = "binding_admission",
|
||||
"template admission unavailable"
|
||||
);
|
||||
return Some(ResourcesOutcome::CatalogUnavailable);
|
||||
}
|
||||
};
|
||||
for template in admitted {
|
||||
let publication = template.publication;
|
||||
let definition: Value = match serde_json::from_str(&template.source.definition_json) {
|
||||
Ok(value) => value,
|
||||
Err(_) => fail_closed!("definition_parse"),
|
||||
};
|
||||
let source = match crank_core::resource::TemplateSource::parse(&definition) {
|
||||
Ok(source) => source,
|
||||
Err(_) => fail_closed!("source_validation"),
|
||||
};
|
||||
let Some(input) = match_template_uri(&source, uri) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
let operation_id = crank_core::OperationId::new(source.operation_id.clone());
|
||||
let operation_record = match state
|
||||
.registry
|
||||
.get_operation_version(workspace_id, &operation_id, source.operation_version)
|
||||
.await
|
||||
{
|
||||
Ok(Some(record)) if record.status == OperationStatus::Published => record,
|
||||
Ok(Some(_record)) => fail_closed!("operation_version_status"),
|
||||
Ok(None) => fail_closed!("operation_version_missing"),
|
||||
Err(_) => fail_closed!("operation_version_query"),
|
||||
};
|
||||
let summary = match state
|
||||
.registry
|
||||
.get_operation_summary(workspace_id, &operation_id)
|
||||
.await
|
||||
{
|
||||
Ok(Some(summary)) if summary.status != OperationStatus::Archived => summary,
|
||||
_ => fail_closed!("operation_eligibility"),
|
||||
};
|
||||
if !crate::access::credential_allows_security_level(
|
||||
context.credential,
|
||||
operation_record.snapshot.security_level,
|
||||
) {
|
||||
return Some(template_output_error(
|
||||
context,
|
||||
crank_core::ExecutionErrorCode::AuthorizationDenied,
|
||||
));
|
||||
}
|
||||
let operation = RuntimeOperation::from(operation_record.snapshot.clone());
|
||||
let safety = operation
|
||||
.execution_config
|
||||
.safety
|
||||
.as_ref()
|
||||
.map(|policy| policy.class);
|
||||
if safety != Some(OperationSafetyClass::Read)
|
||||
|| operation
|
||||
.execution_config
|
||||
.approval_policy
|
||||
.as_ref()
|
||||
.is_some_and(|policy| policy.required)
|
||||
|| !matches!(&operation.target, crank_core::Target::Rest(target) if matches!(target.method, crank_core::HttpMethod::Get | crank_core::HttpMethod::Head))
|
||||
{
|
||||
fail_closed!("operation_policy");
|
||||
}
|
||||
let agent_id = match state
|
||||
.registry
|
||||
.published_agent_id(context.workspace_slug, context.agent_slug)
|
||||
.await
|
||||
{
|
||||
Ok(agent_id) => agent_id,
|
||||
Err(_) => fail_closed!("agent_identity"),
|
||||
};
|
||||
let request_context = RuntimeRequestContext::from_correlation(context.correlation)
|
||||
.with_response_cache_scope(
|
||||
workspace_id.as_str().to_owned(),
|
||||
agent_id.as_str().to_owned(),
|
||||
)
|
||||
.with_resource_response_cache(
|
||||
publication.resource_id.as_str(),
|
||||
publication.version,
|
||||
source.cache.ttl_ms,
|
||||
source.cache.max_bytes,
|
||||
)
|
||||
.with_metering_context(
|
||||
workspace_id.clone(),
|
||||
Some(agent_id.clone()),
|
||||
InvocationSource::AgentToolCall,
|
||||
);
|
||||
// Re-read operation lifecycle and exact version immediately before outbound dispatch.
|
||||
match state
|
||||
.registry
|
||||
.get_operation_summary(workspace_id, &operation_id)
|
||||
.await
|
||||
{
|
||||
Ok(Some(summary)) if summary.status != OperationStatus::Archived => {}
|
||||
_ => fail_closed!("operation_eligibility"),
|
||||
}
|
||||
match state
|
||||
.registry
|
||||
.get_operation_version(workspace_id, &operation_id, source.operation_version)
|
||||
.await
|
||||
{
|
||||
Ok(Some(record)) if record.status == OperationStatus::Published => {}
|
||||
_ => fail_closed!("operation_version"),
|
||||
}
|
||||
let resolved_auth = match crate::app::resolve_operation_auth(
|
||||
state,
|
||||
workspace_id,
|
||||
&operation.execution_config,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(auth) => auth,
|
||||
Err(error) => {
|
||||
return Some(ResourcesOutcome::ExecutionError(
|
||||
crate::tool_error::tool_error_contract_from_runtime(
|
||||
&error,
|
||||
context.correlation.request_id().as_str(),
|
||||
context.correlation.trace_id().as_str(),
|
||||
context.locale,
|
||||
),
|
||||
));
|
||||
}
|
||||
};
|
||||
let request = RuntimeExecutionRequest::try_new(
|
||||
workspace_id,
|
||||
ExecutionOrigin::AgentSnapshot,
|
||||
Some(&agent_id),
|
||||
&operation,
|
||||
&input,
|
||||
ExecutionAuthorization::Authorized,
|
||||
resolved_auth.as_ref(),
|
||||
&request_context,
|
||||
Instant::now()
|
||||
+ std::time::Duration::from_millis(operation.execution_config.timeout_ms.max(1)),
|
||||
);
|
||||
// Acquire the live Resource lock only after registry/auth lookups, then hold it through dispatch.
|
||||
let guard = match state
|
||||
.registry
|
||||
.begin_authorized_resource_template_read(
|
||||
workspace_id.as_str(),
|
||||
&publication.resource_id,
|
||||
publication.version,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(guard) => guard,
|
||||
Err(ResourceError::Revoked | ResourceError::NotFound) => {
|
||||
return Some(ResourcesOutcome::NotAvailable);
|
||||
}
|
||||
Err(_) => fail_closed!("resource_read_admission"),
|
||||
};
|
||||
let success = match request {
|
||||
Ok(request) => match state.runtime.execute_outcome(request).await {
|
||||
Ok(success) => success,
|
||||
Err(failure) => {
|
||||
return Some(ResourcesOutcome::ExecutionError(
|
||||
crate::tool_error::tool_error_contract_from_failure(
|
||||
&failure,
|
||||
context.locale,
|
||||
),
|
||||
));
|
||||
}
|
||||
},
|
||||
Err(_) => fail_closed!("runtime_request"),
|
||||
};
|
||||
let Some(kind) = ResourceKind::for_mime(&publication.mime_type) else {
|
||||
return Some(template_output_error(
|
||||
context,
|
||||
crank_core::ExecutionErrorCode::OutputMappingInvalid,
|
||||
));
|
||||
};
|
||||
let Some(bytes) = mapped_resource_bytes(kind, &success.output) else {
|
||||
return Some(template_output_error(
|
||||
context,
|
||||
crank_core::ExecutionErrorCode::OutputMappingInvalid,
|
||||
));
|
||||
};
|
||||
let max_bytes = usize::try_from(source.cache.max_bytes)
|
||||
.unwrap_or(MAX_ARTIFACT_BYTES)
|
||||
.min(MAX_ARTIFACT_BYTES);
|
||||
if bytes.is_empty() || bytes.len() > max_bytes {
|
||||
return Some(template_output_error(
|
||||
context,
|
||||
crank_core::ExecutionErrorCode::UpstreamResponseTooLarge,
|
||||
));
|
||||
}
|
||||
if guard.commit().await.is_err() {
|
||||
fail_closed!("resource_guard_commit");
|
||||
}
|
||||
let contents = if revision == MODERN_PROTOCOL_VERSION {
|
||||
resource_contents_2026_07_28(uri, kind, &publication.mime_type, &bytes)
|
||||
} else {
|
||||
resource_contents_2025_11_25(uri, kind, &publication.mime_type, &bytes)
|
||||
};
|
||||
let _ = summary;
|
||||
return Some(ResourcesOutcome::Read {
|
||||
contents: json!([contents]),
|
||||
});
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn mapped_resource_bytes(kind: ResourceKind, output: &Value) -> Option<Vec<u8>> {
|
||||
match kind {
|
||||
ResourceKind::Text => output.as_str().map(|text| text.as_bytes().to_vec()),
|
||||
ResourceKind::Json if !output.is_null() => serde_json::to_vec(output).ok(),
|
||||
ResourceKind::Binary => output
|
||||
.as_object()
|
||||
.filter(|object| object.len() == 1 && object.contains_key("data_base64"))
|
||||
.and_then(|object| object.get("data_base64"))
|
||||
.and_then(Value::as_str)
|
||||
.and_then(|encoded| {
|
||||
base64::engine::general_purpose::STANDARD
|
||||
.decode(encoded)
|
||||
.ok()
|
||||
}),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn template_output_error(
|
||||
context: &ServiceContext<'_>,
|
||||
code: crank_core::ExecutionErrorCode,
|
||||
) -> ResourcesOutcome {
|
||||
let failure = crank_core::ExecutionFailure::new(code, context.correlation.clone());
|
||||
ResourcesOutcome::ExecutionError(crate::tool_error::tool_error_contract_from_failure(
|
||||
&failure,
|
||||
context.locale,
|
||||
))
|
||||
}
|
||||
|
||||
fn match_template_uri(source: &crank_core::resource::TemplateSource, uri: &str) -> Option<Value> {
|
||||
let names = crank_core::resource::parse_uri_template(&source.uri_template).ok()?;
|
||||
let template_segments: Vec<_> = source.uri_template.split('/').collect();
|
||||
let uri_segments: Vec<_> = uri.split('/').collect();
|
||||
if template_segments.len() != uri_segments.len() {
|
||||
return None;
|
||||
}
|
||||
let mut values = serde_json::Map::new();
|
||||
let mut name_index = 0;
|
||||
for (template, actual) in template_segments.iter().zip(uri_segments) {
|
||||
if template.starts_with('{') && template.ends_with('}') {
|
||||
let name = names.get(name_index)?;
|
||||
let decoded = decode_uri_segment(actual)?;
|
||||
let parameter = source.parameters.iter().find(|p| p.name == *name)?;
|
||||
let value = parse_template_parameter(¶meter.schema, &decoded)?;
|
||||
if !set_input_path(&mut values, ¶meter.input_path, value) {
|
||||
return None;
|
||||
}
|
||||
name_index += 1;
|
||||
} else if template != &actual {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
Some(Value::Object(values))
|
||||
}
|
||||
|
||||
fn parse_template_parameter(schema: &Value, raw: &str) -> Option<Value> {
|
||||
let value = match schema.get("type")?.as_str()? {
|
||||
"string" | "enum" => Value::String(raw.to_owned()),
|
||||
"integer" => Value::Number(raw.parse::<i64>().ok()?.into()),
|
||||
"number" => serde_json::Number::from_f64(raw.parse::<f64>().ok()?).map(Value::Number)?,
|
||||
"boolean" => Value::Bool(raw.parse::<bool>().ok()?),
|
||||
_ => return None,
|
||||
};
|
||||
let parameter_schema: crank_schema::Schema = serde_json::from_value(schema.clone()).ok()?;
|
||||
crank_runtime::validate_resource_template_parameter(¶meter_schema, &value).ok()?;
|
||||
Some(value)
|
||||
}
|
||||
|
||||
pub(super) fn set_input_path(
|
||||
root: &mut serde_json::Map<String, Value>,
|
||||
path: &str,
|
||||
value: Value,
|
||||
) -> bool {
|
||||
let Some((prefix, segments)) = path.split_once('.') else {
|
||||
return false;
|
||||
};
|
||||
if prefix != "input" {
|
||||
return false;
|
||||
}
|
||||
let mut current = root;
|
||||
let mut parts = segments.split('.').peekable();
|
||||
while let Some(part) = parts.next() {
|
||||
if parts.peek().is_none() {
|
||||
current.insert(part.to_owned(), value);
|
||||
return true;
|
||||
}
|
||||
let entry = current.entry(part.to_owned()).or_insert_with(|| json!({}));
|
||||
let Some(object) = entry.as_object_mut() else {
|
||||
return false;
|
||||
};
|
||||
current = object;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn decode_uri_segment(segment: &str) -> Option<String> {
|
||||
let bytes = segment.as_bytes();
|
||||
let mut decoded = Vec::with_capacity(bytes.len());
|
||||
let mut i = 0;
|
||||
while i < bytes.len() {
|
||||
if bytes[i] == b'%' {
|
||||
let hi = *bytes.get(i + 1)?;
|
||||
let lo = *bytes.get(i + 2)?;
|
||||
decoded.push((hex_digit(hi)? << 4) | hex_digit(lo)?);
|
||||
i += 3;
|
||||
} else {
|
||||
if !bytes[i].is_ascii_alphanumeric() && !matches!(bytes[i], b'-' | b'_' | b'.' | b'~') {
|
||||
return None;
|
||||
}
|
||||
decoded.push(bytes[i]);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
let value = String::from_utf8(decoded).ok()?;
|
||||
if value == "." || value == ".." {
|
||||
return None;
|
||||
}
|
||||
Some(value)
|
||||
}
|
||||
|
||||
fn hex_digit(value: u8) -> Option<u8> {
|
||||
match value {
|
||||
b'0'..=b'9' => Some(value - b'0'),
|
||||
b'a'..=b'f' => Some(value - b'a' + 10),
|
||||
b'A'..=b'F' => Some(value - b'A' + 10),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod template_uri_tests {
|
||||
use super::{decode_uri_segment, match_template_uri, parse_template_parameter};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
#[test]
|
||||
fn uri_variables_are_decoded_before_typed_validation_but_keep_reserved_data() {
|
||||
let source = crank_core::resource::TemplateSource::parse(&json!({
|
||||
"operation_id": "op_order", "operation_version": 1,
|
||||
"uri_template": "crank://orders/{order_id}",
|
||||
"parameters": [{ "name": "order_id", "input_path": "input.order_id", "schema": { "type": "string" } }],
|
||||
"cache": { "ttl_ms": 1000, "vary": ["order_id"], "max_bytes": 1024 },
|
||||
"failure": { "outcome": "error" }
|
||||
})).unwrap();
|
||||
let input = match_template_uri(&source, "crank://orders/a%2Fb%3Fc").unwrap();
|
||||
assert_eq!(input["order_id"], "a/b?c");
|
||||
assert_eq!(decode_uri_segment("%2e%2e"), None);
|
||||
assert!(match_template_uri(&source, "crank://orders/../admin").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resource_parameter_enum_values_are_enforced_from_the_saved_schema() {
|
||||
let schema: Value = json!({ "type": "string", "enum_values": ["eu"] });
|
||||
assert_eq!(parse_template_parameter(&schema, "eu"), Some(json!("eu")));
|
||||
assert!(parse_template_parameter(&schema, "us").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uuid_parameters_are_rejected_before_runtime_request_construction() {
|
||||
let schema: Value = json!({ "type": "string", "format": "uuid" });
|
||||
assert!(
|
||||
parse_template_parameter(&schema, "f47ac10b-58cc-4372-a567-0e02b2c3d479").is_some()
|
||||
);
|
||||
assert!(parse_template_parameter(&schema, "not-a-uuid").is_none());
|
||||
}
|
||||
}
|
||||
|
||||
fn resolved_request_id() -> String {
|
||||
crank_observability::current_request_correlation()
|
||||
.0
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn resolved_trace_id() -> String {
|
||||
crank_observability::current_request_correlation()
|
||||
.1
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Resolve one exact bound version to its publication metadata.
|
||||
///
|
||||
/// `Ok(None)` means the bound version has no exact publication (it cannot be the requested URI);
|
||||
/// every other error keeps its type so the caller can answer a safe *unavailable* instead of a
|
||||
/// misleading "not available". The bytes are still only served through the live gate below.
|
||||
async fn resolve_binding(
|
||||
state: &Arc<AppState>,
|
||||
workspace_id: &crank_core::WorkspaceId,
|
||||
binding: &AgentResourceBinding,
|
||||
) -> Result<Option<ResolvedResourcePublication>, ResourceError> {
|
||||
match state
|
||||
.registry
|
||||
.resolve_resource_publication(
|
||||
workspace_id.as_str(),
|
||||
&binding.resource_id,
|
||||
binding.resource_version,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(resolved) => Ok(Some(resolved)),
|
||||
Err(ResourceError::NotFound) => Ok(None),
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
}
|
||||
|
||||
/// Denied-read telemetry: correlation identity and the safe outcome only. The URI, Resource name,
|
||||
/// MIME, digest and any path are deliberately absent, so a denied read cannot leak what it denied.
|
||||
fn log_read_denied(outcome: &'static str) {
|
||||
info!(
|
||||
name: "mcp.resources.read",
|
||||
request_id = %resolved_request_id(),
|
||||
trace_id = %resolved_trace_id(),
|
||||
outcome,
|
||||
"resource read outcome"
|
||||
);
|
||||
}
|
||||
|
||||
/// The immutable scope a continuation token is bound to: workspace + Agent + catalog revision + the
|
||||
/// negotiated MCP revision. A cursor that does not match this request is never mixed into a page.
|
||||
struct CursorScope<'a> {
|
||||
workspace_slug: &'a str,
|
||||
agent_slug: &'a str,
|
||||
catalog_revision: &'a str,
|
||||
revision: &'a str,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct CursorPayload {
|
||||
v: u8,
|
||||
w: String,
|
||||
a: String,
|
||||
c: String,
|
||||
r: String,
|
||||
o: usize,
|
||||
}
|
||||
|
||||
fn encode_cursor(scope: &CursorScope<'_>, offset: usize) -> String {
|
||||
let payload = CursorPayload {
|
||||
v: CURSOR_VERSION,
|
||||
w: scope.workspace_slug.to_owned(),
|
||||
a: scope.agent_slug.to_owned(),
|
||||
c: scope.catalog_revision.to_owned(),
|
||||
r: scope.revision.to_owned(),
|
||||
o: offset,
|
||||
};
|
||||
let encoded = serde_json::to_vec(&payload).unwrap_or_default();
|
||||
URL_SAFE_NO_PAD.encode(encoded)
|
||||
}
|
||||
|
||||
fn decode_cursor(raw: &str, scope: &CursorScope<'_>, len: usize) -> Option<usize> {
|
||||
let bytes = URL_SAFE_NO_PAD.decode(raw).ok()?;
|
||||
let payload: CursorPayload = serde_json::from_slice(&bytes).ok()?;
|
||||
let matches = payload.v == CURSOR_VERSION
|
||||
&& payload.w == scope.workspace_slug
|
||||
&& payload.a == scope.agent_slug
|
||||
&& payload.c == scope.catalog_revision
|
||||
&& payload.r == scope.revision;
|
||||
(matches && payload.o <= len).then_some(payload.o)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod template_output_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn resource_output_mapping_enforces_text_json_and_binary_contracts() {
|
||||
assert_eq!(
|
||||
mapped_resource_bytes(ResourceKind::Text, &json!("hi")).unwrap(),
|
||||
b"hi"
|
||||
);
|
||||
assert_eq!(
|
||||
mapped_resource_bytes(ResourceKind::Text, &json!({"text":"hi"})),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
mapped_resource_bytes(ResourceKind::Json, &json!({"ok":true})).unwrap(),
|
||||
br#"{"ok":true}"#
|
||||
);
|
||||
assert_eq!(
|
||||
mapped_resource_bytes(ResourceKind::Json, &Value::Null),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
mapped_resource_bytes(ResourceKind::Binary, &json!({"data_base64":"AAE="})).unwrap(),
|
||||
[0, 1]
|
||||
);
|
||||
assert_eq!(
|
||||
mapped_resource_bytes(ResourceKind::Binary, &json!({"data_base64":"not-base64"})),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
mapped_resource_bytes(
|
||||
ResourceKind::Binary,
|
||||
&json!({"data_base64":"AA==","path":"/tmp/x"})
|
||||
),
|
||||
None
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
//! Story 3.6, граница MCP (AT-3.6-06): чистые per-revision функции,
|
||||
//! транслирующие Resource Version в `contents[]`.
|
||||
//!
|
||||
//! Регистрация MCP живёт в `protocol::registry`: Story 3.8 добавила Resources
|
||||
//! capability и `resources/list`/`resources/read` ровно потому, что handlers
|
||||
//! реализованы; этот модуль остаётся чистой границей ревизий и не решает, что
|
||||
//! рекламируется и что диспатчится.
|
||||
//!
|
||||
//! Ветка `contents[]` выбирается **typed kind**, а не разбором байтов: для
|
||||
//! `ResourceKind::Binary` это всегда `blob` (base64), даже если bytes декодируются
|
||||
//! как UTF-8; для text/JSON — `text`. Content sniffing отсутствует.
|
||||
//!
|
||||
//! Форма `contents[]` одинакова для обеих ревизий и следует их схемам:
|
||||
//!
|
||||
//! - `2026-07-28-schema.ts`: `ReadResourceResult extends CacheableResult`,
|
||||
//! `ResourceContents {uri, mimeType?, _meta?}`, `TextResourceContents{text}`,
|
||||
//! `BlobResourceContents{blob}`;
|
||||
//! - `2025-11-25-schema.ts`: `ReadResourceResult extends Result`, тот же
|
||||
//! `ResourceContents`.
|
||||
//!
|
||||
//! Различия ревизий лежат во внешнем результате (cacheable-поля), который 3.6 не
|
||||
//! публикует, поэтому здесь строится только `contents`.
|
||||
|
||||
use base64::{Engine as _, engine::general_purpose::STANDARD};
|
||||
use crank_core::resource::ResourceKind;
|
||||
#[cfg(test)]
|
||||
use crank_core::resource::{ResourceFinding, ResourceLimits, ResourceMetadata};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// `contents[]` для ревизии `2026-07-28`.
|
||||
///
|
||||
/// Чистая функция границы ревизий: она не регистрирует MCP-метод и не рекламирует
|
||||
/// capability (D-17), а только транслирует уже провалидированную версию Resource.
|
||||
pub fn resource_contents_2026_07_28(
|
||||
uri: &str,
|
||||
kind: ResourceKind,
|
||||
mime_type: &str,
|
||||
bytes: &[u8],
|
||||
) -> Value {
|
||||
contents(uri, kind, mime_type, bytes)
|
||||
}
|
||||
|
||||
/// `contents[]` для ревизии `2025-11-25`.
|
||||
pub fn resource_contents_2025_11_25(
|
||||
uri: &str,
|
||||
kind: ResourceKind,
|
||||
mime_type: &str,
|
||||
bytes: &[u8],
|
||||
) -> Value {
|
||||
contents(uri, kind, mime_type, bytes)
|
||||
}
|
||||
|
||||
fn contents(uri: &str, kind: ResourceKind, mime_type: &str, bytes: &[u8]) -> Value {
|
||||
match kind {
|
||||
ResourceKind::Binary => json!({
|
||||
"uri": uri,
|
||||
"mimeType": mime_type,
|
||||
"blob": STANDARD.encode(bytes),
|
||||
}),
|
||||
ResourceKind::Text | ResourceKind::Json => json!({
|
||||
"uri": uri,
|
||||
"mimeType": mime_type,
|
||||
"text": String::from_utf8_lossy(bytes),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// Безопасный finding для MIME вне allowlist: только код и поле, без bytes.
|
||||
///
|
||||
/// Используется тестами границы (в production-коде 3.6 вызов не нужен).
|
||||
#[cfg(test)]
|
||||
pub(crate) fn resource_mime_finding(mime_type: &str) -> ResourceFinding {
|
||||
ResourceMetadata::mime_finding(mime_type, ResourceKind::Binary, &ResourceLimits::default())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "resource_wire/tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,195 @@
|
||||
//! BUILD-ONLY: in-crate проверки per-revision адаптера Story 3.6 (AT-3.6-06, таргет V).
|
||||
//!
|
||||
//! Статус на стадии Dev ATDD: **не зарегистрирован**. BUILD объявляет файл из production-модуля:
|
||||
//! ```text
|
||||
//! // crates/crank-community-mcp/src/resource_wire.rs
|
||||
//! #[cfg(test)] #[path = "resource_wire/tests.rs"] mod tests;
|
||||
//! ```
|
||||
//! Сегодня `src/resource_wire.rs` не существует, поэтому файл не компилируется и не исполняется;
|
||||
//! нулевая коллекция — не PASS. Внешний таргет `tests/unit.rs` этой крейты для приватного модуля
|
||||
//! невидим и намеренно не трогается (D-19).
|
||||
//!
|
||||
//! Минимальный будущий интерфейс (SPEC v4 §5, D-17): чистые per-revision функции
|
||||
//! `resource_wire::{resource_contents_2026_07_28, resource_contents_2025_11_25}` (без регистрации
|
||||
//! MCP-методов и без рекламы capability) вида
|
||||
//! `(uri: &str, kind: crank_core::resource::ResourceKind, mime_type: &str, bytes: &[u8]) -> Value`:
|
||||
//! ветка `contents[]` выбирается **typed kind**, а не разбором байтов (никакого content sniffing):
|
||||
//! для `ResourceKind::Binary` — `{uri, mimeType, blob: base64}` всегда, даже если байты
|
||||
//! декодируются как UTF-8; для text/JSON — `{uri, mimeType, text}`. Форма одинакова для обеих
|
||||
//! ревизий (`2026-07-28`, `2025-11-25`) со своими правилами ревизии.
|
||||
//! Регистрация `CAPABILITY_DESCRIPTORS`/`METHOD_DESCRIPTORS` не меняется, и `resources/read`
|
||||
//! сохраняет существующий ответ (existing GREEN, проверяется отдельной строкой).
|
||||
//!
|
||||
//! Запуск после BUILD: `cargo test -p crank-community-mcp --lib story36_ -- --test-threads=1`.
|
||||
|
||||
use super::{resource_contents_2025_11_25, resource_contents_2026_07_28};
|
||||
use crate::protocol::{CAPABILITY_DESCRIPTORS, METHOD_DESCRIPTORS};
|
||||
use crank_core::resource::ResourceKind;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
const TEXT: &[u8] = "Заголовок\n".as_bytes();
|
||||
const JSON_DOCUMENT: &[u8] = "{\"b\":1,\"a\":[1,2,3],\"дубликат\":1,\"дубликат\":2}".as_bytes();
|
||||
const BINARY_BYTES: &[u8] = &[0x00, 0xFF, 0x80, 0xC3, 0x28];
|
||||
/// Байты, которые **корректно** декодируются как UTF-8, но принадлежат kind=binary:
|
||||
/// выбор ветки не может зависеть от декодируемости (D-5/D-17).
|
||||
const BINARY_UTF8_MARKUP: &[u8] =
|
||||
b"<html><body><script>window.__c36='active'</script></body></html>";
|
||||
|
||||
struct Case {
|
||||
label: &'static str,
|
||||
uri: &'static str,
|
||||
kind: ResourceKind,
|
||||
mime: &'static str,
|
||||
bytes: &'static [u8],
|
||||
}
|
||||
|
||||
/// Один набор кейсов на обе ревизии: правила выбора ветки общие, форма `contents[]`
|
||||
/// отличается только правилами конкретной ревизии.
|
||||
fn cases() -> Vec<Case> {
|
||||
let mut cases = vec![
|
||||
Case {
|
||||
label: "text/plain",
|
||||
uri: "crank://adapter/text",
|
||||
kind: ResourceKind::Text,
|
||||
mime: "text/plain",
|
||||
bytes: TEXT,
|
||||
},
|
||||
Case {
|
||||
label: "json/application-json",
|
||||
uri: "crank://adapter/payload",
|
||||
kind: ResourceKind::Json,
|
||||
mime: "application/json",
|
||||
bytes: JSON_DOCUMENT,
|
||||
},
|
||||
];
|
||||
|
||||
for (label, mime, bytes) in [
|
||||
(
|
||||
"binary/octet-stream",
|
||||
"application/octet-stream",
|
||||
BINARY_UTF8_MARKUP,
|
||||
),
|
||||
("binary/image-png", "image/png", BINARY_BYTES),
|
||||
("binary/image-jpeg", "image/jpeg", BINARY_BYTES),
|
||||
("binary/image-gif", "image/gif", BINARY_BYTES),
|
||||
("binary/image-webp", "image/webp", BINARY_BYTES),
|
||||
("binary/image-svg", "image/svg+xml", BINARY_UTF8_MARKUP),
|
||||
("binary/text-html", "text/html", BINARY_UTF8_MARKUP),
|
||||
("binary/application-pdf", "application/pdf", BINARY_BYTES),
|
||||
] {
|
||||
cases.push(Case {
|
||||
label,
|
||||
uri: "crank://adapter/asset",
|
||||
kind: ResourceKind::Binary,
|
||||
mime,
|
||||
bytes,
|
||||
});
|
||||
}
|
||||
|
||||
cases
|
||||
}
|
||||
|
||||
fn assert_case(revision: &str, build: fn(&str, ResourceKind, &str, &[u8]) -> Value, case: &Case) {
|
||||
let label = format!("{revision}/{}", case.label);
|
||||
let contents = build(case.uri, case.kind, case.mime, case.bytes);
|
||||
|
||||
assert_eq!(
|
||||
contents["uri"],
|
||||
json!(case.uri),
|
||||
"{label}: uri must be preserved"
|
||||
);
|
||||
assert_eq!(
|
||||
contents["mimeType"],
|
||||
json!(case.mime),
|
||||
"{label}: adapter must report the declared MIME"
|
||||
);
|
||||
|
||||
match case.kind {
|
||||
ResourceKind::Binary => {
|
||||
assert!(
|
||||
contents.get("text").is_none(),
|
||||
"{label}: kind=binary must never carry a text branch, even for UTF-8-decodable bytes"
|
||||
);
|
||||
let blob = contents["blob"]
|
||||
.as_str()
|
||||
.unwrap_or_else(|| panic!("{label}: kind=binary must carry base64 `blob`"));
|
||||
assert_eq!(
|
||||
base64_decode(blob),
|
||||
case.bytes,
|
||||
"{label}: base64 must decode to the exact stored bytes"
|
||||
);
|
||||
}
|
||||
ResourceKind::Text | ResourceKind::Json => {
|
||||
assert!(
|
||||
contents.get("blob").is_none(),
|
||||
"{label}: text/JSON contents must not carry a blob branch"
|
||||
);
|
||||
assert_eq!(
|
||||
contents["text"],
|
||||
json!(std::str::from_utf8(case.bytes).expect("text/JSON fixtures must be UTF-8")),
|
||||
"{label}: text contents must be the exact stored bytes"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn story36_at06_negotiated_binary_adapter_both_revisions() {
|
||||
for case in cases() {
|
||||
assert_case("2026-07-28", resource_contents_2026_07_28, &case);
|
||||
assert_case("2025-11-25", resource_contents_2025_11_25, &case);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn story36_at06_unknown_or_unsupported_mime_is_a_safe_finding() {
|
||||
let finding = super::resource_mime_finding("application/zip");
|
||||
assert_eq!(finding.code(), "resource_mime_not_allowed");
|
||||
// finding не содержит bytes содержимого
|
||||
let serialized = serde_json::to_string(&finding).expect("finding must serialize");
|
||||
assert!(!serialized.contains("blob"));
|
||||
assert!(!serialized.contains("text"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn story38_resources_capability_is_registered_and_advertised() {
|
||||
// D-17 regression successor: 3.6 deliberately registered no Resources while the handler did not
|
||||
// exist; Story 3.8 implements `resources/list` + `resources/read`, so advertisement and dispatch
|
||||
// now carry the capability for both supported revisions.
|
||||
let capability_names: Vec<String> = CAPABILITY_DESCRIPTORS
|
||||
.iter()
|
||||
.map(|descriptor| format!("{:?}", descriptor.id).to_ascii_lowercase())
|
||||
.collect();
|
||||
assert!(
|
||||
capability_names
|
||||
.iter()
|
||||
.any(|name| name.contains("resource")),
|
||||
"CAPABILITY_DESCRIPTORS must carry the implemented Resources capability: {capability_names:?}"
|
||||
);
|
||||
let advertised_keys: Vec<String> = CAPABILITY_DESCRIPTORS
|
||||
.iter()
|
||||
.filter_map(|descriptor| descriptor.advertised.map(|(key, _)| key.to_owned()))
|
||||
.collect();
|
||||
assert!(
|
||||
advertised_keys.iter().any(|key| key == "resources"),
|
||||
"the implemented Resources capability must be advertised: {advertised_keys:?}"
|
||||
);
|
||||
let method_names: Vec<String> = METHOD_DESCRIPTORS
|
||||
.iter()
|
||||
.map(|descriptor| descriptor.name.to_owned())
|
||||
.collect();
|
||||
for method in ["resources/list", "resources/read"] {
|
||||
assert!(
|
||||
method_names.iter().any(|name| name == method),
|
||||
"{method} must be registered now that it is served: {method_names:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Независимый декодер: ожидание не берётся из адаптера.
|
||||
fn base64_decode(encoded: &str) -> Vec<u8> {
|
||||
use base64::Engine as _;
|
||||
base64::engine::general_purpose::STANDARD
|
||||
.decode(encoded)
|
||||
.expect("adapter must emit standard base64")
|
||||
}
|
||||
@@ -1,24 +1,20 @@
|
||||
use std::{collections::BTreeSet, sync::Arc};
|
||||
//! Domain of the shared `search_tools` command (Story 3.1, decision D-4).
|
||||
//!
|
||||
//! The wire-level shared entry that used to live in this file (`handle_catalog_tool_call`, carrying
|
||||
//! the request envelope, the response mode, the protocol revision and an `axum::Response`) is
|
||||
//! replaced by `protocol::command::handle_tools_command`: the neutral Tools boundary owns the
|
||||
//! command, while the catalog-search domain stays here and never sees the wire. The reserved
|
||||
//! `_crank_confirmation_token` handling, the proxy-revision check and the approval policy moved with
|
||||
//! the command, not with the domain.
|
||||
|
||||
use axum::{http::StatusCode, response::Response};
|
||||
use crank_core::{CorrelationContext, ToolAccessMode, search_tool_catalog};
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use crank_core::search_tool_catalog;
|
||||
use crank_registry::PublishedAgentCatalog;
|
||||
use crank_trace::{ErrorCategory, Stage, StageOutcome};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::{
|
||||
app::{
|
||||
AppState, handle_tool_call, resolve_generated_tool, take_confirmation_token,
|
||||
tool_error_response,
|
||||
},
|
||||
auth::VerifiedMachineCredential,
|
||||
jsonrpc::{jsonrpc_error, jsonrpc_result, request_id},
|
||||
manifest::{CALL_TOOL_NAME, SEARCH_TOOLS_NAME, searchable_tools},
|
||||
session::SessionState,
|
||||
tool_error::{McpControlError, control_tool_error_contract, execution_locale},
|
||||
transport::{ResponseMode, transport_response},
|
||||
};
|
||||
use crate::manifest::searchable_tools;
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct SearchToolsArguments {
|
||||
@@ -28,161 +24,18 @@ struct SearchToolsArguments {
|
||||
max_results: Option<usize>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct ProxyToolCallArguments {
|
||||
name: String,
|
||||
#[serde(default)]
|
||||
arguments: Value,
|
||||
catalog_revision: String,
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) async fn handle_catalog_tool_call(
|
||||
state: Arc<AppState>,
|
||||
session: &SessionState,
|
||||
message: &Value,
|
||||
response_mode: ResponseMode,
|
||||
credential: &VerifiedMachineCredential,
|
||||
catalog: &PublishedAgentCatalog,
|
||||
tool_name: &str,
|
||||
arguments: Value,
|
||||
transport_correlation: &CorrelationContext,
|
||||
) -> Response {
|
||||
let transport_request_id = transport_correlation.request_id().as_str();
|
||||
match catalog.tool_selection_policy.mode {
|
||||
ToolAccessMode::Direct => {
|
||||
execute_catalog_tool(
|
||||
state,
|
||||
session,
|
||||
message,
|
||||
response_mode,
|
||||
credential,
|
||||
catalog,
|
||||
tool_name,
|
||||
arguments,
|
||||
transport_correlation,
|
||||
)
|
||||
.await
|
||||
}
|
||||
ToolAccessMode::Search if tool_name == SEARCH_TOOLS_NAME => {
|
||||
handle_search_tools(message, response_mode, session, catalog, arguments)
|
||||
}
|
||||
ToolAccessMode::Search if tool_name == CALL_TOOL_NAME => {
|
||||
let proxy: ProxyToolCallArguments = match serde_json::from_value(arguments) {
|
||||
Ok(proxy) => proxy,
|
||||
Err(error) => {
|
||||
return invalid_arguments_response(
|
||||
message,
|
||||
response_mode,
|
||||
&session.protocol_version,
|
||||
error.to_string(),
|
||||
);
|
||||
}
|
||||
};
|
||||
if proxy.catalog_revision != catalog_revision(catalog) {
|
||||
return tool_error_response(
|
||||
message,
|
||||
response_mode,
|
||||
&session.protocol_version,
|
||||
control_tool_error_contract(
|
||||
McpControlError::CatalogRevisionChanged,
|
||||
transport_request_id,
|
||||
transport_correlation.trace_id().as_str(),
|
||||
execution_locale(message),
|
||||
),
|
||||
);
|
||||
}
|
||||
execute_catalog_tool(
|
||||
state,
|
||||
session,
|
||||
message,
|
||||
response_mode,
|
||||
credential,
|
||||
catalog,
|
||||
&proxy.name,
|
||||
proxy.arguments,
|
||||
transport_correlation,
|
||||
)
|
||||
.await
|
||||
}
|
||||
ToolAccessMode::Search => {
|
||||
tool_not_found_response(message, response_mode, &session.protocol_version, tool_name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
async fn execute_catalog_tool(
|
||||
state: Arc<AppState>,
|
||||
session: &SessionState,
|
||||
message: &Value,
|
||||
response_mode: ResponseMode,
|
||||
credential: &VerifiedMachineCredential,
|
||||
catalog: &PublishedAgentCatalog,
|
||||
tool_name: &str,
|
||||
mut arguments: Value,
|
||||
transport_correlation: &CorrelationContext,
|
||||
) -> Response {
|
||||
let resolve_span = Stage::McpToolsResolve.span();
|
||||
let resolved = resolve_span.in_scope(|| resolve_generated_tool(&catalog.tools, tool_name));
|
||||
let resolved = match resolved {
|
||||
Some(resolved) => {
|
||||
StageOutcome::Success.record(&resolve_span);
|
||||
drop(resolve_span);
|
||||
resolved
|
||||
}
|
||||
None => {
|
||||
StageOutcome::Error.record(&resolve_span);
|
||||
ErrorCategory::Catalog.record(&resolve_span);
|
||||
drop(resolve_span);
|
||||
return tool_not_found_response(
|
||||
message,
|
||||
response_mode,
|
||||
&session.protocol_version,
|
||||
tool_name,
|
||||
);
|
||||
}
|
||||
};
|
||||
let confirmation_token = take_confirmation_token(&mut arguments);
|
||||
handle_tool_call(
|
||||
state,
|
||||
session,
|
||||
message,
|
||||
response_mode,
|
||||
credential,
|
||||
resolved,
|
||||
arguments,
|
||||
confirmation_token,
|
||||
transport_correlation,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
fn handle_search_tools(
|
||||
message: &Value,
|
||||
response_mode: ResponseMode,
|
||||
session: &SessionState,
|
||||
/// The domain result of the catalog search tool, without any wire wrapping.
|
||||
///
|
||||
/// The error is the invalid-params detail the adapter answers with; a domain failure never carries a
|
||||
/// response shape of its own.
|
||||
pub(crate) fn search_tools_outcome(
|
||||
catalog: &PublishedAgentCatalog,
|
||||
arguments: Value,
|
||||
) -> Response {
|
||||
let search: SearchToolsArguments = match serde_json::from_value(arguments) {
|
||||
Ok(search) => search,
|
||||
Err(error) => {
|
||||
return invalid_arguments_response(
|
||||
message,
|
||||
response_mode,
|
||||
&session.protocol_version,
|
||||
error.to_string(),
|
||||
);
|
||||
}
|
||||
};
|
||||
) -> Result<Value, String> {
|
||||
let search: SearchToolsArguments =
|
||||
serde_json::from_value(arguments).map_err(|error| error.to_string())?;
|
||||
if search.query.trim().is_empty() {
|
||||
return invalid_arguments_response(
|
||||
message,
|
||||
response_mode,
|
||||
&session.protocol_version,
|
||||
"query must not be empty".to_owned(),
|
||||
);
|
||||
return Err("query must not be empty".to_owned());
|
||||
}
|
||||
let known_group_ids = catalog
|
||||
.tool_selection_policy
|
||||
@@ -195,12 +48,7 @@ fn handle_search_tools(
|
||||
.iter()
|
||||
.find(|group_id| !known_group_ids.contains(group_id.as_str()))
|
||||
{
|
||||
return invalid_arguments_response(
|
||||
message,
|
||||
response_mode,
|
||||
&session.protocol_version,
|
||||
format!("unknown tool group {group_id}"),
|
||||
);
|
||||
return Err(format!("unknown tool group {group_id}"));
|
||||
}
|
||||
|
||||
let configured_limit = catalog.tool_selection_policy.search.max_results;
|
||||
@@ -223,62 +71,9 @@ fn handle_search_tools(
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let result = json!({
|
||||
"catalog_revision": catalog_revision(catalog),
|
||||
|
||||
Ok(json!({
|
||||
"catalog_revision": catalog.catalog_revision,
|
||||
"tools": tools,
|
||||
});
|
||||
let text = serde_json::to_string_pretty(&result).unwrap_or_else(|_| result.to_string());
|
||||
|
||||
transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
json!({
|
||||
"content": [{"type": "text", "text": text}],
|
||||
"structuredContent": result,
|
||||
"isError": false
|
||||
}),
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
)
|
||||
}
|
||||
|
||||
fn catalog_revision(catalog: &PublishedAgentCatalog) -> String {
|
||||
catalog.catalog_revision.clone()
|
||||
}
|
||||
|
||||
fn invalid_arguments_response(
|
||||
message: &Value,
|
||||
response_mode: ResponseMode,
|
||||
protocol_version: &str,
|
||||
detail: String,
|
||||
) -> Response {
|
||||
transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(request_id(message), -32602, detail),
|
||||
response_mode,
|
||||
None,
|
||||
Some(protocol_version),
|
||||
)
|
||||
}
|
||||
|
||||
fn tool_not_found_response(
|
||||
message: &Value,
|
||||
response_mode: ResponseMode,
|
||||
protocol_version: &str,
|
||||
tool_name: &str,
|
||||
) -> Response {
|
||||
transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(
|
||||
request_id(message),
|
||||
-32602,
|
||||
format!("tool {tool_name} was not found"),
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(protocol_version),
|
||||
)
|
||||
}))
|
||||
}
|
||||
@@ -16,9 +16,7 @@ use futures_util::stream;
|
||||
use reqwest::Url;
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::jsonrpc::{
|
||||
CURRENT_PROTOCOL_VERSION, DEFAULT_PROTOCOL_VERSION, negotiated_protocol_version,
|
||||
};
|
||||
use crate::jsonrpc::{LEGACY_PROTOCOL_VERSION, negotiated_protocol_version};
|
||||
|
||||
pub(super) const HEADER_MCP_SESSION_ID: &str = "MCP-Session-Id";
|
||||
pub(super) const HEADER_MCP_PROTOCOL_VERSION: &str = "MCP-Protocol-Version";
|
||||
@@ -99,13 +97,29 @@ pub(super) fn validate_origin(
|
||||
Err(StatusCode::FORBIDDEN)
|
||||
}
|
||||
|
||||
/// The media types of the `Accept` header, in the client's preference order.
|
||||
///
|
||||
/// `None` means the header is absent or not text; both are the caller's own admission decision.
|
||||
fn accepted_media_types(headers: &HeaderMap) -> Option<Vec<String>> {
|
||||
let accept = headers.get(ACCEPT)?.to_str().ok()?;
|
||||
Some(
|
||||
accept
|
||||
.split(',')
|
||||
.map(|part| {
|
||||
part.split(';')
|
||||
.next()
|
||||
.unwrap_or_default()
|
||||
.trim()
|
||||
.to_ascii_lowercase()
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn negotiate_post_response_mode(
|
||||
headers: &HeaderMap,
|
||||
) -> Result<ResponseMode, StatusCode> {
|
||||
let Some(accept) = headers.get(ACCEPT) else {
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
};
|
||||
let Ok(accept) = accept.to_str() else {
|
||||
let Some(media_types) = accepted_media_types(headers) else {
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
};
|
||||
|
||||
@@ -113,14 +127,7 @@ pub(super) fn negotiate_post_response_mode(
|
||||
let mut saw_sse = false;
|
||||
let mut preferred = None;
|
||||
|
||||
for part in accept.split(',') {
|
||||
let media_type = part
|
||||
.split(';')
|
||||
.next()
|
||||
.unwrap_or_default()
|
||||
.trim()
|
||||
.to_ascii_lowercase();
|
||||
|
||||
for media_type in media_types {
|
||||
match media_type.as_str() {
|
||||
"application/json" => {
|
||||
saw_json = true;
|
||||
@@ -146,22 +153,12 @@ pub(super) fn negotiate_post_response_mode(
|
||||
}
|
||||
|
||||
pub(super) fn validate_get_accept_header(headers: &HeaderMap) -> Result<(), StatusCode> {
|
||||
let Some(accept) = headers.get(ACCEPT) else {
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
};
|
||||
let Ok(accept) = accept.to_str() else {
|
||||
let Some(media_types) = accepted_media_types(headers) else {
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
};
|
||||
|
||||
if accept
|
||||
.split(',')
|
||||
.map(|part| {
|
||||
part.split(';')
|
||||
.next()
|
||||
.unwrap_or_default()
|
||||
.trim()
|
||||
.to_ascii_lowercase()
|
||||
})
|
||||
if media_types
|
||||
.iter()
|
||||
.any(|media_type| media_type == "text/event-stream")
|
||||
{
|
||||
return Ok(());
|
||||
@@ -170,31 +167,50 @@ pub(super) fn validate_get_accept_header(headers: &HeaderMap) -> Result<(), Stat
|
||||
Err(StatusCode::NOT_ACCEPTABLE)
|
||||
}
|
||||
|
||||
pub(super) fn protocol_version_from_headers(headers: &HeaderMap) -> Result<String, StatusCode> {
|
||||
let Some(version) = headers.get(HEADER_MCP_PROTOCOL_VERSION) else {
|
||||
return Ok(DEFAULT_PROTOCOL_VERSION.to_owned());
|
||||
/// Read a singleton identity carrier.
|
||||
///
|
||||
/// Pinned HTTP semantics allow repeated header lines, so the ingress must decide what a repeated
|
||||
/// carrier means instead of silently reading the first value. Identical duplicates carry no ambiguity
|
||||
/// and collapse deterministically to one value; conflicting duplicates are an ambiguous identity and
|
||||
/// are rejected. A non-text value is rejected as well.
|
||||
pub(super) fn singleton_header<'a>(
|
||||
headers: &'a HeaderMap,
|
||||
name: &str,
|
||||
) -> Result<Option<&'a str>, StatusCode> {
|
||||
let mut values = headers.get_all(name).iter();
|
||||
let Some(first) = values.next() else {
|
||||
return Ok(None);
|
||||
};
|
||||
let Ok(version) = version.to_str() else {
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
};
|
||||
|
||||
if negotiated_protocol_version(version).is_some() {
|
||||
return Ok(version.to_owned());
|
||||
let first = first.to_str().map_err(|_| StatusCode::BAD_REQUEST)?;
|
||||
for value in values {
|
||||
let value = value.to_str().map_err(|_| StatusCode::BAD_REQUEST)?;
|
||||
if value != first {
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
|
||||
Err(StatusCode::BAD_REQUEST)
|
||||
Ok(Some(first))
|
||||
}
|
||||
|
||||
/// Negotiated revision carried by the request header.
|
||||
///
|
||||
/// A missing header is reported as `None` rather than being replaced by an implicit default: the
|
||||
/// withdrawn `2025-03-26` fallback is no longer served. Era resolution (header vs body identity,
|
||||
/// mismatch and unsupported handling) happens in the request pipeline. Conflicting duplicate
|
||||
/// carriers are rejected here, so no caller can resolve an ambiguous identity to the first value.
|
||||
pub(super) fn protocol_version_from_headers(
|
||||
headers: &HeaderMap,
|
||||
) -> Result<Option<String>, StatusCode> {
|
||||
Ok(singleton_header(headers, HEADER_MCP_PROTOCOL_VERSION)?.map(str::to_owned))
|
||||
}
|
||||
|
||||
pub(super) fn validate_session_protocol_version(
|
||||
headers: &HeaderMap,
|
||||
negotiated_session_version: &str,
|
||||
) -> Result<(), StatusCode> {
|
||||
let Some(version) = headers.get(HEADER_MCP_PROTOCOL_VERSION) else {
|
||||
let Some(version) = singleton_header(headers, HEADER_MCP_PROTOCOL_VERSION)? else {
|
||||
return Ok(());
|
||||
};
|
||||
let Ok(version) = version.to_str() else {
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
};
|
||||
|
||||
if negotiated_protocol_version(version).is_none() {
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
@@ -208,14 +224,7 @@ pub(super) fn validate_session_protocol_version(
|
||||
}
|
||||
|
||||
pub(super) fn session_id_from_headers(headers: &HeaderMap) -> Result<Option<String>, StatusCode> {
|
||||
let Some(session_id) = headers.get(HEADER_MCP_SESSION_ID) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let Ok(session_id) = session_id.to_str() else {
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
};
|
||||
|
||||
Ok(Some(session_id.to_owned()))
|
||||
Ok(singleton_header(headers, HEADER_MCP_SESSION_ID)?.map(str::to_owned))
|
||||
}
|
||||
|
||||
pub(super) fn json_response(
|
||||
@@ -242,7 +251,7 @@ pub(super) fn json_response(
|
||||
response.headers_mut().insert(
|
||||
HEADER_MCP_PROTOCOL_VERSION,
|
||||
HeaderValue::from_str(protocol_version)
|
||||
.unwrap_or_else(|_| HeaderValue::from_static(CURRENT_PROTOCOL_VERSION)),
|
||||
.unwrap_or_else(|_| HeaderValue::from_static(LEGACY_PROTOCOL_VERSION)),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -258,8 +267,7 @@ pub(super) fn transport_response(
|
||||
) -> Response {
|
||||
let outcome = payload_outcome(&payload);
|
||||
if status == StatusCode::OK && matches!(response_mode, ResponseMode::Sse) {
|
||||
let payload = payload.to_string();
|
||||
let stream = stream::once(async move { Ok(Event::default().data(payload)) });
|
||||
let stream = stream::iter([Ok(Event::default().data(payload.to_string()))]);
|
||||
|
||||
let mut response = sse_response(status, stream, session_id, protocol_version);
|
||||
if let Some(outcome) = outcome {
|
||||
@@ -319,7 +327,7 @@ where
|
||||
response.headers_mut().insert(
|
||||
HEADER_MCP_PROTOCOL_VERSION,
|
||||
HeaderValue::from_str(protocol_version)
|
||||
.unwrap_or_else(|_| HeaderValue::from_static(CURRENT_PROTOCOL_VERSION)),
|
||||
.unwrap_or_else(|_| HeaderValue::from_static(LEGACY_PROTOCOL_VERSION)),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user