Repository navigation
fix: schedule local continuations with unauthenticated MCP integrations - #160793
roboclaw-bot wants to merge 2 commits into
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: blocked before merge. Reviewed September 28, 2026, 10:06 PM ET / September 29, 2026, 02:06 UTC (Revision 4). ClawSweeper reviewWhat this changesThe branch lets Codex-backed agents schedule continuations with available authorized tools, reports excluded MCP integrations, validates requested tool names, and preserves executable shell aliases. Merge readiness⛔ Blocked before merge - 5 items remain Keep open. Current main still blocks inherited scheduling when unrelated MCP authentication is missing, and the pinned real-Gateway proof supports the proposed repair. The branch also makes mixed finite tool requests fail where the latest release saves their available intersection; no owner acceptance of that upgrade change is recorded. Priority: P2 Review scores
Verification
How this fits togetherAn agent asks OpenClaw to save a future continuation using tools discovered through its Codex runtime and configured MCP integrations. OpenClaw captures a tool ceiling at creation, then the Gateway applies that ceiling and current authority when the job runs. flowchart LR
A[Agent requests continuation] --> B[Codex tool discovery]
B --> C[Creator authority snapshot]
C --> D[Requested tool validation]
D --> E[Saved job tool ceiling]
E --> F[Scheduled run authority checks]
C --> G[Excluded integration warnings]
Decision needed
Why: The branch changes an intentional capture policy and a shipped create/edit behavior, so proof of correct execution cannot authorize the upgrade semantics. Before merge
Findings
Agent review detailsSecurityNone. PR surfaceSource +110, Tests +372, Docs +16. Total +498 across 19 files. View PR surface stats
Review metricsNone. Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. Merge-risk optionsMaintainer options:
Technical reviewBest possible solution: Capture the authorized executable subset with visible exclusions while preserving finite-list intersection as the default; offer atomic required-tool rejection only through an explicitly approved opt-in contract. Do we have a high-confidence way to reproduce the issue? Yes. A pinned real-Gateway baseline reproduced the MCP-authentication rejection, and current main retains the same throw; this reviewer did not run the current-main path. Is this the best way to solve the issue? Partly. The bounded-subset capture addresses the reported failure at the existing authority owner, but atomic rejection of mixed finite lists is an avoidable shipped-behavior break without owner acceptance. Full review comments:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against 6b3033b65ca9. LabelsLabel changes: No label changes. Label justifications:
EvidenceWhat I checked:
Likely related people:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (3 earlier review cycles)
|
Real Gateway before/after proofVerified candidate:
All 16 candidate cases passed. The Gateway, managed Codex 0.158.0, signed-device authentication, SQLite jobs/history, tool dispatch, shell/file effects, and MCP HTTP/OAuth transport were real. Inference and the local MCP/OAuth peers were deterministic synthetic fixtures, not a mock Gateway or direct-helper substitute. No production MCP login/config or operator Gateway was changed.
Limits: this does not claim live-vendor inference or immediate warm MCP-cache invalidation after login. A prior observation retained the existing OAuth startup backoff; the final ceiling control deliberately uses a new Gateway process and fresh discovery. The native mirror labels the unsupported-call result Inspected result artifact{
"sourceSha": "685ddfc5f86d242c115c96b988975421ad962d2c",
"sourceTree": "669c1027a4e95e6bc1daf18263c5eb9c999d2a39",
"cases": 16,
"result": "PASS",
"capUnchanged": true,
"savedCapSize": 43,
"authenticatedNewJobCalls": 1,
"excludedOldJobCalls": 0,
"nativeDenial": "unsupported call: unrelated_oauth__ping",
"nativeMirrorIsError": false,
"gatewayRestartAfterLogin": true,
"revocationDenied": true,
"readOnlyDenied": true
}Inline reproducibility artifact (sanitized; no bearer download URL)Reproduction harnessDeterministic synthetic inference uses the repository’s Responses WebSocket adapter. Gateway, managed Codex, signed-device auth, tool dispatch, MCP HTTP/OAuth exchange, SQLite jobs/history and scheduled shell/file execution are real. All token values in this fixture are public synthetic values; no production configuration or credentials are used. The tested model identifier is parameterized as Pins: baseline Save the seven files under
Scheduled shell calls use the registered The runner asserts exact HEAD/tree and clean tracked bytes. Baseline write-config.mjsimport fs from 'node:fs';
const out=process.env.PROOF_OUT;
const model=process.env.PROOF_MODEL;
if(!model?.startsWith('openai/'))throw Error('Set PROOF_MODEL to a native-tool-surface-capable model supported by the pinned runtime.');
const cfg={gateway:{mode:'local',port:19742,bind:'loopback',auth:{mode:'token',token:'mcp-proof-fixture-token'},controlUi:{enabled:false}},plugins:{enabled:true,allow:['codex'],entries:{codex:{enabled:true,config:{codexDynamicToolsLoading:'direct',appServer:{mode:'yolo',args:['app-server','--listen','stdio://','-c','openai_base_url="http://127.0.0.1:19741/v1"','-c','features.responses_websockets=false','-c','features.responses_websockets_v2=false'],requestTimeoutMs:60000}}}}},agents:{defaults:{model:{primary:model,fallbacks:[]},models:{[model]:{agentRuntime:{id:'codex'}}},workspace:out+'/workspace',skipBootstrap:true,timeoutSeconds:120,sandbox:{mode:'off'}},entries:{main:{default:true,workspace:out+'/workspace'}}},skills:{allowBundled:[]},tools:{codeMode:false,allow:['automations','read','create_goal','bundle-mcp']},mcp:{servers:{healthy:{url:'http://127.0.0.1:19741/mcp/healthy',transport:'streamable-http',enabled:true},unrelated_oauth:{url:'http://127.0.0.1:19741/mcp/blocked',transport:'streamable-http',enabled:true,auth:'oauth',connectionTimeoutMs:5000,requestTimeoutMs:5000}}}};
fs.mkdirSync(out+'/workspace',{recursive:true});fs.mkdirSync(out+'/home',{recursive:true});fs.mkdirSync(out+'/state',{recursive:true});fs.writeFileSync(out+'/config.json',JSON.stringify(cfg,null,2));v2-config.mjsimport fs from 'node:fs';
await import('./write-config.mjs');
const out=process.env.PROOF_OUT;const cfg=JSON.parse(fs.readFileSync(out+'/config.json'));
// An explicit finite global policy intentionally disables native tools and their aliases.
// This owned operator fixture uses the full profile; each saved job still receives its finite captured ceiling.
cfg.tools={profile:'full',codeMode:false,exec:{host:'auto',mode:'full'}};
cfg.agents.defaults.heartbeat={every:'0m'};cfg.agents.defaults.timeoutSeconds=120;
cfg.mcp.servers.unrelated_oauth.oauth={redirectUrl:'http://127.0.0.1:19743/oauth/callback'};
fs.writeFileSync(out+'/config.json',JSON.stringify(cfg,null,2));v2-peer.mjs// Synthetic inference and MCP/OAuth peers; Gateway, Codex and all storage/dispatch are real.
import http from 'node:http';
import fs from 'node:fs';
import {randomUUID,createHash} from 'node:crypto';
import {zstdDecompressSync,gunzipSync} from 'node:zlib';
import {pathToFileURL} from 'node:url';
const out=process.env.PROOF_OUT, source=process.env.PROOF_SOURCE, origin='http://127.0.0.1:19741';
const log=(kind,data={})=>fs.appendFileSync(out+'/peer.jsonl',JSON.stringify({kind,at:new Date().toISOString(),...data})+'\n');
const json=(res,status,body,headers={})=>{res.writeHead(status,{'content-type':'application/json',...headers});res.end(JSON.stringify(body));};
const plans=new Map(), codes=new Map(); let activeTag;
function dispatch(body){
const tag=activeTag, plan=plans.get(tag); if(!plan)throw new Error('No authorized proof scenario');
const outputs=(body.input||[]).filter(x=>x.type==='function_call_output'||x.type==='custom_tool_call_output');
for(const item of outputs)if(item.call_id?.startsWith('call_'+tag+'_'))plan.completed.add(item.call_id);
const index=plan.completed.size, selected=plan.calls[index];
if(selected?.name==='automations'&&(plan.holdCapture||plan.rejectCapture))plan.captureIssued=true;
const specs=(body.tools||[]).flatMap(t=>t.type==='namespace'?(t.tools||[]).map(s=>({...s,namespace:t.name})):[t]);
log('inference',{tag,index,transport:body.type==='response.create'?'websocket':'http',tools:specs.map(x=>x.name||x.function?.name),outputs:outputs.map(x=>({callId:x.call_id,output:x.output}))});
const id='resp_'+randomUUID(), created_at=Math.floor(Date.now()/1000);
const spec=specs.find(x=>(x.name||x.function?.name)===selected?.name);
const item=selected?{type:'function_call',id:'fc_'+randomUUID(),call_id:'call_'+tag+'_'+index,name:selected.name,...((selected.namespace||spec?.namespace)?{namespace:selected.namespace||spec.namespace}:{}),arguments:JSON.stringify(selected.args)}:{type:'message',id:'msg_'+randomUUID(),role:'assistant',status:'completed',phase:'final_answer',content:[{type:'output_text',text:'PROOF_FINISHED_'+tag,annotations:[]}]};
const events=[{type:'response.created',response:{id,object:'response',created_at,model:body.model,status:'in_progress',output:[]}},{type:'response.output_item.added',output_index:0,item:{...item,...(selected?{arguments:''}:{status:'in_progress',content:[]})}}];
if(selected)events.push({type:'response.function_call_arguments.delta',item_id:item.id,output_index:0,delta:item.arguments});
else events.push({type:'response.output_text.delta',item_id:item.id,output_index:0,content_index:0,delta:item.content[0].text},{type:'response.output_text.done',item_id:item.id,output_index:0,content_index:0,text:item.content[0].text});
events.push({type:'response.output_item.done',output_index:0,item},{type:'response.completed',response:{id,object:'response',created_at,model:body.model,status:'completed',output:[item],usage:{input_tokens:100,output_tokens:30,total_tokens:130,input_tokens_details:{cached_tokens:0},output_tokens_details:{reasoning_tokens:0}}}});
return {events,model:body.model};
}
const server=http.createServer(async(req,res)=>{
try{
const url=new URL(req.url,origin);const chunks=[];for await(const c of req)chunks.push(c);let bytes=Buffer.concat(chunks);
if(req.headers['content-encoding']==='zstd')bytes=zstdDecompressSync(bytes);if(req.headers['content-encoding']==='gzip')bytes=gunzipSync(bytes);
const raw=bytes.toString();let body;try{body=JSON.parse(raw)}catch{body={};}
if(url.pathname==='/control'&&req.method==='POST'){activeTag=body.tag;plans.set(body.tag,{calls:body.calls,completed:new Set(),holdCapture:body.holdCapture===true,rejectCapture:body.rejectCapture===true,held:0,releases:[]});return json(res,200,{ok:true});}
if(url.pathname==='/health')return json(res,200,{ok:true});
if(url.pathname==='/probe')return json(res,200,{tag:activeTag,held:plans.get(activeTag)?.held||0});
if(url.pathname==='/release'){const plan=plans.get(activeTag);if(plan){plan.released=true;for(const release of plan.releases)release();}return json(res,200,{ok:true});}
if(url.pathname.startsWith('/mcp/')){
const authorized=req.headers.authorization==='Bearer synthetic-mcp-proof-access';
log('mcp',{path:url.pathname,rpc:body.method,tool:body.params?.name,clientInfo:body.params?.clientInfo,authorized,tag:activeTag});
const plan=plans.get(activeTag);if(url.pathname==='/mcp/healthy'&&body.method==='tools/list'&&plan?.holdCapture&&plan.captureIssued&&!plan.released){plan.held++;log('capture_held',{tag:activeTag});await new Promise(resolve=>plan.releases.push(resolve));}
if((url.pathname==='/mcp/blocked'&&!authorized)||(url.pathname==='/mcp/healthy'&&plan?.rejectCapture&&plan.captureIssued))return json(res,401,{error:'OAuth required'},{'WWW-Authenticate':'Bearer resource_metadata="'+origin+'/.well-known/oauth-protected-resource"'});
if(req.method==='DELETE')return json(res,200,{});if(req.method==='GET'){res.writeHead(405);res.end();return;}if(body.id===undefined){res.writeHead(202);res.end();return;}
let result={};if(body.method==='initialize')result={protocolVersion:'2025-03-26',capabilities:{tools:{}},serverInfo:{name:url.pathname.endsWith('healthy')?'healthy-proof':'oauth-proof',version:'1.0.0'}};
if(body.method==='tools/list')result={tools:[{name:'ping',description:'Harmless protocol proof ping',inputSchema:{type:'object',properties:{}},annotations:{readOnlyHint:true}}]};
if(body.method==='tools/call')result={content:[{type:'text',text:'MCP_PONG_'+(authorized?'AUTHORIZED':'HEALTHY')}]};
return json(res,200,{jsonrpc:'2.0',id:body.id,result});
}
if(url.pathname.startsWith('/.well-known/oauth-protected-resource'))return json(res,200,{resource:origin+'/mcp/blocked',authorization_servers:[origin]});
if(url.pathname.startsWith('/.well-known/'))return json(res,200,{issuer:origin,authorization_endpoint:origin+'/authorize',token_endpoint:origin+'/token',registration_endpoint:origin+'/register',response_types_supported:['code'],grant_types_supported:['authorization_code'],token_endpoint_auth_methods_supported:['none'],code_challenge_methods_supported:['S256']});
if(url.pathname==='/register')return json(res,201,{...body,client_id:'synthetic-proof-client',token_endpoint_auth_method:'none'});
if(url.pathname==='/authorize'){
const code=randomUUID(), redirect=new URL(url.searchParams.get('redirect_uri'));
if(redirect.hostname!=='127.0.0.1'||redirect.port!=='19743')return json(res,400,{error:'unexpected redirect'});
codes.set(code,{challenge:url.searchParams.get('code_challenge'),redirect:redirect.href});redirect.searchParams.set('code',code);redirect.searchParams.set('state',url.searchParams.get('state'));
log('oauth_authorized');res.writeHead(302,{location:redirect.href});res.end();return;
}
if(url.pathname==='/token'){
const params=new URLSearchParams(raw), saved=codes.get(params.get('code'));const valid=saved&&saved.redirect===params.get('redirect_uri')&&saved.challenge===createHash('sha256').update(params.get('code_verifier')||'').digest('base64url');
log('oauth_exchange',{valid:Boolean(valid)});if(!valid)return json(res,400,{error:'invalid_grant'});codes.delete(params.get('code'));
return json(res,200,{access_token:'synthetic-mcp-proof-access',token_type:'Bearer',expires_in:3600});
}
if(url.pathname.endsWith('/models'))return json(res,200,{object:'list',data:[{id:process.env.PROOF_MODEL.split('/').slice(1).join('/'),object:'model'}]});
if(url.pathname==='/v1/responses'&&req.method==='POST'){
const {events}=dispatch(body);if(body.stream===false)return json(res,200,events.at(-1).response);
res.writeHead(200,{'content-type':'text/event-stream'});for(const event of events)res.write('data: '+JSON.stringify(event)+'\n\n');res.end();return;
}
return json(res,404,{error:'unhandled synthetic route'});
}catch(error){log('fixture_error',{message:String(error)});return json(res,500,{error:'fixture error'});}
});
const {attachQaMockResponsesWebSocketServer}=await import(pathToFileURL(source+'/extensions/qa-lab/src/providers/mock-openai/mock-openai-responses-websocket.ts'));
attachQaMockResponsesWebSocketServer({server,dispatch:async({body})=>dispatch(body)});
server.listen(19741,'127.0.0.1',()=>console.log('SYNTHETIC_PEER_READY'));v2-client.mjsimport fs from 'node:fs';
import {randomUUID,generateKeyPairSync,createHash,sign} from 'node:crypto';
import {spawn} from 'node:child_process';
import {setTimeout as sleep} from 'node:timers/promises';
import {pathToFileURL} from 'node:url';
import assert from 'node:assert/strict';
const source=process.env.PROOF_SOURCE,out=process.env.PROOF_OUT,expected=process.env.PROOF_EXPECT;
const {createGatewayWsClient}=await import(pathToFileURL(source+'/scripts/lib/gateway-ws-client.ts'));
const {PROTOCOL_VERSION}=await import(pathToFileURL(source+'/packages/gateway-protocol/src/version.ts'));
const {buildDeviceAuthPayloadV3}=await import(pathToFileURL(source+'/packages/gateway-client/src/device-auth.ts'));
const pair=generateKeyPairSync('ed25519'),publicKey=pair.publicKey.export({format:'der',type:'spki'}).subarray(-32).toString('base64url'),deviceId=createHash('sha256').update(Buffer.from(publicKey,'base64url')).digest('hex');
let challengeResolve,challenge,c;
const events=[];
function createClient(){challenge=new Promise(r=>challengeResolve=r);c=createGatewayWsClient({url:'ws://127.0.0.1:19742',onEvent:e=>{if(e.event==='connect.challenge')challengeResolve(e.payload.nonce);events.push(e);fs.appendFileSync(out+'/gateway-events.jsonl',JSON.stringify(e)+'\n');}});}
const save=(name,value)=>fs.writeFileSync(out+'/'+name+'.json',JSON.stringify(value,null,2));
const report={expected,cases:[],sourceSha:process.env.PROOF_SHA,sourceTree:process.env.PROOF_TREE,baseline:'fb503c9e1f25d8c3877881e55e83d4378eda3676',syntheticPeers:true};
const request=async(method,params)=>{const r=await c.request(method,params,180000);fs.appendFileSync(out+'/rpc.jsonl',JSON.stringify({method,response:r})+'\n');if(!r.ok)throw new Error(method+': '+JSON.stringify(r));return Object.hasOwn(r,'payload')?r.payload:r.result;};
const control=async(tag,calls,extra={})=>{const r=await fetch('http://127.0.0.1:19741/control',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({tag,calls,...extra})});assert(r.ok);};
const toolResults=h=>(h.messages||[]).filter(m=>m.role==='toolResult');
const resultText=h=>toolResults(h).map(m=>JSON.stringify(m.content)).join('\n');
async function turn(tag,calls,extra={}){
await control(tag,calls,extra);const sessionKey='agent:main:mcp-v2-'+tag+'-'+randomUUID();const runId=randomUUID();
const sent=await request('chat.send',{sessionKey,idempotencyKey:runId,message:'Authorized isolated regression proof '+tag+': perform the exact harmless scheduling/tool operation requested by the operator; keep configured permission ceilings. No unrelated integration is required.'});
const done=await request('agent.wait',{runId:sent.runId||runId,timeoutMs:160000});
const history=await request('chat.history',{sessionKey,limit:80});save(tag+'-history',history);save(tag+'-wait',done);
const text=JSON.stringify(history);assert(text.includes('PROOF_FINISHED_'+tag),'Native model final missing: '+tag);
report.cases.push({tag,runId:sent.runId||runId,toolResults:toolResults(history).length});return history;
}
const job=(name,toolsAllow,message)=>({name,declarationKey:'proof-'+name,schedule:{kind:'at',at:'2026-10-28T12:00:00.000Z'},sessionTarget:'isolated',payload:{kind:'agentTurn',message:message||'Perform harmless local shell and file work.',...(toolsAllow?{toolsAllow}:{})},delivery:{mode:'none'},enabled:false,deleteAfterRun:false});
const addCall=j=>({name:'automations',args:{action:'add',job:j}});
async function jobs(){return (await request('cron.list',{includeDisabled:true,limit:100})).jobs;}
async function runJob(tag,savedJob,calls){
await control(tag,calls);const queued=await request('cron.run',{id:savedJob.id,mode:'force'});save(tag+'-enqueue',queued);assert(queued.runId,'scheduled runId missing');
const started=Date.now();let entry;
while(Date.now()-started<160000){const page=await request('cron.runs',{id:savedJob.id,runId:queued.runId,limit:1});entry=page.entries?.[0];if(['ok','error','skipped'].includes(entry?.status))break;await sleep(500);}
assert(entry&&['ok','error','skipped'].includes(entry.status),'No terminal run history: '+tag);save(tag+'-run',entry);
const history=await request('cron.history',{id:savedJob.id,runId:queued.runId,limit:80});save(tag+'-history',history);
report.cases.push({tag,runId:queued.runId,status:entry.status,toolResults:toolResults(history).length});return {entry,history,queued};
}
async function readOnlyCaller(){
const keys=generateKeyPairSync('ed25519'),pub=keys.publicKey.export({format:'der',type:'spki'}).subarray(-32).toString('base64url'),id=createHash('sha256').update(Buffer.from(pub,'base64url')).digest('hex');
let ready;const noncePromise=new Promise(r=>ready=r);
const reader=createGatewayWsClient({url:'ws://127.0.0.1:19742',onEvent:e=>{if(e.event==='connect.challenge')ready(e.payload.nonce);}});
try{
await reader.waitOpen();const nonce=await noncePromise,signedAtMs=Date.now(),scopes=['operator.read'];
const signed=buildDeviceAuthPayloadV3({deviceId:id,clientId:'openclaw-tui',clientMode:'ui',role:'operator',scopes,signedAtMs,token:'mcp-proof-fixture-token',nonce,platform:process.platform});
const connected=await reader.request('connect',{minProtocol:PROTOCOL_VERSION,maxProtocol:PROTOCOL_VERSION,client:{id:'openclaw-tui',version:'1',platform:process.platform,mode:'ui'},role:'operator',scopes,device:{id,publicKey:pub,signature:sign(null,Buffer.from(signed),keys.privateKey).toString('base64url'),signedAt:signedAtMs,nonce},caps:[],auth:{token:'mcp-proof-fixture-token'}},30000);
assert(connected.ok,'Read-only client was not admitted for the scope control');
const denied=await reader.request('cron.add',job('read-only-forbidden'),30000);save('read-only-denial',denied);assert.equal(denied.ok,false,'Read-only caller unexpectedly created automation');assert.match(JSON.stringify(denied.error),/scope|unauthorized|permission|forbidden/i);
assert(!(await jobs()).some(j=>j.name==='read-only-forbidden'));report.readOnlyCallerDenied=true;report.cases.push({tag:'read_only_caller',saved:false});
}finally{reader.close();}
}
async function revokeCreator(){
const tag='revoked_creator',sessionKey='agent:main:mcp-v2-revoke-'+randomUUID(),runId=randomUUID();
await control(tag,[addCall(job('revoked-before-save'))],{holdCapture:true});
const sent=await request('chat.send',{sessionKey,idempotencyKey:runId,message:'Create the authorized local-only continuation for the revocation boundary proof.'});
const start=Date.now();let held;
while(Date.now()-start<30000){held=await (await fetch('http://127.0.0.1:19741/probe')).json();if(held.tag===tag&&held.held>0)break;await sleep(100);}
assert(held?.held>0,'Creator capture did not reach the held MCP discovery boundary');
const before=await request('chat.history',{sessionKey,limit:40});save('revoked-before-abort',before);assert(JSON.stringify(before).includes('automations'),'No actual scheduling tool call before revocation');
let aborted,abortError;const abortPromise=request('chat.abort',{sessionKey,runId:sent.runId||runId}).then(r=>{aborted=r;},e=>{abortError=e;});
const abortStart=Date.now();const committed=()=>events.some(e=>e.event==='chat'&&e.payload?.runId===(sent.runId||runId)&&e.payload?.state==='aborted');
while(!aborted&&!abortError&&!committed()&&Date.now()-abortStart<10000)await sleep(10);
assert(committed()||aborted?.aborted===true||aborted?.runIds?.includes(sent.runId||runId),'No committed abort before release');
await fetch('http://127.0.0.1:19741/release',{method:'POST'});
await abortPromise;if(abortError)throw abortError;save('revoked-abort-result',aborted);
const done=await request('agent.wait',{runId:sent.runId||runId,timeoutMs:160000});save('revoked-wait',done);assert.notEqual(done.status,'timeout','Revoked run did not settle');
save('revoked-after-release',await request('chat.history',{sessionKey,limit:60}));
assert(!(await jobs()).some(j=>j.name==='revoked-before-save'),'Revoked creator saved a job');
report.creatorRevokedBeforeSave=true;report.cases.push({tag,runId:sent.runId||runId,heldDiscovery:true,saved:false});
}
async function login(){
const child=spawn(process.execPath,['openclaw.mjs','mcp','login','unrelated_oauth'],{cwd:source,env:process.env,stdio:['ignore','pipe','pipe']});
let output='',browsed=false,browser;const collect=b=>{output+=b.toString();const match=output.split(String.fromCharCode(27)).join(' ').match(/http:\/\/127\.0\.0\.1:19741\/authorize[^\s]+/);if(match&&!browsed){browsed=true;browser=fetch(match[0]).then(async r=>{assert.equal(r.status,200);assert((await r.text()).includes('Authorization received'));});}};
child.stdout.on('data',collect);child.stderr.on('data',collect);
const code=await new Promise((resolve,reject)=>{child.on('error',reject);child.on('exit',resolve);});if(browser)await browser;assert(browsed,'No operator authorization URL');assert.equal(code,0,output);assert(output.includes('credentials saved'),'OAuth exchange did not save credentials');save('login-result',{browsed,exitCode:code,credentialsSaved:true});
}
async function connectOperator(){createClient();
await c.waitOpen();const nonce=await challenge,signedAtMs=Date.now(),scopes=['operator.read','operator.write','operator.admin'];
const payload=buildDeviceAuthPayloadV3({deviceId,clientId:'openclaw-tui',clientMode:'ui',role:'operator',scopes,signedAtMs,token:'mcp-proof-fixture-token',nonce,platform:process.platform});
await request('connect',{minProtocol:PROTOCOL_VERSION,maxProtocol:PROTOCOL_VERSION,client:{id:'openclaw-tui',displayName:'MCP boundary proof',version:'1',platform:process.platform,mode:'ui'},role:'operator',scopes,device:{id:deviceId,publicKey,signature:sign(null,Buffer.from(payload),pair.privateKey).toString('base64url'),signedAt:signedAtMs,nonce},caps:[],auth:{token:'mcp-proof-fixture-token'}});
}
async function restartOwnedGateway(){
c.close();fs.writeFileSync(out+'/restart-requested','OAuth login committed; exercise fresh authenticated discovery with the same persisted jobs.');
const started=Date.now();while(!fs.existsSync(out+'/restart-ready')&&Date.now()-started<60000)await sleep(100);
assert(fs.existsSync(out+'/restart-ready'),'Owned Gateway restart did not reach readiness');
await connectOperator();report.gatewayRestartAfterLogin=true;
}
try{
await connectOperator();
const localHistory=await turn('inherited_local',[addCall(job('inherited-local'))]);
let inventory=await jobs();const local=inventory.find(j=>j.name==='inherited-local');
if(expected==='baseline'){assert(!local,'Baseline unexpectedly saved default job');assert.match(resultText(localHistory),/Sign in to the affected MCP server/);report.defaultCapture='rejected-unrelated-oauth';}
else {assert(local,'Candidate did not save default job');assert.match(resultText(localHistory),/warnings/);assert.match(resultText(localHistory),/unrelated_oauth/);assert(local.payload.toolsAllow.includes('exec'));assert(local.payload.toolsAllow.includes('read'));assert(!local.payload.toolsAllow.some(n=>n.startsWith('unrelated_oauth__')));report.defaultCapture='saved-bounded-subset';report.savedCap=local.payload.toolsAllow;save('saved-local-before-login',local);}
const required=await turn('required_unavailable',[addCall(job('required-unavailable',['unrelated_oauth__ping']))]);
assert(!(await jobs()).some(j=>j.name==='required-unavailable'));
assert.match(resultText(required),expected==='candidate'?/not currently executable: unrelated_oauth__ping/:/Sign in to the affected MCP server/);
if(expected==='candidate')assert.match(resultText(required),/openclaw mcp login unrelated_oauth/);
const aliasHistory=await turn('finite_alias',[addCall(job('finite-alias',['gateway_exec','gateway_process','read']))]);
const alias=(await jobs()).find(j=>j.name==='finite-alias');assert(alias,'Executable aliases did not save: '+resultText(aliasHistory));if(expected==='candidate'){assert(alias.payload.toolsAllow.includes('exec'));assert(alias.payload.toolsAllow.includes('process'));assert(!alias.payload.toolsAllow.includes('gateway_exec'));report.aliasCapture='canonical';}else{assert.deepEqual(alias.payload.toolsAllow,['gateway_exec','gateway_process','read']);report.aliasCapture='broken-literal-aliases';}
const unknown=await turn('unknown_name',[addCall(job('unknown-name',['invented__not_executable']))]);
const unknownSaved=(await jobs()).find(j=>j.name==='unknown-name');if(expected==='candidate'){assert(!unknownSaved);assert.match(resultText(unknown),/not currently executable: invented__not_executable/);report.unknownSelector='rejected';}else{assert(!unknownSaved);assert.match(resultText(unknown),/Sign in to the affected MCP server/);report.unknownSelector='unrelated-oauth-rejection';}
if(expected==='candidate'){
const mixed=await turn('wildcard_required',[addCall(job('wildcard-required',['*','unrelated_oauth__ping']))]);
assert(!(await jobs()).some(j=>j.name==='wildcard-required'));assert.match(resultText(mixed),/not currently executable: unrelated_oauth__ping/);
await readOnlyCaller();
const ceilingHistory=await turn('capture_ceiling',[addCall(job('saved-ceiling',undefined,'Probe whether the unrelated_oauth__ping integration is available. Report failure accurately.'))]);assert.match(resultText(ceilingHistory),/warnings/);
const ceiling=(await jobs()).find(j=>j.name==='saved-ceiling');assert(ceiling);
const marker=out+'/workspace/local-proof.txt';
const localRun=await runJob('local_before_login',local,[{name:'exec',namespace:'openclaw_direct',args:{command:'printf MCP_LOCAL_FILE_OK > '+marker}},{name:'read',args:{path:marker}}]);
assert.equal(localRun.entry.status,'ok');assert.equal(fs.readFileSync(marker,'utf8'),'MCP_LOCAL_FILE_OK');assert.match(resultText(localRun.history),/MCP_LOCAL_FILE_OK/);
const healthyHistory=await turn('healthy_requirement',[addCall(job('healthy-required',['healthy__ping'],'Call healthy__ping once.'))]);const healthy=(await jobs()).find(j=>j.name==='healthy-required');assert(healthy,'Healthy integration unavailable: '+resultText(healthyHistory));
const healthyRun=await runJob('healthy_sibling',healthy,[{name:'healthy__ping',args:{}}]);assert.equal(healthyRun.entry.status,'ok');assert.match(resultText(healthyRun.history),/MCP_PONG_HEALTHY/);
await revokeCreator();
await login();
await restartOwnedGateway();
const current=await request('cron.get',{id:local.id});save('saved-local-after-login',current);assert.deepEqual(current.payload.toolsAllow,local.payload.toolsAllow);
const after=await runJob('local_after_login',local,[{name:'exec',namespace:'openclaw_direct',args:{command:'printf MCP_AFTER_LOGIN_OK > '+marker}},{name:'read',args:{path:marker}}]);assert.equal(after.entry.status,'ok');assert.equal(fs.readFileSync(marker,'utf8'),'MCP_AFTER_LOGIN_OK');assert.notEqual(after.queued.processInstanceId,localRun.queued.processInstanceId,'Gateway process did not change');
const authorizedHistory=await turn('new_authorized_requirement',[addCall(job('newly-authorized',['unrelated_oauth__ping'],'Call unrelated_oauth__ping once.'))]);const authorized=(await jobs()).find(j=>j.name==='newly-authorized');assert(authorized,'Post-login tool not available: '+resultText(authorizedHistory));
const authorizedRun=await runJob('new_authorized_run',authorized,[{name:'unrelated_oauth__ping',args:{}}]);assert.equal(authorizedRun.entry.status,'ok');assert.match(resultText(authorizedRun.history),/MCP_PONG_AUTHORIZED/);
const beforeLines=fs.readFileSync(out+'/peer.jsonl','utf8').trim().split('\n').length;
const denied=await runJob('saved_ceiling_denial',ceiling,[{name:'unrelated_oauth__ping',args:{}}]);
const attempts=fs.readFileSync(out+'/peer.jsonl','utf8').trim().split('\n').slice(beforeLines).map(JSON.parse);assert(!attempts.some(x=>x.kind==='mcp'&&x.path==='/mcp/blocked'&&x.rpc==='tools/call'),'Saved job reached excluded integration after login');
const refusal=toolResults(denied.history).find(m=>m.toolCallId==='call_saved_ceiling_denial_0'&&m.toolName==='unrelated_oauth__ping');
assert(refusal,'No retained response to the attempted excluded tool');assert.equal(refusal.content.filter(x=>x.type==='text').map(x=>x.text).join('\n'),'unsupported call: unrelated_oauth__ping');
const vanished=await turn('interactive_then_unavailable',[addCall(job('vanished-required',['healthy__ping']))],{rejectCapture:true});
assert(!(await jobs()).some(j=>j.name==='vanished-required'));assert.match(resultText(vanished),/not currently executable: healthy__ping/);
report.interactiveVisibilityCannotPreauthorize=true;
report.loginDoesNotWiden=true;report.localFileBeforeAndAfter=true;report.healthySibling=true;report.postLoginNewGrant=true;report.savedCeilingDenied=true;
}
save('jobs-final',{jobs:await jobs()});report.result='PASS';save('report',report);console.log(JSON.stringify(report,null,2));
}catch(error){report.result='FAIL';report.error=String(error);save('report',report);console.error(error);process.exitCode=1;}finally{c.close();}v2-run.sh#!/usr/bin/env bash
set -euo pipefail
synced="$(pwd -P)"
proof=/tmp/openclaw-mcp-proof-d69308f5
export PROOF_TREE="$(cat "$synced/.openclaw/tmp/mcp-proof/candidate-tree.txt")"
expected="$PROOF_EXPECT"
export PROOF_SOURCE="$proof/baseline"
if [ "$expected" = candidate ]; then export PROOF_SOURCE="$proof/candidate-complete-$PROOF_TREE"; fi
export PROOF_OUT="$proof/$expected-v2-$PROOF_ATTEMPT"
test ! -e "$PROOF_OUT"
mkdir -p "$PROOF_OUT" "$proof/fixtures-v2"
cp "$synced"/.openclaw/tmp/mcp-proof/{v2-peer.mjs,v2-config.mjs,v2-client.mjs,write-config.mjs} "$proof/fixtures-v2/"
if [ "$expected" = candidate ]; then test "$(git -C "$PROOF_SOURCE" write-tree)" = "$PROOF_TREE"; git -C "$PROOF_SOURCE" diff --exit-code; else test -z "$(git -C "$PROOF_SOURCE" status --porcelain --untracked-files=no)"; fi
export PROOF_SHA="$(git -C "$PROOF_SOURCE" rev-parse HEAD)"
if [ "$expected" = candidate ]; then test "$PROOF_SHA" = "$(cat "$synced/.openclaw/tmp/mcp-proof/candidate-head.txt")"; else test "$PROOF_SHA" = fb503c9e1f25d8c3877881e55e83d4378eda3676; fi
export PROOF_TREE="$(git -C "$PROOF_SOURCE" rev-parse HEAD^{tree})"
node "$proof/fixtures-v2/v2-config.mjs"
export HOME="$PROOF_OUT/home" OPENCLAW_HOME="$PROOF_OUT/home" OPENCLAW_STATE_DIR="$PROOF_OUT/state" OPENCLAW_CONFIG_PATH="$PROOF_OUT/config.json" OPENCLAW_GATEWAY_TOKEN=mcp-proof-fixture-token OPENAI_API_KEY=synthetic-proof-key
unset CODEX_HOME CODEX_API_KEY OPENCLAW_GATEWAY_URL OPENCLAW_CODEX_APP_SERVER_COMMAND OPENCLAW_CODEX_APP_SERVER_BIN OPENCLAW_CODEX_APP_SERVER_ARGS OPENAI_BASE_URL OPENCLAW_AGENT_DIR OPENCLAW_WORKSPACE_DIR
export OPENCLAW_NO_RESPAWN=1
cd "$PROOF_SOURCE"
node --import ./scripts/tsx.mjs "$proof/fixtures-v2/v2-peer.mjs" > "$PROOF_OUT/peer.log" 2>&1 & peer_pid=$!
client_pid=""
cleanup() {
if [ -n "$client_pid" ]; then kill "$client_pid" 2>/dev/null || true; fi
kill "$gateway_pid" "$peer_pid" 2>/dev/null || true
wait "$gateway_pid" "$peer_pid" 2>/dev/null || true
}
trap cleanup EXIT
start_gateway() {
node openclaw.mjs gateway run --allow-unconfigured --port 19742 >> "$PROOF_OUT/gateway.log" 2>&1 & gateway_pid=$!
for i in $(seq 1 120); do
if curl -fsS http://127.0.0.1:19742/readyz >/dev/null 2>&1 && curl -fsS http://127.0.0.1:19741/health >/dev/null 2>&1; then break; fi
kill -0 "$gateway_pid" "$peer_pid" || { tail -60 "$PROOF_OUT/gateway.log" "$PROOF_OUT/peer.log";exit 1; }
sleep 1
done
curl -fsS http://127.0.0.1:19742/readyz >/dev/null
}
start_gateway
node --import ./scripts/tsx.mjs "$proof/fixtures-v2/v2-client.mjs" > "$PROOF_OUT/client.log" 2>&1 & client_pid=$!
restarted=false
while kill -0 "$client_pid" 2>/dev/null; do
if [ "$restarted" = false ] && [ -f "$PROOF_OUT/restart-requested" ]; then
kill "$gateway_pid"
stopped=0; wait "$gateway_pid" || stopped=$?
if [ "$stopped" != 0 ] && [ "$stopped" != 143 ]; then echo "Unexpected Gateway exit: $stopped";exit 1;fi
start_gateway
touch "$PROOF_OUT/restart-ready"
restarted=true
fi
sleep 0.1
done
status=0;wait "$client_pid" || status=$?
client_pid=""
if [ "$status" != 0 ]; then tail -45 "$PROOF_OUT/client.log";tail -45 "$PROOF_OUT/gateway.log";tail -20 "$PROOF_OUT/peer.log";exit "$status";fi
cat "$PROOF_OUT/report.json"
printf 'PROOF_OUTPUT=%s\n' "$PROOF_OUT"
v2-prepare.sh#!/usr/bin/env bash
set -euo pipefail
synced="$(pwd -P)"
proof=/tmp/openclaw-mcp-proof-d69308f5
head="$(cat "$synced/.openclaw/tmp/mcp-proof/candidate-head.txt")"
tree="$(cat "$synced/.openclaw/tmp/mcp-proof/candidate-tree.txt")"
mkdir -p "$proof"
candidate="$proof/candidate-complete-$tree"
test ! -e "$candidate"
echo CRABBOX_PHASE:prepare-complete-candidate
git clone --no-checkout https://github.com/openclaw/openclaw.git "$candidate"
git -C "$candidate" checkout --detach "$head"
test "$(git -C "$candidate" rev-parse HEAD)" = "$head"
test "$(git -C "$candidate" rev-parse HEAD^{tree})" = "$tree"
test -z "$(git -C "$candidate" status --porcelain --untracked-files=no)"
cd "$candidate"
pnpm install --frozen-lockfile > "$proof/candidate-install.log" 2>&1
echo CRABBOX_PHASE:build-candidate
pnpm build > "$proof/candidate-build.log" 2>&1
test -z "$(git status --porcelain --untracked-files=no)"
node extensions/codex/node_modules/@openai/codex/bin/codex.js --version
printf 'SOURCE_READY stage=candidate sha=%s tree=%s\n' "$(git rev-parse HEAD)" "$(git rev-parse HEAD^{tree})"
echo CRABBOX_PHASE:real-gateway-proof
(cd "$synced" && PROOF_EXPECT=candidate PROOF_ATTEMPT=final bash .openclaw/tmp/mcp-proof/v2-run.sh)
v2-launch.mjsimport fs from 'node:fs';
import {spawnSync} from 'node:child_process';
const stage=process.argv[2];if(!['prepare','baseline','candidate'].includes(stage))throw Error('stage required');
const attempt=process.argv[3]||'1';if(!/^[a-zA-Z0-9_-]+$/.test(attempt))throw Error('bad attempt');
const root=new URL('./',import.meta.url);
const names=['v2-peer.mjs','v2-config.mjs','v2-client.mjs','write-config.mjs','v2-prepare.sh','v2-run.sh','candidate-tree.txt','candidate-head.txt','candidate.patch'];
const files=Object.fromEntries(names.map(n=>[n,fs.readFileSync(new URL(n,root),'utf8')]));
const remote="const fs=require('node:fs');const dir=process.cwd()+'/.openclaw/tmp/mcp-proof';fs.mkdirSync(dir,{recursive:true});for(const [n,c] of Object.entries(JSON.parse(process.argv[1])))fs.writeFileSync(dir+'/'+n,c);";
const q=s=>"'"+s.replaceAll("'","'\\''")+"'";
if(!process.env.PROOF_MODEL?.startsWith('openai/'))throw Error('Set PROOF_MODEL');
const command='node -e '+q(remote)+' '+q(JSON.stringify(files))+' && PROOF_MODEL='+q(process.env.PROOF_MODEL)+' '+(stage==='prepare'?'bash .openclaw/tmp/mcp-proof/v2-prepare.sh':'PROOF_EXPECT='+stage+' PROOF_ATTEMPT='+attempt+' bash .openclaw/tmp/mcp-proof/v2-run.sh');
const lease=fs.readFileSync(new URL('lease-id.txt',root),'utf8').trim();
const result=spawnSync(process.execPath,['scripts/crabbox-wrapper.mjs','run',...(lease?['--id',lease]:[]),'--keep','--label','mcp-proof-d69308f5','--timing-json','--','bash','-c',command],{stdio:'inherit'});
process.exitCode=result.status??1; |
Capture the currently executable authorized subset with visible exclusions, reject unresolved required selectors, and retain existing run-bound grants and saved tool ceilings. Co-authored-by: jalehman <[email protected]>
Refresh finite integration caps before saving and reject unavailable explicit selectors even beside a wildcard. Preserve exact host alias provenance through admission-fenced normalization without replacing the executable or losing the current view guard. Co-authored-by: jalehman <[email protected]>
8f100e7 to
685ddfc
Compare
|
This pull request has been automatically marked as stale due to inactivity. |
Related: #156379
What Problem This Solves
Fixes continuation scheduling being blocked when an unrelated configured MCP integration is not authenticated.
User Impact
Agent-created continuations capture the currently executable, authorized subset and report excluded integrations in
warnings. Explicit unavailable or unknown tool selectors fail before saving instead of silently disappearing. Trusted runtime aliases retain their canonical executable identities. Later login does not expand a saved tool ceiling; current permissions and approvals still apply. No configuration, storage schema, or protocol version changes.Intentional upgrade behavior: older finite lists could silently drop unavailable names. New creates and explicit tool-policy edits reject those names, including named requirements alongside
*; remove unavailable selectors or restore access. Existing stored caps are not rewritten.This authority-sensitive PR remains a draft for owner/security review. Required CI/review gates are not waived; no merge or deployment is requested.
Why This Change Was Made
Use the existing creator-authority snapshot and cap owners. Keep the materializer's policy/approval-filtered tools, carry its exclusions into scheduling results, and replace earlier interactive configured-tool bindings with the fresh scheduled snapshot. Unexpected discovery failures and exact-run grant/lifecycle checks still fail closed. Host-issued shell aliases keep their existing executable identity and lifetime checks when provider normalization wraps them.
Thanks @jalehman for the report and the requested bounded-subset behavior.
Work sessions
Evidence
fb503c9e1f25d8c3877881e55e83d4378eda3676rejects local continuation creation for unrelated OAuth. Exact head685ddfc5f86d242c115c96b988975421ad962d2cpasses all 16 cases: bounded save + warning, real shell/file effects, finite aliases, unknown/required selectors, healthy MCP, read-only caller, creator revocation, and unchanged saved ceilings after OAuth plus fresh discovery. Both snapshots use isolated built Gateways and managed Codex 0.158.0. Model/MCP peers are synthetic; Gateway, auth, storage, dispatch and effects are real.openclaw/ci-gateis skipped, not asserted green. Owner/security review remains before merge.Proof limit: post-login ceiling checks explicitly restart only the owned Gateway to force fresh authenticated discovery and verify persistence. This does not claim immediate warm-cache invalidation or live-vendor inference. The saved job’s attempted excluded MCP call is verified against the native unsupported-call response and zero peer tool calls, with a successful authenticated new-job control.
Measured test cost and implementation scope
Canonical
node scripts/run-vitest.mjs run <file> --maxWorkers=1, measured on the final head; wall time includes runner/cache/import overhead. CI seconds are unavailable while the PR is draft.cron-tool-creator-cap.test.tscron-tool.test.tscron-tool.authority-exclusions.test.tscron-tool.output-contract.test.tscron-creator-authority-context.test.tsrun-attempt.configured-mcp-authority.test.tstools.scheduled-projection.test.tsThe attempt-level tests exercise the actual capture composition and stale-binding replacement; the alias suite exercises real normalization and plugin admission, including nested/retired views and replaced executors. Pure name-matching tests would miss those boundaries. Upstream test pruning was preserved during conflict resolution.
Against rebase base
d4be6500114cff6fcbf72f323fc520861a06c6c9: production +150/-40 (net +110); tests +422/-50 (net +372); docs +16. Growth is the returned exclusions, explicit selector validation, fresh finite-MCP capture and admission-preserving alias metadata transfer. The blanket diagnostic rejection, stale interactive-MCP union and duplicate output-schema shape are removed. Existing cap/grant/lifecycle owners remain authoritative; no storage/config/protocol change or budget increase.View the OpenClaw team session