//! 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, /// `subscriptions/listen` of the modern revision: a *client-sent* request that opens the /// notification stream (Story 3.19). It is a dispatch-only registration without an advertisement /// fragment because the pinned modern schema has no server `subscriptions` capability object; /// there is no such method in the legacy revision at all. Subscriptions, /// `logging` server capability: safe structured `notifications/message` events of the negotiated /// client context (Story 3.18). Advertised in both revisions; the pinned modern revision carries /// the level per request in `_meta` and marks the capability deprecated (SEP-2577). Logging, /// `logging/setLevel` as the *legacy* client request that sets a session level. It is a /// dispatch-only registration without an advertisement fragment because the pinned modern /// revision has no such method: there the per-request `_meta` key replaces it, so the same wire /// name is a wrong-era request and must never be served. LoggingSetLevel, 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, /// `subscriptions/listen`: open the long-lived modern notification stream and deliver the /// Resource/Prompt list-change signals the client opted in to (Story 3.19). SubscriptionsListen, /// `logging/setLevel`: validate the pinned level and record it for this legacy session, so the /// adapter can deliver safe structured `notifications/message` events of that context /// (Story 3.18). The handler never widens the accepted vocabulary and never echoes the input. LoggingSetLevel, Ping, Discover, Lifecycle, /// `notifications/cancelled`: the legacy client cancels a `tools/call` it already issued /// (Story 3.4). The handler only routes the id to the owner's in-flight call; it never widens /// what may be cancelled and never authorizes by the progress token. Cancelled, } #[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, pub(crate) deprecated: Option, pub(crate) sub_features: FeatureSet, pub(crate) advertised: Option, 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, /// 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, } 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 { let mut seen_capabilities: Vec = 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::>(); 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"]), // Story 3.5: the adapter emits `notifications/tools/list_changed` from the committed // published Tool bindings of the Agent snapshot, so the declaration is now true. advertised: Some(("tools", &[("listChanged", true)])), revisions: MODERN_AND_LEGACY, }, CapabilityIdDescriptor { id: CapabilityId::Resources, roster: Roster::Server, kind: Kind::Capability, extension: None, deprecated: None, sub_features: FeatureSet(&["subscribe", "listChanged"]), // Story 3.19: the server really emits `notifications/resources/list_changed`; URI-content // subscriptions (`subscribe`) remain unimplemented and are still advertised as false. advertised: Some(("resources", &[("subscribe", false), ("listChanged", true)])), revisions: MODERN_AND_LEGACY, }, CapabilityIdDescriptor { id: CapabilityId::Prompts, roster: Roster::Server, kind: Kind::Capability, extension: None, deprecated: None, sub_features: FeatureSet(&["listChanged"]), // Story 3.19: the server really emits `notifications/prompts/list_changed`. advertised: Some(("prompts", &[("listChanged", true)])), 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 { // Story 3.18: the standard `logging` declaration of both approved revisions. The pinned // modern revision marks it deprecated (SEP-2577) but keeps it in the schema for at least // twelve months, and `notifications/message` remains the only log channel there; the legacy // revision additionally serves `logging/setLevel`. id: CapabilityId::Logging, roster: Roster::Server, kind: Kind::Capability, extension: None, deprecated: None, // The pinned schema declares `logging` as an open object with no named sub-features. sub_features: FeatureSet(&[]), advertised: Some(("logging", &[])), revisions: MODERN_AND_LEGACY, }, CapabilityIdDescriptor { // Dispatch-only registration of the legacy `logging/setLevel` request: it is a client // request, not an advertised server capability, and it does not exist in the modern schema. id: CapabilityId::LoggingSetLevel, roster: Roster::Server, kind: Kind::Method, extension: None, deprecated: None, sub_features: FeatureSet(&[]), advertised: None, revisions: LEGACY_ONLY, }, CapabilityIdDescriptor { // Story 3.19: dispatch-only registration of the modern `subscriptions/listen` request. The // client sends it; the pinned modern schema declares no server `subscriptions` capability // object, so it carries no advertisement fragment. The legacy revision has no such method. id: CapabilityId::Subscriptions, roster: Roster::Client, kind: Kind::Method, extension: None, deprecated: None, sub_features: FeatureSet(&[]), advertised: None, revisions: MODERN_ONLY, }, 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 { // Story 3.18: the legacy client request that sets the log level of its session. It declares // the level, not a server-side name, so only the method header applies; the pinned modern // revision has no such method at all (per-request `_meta` replaces it). name: "logging/setLevel", capability: CapabilityId::LoggingSetLevel, kind: Kind::Method, required_headers: HEADERS_METHOD_ONLY, handler: MethodHandler::LoggingSetLevel, }, MethodDescriptor { // Story 3.19: the modern long-lived notification stream. It declares the notification filter // in its params, not a server-side name, so only the method header applies. The legacy // revision opens its notification stream with `GET` instead, so this name is a wrong-era // request there and must never be served. name: "subscriptions/listen", capability: CapabilityId::Subscriptions, kind: Kind::Method, required_headers: HEADERS_METHOD_ONLY, handler: MethodHandler::SubscriptionsListen, }, 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, }, MethodDescriptor { // Story 3.4: the legacy revision's client-side cancellation of a request it issued. The // pinned modern revision has no client-to-server notification over Streamable HTTP (closing // the response stream is its cancellation signal), so this name exists in the legacy era // only. It is a dispatch-only notification registration and advertises nothing. name: "notifications/cancelled", capability: CapabilityId::LegacyLifecycle, kind: Kind::Notification, required_headers: HEADERS_NONE, handler: MethodHandler::Cancelled, }, ]; #[cfg(test)] #[path = "registry_tests.rs"] mod tests;