Skip to content

MCP shutdown can lose a rotated refresh token during session cleanup #41133

Open

Description

@liangxiwei

Summary

Codex can lose a rotated MCP OAuth refresh token when an MCP client is shut down while transport cleanup is refreshing credentials. The provider successfully consumes RT1 and returns AT2/RT2, but Codex may drop the in-memory credential store before copying RT2 to its durable credential store. A later process then retries RT1, which a rotating-token provider correctly treats as reuse and may revoke the entire token family.

This is a lifecycle/persistence race, not an ordinary access-token expiration problem.

Observed case (redacted)

This happened with Codex desktop's bundled CLI 0.150.0-alpha.8 on macOS arm64. Provider and local credential-store timestamps showed:

  • 07:50:40.602 UTC: AT2 expired.
  • 07:50:47.614 UTC: the Codex app-server began shutting down an inactive task instance.
  • 07:50:47.902 UTC: the OAuth provider committed the RT2 exchange and issued AT3/RT3, about 288 ms after task teardown began.
  • The durable MCP OAuth credential entry retained AT2/RT2 and its modification time did not advance past 06:50:40 UTC.
  • 07:52:42.652 UTC: another Codex process retried RT2, about 115 seconds after the successful rotation. The provider detected reuse and revoked the token family.

Token values, client IDs, family IDs, workspace IDs, and private endpoints are intentionally omitted.

The exact client-side refresh-request start timestamp was not retained, so the shutdown-triggered request cannot be proven from timestamps alone. However, the source path below, the 288 ms overlap, the successful provider-side rotation, and the unchanged durable store make transport cleanup during teardown the strongest source-backed explanation.

Root cause

Codex configures RMCP with an InMemoryCredentialStore and separately copies changes into its durable credential store through OAuthPersistor after normal initialization and tool-call paths.

During RmcpClient::shutdown(), Codex previously replaced the state with Closed and dropped the prior ClientState::Ready. Dropping RMCP's running streamable-HTTP service asynchronously performs session cleanup, including an authenticated DELETE. RMCP obtains an access token for that request and can refresh it when the token is expired or near expiry. That refresh updates only RMCP's in-memory credential store.

At that point there is no later Codex persistence hook: the OAuthPersistor is being dropped together with the service. If the outer shutdown future or task instance is cancelled while the provider is answering, the replacement refresh token is lost even though the provider committed the rotation.

The current refresh request also has no Idempotency-Key, but adding request idempotency alone would not make the returned replacement token durable. Shutdown must not expose a provider-side rotation unless Codex can persist the replacement.

Expected behavior

MCP teardown must satisfy both properties:

  1. Cancellation of the shutdown caller must not discard an in-flight rotating refresh response.
  2. Transport cleanup must not independently consume a refresh token after the durable OAuth owner has begun shutting down.

Proposed fix and proof of concept

I implemented a proof of concept here:

The change:

  • Moves ownership of the previous client state into an independently owned Tokio shutdown task, so cancelling the caller does not drop the service or OAuth state mid-response.
  • Before dropping the transport, persists any RMCP-managed credential change and runs the existing serialized/cross-process refresh transaction when the token is near expiry.
  • Persists the replacement before exposing it to transport cleanup.
  • Removes the refresh token only from RMCP's cleanup-only in-memory view, so the final authenticated session DELETE can use the access token but cannot trigger another hidden rotation.

Regression test

The added integration test models the observed lifecycle race:

  1. Store AT1/RT1 with a 32-second access-token lifetime.
  2. Enter RMCP's 30-second refresh window.
  3. Start shutdown; delay the provider's RT1 -> AT2/RT2 response by 300 ms.
  4. Cancel the outer shutdown caller after 100 ms.
  5. Verify exactly one refresh exchange occurred, AT2/RT2 are in the durable store, and transport cleanup sends its session DELETE with AT2.

Targeted result:

just test -p codex-rmcp-client --test streamable_http_oauth_shutdown
1 passed, 1 skipped

