car-connectors 0.25.0

Remote MCP connectors for the Common Agent Runtime — connect to remote MCP servers over HTTP, register their tools, and route calls through CAR's governance layer (validator, policy, eventlog).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
//! OAuth 2.1 client for remote MCP connectors (Phase 2).
//!
//! Implements the MCP authorization flow for a client connecting to a
//! protected remote MCP server:
//!
//! 1. **Discovery** — Protected Resource Metadata (RFC 9728) to find the
//!    server's authorization server(s), then Authorization Server
//!    Metadata (RFC 8414 / OpenID discovery) for the endpoints.
//! 2. **Dynamic Client Registration** (RFC 7591) — register a public
//!    client (no pre-issued `client_id`).
//! 3. **Authorization Code + PKCE** — build the authorize URL (S256
//!    challenge, RFC 8707 `resource` indicator); the GUI drives the
//!    browser leg and the redirect capture.
//! 4. **Token exchange + refresh** — swap the code for tokens and
//!    refresh them when they expire.
//!
//! PKCE primitives (`pkce_verifier`/`pkce_challenge`/`new_state`) are
//! reused from `car-auth`. Token material is persisted by the caller
//! (the manager) into the OS keychain, never on disk.

use serde::{Deserialize, Serialize};

use crate::error::ConnectorError;

/// Protected Resource Metadata (RFC 9728) — served by the MCP server.
#[derive(Debug, Clone, Deserialize)]
pub struct ProtectedResourceMetadata {
    #[serde(default)]
    pub resource: Option<String>,
    #[serde(default)]
    pub authorization_servers: Vec<String>,
}

/// Authorization Server Metadata (RFC 8414 / OpenID discovery).
#[derive(Debug, Clone, Deserialize)]
pub struct AuthServerMetadata {
    pub authorization_endpoint: String,
    pub token_endpoint: String,
    #[serde(default)]
    pub registration_endpoint: Option<String>,
    #[serde(default)]
    pub scopes_supported: Vec<String>,
    #[serde(default)]
    pub code_challenge_methods_supported: Vec<String>,
}

/// Result of Dynamic Client Registration (RFC 7591).
#[derive(Debug, Clone, Deserialize)]
pub struct ClientRegistration {
    pub client_id: String,
    #[serde(default)]
    pub client_secret: Option<String>,
}

/// A successful token response.
#[derive(Debug, Clone, Deserialize)]
pub struct TokenResponse {
    pub access_token: String,
    #[serde(default = "default_token_type")]
    pub token_type: String,
    #[serde(default)]
    pub expires_in: Option<u64>,
    #[serde(default)]
    pub refresh_token: Option<String>,
    #[serde(default)]
    pub scope: Option<String>,
}

fn default_token_type() -> String {
    "Bearer".to_string()
}

/// Tokens as persisted in the keychain, with an absolute expiry so the
/// manager can decide when to refresh.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StoredTokens {
    pub access_token: String,
    pub token_type: String,
    #[serde(default)]
    pub refresh_token: Option<String>,
    /// Unix seconds at which `access_token` expires, if the server told
    /// us. `None` means "no known expiry" (treated as non-expiring).
    #[serde(default)]
    pub expires_at: Option<u64>,
}

impl StoredTokens {
    /// Build from a token response, stamping the absolute expiry from
    /// `now_unix + expires_in`. A refresh that omits a new
    /// `refresh_token` keeps the prior one (caller passes it in).
    pub fn from_response(resp: TokenResponse, now_unix: u64, prior_refresh: Option<String>) -> Self {
        Self {
            access_token: resp.access_token,
            token_type: resp.token_type,
            refresh_token: resp.refresh_token.or(prior_refresh),
            expires_at: resp.expires_in.map(|e| now_unix.saturating_add(e)),
        }
    }

    /// True if the access token is expired (or within `skew_secs` of it).
    pub fn is_expired(&self, now_unix: u64, skew_secs: u64) -> bool {
        match self.expires_at {
            Some(exp) => now_unix.saturating_add(skew_secs) >= exp,
            None => false,
        }
    }
}

/// `scheme://host[:port]` for `url`.
pub fn origin_of(url: &str) -> Result<String, ConnectorError> {
    let parsed =
        reqwest::Url::parse(url).map_err(|e| ConnectorError::Protocol(format!("bad url: {e}")))?;
    let origin = parsed.origin().ascii_serialization();
    if origin == "null" {
        return Err(ConnectorError::Protocol(format!(
            "url has no usable origin: {url}"
        )));
    }
    Ok(origin)
}

