summaryrefslogtreecommitdiff
path: root/panto_mcp
diff options
context:
space:
mode:
Diffstat (limited to 'panto_mcp')
-rw-r--r--panto_mcp/async.lua59
-rw-r--r--panto_mcp/cache.lua95
-rw-r--r--panto_mcp/client.lua334
-rw-r--r--panto_mcp/config.lua176
-rw-r--r--panto_mcp/docs.lua43
-rw-r--r--panto_mcp/eager.lua60
-rw-r--r--panto_mcp/hash.lua41
-rw-r--r--panto_mcp/http.lua680
-rw-r--r--panto_mcp/jsonrpc.lua75
-rw-r--r--panto_mcp/manager.lua229
-rw-r--r--panto_mcp/namespace.lua31
-rw-r--r--panto_mcp/oauth.lua458
-rw-r--r--panto_mcp/prompts.lua267
-rw-r--r--panto_mcp/results.lua89
-rw-r--r--panto_mcp/search.lua83
-rw-r--r--panto_mcp/stdio.lua108
-rw-r--r--panto_mcp/supervisor.lua65
-rw-r--r--panto_mcp/tools.lua97
-rw-r--r--panto_mcp/validate.lua134
19 files changed, 3124 insertions, 0 deletions
diff --git a/panto_mcp/async.lua b/panto_mcp/async.lua
new file mode 100644
index 0000000..173e6d0
--- /dev/null
+++ b/panto_mcp/async.lua
@@ -0,0 +1,59 @@
+local uv = require('luv')
+local M = {}
+function M.close(h) if h and not h:is_closing() then h:close() end end
+function M.timer(ms, fn)
+ local t = uv.new_timer()
+ t:start(ms, 0, function() M.close(t); fn() end)
+ return t
+end
+function M.resume(co)
+ if coroutine.status(co) ~= 'suspended' then return end
+ local ok, err = coroutine.resume(co)
+ if not ok then io.stderr:write('panto-mcp: ', tostring(err), '\n') end
+end
+-- Futures have many awaiters; awaiting must occur in a yieldable coroutine.
+-- A close guard optionally cancels outstanding work on host interruption.
+function M.future(cancel)
+ local f = { done = false, waiters = {} }
+ function f:resolve(value, err)
+ if self.done then return end
+ self.done, self.value, self.err = true, value, err
+ local waiters = self.waiters; self.waiters = {}
+ for co in pairs(waiters) do M.resume(co) end
+ end
+ function f:abandon(value,err)
+ if self.done then return end
+ self.done,self.value,self.err=true,value,err
+ self.waiters={}
+ end
+ function f:cancel() if not self.done and cancel then cancel() end end
+ function f:await()
+ if not self.done then
+ assert(coroutine.isyieldable(), 'MCP await requires a coroutine')
+ local co = coroutine.running()
+ local guard <close> = setmetatable({}, {__close = function()
+ self.waiters[co] = nil
+ if not self.done then self:cancel() end
+ end})
+ self.waiters[co] = true
+ while not self.done do
+ -- std.lua budgets only active instructions, not parked time.
+ local hook,mask,count=debug.gethook(co)
+ if hook then debug.sethook(co) end
+ coroutine.yield()
+ if hook then debug.sethook(co,hook,mask,count) end
+ end
+ end
+ return self.value, self.err
+ end
+ return f
+end
+function M.run(fn, on_error)
+ local co = coroutine.create(function()
+ local ok, err = xpcall(fn, debug.traceback)
+ if not ok then (on_error or function(e) io.stderr:write(tostring(e), '\n') end)(err) end
+ end)
+ M.resume(co)
+ return co
+end
+return M
diff --git a/panto_mcp/cache.lua b/panto_mcp/cache.lua
new file mode 100644
index 0000000..fb14faa
--- /dev/null
+++ b/panto_mcp/cache.lua
@@ -0,0 +1,95 @@
+local uv = require('luv')
+local json = require('panto').ext.json
+local M = {}
+function M.directory(getenv)
+ getenv = getenv or os.getenv
+ local xdg = getenv('XDG_DATA_HOME')
+ return ((xdg and xdg~='') and xdg or ((getenv('HOME') or '.') .. '/.local/share')) .. '/panto-mcp'
+end
+local function mkdir(path)
+ if uv.fs_stat(path) then return true end
+ local parent = path:match('^(.*)/[^/]+$')
+ if parent and parent~='' then
+ local ok,err=mkdir(parent); if not ok then return nil,err end
+ end
+ local ok,err=uv.fs_mkdir(path, 448)
+ if ok then return true end
+ local stat=uv.fs_stat(path)
+ if stat and stat.type=='directory' then return true end
+ return nil,err
+end
+function M.path(cfg, dir) return (dir or M.directory()) .. '/' .. cfg.name .. '-' .. cfg.fingerprint .. '.json' end
+function M.normalize_catalog(catalog)
+ if type(catalog)~='table' then return nil end
+ local out={}
+ for _,kind in ipairs({'tools','prompts','resources','templates'}) do
+ local items=catalog[kind]
+ if type(items)~='table' then return nil end
+ local clean=json.array({})
+ for _,item in ipairs(items) do
+ if type(item)=='table' then
+ local valid=true
+ for field,value in pairs(item) do if value==json.null then item[field]=nil end end
+ for _,field in ipairs({'name','title','description','uri','uriTemplate','mimeType'}) do
+ if item[field]~=nil and type(item[field])~='string' then valid=false end
+ end
+ if (kind=='tools' or kind=='prompts') and (not item.name or item.name=='') then valid=false end
+ if kind=='tools' and type(item.inputSchema)~='table' then valid=false end
+ if kind=='resources' and not item.uri then valid=false end
+ if kind=='templates' and not item.uriTemplate then valid=false end
+ if valid then clean[#clean+1]=item end
+ end
+ end
+ out[kind]=clean
+ end
+ return out
+end
+function M.load(cfg, dir)
+ local f = io.open(M.path(cfg,dir), 'rb'); if not f then return nil end
+ local text = f:read(16*1024*1024 + 1); f:close()
+ if not text or #text>16*1024*1024 then return nil end
+ local ok, data = pcall(json.decode,text)
+ if not ok or type(data)~='table' or data.fingerprint~=cfg.fingerprint or type(data.catalog)~='table' then return nil end
+ local catalog=M.normalize_catalog(data.catalog)
+ if not catalog then return nil end
+ data.catalog=catalog
+ if data.era~='modern' and data.era~='legacy' then return nil end
+ return data
+end
+local serial = 0
+function M.save(cfg, data, dir)
+ dir = dir or M.directory()
+ local ok,err = mkdir(dir); if not ok then return nil,err end
+ local catalog=M.normalize_catalog(data.catalog)
+ if not catalog then return nil,'invalid cache catalog' end
+ serial=serial+1
+ local path = M.path(cfg,dir)
+ local temp = path .. '.' .. uv.os_getpid() .. '-' .. serial .. '.tmp'
+ local fd; fd,err=uv.fs_open(temp,'wx',384); if not fd then return nil,err end
+ local encoded_ok,text=pcall(json.encode,{fingerprint=cfg.fingerprint, era=data.era,
+ version=data.version, info=data.info, instructions=data.instructions,
+ capabilities=data.capabilities, catalog=catalog})
+ if not encoded_ok then uv.fs_close(fd); uv.fs_unlink(temp); return nil,text end
+ local offset=0
+ while offset<#text do
+ local written; written,err=uv.fs_write(fd,text:sub(offset+1),offset)
+ if not written or written==0 then uv.fs_close(fd); uv.fs_unlink(temp); return nil,err or 'short cache write' end
+ offset=offset+written
+ end
+ uv.fs_close(fd)
+ ok,err=uv.fs_rename(temp,path)
+ if not ok then uv.fs_unlink(temp); return nil,err end
+ local scan=uv.fs_scandir(dir)
+ if scan then
+ while true do
+ local name=uv.fs_scandir_next(scan)
+ if not name then break end
+ local server,fingerprint=name:match('^(.*)%-([0-9a-f]+)%.json$')
+ if server==cfg.name and fingerprint and #fingerprint==8 and name~=path:match('([^/]+)$') then
+ uv.fs_unlink(dir .. '/' .. name)
+ end
+ end
+ end
+ return true
+end
+return M
diff --git a/panto_mcp/client.lua b/panto_mcp/client.lua
new file mode 100644
index 0000000..9d139e1
--- /dev/null
+++ b/panto_mcp/client.lua
@@ -0,0 +1,334 @@
+local rpc = require('panto_mcp.jsonrpc')
+local async = require('panto_mcp.async')
+local json = require('panto').ext.json
+local M = {}; M.__index=M
+M.MODERN='2026-07-28'; M.LEGACY='2025-11-25'; M.VERSION='0.1.0'
+local supported={['2025-11-25']=true,['2025-06-18']=true,['2025-03-26']=true,['2024-11-05']=true}
+local info={name='panto-mcp',version=M.VERSION}
+local function failure(err)
+ if type(err)=='table' then return tostring(err.message or 'RPC error') .. ' (' .. tostring(err.code) .. ')' end
+ return tostring(err)
+end
+local function context(self,method,text)
+ if self.cfg.transport=='http' then return self.cfg.name..' '..method..': '..tostring(text) end
+ return text
+end
+M.error_text=failure
+function M.new(cfg,settings,opts)
+ opts=opts or {}
+ return setmetatable({cfg=cfg,settings=settings,opts=opts,catalog={tools=json.array({}),prompts=json.array({}),resources=json.array({}),templates=json.array({})}},M)
+end
+local function filter_http_tools(self,items)
+ if self.cfg.transport=='http' then return require('panto_mcp.http').filter_tools(items,self.cfg.name) end
+ return items,{}
+end
+function M:open()
+ if self.closed then return nil,'connection closed' end
+ async.close(self.notification_retry_timer); self.notification_retry_timer=nil
+ if self.rpc then self.replacing=true; self.rpc:close(); self.replacing=false end
+ local factory=self.opts.transport_factory or function(cfg,settings)
+ if cfg.transport=='stdio' then return require('panto_mcp.stdio').new(cfg) end
+ if cfg.transport=='http' then
+ local transport,why
+ transport,why=require('panto_mcp.http').new(cfg,settings,{timer_factory=self.opts.timer_factory,
+ oauth=self.opts.oauth,request_fn=self.opts.request_fn,on_notification_stream_end=function(status)
+ if self.transport==transport then self:schedule_notification_stream_retry(status) end
+ end})
+ return transport,why
+ end
+ return nil,'unknown MCP transport'
+ end
+ local transport,err=factory(self.cfg,self.settings)
+ if not transport then
+ if self.cfg.transport=='http' then return nil,self.cfg.name..' connect: '..tostring(err) end
+ return nil,err
+ end
+ self.transport=transport
+ self.rpc=rpc.new(transport,{timeout_ms=self.settings.call_timeout_ms,timer_factory=self.opts.timer_factory,
+ on_notification=function(method) self:notification(method) end,
+ on_error=function(e) if not self.replacing and self.opts.on_error then self.opts.on_error(e) end end})
+ return true
+end
+function M:request(method,params,timeout_ms)
+ params=params or {}
+ local oauth=self.opts.oauth
+ if oauth then
+ local ok,err=oauth:before_request(); if not ok then return nil,err end
+ end
+ if self.era=='legacy' and self.transport and self.transport.protocol_version then self.version=self.transport.protocol_version end
+ if self.legacy_reinit and method~='initialize' then
+ local ok,err=self.legacy_reinit:await(); if not ok then return nil,err end
+ end
+ if self.era=='modern' then
+ params._meta=params._meta or {}
+ params._meta['io.modelcontextprotocol/protocolVersion']=self.version
+ params._meta['io.modelcontextprotocol/clientCapabilities']={}
+ params._meta['io.modelcontextprotocol/clientInfo']=info
+ end
+ local opts={era=self.era,protocol_version=self.version,method=method,
+ name=params.name or params.uri,timeout_ms=timeout_ms,cancel_protocol=method~='initialize'}
+ if method=='tools/call' and self.tool_headers then opts.param_headers=self.tool_headers[params.name] end
+ local function request_once()
+ local value,request_error=self.rpc:request(method,params,opts)
+ if type(request_error)=='string' and request_error:match('^request timed out:') then request_error=context(self,method,request_error) end
+ return value,request_error
+ end
+ local result,err=request_once()
+ local data=type(err)=='table' and type(err.data)=='table' and err.data or nil
+ if oauth and data and data.auth_error then
+ local retry,why=oauth:recover(data)
+ if not retry then return nil,why end
+ result,err=request_once()
+ data=type(err)=='table' and type(err.data)=='table' and err.data or nil
+ if data and data.auth_error then
+ if data.http_status==403 then
+ local _,why=oauth:recover(data)
+ return nil,why
+ end
+ oauth.login_required=not oauth:usable() or nil
+ return nil,oauth.cfg.auth and oauth:configured_error() or oauth:login_error()
+ end
+ end
+ if self.cfg.transport=='http' and self.era=='legacy' and method~='initialize' and data and data.session_expired then
+ if data.session_generation~=nil and self.transport and self.transport.session_generation~=data.session_generation then
+ if self.legacy_reinit then local ok,why=self.legacy_reinit:await(); if not ok then return nil,why end end
+ opts.protocol_version=self.transport.protocol_version or self.version
+ return request_once()
+ end
+ local ok,why=self:reinitialize_legacy(); if not ok then return nil,why end
+ opts.protocol_version=self.version
+ return request_once()
+ end
+ if self.cfg.transport=='http' and self.era=='modern' and method=='tools/call' and type(err)=='table' and err.code==-32020 then
+ local original_error=err
+ local catalog,refresh_err=self:refresh()
+ if not catalog then return nil,refresh_err end
+ local definition
+ for _,tool in ipairs(catalog.tools) do if tool.name==params.name then definition=tool; break end end
+ if not definition then return nil,original_error end
+ local input=params.arguments or {}
+ local valid,validation_errors=require('panto_mcp.validate').check(input,definition.inputSchema)
+ if not valid then
+ return nil,{code=-32602,message=context(self,'tools/call','input validation failed after schema refresh: '..table.concat(validation_errors,'; ')),
+ data={validation_errors=validation_errors,schema=definition.inputSchema}}
+ end
+ opts.param_headers=self.tool_headers[params.name]
+ return request_once()
+ end
+ return result,err
+end
+function M:reinitialize_legacy()
+ local future=self.legacy_reinit
+ if not future then
+ future=async.future(); self.legacy_reinit=future
+ local function failed(err)
+ local why=failure(err)
+ if self.rpc and not self.rpc.closed then self.rpc:fail(why) end
+ future:resolve(nil,why)
+ if self.legacy_reinit==future then self.legacy_reinit=nil end
+ end
+ async.run(function()
+ local result,err=self:handshake('legacy',self.version or M.LEGACY,self.settings.startup_timeout_ms)
+ if result then
+ future:resolve(true); if self.legacy_reinit==future then self.legacy_reinit=nil end
+ else failed(err) end
+ end,function(err) failed(err) end)
+ end
+ return future:await()
+end
+function M:schedule_notification_stream_retry(status)
+ if status==401 then
+ self.notification_retry_stopped=true
+ self.notification_warning='Notification stream rejected (HTTP 401); '..(self.cfg.auth and 'check configured auth' or ('run /mcp-login '..self.cfg.name))
+ async.close(self.notification_retry_timer); self.notification_retry_timer=nil
+ return
+ end
+ if self.notification_retry_stopped then return end
+ if self.closed or self.cfg.expose~='eager' or self.cfg.transport~='http' or self.era~='legacy'
+ or self.version~=M.LEGACY or type(self.capabilities)~='table'
+ or type(self.capabilities.tools)~='table' or self.capabilities.tools.listChanged~=true then return end
+ async.close(self.notification_retry_timer)
+ local timer_factory=self.opts.timer_factory or async.timer
+ self.notification_retry_delay=math.min((self.notification_retry_delay or 500)*2,60000)
+ self.notification_retry_timer=timer_factory(self.notification_retry_delay,function()
+ self.notification_retry_timer=nil
+ if not self.closed and self.transport and self.transport.open_notification_stream then
+ self.transport:open_notification_stream()
+ end
+ end)
+end
+function M:handshake(era,version,timeout)
+ if era=='legacy' and self.cfg.transport=='http' and self.transport and self.transport.close_notification_stream then
+ self.transport:close_notification_stream()
+ self.notification_retry_stopped=nil; self.notification_warning=nil; self.notification_retry_delay=nil
+ async.close(self.notification_retry_timer); self.notification_retry_timer=nil
+ end
+ self.era=era; self.version=version or (era=='modern' and M.MODERN or M.LEGACY)
+ local result,err
+ if era=='modern' then result,err=self:request('server/discover',{},timeout)
+ else
+ result,err=self:request('initialize',{protocolVersion=self.version,capabilities={},clientInfo=info},timeout)
+ if result then
+ if not supported[result.protocolVersion] then return nil,context(self,'initialize','unsupported initialize version: '..tostring(result.protocolVersion)) end
+ self.version=result.protocolVersion
+ local sent,why=self.rpc:notify('notifications/initialized',{}, {era='legacy',protocol_version=self.version})
+ if not sent then return nil,why end
+ if type(sent)=='table' and type(sent.await)=='function' then
+ local accepted,notify_err=sent:await(); if not accepted then return nil,notify_err end
+ end
+ end
+ end
+ if not result then return nil,err end
+ if type(result)~='table' then return nil,context(self,era=='modern' and 'server/discover' or 'initialize','invalid discovery response') end
+ if result.resultType=='input_required' then return nil,context(self,era=='modern' and 'server/discover' or 'initialize','discovery requested unsupported user input') end
+ if era=='legacy' and self.transport and self.transport.protocol_version then self.transport.protocol_version=self.version end
+ self.capabilities=type(result.capabilities)=='table' and result.capabilities or {}
+ self.info=result.serverInfo or (type(result._meta)=='table' and result._meta['io.modelcontextprotocol/serverInfo']) or {}
+ self.instructions=result.instructions
+ if self.cfg.expose=='eager' and self.cfg.transport=='http' and era=='legacy'
+ and self.version==M.LEGACY and type(self.capabilities.tools)=='table'
+ and self.capabilities.tools.listChanged==true and self.transport.open_notification_stream then
+ self.transport:open_notification_stream()
+ end
+ return result
+end
+function M:refresh_stable()
+ local catalog,err
+ repeat
+ self.dirty=false
+ catalog,err=self:refresh()
+ if not catalog then return nil,err end
+ until not self.dirty or self.closed
+ return catalog
+end
+local function real_rejection(err)
+ return type(err)=='table' or (type(err)=='string' and err:find('unsupported initialize version',1,true)~=nil)
+end
+function M:connect(cached)
+ self.closed=false; self.connecting=true
+ local ok,err=self:open(); if not ok then return nil,err end
+ local result
+ if cached then
+ local version=cached.era=='legacy' and M.LEGACY or cached.version
+ result,err=self:handshake(cached.era,version,self.settings.startup_timeout_ms)
+ if result then
+ local catalog; catalog,err=self:refresh_stable()
+ if catalog then self.connecting=false; return true end
+ return nil,err
+ end
+ if self.cfg.transport=='http' then
+ if not require('panto_mcp.http').should_fallback(err) and not (type(err)=='table' and err.code==-32022) then return nil,failure(err) end
+ elseif not real_rejection(err) then return nil,failure(err) end
+ ok,err=self:open(); if not ok then return nil,err end
+ end
+ result,err=self:handshake('modern',M.MODERN,math.min(1500,self.settings.startup_timeout_ms))
+ local modern_probe_error=err
+ if not result and type(err)=='table' and err.code==-32022 then
+ local versions=(type(err.data)=='table' and err.data.supported) or err.supported or {}
+ if type(versions)~='table' then versions={} end
+ local choice
+ for _,v in ipairs(versions) do
+ if v==M.MODERN or supported[v] then choice=v; break end
+ end
+ if choice and choice~=M.MODERN then
+ result,err=self:handshake('legacy',choice,self.settings.startup_timeout_ms)
+ if not result then return nil,failure(err) end
+ elseif self.cfg.transport=='http' then
+ return nil,failure(err)
+ end
+ end
+ if not result and self.cfg.transport=='http' and self.transport and not require('panto_mcp.http').should_fallback(modern_probe_error) then
+ return nil,failure(modern_probe_error)
+ end
+ if not result then
+ -- Some legacy stdio implementations close on a pre-initialize probe.
+ -- Always give initialize a fresh process, with no probe history.
+ ok,err=self:open(); if not ok then return nil,err end
+ result,err=self:handshake('legacy',M.LEGACY,self.settings.startup_timeout_ms)
+ if not result and not self.closed then
+ local initialize_error=err
+ if self.cfg.transport=='stdio' then
+ if self.rpc.closed then ok,err=self:open(); if not ok then return nil,err end end
+ result,err=self:handshake('modern',M.MODERN,self.settings.startup_timeout_ms)
+ if not result then err=initialize_error end
+ end
+ end
+ end
+ if not result then return nil,failure(err) end
+ local catalog; catalog,err=self:refresh_stable()
+ if not catalog then return nil,err end
+ self.connecting=false
+ return true
+end
+function M:list(method,key)
+ local items,cursor,seen=json.array({}),nil,{}
+ local pages=0
+ repeat
+ pages=pages+1
+ if pages>1000 then return nil,context(self,method,'pagination exceeds 1000 pages') end
+ local result,err=self:request(method,{cursor=cursor})
+ if not result then
+ if type(err)=='table' and err.code==-32601 then return items end
+ return nil,failure(err)
+ end
+ if type(result)~='table' or type(result[key])~='table' then return nil,context(self,method,'invalid '..method..' result') end
+ for _,item in ipairs(result[key]) do items[#items+1]=item end
+ if #items>100000 then return nil,context(self,method,'catalog exceeds 100000 entries') end
+ cursor=result.nextCursor
+ if cursor==json.null then cursor=nil end
+ if cursor~=nil then
+ if type(cursor)~='string' or seen[cursor] then return nil,context(self,method,'invalid/repeated pagination cursor') end
+ seen[cursor]=true
+ end
+ until not cursor
+ return items
+end
+function M:refresh()
+ local catalog={tools=json.array({}),prompts=json.array({}),resources=json.array({}),templates=json.array({})}
+ local tool_headers={}
+ for _,entry in ipairs({{'tools','tools/list','tools','tools'}, {'prompts','prompts/list','prompts','prompts'},
+ {'resources','resources/list','resources','resources'}, {'resources','resources/templates/list','resourceTemplates','templates'}}) do
+ if type(self.capabilities[entry[1]])=='table' then
+ local items,err=self:list(entry[2],entry[3]); if not items then return nil,err end
+ if entry[4]=='tools' then items,tool_headers=filter_http_tools(self,items) end
+ catalog[entry[4]]=items
+ end
+ end
+ catalog=require('panto_mcp.cache').normalize_catalog(catalog)
+ if not catalog then return nil,context(self,'catalog','invalid catalog metadata') end
+ self.catalog=catalog
+ self.tool_headers=tool_headers
+ if self.opts.on_catalog then self.opts.on_catalog(self) end
+ return catalog
+end
+function M:notification(method)
+ self.notification_retry_delay=nil
+ if not method:match('^notifications/[a-z]+/list_changed$') then return end
+ if self.closed then return end
+ self.dirty=true
+ if self.connecting or self.refreshing then return end
+ self.refreshing=true
+ async.run(function()
+ repeat
+ self.dirty=false
+ local _,err=self:refresh()
+ if err and self.opts.on_error then self.opts.on_error(err); break end
+ until not self.dirty or self.closed
+ self.refreshing=false
+ end,function(err) self.refreshing=false; if self.opts.on_error then self.opts.on_error(err) end end)
+end
+function M:call(name,input) return self:request('tools/call',{name=name,arguments=input or {}}) end
+function M:read_resource(uri) return self:request('resources/read',{uri=uri}) end
+function M:prompt(name,args) return self:request('prompts/get',{name=name,arguments=args or {}}) end
+function M:metadata()
+ return {era=self.era,version=self.version,info=self.info,instructions=self.instructions,
+ capabilities=self.capabilities,catalog=self.catalog}
+end
+function M:close(abandon)
+ self.closed=true
+ async.close(self.notification_retry_timer); self.notification_retry_timer=nil
+ self.replacing=true
+ if self.rpc then self.rpc:close(abandon) end
+ self.replacing=false
+end
+return M
diff --git a/panto_mcp/config.lua b/panto_mcp/config.lua
new file mode 100644
index 0000000..2a88c9c
--- /dev/null
+++ b/panto_mcp/config.lua
@@ -0,0 +1,176 @@
+local json = require('panto').ext.json
+local M = {}
+local function string_ok(v) return type(v) == 'string' and not v:find('%z') end
+function M.expand(s, root, getenv)
+ return (s:gsub('%${env:([%w_]+)}', function(k) return (getenv or os.getenv)(k) or '' end)
+ :gsub('%${project_root}', function() return root end))
+end
+function M.canonical(v) return json.encode(v) end
+function M.hash(s)
+ local h = 2166136261
+ for i = 1, #s do h = ((h ~ s:byte(i)) * 16777619) & 0xffffffff end
+ return string.format('%08x', h)
+end
+function M.fingerprint(s)
+ return M.hash(M.canonical({url=s.url, command=s.command, args=s.args, env=s.env,
+ cwd=s.cwd, headers=s.headers, auth=s.auth, oauth=s.oauth}))
+end
+local function tool_hash(name) return M.hash(name)..M.hash(name:reverse()) end
+function M.valid_name(s)
+ return type(s)=='string' and s:match('^[A-Za-z0-9_-]+$')~=nil
+ and not s:find('__',1,true) and s:sub(-1)~='_'
+end
+function M.tool_name(server,name)
+ local server_part=server
+ if #server_part>32 then server_part=server_part:sub(1,15)..'-'..tool_hash(server_part) end
+ local prefix='mcp.'..server_part..'.'
+ local stem=name:gsub('[^A-Za-z0-9_-]','_'):gsub('__+','_')
+ local available=64-(#prefix+2)
+ -- Reserve encoded-looking suffixes so a literal name cannot impersonate a sanitized one.
+ if stem:match('%-'..string.rep('%x',16)..'$') then stem=stem..'_' end
+ if stem==name and #stem<=available then return prefix..stem end
+ local suffix='-'..tool_hash(name)
+ stem=stem:sub(1,math.max(1,available-#suffix))
+ return prefix..stem..suffix
+end
+local function list(v, field)
+ if v == nil then return {} end
+ assert(type(v)=='table', field .. ' must be an array')
+ local count = 0
+ for k,x in pairs(v) do
+ assert(type(k)=='number' and k>=1 and k%1==0 and string_ok(x), field .. ' must contain strings')
+ count = count+1
+ end
+ assert(count == #v, field .. ' must be dense')
+ return v
+end
+local function map(v, field)
+ if v == nil then return {} end
+ assert(type(v)=='table', field .. ' must be a table')
+ for k,x in pairs(v) do assert(string_ok(k) and string_ok(x), field .. ' must map strings to strings') end
+ return v
+end
+local forbidden_headers={host=true,connection=true,['content-length']=true,['transfer-encoding']=true,
+ expect=true,upgrade=true,te=true,['keep-alive']=true,['proxy-connection']=true}
+local sensitive_headers={authorization=true,['proxy-authorization']=true,cookie=true,['x-api-key']=true,
+ ['api-key']=true,['x-auth-token']=true,['x-access-token']=true}
+local function loopback_url(url)
+ local authority=url:match('^[Hh][Tt][Tt][Pp]://([^/?#]+)')
+ if not authority then return false end
+ authority=authority:match('@(.+)$') or authority
+ local host
+ if authority:sub(1,1)=='[' then host=authority:match('^(%b[])')
+ else host=authority:match('^([^:]+)') end
+ if not host then return false end
+ local lower=host:lower()
+ if lower=='localhost' or lower=='[::1]' or lower=='::1' then return true end
+ local a,b,c,d=lower:match('^(%d+)%.(%d+)%.(%d+)%.(%d+)$')
+ if not a then return false end
+ for _,octet in ipairs({a,b,c,d}) do if #octet>1 and octet:sub(1,1)=='0' then return false end end
+ a,b,c,d=tonumber(a),tonumber(b),tonumber(c),tonumber(d)
+ return a==127 and b<256 and c<256 and d<256
+end
+local function header_token(s)
+ if type(s)~='string' or s=='' then return false end
+ for i=1,#s do
+ local c=s:sub(i,i)
+ if not c:match('^[A-Za-z0-9]$') and not ("!#$%&'*+-.^_`|~"):find(c,1,true) then return false end
+ end
+ return true
+end
+local function empty_env_expansion(value,getenv)
+ for key in value:gmatch('%${env:([%w_]+)}') do
+ local expanded=(getenv or os.getenv)(key)
+ if expanded==nil or expanded=='' then return true end
+ end
+ return false
+end
+local function glob(pattern, s)
+ local p = pattern:gsub('([%^%$%(%)%%%.%[%]%+%-])', '%%%1'):gsub('%*', '.*'):gsub('%?', '.')
+ return s:match('^' .. p .. '$') ~= nil
+end
+function M.tool_enabled(cfg, name)
+ local enabled = #cfg.enabled_tools == 0
+ for _,p in ipairs(cfg.enabled_tools) do if glob(p,name) then enabled = true end end
+ for _,p in ipairs(cfg.disabled_tools) do if glob(p,name) then return false end end
+ return enabled
+end
+function M.parse(raw, dirs, getenv)
+ local warnings, servers = {}, {}
+ if raw~=nil and type(raw)~='table' then warnings[#warnings+1]='mcp must be a table' end
+ raw = type(raw)=='table' and raw or {}
+ local settings = {}
+ for k,default in pairs({startup_timeout_ms=30000, call_timeout_ms=300000, idle_timeout_ms=60000}) do
+ local v = raw[k] or default
+ if type(v)~='number' or v<1 or v%1~=0 then warnings[#warnings+1]=k .. ': using default'; v=default end
+ settings[k]=v
+ end
+ local root = (dirs and dirs.project_root) or require('luv').cwd()
+ local function expand(v) return M.expand(v, root, getenv) end
+ if raw.servers ~= nil and type(raw.servers)~='table' then warnings[#warnings+1]='servers must be a table'; return settings,servers,warnings end
+ for name, raw_server in pairs(raw.servers or {}) do
+ local ok, s = pcall(function()
+ assert(M.valid_name(name), 'invalid server name')
+ assert(type(raw_server)=='table', 'server must be a table')
+ local r = raw_server
+ assert(r.enabled == nil or type(r.enabled)=='boolean', 'enabled must be boolean')
+ if r.enabled == false then return nil end
+ assert((r.url~=nil) ~= (r.command~=nil), 'configure exactly one of url / command')
+ local c = {name=name, expose=r.expose or 'search', enabled=true}
+ assert(c.expose=='search' or c.expose=='eager', 'expose must be search or eager')
+ for _,k in ipairs({'url','command','cwd','auth'}) do
+ if r[k]~=nil then assert(string_ok(r[k]) and r[k]~='', k .. ' must be a nonempty string'); c[k]=expand(r[k]) end
+ end
+ if c.command then assert(c.command~='', 'command expanded to empty') end
+ if c.url then assert(c.url:match('^https?://'), 'url must use http(s)') end
+ if c.url and c.url:match('^http://') and c.auth and not loopback_url(c.url) then
+ warnings[#warnings+1]=name .. ': named auth on non-loopback HTTP is forbidden; server ignored'
+ return nil
+ end
+ if r.oauth~=nil then
+ assert(c.url and type(r.oauth)=='table', 'oauth requires an HTTP server and a table')
+ c.oauth={scopes=list(r.oauth.scopes,'oauth.scopes')}
+ for _,key in ipairs({'client_id','client_secret','issuer'}) do
+ if r.oauth[key]~=nil then
+ assert(string_ok(r.oauth[key]) and r.oauth[key]~='', 'oauth.'..key..' must be a nonempty string')
+ c.oauth[key]=expand(r.oauth[key])
+ assert(c.oauth[key]~='', 'oauth.'..key..' expanded to empty')
+ end
+ end
+ assert(not c.oauth.client_secret or c.oauth.client_id, 'oauth.client_secret requires client_id')
+ assert(not c.oauth.client_id or c.oauth.issuer, 'oauth.client_id requires oauth.issuer')
+ end
+ c.args={}; for _,v in ipairs(list(r.args,'args')) do c.args[#c.args+1]=expand(v) end
+ c.env={}; for k,v in pairs(map(r.env,'env')) do
+ assert(k~='' and not k:find('=',1,true), 'invalid environment name'); c.env[k]=expand(v)
+ end
+ c.headers={}
+ for k,v in pairs(map(r.headers,'headers')) do
+ local lower=k:lower()
+ if not header_token(k) then warnings[#warnings+1]=name .. ': invalid HTTP header name ignored'
+ elseif forbidden_headers[lower] or (lower=='authorization' and c.auth~=nil) then warnings[#warnings+1]=name .. ': core-forbidden HTTP header ignored'
+ elseif c.url and c.url:match('^http://') and not loopback_url(c.url) and sensitive_headers[lower] then
+ warnings[#warnings+1]=name .. ': sensitive header on non-loopback HTTP ignored'
+ elseif empty_env_expansion(v,getenv) then warnings[#warnings+1]=name .. ': header has an empty env expansion and was ignored'
+ else
+ local value=expand(v)
+ if (k..value):find('[\r\n]') then warnings[#warnings+1]=name .. ': unsafe HTTP header ignored'
+ else c.headers[k]=value end
+ end
+ end
+ c.enabled_tools=list(r.enabled_tools,'enabled_tools'); c.disabled_tools=list(r.disabled_tools,'disabled_tools')
+ c.cwd=c.cwd or root
+ if c.cwd:sub(1,1)~='/' then c.cwd=root .. '/' .. c.cwd end
+ c.transport=c.url and 'http' or 'stdio'
+ c.fingerprint=M.fingerprint(c)
+ return c
+ end)
+ if not ok then warnings[#warnings+1]=tostring(name) .. ': ' .. tostring(s)
+ elseif s then
+ servers[name]=s
+
+ end
+ end
+ return settings, servers, warnings
+end
+return M
diff --git a/panto_mcp/docs.lua b/panto_mcp/docs.lua
new file mode 100644
index 0000000..af726d3
--- /dev/null
+++ b/panto_mcp/docs.lua
@@ -0,0 +1,43 @@
+return {
+ discovery = [[MCP code mode (also available to child agents)
+mcp.servers() -> array {name,transport,mode,era,version,state,auth?,error,notification_warning?,tools,prompts,resources,templates,stderr}
+Transport is stdio or an HTTP URL. HTTP uses modern 2026-07-28 POST with JSON/SSE, falling back to supported legacy session revisions (2025-11-25, 2025-06-18, or 2025-03-26); it requires panto's POST/streaming http_request API. Configure url, optional static headers, and auth = "<session>" on the server. Valid HTTP tool schemas may annotate primitive parameters with x-mcp-header; matching values are mirrored as safe Mcp-Param-* headers, and tools with invalid annotations are excluded. Secrets should use named auth; headers are never shown by status.
+mcp.search(query?, {server?,limit?}) -> {hits,total,instructions?,servers}, or nil,error.
+Search warm metadata without starting servers. Cold catalogs wait for bounded startup.
+Hits are tools/resources/templates, with server, name, description and full inputSchema.
+Search is the default exposure mode; `expose = "eager"` opts in to cached
+`mcp.<server>.<tool>` tools at activation and cold-catalog reconciliation.
+Eager tool names are sanitized, stable per MCP name, and capped at 64 provider-wire bytes. Older panto
+builds without dynamic tool registration fall back to search mode.
+Use exact server/tool names from search; calls never execute fuzzy matches.
+return mcp.search("read file", {server="fs",limit=5})]],
+ auth = [[HTTP OAuth: /mcp-login <server> [callback-url | --reregister]; /mcp shows status. Preparation is async; explicit auth wins.
+Optional oauth.issuer pins discovery; client_id requires it. Public DCR registrations survive failures; --reregister explicitly replaces one. Sessions use SHA-256 identity hashes.
+401 refreshes once (parallel calls wait); scope consent keeps working tokens usable. See README for storage, recovery and provider limits.]],
+ calls = [[mcp.call(server,tool,input?) -> {text,attachments,structured?,is_error}.
+Validates against LIVE inputSchema after lazy connection; failed servers retry next use.
+Validation failures include validation_errors and schema. Attachments contain raw data bytes
+and media_type. Output text is capped at 100 KiB with a truncation marker; images are
+capped at 5 MiB each / 10 MiB total. RPC/tool/input_required failures set is_error=true.
+local h1=mcp.start("fs","read_text_file",{path="/allowed/a"})
+local h2=mcp.start("fs","read_text_file",{path="/allowed/b"})
+return {h1:await(), h2:await()}
+A start handle also supports :cancel(); :await() returns nil,error on cancellation.
+Await only from the std.lua script coroutine, never from a non-yielding TUI callback.
+No polling or sleeps. Calls time out at the configured deadline; progress never extends it.]],
+ resources = [[mcp.read_resource(server,uri) -> same mapped result as mcp.call.
+A resource_link names its originating server: read there, not with web.fetch.
+Fill resource template variables to form a concrete URI before reading.
+return mcp.read_resource("catalog", "docs://guide")
+No subscriptions; resources/list and resources/templates/list are cached/searchable.]],
+ prompts = [[mcp.prompts(server) -> prompt definitions, or nil,error.
+mcp.prompt(server,name,args?) -> messages [{role,content}], or nil,error.
+Args must be string-valued. These namespace methods return data only.
+Each prompt is also registered as `/mcp:<server>:<prompt>`; pass `name=value`
+tokens with shell-style quoting, or a single raw trimmed remainder when no
+matching `name=` token appears. Prompts with slash/whitespace names are skipped
+and shown in `/mcp` warnings. Commands return immediately; asynchronous failures
+show above the input until the next command or turn. A trailing user message is submitted;
+an assistant tail is appended and wakes idle conversation sync without a turn.
+Messages retain user/assistant roles, and media is text for assistant or unsupported image/non-image content.]],
+}
diff --git a/panto_mcp/eager.lua b/panto_mcp/eager.lua
new file mode 100644
index 0000000..30dd400
--- /dev/null
+++ b/panto_mcp/eager.lua
@@ -0,0 +1,60 @@
+local json = require('panto').ext.json
+local config = require('panto_mcp.config')
+
+local M = {}
+local function log(err)
+ io.stderr:write('panto-mcp: registration: ', tostring(err), '\n')
+end
+local function invoke(ext, method, name)
+ local ok, value, err = pcall(ext[method], name)
+ if not ok then log(value); return false end
+ if not value then log(err or (method .. ' failed for ' .. name)); return false end
+ return true
+end
+local function tool_spec(manager, server, tool, wire_name)
+ return {
+ name = wire_name,
+ description = tool.description or tool.title or ('MCP tool ' .. tool.name .. ' on ' .. server),
+ schema = tool.inputSchema,
+ handler = function(input)
+ local result = manager:call(server, tool.name, input)
+ if result.is_error then error(result.text, 0) end
+ return {text=result.text, attachments=result.attachments}
+ end,
+ }
+end
+function M.new(ext, manager)
+ local self = {ext=ext, manager=manager, tools={}}
+ function self:reconcile()
+ if type(ext.unregister_tool) ~= 'function' then return end
+ local wanted = {}
+ for server, state in pairs(manager.states) do
+ if state.cfg.expose == 'eager' then
+ for _,tool in ipairs((state.metadata and state.metadata.catalog and state.metadata.catalog.tools) or {}) do
+ if config.tool_enabled(state.cfg,tool.name) then
+ local wire=config.tool_name(server,tool.name)
+ local fingerprint=json.encode({description=tool.description,title=tool.title,schema=tool.inputSchema})
+ wanted[wire]={server=server,name=tool.name,tool=tool,fingerprint=fingerprint}
+ end
+ end
+ end
+ end
+ for wire, old in pairs(self.tools) do
+ local current = wanted[wire]
+ if not current or current.fingerprint ~= old.fingerprint or current.server ~= old.server or current.name ~= old.name then
+ if invoke(ext, 'unregister_tool', wire) then self.tools[wire] = nil end
+ end
+ end
+ for wire, current in pairs(wanted) do
+ if not self.tools[wire] then
+ local spec = tool_spec(manager, current.server, current.tool, wire)
+ local ok, value, err = pcall(ext.register_tool, spec)
+ if ok and value then
+ self.tools[wire] = current
+ else log(ok and (err or ('register_tool failed for ' .. wire)) or value) end
+ end
+ end
+ end
+ return self
+end
+return M
diff --git a/panto_mcp/hash.lua b/panto_mcp/hash.lua
new file mode 100644
index 0000000..7ba2438
--- /dev/null
+++ b/panto_mcp/hash.lua
@@ -0,0 +1,41 @@
+-- SHA-256 over bytes, returning lowercase hexadecimal (Lua 5.4 integers).
+local M = {}
+local K={
+ 0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,
+ 0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,
+ 0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,
+ 0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,
+ 0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,
+ 0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,
+ 0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,
+ 0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2,
+}
+local function rotate(x,n) return ((x>>n)|(x<<(32-n))) & 0xffffffff end
+function M.sha256(bytes)
+ local size=#bytes
+ bytes=bytes..'\128'..string.rep('\0',(55-size)%64)..string.pack('>I8',size*8)
+ local h={0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19}
+ for offset=1,#bytes,64 do
+ local w={}
+ for i=1,16 do w[i]=string.unpack('>I4',bytes,offset+(i-1)*4) end
+ for i=17,64 do
+ local x,y=w[i-15],w[i-2]
+ local s0=rotate(x,7) ~ rotate(x,18) ~ (x>>3)
+ local s1=rotate(y,17) ~ rotate(y,19) ~ (y>>10)
+ w[i]=(w[i-16]+s0+w[i-7]+s1)&0xffffffff
+ end
+ local a,b,c,d,e,f,g,z=table.unpack(h)
+ for i=1,64 do
+ local s1=rotate(e,6) ~ rotate(e,11) ~ rotate(e,25)
+ local choice=(e&f) ~ ((~e)&g)
+ local t1=(z+s1+choice+K[i]+w[i])&0xffffffff
+ local s0=rotate(a,2) ~ rotate(a,13) ~ rotate(a,22)
+ local majority=(a&b) ~ (a&c) ~ (b&c)
+ z,g,f,e,d,c,b,a=g,f,e,(d+t1)&0xffffffff,c,b,a,(t1+s0+majority)&0xffffffff
+ end
+ for i,v in ipairs({a,b,c,d,e,f,g,z}) do h[i]=(h[i]+v)&0xffffffff end
+ end
+ local out={}; for i,v in ipairs(h) do out[i]=string.format('%08x',v) end
+ return table.concat(out)
+end
+return M
diff --git a/panto_mcp/http.lua b/panto_mcp/http.lua
new file mode 100644
index 0000000..206e2d5
--- /dev/null
+++ b/panto_mcp/http.lua
@@ -0,0 +1,680 @@
+local json = require('panto').ext.json
+local async = require('panto_mcp.async')
+local M = {}
+local Transport = {}; Transport.__index = Transport
+local MAX_BODY,MAX_ERROR_BODY,FIRE_TIMEOUT_MS=16*1024*1024,1024,10000
+local method_support=setmetatable({}, {__mode='k'})
+
+local function cancel_handle(handle)
+ if handle and type(handle.cancel)=='function' then pcall(handle.cancel,handle) end
+end
+local function newer_error()
+ return 'URL MCP servers require a newer panto with HTTP POST and streaming support'
+end
+M.newer_error=newer_error
+function M.methods_supported(request_fn)
+ if type(request_fn)~='function' then return false end
+ local cached=method_support[request_fn]
+ if cached~=nil then return cached end
+ -- A supported API rejects OPTIONS during parsing, before opening a socket.
+ local ok,handle,err=pcall(request_fn,{url='http://127.0.0.1:1/',method='OPTIONS',timeout_ms=1},function() end)
+ local supported=ok and not handle and type(err)=='string' and err:find('invalid HTTP request options',1,true)~=nil
+ if handle then cancel_handle(handle) end
+ method_support[request_fn]=not not supported
+ return not not supported
+end
+
+local function header_value(headers,name)
+ local value=headers and headers[name:lower()]
+ if type(value)=='table' then return value[1] end
+ return value
+end
+local function set_header(out,lower,name,value)
+ local key=name:lower()
+ if lower[key] then out[lower[key]]=nil end
+ lower[key]=name; out[name]=value
+end
+local function remove_header(out,lower,name)
+ local key=name:lower()
+ if lower[key] then out[lower[key]]=nil; lower[key]=nil end
+end
+local function b64(value)
+ local alphabet='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
+ local out={}
+ for i=1,#value,3 do
+ local a,b,c=value:byte(i,i+2); b=b or 0; c=c or 0
+ local n=(a<<16)|(b<<8)|c
+ out[#out+1]=alphabet:sub(((n>>18)&63)+1,((n>>18)&63)+1)
+ out[#out+1]=alphabet:sub(((n>>12)&63)+1,((n>>12)&63)+1)
+ out[#out+1]=i+1<=#value and alphabet:sub(((n>>6)&63)+1,((n>>6)&63)+1) or '='
+ out[#out+1]=i+2<=#value and alphabet:sub((n&63)+1,(n&63)+1) or '='
+ end
+ return table.concat(out)
+end
+local function encode_value(value)
+ local safe=not (value:match('^[ \t]') or value:match('[ \t]$') or
+ (value:sub(1,9)=='=?base64?' and value:sub(-2)=='?='))
+ if safe then
+ for i=1,#value do local b=value:byte(i); if not (b==9 or b==32 or (b>=33 and b<=126)) then safe=false; break end end
+ end
+ if safe then return value end
+ return '=?base64?'..b64(value)..'?='
+end
+M.encode_header_value=encode_value
+
+local tchar={}
+for c in ('!#$%&\'*+-.^_`|~'):gmatch('.') do tchar[c]=true end
+local function valid_token(value)
+ if type(value)~='string' or value=='' then return false end
+ for i=1,#value do
+ local b=value:byte(i)
+ if not ((b>=48 and b<=57) or (b>=65 and b<=90) or (b>=97 and b<=122) or tchar[value:sub(i,i)]) then return false end
+ end
+ return true
+end
+function M.validate_param_headers(schema)
+ local found,seen,reason={}, {}, nil
+ local total,reachable=0,0
+ local instance_data={enum=true,const=true,default=true,examples=true}
+ local function reject(text) reason=reason or text end
+ local function count(value)
+ if type(value)~='table' then return end
+ if value['x-mcp-header']~=nil then total=total+1 end
+ for key,child in pairs(value) do
+ if key=='properties' or key=='patternProperties' or key=='dependentSchemas' or key=='dependencies' or key=='$defs' or key=='definitions' then
+ if type(child)=='table' then for _,nested in pairs(child) do count(nested) end end
+ elseif not instance_data[key] then count(child) end
+ end
+ end
+ local function get_type(value)
+ local types={}
+ if type(value)=='string' then types[1]=value
+ elseif type(value)=='table' then
+ local n=0
+ for k,t in pairs(value) do
+ if type(k)~='number' or k<1 or k%1~=0 or type(t)~='string' then return nil end
+ n=n+1; types[#types+1]=t
+ end
+ if n~=#value then return nil end
+ else return nil end
+ local base
+ for _,t in ipairs(types) do
+ if t~='null' then
+ if base then return nil end
+ base=t
+ end
+ end
+ if base=='string' or base=='integer' or base=='boolean' then return base end
+ return nil
+ end
+ local function walk(node,path,reachable_path)
+ if type(node)~='table' then return end
+ local name=node['x-mcp-header']
+ if name~=nil and reachable_path then
+ reachable=reachable+1
+ local primitive=get_type(node.type)
+ if #path==0 then reject('x-mcp-header must annotate a parameter property')
+ elseif not valid_token(name) then reject('x-mcp-header must be an HTTP token')
+ elseif not primitive then reject('x-mcp-header requires string, integer, or boolean')
+ else
+ local key=name:lower()
+ if seen[key] then reject('x-mcp-header names must be case-insensitively unique')
+ else seen[key]=true; found[#found+1]={name=name,path=path,type=primitive} end
+ end
+ end
+ local properties=node.properties
+ if type(properties)=='table' then
+ for property,child in pairs(properties) do
+ if type(property)=='string' and type(child)=='table' then
+ local nested={}; for i,v in ipairs(path) do nested[i]=v end; nested[#nested+1]=property
+ walk(child,nested,reachable_path)
+ elseif type(child)=='table' then walk(child,path,false) end
+ end
+ end
+ end
+ count(schema); walk(schema,{},true)
+ if total~=reachable then reject('x-mcp-header is not statically reachable through properties') end
+ if reason then return nil,reason end
+ return found
+end
+function M.filter_tools(tools,server,quiet)
+ local filtered,headers=json.array({}),{}
+ for _,tool in ipairs(tools or {}) do
+ local annotations,why=M.validate_param_headers(type(tool)=='table' and tool.inputSchema or nil)
+ if annotations then
+ filtered[#filtered+1]=tool
+ if #annotations>0 and type(tool)=='table' and type(tool.name)=='string' then headers[tool.name]=annotations end
+ else
+ local name=type(tool)=='table' and tostring(tool.name or '?') or '?'
+ name=name:gsub('[%z\1-\31\127]','?'):sub(1,100)
+ if not quiet then io.stderr:write('panto-mcp: ',tostring(server),': excluded tool ',name,': invalid x-mcp-header (',why,')\n') end
+ end
+ end
+ return filtered,headers
+end
+local function param_value(spec,arguments)
+ local value=arguments
+ for _,key in ipairs(spec.path) do if type(value)~='table' then return nil end; value=value[key] end
+ if value==nil or value==json.null then return nil end
+ if spec.type=='string' then
+ if type(value)~='string' then return nil,'must be a string' end
+ elseif spec.type=='boolean' then
+ if type(value)~='boolean' then return nil,'must be a boolean' end
+ value=value and 'true' or 'false'
+ elseif spec.type=='integer' then
+ if type(value)~='number' or value%1~=0 or math.abs(value)>9007199254740991 then return nil,'must be a safe integer' end
+ value=string.format('%.0f',value)
+ else return nil,'has an unsupported annotated type' end
+ return encode_value(value)
+end
+M.parameter_value=param_value
+function M.headers(cfg,opts,session_id)
+ opts=opts or {}
+ local out,lower={},{}
+ for name,value in pairs(cfg.headers or {}) do set_header(out,lower,name,value) end
+ set_header(out,lower,'Accept','application/json, text/event-stream')
+ set_header(out,lower,'Content-Type','application/json')
+ if opts.era=='modern' then
+ remove_header(out,lower,'Mcp-Session-Id')
+ set_header(out,lower,'MCP-Protocol-Version',opts.protocol_version or '2026-07-28')
+ set_header(out,lower,'Mcp-Method',opts.method or '')
+ remove_header(out,lower,'Mcp-Name')
+ if opts.method=='tools/call' or opts.method=='resources/read' or opts.method=='prompts/get' then
+ if type(opts.name)~='string' then return nil,'Mcp-Name requires a string value' end
+ set_header(out,lower,'Mcp-Name',encode_value(opts.name))
+ end
+ if opts.method=='tools/call' then
+ for _,spec in ipairs(opts.param_headers or {}) do
+ local value,err=param_value(spec,opts.arguments)
+ if err then return nil,'annotated parameter '..table.concat(spec.path,'.')..' '..err end
+ if value~=nil then set_header(out,lower,'Mcp-Param-'..spec.name,value) end
+ end
+ end
+ elseif opts.initial then
+ remove_header(out,lower,'MCP-Protocol-Version'); remove_header(out,lower,'Mcp-Session-Id')
+ remove_header(out,lower,'Mcp-Method'); remove_header(out,lower,'Mcp-Name')
+ else
+ remove_header(out,lower,'Mcp-Method'); remove_header(out,lower,'Mcp-Name')
+ set_header(out,lower,'MCP-Protocol-Version',opts.protocol_version or '2025-11-25')
+ if session_id then set_header(out,lower,'Mcp-Session-Id',session_id) end
+ end
+ return out
+end
+
+-- Processes each input byte once; only the current line and event are retained.
+function M.sse_parser(on_event,max_bytes)
+ local line_parts,data_lines,line_bytes,event_bytes= {},{},0,0
+ local event_type,skip_lf,bom_started,bom_pending=nil,false,false,''
+ max_bytes=max_bytes or MAX_BODY
+ local function append_line(part)
+ if part~='' then line_parts[#line_parts+1]=part; line_bytes=line_bytes+#part end
+ if line_bytes>max_bytes then error('SSE line exceeds size limit',0) end
+ end
+ local function dispatch_event()
+ if #data_lines>0 then
+ local data=table.concat(data_lines,'\n')
+ if data~='' and (event_type==nil or event_type=='' or event_type=='message') then on_event(data,event_type) end
+ end
+ data_lines={}; event_type=nil; event_bytes=0
+ end
+ local function process_line()
+ local value=table.concat(line_parts); line_parts={}; line_bytes=0
+ if value=='' then dispatch_event(); return end
+ if value:sub(1,1)==':' then return end
+ local colon=value:find(':',1,true); local field,content
+ if colon then field,content=value:sub(1,colon-1),value:sub(colon+1); if content:sub(1,1)==' ' then content=content:sub(2) end
+ else field,content=value,'' end
+ if field=='data' then
+ event_bytes=event_bytes+#content+1
+ if event_bytes>max_bytes then error('SSE event exceeds size limit',0) end
+ data_lines[#data_lines+1]=content
+ elseif field=='event' then event_type=content end
+ end
+ local function process(chunk)
+ local i=1
+ if skip_lf then
+ if chunk=='' then return end
+ if chunk:sub(1,1)=='\n' then i=2 end
+ skip_lf=false
+ end
+ while i<=#chunk do
+ local at=chunk:find('[\r\n]',i)
+ if not at then append_line(chunk:sub(i)); break end
+ append_line(chunk:sub(i,at-1))
+ local is_cr=chunk:sub(at,at)=='\r'
+ if is_cr and chunk:sub(at+1,at+1)=='\n' then i=at+2
+ else i=at+1; if is_cr and i>#chunk then skip_lf=true end end
+ process_line()
+ end
+ end
+ local parser={}
+ function parser:feed(chunk)
+ if type(chunk)~='string' then return nil,'invalid SSE chunk' end
+ if not bom_started then
+ bom_pending=bom_pending..chunk
+ if #bom_pending<3 then return true end
+ if bom_pending:sub(1,3)=='\239\187\191' then bom_pending=bom_pending:sub(4) end
+ chunk=bom_pending; bom_pending=''; bom_started=true
+ end
+ local ok,err=pcall(process,chunk); if not ok then return nil,err end
+ return true
+ end
+ function parser:finish()
+ if not bom_started then
+ local chunk=bom_pending; bom_pending=''; bom_started=true
+ if chunk:sub(1,3)=='\239\187\191' then chunk=chunk:sub(4) end
+ local ok,err=pcall(process,chunk); if not ok then return nil,err end
+ end
+ if #line_parts>0 then local ok,err=pcall(process_line); if not ok then return nil,err end end
+ local ok,err=pcall(dispatch_event); if not ok then return nil,err end
+ return true
+ end
+ return parser
+end
+
+local function decode_message(body)
+ if not body or body=='' then return nil end
+ local ok,msg=pcall(json.decode,body)
+ if ok and type(msg)=='table' then return msg end
+ return nil
+end
+local function is_sse(headers)
+ local value=header_value(headers,'content-type')
+ return type(value)=='string' and value:lower():match('^%s*text/event%-stream')~=nil
+end
+local function escaped_pattern(value) return value:gsub('([^%w])','%%%1') end
+local function redact(text,headers)
+ text=text or ''
+ for name,value in pairs(headers or {}) do
+ if type(value)=='string' and value~='' then
+ text=text:gsub(escaped_pattern(value),'[redacted]')
+ if name:lower()=='authorization' then
+ local token=value:match('^%s*%S+%s+(%S+)%s*$')
+ if token and token~='' then text=text:gsub(escaped_pattern(token),'[redacted]') end
+ end
+ end
+ end
+ return text:sub(1,MAX_ERROR_BODY)
+end
+local function prefix_error(server,method,text)
+ return tostring(server)..' '..tostring(method or 'HTTP')..': '..tostring(text)
+end
+local function failure_kind(err)
+ local text=tostring(err or '')
+ if text:match('^on_head callback failed:') or text:match('^on_data callback failed:') then return 'callback' end
+ if text=='timeout' then return 'timeout' end
+ if text=='idle timeout' then return 'idle_timeout' end
+ return 'transport'
+end
+M.failure_kind=failure_kind
+function M.should_fallback(err)
+ if type(err)=='table' then
+ local data=type(err.data)=='table' and err.data or {}
+ if data.session_expired or data.auth_error or data.http_status==401 or data.http_status==403 then return false end
+ if err.code==-32020 or err.code==-32021 or err.code==-32022 or data.supported then return false end
+ if data.http_status then return data.transport_fallback==true end
+ if data.transport_error=='timeout' or data.transport_error=='idle_timeout' then return true end
+ return false
+ end
+ local kind=failure_kind(err)
+ return kind=='timeout' or kind=='idle_timeout' or (type(err)=='string' and
+ (err:match('^request timed out:')~=nil or err:match('^[^%s]+ [^:]+: request timed out:')~=nil))
+end
+function M.new(cfg,settings,opts)
+ opts=opts or {}; settings=settings or {}
+ local request_fn=opts.request_fn
+ if not request_fn then
+ local ext=require('panto').ext
+ request_fn=ext and ext.http_request
+ if type(request_fn)~='function' or not M.methods_supported(request_fn) then return nil,newer_error() end
+ end
+ return setmetatable({cfg=cfg,settings=settings,request_fn=request_fn,
+ timer_factory=opts.timer_factory or async.timer,active={},sequence=0,closed=false,
+ session_id=nil,protocol_version=nil,era=nil,session_generation=0,initialize_params=nil,
+ on_message=nil,on_error=nil,oauth=opts.oauth,
+ on_notification_stream_end=opts.on_notification_stream_end},Transport)
+end
+function Transport:set_callbacks(message,err) self.on_message=message; self.on_error=err end
+function Transport:auth_name()
+ if self.oauth then return self.oauth:request_auth() end
+ return self.cfg.auth
+end
+
+function Transport:_clear_state(state)
+ if state.done then return end
+ state.done=true; self.active[state.key]=nil
+ local op=state.op
+ if op then async.close(op.idle_timer); async.close(op.fire_timer) end
+end
+function Transport:_log_failure(text)
+ self.stderr_tail=((self.stderr_tail or '')..text..'\n'):sub(-8192)
+ io.stderr:write('panto-mcp: ',text,'\n')
+end
+function Transport:_finish_handshake(state,ok,err)
+ if state.handshake_future and not state.handshake_future.done then state.handshake_future:resolve(ok,err) end
+end
+function Transport:_emit_error(state,message,text,data)
+ if state.done or state.cancelled then return end
+ local method=(message and message.method) or state.opts.method
+ text=redact(prefix_error(self.cfg.name,method,text),self.cfg.headers)
+ self:_clear_state(state)
+ if state.fire_and_forget then
+ if state.handshake_notification then self:_finish_handshake(state,nil,text) else self:_log_failure(text) end
+ elseif message and message.id~=nil then
+ if self.on_message then self.on_message({jsonrpc='2.0',id=message.id,error={code=-32000,message=text,data=data}}) end
+ else self:_log_failure(text) end
+end
+function Transport:_deliver(state,message)
+ if type(message)~='table' or message.jsonrpc~='2.0' then
+ self:_emit_error(state,state.message,'invalid JSON-RPC message'); return
+ end
+ if type(message.error)=='table' and type(message.error.message)=='string' then
+ message.error.message=redact(message.error.message,self.cfg.headers)
+ if not state.fire_and_forget then message.error.message=prefix_error(self.cfg.name,state.opts.method,message.error.message) end
+ end
+ if state.fire_and_forget then
+ if message.error then self:_emit_error(state,state.message,message.error.message or 'JSON-RPC error on fire-and-forget POST') end
+ return
+ end
+ if message.method==nil and message.error~=nil and (message.id==nil or message.id==json.null) and state.message.id~=nil then
+ message.id=state.message.id
+ end
+ local is_response=message.method==nil and message.id~=nil and message.id==state.message.id
+ if is_response and message.result==nil and message.error==nil then
+ self:_emit_error(state,state.message,'malformed JSON-RPC response'); return
+ end
+ if is_response then state.got_response=true end
+ if self.on_message then self.on_message(message) end
+ if state.got_response then
+ local handle=state.op and state.op.handle
+ self:_clear_state(state); cancel_handle(handle)
+ end
+end
+function Transport:_delete_session(session_id)
+ if not session_id then return end
+ local headers=M.headers(self.cfg,{era='legacy',protocol_version=self.protocol_version or '2025-11-25'},session_id)
+ pcall(self.request_fn,{url=self.cfg.url,method='DELETE',auth=self:auth_name(),headers=headers,timeout_ms=1000,max_bytes=1024},function() end)
+end
+function Transport:_session_expired(state,message,session_id,generation)
+ if self.session_id==session_id then self.session_id=nil end
+ self:_emit_error(state,message,'session expired',{session_expired=true,http_status=404,session_generation=generation})
+end
+function Transport:_start_http(state,message,opts,on_done)
+ if state.cancelled or state.done or self.closed then return end
+ local initial=opts.era=='legacy' and message.method=='initialize'
+ local session_id=initial and nil or self.session_id
+ local headers,header_err=M.headers(self.cfg,{era=opts.era,protocol_version=opts.protocol_version,
+ method=message.method or opts.method,name=(message.params and (message.params.name or message.params.uri)) or opts.name,
+ param_headers=opts.param_headers,arguments=message.params and message.params.arguments,initial=initial},session_id)
+ if not headers then self:_emit_error(state,message,header_err); return end
+ local op={body_parts={},body_len=0,sse=false,parser=nil,handle=nil,headers={},status=0,
+ session_id=session_id,session_generation=self.session_generation or 0,idle_timer=nil,fire_timer=nil}
+ state.op=op
+ local request_options={url=self.cfg.url,method='POST',body=json.encode(message),auth=self:auth_name(),headers=headers,
+ timeout_ms=0,idle_timeout_ms=0,max_bytes=MAX_BODY}
+ op.auth_used=request_options.auth~=nil
+ local function reset_idle()
+ async.close(op.idle_timer); op.idle_timer=nil
+ local idle=self.settings.idle_timeout_ms or 60000
+ if idle>0 and op.sse and op.status>=200 and op.status<300 and not state.done and not state.cancelled then
+ op.idle_timer=self.timer_factory(idle,function()
+ cancel_handle(op.handle)
+ self:_emit_error(state,message,'idle timeout',{transport_error='idle_timeout',idle_timeout=true})
+ end)
+ end
+ end
+ request_options.on_head=function(head)
+ if state.cancelled or state.done or self.closed then cancel_handle(op.handle); return end
+ op.status=head.status or 0; op.headers=head.headers or {}; op.sse=is_sse(op.headers)
+ if opts.era=='legacy' and message.method=='initialize' then
+ self.session_id=header_value(op.headers,'mcp-session-id')
+ self.protocol_version=opts.protocol_version
+ self.session_generation=(self.session_generation or 0)+1
+ end
+ if op.sse then
+ op.parser=M.sse_parser(function(data)
+ local msg=decode_message(data)
+ if not msg then self:_emit_error(state,message,'invalid JSON in SSE event'); return end
+ self:_deliver(state,msg)
+ end,MAX_BODY)
+ reset_idle()
+ end
+ end
+ request_options.on_data=function(chunk)
+ if state.done or state.cancelled or self.closed then return end
+ if op.sse and op.parser and op.status>=200 and op.status<300 then
+ reset_idle()
+ local ok,err=op.parser:feed(chunk)
+ if not ok then self:_emit_error(state,message,err); cancel_handle(op.handle) end
+ else
+ if op.body_len+#chunk>MAX_BODY then
+ if op.status>=400 then self:_http_failure(state,message,op.status,table.concat(op.body_parts),nil,opts)
+ else self:_emit_error(state,message,'HTTP response exceeds size limit') end
+ cancel_handle(op.handle); return
+ end
+ op.body_parts[#op.body_parts+1]=chunk; op.body_len=op.body_len+#chunk
+ end
+ end
+ local function complete(response,request_error)
+ if state.done or state.cancelled or state.op~=op then return end
+ async.close(op.idle_timer); op.idle_timer=nil; async.close(op.fire_timer); op.fire_timer=nil
+ if request_error then on_done(nil,nil,tostring(request_error),op); return end
+ if response then
+ op.status=response.status or op.status; op.headers=response.headers or op.headers
+ if response.body and response.body~='' then op.body_parts[#op.body_parts+1]=response.body; op.body_len=op.body_len+#response.body end
+ end
+ if op.sse and op.parser then
+ local ok,err=op.parser:finish()
+ if not ok then op.parse_error=err end
+ end
+ local body=table.concat(op.body_parts)
+ local msg
+ if not op.sse or op.status<200 or op.status>=300 then msg=decode_message(body) end
+ if msg and not state.fire_and_forget and op.status>=200 and op.status<300 and msg.id==message.id then self:_deliver(state,msg) end
+ on_done({status=op.status,headers=op.headers,body=body},msg,op.parse_error,op)
+ end
+ local ok,handle,err=pcall(self.request_fn,request_options,complete)
+ if not ok then complete(nil,handle); return end
+ if not handle then complete(nil,err or 'HTTP request could not start'); return end
+ op.handle=handle
+ if state.op==op and not state.done and not state.cancelled then
+ if state.fire_and_forget then
+ op.fire_timer=self.timer_factory(FIRE_TIMEOUT_MS,function()
+ cancel_handle(op.handle); self:_emit_error(state,message,'request timed out',{transport_error='timeout'})
+ end)
+ end
+ else cancel_handle(handle) end
+end
+function Transport:_http_failure(state,message,status,body,jsonrpc_error,opts)
+ if status==401 or status==403 then
+ if self.oauth then
+ local op=state.op or {}
+ local text=status==403 and 'Forbidden (HTTP 403); check server permissions' or
+ (self.cfg.auth and self.oauth:configured_error() or self.oauth:login_error())
+ self:_emit_error(state,message,text,{http_status=status,auth_error=true,
+ challenge=require('panto_mcp.oauth').challenge(header_value(op.headers,'www-authenticate')),auth_used=op.auth_used})
+ return
+ end
+ local text=status==403 and 'Forbidden (HTTP 403); check server permissions' or
+ string.format('requires authentication (HTTP 401); configure auth = "<session>" in [mcp.servers.%s]',self.cfg.name)
+ self:_emit_error(state,message,text,{http_status=status,auth_error=true}); return
+ end
+ if status==404 and opts and opts.era=='legacy' and not state.fire_and_forget and message.method and state.op and state.op.session_id then
+ self:_session_expired(state,message,state.op.session_id,state.op.session_generation); return
+ end
+ if jsonrpc_error then
+ local error_text=state.op and state.op.auth_used and ('HTTP '..status..' JSON-RPC error') or jsonrpc_error.message
+ if state.fire_and_forget then self:_emit_error(state,message,error_text or 'HTTP JSON-RPC error',{http_status=status}); return end
+ local data=type(jsonrpc_error.data)=='table' and jsonrpc_error.data or {}
+ data.http_status=status
+ data.transport_fallback=(status==400 or status==404 or status==405) and
+ jsonrpc_error.code~=-32020 and jsonrpc_error.code~=-32021 and jsonrpc_error.code~=-32022 and
+ not (status==404 and jsonrpc_error.code==-32601 and message.method~='server/discover')
+ local text=redact(error_text or 'HTTP JSON-RPC error',self.cfg.headers)
+ self:_clear_state(state)
+ if self.on_message then self.on_message({jsonrpc='2.0',id=message.id,error={code=jsonrpc_error.code,message=prefix_error(self.cfg.name,message.method or state.opts.method,text),data=data}}) end
+ return
+ end
+ local body_text=state.op and state.op.auth_used and '' or redact(body,self.cfg.headers)
+ local text=string.format('HTTP %d%s',status,body_text~='' and ': '..body_text or '')
+ self:_emit_error(state,message,text,{http_status=status,transport_fallback=status==400 or status==404 or status==405})
+end
+function Transport:_main_complete(state,message,opts,response,msg,err,op)
+ if state.done or state.cancelled then return end
+ local status=response and response.status or (op and op.status) or 0
+ if err then
+ if status==404 and opts.era=='legacy' and not state.fire_and_forget and message.method and op and op.session_id then
+ self:_session_expired(state,message,op.session_id,op.session_generation); return
+ end
+ if status>=400 then self:_http_failure(state,message,status,op and table.concat(op.body_parts),nil,opts)
+ else
+ local kind=failure_kind(err)
+ self:_emit_error(state,message,err,{transport_error=kind,timeout=kind=='timeout',idle_timeout=kind=='idle_timeout'})
+ end
+ return
+ end
+ if status==404 and opts.era=='legacy' and not state.fire_and_forget and message.method and op and op.session_id then
+ self:_session_expired(state,message,op.session_id,op.session_generation); return
+ end
+ if status<200 or status>=300 then
+ local null_id=msg and (msg.id==nil or msg.id==json.null)
+ if msg and msg.error and (msg.id==message.id or null_id) then self:_http_failure(state,message,status,response.body,msg.error,opts)
+ else self:_http_failure(state,message,status,response and response.body,nil,opts) end
+ return
+ end
+ if state.fire_and_forget then
+ if msg and msg.error then
+ self:_emit_error(state,message,msg.error.message or 'JSON-RPC error on fire-and-forget POST')
+ else
+ self:_clear_state(state)
+ if state.handshake_notification then self:_finish_handshake(state,true) end
+ end
+ return
+ end
+ if op.sse then
+ if message.id~=nil and not state.got_response then self:_emit_error(state,message,'HTTP SSE stream ended without a response for this request',{http_status=status})
+ elseif not state.done then self:_clear_state(state) end
+ return
+ end
+ if message.id~=nil and not state.got_response then
+ self:_emit_error(state,message,'HTTP response did not contain this request\'s JSON-RPC response',{http_status=status})
+ elseif not state.done then self:_clear_state(state) end
+end
+function Transport:send(message,opts)
+ if self.closed then return nil,'HTTP transport closed' end
+ opts=opts or {}
+ local current_era=opts.era or self.era
+ if message.method==nil and current_era=='modern' then return {} end
+ self.sequence=self.sequence+1
+ local fire=message.method==nil or message.id==nil
+ local key=fire and ('fire:'..self.sequence) or ('id:'..tostring(message.id))
+ local effective={era=opts.era or self.era,protocol_version=opts.protocol_version or self.protocol_version,
+ method=opts.method or message.method,name=opts.name,param_headers=opts.param_headers,arguments=opts.arguments}
+ if opts.era then self.era=opts.era end
+ if opts.protocol_version then self.protocol_version=opts.protocol_version end
+ local handshake_notification=effective.era=='legacy' and message.method=='notifications/initialized'
+ local state={key=key,message=message,opts=effective,fire_and_forget=fire,handshake_notification=handshake_notification,cancelled=false,done=false,got_response=false}
+ if handshake_notification then
+ state.handshake_future=async.future()
+ function state:await() return self.handshake_future:await() end
+ end
+ self.active[key]=state
+ if effective.era=='legacy' and message.method=='initialize' then self.initialize_params=message.params or {} end
+ self:_start_http(state,message,effective,function(response,result,err,op)
+ self:_main_complete(state,message,effective,response,result,err,op)
+ end)
+ return state
+end
+local function cancel_state(self,id,handle,notify)
+ local state=self.active['id:'..tostring(id)] or handle
+ if not state then return end
+ local was_legacy=state.opts.era=='legacy'
+ local method=state.message and state.message.method
+ local version=state.opts.protocol_version or self.protocol_version
+ state.cancelled=true; self.active[state.key]=nil
+ local op=state.op; if op then async.close(op.idle_timer); async.close(op.fire_timer); cancel_handle(op.handle) end
+ if notify and was_legacy and state.op and state.op.session_generation==self.session_generation and
+ method and method~='initialize' and method~='notifications/cancelled' and not self.closed then
+ self:send({jsonrpc='2.0',method='notifications/cancelled',params={requestId=id,reason='request cancelled'}},
+ {era='legacy',protocol_version=version,method='notifications/cancelled'})
+ end
+end
+function Transport:open_notification_stream()
+ if self.closed or self.notification_stream then return false end
+ local headers=M.headers(self.cfg,{era='legacy',protocol_version=self.protocol_version or '2025-11-25'},self.session_id)
+ headers.Accept='text/event-stream'
+ headers['Content-Type']=nil
+ local stream={status=0,ignore=false,handle=nil,parser=nil}
+ self.notification_stream=stream
+ local function finish()
+ if self.notification_stream~=stream then return end
+ self.notification_stream=nil
+ if stream.status~=405 and not self.closed and self.on_notification_stream_end then
+ pcall(self.on_notification_stream_end,stream.status)
+ end
+ end
+ local options={url=self.cfg.url,method='GET',auth=self:auth_name(),headers=headers,
+ timeout_ms=0,idle_timeout_ms=0}
+ options.on_head=function(head)
+ if self.closed or self.notification_stream~=stream then return end
+ stream.status=head.status or 0
+ if stream.status<200 or stream.status>=300 then
+ stream.ignore=true
+ cancel_handle(stream.handle)
+ finish()
+ return
+ end
+ stream.opened=true
+ stream.parser=M.sse_parser(function(data)
+ local message=decode_message(data)
+ if message and self.on_message and not self.closed then self.on_message(message) end
+ end,MAX_BODY)
+ end
+ options.on_data=function(chunk)
+ if self.closed or stream.ignore or self.notification_stream~=stream or not stream.parser then return end
+ local ok=stream.parser:feed(chunk)
+ if not ok then stream.ignore=true; cancel_handle(stream.handle); finish() end
+ end
+ local ok,handle=pcall(self.request_fn,options,function()
+ if self.notification_stream~=stream then return end
+ if stream.parser and not stream.ignore then pcall(stream.parser.finish,stream.parser) end
+ finish()
+ end)
+ if not ok or not handle then finish(); return false end
+ stream.handle=handle
+ if self.closed or self.notification_stream~=stream or stream.ignore then cancel_handle(handle); return false end
+ return true
+end
+function Transport:close_notification_stream()
+ local stream=self.notification_stream
+ if not stream then return end
+ self.notification_stream=nil; stream.ignore=true
+ cancel_handle(stream.handle)
+end
+function Transport:cancel_request(id,handle) cancel_state(self,id,handle,false) end
+function Transport:cancel(id,handle) cancel_state(self,id,handle,true) end
+function Transport:fail(err)
+ if self.closed then return end
+ self.closed=true
+ if self.notification_stream then self:close_notification_stream() end
+ for _,state in pairs(self.active) do
+ state.cancelled=true
+ if state.handshake_future then self:_finish_handshake(state,nil,'HTTP transport closed') end
+ if state.op then async.close(state.op.idle_timer); async.close(state.op.fire_timer); cancel_handle(state.op.handle) end
+ end
+ self.active={}; if self.on_error then self.on_error(err) end
+end
+function Transport:close()
+ if self.did_close then return end
+ self.did_close=true
+ if self.notification_stream then self:close_notification_stream() end
+ local session=self.session_id
+ for _,state in pairs(self.active) do
+ state.cancelled=true
+ if state.handshake_future then self:_finish_handshake(state,nil,'HTTP transport closed') end
+ if state.op then async.close(state.op.idle_timer); async.close(state.op.fire_timer); cancel_handle(state.op.handle) end
+ end
+ self.active={}; self.closed=true
+ self:_delete_session(session)
+end
+return M
diff --git a/panto_mcp/jsonrpc.lua b/panto_mcp/jsonrpc.lua
new file mode 100644
index 0000000..714c137
--- /dev/null
+++ b/panto_mcp/jsonrpc.lua
@@ -0,0 +1,75 @@
+-- Transport contract (shared with future HTTP):
+-- t:set_callbacks(on_message, on_error); t:send(message, opts) -> handle|nil, err
+-- t:cancel(id, handle); t:close() (nonblocking).
+-- cancel_request cancels a transport handle without sending an MCP-level notice.
+-- `cancel` additionally permits a transport-specific cancellation notification.
+-- opts = {era, protocol_version, method, name, param_headers?};
+-- on_error means the whole transport failed, not a request-level RPC error.
+local async = require('panto_mcp.async')
+local json = require('panto').ext.json
+local M = {}; M.__index = M
+function M.new(transport, opts)
+ opts=opts or {}
+ local self=setmetatable({transport=transport, next_id=0, pending={},
+ timeout_ms=opts.timeout_ms or 300000, timer_factory=opts.timer_factory or async.timer,
+ on_notification=opts.on_notification, on_error=opts.on_error},M)
+ transport:set_callbacks(function(msg) self:receive(msg) end, function(err) self:fail(err) end)
+ return self
+end
+function M:finish(id, value, err)
+ local p=self.pending[id]; if not p then return end
+ self.pending[id]=nil
+ async.close(p.timer)
+ p.future:resolve(value,err)
+end
+function M:receive(msg)
+ if self.closed then return end
+ if type(msg)~='table' or msg.jsonrpc~='2.0' then self:fail('malformed JSON-RPC message'); return end
+ if type(msg.method)=='string' then
+ if msg.id~=nil then
+ local reply={jsonrpc='2.0',id=msg.id}
+ if msg.method=='ping' then reply.result={} else reply.error={code=-32601,message='Method not found'} end
+ self.transport:send(reply,{method=msg.method})
+ elseif self.on_notification then self.on_notification(msg.method,msg.params) end
+ elseif msg.id~=nil and (msg.result~=nil or msg.error~=nil) then
+ self:finish(msg.id,msg.result,msg.error)
+ else self:fail('malformed JSON-RPC response') end
+end
+function M:start(method, params, opts)
+ opts=opts or {}; opts.method=method
+ if self.closed then local f=async.future(); f:resolve(nil,self.error or 'connection closed'); return f end
+ self.next_id=self.next_id+1
+ local id=self.next_id
+ local future=async.future(function() self:cancel(id,'request cancelled') end)
+ local p={future=future,cancel_protocol=opts.cancel_protocol}; self.pending[id]=p
+ p.timer=self.timer_factory(opts.timeout_ms or self.timeout_ms,function() self:cancel(id,'request timed out: ' .. method) end)
+ local ok,h,err=pcall(self.transport.send,self.transport,{jsonrpc='2.0',id=id,method=method,params=params or {}},opts)
+ if not ok or not h then self:finish(id,nil,not ok and h or err or 'send failed') else p.handle=h end
+ return future
+end
+function M:request(method,params,opts) return self:start(method,params,opts):await() end
+function M:notify(method,params,opts)
+ if self.closed then return nil,self.error end
+ opts=opts or {}; opts.method=method
+ return self.transport:send({jsonrpc='2.0',method=method,params=params or {}},opts)
+end
+function M:cancel(id,reason)
+ local p=self.pending[id]; if not p then return end
+ self.pending[id]=nil; async.close(p.timer)
+ if p.cancel_protocol~=false then pcall(self.transport.cancel,self.transport,id,p.handle)
+ elseif type(self.transport.cancel_request)=='function' then pcall(self.transport.cancel_request,self.transport,id,p.handle) end
+ p.future:resolve(nil,reason or 'request cancelled')
+end
+function M:fail(err,abandon)
+ if self.closed then return end
+ self.closed=true; self.error=err or 'connection closed'
+ local pending=self.pending; self.pending={}
+ for _,p in pairs(pending) do
+ async.close(p.timer)
+ if abandon then p.future:abandon(nil,self.error) else p.future:resolve(nil,self.error) end
+ end
+ self.transport:close()
+ if self.on_error then self.on_error(self.error) end
+end
+function M:close(abandon) self:fail('connection closed',abandon) end
+return M
diff --git a/panto_mcp/manager.lua b/panto_mcp/manager.lua
new file mode 100644
index 0000000..a76e7bf
--- /dev/null
+++ b/panto_mcp/manager.lua
@@ -0,0 +1,229 @@
+local async = require('panto_mcp.async')
+local Client = require('panto_mcp.client')
+local cache = require('panto_mcp.cache')
+local search = require('panto_mcp.search')
+local config = require('panto_mcp.config')
+local results = require('panto_mcp.results')
+local validate = require('panto_mcp.validate')
+local json = require('panto').ext.json
+local M = {}; M.__index=M
+function M.new(settings,servers,opts)
+ opts=opts or {}
+ local self=setmetatable({settings=settings,states={},opts=opts},M)
+ for name,cfg in pairs(servers) do
+ local metadata=cache.load(cfg,opts.cache_dir)
+ if metadata and cfg.transport=='http' and metadata.catalog then
+ metadata.catalog.tools=require('panto_mcp.http').filter_tools(metadata.catalog.tools,cfg.name,true)
+ end
+ self.states[name]={cfg=cfg,state='idle',metadata=metadata,
+ oauth=cfg.transport=='http' and require('panto_mcp.oauth').new(cfg,opts) or nil}
+ end
+ return self
+end
+function M:lookup(name)
+ if type(name)~='string' then return nil,'server must be an exact name' end
+ local state=self.states[name]; if state then return state end
+ local names={}; for n in pairs(self.states) do names[#names+1]=n end
+ return nil,'unknown server ' .. name .. '; closest: ' .. search.closest(name,names)
+end
+function M:start(state)
+ if self.closed then local f=async.future(); f:resolve(nil,'session ended'); return f end
+ if state.state=='connecting' then return state.ready end
+ if state.state=='ready' then local f=async.future(); f:resolve(state.client); return f end
+ state.state='connecting'; state.error=nil
+ local ready=async.future(); state.ready=ready
+ local timer_factory=self.opts.timer_factory or async.timer
+ local timer
+ local function fail(err)
+ if ready.done then return end
+ state.state='failed'; state.error=Client.error_text(err)
+ async.close(timer)
+ -- Resolve the shared startup first: closing RPC resumes the connector.
+ local failed_client=state.client
+ ready:resolve(nil,state.error)
+ if failed_client then failed_client:close() end
+ end
+ local c
+ c=Client.new(state.cfg,self.settings,{
+ transport_factory=self.opts.transport_factory,timer_factory=self.opts.timer_factory,oauth=state.oauth,request_fn=self.opts.request_fn,
+ on_error=function(err)
+ if state.state=='ready' and state.client==c then
+ state.state='failed'; state.error=Client.error_text(err); c:close()
+ end
+ end,
+ on_catalog=function(client)
+ if self.closed or client.closed then return end
+ state.metadata=client:metadata()
+ local _,err=cache.save(state.cfg,state.metadata,self.opts.cache_dir)
+ state.cache_error=err
+ -- E5/E6 hook: reconcile eager tools/prompt commands from this snapshot.
+ if self.opts.on_catalog then self.opts.on_catalog(state.cfg.name,state.metadata) end
+ end,
+ })
+ state.client=c
+ timer=timer_factory(self.settings.startup_timeout_ms,function()
+ fail(state.cfg.transport=='http' and state.cfg.name .. ' server/discover: startup timed out' or 'startup timed out')
+ end)
+ state.timer=timer
+ async.run(function()
+ local ok,err=c:connect(state.metadata)
+ if ready.done or self.closed then c:close(); return end
+ if not ok then fail(err); return end
+ async.close(timer)
+ state.state='ready'; state.error=nil
+ ready:resolve(c)
+ end,fail)
+ return ready
+end
+function M:ensure(name)
+ local state,err=self:lookup(name); if not state then return nil,err end
+ return self:start(state):await()
+end
+function M:start_cold()
+ for _,s in pairs(self.states) do if not s.metadata then self:start(s) end end
+end
+function M:servers()
+ local out=json.array({})
+ for name,s in pairs(self.states) do
+ local meta=s.metadata or {}; local catalog=meta.catalog or {}
+ out[#out+1]={name=name,transport=s.cfg.transport,mode=s.cfg.expose,state=s.state,
+ era=meta.era,version=meta.version,error=s.error,cache_error=s.cache_error,auth=s.oauth and s.oauth:status(),
+ notification_warning=s.client and s.client.notification_warning,
+ tools=#(catalog.tools or {}),prompts=#(catalog.prompts or {}),resources=#(catalog.resources or {}),
+ templates=#(catalog.templates or {}),stderr=s.client and s.client.transport and s.client.transport.stderr_tail or ''}
+ end
+ table.sort(out,function(a,b) return a.name<b.name end)
+ return out
+end
+function M:search(query,opts)
+ opts=opts or {}
+ if query~=nil and type(query)~='string' then return nil,'query must be a string' end
+ if opts.limit~=nil and (type(opts.limit)~='number' or opts.limit%1~=0 or opts.limit<1 or opts.limit>100) then return nil,'limit must be an integer from 1 to 100' end
+ if opts.server then local s,err=self:lookup(opts.server); if not s then return nil,err end end
+ -- Warm search never starts processes; cold activation is already connecting.
+ for name,s in pairs(self.states) do
+ if not opts.server or name==opts.server then
+ if s.state=='failed' or (not s.metadata and s.state=='idle') then self:start(s) end
+ if s.state=='connecting' then s.ready:await() end
+ end
+ end
+ local out=search.search(self.states,query,opts)
+ out.servers=self:servers()
+ for _,server in ipairs(out.servers) do server.stderr=nil end
+ return out
+end
+function M:call(server,tool,input)
+ if type(tool)~='string' or tool=='' then return results.map(tostring(server),nil,'tool must be an exact nonempty name') end
+ local c,err=self:ensure(server)
+ if not c then return results.map(tostring(server),nil,err) end
+ local definition,names=nil,{}
+ for _,t in ipairs(c.catalog.tools) do
+ if config.tool_enabled(c.cfg,t.name or '') then
+ names[#names+1]=t.name
+ if t.name==tool then definition=t end
+ end
+ end
+ if not definition then return results.map(server,nil,'unknown or disabled tool ' .. tool .. '; closest: ' .. search.closest(tool,names)) end
+ if input==nil then input={} end
+ local valid,errors=validate.check(input,definition.inputSchema)
+ if not valid then
+ local out=results.map(server,nil,'input validation failed:\n' .. table.concat(errors,'\n') .. '\nSchema: ' .. json.encode(definition.inputSchema))
+ out.validation_errors=errors; out.schema=definition.inputSchema
+ return out
+ end
+ local result; result,err=c:call(tool,input)
+ return results.map(server,result,err)
+end
+function M:read_resource(server,uri)
+ if type(uri)~='string' or uri=='' then return results.map(tostring(server),nil,'uri must be a nonempty string') end
+ local c,err=self:ensure(server); if not c then return results.map(tostring(server),nil,err) end
+ local result; result,err=c:read_resource(uri)
+ return results.map(server,result,err)
+end
+function M:prompts(server)
+ local c,err=self:ensure(server); if not c then return nil,err end
+ return c.catalog.prompts
+end
+function M:prompt(server,name,args)
+ if type(name)~='string' or name=='' then return nil,'prompt name must be nonempty' end
+ if args~=nil then
+ if type(args)~='table' then return nil,'prompt arguments must be an object of strings' end
+ for k,v in pairs(args) do if type(k)~='string' or type(v)~='string' then return nil,'prompt arguments must be an object of strings' end end
+ end
+ local c,err=self:ensure(server); if not c then return nil,err end
+ local result; result,err=c:prompt(name,args)
+ if not result then return nil,Client.error_text(err) end
+ if result.resultType=='input_required' then return nil,'server requested unsupported user input' end
+ return result.messages
+end
+function M:refresh(name)
+ local names={}
+ if name then local s,err=self:lookup(name); if not s then return nil,err end; names={name}
+ else for n in pairs(self.states) do names[#names+1]=n end; table.sort(names) end
+ local failures={}
+ for _,n in ipairs(names) do
+ local s=self.states[n]
+ if s.state=='ready' then
+ local _,err=s.client:refresh()
+ if err then s.state='failed'; s.error=err; s.client:close(); failures[#failures+1]=n .. ': ' .. err end
+ else local _,err=self:ensure(n); if err then failures[#failures+1]=n .. ': ' .. err end end
+ end
+ if #failures>0 then return nil,table.concat(failures,'\n') end
+ return true
+end
+function M:login(name,callback_url,reregister)
+ local state,err=self:lookup(name); if not state then return err end
+ local oauth=state.oauth
+ if not oauth then return 'OAuth is only available for HTTP servers' end
+ local function reconnect()
+ if self.closed then return end
+ if state.client then state.client:close() end
+ state.state='idle'; state.error=nil
+ self:start(state)
+ end
+ local function present(url)
+ if url==true then return 'OAuth callback accepted; /mcp shows login/reconnect status.' end
+ return 'Open this URL to log in:\n'..url..'\nFor SSH/headless, paste the full callback URL: /mcp-login '..name..' <callback-url>'
+ end
+ if state.login_preparing then return 'OAuth discovery/login preparation started; retry /mcp-login '..name..' to get the URL.' end
+ if oauth.refreshing then return 'OAuth refresh is in progress; retry /mcp-login '..name..' when it finishes.' end
+ local function failed(why) state.error=why end
+ local url,why
+ if reregister and (state.cfg.auth or (state.cfg.oauth and state.cfg.oauth.client_id)) then
+ return '--reregister is only available for automatic public DCR clients.'
+ end
+ if not reregister and (oauth.definition or state.cfg.auth or callback_url) then
+ url,why=oauth:login(callback_url,reconnect,failed)
+ if url or callback_url or state.cfg.auth or not oauth:available() then return url and present(url) or why end
+ end
+ if not oauth:available() then local _,err=oauth:login(nil,reconnect,failed); return err end
+ -- Only missing/failed definitions or an explicit registration reset need discovery.
+ if state.ready and not state.ready.done then state.ready:resolve(nil,'OAuth rediscovery requested') end
+ async.close(state.timer)
+ if state.client then state.client:close() end
+ oauth:invalidate(reregister); state.state='idle'; state.login_preparing=true
+ async.run(function()
+ local _,connect_error=self:start(state):await()
+ if self.closed then return end
+ if oauth.definition then url,why=oauth:login(nil,reconnect,failed)
+ else why=oauth:recovery_error(connect_error or 'OAuth discovery failed') end
+ state.login_preparing=nil
+ if not url then state.error=why end
+ end,function()
+ state.login_preparing=nil; state.error=oauth:recovery_error('OAuth discovery/login preparation failed')
+ end)
+ if url then return present(url) end
+ return why or ('OAuth discovery/login preparation started; retry /mcp-login '..name..' to get the URL.')
+end
+function M:close()
+ if self.closed then return end
+ self.closed=true
+ for _,s in pairs(self.states) do
+ s.state='failed'; s.error='session ended'
+ async.close(s.timer)
+ if s.oauth then s.oauth:close() end
+ if s.ready and not s.ready.done then s.ready:abandon(nil,'session ended') end
+ if s.client then s.client:close(true) end
+ end
+end
+return M
diff --git a/panto_mcp/namespace.lua b/panto_mcp/namespace.lua
new file mode 100644
index 0000000..47e99ed
--- /dev/null
+++ b/panto_mcp/namespace.lua
@@ -0,0 +1,31 @@
+local async = require('panto_mcp.async')
+local M = {}
+function M.factory(manager, _context)
+ -- Unlike delegation, MCP is also available in child agent lanes.
+ local api={}
+ function api.servers() return manager:servers() end
+ function api.search(query,opts) return manager:search(query,opts) end
+ function api.call(server,tool,input) return manager:call(server,tool,input) end
+ function api.start(server,tool,input)
+ local co
+ local future
+ future=async.future(function()
+ if co and coroutine.status(co)~='dead' then coroutine.close(co) end
+ future:resolve(nil,'request cancelled')
+ end)
+ co=async.run(function() future:resolve(manager:call(server,tool,input)) end,
+ function(err) future:resolve(nil,tostring(err)) end)
+ return future
+ end
+ function api.read_resource(server,uri) return manager:read_resource(server,uri) end
+ function api.prompts(server) return manager:prompts(server) end
+ function api.prompt(server,name,args) return manager:prompt(server,name,args) end
+ return api
+end
+function M.install(manager)
+ local ok,std=pcall(require,'_std')
+ if not ok or type(std.lua_namespace)~='function' then return false end
+ std.lua_namespace('mcp',function(context) return M.factory(manager,context) end)
+ return true
+end
+return M
diff --git a/panto_mcp/oauth.lua b/panto_mcp/oauth.lua
new file mode 100644
index 0000000..b97c1a7
--- /dev/null
+++ b/panto_mcp/oauth.lua
@@ -0,0 +1,458 @@
+local ext = require('panto').ext
+local json = ext.json
+local async = require('panto_mcp.async')
+local config = require('panto_mcp.config')
+local M = {}; M.__index=M
+local function nonempty(v) return type(v)=='string' and v~='' and not v:find('[%z\1-\32\127]') end
+-- Credentials, fragments and ambiguous authorities are never accepted.
+function M.url(value)
+ if type(value)~='string' or value:find('[%z\1-\32\127\\#]') then return nil end
+ local scheme,authority,tail=value:match('^([A-Za-z]+)://([^/?]+)(.*)$')
+ if not scheme then return nil end
+ scheme=scheme:lower(); if scheme~='https' and scheme~='http' then return nil end
+ local host,port
+ if authority:sub(1,1)=='[' then host,port=authority:match('^(%[[%x:]+%])(:?%d*)$')
+ else host,port=authority:match('^([A-Za-z0-9.-]+)(:?%d*)$') end
+ if not host or port==':' then return nil end
+ if port~='' and (not tonumber(port:sub(2)) or tonumber(port:sub(2))<1 or tonumber(port:sub(2))>65535) then return nil end
+ host=host:lower()
+ local literal_loopback=host=='[::1]'
+ local mapped_loopback=false
+ if host:sub(1,1)=='[' then
+ local address=host:sub(2,-2); local left,right=address:match('^(.-)::(.-)$')
+ local groups={}
+ for group in (left or address):gmatch('[^:]+') do groups[#groups+1]=tonumber(group,16) end
+ if left then
+ local suffix={}; for group in right:gmatch('[^:]+') do suffix[#suffix+1]=tonumber(group,16) end
+ while #groups+#suffix<8 do groups[#groups+1]=0 end
+ for _,group in ipairs(suffix) do groups[#groups+1]=group end
+ end
+ if #groups==8 then
+ local zeros=true; for i=1,5 do if groups[i]~=0 then zeros=false end end
+ literal_loopback=zeros and groups[6]==0 and groups[7]==0 and groups[8]==1
+ mapped_loopback=zeros and groups[6]==0xffff and groups[7]>=0x7f00 and groups[7]<=0x7fff
+ end
+ end
+ local a,b,c,d=host:match('^(%d+)%.(%d+)%.(%d+)%.(%d+)$')
+ if a then
+ for _,octet in ipairs({a,b,c,d}) do
+ if (#octet>1 and octet:sub(1,1)=='0') or tonumber(octet)>255 then return nil end
+ end
+ literal_loopback=a=='127'
+ elseif host:match('^[%d.]+$') then return nil end
+ for octet in host:gmatch('[^.]+') do if octet:match('^0x%x+$') then return nil end end
+ if scheme=='http' and not literal_loopback then return nil end
+ if (scheme=='https' and port==':443') or (scheme=='http' and port==':80') then port='' end
+ local origin=scheme..'://'..host..port
+ if tail=='/' then tail='' end
+ return origin..tail,origin,tail:match('^[^?]*'),literal_loopback or mapped_loopback or host=='localhost' or host=='localhost.' or host:match('%.localhost%.?$')~=nil
+end
+function M.prm_urls(resource)
+ local _,origin,path=M.url(resource); if not origin then return {} end
+ local root=origin..'/.well-known/oauth-protected-resource'
+ return path~='' and {root..path,root} or {root}
+end
+function M.metadata_urls(issuer)
+ local _,origin,path=M.url(issuer)
+ if not origin or issuer:find('?',1,true) then return {} end
+ path=path:gsub('/$','')
+ local urls={origin..'/.well-known/oauth-authorization-server'..path,origin..'/.well-known/openid-configuration'..path}
+ if path~='' then urls[#urls+1]=origin..path..'/.well-known/openid-configuration' end
+ return urls
+end
+function M.scopes(value)
+ local out,seen={},{}
+ if type(value)=='string' then
+ local parts={}; for part in value:gmatch('%S+') do parts[#parts+1]=part end; value=parts
+ end
+ if type(value)~='table' then return out end
+ for _,v in ipairs(value) do
+ local valid=type(v)=='string' and v~=''
+ if valid then
+ for i=1,#v do
+ local byte=v:byte(i)
+ if byte<33 or byte>126 or byte==34 or byte==92 then valid=false; break end
+ end
+ end
+ if valid and not seen[v] then seen[v]=true; out[#out+1]=v end
+ end
+ return out
+end
+function M.union(a,b)
+ local out=M.scopes(a); local seen={}; for _,v in ipairs(out) do seen[v]=true end
+ for _,v in ipairs(M.scopes(b)) do if not seen[v] then seen[v]=true; out[#out+1]=v end end
+ return out
+end
+-- Commas inside quoted strings are not challenge separators; quoted-pairs are unescaped.
+function M.challenge(header)
+ if type(header)~='string' or #header>16384 or header:find('[\r\n%z]') then return {} end
+ local chunks,begin,quoted,escaped={},1,false,false
+ for i=1,#header do
+ local c=header:sub(i,i)
+ if escaped then escaped=false
+ elseif quoted and c=='\\' then escaped=true
+ elseif c=='"' then quoted=not quoted
+ elseif c==',' and not quoted then chunks[#chunks+1]=header:sub(begin,i-1); begin=i+1 end
+ end
+ if quoted or escaped then return {} end
+ chunks[#chunks+1]=header:sub(begin)
+ local candidates,current={},nil
+ for _,chunk in ipairs(chunks) do
+ chunk=chunk:match('^%s*(.-)%s*$')
+ local scheme,rest=chunk:match('^([%w!#$%%&\'*+.^_`|~-]+)%s+(.+)$')
+ if scheme and not rest:match('^=') then
+ current={scheme=scheme:lower()}; candidates[#candidates+1]=current; chunk=rest
+ elseif chunk:match('^[%w_-]+$') then
+ current={scheme=chunk:lower()}; candidates[#candidates+1]=current; chunk=''
+ end
+ if current and chunk~='' then
+ local key,value=chunk:match('^([%w!#$%%&\'*+.^_`|~-]+)%s*=%s*(.-)%s*$')
+ if key then
+ key=key:lower()
+ if value:sub(1,1)=='"' and value:sub(-1)=='"' then
+ value=value:sub(2,-2):gsub('\\(.)','%1')
+ elseif not value:match('^[%w!#$%%&\'*+.^_`|~-]+$') then current.invalid=true end
+ if current[key]~=nil then current.invalid=true end
+ current[key]=value
+ else current.invalid=true end
+ end
+ end
+ local first
+ for _,c in ipairs(candidates) do
+ if c.scheme=='bearer' and not c.invalid then
+ local safe={resource_metadata=c.resource_metadata,scope=c.scope,error=c.error}
+ if c.resource_metadata then return safe end
+ first=first or safe
+ end
+ end
+ return first or {}
+end
+function M.validate_metadata(metadata,issuer)
+ if type(metadata)~='table' or metadata.issuer~=issuer then return nil,'OAuth metadata issuer mismatch' end
+ if not M.url(metadata.authorization_endpoint) or not M.url(metadata.token_endpoint) then return nil,'OAuth metadata has unsafe endpoints' end
+ local s256=false
+ for _,method in ipairs(type(metadata.code_challenge_methods_supported)=='table' and metadata.code_challenge_methods_supported or {}) do
+ if method=='S256' then s256=true end
+ end
+ if not s256 then return nil,'OAuth server must advertise PKCE S256' end
+ if metadata.authorization_response_iss_parameter_supported~=nil and type(metadata.authorization_response_iss_parameter_supported)~='boolean' then
+ return nil,'Invalid OAuth issuer-response metadata'
+ end
+ return true
+end
+function M.session_name(server,resource,issuer,client_id)
+ local identity=json.encode({resource=resource,issuer=issuer,client_id=client_id})
+ return 'mcp.'..server:sub(1,91)..'.'..require('panto_mcp.hash').sha256(identity):sub(1,32)
+end
+function M.new(cfg,opts)
+ opts=opts or {}
+ local resource,origin,_,loopback=M.url(cfg.url)
+ local self=setmetatable({cfg=cfg,name=cfg.auth,auth=opts.auth or ext.auth,
+ state=opts.state or ext.state,request_fn=opts.request_fn or ext.http_request,
+ timer_factory=opts.timer_factory or async.timer,clock=opts.clock or require('luv').now,
+ timers={},resource=resource,origin=origin,loopback=loopback},M)
+ self.key='mcp.oauth.server_'..cfg.name
+ if not cfg.auth and self.state then
+ local stored=self.state.get(self.key)
+ if type(stored)=='table' and stored.version==2 and stored.fingerprint==cfg.fingerprint and stored.resource==resource and self:available() then
+ self.name=stored.name
+ self:define(stored)
+ end
+ end
+ return self
+end
+function M:available()
+ return type(self.auth)=='table' and type(self.auth.define)=='function' and type(self.auth.status)=='function'
+ and type(self.auth.login)=='function' and type(self.auth.refresh)=='function' and type(self.auth.complete)=='function'
+end
+function M:login_error() return 'Authentication required; run /mcp-login '..self.cfg.name end
+function M:recovery_error(text)
+ if self.cfg.auth then return text..'; check configured auth with panto auth login/status' end
+ local hint=(self.cfg.oauth and self.cfg.oauth.client_id) and 'check the configured OAuth client/issuer' or
+ ('try /mcp-login '..self.cfg.name..' --reregister to replace a stale DCR client')
+ return text..'; '..hint
+end
+function M:usable()
+ local state=self:auth_status().state
+ return state=='logged_in' or (state=='pending' and self.login_usable==true)
+end
+function M:configured_error()
+ return 'Configured auth session rejected (HTTP 401); check its credentials/type with panto auth login/status'
+end
+function M:auth_status()
+ if not self.name or not self:available() then return {state='logged_out'} end
+ local now=self.clock()
+ if not self.cached_status or now>=(self.status_at or 0)+1000 then
+ self.cached_status=self.auth.status(self.name) or {state='logged_out'}; self.status_at=now
+ end
+ return self.cached_status
+end
+function M:status()
+ if not self:available() then return 'unavailable' end
+ if not self.cfg.auth and not self.definition then return 'undiscovered' end
+ local state=self:auth_status().state
+ if self.login_required and state~='pending' then return 'login_required' end
+ return state
+end
+function M:request_auth()
+ if self.cfg.auth then return self.cfg.auth end
+ if self.definition and (self.refreshing or (not self.login_required and self:usable())) then return self.name end
+end
+function M:blocked()
+ if self.refreshing then return false end
+ return not self.cfg.auth and self.definition and (self.login_required or not self:usable())
+end
+function M:before_request()
+ if self.refreshing then
+ local ok,err=self.refreshing:await(); if not ok then return nil,err end
+ end
+ if self:blocked() then return nil,self:login_error() end
+ if not self.definition and self.discovery_error and self.clock()<self.retry_at then return nil,self.discovery_error end
+ return true
+end
+function M:url_allowed(url)
+ local canonical,_,_,loopback=M.url(url)
+ return canonical and (not loopback or self.loopback)
+end
+function M:define(stored)
+ if not self:available() then return nil,'MCP OAuth requires a newer panto with panto.ext.auth' end
+ if not self.resource then return nil,'MCP OAuth requires HTTPS (or literal loopback HTTP)' end
+ local configured=self.cfg.oauth
+ if configured and ((configured.issuer and configured.issuer~=stored.issuer) or
+ (configured.client_id and (not configured.issuer or configured.client_id~=stored.client_id))) then
+ return nil,'Configured oauth.issuer does not match the discovered authorization server/client'
+ end
+ if not self:url_allowed(stored.issuer) or #M.metadata_urls(stored.issuer)==0 then return nil,'Unsafe OAuth issuer for this resource' end
+ local ok,err=M.validate_metadata(stored.metadata,stored.issuer); if not ok then return nil,err end
+ if not self:url_allowed(stored.metadata.authorization_endpoint) or not self:url_allowed(stored.metadata.token_endpoint) then return nil,'Unsafe OAuth endpoint for this resource' end
+ if not nonempty(stored.client_id) or stored.client_secret~=nil then return nil,'Invalid/public-only OAuth client registration; configure oauth.client_id and oauth.issuer' end
+ local name=M.session_name(self.cfg.name,self.resource,stored.issuer,stored.client_id)
+ local spec={type='oauth_pkce',authorization_url=stored.metadata.authorization_endpoint,token_url=stored.metadata.token_endpoint,
+ client_id=stored.client_id,client_secret=configured and configured.client_secret,
+ scopes=M.scopes(stored.scopes),resource=self.resource,issuer=stored.issuer,
+ require_iss=stored.metadata.authorization_response_iss_parameter_supported==true}
+ if not self.auth.define(name,spec) then return nil,'Cannot define MCP OAuth session (check session name/config collision)' end
+ if self.name and self.name~=name then
+ -- Runtime definitions are process-local; a stored old name may need restoring for logout.
+ if not self.auth.define(self.name,self.spec or spec) then return nil,'Cannot restore the previous OAuth session for logout' end
+ local ok=self.auth.logout and self.auth.logout(self.name)
+ if not ok then return nil,'Cannot retire the previous OAuth session' end
+ end
+ if self.name~=name then self.cached_status=nil; self.login_usable=nil end
+ self.name=name; self.definition=stored; self.spec=spec
+ return true
+end
+function M:save()
+ if self.state and self.definition then
+ local d=self.definition
+ return self.state.set(self.key,{version=2,name=self.name,fingerprint=self.cfg.fingerprint,resource=self.resource,issuer=d.issuer,
+ metadata=d.metadata,client_id=d.client_id,scopes=d.scopes})
+ end
+ return true
+end
+function M:invalidate(reregister)
+ if self.cfg.auth then return end
+ if self.definition then
+ self.previous_issuer=self.definition.issuer; self.requested_scopes=self.spec.scopes
+ end
+ if reregister and self.state and self.previous_issuer then
+ self.state.set('mcp.oauth.registration_'..config.hash(self.previous_issuer),nil)
+ end
+ if self.state then self.state.set(self.key,nil) end
+ self.login_poll=(self.login_poll or 0)+1
+ self.definition=nil; self.spec=nil; self.cached_status=nil; self.login_required=nil; self.login_url=nil
+ self.discovery_error=nil; self.retry_at=nil; self.backoff=nil
+end
+function M:fetch(url,body)
+ if self.closed then return nil,'session ended' end
+ if not self:url_allowed(url) then return nil,'Unsafe OAuth discovery URL for this resource' end
+ local future=async.future()
+ local opts={url=url,method=body and 'POST' or 'GET',timeout_ms=10000,max_bytes=1024*1024,headers={Accept='application/json'}}
+ if body then opts.body=json.encode(body); opts.headers['Content-Type']='application/json' end
+ local ok,handle=pcall(self.request_fn,opts,function(response)
+ if self.closed then future:resolve(nil,'session ended'); return end
+ if not response or response.status<200 or response.status>=300 then future:resolve(nil,'OAuth discovery/registration request failed'); return end
+ local decoded,value=pcall(json.decode,response.body or '')
+ if not decoded or type(value)~='table' then future:resolve(nil,'Invalid OAuth metadata JSON'); return end
+ future:resolve(value)
+ end)
+ if not ok or not handle then return nil,'OAuth HTTP request could not start' end
+ self.requests=self.requests or {}; self.requests[handle]=future
+ local value,err=future:await(); self.requests[handle]=nil
+ return value,err
+end
+function M:discover(challenge)
+ if self.cfg.auth then return nil,self:configured_error() end
+ challenge=challenge or {}
+ if self.definition then return true end
+ if self.discovering then return self.discovering:await() end
+ if self.discovery_error and self.clock()<self.retry_at then return nil,self.discovery_error end
+ if not self:available() then return nil,'MCP OAuth requires a newer panto with panto.ext.auth and HTTP POST support' end
+ if not self.resource then return nil,'MCP OAuth requires HTTPS (or literal loopback HTTP)' end
+ local future=async.future(); self.discovering=future
+ local function work()
+ local urls=challenge.resource_metadata and {challenge.resource_metadata} or M.prm_urls(self.resource)
+ local prm,expected_resource
+ for i,url in ipairs(urls) do
+ local value=self:fetch(url)
+ if value then
+ prm=value; expected_resource=(not challenge.resource_metadata and i==2) and self.origin or self.resource
+ break
+ end
+ end
+ if not prm then return nil,'Cannot discover OAuth protected-resource metadata' end
+ if M.url(prm.resource)~=expected_resource then return nil,'OAuth protected-resource metadata resource mismatch' end
+ local servers=type(prm.authorization_servers)=='table' and prm.authorization_servers or {}
+ local issuer=servers[1]
+ local pinned=self.cfg.oauth and self.cfg.oauth.issuer
+ if pinned then
+ issuer=nil
+ for _,candidate in ipairs(servers) do if candidate==pinned then issuer=candidate; break end end
+ if not issuer then return nil,'Configured oauth.issuer is not advertised by the resource' end
+ end
+ if not issuer or #M.metadata_urls(issuer)==0 or not self:url_allowed(issuer) then return nil,'OAuth resource has no safe authorization server' end
+ local metadata
+ for _,url in ipairs(M.metadata_urls(issuer)) do
+ local value=self:fetch(url)
+ if value then
+ local valid,why=M.validate_metadata(value,issuer); if not valid then return nil,why end
+ metadata={issuer=issuer,authorization_endpoint=value.authorization_endpoint,token_endpoint=value.token_endpoint,
+ code_challenge_methods_supported={'S256'},registration_endpoint=value.registration_endpoint,
+ authorization_response_iss_parameter_supported=value.authorization_response_iss_parameter_supported}
+ break
+ end
+ end
+ if not metadata then return nil,'Cannot discover OAuth authorization-server metadata' end
+ if not self:url_allowed(metadata.authorization_endpoint) or not self:url_allowed(metadata.token_endpoint) then return nil,'Unsafe OAuth endpoint for this resource' end
+ local registration=self.cfg.oauth
+ local registration_key='mcp.oauth.registration_'..config.hash(issuer)
+ if not registration or not registration.client_id then
+ registration=self.state and self.state.get(registration_key)
+ if type(registration)=='table' and registration.client_secret~=nil then
+ return nil,self:recovery_error('Confidential DCR is unsupported')
+ end
+ if type(registration)~='table' or registration.issuer~=issuer or not nonempty(registration.client_id) then
+ if not self:url_allowed(metadata.registration_endpoint) then return nil,'OAuth server needs configured oauth.client_id and oauth.issuer (no safe DCR endpoint)' end
+ local value,why=self:fetch(metadata.registration_endpoint,{client_name='panto-mcp',application_type='native',
+ redirect_uris={'http://127.0.0.1/callback'},token_endpoint_auth_method='none',
+ grant_types={'authorization_code','refresh_token'},response_types={'code'}})
+ if not value then return nil,why end
+ if value.client_secret~=nil or (value.token_endpoint_auth_method~=nil and value.token_endpoint_auth_method~='none') then
+ return nil,'Confidential DCR is unsupported; configure oauth.client_id, oauth.issuer and optional oauth.client_secret'
+ end
+ if not nonempty(value.client_id) then return nil,'Invalid OAuth registration response' end
+ registration={issuer=issuer,client_id=value.client_id}
+ if self.state and not self.state.set(registration_key,registration) then return nil,'Cannot persist OAuth registration' end
+ end
+ end
+ local scopes=challenge.scope
+ if scopes==nil then scopes=prm.scopes_supported end
+ if scopes==nil then scopes=self.cfg.oauth and self.cfg.oauth.scopes end
+ if self.previous_issuer==issuer then scopes=M.union(scopes,self.requested_scopes) end
+ local ok,why=self:define({issuer=issuer,metadata=metadata,client_id=registration.client_id,scopes=M.scopes(scopes)})
+ if not ok then return nil,why end
+ if not self:save() then return nil,'Cannot persist OAuth discovery' end
+ if self.previous_issuer and self.previous_issuer~=issuer and self.state then
+ self.state.set('mcp.oauth.registration_'..config.hash(self.previous_issuer),nil)
+ end
+ return true
+ end
+ local ok,value,err=pcall(work)
+ if not ok then value=nil; err='OAuth discovery failed' end
+ if not value then
+ self.backoff=math.min((self.backoff or 2500)*2,60000); self.retry_at=self.clock()+self.backoff; self.discovery_error=err
+ else self.backoff=nil; self.discovery_error=nil; self.retry_at=nil end
+ self.discovering=nil; future:resolve(value,err)
+ return value,err
+end
+function M:poll(callback,remaining,active)
+ if self.closed then return end
+ local t
+ t=self.timer_factory(1000,function()
+ self.timers[t]=nil
+ if self.closed or (active and not active()) then return end
+ local status=self:auth_status()
+ if status.state~='pending' then callback(status); return end
+ if remaining<=1000 then callback(nil); return end
+ self:poll(callback,remaining-1000,active)
+ end)
+ self.timers[t]=true
+end
+function M:refresh()
+ if self.refreshing then return self.refreshing:await() end
+ local future=async.future(); self.refreshing=future
+ local ok=self.auth.refresh(self.name)
+ if not ok then self.refreshing=nil; return nil,self.cfg.auth and self:configured_error() or self:recovery_error(self:login_error()) end
+ self.cached_status={state='pending'}; self.status_at=self.clock()
+ self:poll(function(status)
+ self.refreshing=nil
+ if status and status.state=='logged_in' and not status.error then future:resolve(true)
+ else future:resolve(nil,self.cfg.auth and self:configured_error() or self:recovery_error(self:login_error())) end
+ end,70000)
+ return future:await()
+end
+function M:recover(data)
+ local challenge=data.challenge or {}
+ if data.http_status==403 then
+ if challenge.error~='insufficient_scope' then return nil,'Forbidden (HTTP 403); check server permissions' end
+ if self.cfg.auth then return nil,'Configured auth session needs additional scopes; update its scopes and use panto auth login' end
+ if not self.definition then return nil,'Insufficient scope (HTTP 403); no OAuth definition is available' end
+ local scopes=M.union(M.union(self.spec.scopes,self:auth_status().scopes),challenge.scope)
+ self.definition.scopes=scopes
+ local ok,err=self:define(self.definition); if not ok then return nil,err end
+ self:save()
+ return nil,'Additional permission required; run /mcp-login '..self.cfg.name
+ end
+ if not self:available() then
+ return nil,self.cfg.auth and self:configured_error() or 'MCP OAuth requires a newer panto with panto.ext.auth and HTTP POST support'
+ end
+ if data.auth_used then
+ local ok,err=self:refresh()
+ if ok or self.cfg.auth then return ok,err end
+ self:invalidate()
+ local discovered,why=self:discover(challenge)
+ self.login_required=not self:usable() or nil
+ return nil,discovered and err or self:recovery_error(why)
+ end
+ local ok,err=self:discover(challenge)
+ if not ok then return nil,err end
+ if self:request_auth() then return true end
+ return nil,self:login_error()
+end
+function M:login(callback_url,on_success,on_error)
+ if not self:available() then return nil,self.cfg.auth and 'Configured auth login requires a newer panto and an oauth_pkce session; use panto auth login instead' or 'MCP OAuth requires a newer panto with panto.ext.auth' end
+ if not self.cfg.auth and not self.definition then return nil,'OAuth discovery is not ready; retry /mcp-login '..self.cfg.name..' after checking /mcp' end
+ local usable=self:usable()
+ local result
+ if callback_url then
+ if not self.auth.complete(self.name,callback_url) then return nil,'OAuth callback rejected; check the URL/state/issuer and retry' end
+ elseif self.login_url and self:auth_status().state=='pending' then result={url=self.login_url}
+ else
+ result=self.auth.login(self.name)
+ if not result then
+ local text='Cannot start OAuth login; check that the configured auth session is oauth_pkce'
+ return nil,self.cfg.auth and text or self:recovery_error(text)
+ end
+ self.login_url=result.url
+ end
+ self.login_usable=usable; self.login_required=not usable or nil
+ self.cached_status={state='pending'}; self.status_at=self.clock()
+ self.login_poll=(self.login_poll or 0)+1
+ local generation=self.login_poll
+ self:poll(function(status)
+ self.login_required=nil; self.login_url=nil
+ if status and status.state=='logged_in' and not status.error then
+ self.login_usable=nil; on_success()
+ elseif on_error then
+ on_error(self:recovery_error('OAuth login failed or timed out'))
+ end
+ end,670000,function() return generation==self.login_poll end)
+ return result and result.url or true
+end
+function M:close()
+ self.closed=true
+ for t in pairs(self.timers) do async.close(t) end; self.timers={}
+ for handle,future in pairs(self.requests or {}) do handle:cancel(); future:resolve(nil,'session ended') end
+ if self.refreshing then self.refreshing:resolve(nil,'session ended') end
+end
+return M
diff --git a/panto_mcp/prompts.lua b/panto_mcp/prompts.lua
new file mode 100644
index 0000000..6d84509
--- /dev/null
+++ b/panto_mcp/prompts.lua
@@ -0,0 +1,267 @@
+local async = require('panto_mcp.async')
+local json = require('panto').ext.json
+local results = require('panto_mcp.results')
+
+local M = {}
+local function shell_words(text)
+ local words, i = {}, 1
+ while i <= #text do
+ while text:sub(i,i):match('%s') do i=i+1 end
+ if i > #text then break end
+ local out, quote, started = {}, nil, false
+ while i <= #text do
+ local ch=text:sub(i,i)
+ if quote == "'" then
+ if ch == "'" then quote=nil else out[#out+1]=ch end
+ started=true; i=i+1
+ elseif quote == '"' then
+ if ch == '"' then quote=nil; i=i+1
+ elseif ch == '\\' then
+ if i == #text then return nil,'trailing escape' end
+ out[#out+1]=text:sub(i+1,i+1); i=i+2
+ else out[#out+1]=ch; i=i+1 end
+ started=true
+ elseif ch:match('%s') then break
+ elseif ch == "'" or ch == '"' then quote=ch; started=true; i=i+1
+ elseif ch == '\\' then
+ if i == #text then return nil,'trailing escape' end
+ out[#out+1]=text:sub(i+1,i+1); started=true; i=i+2
+ else out[#out+1]=ch; started=true; i=i+1 end
+ end
+ if quote then return nil,'unclosed quote' end
+ if started then words[#words+1]=table.concat(out) end
+ end
+ return words
+end
+M.shell_words = shell_words
+
+local function has_named_token(text,name)
+ local needle=name..'='
+ local cursor=1
+ while true do
+ local start=text:find(needle,cursor,true)
+ if not start then return false end
+ if start==1 or text:sub(start-1,start-1):match('%s') then return true end
+ cursor=start+1
+ end
+end
+function M.parse_arguments(prompt, text)
+ if type(text) ~= 'string' then return nil,'arguments must be text' end
+ local args, definitions = {}, {}
+ for _, argument in ipairs(prompt.arguments or {}) do
+ if type(argument.name) ~= 'string' or argument.name == '' then return nil,'invalid prompt argument metadata' end
+ definitions[argument.name]=argument
+ end
+ local words,err={},nil
+ if #(prompt.arguments or {})==1 then
+ local only=prompt.arguments[1].name
+ local remainder=text:match('^%s*(.-)%s*$') or ''
+ if not has_named_token(remainder,only) then
+ if remainder~='' then args[only]=remainder end
+ else words,err=shell_words(text) end
+ else words,err=shell_words(text) end
+ if not words then return nil,err end
+ for _,word in ipairs(words) do
+ local equals=word:find('=',1,true)
+ if not equals or equals == 1 then return nil,'expected name=value argument' end
+ local name,value=word:sub(1,equals-1),word:sub(equals+1)
+ if not definitions[name] then return nil,'unknown prompt argument: '..name end
+ if args[name] ~= nil then return nil,'duplicate prompt argument: '..name end
+ args[name]=value
+ end
+ local missing={}
+ for _,argument in ipairs(prompt.arguments or {}) do
+ if argument.required and args[argument.name] == nil then missing[#missing+1]=argument.name end
+ end
+ if #missing > 0 then return nil,'missing required arguments: '..table.concat(missing,', ') end
+ return args
+end
+
+local function text_block(text) return {type='text',text=text} end
+local function content_blocks(content, role)
+ if type(content)=='string' then return {text_block(content)} end
+ local entries
+ if type(content)~='table' then return {text_block('[Unsupported MCP prompt content]')} end
+ if type(content.type)=='string' then entries={content} else entries=content end
+ local out={}
+ local function add_image(data,mime)
+ mime=type(mime)=='string' and mime or nil
+ local supported={['image/png']=true,['image/jpeg']=true,['image/webp']=true,['image/bmp']=true,['image/gif']=true}
+ local is_image=mime and supported[mime:lower()]
+ local decoded=is_image and type(data)=='string' and results.decode64(data)
+ if role=='assistant' then out[#out+1]=text_block('[Assistant media omitted: '..tostring(mime or 'image')..']')
+ elseif not is_image then out[#out+1]=text_block('[MCP unsupported attachment omitted: '..tostring(mime or 'unknown MIME type')..']')
+ elseif decoded then out[#out+1]={type='media',data=decoded,media_type=mime}
+ else out[#out+1]=text_block('[Invalid MCP image omitted]') end
+ end
+ for _,block in ipairs(entries) do
+ if type(block)~='table' then out[#out+1]=text_block('[Unsupported MCP prompt content]')
+ elseif block.type=='text' then out[#out+1]=text_block(block.text or '')
+ elseif block.type=='image' then add_image(block.data,block.mimeType)
+ elseif block.type=='audio' then out[#out+1]=text_block('[MCP audio omitted: '..tostring(block.mimeType or 'unknown MIME type')..']')
+ elseif block.type=='resource' and type(block.resource)=='table' then
+ local resource=block.resource
+ if type(resource.text)=='string' then out[#out+1]=text_block((type(resource.uri)=='string' and '['..resource.uri..']\n' or '')..resource.text)
+ elseif resource.blob then add_image(resource.blob,resource.mimeType)
+ else out[#out+1]=text_block('[MCP resource omitted: '..tostring(resource.uri or 'unknown URI')..']') end
+ else out[#out+1]=text_block('[Unsupported MCP prompt content: '..tostring(block.type or 'unknown')..']') end
+ end
+ return out
+end
+function M.map_messages(messages)
+ if type(messages)~='table' then return nil,'invalid prompt messages' end
+ local mapped={}
+ for _,message in ipairs(messages) do
+ if type(message)~='table' or (message.role~='user' and message.role~='assistant') then
+ return nil,'invalid prompt message role'
+ end
+ mapped[#mapped+1]={role=message.role,blocks=content_blocks(message.content,message.role)}
+ end
+ return mapped
+end
+local function preflight(mapped)
+ local has_media=false
+ for _,message in ipairs(mapped) do
+ for _,block in ipairs(message.blocks) do if block.type=='media' then has_media=true end end
+ end
+ if not has_media then return end
+ local probe=require('panto').conversation()
+ for _,message in ipairs(mapped) do
+ if message.role=='user' then probe:add_user_blocks(message.blocks)
+ else probe:add_assistant_message({blocks=message.blocks}) end
+ end
+end
+function M.append_to(agent, messages)
+ local mapped,err=M.map_messages(messages)
+ if not mapped then return nil,err end
+ local ok=pcall(preflight,mapped)
+ if not ok then return nil,'MCP prompt image could not be decoded' end
+ local trailing_user=mapped[#mapped] and mapped[#mapped].role=='user'
+ local conv=agent:conversation()
+ local stop=trailing_user and #mapped-1 or #mapped
+ for i=1,stop do
+ local message=mapped[i]
+ if message.role=='user' then conv:add_user_blocks(message.blocks)
+ else conv:add_assistant_message({blocks=message.blocks}) end
+ end
+ if trailing_user then agent:submit(mapped[#mapped].blocks); return true end
+ return false
+end
+
+local function log(err) io.stderr:write('panto-mcp: prompt command: ',tostring(err),'\n') end
+local function unregister(ext,name)
+ local ok,value,err=pcall(ext.unregister_command,name)
+ if not ok or not value then log(ok and (err or ('cannot unregister '..name)) or value); return false end
+ return true
+end
+local function prompt_description(prompt)
+ local parts={}
+ if type(prompt.title)=='string' and prompt.title~='' then parts[#parts+1]=prompt.title end
+ if type(prompt.description)=='string' and prompt.description~='' then parts[#parts+1]=prompt.description end
+ local names={}
+ for _,argument in ipairs(prompt.arguments or {}) do names[#names+1]=argument.name end
+ if #names>0 then parts[#parts+1]='Arguments: '..table.concat(names,', ') end
+ return #parts>0 and table.concat(parts,' — ') or ('MCP prompt '..prompt.name)
+end
+function M.commands(ext, manager, turn, dynamic, warnings)
+ local registered, warned={},{}
+ local error_mount,error_text
+ local function clear_error()
+ if error_mount then
+ pcall(function() if error_mount:alive() then error_mount:unmount() end end)
+ error_mount=nil; error_text=nil
+ end
+ end
+ local function show_error(err)
+ error_text='MCP prompt failed: '..tostring(err):gsub('[%z\1-\8\11\12\14-\31\127]','?'):sub(1,800)
+ if error_mount then
+ local ok=pcall(error_mount.invalidate,error_mount)
+ if ok then return end
+ error_mount=nil
+ end
+ if type(ext.mount)=='function' then
+ local ok,handle=pcall(ext.mount,{render=function() return error_text end},'above_input')
+ if ok then error_mount=handle; return end
+ end
+ log(error_text)
+ end
+ if type(ext.on)=='function' then
+ ext.on('command_start',clear_error); ext.on('turn_start',clear_error)
+ end
+ local function warning(key,text)
+ if warned[key] then return end
+ warned[key]=true
+ local message='prompt '..text
+ if warnings then warnings[#warnings+1]=message end
+ log(message)
+ end
+ local function reconcile(server, metadata, warm)
+ local wanted={}
+ for _,prompt in ipairs((metadata and metadata.catalog and metadata.catalog.prompts) or {}) do
+ if type(prompt.name)=='string' and not prompt.name:find('[/%s]') then
+ local name='mcp:'..server..':'..prompt.name
+ local description=prompt_description(prompt)
+ wanted[name]={server=server,prompt=prompt,signature=json.encode({description=description,arguments=prompt.arguments})}
+ else warning(server..':'..tostring(prompt.name),'command skipped because its name contains slash or whitespace: '..tostring(prompt.name)) end
+ end
+ if dynamic then
+ for name,old in pairs(registered) do
+ if old.server==server then
+ local next_prompt=wanted[name]
+ if not next_prompt or next_prompt.signature~=old.signature then
+ if unregister(ext,name) then registered[name]=nil end
+ end
+ end
+ end
+ end
+ for name,current in pairs(wanted) do
+ if not registered[name] and (dynamic or warm) then
+ local handler=function(text)
+ if turn.busy then return 'Cannot run an MCP prompt while a turn is in progress.' end
+ local args,why=M.parse_arguments(current.prompt,text or '')
+ if not args then return 'MCP prompt arguments: '..why end
+ async.run(function()
+ local messages,err=manager:prompt(current.server,current.prompt.name,args)
+ if not messages then show_error(err); return end
+ if turn.busy then show_error('result discarded because a turn started while the prompt was loading'); return end
+ local submitted,append_err=M.append_to(require('panto').ext.agent,messages)
+ if submitted==nil then show_error(append_err)
+ elseif not submitted and type(ext.emit)=='function' then
+ local emitted,emit_err=pcall(ext.emit,'agent_submission')
+ if not emitted then show_error(emit_err) end
+ end
+ end,show_error)
+ return 'Fetching MCP prompt…'
+ end
+ local ok,value,err=pcall(ext.register_command,{name=name,description=prompt_description(current.prompt),handler=handler})
+ if ok and (value or (not dynamic and err==nil)) then registered[name]=current
+ else
+ local reason=ok and (err or ('register_command failed for '..name)) or value
+ warning(name..':registration','command registration failed for '..name..': '..tostring(reason))
+ end
+ end
+ end
+ end
+ return {reconcile=reconcile,registered=registered}
+end
+function M.track_busy(ext,turn,prompt_commands)
+ local in_turn,commands,prompt_dispatch=false,0,false
+ local function update() turn.busy=in_turn or commands>0 end
+ local function event_name(event)
+ return type(event)=='table' and type(event.command_name)=='string' and event.command_name or '<unknown command>'
+ end
+ ext.on('turn_start',function() in_turn=true; update() end)
+ ext.on('turn_end',function() in_turn=false; update() end)
+ ext.on('command_start',function(event)
+ local name=event_name(event)
+ prompt_dispatch=prompt_commands.registered[name]~=nil
+ if not prompt_dispatch then commands=commands+1 end
+ update()
+ end)
+ ext.on('command_end',function(event)
+ if not prompt_dispatch then commands=math.max(0,commands-1) end
+ prompt_dispatch=false
+ update()
+ end)
+end
+return M
diff --git a/panto_mcp/results.lua b/panto_mcp/results.lua
new file mode 100644
index 0000000..b7da16b
--- /dev/null
+++ b/panto_mcp/results.lua
@@ -0,0 +1,89 @@
+local json = require('panto').ext.json
+local M = {MAX_OUTPUT=100*1024, MAX_IMAGE=5*1024*1024, MAX_ATTACHMENTS=10*1024*1024}
+local alphabet='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
+local tokens,bytes={},{}
+for i=1,#alphabet do
+ local c=alphabet:sub(i,i); local v=i-1
+ tokens[c]=string.char((v>>4)&3,(v>>2)&3,v&3)
+end
+for a=0,3 do for b=0,3 do for c=0,3 do for d=0,3 do
+ local key=string.char(a,b,c,d)
+ local value=string.char((a<<6)|(b<<4)|(c<<2)|d)
+ bytes[key]=value=='%' and '%%' or value
+end end end end
+function M.decode64(s,cap)
+ if type(s)~='string' then return nil,'invalid base64' end
+ cap=cap or M.MAX_IMAGE
+ if #s>math.ceil(cap/3)*4 then return nil,'attachment exceeds size cap' end
+ if #s%4~=0 or s:find('[^A-Za-z0-9+/=]') or not s:match('^[A-Za-z0-9+/]*=?=?$') then return nil,'invalid base64' end
+ local symbols=s:gsub('=+$','')
+ local padding=#s-#symbols
+ if padding>2 or (#symbols%4~=0 and #symbols%4~=2 and #symbols%4~=3) or
+ (padding==1 and #symbols%4~=3) or (padding==2 and #symbols%4~=2) then return nil,'invalid base64 padding' end
+ local size=math.floor(#symbols*3/4)
+ if size>cap then return nil,'attachment exceeds size cap' end
+ if #symbols==0 then return '' end
+ -- Table replacements keep both full-string passes in gsub's C loop. Each
+ -- sextet expands to three 2-bit tokens; groups of four tokens form a byte.
+ local bits=symbols:gsub('.',tokens)
+ local rem=#bits%4
+ if rem~=0 then bits=bits .. string.rep('\0',4-rem) end
+ local decoded=bits:gsub('....',bytes)
+ return decoded:sub(1,size)
+end
+function M.cap(text,limit)
+ limit=limit or M.MAX_OUTPUT
+ if #text<=limit then return text end
+ local at=limit
+ while at>0 and text:byte(at+1) and text:byte(at+1)>=128 and text:byte(at+1)<192 do at=at-1 end
+ return text:sub(1,at) .. '\n[truncated at ' .. limit .. ' bytes]'
+end
+function M.map(server,result,err)
+ if err then
+ local message=type(err)=='table' and (tostring(err.message) .. ' (' .. tostring(err.code) .. ')') or tostring(err)
+ return {text=M.cap(server .. ': ' .. message),is_error=true,attachments=json.array({})}
+ end
+ if type(result)~='table' then return {text=server .. ': invalid MCP result',is_error=true,attachments=json.array({})} end
+ if result.resultType=='input_required' then return {text=server .. ': server requested user input; panto does not support it yet',is_error=true,attachments=json.array({})} end
+ local texts,attachments={},json.array({}); local total=0
+ local function text(s) texts[#texts+1]=tostring(s or '') end
+ local function image(data,mime)
+ local bytes,why=M.decode64(data,math.min(M.MAX_IMAGE,M.MAX_ATTACHMENTS-total))
+ if not bytes then text('[' .. why .. ']'); return end
+ total=total+#bytes
+ attachments[#attachments+1]={data=bytes,media_type=mime or 'image/png'}
+ end
+ local content
+ content=function(block)
+ if type(block)~='table' then return end
+ if block.type=='text' then text(block.text)
+ elseif block.type=='image' then image(block.data,block.mimeType)
+ elseif block.type=='audio' then text('[audio ' .. tostring(block.mimeType or 'unknown') .. ', base64 bytes ' .. (type(block.data)=='string' and #block.data or 0) .. ']')
+ elseif block.type=='resource_link' then
+ text(tostring(block.name or '') .. ' ' .. tostring(block.uri or '') .. ' ' .. tostring(block.description or '') ..
+ '\nRead with mcp.read_resource{server=' .. json.encode(server) .. ', uri=' .. json.encode(block.uri or '') .. '}')
+ elseif block.type=='resource' then
+ local r=type(block.resource)=='table' and block.resource or {}; text('Resource: ' .. tostring(r.uri or ''))
+ if r.text then text(r.text)
+ elseif r.blob and type(r.mimeType)=='string' and r.mimeType:match('^image/') then image(r.blob,r.mimeType)
+ else text('[embedded resource ' .. tostring(r.mimeType or 'unknown') .. ', base64 bytes ' .. (type(r.blob)=='string' and #r.blob or 0) .. ']') end
+ else text('[unsupported MCP content: ' .. tostring(block.type) .. ']') end
+ end
+ for _,block in ipairs(type(result.content)=='table' and result.content or {}) do content(block) end
+ for _,resource in ipairs(type(result.contents)=='table' and result.contents or {}) do content({type='resource',resource=resource}) end
+ local structured=result.structuredContent
+ if structured~=nil then
+ local encoded=json.encode(structured)
+ local duplicate=false
+ for _,s in ipairs(texts) do
+ if s==encoded then duplicate=true; break end
+ local ok,decoded=pcall(json.decode,s)
+ if ok and json.encode(decoded)==encoded then duplicate=true; break end
+ end
+ if not duplicate then text(encoded) end
+ if #encoded>M.MAX_OUTPUT then structured=nil end
+ end
+ return {text=M.cap(table.concat(texts,'\n')),attachments=attachments,
+ structured=structured,is_error=result.isError==true}
+end
+return M
diff --git a/panto_mcp/search.lua b/panto_mcp/search.lua
new file mode 100644
index 0000000..a36e48c
--- /dev/null
+++ b/panto_mcp/search.lua
@@ -0,0 +1,83 @@
+local config = require('panto_mcp.config')
+local json = require('panto').ext.json
+local M = {}
+local function terms(s)
+ local out={}; for t in tostring(s or ''):lower():gmatch('[%w]+') do out[#out+1]=t end; return out
+end
+local function fields(item)
+ local out={item.name or '',item.name or '',item.name or '',item.title or '',item.title or '',item.uri or '',item.uriTemplate or '',item.description or ''}
+ local function props(schema,depth)
+ if type(schema)~='table' or depth>8 then return end
+ for name,p in pairs(type(schema.properties)=='table' and schema.properties or {}) do
+ out[#out+1]=tostring(name)
+ if type(p)=='table' then out[#out+1]=type(p.description)=='string' and p.description or ''; props(p,depth+1) end
+ end
+ end
+ props(item.inputSchema,0)
+ return table.concat(out,' ')
+end
+function M.search(states,query,opts)
+ opts=opts or {}; local docs,df={},{}
+ for server,state in pairs(states) do
+ if not opts.server or opts.server==server then
+ local catalog=(state.metadata and state.metadata.catalog) or {}
+ for _,kind in ipairs({'tools','resources','templates'}) do
+ for _,item in ipairs(catalog[kind] or {}) do
+ if kind~='tools' or config.tool_enabled(state.cfg,item.name or '') then
+ local tf,n={},0
+ for _,t in ipairs(terms(fields(item))) do tf[t]=(tf[t] or 0)+1; n=n+1 end
+ for t in pairs(tf) do df[t]=(df[t] or 0)+1 end
+ docs[#docs+1]={server=server,item=item,kind=kind,tf=tf,n=n}
+ end
+ end
+ end
+ end
+ end
+ local total=0; for _,d in ipairs(docs) do total=total+d.n end
+ local avg=math.max(1,total/math.max(1,#docs)); local q=terms(query)
+ local ranked={}
+ for _,d in ipairs(docs) do
+ local score=0
+ for _,t in ipairs(q) do
+ local f=d.tf[t] or 0
+ if f>0 then score=score+math.log(1+(#docs-(df[t] or 0)+0.5)/((df[t] or 0)+0.5))*f*2.2/(f+1.2*(0.25+0.75*d.n/avg)) end
+ end
+ if #q==0 or score>0 then d.score=score; ranked[#ranked+1]=d end
+ end
+ table.sort(ranked,function(a,b)
+ if a.score~=b.score then return a.score>b.score end
+ return (a.server .. ':' .. a.kind .. ':' .. tostring(a.item.name or a.item.uri or a.item.uriTemplate)) <
+ (b.server .. ':' .. b.kind .. ':' .. tostring(b.item.name or b.item.uri or b.item.uriTemplate))
+ end)
+ local hits=json.array({})
+ for i=1,math.min(#ranked,opts.limit or 10) do
+ local d=ranked[i]; local v=d.item
+ hits[#hits+1]={server=d.server,kind=d.kind,name=v.name or v.uri or v.uriTemplate,
+ title=v.title or (type(v.annotations)=='table' and v.annotations.title),description=v.description,
+ inputSchema=v.inputSchema,uri=v.uri,uriTemplate=v.uriTemplate,mimeType=v.mimeType,score=d.score}
+ end
+ local out={hits=hits,total=#ranked}
+ if opts.server and states[opts.server] then
+ local meta=states[opts.server].metadata
+ if meta and type(meta.instructions)=='string' then out.instructions=require('panto_mcp.results').cap(meta.instructions,4096) end
+ end
+ return out
+end
+local function distance(a,b)
+ a=a:sub(1,256):lower(); b=b:sub(1,256):lower()
+ local prev={}; for j=0,#b do prev[j]=j end
+ for i=1,#a do
+ local row={[0]=i}
+ for j=1,#b do row[j]=math.min(row[j-1]+1,prev[j]+1,prev[j-1]+(a:byte(i)==b:byte(j) and 0 or 1)) end
+ prev=row
+ end
+ return prev[#b]
+end
+function M.closest(name,names)
+ local ranked={}
+ for _,n in ipairs(names) do ranked[#ranked+1]={name=n,d=distance(name,n)} end
+ table.sort(ranked,function(a,b) return a.d==b.d and a.name<b.name or a.d<b.d end)
+ local out={}; for i=1,math.min(3,#ranked) do out[#out+1]=ranked[i].name end
+ return table.concat(out,', ')
+end
+return M
diff --git a/panto_mcp/stdio.lua b/panto_mcp/stdio.lua
new file mode 100644
index 0000000..1a9d996
--- /dev/null
+++ b/panto_mcp/stdio.lua
@@ -0,0 +1,108 @@
+local uv = require('luv')
+local json = require('panto').ext.json
+local async = require('panto_mcp.async')
+local M = {}; M.__index=M
+-- Exported small framer for deterministic checks. Protocol-sized bound prevents
+-- an untrusted/noisy server from accumulating an unbounded partial line.
+function M.framer(emit, max_bytes, on_bad_line)
+ local buf=''; max_bytes=max_bytes or 16*1024*1024
+ return function(chunk)
+ buf=buf .. chunk
+ while true do
+ local at=buf:find('\n',1,true)
+ if not at then if #buf>max_bytes then return nil,'stdio frame exceeds size limit' end; return true end
+ if at>max_bytes then return nil,'stdio frame exceeds size limit' end
+ local line=buf:sub(1,at-1):gsub('\r$',''); buf=buf:sub(at+1)
+ if line:match('%S') then
+ local ok,msg=pcall(json.decode,line)
+ if not ok then
+ if on_bad_line then on_bad_line(line) end
+ elseif type(msg)~='table' then return nil,'malformed JSON on MCP stdout'
+ else emit(msg) end
+ end
+ end
+ end
+end
+function M.new(cfg)
+ local path,err=package.searchpath('panto_mcp.supervisor',package.path)
+ if not path then return nil,err end
+ local self=setmetatable({stderr_tail='',cfg=cfg},M)
+ self.stdin=uv.new_pipe(false); self.stdout=uv.new_pipe(false)
+ self.stderr=uv.new_pipe(false); self.lifeline=uv.new_pipe(false)
+ local function stop_orphan()
+ local server_pid=self.server_pid
+ if not server_pid then return end
+ pcall(uv.kill,-server_pid,'sigterm')
+ local escalation=uv.new_timer()
+ escalation:start(2000,0,function()
+ if uv.kill(-server_pid,0) then pcall(uv.kill,-server_pid,'sigkill') end
+ async.close(escalation)
+ end)
+ end
+ local proc,pid=uv.spawn(uv.exepath(),{
+ args={'lua',path,json.encode({command=cfg.command,args=json.array(cfg.args or {}),env=cfg.env or {}})},
+ cwd=cfg.cwd,detached=true,
+ stdio={self.stdin,self.stdout,self.stderr,self.lifeline},
+ },function(code,signal)
+ async.close(self.proc)
+ if not self.closed then
+ stop_orphan()
+ self:fail('supervisor exited (' .. code .. ', signal ' .. signal .. ')')
+ end
+ end)
+ if not proc then self:close(); return nil,pid end
+ self.proc=proc; self.supervisor_pid=pid
+ local function append_tail(data)
+ self.stderr_tail=(self.stderr_tail .. data):sub(-8192)
+ end
+ local feed=M.framer(function(msg) if self.on_message then self.on_message(msg) end end,nil,function(line)
+ append_tail(line .. '\n')
+ end)
+ self.stdout:read_start(function(e,data)
+ if self.closed then return end
+ if e or not data then self:fail(e or 'MCP stdout closed'); return end
+ local ok,why=feed(data); if not ok then self:fail(why) end
+ end)
+ local stderr_buf=''
+ self.stderr:read_start(function(_,data)
+ if not data then return end
+ stderr_buf=stderr_buf .. data
+ -- Marker can straddle chunks. Keep only a bounded diagnostic tail.
+ self.server_pid=tonumber(stderr_buf:match('PANTO_MCP_PID=(%d+)\n')) or self.server_pid
+ stderr_buf=stderr_buf:sub(-8192)
+ append_tail(data:gsub('PANTO_MCP_PID=%d+\r?\n',''))
+ end)
+ -- Pending request/startup timers keep the loop alive only while needed.
+ for _,h in ipairs({proc,self.stdin,self.stdout,self.stderr,self.lifeline}) do h:unref() end
+ return self
+end
+function M:set_callbacks(message,err) self.on_message=message; self.on_error=err end
+function M:fail(err)
+ if self.closed then return end
+ local tail=self.stderr_tail:sub(-500):gsub('[%z\1-\8\11\12\14-\31\127]',' ')
+ if tail~='' then err=tostring(err) .. ' (stderr: ' .. tail .. ')' end
+ self:close()
+ if self.on_error then self.on_error(tostring(err)) end
+end
+function M:send(msg, _opts)
+ if self.closed then return nil,'stdio transport closed' end
+ local ok,payload=pcall(json.encode,msg); if not ok then return nil,payload end
+ local wrote,handle,err=pcall(self.stdin.write,self.stdin,payload .. '\n',function(e)
+ if e then self:fail(e) end
+ end)
+ if not wrote then self:fail(handle); return nil,handle end
+ if not handle then self:fail(err); return nil,err end
+ return handle
+end
+function M:cancel(id)
+ self:send({jsonrpc='2.0',method='notifications/cancelled',params={requestId=id,reason='client cancelled'}})
+end
+function M:close()
+ if self.closed then return end
+ self.closed=true
+ -- Never signal/wait here: the detached supervisor owns escalation, even
+ -- after this runtime disappears. Closing stdin precedes lifeline EOF.
+ async.close(self.stdin); async.close(self.lifeline)
+ async.close(self.stdout); async.close(self.stderr)
+end
+return M
diff --git a/panto_mcp/supervisor.lua b/panto_mcp/supervisor.lua
new file mode 100644
index 0000000..48649aa
--- /dev/null
+++ b/panto_mcp/supervisor.lua
@@ -0,0 +1,65 @@
+-- Standalone: panto lua <this file> <JSON {command,args}>. Never require in host.
+-- fds 0/1/2 are inherited by the detached server; fd 3 is the host lifeline.
+local uv = require('luv')
+local json = require('panto').ext.json
+local cfg = assert(json.decode(assert(arg[1], 'missing supervisor configuration')))
+local timers, signals = {}, {}
+local child, pid, stopping, exited
+local function close(h) if h and not h:is_closing() then h:close() end end
+local life = uv.new_pipe(false)
+assert(life:open(3))
+local function alive()
+ return pid and uv.kill(-pid, 0) ~= nil
+end
+local function finish()
+ close(life)
+ for _, h in ipairs(timers) do close(h) end
+ for _, h in ipairs(signals) do close(h) end
+ if exited then close(child) end
+end
+local function timer(ms, repeat_ms, fn)
+ local t = uv.new_timer(); timers[#timers + 1] = t
+ t:start(ms, repeat_ms, fn)
+ return t
+end
+local function shutdown()
+ if stopping then return end
+ stopping = true
+ close(life)
+ -- The host has already closed stdin. Even if the group leader exited,
+ -- descendants still receive the escalation (npx/shell wrappers).
+ timer(2000, 0, function()
+ if alive() then uv.kill(-pid, 'sigterm') end
+ timer(2000, 0, function()
+ if alive() then uv.kill(-pid, 'sigkill') end
+ end)
+ end)
+ timer(0, 50, function() if not alive() then finish() end end)
+end
+local child_env = uv.os_environ()
+for k, v in pairs(cfg.env or {}) do child_env[k] = v end
+local env = {}
+for k, v in pairs(child_env) do env[#env + 1] = k .. '=' .. v end
+child, pid = uv.spawn(cfg.command, {
+ args = cfg.args or {}, stdio = {0, 1, 2}, env = env, detached = true,
+}, function()
+ exited = true
+ close(child)
+ shutdown()
+end)
+if not child then
+ io.stderr:write('panto-mcp supervisor spawn failed: ', tostring(pid), '\n'); io.stderr:flush()
+ close(life)
+else
+ io.stderr:write('PANTO_MCP_PID=', tostring(pid), '\n'); io.stderr:flush()
+ -- The server inherited these descriptors; retaining supervisor copies
+ -- would delay stdout EOF until after the grace period.
+ assert(uv.fs_close(0))
+ assert(uv.fs_close(1))
+ life:read_start(function(_, data) if not data then shutdown() end end)
+ for _, name in ipairs({'sigint', 'sigterm', 'sighup'}) do
+ local s = uv.new_signal(); signals[#signals + 1] = s
+ s:start(name, shutdown)
+ end
+end
+uv.run()
diff --git a/panto_mcp/tools.lua b/panto_mcp/tools.lua
new file mode 100644
index 0000000..4651ea6
--- /dev/null
+++ b/panto_mcp/tools.lua
@@ -0,0 +1,97 @@
+local async = require('panto_mcp.async')
+local results = require('panto_mcp.results')
+local validate = require('panto_mcp.validate')
+local json = require('panto').ext.json
+local M = {}
+function M.status(manager,warnings)
+ local lines={}
+ for _,warning in ipairs(warnings or {}) do lines[#lines+1]='Config warning: ' .. warning end
+ for _,s in ipairs(manager:servers()) do
+ lines[#lines+1]=string.format('%s: %s · %s · %s · tools=%d prompts=%d resources=%d templates=%d',
+ s.name,s.state,s.era or 'unknown era',s.transport=='http' and 'HTTP URL' or s.transport,s.tools,s.prompts,s.resources,s.templates)
+ if s.auth then lines[#lines+1]=' auth: '..s.auth end
+ if s.notification_warning then lines[#lines+1]=' warning: '..s.notification_warning end
+ if s.error then lines[#lines+1]=' error: ' .. s.error end
+ if s.cache_error then lines[#lines+1]=' cache: ' .. tostring(s.cache_error) end
+ if s.stderr~='' then lines[#lines+1]=' stderr: '..s.stderr:sub(-2048):gsub('[%z\1-\8\11\12\14-\31\127]','?') end
+ end
+ return #lines>0 and table.concat(lines,'\n') or 'No enabled MCP servers.'
+end
+local function checked(input,schema)
+ local ok,errors=validate.check(input,schema)
+ if not ok then error(table.concat(errors,'\n'),0) end
+end
+local function mapped(result)
+ if result.is_error then error(result.text,0) end
+ return {text=result.text,attachments=result.attachments}
+end
+local base={server={type='string'},tool={type='string'},input={},uri={type='string'},
+ query={type='string'},limit={type='integer',minimum=1,maximum=100}}
+function M.register_resource(ext,manager)
+ local schema={type='object',properties={server=base.server,uri=base.uri},required={'server','uri'}}
+ local ok,err=ext.register_tool({name='mcp.read_resource',
+ description='Read an MCP resource URI on its originating server (including resource_link results). Does not fetch arbitrary web URLs.',
+ schema=schema,handler=function(input) checked(input,schema); return mapped(manager:read_resource(input.server,input.uri)) end})
+ if not ok and err then io.stderr:write('panto-mcp: cannot register mcp.read_resource: ',tostring(err),'\n') end
+ return ok
+end
+function M.register(ext,manager,warnings,include_search,include_resource)
+ if include_search ~= false then
+ for _,spec in ipairs({
+ {name='mcp.search',description='Search MCP tools/resources/templates. Omit query to browse. Returns exact names and full tool input schemas; warm metadata search starts no servers.',
+ schema={type='object',properties={query=base.query,server=base.server,limit=base.limit}},
+ handler=function(input)
+ local value,err=manager:search(input.query,{server=input.server,limit=input.limit})
+ if not value then error(err,0) end
+ return results.cap(json.encode(value))
+ end},
+ {name='mcp.call',description='Call one MCP tool by exact server/tool names, with input matching the live inputSchema returned by mcp.search. No fuzzy execution.',
+ schema={type='object',properties={server=base.server,tool=base.tool,input=base.input},required={'server','tool'}},
+ handler=function(input) return mapped(manager:call(input.server,input.tool,input.input)) end},
+ }) do
+ local handler=spec.handler
+ spec.handler=function(input) checked(input,spec.schema); return handler(input) end
+ ext.register_tool(spec)
+ end
+ end
+ if include_resource then M.register_resource(ext,manager) end
+ M.register_status(ext,manager,warnings)
+end
+function M.register_status(ext,manager,warnings)
+ ext.register_command({name='mcp-login',description='Log in to an HTTP MCP server: /mcp-login <server> [callback-url | --reregister]',handler=function(args)
+ local name,callback_url=(args or ''):match('^%s*(%S+)%s*(.-)%s*$')
+ if not name or callback_url:find('%s') then return 'Usage: /mcp-login <server> [callback-url | --reregister]' end
+ return manager:login(name,callback_url~='' and callback_url~='--reregister' and callback_url or nil,callback_url=='--reregister')
+ end})
+ ext.register_command({name='mcp',description='MCP status; /mcp refresh [server] starts a metadata refresh.',handler=function(args)
+ args=args or ''
+ if args=='' then return M.status(manager,warnings) end
+ local cmd,name=args:match('^(%S+)%s*(.-)%s*$')
+ if cmd~='refresh' or name:find('%s') then return 'Usage: /mcp [refresh [server]]' end
+ if name=='' then name=nil end
+ if name then local s,err=manager:lookup(name); if not s then return err end end
+ async.run(function() manager:refresh(name) end)
+ return 'MCP refresh started; /mcp shows current status.'
+ end})
+end
+function M.hint(ext,servers)
+ local names={}; local search_enabled=false
+ for n,c in pairs(servers) do names[#names+1]=n; search_enabled=search_enabled or c.expose=='search' end
+ table.sort(names)
+ local lines={'## MCP'}
+ if search_enabled then
+ lines[#lines+1]='Find tools/resources with mcp.search; call exact names with mcp.call. '
+ ..'std.lua reference: require("panto_mcp.docs").discovery (also .calls, .resources, .prompts).'
+ else
+ lines[#lines+1]='Eager MCP tools are registered as mcp.<server>.<tool>; '
+ ..'std.lua reference: require("panto_mcp.docs").discovery (also .calls, .resources, .prompts).'
+ end
+ for _,n in ipairs(names) do
+ local c=servers[n]; lines[#lines+1]=n .. ': ' .. (c.transport=='http' and 'HTTP URL' or 'stdio') .. ', ' .. c.expose
+ end
+ ext.on('session_ready',function()
+ local agent=ext.agent
+ if agent and type(agent.add_system_message)=='function' then agent:add_system_message(table.concat(lines,'\n')) end
+ end)
+end
+return M
diff --git a/panto_mcp/validate.lua b/panto_mcp/validate.lua
new file mode 100644
index 0000000..4719b54
--- /dev/null
+++ b/panto_mcp/validate.lua
@@ -0,0 +1,134 @@
+-- Cheap JSON Schema 2020-12 checks, not a full dialect implementation.
+-- Unknown keywords (notably pattern/format) are intentionally ignored.
+local json = require('panto').ext.json
+local array_mt=getmetatable(json.array({}))
+local M = {}
+local function array(v)
+ if type(v)~='table' then return false end
+ local n=0
+ for k in pairs(v) do if type(k)~='number' or k<1 or k%1~=0 then return false end; n=n+1 end
+ return n==#v
+end
+local function matches(v,t)
+ if t=='null' then return v==json.null end
+ if v==json.null then return false end
+ if t=='array' then return array(v) end
+ if t=='object' then return type(v)=='table' and getmetatable(v)~=array_mt and (not array(v) or next(v)==nil) end
+ if t=='integer' then return type(v)=='number' and v%1==0 end
+ if t=='number' or t=='string' or t=='boolean' then return type(v)==t end
+ return true
+end
+local function equal(a,b)
+ if type(a)~=type(b) then return false end
+ if type(a)~='table' then return a==b end
+ for k,v in pairs(a) do if not equal(v,b[k]) then return false end end
+ for k in pairs(b) do if a[k]==nil then return false end end
+ -- Empty arrays and objects decoded by the host have distinct encodings.
+ if next(a)==nil and next(b)==nil then return json.encode(a)==json.encode(b) end
+ return true
+end
+M.equal=equal
+local function pointer(path,k) return path .. '/' .. tostring(k):gsub('~','~0'):gsub('/','~1') end
+local function ref(root,s)
+ if s=='#' then return root end
+ if s:sub(1,2)~='#/' then return nil end
+ local v,rest=root,s:sub(3)
+ while true do
+ local at=rest:find('/',1,true)
+ local part=at and rest:sub(1,at-1) or rest
+ part=part:gsub('~1','/'):gsub('~0','~')
+ if type(v)~='table' then return nil end
+ local key=part
+ if array(v) and (next(v)~=nil or getmetatable(v)==array_mt) then
+ if not part:match('^%d+$') then return nil end
+ key=tonumber(part)+1 -- JSON pointers use zero-based array indices.
+ end
+ v=v[key]
+ if not at then return v end
+ rest=rest:sub(at+1)
+ end
+end
+local check
+check=function(v,s,path,errors,root,depth)
+ if #errors>=100 then return end
+ local function add(message) errors[#errors+1]=(path=='' and '/' or path) .. ': ' .. message end
+ if s==false then add('value is forbidden'); return end
+ if type(s)~='table' then return end
+ if depth>64 then return end -- recursive schemas must not exhaust the Lua stack
+ if type(s['$ref'])=='string' then
+ local target=ref(root,s['$ref'])
+ if target~=nil then check(v,target,path,errors,root,depth+1) end
+ end
+ if s.type then
+ local ok=false
+ if type(s.type)=='string' then ok=matches(v,s.type)
+ elseif type(s.type)=='table' then for _,t in ipairs(s.type) do if matches(v,t) then ok=true end end end
+ if not ok then add('expected ' .. json.encode(s.type)); return end
+ end
+ if s.const~=nil and not equal(v,s.const) then add('does not equal const') end
+ if type(s.enum)=='table' then
+ local found=false; for _,x in ipairs(s.enum) do if equal(v,x) then found=true; break end end
+ if not found then add('not in enum') end
+ end
+ for _,kind in ipairs({'anyOf','oneOf','allOf'}) do
+ if type(s[kind])=='table' then
+ local passed=0
+ for _,sub in ipairs(s[kind]) do
+ local e={}; check(v,sub,path,e,root,depth+1)
+ if #e==0 then passed=passed+1 end
+ if kind=='allOf' then for _,message in ipairs(e) do errors[#errors+1]=message end end
+ end
+ if (kind=='anyOf' or kind=='oneOf') and passed==0 then add('no ' .. kind .. ' branch matched') end
+ end
+ end
+ -- `not` and patternProperties are intentionally ignored: this partial
+ -- validator must not reject inputs valid under unsupported constraints.
+ if type(v)=='string' then
+ local n=utf8.len(v) or #v
+ if type(s.minLength)=='number' and n<s.minLength then add('shorter than minLength') end
+ if type(s.maxLength)=='number' and n>s.maxLength then add('longer than maxLength') end
+ elseif type(v)=='number' then
+ for _,b in ipairs({{'minimum',function(a,b) return a<b end},{'maximum',function(a,b) return a>b end},
+ {'exclusiveMinimum',function(a,b) return a<=b end},{'exclusiveMaximum',function(a,b) return a>=b end}}) do
+ if type(s[b[1]])=='number' and b[2](v,s[b[1]]) then add('outside ' .. b[1] .. ' ' .. s[b[1]]) end
+ end
+ if type(s.multipleOf)=='number' and s.multipleOf>0 then
+ local q=v/s.multipleOf
+ if math.abs(q-math.floor(q+0.5))>1e-9*math.max(1,math.abs(q)) then add('not a multipleOf ' .. s.multipleOf) end
+ end
+ elseif type(v)=='table' then
+ local isarray=array(v)
+ -- An unmarked empty Lua table can stand for either shape. Apply the
+ -- relevant keywords rather than inventing a type the host did not keep.
+ if not isarray or next(v)==nil then
+ local props=type(s.properties)=='table' and s.properties or {}
+ for _,k in ipairs(type(s.required)=='table' and s.required or {}) do
+ if v[k]==nil then errors[#errors+1]=pointer(path,k) .. ': required property missing' end
+ end
+ local n=0
+ for k,x in pairs(v) do
+ n=n+1
+ if props[k]~=nil then check(x,props[k],pointer(path,k),errors,root,depth+1)
+ elseif s.additionalProperties~=nil and s.patternProperties==nil then check(x,s.additionalProperties,pointer(path,k),errors,root,depth+1) end
+ end
+ if type(s.minProperties)=='number' and n<s.minProperties then add('fewer than minProperties') end
+ if type(s.maxProperties)=='number' and n>s.maxProperties then add('more than maxProperties') end
+ end
+ if isarray then
+ if type(s.minItems)=='number' and #v<s.minItems then add('fewer than minItems') end
+ if type(s.maxItems)=='number' and #v>s.maxItems then add('more than maxItems') end
+ local prefix=type(s.prefixItems)=='table' and s.prefixItems or {}
+ for i,x in ipairs(v) do
+ local sub=prefix[i]
+ if sub==nil then sub=s.items end
+ if sub~=nil then check(x,sub,pointer(path,i-1),errors,root,depth+1) end
+ if s.uniqueItems then for j=1,i-1 do if equal(x,v[j]) then errors[#errors+1]=pointer(path,i-1) .. ': duplicate array item'; break end end end
+ end
+ end
+ end
+end
+function M.check(value,schema)
+ local errors={}; check(value,schema,'',errors,schema,0)
+ return #errors==0, errors
+end
+return M