The full codex-rmcp-client package run completed with 266 passing tests, 8 skipped, and 5 unrelated environment-dependent failures (proxy authorization expectations, two remote-executor mock expectations, and a missing locally built target/debug/codex binary). just fmt and just fix -p codex-rmcp-client completed successfully.

Related reports

This issue focuses specifically on losing a successfully rotated refresh token during MCP task/client teardown.

Activity

  1. added
    bug
    CLI
    mcp
    auth
    on Aug 27, 2026
  2. liangxiwei commented on Aug 31, 2026

    @liangxiwei
    Author

    Follow-up: reproduced on the exact current Desktop release source

    I investigated a second, independent occurrence after filing this issue. This follow-up is specifically intended to separate the current-version evidence from the local proof-of-concept commit linked in the issue body.

    Exact version under test

    The affected Codex Desktop bundle reports:

    codex-cli 0.151.0-alpha.7.2
    

    The corresponding official release tag resolves to:

    rust-v0.151.0-alpha.7.2
    f70e26c29ccb731e22d1104de550b1b9594d7070
    

    I fetched that tag and ran the regression against a checkout whose product source was exactly that release commit. The only added file was the integration test; no rmcp-client implementation file was changed. The release locks rmcp to 3.1.3.

    For an additional cross-check, the relevant files in my current checkout are byte-identical to the official tag (git diff --exit-code returned 0 for oauth.rs, oauth/refresh_transaction.rs, rmcp_client.rs, and streamable_http_retry.rs).

    The earlier local PoC implementation was therefore not used as evidence that the bug exists in the current release. Only its black-box test scenario was applied to the exact release source.

    Second production timeline

    The provider database and the macOS credential-store metadata show the following sequence (UTC; all token values and private identifiers are omitted):

    2026-08-31 03:03:20  Durable Keychain entry last modified with AT1/RT1
    2026-08-31 03:03:22  Token family and initial AT1/RT1 created
    2026-08-31 04:03:22  AT1 expired
    2026-08-31 04:17:50  RT1 successfully consumed; provider issued AT2/RT2
    2026-08-31 04:58:38  RT1 was presented again outside the 30-second grace period;
                         provider revoked the family as refresh_token_reuse
    

    Important observations:

    • The provider did create the replacement RT2 at 04:17:50.
    • The Keychain entry's modification time did not advance at 04:17:50; it still contained RT1.
    • There was no fallback file credential store containing RT2.
    • The same Codex app-server process was alive at both 04:17 and 04:58, so this was not a process-restart persistence gap.
    • At 04:58, Codex surfaced MCP OAuth refresh token was rejected; reauthorization required; the provider-side error was invalid_grant because the old rotating refresh token had been reused.

    This establishes that the first exchange succeeded at the provider, but the returned replacement credentials did not reach Codex's durable credential authority.

    Current release source path

    Normal foreground MCP operations are protected correctly: they run Codex's serialized refresh transaction before the operation and copy RMCP-managed changes to the durable store afterward. For example:

    The lifecycle gap is outside that path:

    1. RmcpClient::shutdown() first replaces the state with ClientState::Closed, then drops the previous ready state.
    2. Once the state is Closed, oauth_persistor() can no longer return the persistor.
    3. Dropping/closing RMCP's running service closes the streamable-HTTP transport. RMCP 3.1.3 performs an authenticated session DELETE during that cleanup.
    4. RMCP's authenticated HTTP wrapper calls get_access_token() for the cleanup request. If the token has less than its 30-second buffer remaining, or if the server challenges it, RMCP can perform a refresh itself.
    5. That refresh saves AT2/RT2 only to the AuthorizationManager's configured credential store. In this integration, Codex deliberately configures that manager with an InMemoryCredentialStore and separately owns durable persistence.
    6. There is no post-cleanup persistence hook in shutdown(), and the persistor is no longer reachable from client state. The service and in-memory RT2 are then dropped, leaving RT1 in Keychain.

    The same general risk exists for any RMCP background/reconnect/challenge path that can refresh without passing through Codex's foreground pre-refresh/post-persist hooks. For example, send_event_stream_request() has neither hook.

    Exact-release regression result

    The test models the lifecycle window as follows:

    1. Store AT1/RT1 with a 32-second access-token lifetime.
    2. Wait until RMCP's 30-second refresh window.
    3. Start shutdown; make the token endpoint delay the RT1 -> AT2/RT2 response by 300 ms.
    4. Abort the outer shutdown caller after 100 ms.
    5. Wait for background cleanup, then read the durable file credential store.

    Command:

    just test -p codex-rmcp-client --test streamable_http_oauth_shutdown \
      cancelled_shutdown_persists_rotated_refresh_token_before_session_cleanup -- --nocapture
    

    Against the unmodified f70e26c29 product source, nextest retried the test and both attempts failed identically:

    assertion `left == right` failed
      left: "shutdown-refresh-token-1"
     right: "shutdown-refresh-token-2"
    

    Running the access-token assertion first independently produced:

    assertion `left == right` failed
      left: "shutdown-access-token-1"
     right: "shutdown-access-token-2"
    

    Thus the exact current release reproduces the key invariant from production: the provider consumes RT1 and returns AT2/RT2 during transport cleanup, while the durable store remains on AT1/RT1.

    Confidence and remaining ambiguity

    The provider/Ingress configuration did not retain a request-level HTTP access log for the 04:17:50 exchange, so I cannot prove whether that specific production refresh was initiated by the shutdown DELETE or by a background GET/SSE reconnect. Both paths use RMCP's authenticated transport wrapper and can enter the same in-memory refresh path.

    However, the root-cause layer is now directly supported by all three of the following:

    1. Provider-side proof that RT1 was successfully rotated to RT2.
    2. Durable-store proof that RT2 was never committed.
    3. A deterministic failure on the exact official release source showing shutdown/session cleanup loses RT2 in precisely that way.

    The shutdown DELETE remains the strongest matching trigger and is sufficient to reproduce the bug. This is not a provider failure to return a rotated refresh token, and it does not go through Codex's existing cross-process refresh transaction; it is an RMCP-managed refresh that bypasses the durable transaction entirely.

  3. petaxie commented on Sep 10, 2026

    @petaxie

    Independently reproduced on the unmodified 0.153.4 Desktop binary (file store)

    Adding a black-box reproduction of this issue on codex-cli 0.153.4, bundled in ChatGPT.app, macOS 26.6.2 arm64. No product source changes or real OAuth credentials are required. Two expired-token runs reproduced; a fresh-token shutdown control passed.

    Unlike the cancellation regression above, this reproduction uses ordinary thread/archive through the native app-server. It does not abort the shutdown caller or intentionally delay the token response.

    Reproduction

    1. Start a local stateful streamable-HTTP MCP server with SSE and authenticated DELETE, strict single-use rotating refresh tokens, and 70-second access tokens.
    2. Use a disposable CODEX_HOME and explicit mcp_oauth_credentials_store_mode = "file".
    3. Initialize and ping. The first rotation is correctly persisted as AT1/RT1.
    4. Complete one local mock Responses turn so the thread has a rollout and can be archived. This is fixed localhost output, not model inference.
    5. Idle 71 seconds without MCP operations.
    6. Archive the thread. Cleanup refreshes RT1 → AT2/RT2; DELETE succeeds using AT2.
    7. Read the credential file after 8 seconds: it still contains AT1/RT1.
    8. Start a second app-server with the same disposable home. It presents RT1 and receives invalid_grant: Unknown refresh token.

    Observed expired-run sequence (synthetic labels):

    [
      {"event":"refresh_ok","old":0,"new":1},
      {"event":"sse_open"},
      {"event":"ping","generation":1},
      {"event":"refresh_ok","old":1,"new":2},
      {"event":"delete","access":"access-2","valid":true},
      {"event":"sse_closed"},
      {"event":"refresh_rejected","presented":"refresh-1","current_generation":2}
    ]

    The fixture observes SSE closure when its next heartbeat write notices the disconnect, so that event's list position is not an exact client-side close timestamp.

    Case Server generation after cleanup Durable token New process
    Expired run 1 2 refresh-1 invalid_grant
    Expired run 2 2 refresh-1 invalid_grant
    Fresh control (skip idle wait) 1 refresh-1 ping succeeds

    Source correspondence / scope

    The observed behavior matches the issue's path: RmcpClient::shutdown() transitions to Closed and drops the prior ready state; RMCP cleanup can refresh for DELETE, with no subsequent durable persistence hook.

    This is not evidence that ordinary file writes universally fail or that file credentials are being migrated to Keychain during refresh. Normal startup persists correctly in this test. Keychain mode and other releases have not been tested here.

    thread/unsubscribe alone is not an immediate shutdown trigger: the release has a 30-minute idle unload delay. Using a mock turn followed by archive avoids that wait while exercising transport cleanup.

    Runnable fixture

    Save the two files below in one directory. Python 3 standard library only. Adjust BIN in repro.py to the exact installed binary under test.

    python3 shutdown_repro.py --case expired
    python3 shutdown_repro.py --case fresh

    The script prints a temporary report path and structured results. All token values are synthetic, and each run has a separate temporary home. It terminates its children/server on completion. Native app-server startup can still attempt unauthenticated remote plugin/catalog requests; this is credential-isolated, not network-isolated. No real model endpoint is configured for the turn. ConnectionResetError noise from abandoned fixture HTTP connections is not the reproduction signal; use the report's reproduced / control_passed fields and events.

    repro.py — shared synthetic OAuth server and native app-server client
    """Isolated synthetic MCP OAuth rotation probe. No model requests or real credentials."""
    import concurrent.futures
    import hashlib
    import json
    import os
    from pathlib import Path
    import queue
    import subprocess
    import tempfile
    import threading
    import time
    from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
    from urllib.parse import parse_qs
    
    BIN = '/Applications/ChatGPT.app/Contents/Resources/codex'
    TTL = 12
    events = []
    guard = threading.Lock()
    generation = 0
    access = {'access-0': time.time() - 1}
    origin = ''
    
    class Handler(BaseHTTPRequestHandler):
        def log_message(self, *args):
            pass
    
        def respond(self, status, data, headers=None):
            raw = json.dumps(data).encode()
            self.send_response(status)
            self.send_header('Content-Type', 'application/json')
            for k, v in (headers or {}).items():
                self.send_header(k, v)
            self.send_header('Content-Length', str(len(raw)))
            self.end_headers()
            self.wfile.write(raw)
    
        def do_GET(self):
            if 'oauth-protected-resource' in self.path:
                return self.respond(200, {'resource': origin + '/mcp', 'authorization_servers': [origin], 'scopes_supported': ['test']})
            if 'oauth-authorization-server' in self.path or 'openid-configuration' in self.path:
                return self.respond(200, {'issuer': origin, 'authorization_endpoint': origin + '/authorize', 'token_endpoint': origin + '/token', 'registration_endpoint': origin + '/register', 'response_types_supported': ['code'], 'grant_types_supported': ['authorization_code', 'refresh_token'], 'token_endpoint_auth_methods_supported': ['none'], 'code_challenge_methods_supported': ['S256']})
            return self.respond(405, {})
    
        def do_POST(self):
            global generation
            raw = self.rfile.read(int(self.headers.get('Content-Length', '0')))
            if self.path == '/token':
                form = parse_qs(raw.decode())
                token = form.get('refresh_token', [''])[0]
                with guard:
                    old = generation
                    if form.get('grant_type') != ['refresh_token'] or form.get('client_id') != ['synthetic-client'] or token != f'refresh-{old}':
                        events.append({'event': 'refresh_rejected', 'presented': token, 'current_generation': old})
                        return self.respond(400, {'error': 'invalid_grant', 'error_description': 'Unknown refresh token'})
                    generation += 1
                    access[f'access-{generation}'] = time.time() + TTL
                    events.append({'event': 'refresh_ok', 'old': old, 'new': generation})
                    return self.respond(200, {'access_token': f'access-{generation}', 'refresh_token': f'refresh-{generation}', 'token_type': 'Bearer', 'expires_in': TTL, 'scope': 'test'})
            if self.path != '/mcp':
                return self.respond(404, {})
            token = self.headers.get('Authorization', '').removeprefix('Bearer ')
            if access.get(token, 0) <= time.time():
                events.append({'event': 'mcp_401'})
                return self.respond(401, {}, {'WWW-Authenticate': f'Bearer error="invalid_token", resource_metadata="{origin}/.well-known/oauth-protected-resource/mcp"'})
            msg = json.loads(raw)
            method = msg.get('method')
            if 'id' not in msg:
                return self.respond(202, {})
            if method == 'initialize':
                result = {'protocolVersion': msg['params']['protocolVersion'], 'capabilities': {'tools': {}}, 'serverInfo': {'name': 'synthetic-rotation', 'version': '1'}}
            elif method == 'tools/list':
                result = {'tools': [{'name': 'ping', 'description': 'Synthetic read-only ping', 'inputSchema': {'type': 'object'}, 'annotations': {'readOnlyHint': True}}]}
            elif method == 'tools/call':
                events.append({'event': 'ping', 'generation': generation})
                result = {'content': [{'type': 'text', 'text': 'pong'}], 'isError': False}
            elif method in ('resources/list', 'resources/templates/list'):
                result = {'resources': []} if method == 'resources/list' else {'resourceTemplates': []}
            else:
                result = {}
            self.respond(200, {'jsonrpc': '2.0', 'id': msg['id'], 'result': result})
    
    class Client:
        def __init__(self, root, label):
            # CODEX_HOME is used for its documented isolation purpose, only in child env.
            env = dict(os.environ, CODEX_HOME=str(root), RUST_LOG='warn')
            for key in ('OPENAI_API_KEY', 'OPENAI_BASE_URL', 'CHATGPT_TOKEN'):
                env.pop(key, None)
            self.err = open(root / (label + '.stderr'), 'w')
            self.p = subprocess.Popen([BIN, 'app-server'], cwd=root, env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=self.err, text=True)
            self.q = queue.Queue()
            self.n = 0
            threading.Thread(target=self.reader, daemon=True).start()
            self.rpc('initialize', {'clientInfo': {'name': 'oauth-repro', 'version': '1'}, 'capabilities': {'experimentalApi': True}})
            self.thread = self.rpc('thread/start', {'cwd': str(root), 'model': 'gpt-6-astra', 'approvalPolicy': 'never'})['result']['thread']['id']
    
        def reader(self):
            for line in self.p.stdout:
                try:
                    self.q.put(json.loads(line))
                except ValueError:
                    pass
    
        def rpc(self, method, params):
            self.n += 1
            ident = self.n
            self.p.stdin.write(json.dumps({'id': ident, 'method': method, 'params': params}) + '\n')
            self.p.stdin.flush()
            deadline = time.monotonic() + 35
            while time.monotonic() < deadline:
                message = self.q.get(timeout=max(.1, deadline - time.monotonic()))
                if message.get('id') == ident:
                    return message
            raise TimeoutError(method)
    
        def ping(self):
            return self.rpc('mcpServer/tool/call', {'threadId': self.thread, 'server': 'fixture', 'tool': 'ping', 'arguments': {}})
    
        def close(self):
            self.p.terminate()
            try:
                self.p.wait(timeout=5)
            except subprocess.TimeoutExpired:
                self.p.kill()
                self.p.wait()
            self.err.close()
    shutdown_repro.py — stateful transport, local mock turn, archive, and control
    """Reproduce shutdown-time OAuth rotation without durable persistence on 0.153.4.
    
    Uses synthetic credentials, disposable CODEX_HOME and one local fixed-response
    model turn (no real model inference). --case fresh is a non-expiry control.
    """
    import argparse
    import subprocess
    import json
    import hashlib
    import os
    from pathlib import Path
    import tempfile
    import threading
    import time
    from http.server import ThreadingHTTPServer
    import repro as base
    
    class Stateful(base.Handler):
        protocol_version = 'HTTP/1.1'
    
        def do_POST(self):
            if self.path == '/v1/responses':
                self.rfile.read(int(self.headers.get('Content-Length', '0')))
                message = {'id':'msg_mock','type':'message','role':'assistant','status':'completed','content':[{'type':'output_text','text':'Done','annotations':[]}]}
                response = {'id':'resp_mock','object':'response','created_at':int(time.time()),'status':'completed','model':'gpt-6-astra','output':[message],'usage':{'input_tokens':1,'output_tokens':1,'total_tokens':2}}
                events = [{'type':'response.created','response':dict(response,status='in_progress',output=[])}, {'type':'response.output_item.added','output_index':0,'item':dict(message,content=[])}, {'type':'response.output_item.done','output_index':0,'item':message}, {'type':'response.completed','response':response}]
                data = ''.join('event: '+e['type']+'\ndata: '+json.dumps(e)+'\n\n' for e in events).encode()
                self.send_response(200)
                self.send_header('Content-Type','text/event-stream')
                self.send_header('Content-Length',str(len(data)))
                self.end_headers()
                self.wfile.write(data)
                return
            return super().do_POST()
    
        def respond(self, status, data, headers=None):
            headers = dict(headers or {})
            if self.path == '/mcp' and status == 200:
                headers['Mcp-Session-Id'] = 'synthetic-session'
            return super().respond(status, data, headers)
    
        def do_GET(self):
            if self.path != '/mcp':
                return super().do_GET()
            token = self.headers.get('Authorization', '').removeprefix('Bearer ')
            if base.access.get(token, 0) <= time.time():
                return self.respond(401, {}, {'WWW-Authenticate': f'Bearer error="invalid_token", resource_metadata="{base.origin}/.well-known/oauth-protected-resource/mcp"'})
            self.send_response(200)
            self.send_header('Content-Type', 'text/event-stream')
            self.send_header('Cache-Control', 'no-cache')
            self.end_headers()
            base.events.append({'event': 'sse_open'})
            try:
                while True:
                    self.wfile.write(b': heartbeat\n\n')
                    self.wfile.flush()
                    time.sleep(.2)
            except (BrokenPipeError, ConnectionResetError):
                base.events.append({'event': 'sse_closed'})
    
        def do_DELETE(self):
            token = self.headers.get('Authorization', '').removeprefix('Bearer ')
            valid = base.access.get(token, 0) > time.time()
            base.events.append({'event': 'delete', 'access': token, 'valid': valid})
            if not valid:
                return self.respond(401, {}, {'WWW-Authenticate': f'Bearer error="invalid_token", resource_metadata="{base.origin}/.well-known/oauth-protected-resource/mcp"'})
            return self.respond(200, {})
    
    def main():
        parser = argparse.ArgumentParser()
        parser.add_argument('--case', choices=['expired', 'fresh'], default='expired')
        case = parser.parse_args().case
        base.TTL = 70
        root = Path(tempfile.mkdtemp(prefix='sol-oauth-shutdown-'))
        os.chmod(root, 0o700)
        server = ThreadingHTTPServer(('127.0.0.1', 0), Stateful)
        base.origin = f'http://127.0.0.1:{server.server_port}'
        threading.Thread(target=server.serve_forever, daemon=True).start()
        (root/'config.toml').write_text(f'''mcp_oauth_credentials_store_mode = "file"
    cli_auth_credentials_store = "file"
    model_provider = "fixture_model"
    [model_providers.fixture_model]
    name = "Local fixed response"
    base_url = "{base.origin}/v1"
    wire_api = "responses"
    requires_openai_auth = false
    [analytics]
    enabled = false
    [mcp_servers.fixture]
    url = "{base.origin}/mcp"
    startup_timeout_sec = 15
    [mcp_servers.fixture.oauth]
    client_id = "synthetic-client"
    ''')
        payload = json.dumps({'type': 'http', 'url': base.origin+'/mcp', 'headers': {}}, separators=(',', ':'))
        key = 'fixture|'+hashlib.sha256(payload.encode()).hexdigest()[:16]
        (root/'.credentials.json').write_text(json.dumps({key: {'server_name':'fixture','server_url':base.origin+'/mcp','issuer':base.origin,'client_id':'synthetic-client','access_token':'access-0','refresh_token':'refresh-0','expires_at':int((time.time()-1)*1000),'scopes':['test']}}))
        os.chmod(root/'.credentials.json', 0o600)
        clients = []
        report = {'root': str(root), 'case':case, 'version':subprocess.check_output([base.BIN,'--version'],text=True).strip(), 'ttl':base.TTL}
        def disk():
            entries = json.loads((root/'.credentials.json').read_text())
            return max(entries.values(), key=lambda entry: int(entry['refresh_token'].split('-')[-1]))
        try:
            a = base.Client(root, 'first'); clients.append(a)
            report['initial_ping'] = a.ping()
            assert 'result' in report['initial_ping'], report['initial_ping']
            report['mock_turn'] = a.rpc('turn/start', {'threadId':a.thread,'input':[{'type':'text','text':'Return the local fixed test response.'}]})
            deadline = time.monotonic()+30
            while time.monotonic() < deadline:
                event = a.q.get(timeout=30)
                if event.get('method') == 'turn/completed':
                    report['mock_completed'] = event
                    break
            assert 'mock_completed' in report
            report['before_close'] = disk()
            assert len(json.loads((root/'.credentials.json').read_text())) == 1, 'unexpected credential key duplication'
            print(json.dumps({'phase':'ready', 'generation':base.generation, 'disk':disk()['refresh_token']}), flush=True)
            # Let both client and server agree that the access token has expired.
            # Do not invoke any normal MCP operation during this idle period.
            if case == 'expired':
                time.sleep(base.TTL + 1)
            report['unsubscribe'] = a.rpc('thread/archive', {'threadId':a.thread})
            time.sleep(8)
            report['after_close'] = disk()
            report['server_generation_after_close'] = base.generation
            print(json.dumps({'phase':'closed','response':report['unsubscribe'],'generation':base.generation,'disk':disk()['refresh_token'],'events':base.events}), flush=True)
            b = base.Client(root, 'second'); clients.append(b)
            report['reopen_ping'] = b.ping()
            report['reproduced'] = (case == 'expired' and report['server_generation_after_close'] > int(report['after_close']['refresh_token'].split('-')[-1]) and 'Unknown refresh token' in json.dumps(report['reopen_ping']) and any(e['event']=='delete' and e['valid'] for e in base.events))
            report['control_passed'] = case == 'fresh' and 'result' in report['reopen_ping'] and report['before_close']['refresh_token']==report['after_close']['refresh_token']
        except Exception as exc:
            report['exception'] = str(exc)
        finally:
            for client in clients:
                client.close()
            server.shutdown()
            report['events'] = base.events
            (root/'report.json').write_text(json.dumps(report, indent=2))
            print(json.dumps(report), flush=True)
    
    if __name__ == '__main__':
        main()

    No private service endpoints, production token fingerprints, or private project identifiers are included.

    Investigated with GPT-6 Astra and Claude Opus 4.8.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    CLIauthbugmcp

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions