Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,14 @@ check. `registry::OAuthBundle` is the stored refresh bundle's shape.
the authorization server shows on its consent screen; it defaults to
`DEFAULT_CLIENT_NAME` (`TinyMCP`).

Dynamic registration asks for a confidential client (`client_secret_post`)
when the authorization server's `token_endpoint_auth_methods_supported` lists
it or lists nothing, and for a public client (`none`) when it lists `none` but
not `client_secret_post`, whatever else it lists.
A public client stores no secret, and neither the code exchange nor a refresh
sends one. A server that accepts neither is not offered a sign-in: `detect`
reports a static token and `begin` refuses before registering.

OAuth discovery starts from the 401. When its challenge names
`resource_metadata`, that protected-resource metadata is followed. When a
Bearer challenge names none, the server's origin is checked in this order:
Expand Down
5 changes: 5 additions & 0 deletions crates/tinymcp-bus/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,11 @@ so a host can tell a tool that only reads from one that changes something
before it calls it. The field is optional and omitted when absent, and
`StaticScrubTools` scrubs it like the rest of a tool's metadata.

Contract 1.29 adds the optional `token_endpoint_auth_methods_supported` on
`AuthorizationServerMetadata`, so a client can register as a public client
(`none`) with an authorization server that accepts nothing else. The field is
omitted when absent.

Contract 1.30 adds `McpClientConfig::local_oauth_origins` and turns the OAuth
endpoint guard on by default. The authorization, registration and token
endpoints a server advertises are requested from the host, so they must now be
Expand Down
37 changes: 36 additions & 1 deletion crates/tinymcp-bus/src/transport/mod_tests.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
//! The remote tool's wire form, annotations included.
//! The transport wire forms: remote tool annotations and authorization-server
//! metadata.

use serde_json::json;

Expand Down Expand Up @@ -51,3 +52,37 @@ fn absent_annotations_stay_off_the_wire() -> TestResult {
assert_eq!(serde_json::from_value::<McpRemoteTool>(wire)?, annotated);
Ok(())
}

#[test]
fn an_authorization_servers_token_endpoint_auth_methods_are_kept() -> TestResult {
let metadata: AuthorizationServerMetadata = serde_json::from_value(json!({
"issuer": "https://auth.test",
"token_endpoint_auth_methods_supported": ["none"],
}))?;

assert_eq!(
metadata.token_endpoint_auth_methods_supported,
Some(vec!["none".to_string()])
);
let wire = serde_json::to_value(&metadata)?;
assert_eq!(
wire["token_endpoint_auth_methods_supported"],
json!(["none"])
);
assert_eq!(
serde_json::from_value::<AuthorizationServerMetadata>(wire)?,
metadata
);
Ok(())
}

#[test]
fn absent_token_endpoint_auth_methods_stay_off_the_wire() -> TestResult {
let metadata: AuthorizationServerMetadata =
serde_json::from_value(json!({ "issuer": "https://auth.test" }))?;

assert_eq!(metadata.token_endpoint_auth_methods_supported, None);
let wire = serde_json::to_value(&metadata)?;
assert!(wire.get("token_endpoint_auth_methods_supported").is_none());
Ok(())
}
5 changes: 5 additions & 0 deletions crates/tinymcp-bus/src/transport/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -427,6 +427,11 @@ pub struct AuthorizationServerMetadata {
/// The PKCE code-challenge methods the server supports.
#[serde(default)]
pub code_challenge_methods_supported: Vec<String>,
/// How clients may authenticate at the token endpoint, for example
/// `client_secret_post` or `none` for a public client. `None` when the
/// server does not say.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub token_endpoint_auth_methods_supported: Option<Vec<String>>,
}