/// Discover the authorization server for an MCP endpoint and fetch its
/// metadata. Returns `(resource, AuthServerMetadata)` where `resource`
/// is the RFC 8707 resource indicator to bind tokens to.
///
/// Tries Protected Resource Metadata at the server origin first; if
/// absent (or it names no authorization server), assumes the server
/// origin is itself the authorization server.
pub async fn discover(
    http: &reqwest::Client,
    mcp_url: &str,
) -> Result<(Option<String>, AuthServerMetadata), ConnectorError> {
    let origin = origin_of(mcp_url)?;

    let (resource, auth_server) = match fetch_json::<ProtectedResourceMetadata>(
        http,
        &format!("{origin}/.well-known/oauth-protected-resource"),
    )
    .await
    {
        Ok(prm) => {
            let auth = prm.authorization_servers.first().cloned();
            let resource = prm.resource.or_else(|| Some(mcp_url.to_string()));
            (resource, auth.unwrap_or_else(|| origin.clone()))
        }
        // No PRM: assume the resource server co-locates its auth server.
        Err(_) => (Some(mcp_url.to_string()), origin.clone()),
    };

    let asm = fetch_auth_server_metadata(http, &auth_server).await?;
    Ok((resource, asm))
}

async fn fetch_auth_server_metadata(
    http: &reqwest::Client,
    auth_server: &str,
) -> Result<AuthServerMetadata, ConnectorError> {
    let base = auth_server.trim_end_matches('/');
    // RFC 8414 first, then OpenID Connect discovery.
    for path in [
        "/.well-known/oauth-authorization-server",
        "/.well-known/openid-configuration",
    ] {
        if let Ok(asm) = fetch_json::<AuthServerMetadata>(http, &format!("{base}{path}")).await {
            return Ok(asm);
        }
    }
    Err(ConnectorError::Protocol(format!(
        "no authorization server metadata at {auth_server}"
    )))
}

/// Register a public client via Dynamic Client Registration (RFC 7591).
pub async fn register_client(
    http: &reqwest::Client,
    asm: &AuthServerMetadata,
    redirect_uri: &str,
    client_name: &str,
) -> Result<ClientRegistration, ConnectorError> {
    let endpoint = asm.registration_endpoint.as_ref().ok_or_else(|| {
        ConnectorError::Protocol(
            "authorization server has no registration_endpoint (dynamic client registration unsupported)".into(),
        )
    })?;
    let body = serde_json::json!({
        "client_name": client_name,
        "redirect_uris": [redirect_uri],
        "grant_types": ["authorization_code", "refresh_token"],
        "response_types": ["code"],
        "token_endpoint_auth_method": "none",
    });
    let resp = http
        .post(endpoint)
        .json(&body)
        .send()
        .await
        .map_err(|e| ConnectorError::Http(e.to_string()))?;
    let status = resp.status();
    let text = resp
        .text()
        .await
        .map_err(|e| ConnectorError::Http(e.to_string()))?;
    if !status.is_success() {
        return Err(ConnectorError::Http(format!(
            "client registration failed: HTTP {status}: {text}"
        )));
    }
    serde_json::from_str(&text)
        .map_err(|e| ConnectorError::Protocol(format!("parse registration response: {e}")))
}

/// Build the authorization-code-with-PKCE authorize URL.
pub fn authorization_url(
    asm: &AuthServerMetadata,
    client_id: &str,
    redirect_uri: &str,
    state: &str,
    challenge: &str,
    resource: Option<&str>,
    scopes: &[String],
) -> Result<String, ConnectorError> {
    let mut url = reqwest::Url::parse(&asm.authorization_endpoint)
        .map_err(|e| ConnectorError::Protocol(format!("bad authorization_endpoint: {e}")))?;
    {
        let mut q = url.query_pairs_mut();
        q.append_pair("response_type", "code");
        q.append_pair("client_id", client_id);
        q.append_pair("redirect_uri", redirect_uri);
        q.append_pair("state", state);
        q.append_pair("code_challenge", challenge);
        q.append_pair("code_challenge_method", "S256");
        if !scopes.is_empty() {
            q.append_pair("scope", &scopes.join(" "));
        }
        if let Some(resource) = resource {
            q.append_pair("resource", resource);
        }
    }
    Ok(url.to_string())
}

/// Exchange an authorization code (+ PKCE verifier) for tokens.
#[allow(clippy::too_many_arguments)]
pub async fn exchange_code(
    http: &reqwest::Client,
    token_endpoint: &str,
    client_id: &str,
    client_secret: Option<&str>,
    redirect_uri: &str,
    code: &str,
    verifier: &str,
    resource: Option<&str>,
) -> Result<TokenResponse, ConnectorError> {
    let mut form = vec![
        ("grant_type", "authorization_code"),
        ("code", code),
        ("redirect_uri", redirect_uri),
        ("client_id", client_id),
        ("code_verifier", verifier),
    ];
    if let Some(secret) = client_secret {
        form.push(("client_secret", secret));
    }
    if let Some(resource) = resource {
        form.push(("resource", resource));
    }
    post_token(http, token_endpoint, &form).await
}

