Skip to main content

mcp_server_core/
caller.rs

1//! Who made a request. The bearer guard adds a [`Caller`] to every request it lets through.
2//!
3//! ```
4//! use mcp_server_core::axum::http::request::Parts;
5//! use mcp_server_core::caller::Caller;
6//!
7//! /// The subject to attribute a change to, from a tool's `Extension<Parts>` argument.
8//! fn who(parts: &Parts) -> Option<&str> {
9//!     parts.extensions.get::<Caller>().map(|c| c.subject.as_str())
10//! }
11//! ```
12
13/// Who made a request, and how they proved it.
14#[derive(Debug, Clone, PartialEq, Eq)]
15#[non_exhaustive]
16pub struct Caller {
17    /// Who signed in: `owner` for the owner's password, `key:<16 hex digits>` for a person's own
18    /// credential, `static` for the static token, or what a custom verifier names
19    /// ([`CredentialVerifier::subject`](crate::credential::CredentialVerifier::subject)).
20    pub subject: String,
21    /// How the request was authenticated.
22    pub via: Via,
23}
24
25/// How a request was authenticated.
26#[derive(Debug, Clone, PartialEq, Eq)]
27#[non_exhaustive]
28pub enum Via {
29    /// An OAuth access token this server issued, to this client.
30    OAuth {
31        /// The client the token was issued to.
32        client_id: Option<String>,
33    },
34    /// The person's credential sent directly as the bearer token.
35    Credential,
36    /// The static token (`MCP_AUTH_TOKEN`).
37    StaticToken,
38}
39
40/// The subject of requests made with the static token.
41pub const STATIC_SUBJECT: &str = "static";
42
43impl Caller {
44    /// A caller, for middleware of your own or tests.
45    pub fn new(subject: impl Into<String>, via: Via) -> Self {
46        Caller {
47            subject: subject.into(),
48            via,
49        }
50    }
51
52    /// How the audit log names the way in: `oauth:<client_id>`, `oauth`, `credential` or
53    /// `static`.
54    pub fn audit_label(&self) -> String {
55        match &self.via {
56            Via::OAuth {
57                client_id: Some(id),
58            } => format!("oauth:{id}"),
59            Via::OAuth { client_id: None } => "oauth".into(),
60            Via::Credential => "credential".into(),
61            Via::StaticToken => STATIC_SUBJECT.into(),
62        }
63    }
64}
65
66#[cfg(test)]
67mod tests {
68    use super::*;
69
70    #[test]
71    fn audit_labels_name_the_way_in() {
72        let c = |via| Caller::new("owner", via).audit_label();
73        assert_eq!(
74            c(Via::OAuth {
75                client_id: Some("c1".into())
76            }),
77            "oauth:c1"
78        );
79        assert_eq!(c(Via::OAuth { client_id: None }), "oauth");
80        assert_eq!(c(Via::Credential), "credential");
81        assert_eq!(c(Via::StaticToken), "static");
82    }
83}