/// A parsed `WWW-Authenticate` challenge from a 401.
Expand Down
2 changes: 2 additions & 0 deletions crates/tinymcp-bus/src/version/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@
/// `StdioSandboxConfig::enforcement` (`StdioSandboxEnforcement`), letting the
/// host choose `Declared` for a backend with partial enforcement; the default
/// stays `Enforced`. 1.28 adds the optional `annotations` on `McpRemoteTool`.
/// 1.29 adds the optional `token_endpoint_auth_methods_supported` on
/// `AuthorizationServerMetadata`.
/// 1.30 adds `McpClientConfig::local_oauth_origins` and turns the OAuth
/// endpoint guard on by default: endpoints a server advertises must be `https`
/// and public unless the operator declared that server local.
Expand Down
109 changes: 91 additions & 18 deletions crates/tinymcp/src/registry/oauth/flow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -276,18 +276,13 @@ impl OAuthFlow {

// Chosen by capability rather than by position: the first advertised
// authorization server may be incomplete while a later one is usable.
let metadata = context
let (metadata, auth_method) = context
.authorization_server_metadata
.iter()
.find(|metadata| can_drive_sign_in(metadata))
.and_then(|metadata| client_auth_method(metadata).map(|method| (metadata, method)))
.ok_or_else(|| Error::AuthDiscovery {
detail: if context.authorization_server_metadata.is_empty() {
"the server advertises no authorization server".to_string()
} else {
"no authorization server offers an authorize endpoint, a token endpoint, and \
dynamic client registration together"
.to_string()
},
detail: no_drivable_server_reason(&context.authorization_server_metadata),
challenge: Box::new(context.challenge.clone()),
})?;

Expand Down Expand Up @@ -315,6 +310,7 @@ impl OAuthFlow {
registration_http.as_ref().unwrap_or(&self.http),
&registration_endpoint,
redirect_uri,
auth_method,
)
.await?;

Expand Down Expand Up @@ -525,22 +521,28 @@ impl OAuthFlow {

/// Registers a client dynamically, per RFC 7591.
///
/// A confidential client is requested, and the secret is kept when one is
/// issued: some servers issue one regardless of what was asked for, and the
/// token exchange then fails without it.
/// A confidential client keeps the secret when one is issued: some servers
/// issue one regardless of what was asked for, and the token exchange then
/// fails without it. A public client keeps none, so neither the exchange
/// nor a refresh sends one.
async fn register_client(
&self,
http: &reqwest::Client,
registration_endpoint: &str,
redirect_uri: &str,
auth_method: ClientAuthMethod,
) -> Result<(String, Option<String>)> {
let body = json!({
"client_name": self.client_name,
"redirect_uris": [redirect_uri],
"grant_types": ["authorization_code", "refresh_token"],
"response_types": ["code"],
"token_endpoint_auth_method": "client_secret_post",
"token_endpoint_auth_method": auth_method.as_str(),
});
tracing::debug!(
auth_method = auth_method.as_str(),
"registering an oauth client"
);

let response = http
.post(registration_endpoint)
Expand Down Expand Up @@ -575,28 +577,99 @@ impl OAuthFlow {
.ok_or_else(|| Error::malformed("client registration returned no client_id"))?
.to_string();

let client_secret = registered
.get("client_secret")
.and_then(Value::as_str)
.map(ToString::to_string);
let client_secret = match auth_method {
ClientAuthMethod::SecretPost => registered
.get("client_secret")
.and_then(Value::as_str)
.map(ToString::to_string),
ClientAuthMethod::None => None,
};

Ok((client_id, client_secret))
}
}

/// How a registered client authenticates at the token endpoint.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ClientAuthMethod {
/// A confidential client sending its secret in the form body.
SecretPost,
/// A public client sending no secret.
None,
}

impl ClientAuthMethod {
/// The RFC 7591 `token_endpoint_auth_method` value.
fn as_str(self) -> &'static str {
match self {
Self::SecretPost => "client_secret_post",
Self::None => "none",
}
}
}

/// The method to register with: `client_secret_post` when the server lists it
/// or lists nothing, `none` when it lists that instead, and `None` when it
/// accepts neither.
fn client_auth_method(
metadata: &tinymcp_bus::AuthorizationServerMetadata,
) -> Option<ClientAuthMethod> {
let Some(methods) = metadata
.token_endpoint_auth_methods_supported
.as_deref()
.filter(|methods| !methods.is_empty())
else {
return Some(ClientAuthMethod::SecretPost);
};
let lists = |method: ClientAuthMethod| methods.iter().any(|listed| listed == method.as_str());
[ClientAuthMethod::SecretPost, ClientAuthMethod::None]
.into_iter()
.find(|method| lists(*method))
}

/// Why no advertised authorization server can drive a sign-in.
pub(super) fn no_drivable_server_reason(
metadata: &[tinymcp_bus::AuthorizationServerMetadata],
) -> String {
if metadata.is_empty() {
return "the server advertises no authorization server".to_string();
}
let refused_only_for_auth_method = metadata.iter().any(|server| {
has_sign_in_endpoints(server)
&& supports_authorization_code(server)
&& client_auth_method(server).is_none()
});
if refused_only_for_auth_method {
"no authorization server accepts client_secret_post or none at its token endpoint"
.to_string()
} else {
"no authorization server offers an authorize endpoint, a token endpoint, and dynamic \
client registration together"
.to_string()
}
}

/// Whether this flow can run a sign-in against an authorization server: it
/// advertises an authorize endpoint, a token endpoint and dynamic client
/// registration, and accepts an authorization code.
/// registration, accepts an authorization code, and accepts a client that
/// authenticates with `client_secret_post` or `none`.
///
/// [`OAuthFlow::detect`] and [`OAuthFlow::begin`] both ask this one question,
/// so detection never offers a sign-in that `begin` would then refuse — a
/// server with no registration endpoint (Slack's, for one) reads as wanting a
/// static token, not as a Sign in button that leads nowhere.
fn can_drive_sign_in(metadata: &tinymcp_bus::AuthorizationServerMetadata) -> bool {
has_sign_in_endpoints(metadata)
&& supports_authorization_code(metadata)
&& client_auth_method(metadata).is_some()
}

/// Whether an authorization server advertises the authorize, token and
/// registration endpoints the flow posts to.
fn has_sign_in_endpoints(metadata: &tinymcp_bus::AuthorizationServerMetadata) -> bool {
metadata.authorization_endpoint.is_some()
&& metadata.token_endpoint.is_some()
&& metadata.registration_endpoint.is_some()
&& supports_authorization_code(metadata)
}

/// Whether an authorization server will accept an authorization code.
Expand Down
Loading
Loading