-- panto lua _selfcheck.lua; no network/provider tokens. Child modes reuse this file. local uv=require('luv') local json=require('panto').ext.json local here=debug.getinfo(1,'S').source:match('^@(.*)/[^/]+$') or '.' here=uv.fs_realpath(here) package.path=here .. '/?.lua;' .. here .. '/?/init.lua;' .. package.path local async=require('panto_mcp.async') local function close(h) async.close(h) end local function write(path,text) local f=assert(io.open(path,'wb')); assert(f:write(text)); f:close() end local function read(path) local f=io.open(path,'rb'); if not f then return nil end local s=f:read('a'); f:close(); return s end -- A stand-in parent dies without running extension teardown. Its inherited -- stderr reports the actual server/group pid to the outer test. if arg[1]=='--parent' then local transport=assert(require('panto_mcp.stdio').new({command=uv.exepath(),args={'lua',here .. '/_selfcheck.lua','--fake','grandchild'},env={}})) local reported=false local watchdog=uv.new_timer(); watchdog:start(0,10,function() if transport.server_pid and transport.stderr_tail:find('GRANDCHILD=%d+') and not reported then io.stdout:write('SERVER=',transport.server_pid,'\n'); io.stdout:flush(); reported=true end end) uv.run(); return end if arg[1]=='--fake' then local mode=arg[2] if mode=='banner' then io.stdout:write('starting fake server\n'); io.stdout:flush(); mode='modern' end if mode=='exit-on-eof' then local pipe=uv.new_pipe(false); assert(pipe:open(0)) pipe:read_start(function(_,data) if not data then close(pipe) end end) uv.run(); return end if mode=='noisy-exit' then io.stderr:write('diagnostic-tail-from-child'); io.stderr:flush() io.stdout:write('diagnostic-tail-from-child\n'); io.stdout:flush(); return end if mode=='env-check' then assert(os.getenv('PANTO_MCP_TEST_CHILD_ENV')=='child','server env not applied') mode='modern' end if mode=='ignore' or mode=='grandchild' then local keep=uv.new_timer(); keep:start(100000,100000,function() end) local signal=uv.new_signal(); signal:start('sigterm',function() end) if mode=='grandchild' then local child,pid=assert(uv.spawn('sh',{args={'-c','trap "" TERM; sleep 1000 & wait'},stdio={nil,nil,2}},function() end)) io.stderr:write('GRANDCHILD=',pid,'\n'); io.stderr:flush(); child:unref() end local pipe=uv.new_pipe(false); assert(pipe:open(0)); pipe:read_start(function() end) uv.run(); return end local initialized=false; local changed=false; local removed=false local function send(msg) io.stdout:write(json.encode(msg),'\r\n'); io.stdout:flush() end local pipe=uv.new_pipe(false); assert(pipe:open(0)) local feed=require('panto_mcp.stdio').framer(function(req) if not req.method then return end if req.id==nil then return end local function result(r) send({jsonrpc='2.0',id=req.id,result=r}) end local function err(code,msg,data) send({jsonrpc='2.0',id=req.id,error={code=code,message=msg,data=data}}) end local caps={tools={listChanged=true},prompts={},resources={}} if mode=='tools-only' then caps={tools={}} end if req.method=='server/discover' then if mode=='legacy-close' then close(pipe); return end if mode~='modern' then err(-32600,'initialize first'); return end assert(req.params._meta['io.modelcontextprotocol/protocolVersion']=='2026-07-28') result({resultType='complete',supportedVersions={'2026-07-28'},capabilities=caps,instructions='Fake server instructions',_meta={['io.modelcontextprotocol/serverInfo']={name='fake'}}}); return end if req.method=='initialize' then assert(mode~='modern','modern must never initialize'); initialized=true result({protocolVersion='2025-06-18',capabilities=caps,serverInfo={name='fake'},instructions='Fake server instructions'}); return end if mode=='modern' then assert(req.params._meta and req.params._meta['io.modelcontextprotocol/clientCapabilities']) else assert(initialized,'legacy request before initialize') end if req.method=='tools/list' then if removed then result({tools={}}) elseif req.params.cursor then result({tools={{name='other',description='Other tool',inputSchema={type='object'}}}}) else local tools={{name='echo',description='Echo a message',inputSchema={type='object',properties={message={type='string'}},required={'message'},additionalProperties=false}}} if changed then tools[#tools+1]={name='new_tool',inputSchema={type='object'}} end result({tools=tools,nextCursor='page2'}) end elseif req.method=='prompts/list' then assert(mode~='tools-only') result({prompts=removed and {} or {{name=changed and 'wave' or 'greet',arguments={{name='name',required=true}}}}}) elseif req.method=='resources/list' then assert(mode~='tools-only'); result({resources={{name='guide',uri='docs://guide',description='Guide document'}}}) elseif req.method=='resources/templates/list' then if mode=='missing-templates' then err(-32601,'not implemented') else result({resourceTemplates={{name='entry',uriTemplate='docs://{name}'}}}) end elseif req.method=='resources/read' then result({contents={{uri=req.params.uri,text='resource body'}}}) elseif req.method=='prompts/get' then result({messages={{role='user',content={type='text',text='Hello'}}}}) elseif req.method=='tools/call' then result({content={{type='text',text=(req.params.arguments or {}).message or 'ok'}}}) if req.params.arguments and req.params.arguments.message=='change' then changed=true; send({jsonrpc='2.0',method='notifications/tools/list_changed'}) elseif req.params.arguments and req.params.arguments.message=='remove' then removed=true; send({jsonrpc='2.0',method='notifications/tools/list_changed'}); send({jsonrpc='2.0',method='notifications/prompts/list_changed'}) end else err(-32601,'not implemented') end end) pipe:read_start(function(e,data) assert(not e,e); if data then assert(feed(data)) else close(pipe) end end) uv.run(); return end local checks=0 local function check(v,label) assert(v,label); checks=checks+1 end local function eq(a,b,label) check(a==b,(label or '') .. ': ' .. tostring(a) .. ' ~= ' .. tostring(b)) end local config=require('panto_mcp.config') local cache=require('panto_mcp.cache') local validate=require('panto_mcp.validate') local results=require('panto_mcp.results') local stdio=require('panto_mcp.stdio') local Rpc=require('panto_mcp.jsonrpc') local Manager=require('panto_mcp.manager') local search=require('panto_mcp.search') local prompts=require('panto_mcp.prompts') local namespace=require('panto_mcp.namespace') check(require('panto_mcp.docs').discovery:find('Search is the default',1,true),'docs describe search as default') local manifest_environment={} assert(loadfile(here .. '/panto-mcp-0.1.0-1.rockspec','t',manifest_environment))() local module_scan=assert(uv.fs_scandir(here .. '/panto_mcp')) while true do local file=uv.fs_scandir_next(module_scan); if not file then break end local stem=file:match('^(.*)%.lua$') if stem then check(manifest_environment.build.modules['panto_mcp.' .. stem]=='panto_mcp/' .. file,'rock manifest: ' .. file) end end local temp=assert(uv.fs_mkdtemp('/tmp/panto-mcp-check-XXXXXX')) local function timers() local ts={} local function factory(ms,fn) local t={ms=ms,fn=fn,closed=false} function t:is_closing() return self.closed end function t:close() self.closed=true end function t:fire() if not self.closed then self:close(); self.fn() end end ts[#ts+1]=t; return t end return ts,factory end local function fake_transport() local t={sent={},cancels={}} function t:set_callbacks(message,err) self.message=message; self.error=err end function t:send(msg,opts) self.sent[#self.sent+1]={msg=msg,opts=opts}; return {} end function t:cancel(id) self.cancels[#self.cancels+1]=id end function t:close() self.closed=true end return t end -- Config trust boundary, canonical identity and stable future eager names. local settings,servers,warnings=config.parse({servers={fs={command='echo',args={'${env:ABSENT}','${project_root}'},env={X='${env:TOKEN}'},cwd='sub'},bad={command='x',url='https://x'},['bad.name']={command='x'},['bad__name']={command='x'},['tail_']={command='x'},off={enabled=false}}},{project_root='/project'},function(k) if k=='TOKEN' then return 'secret' end end) eq(servers.fs.args[1],'','missing env'); eq(servers.fs.args[2],'/project'); eq(servers.fs.cwd,'/project/sub'); eq(#warnings,4) check(not servers.off and not servers.bad and not servers.bad__name and not servers.tail_,'invalid/disabled skipped') check(not config.valid_name('a__b') and not config.valid_name('ends_'),'wire-ambiguous server names rejected') do local _,remote_servers=config.parse({servers={cloud={url='https://api.example/mcp',auth='mcp.cloud',headers={['X-Tenant']='${env:TENANT}'}}}},{project_root='/project'},function(k) if k=='TENANT' then return 'tenant-a' end end) eq(remote_servers.cloud.transport,'http'); eq(remote_servers.cloud.url,'https://api.example/mcp') eq(remote_servers.cloud.auth,'mcp.cloud'); eq(remote_servers.cloud.headers['X-Tenant'],'tenant-a') local _,safe_server,header_warnings=config.parse({servers={remote={url='https://api.example',auth='mcp',headers={ Host='h',Connection='c',['Content-Length']='1',['Transfer-Encoding']='chunked',Expect='100-continue',Upgrade='websocket', TE='trailers',['Keep-Alive']='x',['Proxy-Connection']='x',Authorization='Bearer SECRET', ['Bad Header']='x',['X-Empty']='${env:EMPTY}',['X-Good']='fine'}}}},{project_root='/project'},function() end) eq(#header_warnings,12,'unsafe HTTP headers warn at parse time'); eq(safe_server.remote.headers['X-Good'],'fine') for _,header in ipairs({'Host','Connection','Content-Length','Transfer-Encoding','Expect','Upgrade','TE','Keep-Alive','Proxy-Connection','Authorization','Bad Header','X-Empty'}) do eq(safe_server.remote.headers[header],nil,'forbidden header omitted: '..header) end check(not table.concat(header_warnings,' '):find('SECRET',1,true),'header warnings do not reveal values') local _,http_servers,http_warnings=config.parse({servers={ insecure={url='http://example.test/mcp',headers={Cookie='SECRET',['X-API-Key']='APISECRET'}}, secret={url='http://api.example/mcp',auth='mcp.secret'}, loopback={url='http://127.0.0.1:9000/mcp',auth='mcp.local',headers={Cookie='local'}} }},{project_root='/project'}) eq(#http_warnings,3,'plain non-loopback credentials warn early'); check(not http_servers.secret,'unsafe named auth server skipped') eq(next(http_servers.insecure.headers),nil,'sensitive non-loopback headers omitted') eq(http_servers.loopback.headers.Cookie,'local','loopback sensitive header allowed') check(not table.concat(http_warnings,' '):find('APISECRET',1,true),'credential warnings redact values') local long_idle,_,warnings_idle=config.parse({idle_timeout_ms=120001,servers={}},{project_root='/project'}) eq(long_idle.idle_timeout_ms,120001); eq(#warnings_idle,0,'Lua-owned idle timeout has no core cap') end eq(config.hash('hello'),'4f9f2cab','FNV-1a vector') eq(config.canonical({b=2,a=1}),config.canonical({a=1,b=2}),'canonical order') check(config.fingerprint(servers.fs)~=config.fingerprint({command='changed'}),'identity changes') eq(cache.directory(function(k) if k=='XDG_DATA_HOME' then return '' elseif k=='HOME' then return '/h' end end),'/h/.local/share/panto-mcp') local _,eager_servers,eager_warnings=config.parse({servers={fast={command='echo',expose='eager'}}},{project_root='/project'}) eq(eager_servers.fast.expose,'eager','eager setting preserved until core capability check'); eq(#eager_warnings,0,'eager does not warn before activation') check(config.tool_name('fs','a.b')~=config.tool_name('fs','a_b'),'sanitizer collisions') local sanitized_candidate=config.tool_name('fs','a.b') local crafted_collision=sanitized_candidate:sub(#'mcp.fs.'+1) check(config.tool_name('fs',crafted_collision)~=sanitized_candidate,'own-name suffix avoids crafted sanitizer collision') local stable_name=config.tool_name('fs','stable.tool') config.tool_name('fs','a new tool') eq(config.tool_name('fs','stable.tool'),stable_name,'adding a catalog name cannot rename an eager tool') for _,c in ipairs({ {'a.b','mcp.fs.a_b-'}, {'a__b','mcp.fs.a_b-'}, }) do check(config.tool_name('fs',c[1]):find(c[2],1,true),'sanitized wire name '..c[1]) end local long_a=config.tool_name('fs',string.rep('x',300)); local long_b=config.tool_name('fs',string.rep('y',300)) eq(#(long_a:gsub('%.','__'))<=64,true,'wire length') check(long_a~=long_b,'hash-suffixed truncation distinguishes long names') local long_server_a=config.tool_name(string.rep('s',40)..'a','tool'); local long_server_b=config.tool_name(string.rep('s',40)..'b','tool') check(long_server_a~=long_server_b,'long server names are disambiguated') eq(config.tool_name('github','create_issue'),'mcp.github.create_issue','unchanged eager name has no suffix') eq(config.tool_name(string.rep('s',32),'create_issue'),'mcp.'..string.rep('s',32)..'.create_issue','32-byte server leaves normal tool name intact') do local names={'list','_x','x_','__','a.b','é','',string.rep('z',200),'a b','a/b','a__b','_','-','---___'} local seed=1 local function random(n) seed=(seed*1664525+1013904223)&0xffffffff; return (seed%n)+1 end for _=1,3000 do local out={}; for _=1,random(90) do out[#out+1]=string.char(31+random(95)) end; names[#names+1]=table.concat(out) end local seen={}; local valid=true for _,server in ipairs({'a','gh','a-b','x_y',string.rep('s',32),string.rep('t',33),string.rep('u_',40)..'u','s-_-'} ) do for _,name in ipairs(names) do local wire=config.tool_name(server,name):gsub('%.','__'); local parts={}; local cursor=1 while true do local at=wire:find('__',cursor,true); if not at then parts[#parts+1]=wire:sub(cursor); break end parts[#parts+1]=wire:sub(cursor,at-1); cursor=at+2 end local identity=server..'\0'..name if #wire>64 or #parts~=3 or parts[1]~='mcp' or not wire:match('^[A-Za-z0-9_-]+$') or (seen[wire] and seen[wire]~=identity) then valid=false end seen[wire]=identity end end check(valid,'names_probe regression: 3000 random names x 8 servers decode without collisions within wire limits') end check(config.tool_enabled({enabled_tools={'read*'},disabled_tools={'*secret*'}},'read_file'),'enabled glob') check(not config.tool_enabled({enabled_tools={},disabled_tools={'delete_*'}},'delete_a'),'disabled glob') -- Validator table: false/null, deep equality, combinators, refs, prefix items, -- JSON-pointer paths, Unicode lengths and multiple independent diagnostics. for i,c in ipairs({ {false,{type='boolean'},true}, {json.null,{type='null'},true}, {json.null,{type='object'},false}, {{},{type='object'},true}, {json.array({}),{type='array'},true}, {json.array({}),{type='object'},false}, {{1,2},{type='object'},false}, {{a=1},{enum={{a=1}}},true}, {{a=1},{const={a=2}},false}, {2,{anyOf={{type='string'},{type='integer'}}},true}, {2,{oneOf={{type='number'},{type='integer'}}},true}, {2,{allOf={{minimum=1},{maximum=1}}},false}, {2,{['not']={const=2}},true}, {{x=1},{patternProperties={['^x']={type='number'}},additionalProperties=false},true}, {{x=3},{type='object',properties={x={['$ref']='#/$defs/n'}},['$defs']={n={minimum=4}}},false}, {'x',{['$ref']='#/$defs/tuple/0',['$defs']={tuple={{type='integer'}}}},false}, {2,{['$ref']='#/$defs/',['$defs']={['']={const=1}}},false}, {{'x',3},{prefixItems={{type='string'}},items={minimum=2}},true}, {{'x',1},{prefixItems={{type='string'}},items=false},false}, {1,{exclusiveMinimum=1},false}, {0.3,{multipleOf=0.1},true}, {'é',{maxLength=1},true}, {'x',{pattern='never',format='unknown'},true}, {{a=1},{additionalProperties=false},false}, {{1,1},{uniqueItems=true},false}, {{},{minItems=1},false}, {{},{required={'x'}},false}, }) do local ok=validate.check(c[1],c[2]); eq(ok,c[3],'validator case ' .. i) end local valid,errors=validate.check({['a/b']=1,z=false},{properties={['a/b']={type='string'},z={type='integer'}}}) check(not valid and #errors==2 and table.concat(errors,' '):find('/a~1b',1,true),'multiple pointer errors') -- Prompt arguments are parsed synchronously; quoted values and a single -- positional remainder are covered table-first rather than via the TUI. local one_arg={arguments={{name='text',required=true}}} local named_prompt={arguments={{name='person',required=true},{name='tone'}}} for _,case in ipairs({ {one_arg,'two words "quoted phrase"',{text='two words "quoted phrase"'}}, {one_arg,'hello world',{text='hello world'}}, {one_arg,"Don't",{text="Don't"}}, {one_arg,'text="Ada Lovelace"',{text='Ada Lovelace'}}, {one_arg,'other=literal',{text='other=literal'}}, {one_arg,'back\\slash',{text='back\\slash'}}, {named_prompt,'person="Ada Lovelace" tone=\'calm voice\'',{person='Ada Lovelace',tone='calm voice'}}, {named_prompt,'person=Ada\\ Lovelace',{person='Ada Lovelace'}}, }) do local value,why=prompts.parse_arguments(case[1],case[2]); check(value,tostring(why)..' input='..case[2]) for key,expected in pairs(case[3]) do eq(value[key],expected,'prompt argument '..key) end end for _,case in ipairs({ {named_prompt,'','missing required arguments: person'}, {named_prompt,'person="open','unclosed quote'}, {named_prompt,'other=x','unknown prompt argument: other'}, {named_prompt,'person=x person=y','duplicate prompt argument: person'}, }) do local value,why=prompts.parse_arguments(case[1],case[2]); check(not value and why:find(case[3],1,true),'prompt parse error '..case[3]) end local prompt_messages={ {role='user',content={type='text',text='before'}}, {role='assistant',content={{type='text',text='answer'},{type='image',data='aGk=',mimeType='image/png'}}}, {role='user',content={type='text',text='last'}} } local mapped_prompt=assert(prompts.map_messages(prompt_messages)) eq(mapped_prompt[1].role,'user'); eq(mapped_prompt[2].role,'assistant') check(mapped_prompt[2].blocks[2].text:find('Assistant media omitted',1,true),'assistant media becomes placeholder') local conv_log={}; local conversation={} function conversation:add_user_blocks(blocks) conv_log[#conv_log+1]={role='user',blocks=blocks} end function conversation:add_assistant_message(message) conv_log[#conv_log+1]={role='assistant',blocks=message.blocks} end local media_prompt=assert(prompts.map_messages({{role='user',content={{type='resource',resource={uri='file://x',blob='JVBERi0=',mimeType='application/pdf'}},{type='image',data='aGk=',mimeType='image/png'}}}})) eq(media_prompt[1].blocks[1].type,'text','non-image resource blob becomes a placeholder') eq(media_prompt[1].blocks[2].type,'media','image/* content remains media') local unsupported=assert(prompts.map_messages({{role='user',content={type='image',data='aGk=',mimeType='image/svg+xml'}}})) eq(unsupported[1].blocks[1].type,'text','unsupported image subtype becomes a placeholder') local submitted; local agent={} function agent:conversation() return conversation end function agent:submit(blocks) submitted=blocks end local invalid_prompt={{role='user',content={type='text',text='valid'}},{role='system',content={type='text',text='invalid role'}}} local no_append,append_error=prompts.append_to(agent,invalid_prompt) check(not no_append and append_error and #conv_log==0,'all prompt messages map before conversation mutation') if type(require('panto').conversation)=='function' then local ok,why=prompts.append_to(agent,{{role='user',content={type='image',data='aGk=',mimeType='image/png'}}}) check(ok==nil and why=='MCP prompt image could not be decoded' and #conv_log==0,'preflight failure is clean and does not mutate conversation') end check(prompts.append_to(agent,prompt_messages),'trailing user prompt submits') eq(#conv_log,2,'trailing user is not duplicated') eq(conv_log[1].role,'user'); eq(conv_log[2].role,'assistant'); eq(submitted[1].text,'last') submitted=nil; conv_log={} check(not prompts.append_to(agent,{prompt_messages[1],prompt_messages[2]}),'assistant-tail does not submit') eq(#conv_log,2,'assistant-tail appends all roles'); eq(submitted,nil) -- Slash callbacks return synchronously; a late async result is discarded if a turn starts meanwhile. do local waits={async.future(),async.future(),async.future()}; local request_count=0; local command_spec local turn_state={busy=false}; local conversation_log={}; local sent_blocks; local emitted={} local prompt_agent={} function prompt_agent:conversation() return { add_user_blocks=function(_,blocks) conversation_log[#conversation_log+1]={role='user',blocks=blocks} end, add_assistant_message=function(_,message) conversation_log[#conversation_log+1]={role='assistant',blocks=message.blocks} end, } end function prompt_agent:submit(blocks) sent_blocks=blocks end local saved_module=package.loaded.panto package.loaded.panto={ext={agent=prompt_agent}} local prompt_manager={} function prompt_manager:prompt() request_count=request_count+1; return waits[request_count]:await() end local command_set=prompts.commands({register_command=function(spec) command_spec=spec; return true end, unregister_command=function() return true end,emit=function(name) emitted[#emitted+1]=name end},prompt_manager,turn_state,true) command_set.reconcile('server',{catalog={prompts={{name='ask',arguments={{name='who',required=true}}}}}},true) check(command_spec,'async prompt command registered') turn_state.busy=true check(command_spec.handler('who=busy'):find('turn is in progress',1,true),'prompt refuses an active turn') eq(request_count,0,'busy prompt does not start network request') turn_state.busy=false check(command_spec.handler('who=first'):find('Fetching',1,true),'prompt callback returns immediately') eq(request_count,1) waits[1]:resolve({{role='assistant',content={type='text',text='prior'}},{role='user',content={type='text',text='question'}}}) eq(conversation_log[1].role,'assistant','async prompt preserves assistant role') eq(sent_blocks[1].text,'question','async prompt submits trailing user blocks') local before=#conversation_log; turn_state.busy=false command_spec.handler('who=late'); eq(request_count,2) turn_state.busy=true waits[2]:resolve({{role='user',content={type='text',text='discard'}}}) eq(#conversation_log,before,'result arriving during a new turn is discarded') eq(sent_blocks[1].text,'question','discarded prompt does not submit') turn_state.busy=false command_spec.handler('who=tail') waits[3]:resolve({{role='assistant',content={type='text',text='assistant tail'}}}) eq(emitted[1],'agent_submission','assistant-tail prompt wakes TUI conversation sync') eq(sent_blocks[1].text,'question','assistant-tail prompt does not submit a turn') package.loaded.panto=saved_module end do local callbacks={}; local busy_state={busy=false} prompts.track_busy({on=function(name,fn) callbacks[name]=fn end},busy_state,{registered={['mcp:server:ask']=true}}) callbacks.command_start({command_name='mcp:server:ask'}); eq(busy_state.busy,false,'prompt command itself does not block its callback') callbacks.command_end({command_name='mcp:server:ask'}) callbacks.command_start({command_name='compact'}); check(busy_state.busy,'command_start marks /compact busy') callbacks.turn_start({}); callbacks.command_end({command_name='compact'}) check(busy_state.busy,'command_end cannot clear active turn state') callbacks.turn_end({}); eq(busy_state.busy,false,'turn_end clears busy after compact') end do local registrations,removed,warnings,event_hooks={}, {}, {}, {} local mount_component,mount_handle local ext={ register_command=function(spec) registrations[spec.name]=spec; return true end, unregister_command=function(name) removed[#removed+1]=name; registrations[name]=nil; return true end, on=function(name,fn) event_hooks[name]=fn end, mount=function(component,placement) eq(placement,'above_input','prompt errors mount above input') mount_component=component; mount_handle={live=true} function mount_handle:alive() return self.live end function mount_handle:invalidate() self.invalidated=true end function mount_handle:unmount() self.live=false end return mount_handle end, } local failure=async.future(); local prompt_manager={} function prompt_manager:prompt() return failure:await() end local commands=prompts.commands(ext,prompt_manager,{busy=false},true,warnings) commands.reconcile('a',{catalog={prompts={{name='pa'}}}},true) commands.reconcile('b',{catalog={prompts={{name='pb'},{name='bad/name'},{name='bad name'}}}},true) commands.reconcile('a',{catalog={prompts={{name='pa'}}}},false) check(registrations['mcp:a:pa'] and registrations['mcp:b:pb'],'reconciling one server preserves other-server prompt commands') check(not registrations['mcp:b:bad/name'] and not registrations['mcp:b:bad name'],'core-invalid prompt command names skipped') local warning_status=require('panto_mcp.tools').status({servers=function() return {} end},warnings) check(warning_status:find('prompt command skipped',1,true),'invalid prompt names appear in /mcp warnings') check(registrations['mcp:b:pb'].handler(''):find('Fetching',1,true),'prompt failure command returns immediately') failure:resolve(nil,'server unavailable') check(mount_handle and mount_handle:alive() and mount_component.render():find('server unavailable',1,true),'async prompt failure is visible above input') event_hooks.command_start({command_name='next'}) check(not mount_handle:alive(),'prompt error mount clears at next command_start') registrations['mcp:b:pb'].handler(''); event_hooks.turn_start({}) check(not mount_handle:alive(),'prompt error mount clears on a normal turn') end -- NDJSON chunks/CRLF and malformed/oversized lines. local bad_lines={}; local frames={}; local feed=stdio.framer(function(m) frames[#frames+1]=m end,nil,function(line) bad_lines[#bad_lines+1]=line end) check(feed('{"jsonrpc":"2.0",'),'partial frame'); check(feed('"id":1,"result":{}}\r\n\n{"id":2}\n'),'CRLF frame') eq(#frames,2); eq(frames[1].id,1) check(not stdio.framer(function() end,4)('12345'),'frame cap') check(feed('not json\n{"id":3}\n'),'bad stdout line does not stop transport'); eq(#bad_lines,1); eq(#frames,3) do -- OAuth policy checks use injected auth, HTTP and timers; no credentials or wall-clock sleeps. do local OAuth=require('panto_mcp.oauth') local sha256=require('panto_mcp.hash').sha256 for _,case in ipairs({ {'','e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'}, {'abc','ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad'}, {'abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq','248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1'}, }) do eq(sha256(case[1]),case[2],'SHA-256 known vector') end for _,case in ipairs({ {'Bearer scope="read write", resource_metadata="https://r.example/meta"','read write','https://r.example/meta'}, {'Basic realm="a,b", Bearer scope="read", error="insufficient_scope"','read',nil,'insufficient_scope'}, {'Digest realm="x", nonce="a\\\"b,c", Bearer resource_metadata="https://r.example/a,b", scope="r\\ead"','read','https://r.example/a,b'}, {'Bearer scope="first", Basic realm="x", Bearer resource_metadata="https://r.example/m", scope="second"','second','https://r.example/m'}, {'Bearer scope="unterminated',nil}, {'Bearer scope="one", scope="two"',nil}, {'Basic realm="private"',nil}, }) do local c=OAuth.challenge(case[1]); eq(c.scope,case[2],'challenge scope'); eq(c.resource_metadata,case[3],'challenge PRM'); eq(c.error,case[4],'challenge error') end for _,case in ipairs({ {'https://API.example/mcp','https://api.example/.well-known/oauth-protected-resource/mcp,https://api.example/.well-known/oauth-protected-resource'}, {'https://api.example/','https://api.example/.well-known/oauth-protected-resource'}, {'https://api.example/a/b?tenant=x','https://api.example/.well-known/oauth-protected-resource/a/b,https://api.example/.well-known/oauth-protected-resource'}, }) do eq(table.concat(OAuth.prm_urls(case[1]),','),case[2],'PRM URL order') end for _,case in ipairs({ {'https://as.example','https://as.example/.well-known/oauth-authorization-server,https://as.example/.well-known/openid-configuration'}, {'https://as.example/tenant','https://as.example/.well-known/oauth-authorization-server/tenant,https://as.example/.well-known/openid-configuration/tenant,https://as.example/tenant/.well-known/openid-configuration'}, }) do eq(table.concat(OAuth.metadata_urls(case[1]),','),case[2],'AS URL order') end for _,url in ipairs({'http://evil.example','https://u:p@as.example','https://as.example/#x','https://as.example\\@evil.test','https://127.0.0.1:99999'}) do eq(OAuth.url(url),nil,'unsafe OAuth URL rejected') end eq(OAuth.url('HTTPS://API.example:443/mcp'),'https://api.example/mcp','canonical resource') eq(table.concat(OAuth.union({'read','read'},{'write','read'}),' '),'read write','scope union') eq(#OAuth.scopes({'bad scope','quote"','back\\slash','read'}),1,'invalid scope tokens omitted') local metadata={issuer='https://as.example/tenant',authorization_endpoint='https://as.example/authorize',token_endpoint='https://as.example/token',code_challenge_methods_supported={'plain','S256'}} for _,case in ipairs({{metadata.issuer,true},{'https://as.example/tenant/',false},{'https://evil.example',false}}) do eq(not not OAuth.validate_metadata(metadata,case[1]),case[2],'exact issuer') end metadata.code_challenge_methods_supported={'plain'}; check(not OAuth.validate_metadata(metadata,metadata.issuer),'reject missing S256') metadata.code_challenge_methods_supported=nil; check(not OAuth.validate_metadata(metadata,metadata.issuer),'reject absent PKCE declaration') local _,configured,config_warnings=config.parse({servers={oauth={url='https://api.example/mcp',oauth={client_id='id',issuer='https://as.example/tenant',client_secret='${env:SECRET}',scopes={'configured'}}}}},{project_root='/project'},function() return 'DO_NOT_LOG' end) eq(configured.oauth.oauth.client_secret,'DO_NOT_LOG','OAuth secret expansion'); eq(#config_warnings,0) local _,missing_issuer,missing_warnings=config.parse({servers={remote={url='https://api.example/mcp',oauth={client_id='id',client_secret='secret'}}}},{project_root='/project'}) check(not missing_issuer.remote and missing_warnings[1]:find('oauth.issuer',1,true),'H1 configured client requires an issuer binding') local session=OAuth.session_name(string.rep('s',200),'https://resource.example/mcp','https://issuer.example','id') check(#session<=128,'H2 bounded core session name') for _,identity in ipairs({{'https://other.example/mcp','https://issuer.example','id'},{'https://resource.example/mcp','https://other.example','id'},{'https://resource.example/mcp','https://issuer.example','other'}}) do check(OAuth.session_name(string.rep('s',200),table.unpack(identity))~=session,'H2 resource/issuer/client identity changes token namespace') end eq(session,OAuth.session_name(string.rep('s',200),'https://resource.example/mcp','https://issuer.example','id'),'H2 session name is deterministic') for _,url in ipairs({'http://0127.0.0.1/x','https://127.00.0.1/x','http://127.0.0.01/x','https://127.1/x','https://2130706433/x','https://0x7f000001/x'}) do eq(OAuth.url(url),nil,'ambiguous IPv4 octets rejected') end local status={state='logged_out'}; local specs={}; local logins,refreshes=0,0; local definitions=0 local clock=0; local status_reads=0; local refresh_failure=false; local login_failure=false local dcr_count=0; local logouts={}; local prm_servers local issuer='https://as.example/tenant'; local scope_challenge='read write' local fake_auth={ define=function(name,spec) definitions=definitions+1; specs[name]=spec; return true end, status=function() status_reads=status_reads+1; return status end, login=function() logins=logins+1; if login_failure then login_failure=false; return nil,'AuthFlowFailed' end; status={state='pending'}; return {url='https://as.example/authorize?state=opaque'} end, logout=function(name) logouts[#logouts+1]=name; return true end, complete=function(_,url) if url=='bad' then return nil,'SECRET' end; status={state='pending'}; return true end, refresh=function() refreshes=refreshes+1; if refresh_failure then status={state='logged_out'}; return nil,type(refresh_failure)=='string' and refresh_failure or 'AuthLoginRequired' end; status={state='pending'}; return true end, } local stored={}; local fake_state={get=function(k) return stored[k] end,set=function(k,v) stored[k]=v; return true end} local sent={}; local protected='normal'; local refresh_once=false local registration_result={client_id='dynamic-public',registration_access_token='DO_NOT_STORE'} local function request_fn(opts,cb) sent[#sent+1]=opts local response={status=200,headers={},body=''} if opts.url=='https://api.example/mcp' then if not opts.auth or protected=='always401' or ((protected=='refresh' or protected=='refresh_scope') and not refresh_once) then if opts.auth then refresh_once=true end response.status=401; response.headers['www-authenticate']='Basic realm="x", Bearer resource_metadata="https://api.example/meta", scope="read"' response.body='DO_NOT_LOG_ACCESS_TOKEN' elseif protected=='bad_body' then response.status=500; response.body='DO_NOT_LOG_ACCESS_TOKEN' elseif protected=='bad_rpc' then response.status=500; local req=json.decode(opts.body) response.body=json.encode({jsonrpc='2.0',id=req.id,error={code=-32000,message='DO_NOT_LOG_ACCESS_TOKEN'}}) elseif (protected=='scope' or protected=='refresh_scope') and json.decode(opts.body).params.arguments and json.decode(opts.body).params.arguments.restricted then response.status=403; response.headers['www-authenticate']='Bearer error="insufficient_scope", scope="'..scope_challenge..'"' else local req=json.decode(opts.body) local result=req.method=='server/discover' and {capabilities={tools={}},resultType='complete'} or req.method=='tools/list' and {tools={{name='echo',inputSchema={type='object'}}}} or {content={{type='text',text='oauth success'}}} response.body=json.encode({jsonrpc='2.0',id=req.id,result=result}) end elseif opts.url=='https://api.example/meta' then check(not opts.auth and not opts.headers.Authorization,'discovery never carries credentials') response.body=json.encode({resource='https://api.example/mcp',authorization_servers=prm_servers or {issuer},scopes_supported={'fallback'}}) elseif opts.url==OAuth.metadata_urls(issuer)[1] then local origin=issuer:match('^(https://[^/]+)') response.body=json.encode({issuer=issuer,authorization_endpoint=origin..'/authorize',token_endpoint=origin..'/token', registration_endpoint=origin..'/register',code_challenge_methods_supported={'S256'},authorization_response_iss_parameter_supported=true}) elseif opts.url==issuer:match('^(https://[^/]+)')..'/register' then dcr_count=dcr_count+1; registration_result.client_id='dynamic-public-'..dcr_count local body=json.decode(opts.body) eq(body.application_type,'native'); eq(body.redirect_uris[1],'http://127.0.0.1/callback'); eq(body.token_endpoint_auth_method,'none') eq(table.concat(body.grant_types,','),'authorization_code,refresh_token') response.body=json.encode(registration_result) else error('unexpected fake OAuth request') end cb(response); return {cancel=function() end} end local ts,tf=timers() local _,cfgs=config.parse({servers={remote={url='https://api.example/mcp'}}},{project_root='/project'}) local manager=Manager.new(settings,cfgs,{cache_dir=temp..'/oauth-cache',request_fn=request_fn,auth=fake_auth,state=fake_state,timer_factory=tf,clock=function() return clock end}) local s=manager.states.remote; local oauth=s.oauth manager:start(s) eq(s.state,'failed','401 discovers then stops for user login'); check(s.error:find('/mcp-login remote',1,true),'login-required error: '..tostring(s.error)) eq(logins,0,'never starts login automatically'); eq(#sent,4,'401 PRM AS DCR sequence'); eq(definitions,1) check(oauth:blocked(),'logged-out scoped session requires login') local not_authorized=OAuth.new(cfgs.remote,{auth=fake_auth,state=fake_state,request_fn=request_fn,timer_factory=tf}) check(not_authorized:blocked() and not not_authorized:request_auth(),'warm definition still checks core status'); not_authorized:close() eq(specs[oauth.name].resource,'https://api.example/mcp'); eq(specs[oauth.name].scopes[1],'read','challenge overrides PRM') check(specs[oauth.name].require_iss,'require issuer in callback when advertised') check(not json.encode(stored):find('DO_NOT_STORE',1,true),'DCR registration tokens never persisted') local initial_name=oauth.name local command=manager:login('remote'); eq(dcr_count,1,'first login does not repeat initial DCR'); eq(oauth.name,initial_name,'first login retains token namespace') check(command:find('https://as.example/authorize',1,true),'login prints URL'); check(command:find('',1,true),'headless instructions') local function tick() local t=ts[#ts]; check(t and not t.closed,'poll timer armed'); clock=clock+t.ms; t:fire() end status={state='logged_in'}; tick() eq(s.state,'ready','login completion reconnects'); eq(logins,1) local output; async.run(function() output=manager:call('remote','echo',{}) end,error) check(output and not output.is_error and output.text:find('oauth success',1,true),'authenticated tool success') for _,mode in ipairs({'bad_body','bad_rpc'}) do protected=mode; async.run(function() output=manager:call('remote','echo',{}) end,error) check(output.is_error and not output.text:find('DO_NOT_LOG',1,true),'authenticated HTTP errors discard reflected credentials') end protected='normal' local before=#sent local warm=OAuth.new(cfgs.remote,{auth=fake_auth,state=fake_state,request_fn=request_fn,timer_factory=tf}) eq(#sent,before,'warm activation does not rediscover'); check(warm.definition,'warm definition restored') protected='refresh'; output=nil async.run(function() output=manager:call('remote','echo',{}) end,error) eq(refreshes,1,'401 forces one refresh'); check(not output,'refresh waits asynchronously') local parallel; local before_parallel=#sent async.run(function() parallel=manager:call('remote','echo',{}) end,error) check(not parallel,'M4 parallel calls wait for forced refresh'); eq(#sent,before_parallel,'no unauthenticated call while refresh pending') eq(oauth:request_auth(),oauth.name,'M4 refresh-pending retains auth name') status={state='logged_in'}; tick(); check(output and not output.is_error,'refresh retries successfully') check(parallel and not parallel.is_error,'M4 parallel call succeeds after refresh') protected='always401'; output=nil async.run(function() output=manager:call('remote','echo',{}) end,error) status={state='logged_in'}; tick() check(output.is_error and output.text:find('/mcp-login remote',1,true),'second 401 requires login'); eq(refreshes,2,'never refreshes twice per request') check(not output.text:find('DO_NOT_LOG',1,true),'401 body never reaches tool errors') eq(manager:login('remote','bad'),'OAuth callback rejected; check the URL/state/issuer and retry','callback rejection hides core detail') protected='normal'; manager:login('remote','callback'); status={state='logged_in'}; tick() protected='refresh_scope'; refresh_once=false; output=nil; async.run(function() output=manager:call('remote','echo',{restricted=true}) end,error) status={state='logged_in'}; tick() check(output.is_error and output.text:find('/mcp-login remote',1,true),'scope step-up after refresh asks for consent') eq(table.concat(oauth.spec.scopes,' '),'read write','scope step-up unions scopes') check(not oauth.login_required,'M3 scope step-up does not lock out the server') local stepped=OAuth.new(cfgs.remote,{auth=fake_auth,state=fake_state,request_fn=request_fn,timer_factory=tf}) check(not stepped:blocked() and stepped:request_auth(),'M3 warm scope upgrade preserves usable token'); stepped:close() local requests_before=#sent; async.run(function() output=manager:call('remote','echo',{}) end,error) check(#sent>requests_before and not output.is_error,'M3 unrelated tool still works after a scope challenge') scope_challenge='read'; status={state='logged_in',scopes={'read'}}; clock=clock+1000 async.run(function() output=manager:call('remote','echo',{restricted=true}) end,error) check(output.is_error and not oauth.login_required,'M3 already-held scope is a per-tool permission failure, not a server lockout') async.run(function() output=manager:call('remote','echo',{}) end,error) check(not output.is_error,'M3 unrelated tool works after already-held scope challenge') local logins_before=logins for i=1,5 do local ok,err=oauth:recover({http_status=403,challenge={error='insufficient_scope',scope='extra'..i}}) check(not ok and err:find('/mcp-login',1,true),'scope upgrades require user action, not an artificial counter') end eq(logins,logins_before,'scope challenges never start login automatically') protected='refresh'; refresh_once=false; refresh_failure='AuthFlowFailed'; status={state='logged_in'} local discovery_before=#sent async.run(function() output=manager:call('remote','echo',{}) end,error) check(output.is_error and #sent>discovery_before+1 and oauth.definition,'M6 refresh failure rediscovered metadata and registration') eq(dcr_count,1,'transient refresh failure keeps DCR registration'); eq(oauth.name,initial_name,'transient failure retains token namespace') check(output.text:find('--reregister',1,true),'failed refresh explains registration escape hatch') refresh_failure=false; protected='normal'; issuer='https://as2.example/tenant'; local old_name=oauth.name; login_failure=true local refreshed_login=manager:login('remote') check(refreshed_login:find('https://as.example/authorize',1,true),'M6 manual login starts after rediscovery') eq(oauth.spec.issuer,issuer,'M6 manual login observes changed issuer'); check(oauth.name~=old_name,'H2 changed issuer selects a different token file') eq(logouts[#logouts],old_name,'issuer/name change logs out previous session') status={state='logged_in'}; tick(); eq(s.state,'ready','rediscovered login reconnects') local count=dcr_count; local stable=oauth.name; local requests=#sent manager:login('remote') eq(dcr_count,count,'repeat consent login keeps DCR registration'); eq(oauth.name,stable,'repeat consent retains session name'); eq(#sent,requests,'usable definition avoids rediscovery') check(not oauth:blocked() and not oauth.login_required,'consent login does not block an existing usable token') async.run(function() output=manager:call('remote','echo',{}) end,error) check(not output.is_error,'working tools remain usable during consent') for _=1,670 do local t; for i=#ts,1,-1 do if not ts[i].closed then t=ts[i]; break end end assert(t,'login poll must remain active until give-up'); clock=clock+t.ms; t:fire() end check(not oauth.login_required and not oauth:blocked(),'abandoned consent poll clears lockout and retains usable token') check(s.error:find('--reregister',1,true),'failed login poll explains escape hatch') status={state='logged_in'}; clock=clock+1000 async.run(function() output=manager:call('remote','echo',{}) end,error); check(not output.is_error,'working tools survive abandoned consent') manager:login('remote',nil,true) eq(dcr_count,count+1,'explicit --reregister performs exactly one DCR'); check(oauth.name~=stable,'explicit reregistration selects new client namespace') eq(logouts[#logouts],stable,'explicit reregistration logs out old namespace') status={state='logged_in'}; tick() manager:close(); warm:close() for _,case in ipairs({{method='none',secret='IGNORE_PUBLIC_SECRET'},{method='client_secret_basic',secret='CONFIDENTIAL_DCR_SECRET'}}) do local key='mcp.oauth.registration_'..config.hash(issuer); stored[key]=nil registration_result={client_id='registered-'..case.method,client_secret=case.secret,token_endpoint_auth_method=case.method} local instance=OAuth.new({name='client_'..case.method,url=cfgs.remote.url,fingerprint=case.method}, {auth=fake_auth,state=fake_state,request_fn=request_fn,timer_factory=tf}) local ok,why=instance:discover({resource_metadata='https://api.example/meta'}) check(not ok and why:find('Confidential DCR',1,true),'M5 refuse any DCR secret, including public-method responses') check(not instance.spec and not stored[key],'M5 confidential DCR is never defined or persisted') check(not why:find(case.secret,1,true) and not json.encode(stored):find(case.secret,1,true),'M5 secret absent from state/errors') instance:close() end local old=OAuth.new(cfgs.remote,{auth={},state=fake_state,request_fn=request_fn,timer_factory=tf}) local _,old_error=old:recover({http_status=401}); check(old_error:find('newer panto',1,true),'old core OAuth clear error') local override=OAuth.new({name='remote',url='https://api.example/mcp',auth='custom'},{auth=fake_auth,state=fake_state}) eq(override:request_auth(),'custom','explicit auth takes precedence'); check(not override.definition,'explicit auth disables automatic definition') for _,auth in ipairs({{}, {define=function() return true end,status=function() return {state='logged_in'} end,login=function() return nil,'UnsupportedAuthType' end,complete=function() end,refresh=function() return nil,'UnsupportedAuthType' end}}) do local explicit=OAuth.new({name='explicit',auth='api-key',url=cfgs.remote.url},{auth=auth,state=fake_state}) local _,err=explicit:recover({http_status=401,auth_used=true}) check(err:find('Configured auth session',1,true) and not err:find('newer panto',1,true) and not err:find('/mcp-login',1,true),'explicit/non-PKCE auth rejection has actionable, accurate error') end local _,permission_error=override:recover({http_status=403,challenge={}}) check(permission_error:find('permissions',1,true) and not permission_error:find('/mcp-login',1,true),'unrelated 403 is not a login instruction') local cached=OAuth.new(cfgs.remote,{auth=fake_auth,state=fake_state,clock=function() return clock end}) local reads_before=status_reads for _=1,100 do cached:status(); cached:blocked(); cached:request_auth() end eq(status_reads,reads_before+1,'status reads cached across request/status paths') clock=clock+999; cached:status(); eq(status_reads,reads_before+1,'status cache holds for one second') clock=clock+1; cached:status(); eq(status_reads,reads_before+2,'status cache refreshes after one second'); cached:close() local unsafe_requests=0 local remote_policy=OAuth.new({name='remote',url='https://resource.example/mcp'},{auth=fake_auth,state=fake_state,request_fn=function() unsafe_requests=unsafe_requests+1 end}) for _,url in ipairs({'http://127.0.0.1:6379/','http://[::1]/','https://127.0.0.1/','https://localhost/','https://localhost./','https://[0:0:0:0:0:0:0:1]/','https://[::ffff:7f00:1]/'}) do local value=remote_policy:fetch(url); check(not value,'remote OAuth cannot reach loopback discovery/DCR') end eq(unsafe_requests,0,'unsafe loopback URLs rejected before HTTP') local local_policy=OAuth.new({name='local',url='http://127.0.0.1:9000/mcp'},{auth=fake_auth,state=fake_state}) check(local_policy:url_allowed('http://127.0.0.1:9001/meta'),'loopback resource permits loopback OAuth') registration_result={client_id='public'}; prm_servers={'https://unrelated.example',issuer} local pinned=OAuth.new({name='pinned',url=cfgs.remote.url,fingerprint='pin',oauth={issuer=issuer}}, {auth=fake_auth,state=fake_state,request_fn=request_fn,timer_factory=tf}) check(pinned:discover({resource_metadata='https://api.example/meta'}),'issuer-only pin selects the advertised second issuer') eq(pinned.spec.issuer,issuer,'DCR uses the configured issuer without a client ID') local definitions_before=definitions pinned.cfg.oauth.issuer='https://other.example' check(not pinned:define(pinned.definition) and definitions==definitions_before,'warm definition enforces issuer-only pin'); pinned:close() prm_servers=nil -- Discovery fallbacks fail closed on a mismatched resource/issuer, not on unavailable URLs. for _,case in ipairs({ {name='fallback',scope='prm',requests=5}, {name='configured',scope='configured',requests=5,no_prm_scopes=true}, {name='bad_resource',error='resource mismatch',requests=2}, {name='bad_issuer',error='issuer mismatch',requests=5}, {name='bad_pkce',error='S256',requests=5}, {name='foreign_issuer',error='oauth.issuer',requests=2}, }) do local calls={}; local saved={}; local spec local auth={define=function(_,value) spec=value; return true end,status=function() return {state='logged_out'} end, login=fake_auth.login,complete=fake_auth.complete,refresh=fake_auth.refresh} local state={get=function(key) return saved[key] end,set=function(key,value) saved[key]=value; return true end} local cfg={name=case.name,url='https://resource.example/mcp',fingerprint=case.name,oauth={client_id='configured-id',issuer='https://issuer.example/tenant',client_secret='CONFIG_SECRET',scopes={'configured'}}} local function request(options,callback) calls[#calls+1]=options.url local value if options.url=='https://resource.example/.well-known/oauth-protected-resource' then value={resource=case.name=='bad_resource' and 'https://other.example' or 'https://resource.example',authorization_servers={case.name=='foreign_issuer' and 'https://evil-as.example' or 'https://issuer.example/tenant'}, scopes_supported=not case.no_prm_scopes and {'prm'} or nil} elseif options.url=='https://issuer.example/tenant/.well-known/openid-configuration' then value={issuer=case.name=='bad_issuer' and 'https://other.example' or 'https://issuer.example/tenant', authorization_endpoint='https://issuer.example/authorize',token_endpoint='https://issuer.example/token', code_challenge_methods_supported=case.name=='bad_pkce' and {'plain'} or {'S256'}} end callback({status=value and 200 or 404,body=value and json.encode(value) or ''}) return {cancel=function() end} end local failed_clock=0 local o=OAuth.new(cfg,{auth=auth,state=state,request_fn=request,timer_factory=tf,clock=function() return failed_clock end}) local ok,err=o:recover({http_status=401,challenge={}}) check(not ok,'discovery never starts user login'); eq(#calls,case.requests,'fallback request count') if case.error then check(err:find(case.error,1,true),'discovery validation fails closed'); check(not spec,'invalid discovery never defines auth') o:recover({http_status=401,challenge={}}); eq(#calls,case.requests,'failed discovery is negatively cached') failed_clock=5000; o:recover({http_status=401,challenge={}}) eq(#calls,case.requests*2,'negative discovery cache expires via injected clock') eq(o.retry_at,15000,'failed discovery backoff increases without waiting') else check(err:find('/mcp-login',1,true),'configured discovery requests login') eq(spec.client_id,'configured-id','configured id skips DCR'); eq(spec.client_secret,'CONFIG_SECRET') eq(spec.scopes[1],case.scope,'scope selection fallback') check(not json.encode(saved):find('CONFIG_SECRET',1,true),'configured secrets absent from discovery state') eq(calls[3],'https://issuer.example/.well-known/oauth-authorization-server/tenant','RFC8414 before OIDC') eq(calls[4],'https://issuer.example/.well-known/openid-configuration/tenant','OIDC inserted before appended') end o:close() end -- Poll timeout and teardown settle parked refreshes with injected timers only. local timeout_auth={define=fake_auth.define,status=function() return {state='pending'} end,login=fake_auth.login,complete=fake_auth.complete, refresh=function() return true end} local timeout=OAuth.new(cfgs.remote,{auth=timeout_auth,timer_factory=tf,state=fake_state}) local settled,refresh_error async.run(function() settled,refresh_error=timeout:refresh() end,error) for _=1,70 do ts[#ts]:fire() end check(not settled and refresh_error:find('/mcp-login',1,true),'injected refresh deadline settles caller') refresh_error=nil async.run(function() settled,refresh_error=timeout:refresh() end,error) timeout:close() eq(refresh_error,'session ended','teardown settles refresh without blocking') end -- HTTP transport/parser checks use an injected request API. `panto lua` has -- an http_request function, but no usable HTTP service outside an active entry. local http=require('panto_mcp.http') for i,c in ipairs({ {{'data: one\n\n'},{'one'}}, {{'data: hel','lo\r','\n\r\n'},{'hello'}}, {{': ping\r\nevent: message\r\ndata: first\r\ndata: second\r\n\r\n'},{'first\nsecond'}}, {{'event: empty\n\n'},{}}, {{'event: ping\ndata: ignored\n\n'},{}}, {{'event: message\ndata:\n\n'},{}}, {{'\239','\187\191data: bom\n\n'},{'bom'}} }) do local got={}; local parser=http.sse_parser(function(v) got[#got+1]=v end) for _,chunk in ipairs(c[1]) do check(parser:feed(chunk),'SSE feed') end check(parser:finish(),'SSE finish'); eq(#got,#c[2],'SSE event count '..i) for j,value in ipairs(c[2]) do eq(got[j],value,'SSE value '..i) end end local eof_events={}; local eof_parser=http.sse_parser(function(v) eof_events[#eof_events+1]=v end) check(eof_parser:feed('data: final'),'SSE partial'); check(eof_parser:finish(),'SSE EOF'); eq(eof_events[1],'final') check(eof_parser:feed('data: carriage\r'),'SSE trailing CR'); check(eof_parser:finish(),'SSE CR EOF'); eq(eof_events[2],'carriage') local header_cfg={headers={accept='wrong',['MCP-METHOD']='wrong',Authorization='Bearer PRIVATE'}} local mh=http.headers(header_cfg,{era='modern',protocol_version='2026-07-28',method='tools/call',name='lookup'}) eq(mh.Accept,'application/json, text/event-stream'); eq(mh['Content-Type'],'application/json'); eq(mh['MCP-Protocol-Version'],'2026-07-28') eq(mh['Mcp-Method'],'tools/call'); eq(mh['Mcp-Name'],'lookup'); eq(mh.Authorization,'Bearer PRIVATE'); eq(mh.accept,nil) for _,method in ipairs({'tools/call','resources/read','prompts/get'}) do eq(http.headers({}, {era='modern',method=method,name='item'})['Mcp-Name'],'item','required MCP name header') end eq(http.headers({}, {era='modern',method='tools/list'})['Mcp-Name'],nil,'name omitted for other methods') local ih=http.headers(header_cfg,{era='legacy',initial=true,method='initialize'},'old') eq(ih['MCP-Protocol-Version'],nil); eq(ih['Mcp-Session-Id'],nil) local lh=http.headers(header_cfg,{era='legacy',protocol_version='2025-06-18'},'sid') eq(lh['MCP-Protocol-Version'],'2025-06-18'); eq(lh['Mcp-Session-Id'],'sid') do local schema={type='object',properties={region={type={'string','null'},['x-mcp-header']='Region'},nested={type='object',properties={count={type='integer',['x-mcp-header']='Count'},flag={type='boolean',['x-mcp-header']='Flag'},optional={type={'string','null'},['x-mcp-header']='Optional'}}}}} local annotations=assert(http.validate_param_headers(schema)); eq(#annotations,4) local headers=assert(http.headers({}, {era='modern',method='tools/call',name='météo ',param_headers=annotations, arguments={region='us-west1',nested={count=-7,flag=false,optional=json.null}}})) eq(headers['Mcp-Name'],'=?base64?bcOpdMOpbyA=?='); eq(headers['Mcp-Param-Region'],'us-west1') eq(headers['Mcp-Param-Count'],'-7'); eq(headers['Mcp-Param-Flag'],'false'); eq(headers['Mcp-Param-Optional'],nil) for _,c in ipairs({ {'plain','plain'}, {'Hello, 世界','=?base64?SGVsbG8sIOS4lueVjA==?='}, {' padded ','=?base64?IHBhZGRlZCA=?='}, {'=?base64?literal?=','=?base64?PT9iYXNlNjQ/bGl0ZXJhbD89?='} }) do eq(http.encode_header_value(c[1]),c[2],'MCP header value encoding') end check(http.validate_param_headers({type='object',properties={id={type='string',['x-mcp-header']='Id'}},allOf={{type='object'}}}), 'properties path is static despite unrelated composition') check(http.validate_param_headers({type='object',properties={['x-mcp-header']={type='string'}},enum={{['x-mcp-header']='data'}}}), 'instance data is not misread as schema annotation') check(http.validate_param_headers({type='object',properties={enum={type='string',['x-mcp-header']='Enum'}}}), 'instance-data keyword may also name a property') local bad={ {type='string',['x-mcp-header']='Root'}, {type='object',properties={x={type='number',['x-mcp-header']='X'}}}, {type='object',properties={x={type='string',['x-mcp-header']=''}}}, {type='object',properties={x={type='string',['x-mcp-header']='Bad Name'}}}, {type='object',properties={x={type='string',['x-mcp-header']='Region'},y={type='string',['x-mcp-header']='region'}}}, {type='object',properties={items={type='array',items={type='object',properties={r={type='string',['x-mcp-header']='X'}}}}}}, {type='object',oneOf={{type='object',properties={r={type='string',['x-mcp-header']='X'}}}}}, {type='object',properties={items={type='array',items={{type='string',['x-mcp-header']='X'}}}}}, {type='object',properties={x={anyOf={{type='string',['x-mcp-header']='X'}}}}}, {type='object',properties={x={['$ref']='#/$defs/x',['x-mcp-header']='X'}}} } for i,bad_schema in ipairs(bad) do local result,why=http.validate_param_headers(bad_schema); check(not result and why,'invalid x-mcp-header schema '..i) end end for i,c in ipairs({ {{code=-32022,message='UnsupportedProtocolVersion',data={supported={'2025-11-25'}}},false}, {{code=-32020,message='HeaderMismatch'},false}, {{code=-32000,message='bad request',data={http_status=400,transport_fallback=true}},true}, {{code=-32000,message='not found',data={http_status=404,transport_fallback=true}},true}, {{code=-32601,message='modern method not found',data={http_status=404,transport_fallback=false}},false}, {{code=-32601,message='legacy discover missing',data={http_status=404,transport_fallback=true}},true}, {{code=-32000,message='unauthorized',data={http_status=401,auth_error=true}},false}, {'request timed out: server/discover',true}, {'remote server/discover: request timed out: server/discover',true}, {'connect failed',false}, {'DNS resolution failed',false}, {'TLS handshake failed',false}, {'idle timeout',true} }) do eq(http.should_fallback(c[1]),c[2],'era fallback '..i) end for _,c in ipairs({ {'connect failed','transport'}, {'TLS failed','transport'}, {'timeout','timeout'}, {'idle timeout','idle_timeout'}, {'connection closed before response','transport'}, {'connection closed mid-response','transport'}, {'other','transport'}, {'response too large','transport'}, {'authentication unavailable','transport'}, {'on_head callback failed: timeout','callback'}, {'on_data callback failed: timeout','callback'} }) do eq(http.failure_kind(c[1]),c[2],'core failure label') end check(not http.should_fallback('on_data callback failed: timeout'),'callback failure never falls back') check(http.methods_supported(function() return nil,'invalid HTTP request options' end),'method-capable API probe') local old_probe_cancelled=false check(not http.methods_supported(function() return {cancel=function() old_probe_cancelled=true end} end),'GET-only API rejected') check(old_probe_cancelled,'unsupported API probe cancelled') do local probes=0; local capable=function() probes=probes+1; return nil,'invalid HTTP request options' end check(http.methods_supported(capable),'method capability true'); check(http.methods_supported(capable),'method capability cached'); eq(probes,1) end local function http_reply(opts,cb,status,headers,body,chunks) headers=headers or {}; opts.on_head({status=status,headers=headers}) for _,chunk in ipairs(chunks or (body and {body}) or {}) do opts.on_data(chunk) end cb({status=status,headers=headers},nil) end local remote={name='remote',url='https://example.test/mcp',auth='mcp.remote',headers={['X-Tenant']='acme'}} local function injected(cfg,respond,settings_arg,timer_factory) local calls={} local function request(options,callback) calls[#calls+1]=options local handle={cancelled=false}; function handle:cancel() self.cancelled=true end respond(options,callback,handle,#calls); return handle end local tr,err=http.new(cfg,settings_arg or {idle_timeout_ms=4321,call_timeout_ms=300000}, {request_fn=request,timer_factory=timer_factory}); assert(tr,err) local messages,errors={},{}; tr:set_callbacks(function(m) messages[#messages+1]=m end,function(e) errors[#errors+1]=e end) return tr,calls,messages,errors end do local now,js_timers=0,{} local function js_factory(ms,fn) local timer={at=now+ms,closed=false,fn=fn} function timer:is_closing() return self.closed end function timer:close() self.closed=true end function timer:fire() if not self.closed then self:close(); self.fn() end end js_timers[#js_timers+1]=timer; return timer end local function advance(ms) now=now+ms for _,timer in ipairs(js_timers) do if timer.at<=now then timer:fire() end end end local callback,opts,handle local slow=assert(http.new(remote,{idle_timeout_ms=10,call_timeout_ms=5000},{timer_factory=js_factory,request_fn=function(o,cb) opts=o; callback=cb; handle={cancelled=false}; function handle:cancel() self.cancelled=true end o.on_head({status=200,headers={['content-type']='application/json'}}); return handle end})) local rpc=Rpc.new(slow,{timeout_ms=5000,timer_factory=js_factory}) local future=rpc:start('tools/call',{name='hello',arguments={}},{era='modern',protocol_version='2026-07-28',method='tools/call'}) eq(opts.idle_timeout_ms,0,'core idle timeout disabled'); eq(#js_timers,1,'JSON has only total-call deadline') eq(js_timers[1].at,5000,'JSON response total cap is call_timeout_ms') advance(11); check(not future.done,'slow JSON remains pending past idle timeout') opts.on_data(json.encode({jsonrpc='2.0',id=1,result={ok=true}})) callback({status=200,headers={['content-type']='application/json'}},nil) check(future.done and future.value.ok,'slow JSON answer survives idle threshold'); rpc:close() local idle_timers,idle_factory=timers(); local idle_handle; local idle_messages={} local idle_http=assert(http.new(remote,{idle_timeout_ms=25},{timer_factory=idle_factory,request_fn=function(o) idle_handle={cancelled=false}; function idle_handle:cancel() self.cancelled=true end o.on_head({status=200,headers={['content-type']='text/event-stream'}}); return idle_handle end})) idle_http:set_callbacks(function(m) idle_messages[#idle_messages+1]=m end,function() end) idle_http:send({jsonrpc='2.0',id=55,method='tools/call',params={name='hello'}},{era='modern',protocol_version='2026-07-28',method='tools/call'}) eq(idle_timers[1].ms,25,'SSE Lua idle timer starts at response head') idle_timers[1]:fire(); check(idle_handle.cancelled and idle_messages[1].error.data.transport_error=='idle_timeout','idle timeout cancels only stream') end do local stream_options,stream_handle,stream_messages stream_messages={} local notification_stream=assert(http.new(remote,{},{request_fn=function(options) if options.method=='GET' then stream_options=options stream_handle={cancelled=false}; function stream_handle:cancel() self.cancelled=true end options.on_head({status=200,headers={['content-type']='text/event-stream'}}) options.on_data('data: '..json.encode({jsonrpc='2.0',method='notifications/tools/list_changed'})..'\n\n') return stream_handle end return {cancel=function() end} end})) notification_stream.protocol_version='2025-11-25'; notification_stream.session_id='legacy-session' notification_stream:set_callbacks(function(message) stream_messages[#stream_messages+1]=message end,function(err) error(err) end) check(notification_stream:open_notification_stream(),'legacy notification GET opened') eq(stream_options.method,'GET'); eq(stream_options.timeout_ms,0); eq(stream_options.idle_timeout_ms,0) eq(stream_options.headers.Accept,'text/event-stream'); eq(stream_options.headers['Content-Type'],nil) eq(stream_options.headers['Mcp-Session-Id'],'legacy-session'); eq(stream_options.headers['MCP-Protocol-Version'],'2025-11-25') eq(stream_messages[1].method,'notifications/tools/list_changed','legacy GET delivers JSON-RPC notifications') notification_stream:close(); check(stream_handle.cancelled,'legacy GET closes on teardown') local unsupported_handle,unsupported_errors unsupported_errors=0 local no_stream=assert(http.new(remote,{}, {request_fn=function(options) if options.method=='GET' then unsupported_handle={cancelled=false}; function unsupported_handle:cancel() self.cancelled=true end options.on_head({status=405,headers={}}); return unsupported_handle end return {cancel=function() end} end})) no_stream:set_callbacks(function() end,function() unsupported_errors=unsupported_errors+1 end) check(not no_stream:open_notification_stream(),'405 means no notification stream') check(unsupported_handle.cancelled and unsupported_errors==0,'405 stream is benign and cancelled') no_stream:close() end do local retry_timers,retry_factory=timers(); local get_count,list_count,initialize_count=0,0,0 local get_done,get_handles,get_options={},{},{} local request_fn=function(options,callback) if options.method=='GET' then get_count=get_count+1; get_options[get_count]=options; get_done[get_count]=callback local handle={cancelled=false}; function handle:cancel() self.cancelled=true end; get_handles[get_count]=handle options.on_head({status=200,headers={['content-type']='text/event-stream'}}) return handle elseif options.method=='DELETE' then return {cancel=function() end} end local request=json.decode(options.body) if request.method=='initialize' then initialize_count=initialize_count+1 http_reply(options,callback,200,{['content-type']='application/json',['mcp-session-id']='sid'..initialize_count}, json.encode({jsonrpc='2.0',id=request.id,result={protocolVersion='2025-11-25',capabilities={tools={listChanged=true}}}})) elseif request.method=='notifications/initialized' then http_reply(options,callback,202,{}) elseif request.method=='tools/list' then list_count=list_count+1 if list_count==2 then http_reply(options,callback,404,{},'expired') else http_reply(options,callback,200,{['content-type']='application/json'},json.encode({jsonrpc='2.0',id=request.id,result={tools={}}})) end else http_reply(options,callback,200,{['content-type']='application/json'},json.encode({jsonrpc='2.0',id=request.id,result={}})) end return {cancel=function() end} end local eager_http={name='remote',url=remote.url,transport='http',expose='eager',auth=remote.auth,headers=remote.headers,args={},env={}} local client=require('panto_mcp.client').new(eager_http,settings,{timer_factory=retry_factory,request_fn=request_fn}) check(client:connect({era='legacy',version='2025-11-25'}),'legacy eager client connects with notification stream') eq(get_count,1) get_done[1]({status=200,headers={}},nil) local retry_timer for _,timer in ipairs(retry_timers) do if timer.ms==1000 and not timer.closed then retry_timer=timer end end check(retry_timer,'closed legacy stream schedules an injected reconnect timer') retry_timer:fire(); eq(get_count,2,'closed legacy stream reopens') local result,err=client:request('tools/list',{}) check(result and not err,'404 session re-init retries the original list request') eq(initialize_count,2); eq(get_count,3,'404 re-init opens a new notification stream') check(get_handles[2].cancelled,'old session stream closes before re-init') eq(get_options[3].headers['Mcp-Session-Id'],'sid2','reopened stream uses replacement session') client:close(); check(get_handles[3].cancelled,'replacement stream closes on teardown') local gets=0 local proxy=require('panto_mcp.client').new({name='proxy',url=remote.url,transport='http',expose='eager'},settings,{timer_factory=retry_factory,request_fn=function(options,callback) if options.method=='GET' then gets=gets+1 local status=gets>=9 and 401 or 200 options.on_head({status=status,headers={['content-type']='text/event-stream'}}) callback({status=status,headers={}}) elseif options.method=='POST' then local req=json.decode(options.body) local result=req.method=='initialize' and {protocolVersion='2025-11-25',capabilities={tools={listChanged=true}}} or {tools={}} if req.id then http_reply(options,callback,200,{['content-type']='application/json'},json.encode({jsonrpc='2.0',id=req.id,result=result})) else http_reply(options,callback,202,{}) end end return {cancel=function() end} end}) check(proxy:connect({era='legacy',version='2025-11-25'}),'proxy notification test connects') for _,delay in ipairs({1000,2000,4000,8000,16000,32000,60000,60000}) do local t=assert(proxy.notification_retry_timer); eq(t.ms,delay,'stream retry exponential delay/cap'); t:fire() end check(proxy.notification_retry_stopped and not proxy.notification_retry_timer,'401 stops notification reconnects') local warning_manager=Manager.new(settings,{}) warning_manager.states.proxy={cfg=proxy.cfg,state='ready',client=proxy} check(require('panto_mcp.tools').status(warning_manager,{}):find('Notification stream rejected (HTTP 401)',1,true),'401 notification warning is visible in /mcp') warning_manager:close() end local active_http=require('panto').ext.http_request if not http.methods_supported(active_http) then local missing,why=http.new(remote,{}) check(not missing and why:find('require a newer panto',1,true),'missing HTTP POST API reports upgrade requirement') end local jt,jcalls,jm=injected(remote,function(o,cb) eq(o.method,'POST'); eq(o.auth,'mcp.remote'); eq(o.timeout_ms,0); eq(o.idle_timeout_ms,0) eq(o.headers['Mcp-Method'],'server/discover'); eq(o.headers['MCP-Protocol-Version'],'2026-07-28') http_reply(o,cb,200,{['content-type']='application/json'},json.encode({jsonrpc='2.0',id=1,result={ok=true}})) end) jt:send({jsonrpc='2.0',id=1,method='server/discover',params={}},{era='modern',protocol_version='2026-07-28',method='server/discover'}) eq(jm[1].result.ok,true); eq(jcalls[1].headers['X-Tenant'],'acme') local sm={}; local st=injected(remote,function(o,cb) local n='event: message\r\ndata: {"jsonrpc":"2.0","method":"notifications/tools/list_changed"}\r\n\r\n' local r='event: message\r\ndata: {"jsonrpc":"2.0","id":2,"result":{"ok":true}}\r\n\r\n' http_reply(o,cb,200,{['content-type']='text/event-stream'},nil,{n:sub(1,31),n:sub(32)..r:sub(1,25),r:sub(26)}) end) st:set_callbacks(function(m) sm[#sm+1]=m end,function() end) st:send({jsonrpc='2.0',id=2,method='tools/list',params={}},{era='modern',protocol_version='2026-07-28',method='tools/list'}) eq(#sm,2); eq(sm[1].method,'notifications/tools/list_changed'); eq(sm[2].result.ok,true) do local posted=0; local transport=assert(http.new(remote,{idle_timeout_ms=100},{request_fn=function(o,cb) posted=posted+1 local events={ 'data: {"jsonrpc":"2.0","method":"notifications/progress"}\n\n', 'data: {"jsonrpc":"2.0","id":1,"method":"ping"}\n\n', 'data: {"jsonrpc":"2.0","id":1,"result":{"ok":true}}\n\n' } http_reply(o,cb,200,{['content-type']='text/event-stream'},nil,events) return {cancel=function() end} end})) local rpc=Rpc.new(transport,{timer_factory=function() return {close=function() end,is_closing=function() return false end} end}) local future=rpc:start('tools/list',{}, {era='modern',protocol_version='2026-07-28'}) check(future.done and future.value.ok,'server request with colliding id does not settle call') eq(posted,1,'modern response to server request is dropped, not posted') rpc:close() end do local count=0; local transport=assert(http.new(remote,{}, {request_fn=function(o,cb) count=count+1; local id=json.decode(o.body).id local handle={cancelled=false}; function handle:cancel() self.cancelled=true end if count==1 then http_reply(o,cb,200,{['content-type']='application/json'},json.encode({jsonrpc='2.0',id=id})) else o.on_head({status=200,headers={['content-type']='application/json'}}) end return handle end})) local rpc=Rpc.new(transport,{timeout_ms=5000,timer_factory=function() return {close=function() end,is_closing=function() return false end} end}) local malformed=rpc:start('tools/list',{}, {era='modern',protocol_version='2026-07-28'}) local other=rpc:start('tools/call',{name='hello'},{era='modern',protocol_version='2026-07-28'}) check(malformed.done and malformed.err.code==-32000 and malformed.err.message:find('malformed JSON-RPC response',1,true),'malformed matching response is request-scoped') check(not rpc.closed and not other.done,'malformed response leaves other RPCs alive') other:cancel(); rpc:close() end local step=0; local lt,lc= injected({name='legacy',url='http://127.0.0.1:1234',headers={}},function(o,cb) if o.method=='DELETE' then return end local req=json.decode(o.body); step=step+1 if req.method=='initialize' then http_reply(o,cb,200,{['content-type']='application/json',['mcp-session-id']='old-session'},json.encode({jsonrpc='2.0',id=req.id,result={protocolVersion='2025-11-25',capabilities={}}})) elseif req.method=='notifications/initialized' then http_reply(o,cb,202,{}) else http_reply(o,cb,404,{},'expired') end end) local legacy_received={}; lt:set_callbacks(function(m) legacy_received[#legacy_received+1]=m end,function(e) error(e) end) lt:send({jsonrpc='2.0',id=10,method='initialize',params={protocolVersion='2025-11-25'}},{era='legacy',protocol_version='2025-11-25',method='initialize'}) lt:send({jsonrpc='2.0',method='notifications/initialized',params={}},{era='legacy',protocol_version='2025-11-25',method='notifications/initialized'}) lt:send({jsonrpc='2.0',id=11,method='tools/list',params={}},{era='legacy',protocol_version='2025-11-25',method='tools/list'}) eq(#lc,3,'expired session signals re-handshake without DELETE'); eq(legacy_received[#legacy_received].id,11) check(legacy_received[#legacy_received].error.data.session_expired,'404 signals client re-handshake'); eq(lt.session_id,nil) eq(lc[1].headers['MCP-Protocol-Version'],nil); eq(lc[2].headers['MCP-Protocol-Version'],'2025-11-25') eq(lc[3].headers['Mcp-Session-Id'],'old-session') lt:close() do local calls={}; local tr=assert(http.new({name='reply',url='https://example.test',headers={}}, {call_timeout_ms=5000}, {request_fn=function(o,cb) calls[#calls+1]=o local req=json.decode(o.body) local h={cancelled=false}; function h:cancel() self.cancelled=true end if req.method=='tools/list' then o.on_head({status=200,headers={['content-type']='application/json'}}) elseif req.method=='notifications/cancelled' then http_reply(o,cb,404,{},'stale session') elseif req.method==nil and req.error then http_reply(o,cb,400,{['content-type']='application/json'},json.encode({jsonrpc='2.0',id=req.id,error=req.error})) else http_reply(o,cb,202,{}) end return h end})) tr.era='legacy'; tr.protocol_version='2025-06-18'; tr.session_id='sid' local delivered,transport_errors={},{} tr:set_callbacks(function(m) delivered[#delivered+1]=m end,function(e) transport_errors[#transport_errors+1]=e end) local request_state=tr:send({jsonrpc='2.0',id=1,method='tools/list',params={}},{era='legacy',protocol_version='2025-06-18',method='tools/list'}) tr:send({jsonrpc='2.0',id=1,result={}},{method='ping'}) check(tr.active['id:1']==request_state,'server reply ID does not collide with client request') tr:send({jsonrpc='2.0',id=1,error={code=-32601,message='reply failed'}},{method='elicitation/create'}) check(tr.active['id:1']==request_state and #delivered==0 and #transport_errors==0,'failed reply is logged but isolated') eq(calls[2].headers['MCP-Protocol-Version'],'2025-06-18'); eq(calls[2].headers['Mcp-Session-Id'],'sid') tr:cancel(1,request_state) local cancelled=json.decode(calls[4].body); eq(cancelled.method,'notifications/cancelled') eq(calls[4].headers['MCP-Protocol-Version'],'2025-06-18'); eq(calls[4].headers['Mcp-Session-Id'],'sid') check(not tr.closed and #delivered==0 and #transport_errors==0,'failed cancellation POST is non-fatal') end do local calls={}; local tr=assert(http.new({name='sessionless',url='http://127.0.0.1:1234',headers={}}, {}, {request_fn=function(o,cb) calls[#calls+1]=o; local h={cancel=function() end} if json.decode(o.body).method=='notifications/cancelled' then http_reply(o,cb,202,{}) else o.on_head({status=200,headers={['content-type']='application/json'}}) end return h end})) local req=tr:send({jsonrpc='2.0',id=8,method='tools/call',params={name='x'}},{era='legacy',protocol_version='2024-11-05',method='tools/call'}) tr:cancel(8,req); eq(#calls,2,'sessionless legacy sends cancellation') eq(json.decode(calls[2].body).method,'notifications/cancelled'); eq(calls[2].headers['MCP-Protocol-Version'],'2024-11-05') eq(calls[2].headers['Mcp-Session-Id'],nil,'sessionless cancellation omits id') tr:close() end do local modern_posts=0 local modern=assert(http.new({name='modern',url='https://example.test',headers={}}, {}, {request_fn=function() modern_posts=modern_posts+1; return {} end})) modern.era='modern'; modern.protocol_version='2026-07-28' modern:send({jsonrpc='2.0',id='peer',result={}},{method='ping'}) eq(modern_posts,0,'modern era drops forbidden server-request replies') end do local errors={} local tr=assert(http.new({name='handshake',url='https://example.test',headers={}}, {}, {request_fn=function(o,cb) http_reply(o,cb,500,{['content-type']='text/plain'},'initialized rejected') return {cancel=function() end} end})) tr:set_callbacks(function() error('fire-and-forget reached RPC') end,function(e) errors[#errors+1]=e end) local handle=tr:send({jsonrpc='2.0',method='notifications/initialized',params={}},{era='legacy',protocol_version='2025-11-25',method='notifications/initialized'}) local accepted,why=handle:await() check(not accepted and why:find('notifications/initialized',1,true),'initialized failure reaches handshake waiter') check(not tr.closed and #errors==0,'initialized failure is not promoted to transport/RPC failure') end do local fire_timers,fire_factory=timers(); local messages,errors={},{} local tr=assert(http.new({name='notify',url='https://example.test',headers={}}, {call_timeout_ms=999999}, {timer_factory=fire_factory,request_fn=function() return {cancel=function() end} end})) tr:set_callbacks(function(m) messages[#messages+1]=m end,function(e) errors[#errors+1]=e end) tr:send({jsonrpc='2.0',method='notifications/cancelled',params={requestId=1}}, {era='legacy',protocol_version='2025-11-25',method='notifications/cancelled'}) eq(fire_timers[1].ms,10000,'fire-and-forget timeout is fixed') fire_timers[1]:fire(); check(not tr.closed and #messages==0 and #errors==0,'failed notification is diagnostic-only') end do local calls=0; local tr=assert(http.new({name='init',url='https://example.test',headers={}}, {}, {request_fn=function() calls=calls+1; return {cancel=function() end} end})) local init=tr:send({jsonrpc='2.0',id=7,method='initialize',params={}},{era='legacy',protocol_version='2024-11-05',method='initialize'}) tr:cancel(7,init); eq(calls,1,'initialize cancellation never POSTs notifications/cancelled') end local at,_,am=injected({name='github',url='https://example.test',headers={Authorization='Bearer NEVER-SURFACE'}},function(o,cb) http_reply(o,cb,401,{['content-type']='text/event-stream'},'Bearer NEVER-SURFACE') end) at:send({jsonrpc='2.0',id=12,method='server/discover',params={}},{era='modern',protocol_version='2026-07-28',method='server/discover'}) local auth_text=am[1].error.message check(auth_text:find('github',1,true) and auth_text:find('auth = ""',1,true),'401 guidance') check(not auth_text:find('NEVER-SURFACE',1,true),'headers are not surfaced') local body_error_t,_,body_error_m=injected({name='redact',url='https://example.test',headers={['X-Key']='SECRET'}},function(o,cb) http_reply(o,cb,500,{['content-type']='text/plain'},'SECRET '..string.rep('x',1200)) end) body_error_t:send({jsonrpc='2.0',id=15,method='server/discover',params={}},{era='modern',protocol_version='2026-07-28',method='server/discover'}) check(body_error_m[1].error.message:find('500',1,true) and not body_error_m[1].error.message:find('SECRET',1,true),'HTTP status body is bounded and redacted') do local token_t,_,token_messages=injected({name='redact',url='https://example.test',headers={Authorization='Bearer ACCESS_TOKEN'}},function(o,cb) http_reply(o,cb,500,{['content-type']='text/plain'},string.rep('x',1020)..'ACCESS_TOKEN-tail') end) token_t:send({jsonrpc='2.0',id=16,method='tools/list',params={}},{era='modern',protocol_version='2026-07-28',method='tools/list'}) check(not token_messages[1].error.message:find('ACCESS_TOKEN',1,true) and not token_messages[1].error.message:find('ACCESS',1,true),'redaction precedes truncation and removes auth token part') end local json_error_t,_,json_error_m=injected({name='redact',url='https://example.test',headers={['X-Key']='SECRET'},},function(o,cb) http_reply(o,cb,400,{['content-type']='application/json'},json.encode({jsonrpc='2.0',id=18,error={code=-32600,message='SECRET bad header'}})) end) json_error_t:send({jsonrpc='2.0',id=18,method='server/discover',params={}},{era='modern',protocol_version='2026-07-28',method='server/discover'}) check(json_error_m[1].error.message:find('bad header',1,true) and not json_error_m[1].error.message:find('SECRET',1,true) and json_error_m[1].error.data.http_status==400,'HTTP JSON-RPC errors preserve message, context, status, and redaction') do local null_transport,_,null_messages=injected(remote,function(o,cb) http_reply(o,cb,400,{['content-type']='application/json'},json.encode({jsonrpc='2.0',id=json.null,error={code=-32022,message='unsupported',data={supported={'2024-11-05'}}}})) end) null_transport:send({jsonrpc='2.0',id=19,method='server/discover',params={}},{era='modern',protocol_version='2026-07-28',method='server/discover'}) local error_response=null_messages[1].error eq(error_response.code,-32022); eq(error_response.data.supported[1],'2024-11-05') check(not http.should_fallback(error_response),'null-id modern negotiation is not downgraded') end do local ok_transport,_,ok_messages=injected({name='redact',url='https://example.test',headers={['X-Key']='SECRET'}},function(o,cb) http_reply(o,cb,200,{['content-type']='application/json'},json.encode({jsonrpc='2.0',id=20,error={code=-32022,message='SECRET UnsupportedProtocolVersion',data={supported={'2025-11-25'}}}})) end) ok_transport:send({jsonrpc='2.0',id=20,method='server/discover',params={}},{era='modern',protocol_version='2026-07-28',method='server/discover'}) check(not ok_messages[1].error.message:find('SECRET',1,true),'successful HTTP JSON-RPC errors redact static headers') end local et,_,em=injected(remote,function(o,cb) http_reply(o,cb,200,{['content-type']='text/event-stream'},nil,{'data: {"jsonrpc":"2.0","method":"notifications/progress"}\n\n'}) end) et:send({jsonrpc='2.0',id=13,method='tools/call',params={name='hello'}},{era='modern',protocol_version='2026-07-28',method='tools/call',name='hello'}) eq(em[#em].id,13); check(em[#em].error.message:find('without a response',1,true),'SSE EOF is request-scoped') do local stream,_,stream_messages=injected(remote,function(o,cb) http_reply(o,cb,200,{['content-type']='text/event-stream'},nil,{'data: {"jsonrpc":"2.0","id":null,"error":{"code":-32600,"message":"server rejected"}}\n\n'}) end) stream:send({jsonrpc='2.0',id=23,method='tools/list',params={}},{era='modern',protocol_version='2026-07-28',method='tools/list'}) eq(stream_messages[1].id,23); check(stream_messages[1].error.message:find('server rejected',1,true),'null-id SSE error is correlated to its request') check(not stream_messages[1].error.message:find('without a response',1,true),'null-id SSE error is preserved') end local pending_handle; local ct=assert(http.new(remote,{}, {request_fn=function() pending_handle={cancelled=false}; function pending_handle:cancel() self.cancelled=true end; return pending_handle end})) local pending=ct:send({jsonrpc='2.0',id=14,method='tools/list',params={}},{era='modern',protocol_version='2026-07-28',method='tools/list'}) ct:cancel(14,pending); check(pending_handle.cancelled,'HTTP cancellation') do local handles={} local closing_http=assert(http.new(remote,{}, {request_fn=function() local h={cancelled=false}; function h:cancel() self.cancelled=true end; handles[#handles+1]=h; return h end})) closing_http:send({jsonrpc='2.0',id=21,method='tools/list',params={}},{era='modern',protocol_version='2026-07-28',method='tools/list'}) closing_http:send({jsonrpc='2.0',id=22,method='tools/list',params={}},{era='modern',protocol_version='2026-07-28',method='tools/list'}) closing_http:close(); check(handles[1].cancelled and handles[2].cancelled,'session close cancels every HTTP request') end end -- JSON-RPC: injected deadlines, cancellation, late responses, server requests. local ts,tf=timers(); local t=fake_transport(); local rpc=Rpc.new(t,{timer_factory=tf,timeout_ms=99}) local a=rpc:start('one',{}); local b=rpc:start('two',{}) t.message({jsonrpc='2.0',id=2,result={v=2}}); check(b.done and not a.done,'id routing') ts[1]:fire(); check(a.done and a.err:find('timed out',1,true),'injected timeout'); eq(t.cancels[1],1) t.message({jsonrpc='2.0',id=1,result={late=true}}); check(a.err~=nil,'late response ignored') local c=rpc:start('three',{}); c:cancel(); check(c.done,'cancel settles') t.message({jsonrpc='2.0',id='server-ping',method='ping'}); check(t.sent[#t.sent].msg.result~=nil,'ping response') t.message({jsonrpc='2.0',id='other',method='sampling/createMessage'}); eq(t.sent[#t.sent].msg.error.code,-32601) local d=rpc:start('four',{}); rpc:close(); check(d.done and t.closed,'close settles pending') local it,ift=timers(); local itx=fake_transport(); local irpc=Rpc.new(itx,{timer_factory=ift,timeout_ms=9}) local initialize=irpc:start('initialize',{}, {cancel_protocol=false}); it[1]:fire() check(initialize.done and #itx.cancels==0,'initialize timeout sends no cancellation notification'); irpc:close() -- Mapped results and capped/unsupported data. eq(results.decode64('aGVsbG8='),'hello'); eq(results.decode64('JQ=='),'%','percent replacement'); eq(results.decode64('AAAA'),'\0\0\0','zero-byte decode'); eq(results.decode64('+/8='),'\xfb\xff','high-byte decode'); check(not results.decode64('bad!'),'invalid base64') local large_image=assert(results.decode64(string.rep('QUJD',1747626))) eq(#large_image,5242878,'multi-megabyte base64 length'); eq(large_image:sub(1,3),'ABC'); eq(large_image:sub(-3),'ABC') local r=results.map('srv',{content={{type='text',text='{"a":1}'},{type='image',data='aGk=',mimeType='image/png'}, {type='audio',data='aGk=',mimeType='audio/wav'},{type='resource_link',uri='docs://a',name='A'}, {type='resource',resource={uri='docs://b',text='embedded'}}},structuredContent={a=1}}) eq(r.attachments[1].data,'hi'); check(r.text:find('server="srv"',1,true),'resource guidance') local _,n=r.text:gsub('"a":1',''); eq(n,1,'structured dedup') check(results.map('srv',{resultType='input_required'}).is_error,'input_required') check(results.map('srv',{isError=true,content={{type='text',text='oops'}}}).is_error,'tool error') check(results.map('srv',nil,{message='oops',code=-1}).text:find('(-1)',1,true),'rpc error') check(results.cap(string.rep('x',results.MAX_OUTPUT+1)):find('truncated',1,true),'output cap') -- Disk metadata: warm/cold/fingerprint/corrupt. No servers spawn on warm load. local cfg=servers.fs local meta={era='modern',version='2026-07-28',catalog={tools={{name='read_file',description='Read file contents',inputSchema={type='object',properties={path={type='string'}}}}},prompts={},resources={{name='guide',uri='docs://guide'}},templates={}},instructions=string.rep('x',5000)} local cleaned=cache.normalize_catalog({tools={{name='ok',title=json.null,annotations=json.null,inputSchema={}},{name='drop',description=7,inputSchema={}}},prompts={},resources={},templates={}}) eq(#cleaned.tools,1,'malformed catalog entry dropped'); eq(cleaned.tools[1].title,nil,'null catalog field absent'); eq(cleaned.tools[1].annotations,nil,'all null catalog fields absent') check(cache.save(cfg,meta,temp),'cache write'); check(cache.load(cfg,temp),'cache warm') write(temp..'/fs-extra-12345678.json','keep other server cache') check(read(cache.path(cfg,temp)):find('"prompts":%[%]'),'empty cache lists encode as arrays') local warm=Manager.new(settings,{fs=cfg},{cache_dir=temp,transport_factory=function() error('warm activation spawned') end}) eq(warm.states.fs.state,'idle'); warm:start_cold(); eq(warm.states.fs.state,'idle','warm starts nothing') local hits=assert(warm:search('file',{server='fs'})); eq(hits.hits[1].name,'read_file'); check(hits.hits[1].inputSchema,'schema returned'); check(hits.instructions:find('truncated',1,true),'instructions cap') eq(assert(warm:search('guide',{})).hits[1].kind,'resources') local other_cfg={name=cfg.name,fingerprint=config.hash('other')} check(cache.save(other_cfg,meta,temp),'cache save changed fingerprint') check(not read(cache.path(cfg,temp)),'old fingerprint pruned') eq(read(temp..'/fs-extra-12345678.json'),'keep other server cache','shared-prefix server cache preserved') write(cache.path(cfg,temp),'corrupt'); check(not cache.load(cfg,temp),'corrupt is cold') local cfg2={name=cfg.name,fingerprint='different'}; check(not cache.load(cfg2,temp),'fingerprint cold') warm:close() -- Startup deadlines/retry are injected, not tested by sleeping. local timers2,factory2=timers(); local count=0 local stalled=Manager.new(settings,{fs=cfg},{cache_dir=temp,timer_factory=factory2,transport_factory=function() count=count+1; return fake_transport() end}) local pending=stalled:start(stalled.states.fs); timers2[1]:fire() check(pending.done and stalled.states.fs.state=='failed','startup deadline') check(count==1,'deadline must not restart closed client') stalled:start(stalled.states.fs); check(count==2,'failed retried lazily'); stalled:close() local closing_ts,closing_tf=timers() local closing=Manager.new(settings,{fs=cfg},{cache_dir=temp,timer_factory=closing_tf,transport_factory=function() return fake_transport() end}) local closing_ready=closing:start(closing.states.fs); local resumed=false local waiter=coroutine.create(function() closing_ready:await(); resumed=true end) assert(coroutine.resume(waiter)); eq(coroutine.status(waiter),'suspended') closing:close() check(not resumed and coroutine.status(waiter)=='suspended','session_end abandons waiters without resuming them'); check(closing_ready.done,'abandoned startup future settled') -- Era selection and silent-probe fallback with scripted transports/injected -- timers. No elapsed-time sleeps are used to manufacture timeout behavior. local Client=require('panto_mcp.client') local function scripted(respond) local tr=fake_transport() local send=tr.send function tr:send(msg,opts) local h=send(self,msg,opts) if msg.id then local value,err=respond(msg,opts) if value~=nil or err~=nil then self.message({jsonrpc='2.0',id=msg.id,result=value,error=err}) end end return h end return tr end do local t,tf=timers(); local tr=fake_transport(); local send=tr.send local initializes,tool_calls=0,0; local initialized=false function tr:send(msg,opts) local h=send(self,msg,opts) if msg.method=='initialize' then initializes=initializes+1 elseif msg.method=='notifications/initialized' then initialized=true elseif msg.method=='tools/call' then tool_calls=tool_calls+1 if initialized then self.message({jsonrpc='2.0',id=msg.id,result={ok=true}}) end end return h end local client=Client.new({name='remote',url='https://example.test',transport='http'},settings, {timer_factory=tf,transport_factory=function() return tr end}) assert(client:open()); client.era='legacy'; client.version='2025-11-25'; tr.era='legacy'; tr.protocol_version='2025-11-25'; tr.session_generation=1 local r1,e1,r2,e2 async.run(function() r1,e1=client:request('tools/call',{name='hello',arguments={}}) end,function(err) error(err) end) async.run(function() r2,e2=client:request('tools/call',{name='hello',arguments={}}) end,function(err) error(err) end) eq(tool_calls,2,'parallel stale requests in flight') tr.message({jsonrpc='2.0',id=1,error={code=-32000,message='session expired',data={session_expired=true,session_generation=1}}}) tr.message({jsonrpc='2.0',id=2,error={code=-32000,message='session expired',data={session_expired=true,session_generation=1}}}) eq(initializes,1,'parallel session expiry shares one re-init') tr.message({jsonrpc='2.0',id=3,result={protocolVersion='2024-11-05',capabilities={}}}) check(r1 and r1.ok and r2 and r2.ok and not e1 and not e2,'both expired calls retry once') eq(initializes,1); eq(tool_calls,4,'one retry per original request'); eq(tr.protocol_version,'2024-11-05') local initialized_version for _,entry in ipairs(tr.sent) do if entry.msg.method=='notifications/initialized' then initialized_version=entry.opts.protocol_version end end eq(initialized_version,'2024-11-05','2024 counter-offer retained during re-init'); client:close() end local remote_http={name='http',url='https://example.test/mcp',transport='http',headers={},args={},env={}} do local function stream_client(expose,era) local streams=0 local client=Client.new({name='http',url='https://example.test/mcp',transport='http',expose=expose,headers={},args={},env={}},settings, {transport_factory=function() local transport=scripted(function(message) if message.method=='initialize' then return {protocolVersion='2025-11-25',capabilities={tools={listChanged=true}}} end if message.method=='server/discover' then return {capabilities={tools={listChanged=true}}} end if message.method=='tools/list' then return {tools={}} end end) function transport:open_notification_stream() streams=streams+1; return true end return transport end}) local cached=era=='legacy' and {era='legacy',version='2025-11-25'} or {era='modern',version='2026-07-28'} check(client:connect(cached),'cached client connects for notification-stream gate') client:close() return streams end eq(stream_client('eager','legacy'),1,'only eager 2025-11-25 HTTP clients open GET stream') eq(stream_client('search','legacy'),0,'search HTTP client does not open GET stream') eq(stream_client('eager','modern'),0,'modern HTTP client does not open legacy GET stream') end do local calls,reported={},nil; local timer_list,timer_factory=timers() local client=Client.new(remote_http,settings,{timer_factory=timer_factory,on_error=function(err) reported=err end, transport_factory=function(cfg,client_settings) return assert(require('panto_mcp.http').new(cfg,client_settings,{timer_factory=timer_factory,request_fn=function(o,cb) calls[#calls+1]=o local handle={cancel=function() end} if o.method=='DELETE' then return handle end local req=json.decode(o.body); local status=req.method=='initialize' and 200 or 500 local headers=req.method=='initialize' and {['content-type']='application/json',['mcp-session-id']='half-session'} or {['content-type']='text/plain'} local body=req.method=='initialize' and json.encode({jsonrpc='2.0',id=req.id,result={protocolVersion='2025-11-25',capabilities={}}}) or 'initialized failed' o.on_head({status=status,headers=headers}); o.on_data(body); cb({status=status,headers=headers},nil) return handle end})) end}) assert(client:open()); client.era='legacy'; client.version='2025-11-25' local ready,why async.run(function() ready,why=client:reinitialize_legacy() end,function(err) error(err) end) check(not ready and why and client.rpc.closed and reported,'failed re-init fails RPC/client for next-use reconnect') eq(calls[3].method,'DELETE'); eq(calls[3].headers['Mcp-Session-Id'],'half-session','half-initialized session is deleted') client:close() end do local annotated_transport; local list_calls,call_calls,call_headers=0,0,{} local annotated=Client.new(remote_http,settings,{transport_factory=function() annotated_transport=scripted(function(msg,opts) if msg.method=='server/discover' then return {capabilities={tools={}}} end if msg.method=='tools/list' then list_calls=list_calls+1 local header_name=list_calls==1 and 'Region' or 'Locale' return {tools={ {name='hello',inputSchema={type='object',properties={nested={type='object',properties={region={type='string',['x-mcp-header']=header_name}}}}}}, {name='bad',inputSchema={type='object',properties={x={type='number',['x-mcp-header']='Bad'}}}} }} end if msg.method=='tools/call' then call_calls=call_calls+1; call_headers[call_calls]=opts.param_headers[1].name if call_calls==1 then return nil,{code=-32020,message='HeaderMismatch'} end return {content={}} end end) return annotated_transport end}) check(annotated:connect(),'HTTP catalog with annotations connects') eq(#annotated.catalog.tools,1,'invalid annotated tool excluded'); eq(annotated.catalog.tools[1].name,'hello') annotated:call('hello',{nested={region='us-west1'}}) eq(list_calls,2,'HeaderMismatch re-lists tool schemas once'); eq(call_calls,2,'HeaderMismatch retries once') eq(call_headers[1],'Region'); eq(call_headers[2],'Locale','retry uses updated Mcp-Param annotation') annotated:close() end do for _,scenario in ipairs({'removed','new-schema'}) do local call_count,list_count=0,0 local client=Client.new(remote_http,settings,{transport_factory=function() return scripted(function(msg) if msg.method=='server/discover' then return {capabilities={tools={}}} end if msg.method=='tools/list' then list_count=list_count+1 if list_count==2 and scenario=='removed' then return {tools={}} end local kind=list_count==2 and scenario=='new-schema' and 'integer' or 'string' return {tools={{name='hello',inputSchema={type='object',properties={region={type=kind,['x-mcp-header']='Region'}},required={'region'}}}}} end if msg.method=='tools/call' then call_count=call_count+1 return nil,{code=call_count==1 and -32020 or -32602,message='HeaderMismatch'} end end) end}) check(client:connect(),'HeaderMismatch retry precondition') local _,err=client:call('hello',{region='us-west1'}) if scenario=='removed' then eq(err.code,-32020,'removed tool returns original HeaderMismatch') else eq(err.code,-32602,'updated schema revalidates old input') end eq(call_count,1,'removed or incompatible tool is not retried') client:close() end end do local transport local refresh_client=Client.new(remote_http,settings,{transport_factory=function() transport=scripted(function(msg) if msg.method=='tools/list' then return {tools={{name='new',inputSchema={type='object',properties={x={type='string',['x-mcp-header']='X'}}}}}} end if msg.method=='prompts/list' then return nil,{code=-32000,message='list failed'} end end) return transport end}) assert(refresh_client:open()); refresh_client.era='modern'; refresh_client.version='2026-07-28' refresh_client.capabilities={tools={},prompts={}} local old_catalog=json.array({{name='old'}}); local old_headers={old={{name='Old',path={'old'},type='string'}}} refresh_client.catalog.tools=old_catalog; refresh_client.tool_headers=old_headers local refreshed=refresh_client:refresh() check(not refreshed and refresh_client.catalog.tools==old_catalog and refresh_client.tool_headers==old_headers, 'failed catalog refresh retains catalog and MCP parameter headers atomically') refresh_client:close() end local probe_methods={} local fallback_http=Client.new(remote_http,settings,{transport_factory=function() return scripted(function(msg) probe_methods[#probe_methods+1]=msg.method if msg.method=='server/discover' then return nil,{code=-32000,message='empty HTTP 400',data={http_status=400,transport_fallback=true}} end if msg.method=='initialize' then return {protocolVersion='2025-11-25',capabilities={}} end if msg.method=='tools/list' then return {tools={}} end end) end}) check(fallback_http:connect(),'HTTP empty 400 falls back to legacy'); eq(fallback_http.era,'legacy'); eq(probe_methods[1],'server/discover'); eq(probe_methods[2],'initialize'); fallback_http:close() local mismatch_methods={} local mismatch_http=Client.new(remote_http,settings,{transport_factory=function() return scripted(function(msg) mismatch_methods[#mismatch_methods+1]=msg.method if msg.method=='server/discover' then return nil,{code=-32020,message='HeaderMismatch'} end end) end}) local mismatch_ok,mismatch_error=mismatch_http:connect() check(not mismatch_ok and mismatch_error:find('HeaderMismatch',1,true),'HTTP modern JSON-RPC error is not downgraded') eq(#mismatch_methods,1,'recognized modern error stops fallback'); mismatch_http:close() local connection_opens,connection_methods=0,{} local connection_client=Client.new(remote_http,settings,{transport_factory=function() connection_opens=connection_opens+1 return scripted(function(msg) connection_methods[#connection_methods+1]=msg.method return nil,{code=-32000,message='connect failed',data={transport_error='connection'}} end) end}) local connection_ok=connection_client:connect() check(not connection_ok,'connection failures stay errors'); eq(connection_opens,1); eq(#connection_methods,1,'connection failure does not probe legacy') connection_client:close() do local timeout_timers,timeout_factory=timers(); local timeout_client=Client.new(remote_http,settings, {timer_factory=timeout_factory,transport_factory=function() return fake_transport() end}) assert(timeout_client:open()); timeout_client.era='modern'; timeout_client.version='2026-07-28' local timeout_error async.run(function() local _,err=timeout_client:request('tools/call',{name='hello',arguments={}}); timeout_error=err end) timeout_timers[1]:fire() check(timeout_error and timeout_error:find('http tools/call: request timed out',1,true),'HTTP RPC timeout names server and method') timeout_client:close() end local cached_opens=0 local cached_connection=Client.new(remote_http,settings,{transport_factory=function() cached_opens=cached_opens+1 return scripted(function() return nil,{code=-32000,message='TLS handshake failed',data={transport_error='connection'}} end) end}) local cached_ok=cached_connection:connect({era='modern',version='2026-07-28'}) check(not cached_ok,'cached connection failure stays an error'); eq(cached_opens,1,'cached connection failure is not re-probed') cached_connection:close() local retry_opens=0 local retried=Manager.new(settings,{fs=cfg},{cache_dir=temp,transport_factory=function() retry_opens=retry_opens+1 return scripted(function(msg) if msg.method=='server/discover' then return {capabilities={tools={}}} end if msg.method=='tools/list' then return {tools={}} end end) end}) retried.states.fs.metadata=meta; retried.states.fs.state='failed' local retried_search=assert(retried:search(nil,{server='fs'})) eq(retry_opens,1,'search lazily retries failed servers'); eq(retried.states.fs.state,'ready') check(retried_search.servers[1].stderr==nil,'search status strips stderr'); retried:close() local chosen local selection=Client.new(remote_http,settings,{transport_factory=function() return scripted(function(msg,opts) if msg.method=='server/discover' then eq(opts.protocol_version,'2026-07-28','transport version seam') return nil,{code=-32022,message='unsupported',data={supported={'2024-11-05'}}} end if msg.method=='initialize' then chosen=msg.params.protocolVersion; return {protocolVersion=chosen,capabilities={}} end end) end}) check(selection:connect(),'unsupported-version selection'); eq(chosen,'2024-11-05'); selection:close() local counteroffer_calls={} local counteroffer_failure=Client.new(remote_http,settings,{transport_factory=function() return scripted(function(msg) counteroffer_calls[#counteroffer_calls+1]=msg.method if msg.method=='server/discover' then return nil,{code=-32022,message='unsupported',data={supported={'2025-11-25'}}} end if msg.method=='initialize' then return nil,{code=-32600,message='legacy initialize rejected'} end end) end}) local counteroffer_ok,counteroffer_error=counteroffer_failure:connect() check(not counteroffer_ok and counteroffer_error:find('legacy initialize rejected',1,true),'counter-offer failure reports legacy error') eq(table.concat(counteroffer_calls,','),'server/discover,initialize','counter-offer is tried once'); counteroffer_failure:close() local opens=0 local reprobe=Client.new(cfg,settings,{transport_factory=function() opens=opens+1 return scripted(function(msg) if msg.method=='initialize' then return nil,{code=-32601,message='modern only'} end return {capabilities={}} end) end}) check(reprobe:connect({era='legacy',version='2025-11-25'}),'cached era re-probed'); eq(opens,2); eq(reprobe.era,'modern'); reprobe:close() local delayed_ts,delayed_tf=timers(); local delayed_opens,initialize_count,offered=0,0,nil; local delayed_done local delayed=Client.new(cfg,settings,{timer_factory=delayed_tf,transport_factory=function() delayed_opens=delayed_opens+1 local tr=fake_transport(); local send=tr.send function tr:send(msg,opts) local h=send(self,msg,opts) if msg.method=='initialize' then initialize_count=initialize_count+1; offered=msg.params.protocolVersion delayed_tf(2000,function() self.message({jsonrpc='2.0',id=msg.id,result={protocolVersion='2025-11-25',capabilities={}}}) end) end return h end return tr end}) async.run(function() delayed_done=assert(delayed:connect({era='legacy',version='2025-03-26'})) end,function(err) error(err) end) eq(delayed_ts[1].ms,settings.startup_timeout_ms,'cached handshake gets full startup budget') eq(delayed_ts[2].ms,2000,'injectable slow legacy server start') eq(offered,'2025-11-25','cached legacy upgrades its offered version') delayed_ts[2]:fire() check(delayed_done and delayed_opens==1 and initialize_count==1,'slow cached legacy starts one process and initializes once'); delayed:close() local changed_lists,change_transport=0,nil local changed_client=Client.new(cfg,settings,{transport_factory=function() change_transport=scripted(function(msg) if msg.method=='server/discover' then return {capabilities={tools={}}} end if msg.method=='tools/list' then changed_lists=changed_lists+1 if changed_lists==1 then change_transport.message({jsonrpc='2.0',method='notifications/tools/list_changed'}) end return {tools={}} end end) return change_transport end}) check(changed_client:connect(),'connect survives list_changed during initial refresh') eq(changed_lists,2,'connect replays list_changed'); changed_client:close() local silent_ts,silent_tf=timers(); local silent_opens=0; local silent_done local silent=Client.new(cfg,settings,{timer_factory=silent_tf,transport_factory=function() silent_opens=silent_opens+1 return scripted(function(msg) if msg.method=='initialize' then return {protocolVersion='2025-11-25',capabilities={}} end end) end}) async.run(function() silent_done=assert(silent:connect()) end,function(err) error(err) end) eq(silent_ts[1].ms,1500,'short modern probe'); silent_ts[1]:fire() check(silent_done and silent.era=='legacy' and silent_opens==2,'silent legacy probe falls back fresh'); silent:close() local slow_ts,slow_tf=timers(); local slow_opens=0; local slow_done local slow_modern=Client.new(cfg,settings,{timer_factory=slow_tf,transport_factory=function() slow_opens=slow_opens+1 local attempt=slow_opens return scripted(function(msg) if attempt==1 then return nil end if msg.method=='initialize' then return nil,{code=-32601,message='modern only'} end return {capabilities={}} end) end}) async.run(function() slow_done=assert(slow_modern:connect()) end,function(err) error(err) end) slow_ts[1]:fire() check(slow_done and slow_modern.era=='modern' and slow_opens==2,'slow modern-only startup recovers after legacy rejection') slow_modern:close() -- Activation from a warm cache: checkout entry/namespace registration, stable -- config-only guidance, zero process starts, and nonblocking command output. local saved_panto=package.loaded.panto; local saved_std=package.loaded._std local old_directory=cache.directory; cache.directory=function() return temp end local activation_raw={servers={fs={command='echo',expose='eager'},alpha={command='echo'},off={enabled=false}}} local _,activation_servers=config.parse(activation_raw,{project_root=here}) local activation_meta={era='modern',version='2026-07-28',capabilities={tools={},prompts={},resources={}},catalog={ tools=meta.catalog.tools,prompts={{name='greet',title='Greet',arguments={{name='name',required=true}}}}, resources=meta.catalog.resources,templates=meta.catalog.templates}} check(cache.save(activation_servers.fs,activation_meta,temp),'activation warm cache') check(cache.save(activation_servers.alpha,activation_meta,temp),'second activation warm cache') local registered,events,commands,namespaces={},{},{},{} local guidance package.loaded.panto={ext={json=json,config={mcp=activation_raw},dirs={project_root=here}, register_tool=function(tool) registered[#registered+1]=tool end, register_command=function(command) commands[command.name]=command end, on=function(name,fn) events[name]=fn end, style=function() return {dim='',reset=''} end, agent={add_system_message=function(_,text) guidance=text end}}} package.loaded._std={lua_namespace=function(name,factory) namespaces[name]=factory end} dofile(here .. '/init.lua').activate() eq(#registered,3,'older-core eager fallback exposes search tools'); check(namespaces.mcp,'namespace installed') check(commands['mcp:fs:greet'],'warm prompt command registered on older core') check(commands['mcp:fs:greet'].handler(''):find('missing required arguments: name',1,true),'warm prompt validates args without starting server') check(commands.mcp.handler(''):find('idle',1,true),'warm activation stays idle') do local header={render=function(_,width) eq(width,80,'inner header width'); return {'panto',' skills: example',''} end} events.render_header({get_component=function() return header end,set_component=function(_,component) header=component end}) eq(table.concat(header:render(80),'\n'),'panto\n skills: example\n mcp: alpha, fs\n', 'header adds sorted enabled server names before trailing blank') end events.session_ready(); check(guidance:find('fs: stdio, search',1,true),'stable config guidance after old-core fallback') check(commands.mcp.handler(''):find('eager not yet supported',1,true),'old-core eager fallback warning') events.session_end() package.loaded.panto=saved_panto; package.loaded._std=saved_std; cache.directory=old_directory -- The live core path exposes warm eager tools and prompts from cache without a process start. do cache.directory=function() return temp end local raw={servers={fast={command='echo',expose='eager'}}} local _,ss=config.parse(raw,{project_root=here}) local warm_meta={era='modern',version='2026-07-28',capabilities={tools={listChanged=true},prompts={},resources={}},catalog={ tools={{name='read_file',description='Read cached',inputSchema={type='object',properties={path={type='string'}}}}}, prompts={{name='greet',title='Greet',arguments={{name='name',required=true}}}}, resources={{name='guide',uri='docs://guide'}},templates={}}} check(cache.save(ss.fast,warm_meta,temp),'eager cache write') local tools_now,commands_now,events_now={},{},{} local ext={json=json,config={mcp=raw},dirs={project_root=here}, register_tool=function(spec) tools_now[spec.name]=spec; return true end, unregister_tool=function(name) tools_now[name]=nil; return true end, register_command=function(spec) commands_now[spec.name]=spec; return true end, unregister_command=function(name) commands_now[name]=nil; return true end, on=function(name,fn) events_now[name]=fn end, agent={add_system_message=function() end}} package.loaded.panto={ext=ext}; package.loaded._std={lua_namespace=function() end} dofile(here .. '/init.lua').activate() check(tools_now[config.tool_name('fast','read_file')],'warm eager tool registered at activation') check(tools_now['mcp.read_resource'],'eager resource tool registered from warm capability') eq(tools_now['mcp.search'],nil,'eager-only mode omits search tools') check(commands_now['mcp:fast:greet'],'warm prompt command registered') check(commands_now.mcp~=nil,'status command remains available') check(commands_now['mcp:fast:greet'].description:find('name',1,true),'prompt description includes argument names') check(commands_now.mcp.handler(''):find('idle',1,true),'warm eager activation spawns nothing') events_now.session_end() package.loaded.panto=saved_panto; package.loaded._std=saved_std; cache.directory=old_directory end -- Reconcile connect snapshots: new/removed/changed eager tools and prompt commands. do local _,ss=config.parse({servers={fast={command='echo',expose='eager',enabled_tools={'*'},disabled_tools={'disabled*'}}}},{project_root=here}) local calls,tool_specs,command_specs,removed_tools,removed_commands={},{},{},{},{} local fake_manager={states={fast={cfg=ss.fast}}} function fake_manager:call(server,name,input) calls[#calls+1]={server=server,name=name,input=input} return {is_error=false,text='called '..name,attachments={}} end local fake_ext={ register_tool=function(spec) tool_specs[spec.name]=spec; return true end, unregister_tool=function(name) removed_tools[#removed_tools+1]=name; tool_specs[name]=nil; return true end, register_command=function(spec) command_specs[spec.name]=spec; return true end, unregister_command=function(name) removed_commands[#removed_commands+1]=name; command_specs[name]=nil; return true end, } local eager=require('panto_mcp.eager').new(fake_ext,fake_manager) local command_set=prompts.commands(fake_ext,fake_manager,{busy=false},true) local function def(name,description,kind) return {name=name,description=description,inputSchema={type='object',properties={value={type=kind or 'string'}}}} end local initial={catalog={tools={def('a.b','old'),def('a_b','collision'),def('remove_me','remove'),def('change_me','change'),def('disabled_tool','disabled')}, prompts={{name='first',description='First',arguments={{name='q',required=true}}}},resources={},templates={}}} fake_manager.states.fast.metadata=initial eager:reconcile(); command_set.reconcile('fast',initial,true) local dotted=config.tool_name('fast','a.b'); local underscored=config.tool_name('fast','a_b') check(dotted~=underscored,'eager sanitizer collision disambiguated') check(tool_specs[dotted] and tool_specs[underscored],'initial eager catalog registered') eq(tool_specs[config.tool_name('fast','disabled_tool')],nil,'disabled eager tool excluded') eq(tool_specs[dotted].handler({value='x'}).text,'called a.b','eager handler maps sanitized name back to MCP name') eq(calls[1].server,'fast'); eq(calls[1].name,'a.b') local changed={catalog={tools={def('a.b','updated','integer'),def('brand_new','new')}, prompts={{name='second',title='Second',arguments={{name='text',required=true}}}},resources={},templates={}}} fake_manager.states.fast.metadata=changed eager:reconcile(); command_set.reconcile('fast',changed,false) check(tool_specs[dotted] and tool_specs[dotted].description=='updated','changed eager definition re-registered') eq(tool_specs[dotted].schema.properties.value.type,'integer','changed eager schema replaced') check(tool_specs[config.tool_name('fast','brand_new')],'new eager tool registered') eq(tool_specs[underscored],nil,'removed eager tool unregistered') check(#removed_tools>=4,'removed and changed eager registrations unregistered') eq(command_specs['mcp:fast:first'],nil,'removed prompt command unregistered') check(command_specs['mcp:fast:second'],'new prompt command registered') check(#removed_commands==1,'removed prompt registration reconciled') end do local warning_command,render_header package.loaded.panto={ext={json=json,config={mcp={servers={bad={url='file://invalid'}}}},dirs={}, register_command=function(c) warning_command=c end, on=function(name,fn) if name=='render_header' then render_header=fn end end, style=function() return {dim='',reset=''} end}} dofile(here .. '/init.lua').activate() check(warning_command and warning_command.handler(''):find('Config warning',1,true),'invalid-only config still exposes TUI warnings') local header={render=function() return {'panto'} end} render_header({get_component=function() return header end,set_component=function(_,component) header=component end}) eq(table.concat(header:render(80),'\n'),'panto\n mcp: (none)','header excludes invalid servers') package.loaded.panto=saved_panto end local gate=async.future(); local command require('panto_mcp.tools').register({register_tool=function() end,register_command=function(c) command=c end, mount=function() error('refresh must not mount a component') end}, {servers=function() return {} end,refresh=function() return gate:await() end}) check(command.handler('refresh'):find('started',1,true),'refresh returns started while async work is parked') gate:resolve(true) local warning_only require('panto_mcp.tools').register_status({register_command=function(c) warning_only=c end},{servers=function() return {} end},{'bad server'}) check(warning_only.handler(''):find('Config warning: bad server',1,true),'status displays config warnings') do local tools=require('panto_mcp.tools') local status=tools.status({servers=function() return {{name='remote',state='idle',transport='http',tools=0,prompts=0,resources=0,templates=0,stderr=''}} end},{}) check(status:find('HTTP URL',1,true),'status identifies URL transport') local ready,system_hint tools.hint({on=function(name,fn) ready=fn end,agent={add_system_message=function(_,text) system_hint=text end}}, {remote={transport='http',expose='search',url='https://secret.example'}}) ready(); check(system_hint:find('remote: HTTP URL, search',1,true),'config-only URL hint') check(not system_hint:find('secret.example',1,true),'system hint omits remote URL') end -- Real subprocess integration. A bounded watchdog protects the harness; no -- timeout behavior is inferred from elapsed sleeps. local integration_error local done=false local managers={} local watchdog=uv.new_timer(); watchdog:start(30000,0,function() integration_error='integration watchdog expired'; for _,m in ipairs(managers) do m:close() end close(watchdog) end) async.run(function() for _,mode in ipairs({'modern','banner','legacy','legacy-close','tools-only','missing-templates','env-check'}) do local child_env=mode=='env-check' and {PANTO_MCP_TEST_CHILD_ENV='child'} or nil local _,ss=config.parse({servers={fake={command=uv.exepath(),args={'lua',here .. '/_selfcheck.lua','--fake',mode},env=child_env}}},{project_root=here}) local m=Manager.new(settings,ss,{cache_dir=temp}); managers[#managers+1]=m local api=namespace.factory(m,{}) local one,two=api.start('fake','echo',{message='first'}),api.start('fake','echo',{message='second'}) local first=assert(one:await()) check(not first.is_error,first.text .. '\n' .. (m.states.fake.client.transport.stderr_tail or '')) eq(first.text,'first',mode .. ' first call'); eq(assert(two:await()).text,'second',mode .. ' concurrent call') eq(m.states.fake.state,'ready'); eq(#m.states.fake.metadata.catalog.tools,2,'pagination') local searched=assert(m:search(nil,{server='fake'})) check(searched.servers[1].stderr==nil,'search omits stderr'); check(m:servers()[1].stderr~=nil,'servers retains stderr') eq(m.states.fake.metadata.era,(mode=='modern' or mode=='banner' or mode=='env-check') and 'modern' or 'legacy','era') check(m:call('fake','echo',{}).is_error,'live schema validation') check(m:call('fake','ecoh',{message='x'}).text:find('echo',1,true),'closest exact name') if mode~='tools-only' then check(m:read_resource('fake','docs://guide').text:find('resource body',1,true),'resource read') eq(#assert(api.prompts('fake')),1); eq(assert(api.prompt('fake','greet',{name='A'}))[1].role,'user') else eq(#m.states.fake.metadata.catalog.resources,0,'unadvertised list skipped') end if mode=='missing-templates' then eq(#m.states.fake.metadata.catalog.templates,0,'unimplemented list is empty') end if mode=='modern' then local changed=async.future() m.opts.on_catalog=function(_,data) if #data.catalog.tools==3 then changed:resolve(true) end end eq(m:call('fake','echo',{message='change'}).text,'change') check(changed:await(),'list_changed relisted') eq(#assert(cache.load(ss.fake,temp)).catalog.tools,3,'list_changed rewrote cache') local _,eager_servers=config.parse({servers={fake={command=uv.exepath(),args={'lua',here .. '/_selfcheck.lua','--fake','modern'},expose='eager'}}},{project_root=here}) local dynamic_tools,dynamic_commands={},{} local registration_ext={ register_tool=function(spec) dynamic_tools[spec.name]=spec; return true end, unregister_tool=function(name) dynamic_tools[name]=nil; return true end, register_command=function(spec) dynamic_commands[spec.name]=spec; return true end, unregister_command=function(name) dynamic_commands[name]=nil; return true end, } local eager_manager local eager_registration local prompt_registration local catalog_changed=async.future(); local catalog_removed=async.future() eager_manager=Manager.new(settings,eager_servers,{cache_dir=temp,on_catalog=function(server,data) eager_registration:reconcile() prompt_registration.reconcile(server,data,false) if dynamic_tools[config.tool_name('fake','new_tool')] and dynamic_commands['mcp:fake:wave'] then catalog_changed:resolve(true) end if next(dynamic_tools)==nil and dynamic_commands['mcp:fake:wave']==nil then catalog_removed:resolve(true) end end}) eager_registration=require('panto_mcp.eager').new(registration_ext,eager_manager) prompt_registration=prompts.commands(registration_ext,eager_manager,{busy=false},true) eq(eager_manager:call('fake','echo',{message='change'}).text,'change','eager manager starts cold server lazily') check(catalog_changed:await(),'connect/list_changed adds eager tool and reconciles prompt') check(dynamic_tools[config.tool_name('fake','echo')] and dynamic_tools[config.tool_name('fake','new_tool')],'new eager catalog registered') eq(dynamic_commands['mcp:fake:greet'],nil,'removed prompt command reconciled on connect') check(dynamic_commands['mcp:fake:wave'],'new prompt command reconciled on connect') eager_manager:call('fake','echo',{message='remove'}) check(catalog_removed:await(),'second list_changed removes live eager registrations') eager_manager:close() end m:close() end local _,noisy_config=config.parse({servers={noisy={command=uv.exepath(),args={'lua',here .. '/_selfcheck.lua','--fake','noisy-exit'}}}},{project_root=here}) local noisy=Manager.new(settings,noisy_config,{cache_dir=temp}); managers[#managers+1]=noisy local noisy_result=noisy:call('noisy','echo',{}) check(noisy_result.is_error and noisy_result.text:find('diagnostic-tail-from-child',1,true),'transport errors include bounded stderr tail') done=true; close(watchdog) end,function(err) integration_error=err; for _,m in ipairs(managers) do m:close() end; close(watchdog) end) uv.run() assert(not integration_error,integration_error); check(done,'integration finished') -- A server that ignores stdin EOF must still reach TERM/KILL escalation on -- ordinary nonblocking transport.close(), not just on parent death. local ignored=assert(stdio.new({command=uv.exepath(),args={'lua',here .. '/_selfcheck.lua','--fake','ignore'},env={}})) local ignore_poll,ignore_bound=uv.new_timer(),uv.new_timer() local ignore_pid,ignore_gone,ignore_error ignore_poll:start(0,20,function() if ignored.server_pid and not ignore_pid then ignore_pid=ignored.server_pid; ignored:close() end if ignore_pid and not uv.kill(-ignore_pid,0) then ignore_gone=true; close(ignore_poll); close(ignore_bound) end end) ignore_bound:start(8000,0,function() ignore_error='EOF-ignoring server exceeded bounded exit wait' if ignore_pid then uv.kill(-ignore_pid,'sigkill') end ignored:close(); close(ignore_poll); close(ignore_bound) end) uv.run(); assert(not ignore_error,ignore_error); check(ignore_gone,'EOF-ignoring server reaped after close') local orphaned=assert(stdio.new({command=uv.exepath(),args={'lua',here .. '/_selfcheck.lua','--fake','ignore'},env={}})) local orphan_poll,orphan_bound=uv.new_timer(),uv.new_timer() local orphan_pid,supervisor_killed,orphan_gone,orphan_error,supervisor_reason=nil,false,false,nil,nil orphaned:set_callbacks(function() end,function(err) supervisor_reason=err end) orphan_poll:start(0,20,function() if orphaned.server_pid and not supervisor_killed then orphan_pid=orphaned.server_pid; supervisor_killed=true; orphaned.proc:kill('sigkill') end if orphan_pid and not uv.kill(-orphan_pid,0) then orphan_gone=true; close(orphan_poll); close(orphan_bound) end end) orphan_bound:start(8000,0,function() orphan_error='orphan survived supervisor death' if orphan_pid then uv.kill(-orphan_pid,'sigkill') end close(orphan_poll); close(orphan_bound) end) uv.run(); assert(not orphan_error,orphan_error); check(orphan_gone and supervisor_reason and supervisor_reason:find('supervisor exited',1,true),'parent TERM/KILL fallback reaps group after supervisor death') local eof=assert(stdio.new({command=uv.exepath(),args={'lua',here .. '/_selfcheck.lua','--fake','exit-on-eof'},env={}})) local eof_done,eof_alive,eof_closed,eof_error,eof_reason=false,false,false,nil,nil local eof_poll,eof_bound=uv.new_timer(),uv.new_timer() eof:set_callbacks(function() end,function(err) eof_reason=err; eof_alive=uv.kill(eof.supervisor_pid,0)~=nil; eof_done=true end) eof_poll:start(0,10,function() if eof.server_pid and not eof_closed then eof_closed=true; async.close(eof.stdin) end if eof_done then close(eof_poll); close(eof_bound) end end) eof_bound:start(5000,0,function() eof_error='server stdout EOF delayed until supervisor exit'; close(eof_poll); close(eof_bound); eof:close() end) uv.run(); assert(not eof_error,eof_error); check(eof_done and eof_alive and eof_reason:find('stdout closed',1,true),'supervisor drops fd 0/1 before grace period') -- S1: parent SIGKILL must close the fourth-fd lifeline and reap the whole -- TERM-resistant group, including a grandchild shell/sleep tree. local parent_out=uv.new_pipe(false); local parent_err=uv.new_pipe(false) local parent,server_pid,orphan_error,parent_exited,group_gone local poll=uv.new_timer(); local bound=uv.new_timer() local function cleanup() close(poll); close(bound); close(parent_out); close(parent_err); close(parent) end parent=assert(uv.spawn(uv.exepath(),{args={'lua',here .. '/_selfcheck.lua','--parent'},stdio={nil,parent_out,parent_err},detached=true},function() parent_exited=true; close(parent) end)) local output='' parent_out:read_start(function(e,data) if e then orphan_error=e; cleanup(); return end if data then output=output .. data local pid=tonumber(output:match('SERVER=(%d+)\n')) if pid and not server_pid then server_pid=pid; assert(parent:kill('sigkill')) end end end) parent_err:read_start(function(e,data) if e then orphan_error=e end; if data then output=output .. data end end) poll:start(0,25,function() if server_pid and not uv.kill(-server_pid,0) then group_gone=true; cleanup() end end) bound:start(8000,0,function() orphan_error='orphan check exceeded bounded exit wait' if server_pid then uv.kill(-server_pid,'sigkill') end pcall(parent.kill,parent,'sigkill'); cleanup() end) uv.run() assert(not orphan_error,orphan_error); check(server_pid and parent_exited and group_gone,'SIGKILL parent tears down server group') -- panto lua has no active HTTP service. A scripted provider keeps this token-free. -- Set PANTO_MCP_HTTP_E2E=1; PANTO_MCP_PANTO selects the nested test binary. local function http_e2e(mode) local http_panto=uv.fs_realpath(os.getenv('PANTO_MCP_PANTO') or '/tmp/panto-mcp-work/panto-full') assert(http_panto,'HTTP E2E requires /tmp/panto-mcp-work/panto-full (or PANTO_MCP_PANTO)') if http_panto then local rig=temp..'/http-rig-'..mode; local extdir=rig..'/fixture'; local data_home=temp..'/http-data-'..mode assert(uv.fs_mkdir(rig,448)); assert(uv.fs_mkdir(extdir,448)); assert(uv.fs_mkdir(data_home,448)) local provider=[[local panto=require('panto') local json=panto.ext.json local function last_results(request) local out={} for _,m in ipairs(request.messages) do for _,b in ipairs(m.blocks or {}) do if b.type=='tool_result' then out[#out+1]=type(b.content)=='string' and b.content or json.encode(b.content) end end end return table.concat(out,'\\n') end return {name='mcp-http-selfcheck-provider',activate=function() panto.ext.register_protocol{name='mcp-http-selfcheck',open=function(request) local rounds=0 for _,m in ipairs(request.messages) do if m.role=='assistant' then rounds=rounds+1 end end local event if rounds==0 then event={type='tool_call',id='http-search',name='mcp.search',input_json=json.encode({server='remote',query='hello'})} elseif rounds==1 then assert(last_results(request):find('hello',1,true),'HTTP tool search did not return hello') event={type='tool_call',id='http-call',name='mcp.call',input_json=json.encode({server='remote',tool='hello'})} else assert(last_results(request):find('HTTP_E2E_TOOL_OK',1,true),'HTTP MCP call did not return expected content') event={type='text_delta',text='HTTP_MCP_E2E_OK'} end local sent=false return {next=function() if sent then return {type='done'} end; sent=true; return event end} end} end}]] if mode=='oauth' then provider=[[local panto=require('panto') local async=require('panto_mcp.async') local json=panto.ext.json return {name='mcp-oauth-selfcheck-provider',activate=function() local settings,servers=require('panto_mcp.config').parse(panto.ext.config.mcp,panto.ext.dirs) local manager=require('panto_mcp.manager').new(settings,servers) local commands={} require('panto_mcp.tools').register_status({register_command=function(spec) commands[spec.name]=spec; return true end},manager,{}) local function get(url) local future=async.future() assert(panto.ext.http_request({url=url},function(response,err) future:resolve(response,err) end)) local response,err=future:await(); assert(response,err); return response end local function ready() local future=async.future(); local attempts=0 local function poll() attempts=attempts+1 if manager.states.remote.state=='ready' and not manager.states.remote.oauth.login_required and not manager.states.remote.oauth.login_url then future:resolve(true) elseif attempts>=500 then future:resolve(nil,'OAuth reconnect did not finish') else async.timer(20,poll) end end poll(); local ok,err=future:await(); assert(ok,err) end local function authorize(pasted) local future=async.future(); local attempts=0 local function login_url() attempts=attempts+1 local output=commands['mcp-login'].handler('remote') local url=output:match('\n(http[^%s]+)') if url then future:resolve(url) elseif attempts>=20 then future:resolve(nil,'login URL missing: '..output) else async.timer(1000,login_url) end end login_url(); local url,err=future:await(); assert(url,err) local response=get(url); assert(response.status==302,'authorize did not redirect') local callback=assert(response.headers.location,'missing authorization Location') if pasted then local accepted=commands['mcp-login'].handler('remote '..callback) assert(accepted:find('accepted',1,true),'headless callback not accepted') else assert(get(callback).status==200,'loopback callback failed') end ready() end panto.ext.register_tool{name='oauth-check',description='Exercise real-core MCP OAuth',schema={type='object'},handler=function() local client,err=manager:ensure('remote') assert(not client and err:find('/mcp-login remote',1,true),'initial 401 did not request login') authorize(false) local result=manager:call('remote','hello',{}) assert(not result.is_error and result.text:find('HTTP_E2E_TOOL_OK',1,true),'refresh-on-401 failed') result=manager:call('remote','hello',{stepup=true}) assert(result.is_error and result.text:find('/mcp-login remote',1,true),'missing scope consent request') authorize(true) result=manager:call('remote','hello',{stepup=true}) assert(not result.is_error,'step-up reauthorization failed: '..result.text) manager:close() manager=require('panto_mcp.manager').new(settings,servers) assert(manager.states.remote.oauth.definition,'warm discovery missing') result=manager:call('remote','hello',{}) assert(not result.is_error,'warm core session failed') manager:close() return 'HTTP_E2E_TOOL_OK' end} panto.ext.register_protocol{name='mcp-http-selfcheck',open=function(request) local done=false; local completed=false for _,m in ipairs(request.messages) do for _,b in ipairs(m.blocks or {}) do if b.type=='tool_result' then local text=type(b.content)=='string' and b.content or json.encode(b.content) assert(text:find('HTTP_E2E_TOOL_OK',1,true),'OAuth fixture tool failed: '..text); completed=true end end end return {next=function() if done then return {type='done'} end; done=true if completed then return {type='text_delta',text='HTTP_MCP_E2E_OK'} end return {type='tool_call',id='oauth-flow',name='oauth-check',input_json='{}'} end} end} end}]] provider='package.path='..string.format('%q',here..'/?.lua;'..here..'/?/init.lua;')..'..package.path\n'..provider end write(extdir..'/provider.lua',provider) local function q(s) return '"'..s:gsub('\\','\\\\'):gsub('"','\\"')..'"' end local served={}; local server_error; local clients={}; local server_timers={}; local handle_client local oauth_seen={prm=0,metadata=0,registration=0,authorize=0,tokens=0,refresh=0,stepup=0} local authorized_scope='read'; local forced_refresh=false local function form(text) local out={} local function decode(v) return (v:gsub('+',' '):gsub('%%(%x%x)',function(hex) return string.char(tonumber(hex,16)) end)) end for key,value in text:gmatch('([^&=?]+)=([^&]*)') do out[decode(key)]=decode(value) end return out end local function escape(text) return (text:gsub('[^A-Za-z0-9_.~-]',function(c) return string.format('%%%02X',c:byte()) end)) end local listener=assert(uv.new_tcp()); assert(listener:bind('127.0.0.1',0)==0) local port=assert(listener:getsockname()).port assert(listener:listen(32,function(accept_err) if accept_err then server_error=tostring(accept_err); return end local client=assert(uv.new_tcp()); local accepted,why=listener:accept(client) if accepted~=0 then server_error=tostring(why or accepted); close(client); return end handle_client(client) end)) local config_text=(mode=='slow' and '[mcp]\nidle_timeout_ms = 20\ncall_timeout_ms = 5000\n\n' or '').. '[extensions]\npaths = ['..(mode=='oauth' and '' or q(here)..', ')..q(extdir)..']\n\n'.. '[providers.fixture]\nprotocol = "mcp-http-selfcheck"\n\n[defaults]\nmodel = "fixture:dummy"\n\n'.. '[mcp.servers.remote]\nurl = '..q('http://127.0.0.1:'..port..'/mcp')..'\n' write(rig..'/config.toml',config_text) local function respond(client,status,body,content_type,session_id,delay_ms,extra_headers) local text=status==200 and 'OK' or status==202 and 'Accepted' or 'Bad Request' local fields='Content-Length: '..#body..'\r\nConnection: close\r\n' if content_type then fields='Content-Type: '..content_type..'\r\n'..fields end if session_id then fields=fields..'Mcp-Session-Id: '..session_id..'\r\n' end for name,value in pairs(extra_headers or {}) do fields=fields..name..': '..value..'\r\n' end local head='HTTP/1.1 '..status..' '..text..'\r\n'..fields..'\r\n' if delay_ms then client:write(head,function(err) if err then server_error=tostring(err); close(client); return end local timer=uv.new_timer(); server_timers[#server_timers+1]=timer timer:start(delay_ms,0,function() close(timer); client:write(body,function() close(client) end) end) end) else client:write(head..body,function() close(client) end) end end handle_client=function(client) clients[#clients+1]=client local raw=''; local answered=false client:read_start(function(read_err,chunk) if answered then return end if read_err then server_error=tostring(read_err); close(client); return end if not chunk then close(client); return end raw=raw..chunk local boundary=raw:find('\r\n\r\n',1,true); if not boundary then return end local head=raw:sub(1,boundary-1); local headers={} local request_method=head:match('^(%S+)') local target=head:match('^%S+ (%S+)') for line in (head..'\r\n'):gmatch('(.-)\r\n') do local name,value=line:match('^([^:]+):%s*(.*)$'); if name then headers[name:lower()]=value end end local body if (headers['transfer-encoding'] or ''):lower():find('chunked',1,true) then local chunks={}; local cursor=boundary+4 while true do local line_end=raw:find('\r\n',cursor,true); if not line_end then return end local size=tonumber(raw:sub(cursor,line_end-1),16); if not size then server_error='invalid chunk size'; respond(client,400,'bad request'); return end cursor=line_end+2 if size==0 then local trailer_end=raw:find('\r\n\r\n',cursor,true) if trailer_end then cursor=trailer_end+4 elseif raw:sub(cursor,cursor+1)=='\r\n' then cursor=cursor+2 else return end body=table.concat(chunks); break end if #raw