A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
fix(mcp): log in to Google Workspace MCP servers with a user OAuth client (#3676)
Sebastian Müller4057f07d5ef0
diff --git a/.changes/google-workspace-mcp-login.md b/.changes/google-workspace-mcp-login.mdnew file mode 100644index 0000000000..a057f737d5--- /dev/null+++ b/.changes/google-workspace-mcp-login.md@@ -0,0 +1 @@+- User `mcpServers` entries accept `clientSecret` and `scopes`, and OAuth discovery accepts an issuer that differs only by a trailing slash, so Google's Drive and Sheets MCP servers can be logged in with your own Google OAuth client; logins against Google request offline access so the grant refreshes. See `docs/google-workspace-mcp.md`.diff --git a/README.md b/README.mdindex 0a1753902d..58aa00abb8 100644--- a/README.md+++ b/README.md@@ -72,6 +72,14 @@ Connect Slack from `/mcp` or run `/mcp login slack` inside Prime Agent to searchyour workspace and use Slack tools. See the [Slack connector guide](docs/slack-mcp.md)for OAuth setup and troubleshooting.+## Google Drive and Google Sheets++Connect Google's official Drive and Sheets MCP servers with your own Google+OAuth client: add them to `mcpServers` with `clientId`, `clientSecret`,+`callbackPort`, and `scopes`, then run `/mcp login <name>`. See the+[Google Drive and Google Sheets guide](docs/google-workspace-mcp.md) for the+Google Cloud setup and the tool mapping.+## Clipboard over SSH and tmuxPrime Agent uses the local clipboard tool (such as `pbcopy`) when available. In tmux it asks the attached tmux client to forward a clipboard buffer if that client advertises the `Ms` capability. This works with tmux's default `set-clipboard external`, unlike application-origin OSC 52. Without tmux, remote copies request delivery using OSC 52. Terminal requests cannot confirm that your local clipboard changed, so Prime Agent reports them as unconfirmed.diff --git a/crates/pa-cli/src/mcp_login.rs b/crates/pa-cli/src/mcp_login.rsindex f513b0737c..a32906d458 100644--- a/crates/pa-cli/src/mcp_login.rs+++ b/crates/pa-cli/src/mcp_login.rs@@ -30,28 +30,30 @@ pub(crate) fn cli_mcp_manager(cwd: &std::path::Path, agent_dir: &std::path::Pathlet user_agent_dir = agent_dir.to_path_buf();let catalog_cwd = cwd.to_path_buf();let catalog_agent_dir = agent_dir.to_path_buf();+ let user_servers: pa_core::mcp::UserServersFn = std::sync::Arc::new(move || {+ let settings = pa_core::settings::SettingsManager::create(&user_cwd, &user_agent_dir);+ Some(+ settings+ .global_settings()+ .mcp_servers+ .clone()+ .unwrap_or_default()+ .into_iter()+ .filter_map(|(server, config)| {+ serde_json::from_value::<McpServerConfig>(config)+ .ok()+ .map(|parsed| (server, parsed))+ })+ .collect(),+ )+ });+ let oauth_user_servers = std::sync::Arc::clone(&user_servers);McpManager::new(McpManagerOptions {auth_storage: AuthStorage::create_with_oauth(agent_dir,- std::sync::Arc::new(pa_core::mcp::McpOAuth::new()),+ std::sync::Arc::new(pa_core::mcp::McpOAuth::new(oauth_user_servers)),),- get_user_servers: Box::new(move || {- let settings = pa_core::settings::SettingsManager::create(&user_cwd, &user_agent_dir);- Some(- settings- .global_settings()- .mcp_servers- .clone()- .unwrap_or_default()- .into_iter()- .filter_map(|(server, config)| {- serde_json::from_value::<McpServerConfig>(config)- .ok()- .map(|parsed| (server, parsed))- })- .collect(),- )- }),+ get_user_servers: Box::new(move || user_servers()),begin_login: None,agent_dir: Some(agent_dir.to_path_buf()),get_catalog_sources: Some(Box::new(move || {diff --git a/crates/pa-core/src/mcp/catalog_plugin_views.rs b/crates/pa-core/src/mcp/catalog_plugin_views.rsindex 1d5e22b787..abdb6a1a53 100644--- a/crates/pa-core/src/mcp/catalog_plugin_views.rs+++ b/crates/pa-core/src/mcp/catalog_plugin_views.rs@@ -850,6 +850,8 @@ mod connection_view_tests {call_timeout_ms: None,client_id: None,callback_port: None,+ client_secret: None,+ scopes: None,},);let credentials = credentials_with(&[diff --git a/crates/pa-core/src/mcp/login.rs b/crates/pa-core/src/mcp/login.rsindex 04a59f878a..9de0906afb 100644--- a/crates/pa-core/src/mcp/login.rs+++ b/crates/pa-core/src/mcp/login.rs@@ -11,7 +11,7 @@ use crate::auth::{AuthStorage, OAuthIntegration};use super::oauth::{mcp_login, McpLoginUi, McpOAuthConfig};use super::oauth_http::OAuthHttp;-use super::{McpManager, McpServerConfig};+use super::{McpManager, McpServerConfig, UserServersFn};/// One server's login execution: the resolved OAuth config plus the auth store. Detached from the/// manager on purpose — the flow awaits UI input, so no manager lock may be held across it.@@ -55,6 +55,8 @@ impl McpManager {url,client_id,callback_port,+ client_secret,+ scopes,..} = &integration.configelse {@@ -70,7 +72,8 @@ impl McpManager {.clone().or_else(|| slack.then(|| "1601185624273.8899143856786".to_string())),callback_port: (*callback_port).or(slack.then_some(3118)),- scopes: None,+ client_secret: client_secret.clone(),+ scopes: scopes.clone(),})}@@ -134,25 +137,19 @@ pub fn wire_begin_login(/// asks the stored endpoint for a fresh token.pub struct McpOAuth {http: Arc<dyn OAuthHttp>,-}--impl Default for McpOAuth {- fn default() -> Self {- Self::new()- }+ /// Reads `mcpServers`: a configured `clientSecret` stays in settings, never in the credential.+ user_servers: UserServersFn,}impl McpOAuth {#[must_use]- pub fn new() -> Self {- McpOAuth {- http: Arc::new(super::ReqwestOAuthHttp::new()),- }+ pub fn new(user_servers: UserServersFn) -> Self {+ Self::with_http(Arc::new(super::ReqwestOAuthHttp::new()), user_servers)}/// A fixed transport (tests and embedded hosts).- pub fn with_http(http: Arc<dyn OAuthHttp>) -> Self {- McpOAuth { http }+ pub fn with_http(http: Arc<dyn OAuthHttp>, user_servers: UserServersFn) -> Self {+ McpOAuth { http, user_servers }}}@@ -172,12 +169,22 @@ impl McpOAuth {else {return None;};+ // Only the server entry the credential was issued for may lend its secret.+ let client_secret = (self.user_servers)()+ .and_then(|mut servers| servers.remove(&server))+ .and_then(|config| match config {+ McpServerConfig::Http {+ url, client_secret, ..+ } if url == *endpoint => client_secret,+ McpServerConfig::Http { .. } | McpServerConfig::Stdio { .. } => None,+ });let config = McpOAuthConfig {server: server.clone(),label: server,url: endpoint.clone(),client_id: None,callback_port: None,+ client_secret,scopes: None,};let http = Arc::clone(&self.http);@@ -235,13 +242,16 @@ mod tests {use serde_json::json;use std::collections::HashMap;- /// A scripted transport (url -> response); unknown urls fail.- struct ScriptedHttp(HashMap<String, OAuthHttpResponse>);+ /// A scripted transport (url -> response) that records request bodies; unknown urls fail.+ struct ScriptedHttp {+ responses: HashMap<String, OAuthHttpResponse>,+ bodies: Mutex<Vec<(String, Option<String>)>>,+ }impl ScriptedHttp {fn new(responses: Vec<(&str, u16, &str)>) -> Self {- ScriptedHttp(- responses+ ScriptedHttp {+ responses: responses.into_iter().map(|(url, status, body)| {(@@ -257,7 +267,8 @@ mod tests {)}).collect(),- )+ bodies: Mutex::default(),+ }}}@@ -267,7 +278,11 @@ mod tests {request: super::super::oauth_http::OAuthHttpRequest,) -> futures::future::BoxFuture<'_, Result<OAuthHttpResponse>> {Box::pin(async move {- self.0+ self.bodies+ .lock()+ .unwrap()+ .push((request.url.clone(), request.body.clone()));+ self.responses.get(&request.url).cloned().ok_or_else(|| anyhow!("unexpected request: {}", request.url))@@ -317,12 +332,13 @@ mod tests {user_servers: Option<HashMap<String, McpServerConfig>>,http: Arc<dyn OAuthHttp>,) -> Arc<Mutex<McpManager>> {+ let user_servers: UserServersFn = Arc::new(move || user_servers.clone());let manager = McpManager::new(McpManagerOptions {auth_storage: AuthStorage::create_with_oauth(agent_dir,- Arc::new(McpOAuth::with_http(http)),+ Arc::new(McpOAuth::with_http(http, Arc::clone(&user_servers))),),- get_user_servers: Box::new(move || user_servers.clone()),+ get_user_servers: Box::new(move || user_servers()),begin_login: None,agent_dir: None,get_catalog_sources: None,@@ -345,6 +361,8 @@ mod tests {call_timeout_ms: None,client_id: None,callback_port: None,+ client_secret: None,+ scopes: None,}}@@ -511,6 +529,118 @@ mod tests {assert!(enabled.contains(&"slack".to_string()));}+ /// Google Workspace MCP (live metadata captured 2026-10-19: a trailing-slash PRM issuer, no+ /// registration endpoint) with a user-registered confidential client from `mcpServers`.+ #[tokio::test]+ async fn google_workspace_login_and_refresh_use_the_configured_client() {+ const SHEETS: &str = "https://sheetsmcp.googleapis.com/mcp/v1";+ const TOKEN: &str = "https://oauth2.googleapis.com/token";+ const SCOPES: &str = "https://www.googleapis.com/auth/drive.readonly https://www.googleapis.com/auth/spreadsheets";+ let probe = std::net::TcpListener::bind("127.0.0.1:0").unwrap();+ let port = probe.local_addr().unwrap().port();+ drop(probe);+ let http = Arc::new(ScriptedHttp::new(vec![+ (SHEETS, 405, ""),+ (+ "https://sheetsmcp.googleapis.com/.well-known/oauth-protected-resource/mcp/v1",+ 200,+ r#"{"authorization_servers":["https://accounts.google.com/"],"bearer_methods_supported":["header"],"resource":"https://sheetsmcp.googleapis.com/mcp/v1","scopes_supported":["https://www.googleapis.com/auth/drive.readonly","https://www.googleapis.com/auth/spreadsheets.readonly","https://www.googleapis.com/auth/drive","https://www.googleapis.com/auth/spreadsheets"]}"#,+ ),+ (+ "https://accounts.google.com/.well-known/oauth-authorization-server",+ 200,+ r#"{"issuer":"https://accounts.google.com","authorization_endpoint":"https://accounts.google.com/o/oauth2/v2/auth","token_endpoint":"https://oauth2.googleapis.com/token","token_endpoint_auth_methods_supported":["client_secret_post","client_secret_basic"],"code_challenge_methods_supported":["plain","S256"]}"#,+ ),+ // expires_in equals the expiry buffer, so the stored token is due for refresh at once.+ (+ TOKEN,+ 200,+ r#"{"access_token":"google-access","refresh_token":"google-refresh","expires_in":300}"#,+ ),+ ]));+ let user_servers = serde_json::from_value(json!({ "sheets": {+ "type": "http", "url": SHEETS, "oauth": true, "callbackPort": port, "scopes": SCOPES,+ "clientId": "byo.apps.googleusercontent.com", "clientSecret": "byo-secret"+ }}))+ .unwrap();+ let agent = tempfile::tempdir().unwrap();+ let manager = manager(agent.path(), Some(user_servers), http.clone());+ let ui = PasteUi {+ auth_url: Arc::default(),+ };+ let context = manager.lock().unwrap().login_context("sheets").unwrap();+ context.run(&ui, http.as_ref()).await.unwrap();+ let mut handlers = HostRequestHandlers::default();+ McpManager::register_host_handlers(&manager, &mut handlers);+ let refresh = handlers.get("mcp.refresh").expect("wired").clone();+ refresh(HostRequestPayload {+ data: json!({ "server": "sheets" }),+ })+ .await+ .unwrap();++ let pairs = |entries: &[(&str, &str)]| -> HashMap<String, String> {+ entries+ .iter()+ .map(|(key, value)| ((*key).to_string(), (*value).to_string()))+ .collect()+ };+ let redirect_uri = format!("http://localhost:{port}/callback");+ let mut authorize: HashMap<String, String> = url::Url::parse(&ui.auth_url.lock().unwrap())+ .unwrap()+ .query_pairs()+ .into_owned()+ .collect();+ authorize.remove("state");+ authorize.remove("code_challenge");+ assert_eq!(+ authorize,+ pairs(&[+ ("client_id", "byo.apps.googleusercontent.com"),+ ("response_type", "code"),+ ("redirect_uri", redirect_uri.as_str()),+ ("code_challenge_method", "S256"),+ ("scope", SCOPES),+ ("resource", SHEETS),+ ("access_type", "offline"),+ ("prompt", "consent"),+ ])+ );+ let mut tokens: Vec<HashMap<String, String>> = http+ .bodies+ .lock()+ .unwrap()+ .iter()+ .filter(|(url, _)| url == TOKEN)+ .map(|(_, body)| {+ url::form_urlencoded::parse(body.as_deref().unwrap().as_bytes())+ .into_owned()+ .collect()+ })+ .collect();+ tokens[0].remove("code_verifier");+ assert_eq!(+ tokens,+ vec![+ pairs(&[+ ("grant_type", "authorization_code"),+ ("code", "the-code"),+ ("redirect_uri", redirect_uri.as_str()),+ ("client_id", "byo.apps.googleusercontent.com"),+ ("client_secret", "byo-secret"),+ ("resource", SHEETS),+ ]),+ pairs(&[+ ("grant_type", "refresh_token"),+ ("refresh_token", "google-refresh"),+ ("client_id", "byo.apps.googleusercontent.com"),+ ("client_secret", "byo-secret"),+ ("resource", SHEETS),+ ]),+ ]+ );+ }+#[test]fn registered_oauth_client_follows_endpoint_instead_of_connection_name() {let agent = tempfile::tempdir().unwrap();@@ -713,8 +843,10 @@ mod tests {async fn mcp_oauth_refreshes_expired_credentials() {let agent = tempfile::tempdir().unwrap();let http = Arc::new(fixture_http());- let mut auth =- AuthStorage::create_with_oauth(agent.path(), Arc::new(McpOAuth::with_http(http)));+ let mut auth = AuthStorage::create_with_oauth(+ agent.path(),+ Arc::new(McpOAuth::with_http(http, Arc::new(|| None))),+ );auth.set("mcp:fixture",AuthCredential::Oauth {diff --git a/crates/pa-core/src/mcp/manager_catalog.rs b/crates/pa-core/src/mcp/manager_catalog.rsindex dcfae22587..080c892480 100644--- a/crates/pa-core/src/mcp/manager_catalog.rs+++ b/crates/pa-core/src/mcp/manager_catalog.rs@@ -440,6 +440,8 @@ fn http_config(url: &str, uses_oauth: bool) -> McpServerConfig {call_timeout_ms: None,client_id: None,callback_port: None,+ client_secret: None,+ scopes: None,}}@@ -457,6 +459,8 @@ fn disabled_config(config: McpServerConfig) -> McpServerConfig {call_timeout_ms: None,client_id: None,callback_port: None,+ client_secret: None,+ scopes: None,},other @ McpServerConfig::Stdio { .. } => other,}diff --git a/crates/pa-core/src/mcp/mod.rs b/crates/pa-core/src/mcp/mod.rsindex 61129475cc..c802ba066c 100644--- a/crates/pa-core/src/mcp/mod.rs+++ b/crates/pa-core/src/mcp/mod.rs@@ -126,6 +126,16 @@ pub enum McpServerConfig {skip_serializing_if = "Option::is_none")]callback_port: Option<u16>,+ /// Secret of the pre-registered client, for servers that only issue confidential clients.+ #[serde(+ rename = "clientSecret",+ default,+ skip_serializing_if = "Option::is_none"+ )]+ client_secret: Option<String>,+ /// Space-separated scopes to request instead of the server's advertised ones.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ scopes: Option<String>,},#[serde(rename_all = "camelCase")]Stdio {@@ -251,6 +261,9 @@ pub(crate) struct ResolvedIntegration {pub type BeginLoginFuture = Box<dyn Future<Output = anyhow::Result<()>> + Send>;pub type BeginLoginFn = Arc<dyn Fn(String) -> BeginLoginFuture + Send + Sync>;+/// Reads the current `mcpServers` setting.+pub type UserServersFn = Arc<dyn Fn() -> Option<HashMap<String, McpServerConfig>> + Send + Sync>;+pub struct McpManagerOptions {pub auth_storage: AuthStorage,/// Reads the current `mcpServers` setting; re-read on refresh.@@ -542,12 +555,14 @@ impl McpManager {user_servers: std::collections::HashMap<String, McpServerConfig>,agent_dir: &std::path::Path,) -> (Vec<String>, Vec<String>, McpManager) {+ let user_servers: UserServersFn = Arc::new(move || Some(user_servers.clone()));+ let oauth_user_servers = Arc::clone(&user_servers);let manager = McpManager::new(McpManagerOptions {auth_storage: crate::auth::AuthStorage::create_with_oauth(agent_dir,- std::sync::Arc::new(McpOAuth::new()),+ std::sync::Arc::new(McpOAuth::new(oauth_user_servers)),),- get_user_servers: Box::new(move || Some(user_servers.clone())),+ get_user_servers: Box::new(move || user_servers()),begin_login: None,agent_dir: Some(agent_dir.to_path_buf()),get_catalog_sources: None,@@ -1043,6 +1058,8 @@ mod tests {call_timeout_ms: None,client_id: None,callback_port: None,+ client_secret: None,+ scopes: None,}}diff --git a/crates/pa-core/src/mcp/oauth.rs b/crates/pa-core/src/mcp/oauth.rsindex f542005276..76858d60bc 100644--- a/crates/pa-core/src/mcp/oauth.rs+++ b/crates/pa-core/src/mcp/oauth.rs@@ -35,6 +35,8 @@ pub struct McpOAuthConfig {pub client_id: Option<String>,/// Fixed loopback port registered for a public client; otherwise use the DCR port range.pub callback_port: Option<u16>,+ /// Secret of a pre-registered confidential client, sent as `client_secret_post`.+ pub client_secret: Option<String>,/// Requested scopes; defaults to the server's advertised scopes.pub scopes: Option<String>,}@@ -201,6 +203,11 @@ pub async fn mcp_login(if let Some(resource) = &discovery.resource {auth_params.push(("resource".to_string(), resource.clone()));}+ // Google issues a refresh token only for offline access, and re-issues one only on consent.+ if discovery.metadata.issuer == "https://accounts.google.com" {+ auth_params.push(("access_type".to_string(), "offline".to_string()));+ auth_params.push(("prompt".to_string(), "consent".to_string()));+ }let auth_url = authorization_url(&discovery.metadata.authorization_endpoint, &auth_params)?;ui.on_auth(&auth_url,@@ -291,6 +298,9 @@ pub async fn mcp_login(("client_id".to_string(), client_id.clone()),("code_verifier".to_string(), verifier),];+ if let Some(client_secret) = &config.client_secret {+ token_params.push(("client_secret".to_string(), client_secret.clone()));+ }if let Some(resource) = &discovery.resource {token_params.push(("resource".to_string(), resource.clone()));}@@ -487,6 +497,9 @@ pub async fn mcp_refresh_token(if !client_id.is_empty() {refresh_params.push(("client_id".to_string(), client_id.clone()));}+ if let Some(client_secret) = &config.client_secret {+ refresh_params.push(("client_secret".to_string(), client_secret.clone()));+ }if let Some(resource) = resource {refresh_params.push(("resource".to_string(), resource.clone()));}@@ -677,6 +690,7 @@ mod tests {url: url.to_string(),client_id: None,callback_port: None,+ client_secret: None,scopes: None,}}diff --git a/crates/pa-daemon/src/agent_engine/lifecycle.rs b/crates/pa-daemon/src/agent_engine/lifecycle.rsindex edd2adc80a..ee7bd947a1 100644--- a/crates/pa-daemon/src/agent_engine/lifecycle.rs+++ b/crates/pa-daemon/src/agent_engine/lifecycle.rs@@ -72,34 +72,33 @@ impl AgentSessionEngine {let mcp_agent_dir = agent_dir.clone();let catalog_cwd = std::sync::Arc::clone(&cwd);let catalog_agent_dir = agent_dir.clone();+ let user_servers: pa_core::mcp::UserServersFn = std::sync::Arc::new(move || {+ // The live cwd slot, not the construction-time cwd: the rebind must reach the MCP+ // settings discovery.+ let mcp_cwd = mcp_cwd.read().expect("engine cwd lock").clone();+ let settings = pa_core::settings::SettingsManager::create(&mcp_cwd, &mcp_agent_dir);+ Some(+ settings+ .global_settings()+ .mcp_servers+ .clone()+ .unwrap_or_default()+ .into_iter()+ .filter_map(|(server, server_config)| {+ serde_json::from_value(server_config)+ .ok()+ .map(|parsed| (server, parsed))+ })+ .collect::<std::collections::HashMap<String, pa_core::mcp::McpServerConfig>>(),+ )+ });+ let oauth_user_servers = std::sync::Arc::clone(&user_servers);let mcp = pa_core::mcp::McpManager::new(pa_core::mcp::McpManagerOptions {auth_storage: pa_core::auth::AuthStorage::create_with_oauth(&agent_dir,- std::sync::Arc::new(pa_core::mcp::McpOAuth::new()),+ std::sync::Arc::new(pa_core::mcp::McpOAuth::new(oauth_user_servers)),),- get_user_servers: Box::new(move || {- // The live cwd slot, not the construction-time cwd: the rebind must reach the MCP- // settings discovery.- let mcp_cwd = mcp_cwd.read().expect("engine cwd lock").clone();- let settings = pa_core::settings::SettingsManager::create(&mcp_cwd, &mcp_agent_dir);- Some(- settings- .global_settings()- .mcp_servers- .clone()- .unwrap_or_default()- .into_iter()- .filter_map(|(server, server_config)| {- serde_json::from_value(server_config)- .ok()- .map(|parsed| (server, parsed))- })- .collect::<std::collections::HashMap<- String,- pa_core::mcp::McpServerConfig,- >>(),- )- }),+ get_user_servers: Box::new(move || user_servers()),begin_login: None,agent_dir: Some(agent_dir),get_catalog_sources: Some(Box::new(move || {diff --git a/crates/pa-daemon/src/mcp_login.rs b/crates/pa-daemon/src/mcp_login.rsindex 7c252430d7..eb23405234 100644--- a/crates/pa-daemon/src/mcp_login.rs+++ b/crates/pa-daemon/src/mcp_login.rs@@ -233,13 +233,16 @@ mod tests {call_timeout_ms: None,client_id: None,callback_port: None,+ client_secret: None,+ scopes: None,},);let manager = McpManager::new(McpManagerOptions {auth_storage: AuthStorage::create_with_oauth(agent.path(),Arc::new(pa_core::mcp::McpOAuth::with_http(- Arc::clone(&http) as Arc<dyn pa_core::mcp::OAuthHttp>+ Arc::clone(&http) as Arc<dyn pa_core::mcp::OAuthHttp>,+ Arc::new(|| None),)),),get_user_servers: Box::new(move || Some(user_servers.clone())),@@ -387,7 +390,8 @@ mod tests {auth_storage: AuthStorage::create_with_oauth(agent.path(),Arc::new(pa_core::mcp::McpOAuth::with_http(- Arc::clone(&http) as Arc<dyn pa_core::mcp::OAuthHttp>+ Arc::clone(&http) as Arc<dyn pa_core::mcp::OAuthHttp>,+ Arc::new(|| None),)),),get_user_servers: Box::new(|| None),diff --git a/docs/google-workspace-mcp.md b/docs/google-workspace-mcp.mdnew file mode 100644index 0000000000..9fafb8d0d1--- /dev/null+++ b/docs/google-workspace-mcp.md@@ -0,0 +1,121 @@+# Google Drive and Google Sheets MCP servers++Google hosts official remote MCP servers for Drive and Sheets:++- Drive: `https://drivemcp.googleapis.com/mcp/v1`+- Sheets: `https://sheetsmcp.googleapis.com/mcp/v1`++They are in the+[Google Workspace Developer Preview Program](https://developers.google.com/workspace/preview).+Google offers no dynamic client registration and requires a client secret, so+there is no one-click login. You create your own OAuth client in Google Cloud+and add it to Prime Agent's `mcpServers` setting. Google's own setup guide is+[Configure the Google Workspace MCP servers](https://developers.google.com/workspace/guides/configure-mcp-servers).++## 1. Google Cloud project++1. Use a Google Cloud project whose organization or account is enrolled in the+ Workspace Developer Preview Program.+2. Enable the product APIs and the MCP services:++ ```bash+ gcloud services enable drive.googleapis.com sheets.googleapis.com \+ drivemcp.googleapis.com sheetsmcp.googleapis.com --project=PROJECT_ID+ ```++3. In **Google Auth Platform > Branding**, configure the consent screen. Choose+ the **Internal** audience if you can: the app is then limited to your+ Workspace organization and needs no Google verification. With **External**,+ add yourself as a test user; Google expires refresh tokens of apps in+ testing after 7 days.+4. In **Data Access**, add the scopes you will request:+ `https://www.googleapis.com/auth/drive.readonly` for Drive, and also+ `https://www.googleapis.com/auth/spreadsheets` for Sheets.++## 2. OAuth client++In **Google Auth Platform > Clients > Create Client**:++1. Application type: **Web application**.+2. Authorized redirect URI: `http://localhost:<port>/callback`, for a free local+ port you choose, for example `http://localhost:8719/callback`.+3. Select **Use this client for an AI-powered agent**. Google rejects MCP+ requests from clients without this flag.+4. Create the client and copy the client ID and client secret.++## 3. Prime Agent settings++Add the servers to `mcpServers` in the user-level settings file+`~/.prime/agent/settings.json`. MCP servers are read only from user settings;+a project's `.prime/agent/settings.json` cannot add them.++```json+{+ "mcpServers": {+ "google-drive": {+ "type": "http",+ "url": "https://drivemcp.googleapis.com/mcp/v1",+ "oauth": true,+ "clientId": "CLIENT_ID.apps.googleusercontent.com",+ "clientSecret": "CLIENT_SECRET",+ "callbackPort": 8719,+ "scopes": "https://www.googleapis.com/auth/drive.readonly"+ },+ "google-sheets": {+ "type": "http",+ "url": "https://sheetsmcp.googleapis.com/mcp/v1",+ "oauth": true,+ "clientId": "CLIENT_ID.apps.googleusercontent.com",+ "clientSecret": "CLIENT_SECRET",+ "callbackPort": 8719,+ "scopes": "https://www.googleapis.com/auth/drive.readonly https://www.googleapis.com/auth/spreadsheets",+ "callTimeoutMs": 300000+ }+ }+}+```++- `callbackPort` must match the redirect URI registered on the client.+- `scopes` is space-separated. Without it, Prime Agent requests every scope the+ server advertises, which includes full `drive` access.+- `callTimeoutMs` raises the default 60 s tool-call timeout for large writes.++Then run `/mcp login google-drive` and `/mcp login google-sheets` inside Prime+Agent and finish Google's consent screen in the browser. Prime Agent asks Google+for offline access, so the stored grant includes a refresh token and renews+itself. The client secret stays in settings (it is not copied into the stored+login grant) and is sent to Google only on token requests. For SSH sessions, forward the callback port or paste the final+redirect URL into the auth panel.++## Tools++Read each tool's `inputSchema` with `mcp.describe_tool` before calling it.++| Task | Server | Tool |+| --- | --- | --- |+| File metadata | Drive | `get_file_metadata` (`excludeContentSnippets: true` skips the content snippet) |+| Download a file | Drive | `download_file_content` |+| Spreadsheet metadata | Sheets | `get_spreadsheet` with a `fields` mask, for example `["sheets.properties"]` |+| Atomic batch update | Sheets | `update_spreadsheet` (`spreadsheets.batchUpdate`: all requests apply or none do; pass `writeControl.requiredRevisionId` to reject a stale revision) |+| Typed values | Sheets | `get_spreadsheet` with grid data, see below |++`get_values` returns formatted strings and has no `valueRenderOption`. For+unformatted typed values, read the effective values through `get_spreadsheet`:++```python+grid = await mcp.call_tool("google-sheets", "get_spreadsheet", {+ "spreadsheetId": spreadsheet_id,+ "ranges": ["Ledger!A1:F2000"],+ "includeGridData": True,+ "fields": ["sheets.data.rowData.values.effectiveValue"],+})+```++Each cell's `effectiveValue` carries `numberValue`, `stringValue`, or+`boolValue`; dates come back as serial numbers.++For large or exact payloads, follow the "Large or integrity-critical payloads"+section of the `mcp` skill (`skills/mcp/SKILL.md`): load the arguments from a+file in the Python kernel, write results to a file, and verify them in code.++Disconnect with `/mcp logout google-drive` (or `google-sheets`).