/// Refresh an access token using a refresh token.
pub async fn refresh(
    http: &reqwest::Client,
    token_endpoint: &str,
    client_id: &str,
    client_secret: Option<&str>,
    refresh_token: &str,
    resource: Option<&str>,
) -> Result<TokenResponse, ConnectorError> {
    let mut form = vec![
        ("grant_type", "refresh_token"),
        ("refresh_token", refresh_token),
        ("client_id", client_id),
    ];
    if let Some(secret) = client_secret {
        form.push(("client_secret", secret));
    }
    if let Some(resource) = resource {
        form.push(("resource", resource));
    }
    post_token(http, token_endpoint, &form).await
}

async fn post_token(
    http: &reqwest::Client,
    token_endpoint: &str,
    form: &[(&str, &str)],
) -> Result<TokenResponse, ConnectorError> {
    let resp = http
        .post(token_endpoint)
        .form(form)
        .send()
        .await
        .map_err(|e| ConnectorError::Http(e.to_string()))?;
    let status = resp.status();
    let text = resp
        .text()
        .await
        .map_err(|e| ConnectorError::Http(e.to_string()))?;
    if !status.is_success() {
        return Err(ConnectorError::Http(format!(
            "token endpoint failed: HTTP {status}: {text}"
        )));
    }
    serde_json::from_str(&text)
        .map_err(|e| ConnectorError::Protocol(format!("parse token response: {e}")))
}

async fn fetch_json<T: for<'de> Deserialize<'de>>(
    http: &reqwest::Client,
    url: &str,
) -> Result<T, ConnectorError> {
    let resp = http
        .get(url)
        .send()
        .await
        .map_err(|e| ConnectorError::Http(e.to_string()))?;
    if !resp.status().is_success() {
        return Err(ConnectorError::Http(format!(
            "GET {url}: HTTP {}",
            resp.status()
        )));
    }
    let text = resp
        .text()
        .await
        .map_err(|e| ConnectorError::Http(e.to_string()))?;
    serde_json::from_str(&text)
        .map_err(|e| ConnectorError::Protocol(format!("parse {url}: {e}")))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn origin_strips_path() {
        assert_eq!(
            origin_of("https://mcp.example.com/sse/v1?x=1").unwrap(),
            "https://mcp.example.com"
        );
        assert_eq!(
            origin_of("http://127.0.0.1:8931/mcp").unwrap(),
            "http://127.0.0.1:8931"
        );
    }

    #[test]
    fn authorize_url_has_pkce_and_resource() {
        let asm = AuthServerMetadata {
            authorization_endpoint: "https://auth.example.com/authorize".into(),
            token_endpoint: "https://auth.example.com/token".into(),
            registration_endpoint: None,
            scopes_supported: vec![],
            code_challenge_methods_supported: vec!["S256".into()],
        };
        let url = authorization_url(
            &asm,
            "client-123",
            "http://127.0.0.1:7777/cb",
            "state-abc",
            "challenge-xyz",
            Some("https://mcp.example.com/"),
            &["read".into(), "write".into()],
        )
        .unwrap();
        assert!(url.starts_with("https://auth.example.com/authorize?"));
        assert!(url.contains("response_type=code"));
        assert!(url.contains("client_id=client-123"));
        assert!(url.contains("code_challenge=challenge-xyz"));
        assert!(url.contains("code_challenge_method=S256"));
        assert!(url.contains("scope=read+write"));
        assert!(url.contains("resource=https"));
        assert!(url.contains("state=state-abc"));
    }

    #[test]
    fn stored_tokens_expiry() {
        let resp = TokenResponse {
            access_token: "a".into(),
            token_type: "Bearer".into(),
            expires_in: Some(3600),
            refresh_token: Some("r".into()),
            scope: None,
        };
        let t = StoredTokens::from_response(resp, 1_000, None);
        assert_eq!(t.expires_at, Some(4_600));
        assert!(!t.is_expired(4_000, 60));
        assert!(t.is_expired(4_550, 60)); // within skew
        assert!(t.is_expired(4_600, 0));
    }

    #[test]
    fn refresh_keeps_prior_refresh_token_when_omitted() {
        let resp = TokenResponse {
            access_token: "a2".into(),
            token_type: "Bearer".into(),
            expires_in: Some(60),
            refresh_token: None,
            scope: None,
        };
        let t = StoredTokens::from_response(resp, 100, Some("old-refresh".into()));
        assert_eq!(t.refresh_token.as_deref(), Some("old-refresh"));
    }
}