Files
crank/crates/crank-community-mcp/src/protocol/registry.rs
T
bsodfather 54ce770682
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
feat(epic3): deliver the accepted Epic 3 scope through Story 3.17
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.
2026-10-25 09:08:22 +00:00

522 lines
22 KiB
Rust

//! 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;