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
@@ -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
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user