A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
fix(mcp): honor clientId and callbackPort for user MCP servers (#3616)
Sebastian Mülleree1e531e6935
diff --git a/crates/pa-core/src/mcp/catalog_plugin_views.rs b/crates/pa-core/src/mcp/catalog_plugin_views.rsindex e376bbc95b..1d5e22b787 100644--- a/crates/pa-core/src/mcp/catalog_plugin_views.rs+++ b/crates/pa-core/src/mcp/catalog_plugin_views.rs@@ -848,6 +848,8 @@ mod connection_view_tests {disabled_tools: None,startup_timeout_ms: None,call_timeout_ms: None,+ client_id: None,+ callback_port: None,},);let credentials = credentials_with(&[diff --git a/crates/pa-core/src/mcp/login.rs b/crates/pa-core/src/mcp/login.rsindex 4ba12567dc..04a59f878a 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;+use super::{McpManager, McpServerConfig};/// 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.@@ -51,17 +51,25 @@ impl McpManager {if !integration.uses_oauth {return None;}- let url = integration.config_url().map(str::to_string)?;- // Slack publishes this PKCE desktop client in its agent-harness setup guide:- // https://docs.slack.dev/ai/slack-mcp-server/connect-to-harnesses/- // Match the endpoint, never the user-controlled connection name.+ let McpServerConfig::Http {+ url,+ client_id,+ callback_port,+ ..+ } = &integration.config+ else {+ unreachable!("uses_oauth implies an http config");+ };+ // Slack defaults follow the endpoint; explicit user settings take precedence.let slack = url == "https://mcp.slack.com/mcp";Some(McpOAuthConfig {server: integration.server.clone(),label: integration.label.clone(),- url,- client_id: slack.then(|| "1601185624273.8899143856786".to_string()),- callback_port: slack.then_some(3118),+ url: url.clone(),+ client_id: client_id+ .clone()+ .or_else(|| slack.then(|| "1601185624273.8899143856786".to_string())),+ callback_port: (*callback_port).or(slack.then_some(3118)),scopes: None,})}@@ -335,6 +343,8 @@ mod tests {disabled_tools: None,startup_timeout_ms: None,call_timeout_ms: None,+ client_id: None,+ callback_port: None,}}@@ -366,6 +376,28 @@ mod tests {])}+ #[test]+ fn oauth_config_threads_client_id_and_callback_port() {+ for endpoint in ["https://fixture.example/mcp", "https://mcp.slack.com/mcp"] {+ let agent = tempfile::tempdir().unwrap();+ let user_servers: HashMap<String, McpServerConfig> = serde_json::from_value(json!({+ "slack": {+ "type": "http",+ "url": endpoint,+ "oauth": true,+ "clientId": "custom-client",+ "callbackPort": 4567+ }+ }))+ .unwrap();+ let http = Arc::new(fixture_http());+ let manager = manager(agent.path(), Some(user_servers), http);+ let config = manager.lock().unwrap().oauth_config("slack").unwrap();+ assert_eq!(config.client_id.as_deref(), Some("custom-client"));+ assert_eq!(config.callback_port, Some(4567));+ }+ }+/// Slack has no DCR; drive its public desktop client through the real manager and auth store.#[tokio::test]async fn slack_login_persists_refreshes_and_can_login_again() {diff --git a/crates/pa-core/src/mcp/manager_catalog.rs b/crates/pa-core/src/mcp/manager_catalog.rsindex d1b33709ce..dcfae22587 100644--- a/crates/pa-core/src/mcp/manager_catalog.rs+++ b/crates/pa-core/src/mcp/manager_catalog.rs@@ -438,6 +438,8 @@ fn http_config(url: &str, uses_oauth: bool) -> McpServerConfig {disabled_tools: None,startup_timeout_ms: None,call_timeout_ms: None,+ client_id: None,+ callback_port: None,}}@@ -453,6 +455,8 @@ fn disabled_config(config: McpServerConfig) -> McpServerConfig {disabled_tools: None,startup_timeout_ms: None,call_timeout_ms: None,+ client_id: None,+ callback_port: None,},other @ McpServerConfig::Stdio { .. } => other,}diff --git a/crates/pa-core/src/mcp/mod.rs b/crates/pa-core/src/mcp/mod.rsindex b11af97dfb..fc58e982c5 100644--- a/crates/pa-core/src/mcp/mod.rs+++ b/crates/pa-core/src/mcp/mod.rs@@ -117,6 +117,14 @@ pub enum McpServerConfig {skip_serializing_if = "Option::is_none")]call_timeout_ms: Option<u64>,+ #[serde(rename = "clientId", default, skip_serializing_if = "Option::is_none")]+ client_id: Option<String>,+ #[serde(+ rename = "callbackPort",+ default,+ skip_serializing_if = "Option::is_none"+ )]+ callback_port: Option<u16>,},#[serde(rename_all = "camelCase")]Stdio {@@ -998,15 +1006,6 @@ fn is_generic_server_name(name: &str) -> bool {chars.all(|char| char.is_ascii_alphanumeric() || char == '_' || char == '-')}-impl ResolvedIntegration {- fn config_url(&self) -> Option<&str> {- match &self.config {- McpServerConfig::Http { url, .. } => Some(url.as_str()),- McpServerConfig::Stdio { .. } => None,- }- }-}-#[cfg(test)]mod tests {use super::*;@@ -1041,6 +1040,8 @@ mod tests {disabled_tools: None,startup_timeout_ms: None,call_timeout_ms: None,+ client_id: None,+ callback_port: None,}}diff --git a/crates/pa-core/src/mcp/oauth.rs b/crates/pa-core/src/mcp/oauth.rsindex 63575c7f23..f542005276 100644--- a/crates/pa-core/src/mcp/oauth.rs+++ b/crates/pa-core/src/mcp/oauth.rs@@ -136,6 +136,7 @@ pub async fn mcp_login(config: &McpOAuthConfig,ui: &dyn McpLoginUi,) -> Result<AuthCredential> {+ super::oauth_callback::validate_callback_port(config.callback_port)?;let discovery = discover(http, &config.url).await?;ui.on_progress(&format!("Discovered {}",@@ -175,6 +176,7 @@ pub async fn mcp_login(registration_endpoint,&config.label,(!scope.is_empty()).then_some(scope.as_str()),+ config.callback_port,).await?};@@ -1416,7 +1418,24 @@ mod tests {}#[tokio::test]- async fn pre_registered_client_skips_registration() {+ async fn zero_callback_port_fails_before_any_oauth_request() {+ for client_id in [None, Some("fixture-client".to_string())] {+ let http = ScriptedHttp::new(vec![]);+ let ui = test_ui();+ let mut login_config = config("fixture", ORIGIN_URL);+ login_config.client_id = client_id;+ login_config.callback_port = Some(0);+ let error = mcp_login(&http, &login_config, &ui).await.unwrap_err();+ assert!(error.to_string().contains("callbackPort"));+ assert!(http.seen.lock().unwrap().is_empty());+ }+ }++ #[tokio::test]+ async fn pre_registered_client_skips_registration_and_pins_the_redirect() {+ let probe = std::net::TcpListener::bind("127.0.0.1:0").unwrap();+ let port = probe.local_addr().unwrap().port();+ drop(probe);let http = ScriptedHttp::new(vec![(ORIGIN_URL, 404, None, ""),(@@ -1436,6 +1455,7 @@ mod tests {let ui = test_ui();let mut login_config = config("root", ORIGIN_URL);login_config.client_id = Some("root-client".to_string());+ login_config.callback_port = Some(port);let credentials = mcp_login(&http, &login_config, &ui).await.unwrap();match &credentials {AuthCredential::Oauth {@@ -1454,6 +1474,80 @@ mod tests {.map(|(url, _)| url.clone()).collect();assert!(!urls.contains(&ORIGIN_REGISTER.to_string()));+ let redirect_uri = format!("http://localhost:{port}/callback");+ let auth_url = Url::parse(&ui.auth_url.lock().unwrap()).unwrap();+ let redirect = auth_url+ .query_pairs()+ .find(|(key, _)| key == "redirect_uri")+ .map(|(_, value)| value.to_string())+ .unwrap();+ assert_eq!(redirect, redirect_uri);+ let token_request = http+ .seen+ .lock()+ .unwrap()+ .iter()+ .find(|(url, _)| url == ORIGIN_TOKEN)+ .cloned()+ .unwrap();+ let body = token_request.1.unwrap();+ let encoded_redirect = url::form_urlencoded::Serializer::new(String::new())+ .append_pair("redirect_uri", &redirect_uri)+ .finish();+ assert!(body.contains(&encoded_redirect));+ }++ #[tokio::test]+ async fn dynamic_registration_advertises_the_pinned_redirect() {+ let probe = std::net::TcpListener::bind("127.0.0.1:0").unwrap();+ let port = probe.local_addr().unwrap().port();+ drop(probe);+ let http = ScriptedHttp::new(vec![+ (ORIGIN_URL, 404, None, ""),+ (+ "https://srv.test/.well-known/oauth-protected-resource/mcp",+ 404,+ None,+ "",+ ),+ (ORIGIN_META_URL, 200, None, &json_response(&origin_meta())),+ (+ ORIGIN_REGISTER,+ 200,+ None,+ &json_response(&serde_json::json!({ "client_id": "range-client" })),+ ),+ (+ ORIGIN_TOKEN,+ 200,+ None,+ &json_response(&serde_json::json!({ "access_token": "range-access" })),+ ),+ ]);+ let ui = test_ui();+ let mut login_config = config("origin", ORIGIN_URL);+ login_config.callback_port = Some(port);+ let credentials = mcp_login(&http, &login_config, &ui).await.unwrap();+ match &credentials {+ AuthCredential::Oauth { access, .. } => assert_eq!(access, "range-access"),+ other => panic!("oauth credential expected, got {other:?}"),+ }+ let registration_request = http+ .seen+ .lock()+ .unwrap()+ .iter()+ .find(|(url, _)| url == ORIGIN_REGISTER)+ .cloned()+ .unwrap();+ let registration_body =+ serde_json::from_str::<serde_json::Value>(®istration_request.1.unwrap()).unwrap();+ assert_eq!(+ registration_body.get("redirect_uris"),+ Some(&serde_json::json!([format!(+ "http://localhost:{port}/callback"+ )]))+ );}/// The Vercel shape (TS parity): a root endpoint whose declareddiff --git a/crates/pa-core/src/mcp/oauth_callback.rs b/crates/pa-core/src/mcp/oauth_callback.rsindex ed6c5f3e5f..5d8f067fe3 100644--- a/crates/pa-core/src/mcp/oauth_callback.rs+++ b/crates/pa-core/src/mcp/oauth_callback.rs@@ -6,7 +6,7 @@ use std::future::Future;use std::pin::Pin;use std::sync::{Arc, Mutex};-use anyhow::{anyhow, Result};+use anyhow::{anyhow, bail, Result};use tokio::io::{AsyncReadExt, AsyncWriteExt};use tokio::net::TcpListener;@@ -25,12 +25,30 @@ fn redirect_uri_for(port: u16) -> String {format!("http://localhost:{port}{CALLBACK_PATH}")}+pub(super) fn validate_callback_port(callback_port: Option<u16>) -> Result<()> {+ if callback_port == Some(0) {+ bail!("OAuth callbackPort must be between 1 and 65535");+ }+ Ok(())+}++fn candidate_ports(callback_port: Option<u16>) -> Result<Vec<u16>> {+ validate_callback_port(callback_port)?;+ Ok(match callback_port {+ Some(port) => vec![port],+ None => (0..CALLBACK_PORT_COUNT)+ .map(|offset| CALLBACK_PORT_BASE + offset)+ .collect(),+ })+}+/// Every redirect URI a login registers (dynamic client registration/// offers them all).-pub fn all_redirect_uris() -> Vec<String> {- (0..CALLBACK_PORT_COUNT)- .map(|offset| redirect_uri_for(CALLBACK_PORT_BASE + offset))- .collect()+pub fn redirect_uris(callback_port: Option<u16>) -> Result<Vec<String>> {+ Ok(candidate_ports(callback_port)?+ .into_iter()+ .map(redirect_uri_for)+ .collect())}/// The authorization code plus the echoed `state` from the browser@@ -78,16 +96,9 @@ impl CallbackServer {/// Bind a registered port exactly, or the first free DCR candidate. Never substitute/// an unregistered redirect port when the registered one is occupied.pub async fn start(label: &str, callback_port: Option<u16>) -> Result<Self> {- if callback_port == Some(0) {- return Err(anyhow!("The OAuth callback port must be nonzero ({label})"));- }let host = callback_host();let mut last_error: Option<String> = None;- let ports = callback_port.map_or_else(- || (CALLBACK_PORT_BASE..CALLBACK_PORT_BASE + CALLBACK_PORT_COUNT).collect(),- |port| vec![port],- );- for port in ports {+ for port in candidate_ports(callback_port)? {let listener = match TcpListener::bind((host.as_str(), port)).await {Ok(listener) => listener,Err(error) => {@@ -555,4 +566,27 @@ mod tests {assert_eq!(query_param("code=a+b", "code"), Some("a b".to_string()));assert_eq!(query_param("code", "state"), None);}+ #[tokio::test]+ async fn zero_callback_port_is_rejected_before_binding_or_registration() {+ assert!(redirect_uris(Some(0))+ .unwrap_err()+ .to_string()+ .contains("callbackPort"));+ let error = CallbackServer::start("fixture", Some(0)).await.unwrap_err();+ assert!(error.to_string().contains("callbackPort"));+ }++ #[tokio::test]+ async fn pinned_port_rebinds_after_drop() {+ let probe = std::net::TcpListener::bind("127.0.0.1:0").unwrap();+ let port = probe.local_addr().unwrap().port();+ drop(probe);+ {+ let first = CallbackServer::start("Linear", Some(port)).await.unwrap();+ assert_eq!(first.redirect_uri(), redirect_uri_for(port));+ }+ tokio::task::yield_now().await;+ let second = CallbackServer::start("Linear", Some(port)).await.unwrap();+ assert_eq!(second.redirect_uri(), redirect_uri_for(port));+ }}diff --git a/crates/pa-core/src/mcp/oauth_discovery.rs b/crates/pa-core/src/mcp/oauth_discovery.rsindex 8779f5d238..cbe61d3c34 100644--- a/crates/pa-core/src/mcp/oauth_discovery.rs+++ b/crates/pa-core/src/mcp/oauth_discovery.rs@@ -430,11 +430,12 @@ pub(crate) async fn register_client(registration_endpoint: &str,label: &str,scope: Option<&str>,+ callback_port: Option<u16>,) -> Result<String> {validated_https_url(registration_endpoint, "Registration endpoint")?;let mut body = serde_json::json!({"client_name": format!("Prime Agent ({label})"),- "redirect_uris": super::oauth_callback::all_redirect_uris(),+ "redirect_uris": super::oauth_callback::redirect_uris(callback_port)?,"grant_types": ["authorization_code", "refresh_token"],"response_types": ["code"],"token_endpoint_auth_method": "none",diff --git a/crates/pa-daemon/src/mcp_login.rs b/crates/pa-daemon/src/mcp_login.rsindex 82b161b594..7c252430d7 100644--- a/crates/pa-daemon/src/mcp_login.rs+++ b/crates/pa-daemon/src/mcp_login.rs@@ -231,6 +231,8 @@ mod tests {disabled_tools: None,startup_timeout_ms: None,call_timeout_ms: None,+ client_id: None,+ callback_port: None,},);let manager = McpManager::new(McpManagerOptions {diff --git a/scripts/review_mcp_oauth_config_parity.py b/scripts/review_mcp_oauth_config_parity.pynew file mode 100644index 0000000000..a6c11000cc--- /dev/null+++ b/scripts/review_mcp_oauth_config_parity.py@@ -0,0 +1,184 @@+#!/usr/bin/env python3+"""Actual TS/Rust settings -> live mcp.config roundtrip for clientId/callbackPort.++This exercises real daemon/kernel config delivery before and after reload.+It never performs network OAuth, opens a browser or uses real credentials.+Hosted production OAuth tests separately check registration/authorize/token+redirects and zero/busy-port rejection; this receipt does not replace them.+"""+import argparse+import http.server+import json+import os+from pathlib import Path+import subprocess+import sys+import tempfile+import threading++from review_kernel_env_parity import KernelClient as Client+from review_draft_disconnect_parity import env_for, digest, TS_ARCHIVE_SHA256+from review_goal_fixture_lifecycle import OwnedProcesses, TAG, finish+from review_restore_notice_parity import texts++MARKER = 'MCP_OAUTH_CONFIG_RESULT='+NAMES = ('fixture-oauth', 'fixture-default')+DEFAULT = {'type': 'http', 'url': 'https://fixture.invalid/default', 'oauth': True}+BEFORE = {'type': 'http', 'url': 'https://fixture.invalid/mcp', 'oauth': True,+ 'clientId': 'fixture-client-before', 'callbackPort': 3118}+AFTER = {**BEFORE, 'clientId': 'fixture-client-after', 'callbackPort': 4118}+CELL = """from rlm import host_request+oauth_configs = {}+for name in ('fixture-oauth', 'fixture-default'):+ oauth_configs[name] = await host_request('mcp.config', {'server': name})+print('MCP_OAUTH_CONFIG_RESULT=' + __import__('json').dumps(oauth_configs))"""+++class Provider(http.server.ThreadingHTTPServer):+ daemon_threads = True++ def __init__(self):+ super().__init__(('127.0.0.1', 0), Handler)+ self.phase = 'before'+ self.requests = {'before': [], 'after': []}+ self.errors = []+++class Handler(http.server.BaseHTTPRequestHandler):+ def log_message(self, *_args):+ pass++ def do_POST(self):+ if self.path != '/v1/chat/completions':+ self.send_error(404)+ return+ body = json.loads(self.rfile.read(int(self.headers['Content-Length'])))+ requests = self.server.requests[self.server.phase]+ requests.append(body)+ if len(requests) == 1:+ offered = {tool['function']['name'] for tool in body.get('tools', [])}+ name = next((n for n in ('python_repl', 'ipython') if n in offered), None)+ if name is None:+ self.server.errors.append('no Python REPL tool')+ self.send_error(422)+ return+ delta = {'tool_calls': [{'index': 0, 'id': 'oauth_config_' + self.server.phase,+ 'type': 'function', 'function': {'name': name, 'arguments': json.dumps({'code': CELL})}}]}+ reason = 'tool_calls'+ else:+ delta, reason = {'content': 'Config fixture complete.'}, 'stop'+ def chunk(delta, reason=None):+ return {'id': 'oauth-config-fixture', 'object': 'chat.completion.chunk', 'created': 1,+ 'model': 'oauth-config-fixture', 'choices': [{'index': 0, 'delta': delta, 'finish_reason': reason}]}+ wire = ''.join('data: ' + json.dumps(row) + '\n\n' for row in (+ chunk({'role': 'assistant', **delta}), chunk({}, reason))) + 'data: [DONE]\n\n'+ self.send_response(200)+ self.send_header('Content-Type', 'text/event-stream')+ self.send_header('Content-Length', str(len(wire.encode())))+ self.end_headers()+ self.wfile.write(wire.encode())+++def extract(requests, phase):+ assert len(requests) == 2, 'unexpected provider sequence'+ rows = [row for row in requests[-1]['messages'] if row.get('role') == 'tool'+ and row.get('tool_call_id') == 'oauth_config_' + phase]+ assert len(rows) == 1, 'missing/duplicate current config result'+ probes = [json.loads(line[len(MARKER):]) for text in texts(rows[0].get('content'))+ for line in text.splitlines() if line.startswith(MARKER)]+ assert len(probes) == 1, 'missing/duplicate actual config probe'+ return probes[0]+++def validate(observed):+ assert observed['before'] == {'fixture-oauth': BEFORE, 'fixture-default': DEFAULT}, observed+ assert observed['after'] == {'fixture-oauth': AFTER, 'fixture-default': DEFAULT}, observed+++def observe(binary, kind, root, observed):+ env = env_for(root, kind)+ env[TAG] = str(root)+ provider = Provider()+ thread = threading.Thread(target=provider.serve_forever, daemon=True)+ thread.start()+ settings = {'prewarmPythonKernel': False, 'mcpServers': {+ 'fixture-oauth': BEFORE, 'fixture-default': DEFAULT}}+ settings_path = root / 'agent/settings.json'+ settings_path.write_text(json.dumps(settings))+ (root / 'agent/models.json').write_text(json.dumps({'providers': {'fixture': {+ 'api': 'openai-completions', 'apiKey': 'fixture-only',+ 'baseUrl': f'http://127.0.0.1:{provider.server_port}/v1', 'models': [{+ 'id': 'oauth-config-fixture', 'name': 'OAuth config fixture', 'reasoning': False,+ 'contextWindow': 128000, 'maxTokens': 4096}]}}}))+ path = root / 'd.sock'+ scope = OwnedProcesses(binary, root, path)+ daemon = client = None+ log = (root / 'daemon.log').open('w')+ try:+ command = [str(binary), '--mode', 'daemon', '--daemon-socket', str(path)]+ daemon = subprocess.Popen(command, cwd=root, env=env, stdout=log,+ stderr=subprocess.STDOUT, start_new_session=True)+ scope.register(daemon, command)+ client = Client(path, daemon)+ observed['hello'] = client.hello+ created = client.call('create', config={'cwd': str(root), 'agentDir': str(root / 'agent'),+ 'provider': 'fixture', 'model': 'oauth-config-fixture', 'telemetryDisabled': True})+ active = created.get('activeSessionId') or created.get('sessionId') or created.get('id')+ assert active, created+ client.call('attach', activeSessionId=active)+ for phase in ('before', 'after'):+ provider.phase = phase+ if phase == 'after':+ settings['mcpServers']['fixture-oauth'] = AFTER+ settings_path.write_text(json.dumps(settings))+ client.call('reload', activeSessionId=active)+ client.call('prompt', activeSessionId=active, message='Probe OAuth config ' + phase)+ client.call('wait_for_idle', activeSessionId=active)+ observed[phase] = extract(provider.requests[phase], phase)+ assert not provider.errors, provider.errors+ validate(observed)+ observed['behavior_verified'] = True+ finally:+ observed['provider_requests'] = provider.requests+ observed['wire'] = list(client.wire) if client else []+ finish(scope, client, daemon, observed)+ log.close()+ observed['daemon_log'] = (root / 'daemon.log').read_text(errors='replace')[-10000:]+ provider.shutdown()+ provider.server_close()+ thread.join(timeout=2)+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument('--receipt', type=Path, required=True)+ args = parser.parse_args()+ result = {'verified': False, 'runs': {}, 'scope': __doc__, 'not_verified': [+ 'actual authorization browser callback or token exchange', 'credentialed Slack login',+ 'live refresh-token compatibility', 'TUI rendering']}+ try:+ assert sys.platform == 'linux'+ assert digest(Path(os.environ['PA_TS_ARCHIVE'])) == TS_ARCHIVE_SHA256+ result['ts_archive_sha256'] = TS_ARCHIVE_SHA256+ with tempfile.TemporaryDirectory(prefix='pa-oauth-config-', dir='/tmp') as folder:+ for kind in ('ts', 'rust'):+ binary = Path(os.environ[f'PA_{kind.upper()}_BINARY']).resolve()+ observed = result['runs'][kind] = {'binary_sha256': digest(binary)}+ try:+ observe(binary, kind, Path(folder) / kind, observed)+ except Exception as error:+ observed['error'] = str(error)+ assert all(r.get('behavior_verified') and r.get('cleanup_verified') and 'error' not in r+ for r in result['runs'].values()), 'actual OAuth config observation failed'+ for phase in ('before', 'after'):+ assert result['runs']['ts'][phase] == result['runs']['rust'][phase]+ result['verified'] = True+ except Exception as error:+ result['error'] = str(error)+ args.receipt.parent.mkdir(parents=True, exist_ok=True)+ args.receipt.write_text(json.dumps(result, ensure_ascii=False, indent=2))+ return 0 if result['verified'] else 1+++if __name__ == '__main__':+ sys.exit(main())diff --git a/scripts/test_review_mcp_oauth_config_parity.py b/scripts/test_review_mcp_oauth_config_parity.pynew file mode 100644index 0000000000..539b108737--- /dev/null+++ b/scripts/test_review_mcp_oauth_config_parity.py@@ -0,0 +1,64 @@+#!/usr/bin/env python3+import ast+import asyncio+import contextlib+import io+import sys+import types+from unittest.mock import patch+import copy+import json+import unittest+from review_mcp_oauth_config_parity import BEFORE, AFTER, DEFAULT, MARKER, CELL, extract, validate+++class OAuthConfigGuards(unittest.TestCase):+ def test_fields_reload_and_default_absence_are_exact(self):+ good = {'before': {'fixture-oauth': BEFORE, 'fixture-default': DEFAULT},+ 'after': {'fixture-oauth': AFTER, 'fixture-default': DEFAULT}}+ validate(good)+ for phase in ('before', 'after'):+ for key in ('clientId', 'callbackPort'):+ changed = copy.deepcopy(good)+ del changed[phase]['fixture-oauth'][key]+ with self.assertRaises(AssertionError):+ validate(changed)+ changed = copy.deepcopy(good)+ changed['after'] = changed['before']+ with self.assertRaises(AssertionError):+ validate(changed)+ changed = copy.deepcopy(good)+ changed['before']['fixture-default']['callbackPort'] = 0+ with self.assertRaises(AssertionError):+ validate(changed)++ def test_actual_cell_compiles_and_awaits_both_requests(self):+ calls = []+ async def host_request(kind, payload):+ calls.append((kind, payload))+ return BEFORE if payload['server'] == 'fixture-oauth' else DEFAULT+ module = types.ModuleType('rlm')+ module.host_request = host_request+ output = io.StringIO()+ code = compile(CELL, 'fixture-cell', 'exec', flags=ast.PyCF_ALLOW_TOP_LEVEL_AWAIT)+ with patch.dict(sys.modules, {'rlm': module}), contextlib.redirect_stdout(output):+ asyncio.run(eval(code, {}))+ self.assertEqual(calls, [('mcp.config', {'server': 'fixture-oauth'}),+ ('mcp.config', {'server': 'fixture-default'})])+ self.assertEqual(json.loads(output.getvalue().strip().removeprefix(MARKER)),+ {'fixture-oauth': BEFORE, 'fixture-default': DEFAULT})++ def test_current_real_tool_result_is_required(self):+ value = {'fixture-oauth': BEFORE, 'fixture-default': DEFAULT}+ tool = {'role': 'tool', 'tool_call_id': 'oauth_config_before',+ 'content': MARKER + json.dumps(value)}+ self.assertEqual(extract([{}, {'messages': [tool]}], 'before'), value)+ for rows in [[{'messages': [tool]}, {'messages': []}],+ [{}, {'messages': [tool, tool]}],+ [{}, {'messages': [{**tool, 'tool_call_id': 'historical'}]}]]:+ with self.assertRaises(AssertionError):+ extract(rows, 'before')+++if __name__ == '__main__':+ unittest.main()