//! 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, #[serde(default)] pub(crate) limit: Option, } /// 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, next_cursor: Option, }, 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, workspace_slug: &str, agent_slug: &str, revision: &str, command: ResourcesListCommand, ) -> Result<(Vec, Option), 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, 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, 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, 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 = 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, context: &ServiceContext<'_>, workspace_id: &crank_core::WorkspaceId, bindings: &[AgentResourceBinding], revision: &str, uri: &str, ) -> Option { 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> { 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 { 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 { let value = match schema.get("type")?.as_str()? { "string" | "enum" => Value::String(raw.to_owned()), "integer" => Value::Number(raw.parse::().ok()?.into()), "number" => serde_json::Number::from_f64(raw.parse::().ok()?).map(Value::Number)?, "boolean" => Value::Bool(raw.parse::().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, 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 { 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 { 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, workspace_id: &crank_core::WorkspaceId, binding: &AgentResourceBinding, ) -> Result, 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 { 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 ); } }