mlai-code 0.0.0-stage → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +12 -2
- package/bin/mlai.mjs +3 -0
- package/package.json +18 -3
- package/src/browser-setup.mjs +77 -0
- package/src/cli-ext.mjs +146 -0
- package/src/cli.mjs +534 -0
- package/src/cloud.mjs +29 -0
- package/src/completion.mjs +159 -0
- package/src/credentials.mjs +54 -0
- package/src/deploy.mjs +134 -0
- package/src/distribution.mjs +373 -0
- package/src/engine-key.mjs +4 -0
- package/src/engine.mjs +167 -0
- package/src/headless.mjs +196 -0
- package/src/home.mjs +22 -0
- package/src/host.mjs +123 -0
- package/src/local-models.mjs +64 -0
- package/src/modes.mjs +38 -0
- package/src/netbox.mjs +97 -0
- package/src/netjail.py +59 -0
- package/src/offline.mjs +98 -0
- package/src/parity.mjs +86 -0
- package/src/project.mjs +68 -0
- package/src/relay.mjs +140 -0
- package/src/render.mjs +73 -0
- package/src/restricted.mjs +47 -0
- package/src/review.mjs +70 -0
- package/src/runner.mjs +127 -0
- package/src/runtime.mjs +75 -0
- package/src/sandbox.mjs +135 -0
- package/src/sdk.mjs +11 -0
- package/src/server.mjs +110 -0
- package/src/session.mjs +290 -0
- package/src/settings.mjs +135 -0
- package/src/shared-data.mjs +3 -0
- package/src/tui/acp.mjs +145 -0
- package/src/tui/agents-cli.mjs +114 -0
- package/src/tui/agents-local.mjs +65 -0
- package/src/tui/ansi.mjs +123 -0
- package/src/tui/app.mjs +710 -0
- package/src/tui/approval.mjs +88 -0
- package/src/tui/bg.mjs +172 -0
- package/src/tui/bgterm.mjs +79 -0
- package/src/tui/chat.mjs +230 -0
- package/src/tui/clipboard.mjs +74 -0
- package/src/tui/cloud-cli.mjs +57 -0
- package/src/tui/cloud-run.mjs +123 -0
- package/src/tui/cmd-agents.mjs +130 -0
- package/src/tui/cmd-auto-review.mjs +94 -0
- package/src/tui/cmd-cloud.mjs +17 -0
- package/src/tui/cmd-config.mjs +104 -0
- package/src/tui/cmd-core.mjs +160 -0
- package/src/tui/cmd-distribution.mjs +15 -0
- package/src/tui/cmd-ecosystem.mjs +169 -0
- package/src/tui/cmd-extensibility.mjs +333 -0
- package/src/tui/cmd-remote.mjs +18 -0
- package/src/tui/cmd-review.mjs +58 -0
- package/src/tui/cmd-session-extra.mjs +152 -0
- package/src/tui/cmd-tui.mjs +200 -0
- package/src/tui/commands.mjs +160 -0
- package/src/tui/custom-commands.mjs +98 -0
- package/src/tui/diff.mjs +60 -0
- package/src/tui/editor.mjs +190 -0
- package/src/tui/ext-state.mjs +16 -0
- package/src/tui/extensions-local.mjs +140 -0
- package/src/tui/files.mjs +72 -0
- package/src/tui/handoff.mjs +110 -0
- package/src/tui/import-setups.mjs +151 -0
- package/src/tui/init.mjs +104 -0
- package/src/tui/keymap.mjs +70 -0
- package/src/tui/keys.mjs +101 -0
- package/src/tui/loop.mjs +75 -0
- package/src/tui/markdown.mjs +118 -0
- package/src/tui/mcp-config.mjs +225 -0
- package/src/tui/mcp-oauth.mjs +162 -0
- package/src/tui/permissions.mjs +189 -0
- package/src/tui/plain.mjs +32 -0
- package/src/tui/plugins-local.mjs +103 -0
- package/src/tui/remote.mjs +125 -0
- package/src/tui/review-cli.mjs +332 -0
- package/src/tui/review-github.mjs +59 -0
- package/src/tui/screen.mjs +60 -0
- package/src/tui/session-ops.mjs +104 -0
- package/src/tui/skills-local.mjs +92 -0
- package/src/tui/snapshots.mjs +87 -0
- package/src/tui/statusline.mjs +98 -0
- package/src/tui/transcript.mjs +116 -0
- package/src/two-words.mjs +36 -0
- package/src/wakeups.mjs +53 -0
- package/src/winenv.mjs +94 -0
- package/src/winsandbox.py +351 -0
- package/src/workspace-api.mjs +621 -0
- package/src/worktree.mjs +128 -0
- package/vendor/client-sdk/controller.cjs +115 -0
- package/vendor/client-sdk/files.cjs +38 -0
- package/vendor/client-sdk/index.cjs +133 -0
- package/vendor/client-sdk/login.cjs +52 -0
- package/vendor/client-sdk/updates.cjs +41 -0
- package/vendor/cloud-cli/mlai.mjs +394 -0
- package/worker/architecture_parse.cjs +23 -0
- package/worker/architecture_worker.py +394 -0
- package/worker/ask_first.py +96 -0
- package/worker/attachment_reader.py +66 -0
- package/worker/background_jobs.py +111 -0
- package/worker/brief_questions.py +56 -0
- package/worker/browser_local.py +49 -0
- package/worker/browser_pane.py +89 -0
- package/worker/browser_tool.py +101 -0
- package/worker/build_planner.py +187 -0
- package/worker/chat_fork.py +277 -0
- package/worker/checkpoints.py +133 -0
- package/worker/cloud_pty.py +351 -0
- package/worker/command_policy.py +39 -0
- package/worker/command_safety.py +717 -0
- package/worker/computer_card.sh +23 -0
- package/worker/computer_setup.sh +86 -0
- package/worker/computer_use.py +221 -0
- package/worker/connector_search.py +43 -0
- package/worker/context_manager.py +60 -0
- package/worker/conversation.py +144 -0
- package/worker/deploy_pack.py +116 -0
- package/worker/design_director.py +240 -0
- package/worker/dev_jobs.py +166 -0
- package/worker/edit_guard.py +99 -0
- package/worker/env_setup.py +129 -0
- package/worker/evidence.py +109 -0
- package/worker/fast_search.py +24 -0
- package/worker/git_sync.py +333 -0
- package/worker/goals.py +156 -0
- package/worker/handover.py +98 -0
- package/worker/harness_memory.py +194 -0
- package/worker/image_generation.py +173 -0
- package/worker/intelligence.py +149 -0
- package/worker/intent_model.py +78 -0
- package/worker/intent_weights.json +1 -0
- package/worker/ios_simulator.py +87 -0
- package/worker/kimi_bridge.py +997 -0
- package/worker/kimi_compact.py +93 -0
- package/worker/kimi_gates.py +304 -0
- package/worker/kimi_hook.py +617 -0
- package/worker/lifecycle.py +95 -0
- package/worker/lsp.py +77 -0
- package/worker/mcp_local.py +293 -0
- package/worker/memory.py +99 -0
- package/worker/mlai_auto_review.py +177 -0
- package/worker/mlai_hooks.py +966 -0
- package/worker/mlai_mcp.py +441 -0
- package/worker/mlai_permissions.py +283 -0
- package/worker/model_stream.py +75 -0
- package/worker/nested_repos.py +76 -0
- package/worker/offline_guard.py +17 -0
- package/worker/preview.py +806 -0
- package/worker/proc_watch.py +124 -0
- package/worker/project_context.py +72 -0
- package/worker/project_rules.py +99 -0
- package/worker/quality.py +180 -0
- package/worker/reply_language.py +56 -0
- package/worker/repo_hygiene.py +132 -0
- package/worker/repo_memory.py +101 -0
- package/worker/repo_policy.py +269 -0
- package/worker/roles.json +3173 -0
- package/worker/roles.py +303 -0
- package/worker/runner.py +1795 -0
- package/worker/runtime_control.py +205 -0
- package/worker/secret_scan.py +168 -0
- package/worker/session_hub.py +80 -0
- package/worker/skill_library.py +129 -0
- package/worker/skill_pack.py +533 -0
- package/worker/subagents.py +91 -0
- package/worker/task_controller.py +139 -0
- package/worker/task_skills.py +159 -0
- package/worker/team_checkpoint.py +33 -0
- package/worker/token_count.py +32 -0
- package/worker/tool_catalog.py +38 -0
- package/worker/upload_storage.py +531 -0
- package/worker/verification.py +725 -0
- package/worker/vision.py +84 -0
- package/worker/wakeups.py +63 -0
- package/worker/web_tools.py +203 -0
- package/worker/winproc.py +135 -0
- package/worker/work_ledger.py +117 -0
- package/worker/worktrees.py +79 -0
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Markdown for the terminal: headings, emphasis, inline code, links, lists, task lists, quotes, rules, tables
|
|
3
|
+
* and fenced code with syntax highlighting. render(text) returns styled lines wrapped to the width.
|
|
4
|
+
* A Stream renders text that is still arriving: complete blocks are final, the open tail is redrawn.
|
|
5
|
+
*/
|
|
6
|
+
import {wrap,width,pad} from './ansi.mjs';
|
|
7
|
+
|
|
8
|
+
const KEYWORDS={
|
|
9
|
+
js:'await break case catch class const continue debugger default delete do else export extends finally for from function if import in instanceof let new of return static super switch this throw try typeof var void while with yield async true false null undefined',
|
|
10
|
+
py:'and as assert async await break class continue def del elif else except False finally for from global if import in is lambda None nonlocal not or pass raise return True try while with yield self',
|
|
11
|
+
sh:'if then else elif fi for while do done case esac in function return export local set unset echo cd exit source',
|
|
12
|
+
go:'break case chan const continue default defer else fallthrough for func go goto if import interface map package range return select struct switch type var true false nil',
|
|
13
|
+
rs:'as async await break const continue crate else enum extern false fn for if impl in let loop match mod move mut pub ref return self Self static struct super trait true type unsafe use where while',
|
|
14
|
+
json:'true false null',
|
|
15
|
+
css:'important',
|
|
16
|
+
sql:'select from where insert into values update set delete create table alter drop join left right inner outer on group by order having limit and or not null as distinct',
|
|
17
|
+
};
|
|
18
|
+
const LANG={javascript:'js',jsx:'js',ts:'js',tsx:'js',typescript:'js',mjs:'js',cjs:'js',js:'js',python:'py',py:'py',bash:'sh',sh:'sh',shell:'sh',zsh:'sh',console:'sh',go:'go',golang:'go',rust:'rs',rs:'rs',json:'json',jsonc:'json',css:'css',scss:'css',sql:'sql',java:'js',c:'js',cpp:'js',cs:'js',kotlin:'js',swift:'js',php:'js',rb:'py',ruby:'py',yaml:'sh',yml:'sh',toml:'sh',diff:'diff',patch:'diff'};
|
|
19
|
+
const kwCache={};
|
|
20
|
+
const kwSet=l=>kwCache[l]??=new Set((KEYWORDS[l]||'').split(' ').filter(Boolean).map(w=>l==='sql'?w.toLowerCase():w));
|
|
21
|
+
|
|
22
|
+
/** Highlights one line of code. State carries an open block comment or triple-quoted string to the next line. */
|
|
23
|
+
export function highlightLine(line,lang,t,state={}){
|
|
24
|
+
const l=LANG[String(lang||'').toLowerCase()]||(lang?'js':'');
|
|
25
|
+
if(!l||!t.color)return {text:t.code?t.code(line):line,state};
|
|
26
|
+
if(l==='diff'){const c=line[0];return {text:c==='+'?t.add(line):c==='-'?t.del(line):c==='@'?t.hunk(line):line,state}}
|
|
27
|
+
const kw=kwSet(l);let out='',i=0;const s=line;
|
|
28
|
+
const lineComment=l==='py'||l==='sh'?'#':l==='sql'?'--':'//';
|
|
29
|
+
if(state.block){const end=s.indexOf(state.block);if(end<0)return {text:t.comment(s),state};out+=t.comment(s.slice(0,end+state.block.length));i=end+state.block.length;state={}}
|
|
30
|
+
while(i<s.length){
|
|
31
|
+
const rest=s.slice(i);let m;
|
|
32
|
+
if(rest.startsWith(lineComment)&&!(l==='sh'&&i>0&&/\S/.test(s[i-1]))){out+=t.comment(rest);break}
|
|
33
|
+
if((l==='js'||l==='go'||l==='rs'||l==='css')&&rest.startsWith('/*')){const end=rest.indexOf('*/',2);if(end<0){out+=t.comment(rest);return {text:out,state:{block:'*/'}}}out+=t.comment(rest.slice(0,end+2));i+=end+2;continue}
|
|
34
|
+
if(l==='py'&&(rest.startsWith('"""')||rest.startsWith("'''"))){const q=rest.slice(0,3),end=rest.indexOf(q,3);if(end<0){out+=t.string(rest);return {text:out,state:{block:q}}}out+=t.string(rest.slice(0,end+3));i+=end+3;continue}
|
|
35
|
+
if((m=/^(["'`])(?:\\.|(?!\1)[^\\])*\1?/.exec(rest))){out+=t.string(m[0]);i+=m[0].length;continue}
|
|
36
|
+
if((m=/^(?:0x[\da-f]+|\d+(?:\.\d+)?(?:e[+-]?\d+)?)\b/i.exec(rest))&&!/[\w$]/.test(s[i-1]||'')){out+=t.number(m[0]);i+=m[0].length;continue}
|
|
37
|
+
if((m=/^[A-Za-z_$][\w$]*/.exec(rest))){
|
|
38
|
+
const w=m[0];
|
|
39
|
+
if(kw.has(l==='sql'?w.toLowerCase():w))out+=t.keyword(w);
|
|
40
|
+
else if(s[i+w.length]==='(')out+=t.fn(w);
|
|
41
|
+
else out+=w;
|
|
42
|
+
i+=w.length;continue;
|
|
43
|
+
}
|
|
44
|
+
out+=s[i];i++;
|
|
45
|
+
}
|
|
46
|
+
return {text:out,state};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// Inline markdown: `code`, **bold**, *em* or _em_, ~~strike~~, [text](url).
|
|
50
|
+
export function inline(text,t){
|
|
51
|
+
const parts=[];let s=String(text);
|
|
52
|
+
// Pull code spans out first so their contents are not styled.
|
|
53
|
+
s=s.replace(/`([^`]+)`/g,(_,c)=>{parts.push(t.code(c));return '\u0000'+(parts.length-1)+'\u0000'});
|
|
54
|
+
s=s.replace(/\[([^\]]+)\]\((https?:\/\/[^)\s]+)\)/g,(_,label,url)=>{parts.push(t.under(label)+t.dim(' ('+url+')'));return '\u0000'+(parts.length-1)+'\u0000'});
|
|
55
|
+
s=s.replace(/\*\*([^*]+)\*\*|__([^_]+)__/g,(_,a,b)=>t.bold(a||b));
|
|
56
|
+
s=s.replace(/(^|[^\w*])\*([^*\s][^*]*?)\*(?!\w)/g,(_,p,a)=>p+t.italic(a));
|
|
57
|
+
s=s.replace(/(^|[^\w])_([^_\s][^_]*?)_(?!\w)/g,(_,p,a)=>p+t.italic(a));
|
|
58
|
+
s=s.replace(/~~([^~]+)~~/g,(_,a)=>t.faint(a));
|
|
59
|
+
return s.replace(/\u0000(\d+)\u0000/g,(_,n)=>parts[Number(n)]);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function table(rows,t,cols){
|
|
63
|
+
const cells=rows.map(r=>r.replace(/^\s*\|/,'').replace(/\|\s*$/,'').split('|').map(c=>c.trim()));
|
|
64
|
+
const body=cells.filter((_,i)=>i!==1||!cells[1].every(c=>/^:?-{2,}:?$/.test(c)));
|
|
65
|
+
const n=Math.max(...body.map(r=>r.length));
|
|
66
|
+
const w=Array.from({length:n},(_,i)=>Math.max(3,...body.map(r=>width(inline(r[i]||'',t)))));
|
|
67
|
+
const total=w.reduce((a,b)=>a+b+3,1);
|
|
68
|
+
if(total>cols)return body.map(r=>r.map(c=>inline(c,t)).join(t.dim(' | ')));
|
|
69
|
+
return body.map((r,ri)=>{
|
|
70
|
+
const line=t.dim('│ ')+r.map((c,i)=>pad(ri===0?t.bold(inline(c,t)):inline(c,t),w[i])).join(t.dim(' │ '))+t.dim(' │');
|
|
71
|
+
return ri===0&&body.length>1?line+'\n'+t.dim('├'+w.map(x=>'─'.repeat(x+2)).join('┼')+'┤'):line;
|
|
72
|
+
}).flatMap(l=>l.split('\n'));
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Renders a whole markdown text to lines no wider than cols. */
|
|
76
|
+
export function render(text,{t,cols=80,box}={}){
|
|
77
|
+
const out=[];const lines=String(text??'').replace(/\r\n?/g,'\n').split('\n');
|
|
78
|
+
const push=(s,indent='',first=indent)=>{const w=wrap(s,cols-width(first));w.forEach((x,i)=>out.push((i?indent:first)+x))};
|
|
79
|
+
for(let i=0;i<lines.length;i++){
|
|
80
|
+
const line=lines[i];let m;
|
|
81
|
+
if((m=/^(\s*)(```+|~~~+)\s*([\w+#.-]*)/.exec(line))){
|
|
82
|
+
const fence=m[2],lang=m[3];const code=[];i++;
|
|
83
|
+
while(i<lines.length&&!lines[i].trimStart().startsWith(fence))code.push(lines[i++]);
|
|
84
|
+
const bar=t.dim(box?.bar||'▌')+' ';
|
|
85
|
+
if(lang)out.push(t.dim(box?.bar||'▌')+' '+t.faint(lang));
|
|
86
|
+
let state={};
|
|
87
|
+
for(const c of code){const h=highlightLine(c.replace(/\t/g,' '),lang,t,state);state=h.state;for(const w of wrap(h.text,cols-2))out.push(bar+w)}
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
if(!line.trim()){if(out.length&&out.at(-1)!=='')out.push('');continue}
|
|
91
|
+
if((m=/^(#{1,6})\s+(.*)$/.exec(line))){const txt=inline(m[2].replace(/\s*#+\s*$/,''),t);push(m[1].length<=2?t.head(txt):t.bold(txt));continue}
|
|
92
|
+
if(/^\s*([-*_])(\s*\1){2,}\s*$/.test(line)){out.push(t.dim((box?.h||'─').repeat(Math.min(cols,40))));continue}
|
|
93
|
+
if(/^\s*\|.*\|\s*$/.test(line)){const rows=[];while(i<lines.length&&/^\s*\|.*\|\s*$/.test(lines[i]))rows.push(lines[i++]);i--;for(const r of table(rows,t,cols))out.push(r);continue}
|
|
94
|
+
if((m=/^(\s*)>\s?(.*)$/.exec(line))){push(t.quote(inline(m[2],t)),t.quote('│ '),t.quote('│ '));continue}
|
|
95
|
+
if((m=/^(\s*)([-*+])\s+\[([ xX])\]\s+(.*)$/.exec(line))){const ind=' '.repeat(Math.min(8,m[1].length));const done=m[3]!==' ';push(done?t.faint(inline(m[4],t)):inline(m[4],t),ind+' ',ind+(done?t.ok('[x] '):t.dim('[ ] ')));continue}
|
|
96
|
+
if((m=/^(\s*)([-*+])\s+(.*)$/.exec(line))){const ind=' '.repeat(Math.min(8,m[1].length));push(inline(m[3],t),ind+' ',ind+t.accent((box?.dot||'•')==='*'?'- ':'• '));continue}
|
|
97
|
+
if((m=/^(\s*)(\d+)[.)]\s+(.*)$/.exec(line))){const ind=' '.repeat(Math.min(8,m[1].length)),num=m[2]+'. ';push(inline(m[3],t),ind+' '.repeat(num.length),ind+t.accent(num));continue}
|
|
98
|
+
push(inline(line,t));
|
|
99
|
+
}
|
|
100
|
+
while(out.length&&out.at(-1)==='')out.pop();
|
|
101
|
+
return out;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Incremental rendering for text that grows (the model's reply while it streams). The text is split at the last
|
|
106
|
+
* blank line outside a code fence: everything before it is stable and can be printed for good; the tail is
|
|
107
|
+
* re-rendered on each update.
|
|
108
|
+
*/
|
|
109
|
+
export function splitStable(text){
|
|
110
|
+
const s=String(text??'');let inFence=false,cut=0,pos=0;
|
|
111
|
+
for(const line of s.split('\n')){
|
|
112
|
+
const end=pos+line.length+1;
|
|
113
|
+
if(/^\s*(```|~~~)/.test(line))inFence=!inFence;
|
|
114
|
+
else if(!inFence&&!line.trim()&&end<=s.length)cut=end;
|
|
115
|
+
pos=end;
|
|
116
|
+
}
|
|
117
|
+
return {stable:s.slice(0,cut),tail:s.slice(cut)};
|
|
118
|
+
}
|
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The user's MCP servers for CLI runs (/mcp). Sources, later ones win by server name:
|
|
3
|
+
* ~/.mlai/mcp.json (user) < mcpServers in ~/.mlai/settings.json < .cursor/mcp.json < .mcp.json < .mlai/mcp.json
|
|
4
|
+
* < mcpServers in .mlai/settings.json < mcpServers in .mlai/settings.local.json
|
|
5
|
+
* Every file holds {"mcpServers": {name: {command, args, env, cwd} | {url, headers}}} (the format other tools use), and
|
|
6
|
+
* a server can be turned off with "disabled": true (e.g. in the local settings, without editing a shared file).
|
|
7
|
+
* Servers defined by the repository (the project files and project settings) start programs on this computer, so
|
|
8
|
+
* they run only after the user trusted them (/mcp trust); the trust resets when their definition changes.
|
|
9
|
+
* ${VAR} and ${VAR:-default} expand from this terminal's environment. Expanded env and header values are not written
|
|
10
|
+
* to the session files: they travel to the engine like Vault secrets (MINI_MCP_ENV), see worker/mcp_local.py.
|
|
11
|
+
*/
|
|
12
|
+
import {readFileSync} from 'node:fs';
|
|
13
|
+
import {mkdir,readFile,writeFile,rename} from 'node:fs/promises';
|
|
14
|
+
import {spawn} from 'node:child_process';
|
|
15
|
+
import path from 'node:path';
|
|
16
|
+
import {home} from '../home.mjs';
|
|
17
|
+
import {isTrusted,setTrusted,readLayer} from './permissions.mjs';
|
|
18
|
+
import {extState} from './ext-state.mjs';
|
|
19
|
+
import {authHeader,authStatus} from './mcp-oauth.mjs';
|
|
20
|
+
|
|
21
|
+
export const NAME=/^[A-Za-z0-9][A-Za-z0-9_-]{0,47}$/;
|
|
22
|
+
const isObj=v=>v!==null&&typeof v==='object'&&!Array.isArray(v);
|
|
23
|
+
export function mcpFiles(root){
|
|
24
|
+
// --mcp-config files come last (they win); with --strict-mcp-config they are the only source.
|
|
25
|
+
const flagged=extState.mcpConfigs.map(c=>({id:c.id,servers:c.servers,scope:'flag',repo:false}));
|
|
26
|
+
if(extState.strictMcp)return flagged;
|
|
27
|
+
const plugins=extState.pluginServers||[];
|
|
28
|
+
return [
|
|
29
|
+
{id:'user',file:path.join(home(),'mcp.json'),scope:'user',repo:false},
|
|
30
|
+
{id:'settings:user',settings:'user',scope:'user',repo:false},
|
|
31
|
+
...(root?[
|
|
32
|
+
{id:'.cursor/mcp.json',file:path.join(root,'.cursor','mcp.json'),scope:'project',repo:true},
|
|
33
|
+
{id:'.mcp.json',file:path.join(root,'.mcp.json'),scope:'project',repo:true},
|
|
34
|
+
{id:'.mlai/mcp.json',file:path.join(root,'.mlai','mcp.json'),scope:'project',repo:true},
|
|
35
|
+
{id:'settings:project',settings:'project',scope:'project',repo:true},
|
|
36
|
+
{id:'settings:local',settings:'local',scope:'local',repo:false},
|
|
37
|
+
]:[]),
|
|
38
|
+
...plugins.map(p=>({id:'plugin:'+p.id,servers:p.servers,scope:'plugin',repo:false})),
|
|
39
|
+
...flagged,
|
|
40
|
+
];
|
|
41
|
+
}
|
|
42
|
+
function readServers(src,root){
|
|
43
|
+
if(src.servers)return isObj(src.servers)?src.servers:{};
|
|
44
|
+
if(src.settings){const v=readLayer(root,src.settings).mcpServers;return isObj(v)?v:{}}
|
|
45
|
+
try{const v=JSON.parse(readFileSync(src.file,'utf8'));return isObj(v?.mcpServers)?v.mcpServers:isObj(v?.servers)?v.servers:{}}catch{return {}}
|
|
46
|
+
}
|
|
47
|
+
/** Servers defined by the repository, as one object (what /mcp trust records). */
|
|
48
|
+
export function repoServers(root){
|
|
49
|
+
const out={};for(const s of mcpFiles(root).filter(s=>s.repo))for(const [k,v] of Object.entries(readServers(s,root)))out[k]={...(out[k]||{}),...(isObj(v)?v:{})};
|
|
50
|
+
return out;
|
|
51
|
+
}
|
|
52
|
+
/** [{name, spec, source, scope, transport, enabled, trusted, problem}] */
|
|
53
|
+
export function listServers(root){
|
|
54
|
+
const byName=new Map();
|
|
55
|
+
for(const src of mcpFiles(root)){
|
|
56
|
+
for(const [name,spec] of Object.entries(readServers(src,root))){
|
|
57
|
+
if(!isObj(spec))continue;
|
|
58
|
+
const prev=byName.get(name);
|
|
59
|
+
const merged=prev?{...prev.spec,...spec}:{...spec};
|
|
60
|
+
byName.set(name,{name,spec:merged,source:spec.command||spec.url?src.id:(prev?.source||src.id),scope:spec.command||spec.url?src.scope:(prev?.scope||src.scope),repo:spec.command||spec.url?src.repo:(prev?.repo??src.repo)});
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
const repoTrusted=isTrusted(root,'mcp',repoServers(root));
|
|
64
|
+
return [...byName.values()].map(s=>{
|
|
65
|
+
const problem=!NAME.test(s.name)?'name must be letters, digits, - or _':s.name==='mlai'?'the name mlai is reserved':!(typeof s.spec.command==='string'&&s.spec.command.trim())&&!(typeof s.spec.url==='string'&&/^https?:\/\//.test(s.spec.url))?'needs a command or an http(s) url':null;
|
|
66
|
+
const enabled=s.spec.disabled!==true&&s.spec.enabled!==false;
|
|
67
|
+
return {...s,transport:transportOf(s.spec),enabled,trusted:!s.repo||repoTrusted,problem,...(s.spec.url?{auth:authStatus(s.name,s.spec.url)}:{})};
|
|
68
|
+
}).sort((a,b)=>a.name.localeCompare(b.name));
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** 'stdio' | 'http' (streamable HTTP) | 'sse' (the older HTTP+SSE transport: "type": "sse" or "transport": "sse"). */
|
|
72
|
+
export const transportOf=spec=>spec.url?(String(spec.type||spec.transport||'').toLowerCase()==='sse'?'sse':'http'):'stdio';
|
|
73
|
+
const REF=/\$\{([A-Za-z_][A-Za-z0-9_]*)(?::-([^}]*))?\}/g;
|
|
74
|
+
export function expand(text,env=process.env){return String(text).replace(REF,(_,k,d)=>env[k]!=null&&env[k]!==''?env[k]:d??'')}
|
|
75
|
+
const hasRef=v=>typeof v==='string'&&/\$\{[A-Za-z_]/.test(v);
|
|
76
|
+
/**
|
|
77
|
+
* What the engine gets: {mcpServers, mcpEnv, skipped:[{name, reason}]}. Only enabled, valid, trusted servers.
|
|
78
|
+
* Values with ${VAR} references in env/headers move to mcpEnv (name -> {VAR: value} or {headers: {...}}).
|
|
79
|
+
*/
|
|
80
|
+
export function engineServers(root,{env=process.env}={}){
|
|
81
|
+
const out={},secret={},skipped=[];
|
|
82
|
+
for(const s of listServers(root)){
|
|
83
|
+
if(!s.enabled)continue;
|
|
84
|
+
if(s.problem){skipped.push({name:s.name,reason:s.problem});continue}
|
|
85
|
+
if(!s.trusted){skipped.push({name:s.name,reason:'defined by the repository and not trusted yet (/mcp trust)'});continue}
|
|
86
|
+
const spec=s.spec,clean={...(spec.readOnly===true?{readOnly:true}:{})};
|
|
87
|
+
if(spec.url){
|
|
88
|
+
clean.url=expand(spec.url,env);const h={},hs={};
|
|
89
|
+
for(const [k,v] of Object.entries(isObj(spec.headers)?spec.headers:{}))(hasRef(v)?hs:h)[k]=expand(v,env);
|
|
90
|
+
// A sign-in from `mlai mcp login` travels like a secret; a header the user set themselves wins.
|
|
91
|
+
const signed=!Object.keys({...h,...hs}).some(k=>k.toLowerCase()==='authorization')&&authHeader(s.name,spec.url);
|
|
92
|
+
if(signed)hs.Authorization=signed;
|
|
93
|
+
if(transportOf(spec)==='sse')clean.transport='sse';
|
|
94
|
+
clean.headers=h;if(Object.keys(hs).length)secret[s.name]={headers:hs};
|
|
95
|
+
}else{
|
|
96
|
+
clean.command=expand(spec.command,env);clean.args=(Array.isArray(spec.args)?spec.args:[]).map(a=>expand(a,env));
|
|
97
|
+
const e={},es={};for(const [k,v] of Object.entries(isObj(spec.env)?spec.env:{}))(hasRef(v)?es:e)[k]=expand(v,env);
|
|
98
|
+
clean.env=e;if(Object.keys(es).length)secret[s.name]=es;
|
|
99
|
+
if(typeof spec.cwd==='string')clean.cwd=path.resolve(root||process.cwd(),expand(spec.cwd,env));
|
|
100
|
+
}
|
|
101
|
+
out[s.name]=clean;
|
|
102
|
+
}
|
|
103
|
+
return {mcpServers:out,mcpEnv:secret,skipped};
|
|
104
|
+
}
|
|
105
|
+
export async function trustRepoServers(root){await setTrusted(root,'mcp',repoServers(root))}
|
|
106
|
+
|
|
107
|
+
/** Writes a server to ~/.mlai/mcp.json (user), .mlai/mcp.json (project) or the local settings (local). */
|
|
108
|
+
export async function addServer({root,settings,scope='local',name,spec}){
|
|
109
|
+
if(!NAME.test(name||'')||name==='mlai')throw new Error('Server names use letters, digits, - and _ (mlai is reserved)');
|
|
110
|
+
if(scope==='local'){
|
|
111
|
+
if(!settings?.save)throw new Error('Local scope needs a project folder');
|
|
112
|
+
const cur=readLayer(root,'local').mcpServers;await settings.save('local','mcpServers',{...(isObj(cur)?cur:{}),[name]:spec},{replace:true});return 'settings.local.json';
|
|
113
|
+
}
|
|
114
|
+
const file=scope==='user'?path.join(home(),'mcp.json'):scope==='project'&&root?path.join(root,'.mlai','mcp.json'):null;
|
|
115
|
+
if(!file)throw new Error('Scope must be user, project or local');
|
|
116
|
+
// The user adding a project server is a review of it: keep the project's servers trusted if they were before.
|
|
117
|
+
const before=scope==='project'?repoServers(root):null,wasTrusted=before&&(!Object.keys(before).length||isTrusted(root,'mcp',before));
|
|
118
|
+
await editJson(file,v=>({...v,mcpServers:{...(isObj(v.mcpServers)?v.mcpServers:{}),[name]:spec}}));
|
|
119
|
+
if(wasTrusted)await trustRepoServers(root);
|
|
120
|
+
return file;
|
|
121
|
+
}
|
|
122
|
+
/** Removes a server from the files this CLI owns; returns the places it was removed from, and where it remains. */
|
|
123
|
+
export async function removeServer({root,settings,name}){
|
|
124
|
+
const removed=[],remains=[];
|
|
125
|
+
for(const src of mcpFiles(root)){
|
|
126
|
+
const servers=readServers(src,root);if(!(name in servers))continue;
|
|
127
|
+
if(src.settings){
|
|
128
|
+
const {[name]:_,...rest}=servers;await settings.save(src.settings,'mcpServers',rest,{replace:true});removed.push('settings:'+src.settings);
|
|
129
|
+
}else if(src.id==='user'||src.id==='.mlai/mcp.json'){
|
|
130
|
+
await editJson(src.file,v=>{const s={...(v.mcpServers||{})};delete s[name];return {...v,mcpServers:s}});removed.push(src.id);
|
|
131
|
+
}else remains.push(src.id);
|
|
132
|
+
}
|
|
133
|
+
return {removed,remains};
|
|
134
|
+
}
|
|
135
|
+
async function editJson(file,fn){
|
|
136
|
+
let cur={};try{const v=JSON.parse(await readFile(file,'utf8'));if(isObj(v))cur=v}catch{}
|
|
137
|
+
const next=fn(cur);await mkdir(path.dirname(file),{recursive:true});
|
|
138
|
+
const tmp=file+'.'+process.pid+'.tmp';await writeFile(tmp,JSON.stringify(next,null,2)+'\n',{mode:0o600});await rename(tmp,file);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// ------------------------------------------------------------------ minimal MCP client, for /mcp tools
|
|
142
|
+
const INIT={protocolVersion:'2025-03-26',capabilities:{},clientInfo:{name:'mlai-code',version:'1'}};
|
|
143
|
+
export async function listTools(spec,{root=process.cwd(),timeout=20000,env=process.env,secretEnv={},name=null}={}){
|
|
144
|
+
if(name)spec={...spec,name};
|
|
145
|
+
const call=spec.url?(transportOf(spec)==='sse'?sseClient(spec,timeout,secretEnv):httpClient(spec,timeout,secretEnv)):stdioClient(spec,root,timeout,env,secretEnv);
|
|
146
|
+
try{
|
|
147
|
+
await call.request('initialize',INIT);call.notify('notifications/initialized');
|
|
148
|
+
const tools=[];let cursor;
|
|
149
|
+
for(let i=0;i<10;i++){const r=await call.request('tools/list',cursor?{cursor}:{});tools.push(...(r?.tools||[]).filter(t=>t&&typeof t.name==='string'));cursor=r?.nextCursor;if(!cursor)break}
|
|
150
|
+
return tools.map(t=>({name:t.name,description:String(t.description||'').slice(0,300),readOnly:!!t.annotations?.readOnlyHint}));
|
|
151
|
+
}finally{call.close()}
|
|
152
|
+
}
|
|
153
|
+
function stdioClient(spec,root,timeout,env,secretEnv){
|
|
154
|
+
const childEnv={...env,...(spec.env||{}),...secretEnv};
|
|
155
|
+
const p=spawn(spec.command,spec.args||[],{cwd:spec.cwd||root,env:childEnv,stdio:['pipe','pipe','ignore']});
|
|
156
|
+
let buf='',id=0,dead=null;const waiting=new Map();
|
|
157
|
+
p.on('error',e=>{dead=new Error('Could not start '+spec.command+': '+e.message);for(const w of waiting.values())w.reject(dead);waiting.clear()});
|
|
158
|
+
p.on('exit',()=>{dead??=new Error('The server exited');for(const w of waiting.values())w.reject(dead);waiting.clear()});
|
|
159
|
+
p.stdout.on('data',d=>{buf+=d;let i;while((i=buf.indexOf('\n'))>=0){const line=buf.slice(0,i);buf=buf.slice(i+1);let m;try{m=JSON.parse(line)}catch{continue}const w=waiting.get(m?.id);if(w){waiting.delete(m.id);m.error?w.reject(new Error(String(m.error.message||'Server error'))):w.resolve(m.result)}}});
|
|
160
|
+
p.stdin.on('error',()=>{});
|
|
161
|
+
return {
|
|
162
|
+
request(method,params){if(dead)return Promise.reject(dead);const n=++id;p.stdin.write(JSON.stringify({jsonrpc:'2.0',id:n,method,params})+'\n');
|
|
163
|
+
return new Promise((resolve,reject)=>{const t=setTimeout(()=>{waiting.delete(n);reject(new Error('No answer from the server within '+Math.round(timeout/1000)+' seconds'))},timeout);waiting.set(n,{resolve:v=>{clearTimeout(t);resolve(v)},reject:e=>{clearTimeout(t);reject(e)}})})},
|
|
164
|
+
notify(method){if(!dead)p.stdin.write(JSON.stringify({jsonrpc:'2.0',method})+'\n')},
|
|
165
|
+
close(){try{p.stdin.end();p.kill()}catch{}},
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
function httpClient(spec,timeout,secretEnv){
|
|
169
|
+
let id=0,session=null;const headers={...(spec.headers||{}),...(secretEnv.headers||{})};
|
|
170
|
+
const post=async(msg)=>{
|
|
171
|
+
const r=await fetch(spec.url,{method:'POST',headers:{'content-type':'application/json',accept:'application/json, text/event-stream',...headers,...(session?{'mcp-session-id':session}:{})},body:JSON.stringify(msg),signal:AbortSignal.timeout(timeout)})
|
|
172
|
+
.catch(e=>{throw new Error('Could not reach the server: '+(e.cause?.code||e.message))});
|
|
173
|
+
session=r.headers.get('mcp-session-id')||session;
|
|
174
|
+
if(r.status===401)throw new Error('the server wants a sign-in (HTTP 401); run mlai mcp login '+(spec.name||'<name>'));
|
|
175
|
+
if(!r.ok)throw new Error('HTTP '+r.status+' from the server');
|
|
176
|
+
return r;
|
|
177
|
+
};
|
|
178
|
+
return {
|
|
179
|
+
async request(method,params){
|
|
180
|
+
const n=++id;const r=await post({jsonrpc:'2.0',id:n,method,params});const text=await r.text();
|
|
181
|
+
const msgs=(r.headers.get('content-type')||'').includes('text/event-stream')?text.split('\n').filter(l=>l.startsWith('data:')).map(l=>{try{return JSON.parse(l.slice(5))}catch{return null}}):[(()=>{try{return JSON.parse(text)}catch{return null}})()];
|
|
182
|
+
const m=msgs.find(x=>x?.id===n);if(!m)throw new Error('The server did not answer the request');
|
|
183
|
+
if(m.error)throw new Error(String(m.error.message||'Server error'));return m.result;
|
|
184
|
+
},
|
|
185
|
+
notify(method){post({jsonrpc:'2.0',method}).catch(()=>{})},
|
|
186
|
+
close(){},
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
/** The older HTTP+SSE transport: GET opens an event stream whose "endpoint" event names the URL to POST messages to;
|
|
190
|
+
* answers arrive on the stream. */
|
|
191
|
+
function sseClient(spec,timeout,secretEnv){
|
|
192
|
+
const headers={...(spec.headers||{}),...(secretEnv.headers||{})};const ctl=new AbortController();
|
|
193
|
+
let id=0,endpoint=null,dead=null;const waiting=new Map();let ready;const opened=new Promise((ok,fail)=>{ready={ok,fail}});
|
|
194
|
+
const fail=e=>{dead=e;ready.fail(e);for(const w of waiting.values())w.reject(e);waiting.clear()};
|
|
195
|
+
(async()=>{
|
|
196
|
+
const r=await fetch(spec.url,{headers:{accept:'text/event-stream',...headers},signal:ctl.signal});
|
|
197
|
+
if(r.status===401)throw new Error('the server wants a sign-in (HTTP 401); run mlai mcp login '+(spec.name||'<name>'));
|
|
198
|
+
if(!r.ok||!r.body)throw new Error('HTTP '+r.status+' from the server');
|
|
199
|
+
const dec=new TextDecoder();let buf='';
|
|
200
|
+
for await(const chunk of r.body){
|
|
201
|
+
buf+=dec.decode(chunk,{stream:true}).replace(/\r\n/g,'\n');let i;
|
|
202
|
+
while((i=buf.indexOf('\n\n'))>=0){
|
|
203
|
+
const block=buf.slice(0,i);buf=buf.slice(i+2);
|
|
204
|
+
const ev=(/^event:\s*(.*)$/m.exec(block)||[])[1]||'message',data=block.split('\n').filter(l=>l.startsWith('data:')).map(l=>l.slice(5).replace(/^ /,'')).join('\n');
|
|
205
|
+
if(ev==='endpoint'){endpoint=new URL(data.trim(),spec.url).toString();ready.ok()}
|
|
206
|
+
else{let m;try{m=JSON.parse(data)}catch{continue}const w=waiting.get(m?.id);if(w){waiting.delete(m.id);m.error?w.reject(new Error(String(m.error.message||'Server error'))):w.resolve(m.result)}}
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
throw new Error('The server closed the event stream');
|
|
210
|
+
})().catch(e=>{if(!ctl.signal.aborted)fail(e.name==='TypeError'?new Error('Could not reach the server: '+(e.cause?.code||e.message)):e)});
|
|
211
|
+
const post=async msg=>{
|
|
212
|
+
await Promise.race([opened,new Promise((_,f)=>setTimeout(()=>f(new Error('The server sent no endpoint within '+Math.round(timeout/1000)+' seconds')),timeout).unref?.())]);
|
|
213
|
+
const r=await fetch(endpoint,{method:'POST',headers:{'content-type':'application/json',...headers},body:JSON.stringify(msg),signal:AbortSignal.timeout(timeout)});
|
|
214
|
+
if(!r.ok&&r.status!==202)throw new Error('HTTP '+r.status+' from the server');await r.text().catch(()=>{});
|
|
215
|
+
};
|
|
216
|
+
return {
|
|
217
|
+
async request(method,params){
|
|
218
|
+
if(dead)throw dead;const n=++id;
|
|
219
|
+
const p=new Promise((resolve,reject)=>{const t=setTimeout(()=>{waiting.delete(n);reject(new Error('No answer from the server within '+Math.round(timeout/1000)+' seconds'))},timeout);waiting.set(n,{resolve:v=>{clearTimeout(t);resolve(v)},reject:e=>{clearTimeout(t);reject(e)}})});
|
|
220
|
+
await post({jsonrpc:'2.0',id:n,method,params});return p;
|
|
221
|
+
},
|
|
222
|
+
notify(method){post({jsonrpc:'2.0',method}).catch(()=>{})},
|
|
223
|
+
close(){ctl.abort()},
|
|
224
|
+
};
|
|
225
|
+
}
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Sign-in for remote MCP servers that use OAuth (the MCP authorization spec): `mlai mcp login <name>` and
|
|
3
|
+
* `mlai mcp logout <name>`, also /mcp login and /mcp logout in a session.
|
|
4
|
+
* 1. Discovery: the server's 401 WWW-Authenticate resource_metadata, else /.well-known/oauth-protected-resource
|
|
5
|
+
* (RFC 9728); then the authorization server's /.well-known/oauth-authorization-server or openid-configuration
|
|
6
|
+
* (RFC 8414). Servers without metadata fall back to /authorize, /token and /register on their own origin.
|
|
7
|
+
* 2. Dynamic client registration (RFC 7591) when the server offers it; otherwise the server's "oauth": {"clientId"}
|
|
8
|
+
* in the MCP config (or --client-id).
|
|
9
|
+
* 3. Authorization code with PKCE (S256) and the resource parameter (RFC 8707), redirected to a loopback port on
|
|
10
|
+
* this computer. --no-browser prints the link instead and accepts the address the browser ends on, pasted back.
|
|
11
|
+
* Tokens are kept in ~/.mlai/mcp-auth.json (owner-only), never in settings or session files. Each run gets the access
|
|
12
|
+
* token as an Authorization header through the MCP secret channel (MINI_MCP_ENV), refreshed when it is about to expire.
|
|
13
|
+
*/
|
|
14
|
+
import {readFileSync} from 'node:fs';
|
|
15
|
+
import {mkdir,writeFile,rename,readFile} from 'node:fs/promises';
|
|
16
|
+
import {createServer} from 'node:http';
|
|
17
|
+
import {createHash,randomBytes} from 'node:crypto';
|
|
18
|
+
import path from 'node:path';
|
|
19
|
+
import {home} from '../home.mjs';
|
|
20
|
+
|
|
21
|
+
const isObj=v=>v!==null&&typeof v==='object'&&!Array.isArray(v);
|
|
22
|
+
export const authFile=()=>path.join(home(),'mcp-auth.json');
|
|
23
|
+
const b64url=buf=>Buffer.from(buf).toString('base64').replace(/\+/g,'-').replace(/\//g,'_').replace(/=+$/,'');
|
|
24
|
+
|
|
25
|
+
export function readAuth(){try{const v=JSON.parse(readFileSync(authFile(),'utf8'));return isObj(v)?v:{}}catch{return {}}}
|
|
26
|
+
async function writeAuth(all){
|
|
27
|
+
const f=authFile();await mkdir(path.dirname(f),{recursive:true,mode:0o700});
|
|
28
|
+
const tmp=f+'.'+process.pid+'.tmp';await writeFile(tmp,JSON.stringify(all,null,2)+'\n',{mode:0o600});await rename(tmp,f);
|
|
29
|
+
}
|
|
30
|
+
async function update(name,fn){let all={};try{const v=JSON.parse(await readFile(authFile(),'utf8'));if(isObj(v))all=v}catch{}const next=fn(all[name]);if(next)all[name]=next;else delete all[name];await writeAuth(all);return next}
|
|
31
|
+
|
|
32
|
+
/** The stored sign-in for a server, when it belongs to this URL. */
|
|
33
|
+
export function tokenFor(name,url,all=readAuth()){const t=all[name];return isObj(t)&&t.url===url&&typeof t.access_token==='string'?t:null}
|
|
34
|
+
/** Authorization header for a server, or null. Expired tokens without a refresh token are not sent. */
|
|
35
|
+
export function authHeader(name,url,{now=Date.now(),all}={}){
|
|
36
|
+
const t=tokenFor(name,url,all);if(!t)return null;
|
|
37
|
+
if(t.expires_at&&t.expires_at<=now&&!t.refresh_token)return null;
|
|
38
|
+
return (t.token_type&&/^bearer$/i.test(t.token_type)?'Bearer':t.token_type||'Bearer')+' '+t.access_token;
|
|
39
|
+
}
|
|
40
|
+
/** 'signed in' | 'expired' | null, for /mcp list. */
|
|
41
|
+
export function authStatus(name,url,now=Date.now()){const t=tokenFor(name,url);if(!t)return null;return t.expires_at&&t.expires_at<=now&&!t.refresh_token?'expired':'signed in'}
|
|
42
|
+
|
|
43
|
+
const json=async(r,what)=>{const text=await r.text();try{return JSON.parse(text)}catch{throw new Error(what+' did not return JSON (HTTP '+r.status+')')}};
|
|
44
|
+
async function getJson(fetcher,url){try{const r=await fetcher(url,{headers:{accept:'application/json'},signal:AbortSignal.timeout(15000)});if(!r.ok)return null;return await r.json()}catch{return null}}
|
|
45
|
+
/** RFC 8414 path-aware well-known URL: https://as/tenant -> https://as/.well-known/<kind>/tenant */
|
|
46
|
+
const wellKnown=(base,kind)=>{const u=new URL(base);const p=u.pathname.replace(/\/$/,'');return [u.origin+'/.well-known/'+kind+(p&&p!=='/'?p:''),...(p&&p!=='/'?[u.origin+'/.well-known/'+kind]:[])]};
|
|
47
|
+
|
|
48
|
+
/** Finds the authorization server for an MCP URL: {resource, issuer, authorization_endpoint, token_endpoint, registration_endpoint?, revocation_endpoint?, scopes?}. */
|
|
49
|
+
export async function discover(url,{fetcher=fetch}={}){
|
|
50
|
+
let metaUrl=null;
|
|
51
|
+
try{
|
|
52
|
+
const r=await fetcher(url,{method:'POST',headers:{'content-type':'application/json',accept:'application/json, text/event-stream'},body:JSON.stringify({jsonrpc:'2.0',id:1,method:'initialize',params:{protocolVersion:'2025-06-18',capabilities:{},clientInfo:{name:'mlai-code',version:'1'}}})});
|
|
53
|
+
const h=r.headers.get('www-authenticate')||'';const m=/resource_metadata="([^"]+)"/i.exec(h);if(m)metaUrl=new URL(m[1],url).toString();
|
|
54
|
+
await r.text().catch(()=>{});
|
|
55
|
+
}catch(e){throw new Error('Could not reach '+url+': '+(e.cause?.code||e.message))}
|
|
56
|
+
let prm=null;
|
|
57
|
+
for(const u of metaUrl?[metaUrl]:wellKnown(url,'oauth-protected-resource')){prm=await getJson(fetcher,u);if(prm)break}
|
|
58
|
+
const issuer=Array.isArray(prm?.authorization_servers)&&prm.authorization_servers[0]?String(prm.authorization_servers[0]):new URL(url).origin;
|
|
59
|
+
let as=null;
|
|
60
|
+
for(const u of [...wellKnown(issuer,'oauth-authorization-server'),...wellKnown(issuer,'openid-configuration')]){as=await getJson(fetcher,u);if(as?.authorization_endpoint&&as?.token_endpoint)break;as=null}
|
|
61
|
+
const o=new URL(issuer).origin;
|
|
62
|
+
as??={authorization_endpoint:o+'/authorize',token_endpoint:o+'/token',registration_endpoint:o+'/register'};
|
|
63
|
+
// Tokens and codes only travel over https (or to this computer, for local servers).
|
|
64
|
+
for(const e of [as.authorization_endpoint,as.token_endpoint,as.registration_endpoint,as.revocation_endpoint].filter(Boolean)){
|
|
65
|
+
let u;try{u=new URL(e)}catch{throw new Error('The sign-in server gave an invalid address: '+e)}
|
|
66
|
+
if(u.protocol!=='https:'&&!(u.protocol==='http:'&&/^(127\.0\.0\.1|localhost|\[::1\])$/.test(u.hostname)))throw new Error('The sign-in server must use https:// ('+u.origin+' does not).');
|
|
67
|
+
}
|
|
68
|
+
return {resource:String(prm?.resource||url),issuer:as.issuer||issuer,authorization_endpoint:as.authorization_endpoint,token_endpoint:as.token_endpoint,
|
|
69
|
+
...(as.registration_endpoint?{registration_endpoint:as.registration_endpoint}:{}),...(as.revocation_endpoint?{revocation_endpoint:as.revocation_endpoint}:{}),
|
|
70
|
+
scopes:Array.isArray(prm?.scopes_supported)?prm.scopes_supported:Array.isArray(as.scopes_supported)?as.scopes_supported:[]};
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
async function register(meta,redirect,fetcher){
|
|
74
|
+
const r=await fetcher(meta.registration_endpoint,{method:'POST',headers:{'content-type':'application/json',accept:'application/json'},
|
|
75
|
+
body:JSON.stringify({client_name:'ML AI Code',redirect_uris:[redirect],grant_types:['authorization_code','refresh_token'],response_types:['code'],token_endpoint_auth_method:'none'})});
|
|
76
|
+
if(!r.ok)throw new Error('The server refused client registration (HTTP '+r.status+'). Set "oauth": {"clientId": "..."} for this server, or pass --client-id.');
|
|
77
|
+
const v=await json(r,'Client registration');if(!v.client_id)throw new Error('Client registration returned no client id');
|
|
78
|
+
return {clientId:String(v.client_id),...(v.client_secret?{clientSecret:String(v.client_secret)}:{})};
|
|
79
|
+
}
|
|
80
|
+
async function tokenRequest(endpoint,params,fetcher){
|
|
81
|
+
const r=await fetcher(endpoint,{method:'POST',headers:{'content-type':'application/x-www-form-urlencoded',accept:'application/json'},body:new URLSearchParams(params).toString(),signal:AbortSignal.timeout(20000)});
|
|
82
|
+
const v=await json(r,'The token endpoint');
|
|
83
|
+
if(!r.ok||!v.access_token)throw new Error('Sign-in failed: '+String(v.error_description||v.error||('HTTP '+r.status)).slice(0,200));
|
|
84
|
+
return v;
|
|
85
|
+
}
|
|
86
|
+
const stamp=(v,now)=>({access_token:String(v.access_token),token_type:String(v.token_type||'Bearer'),...(v.refresh_token?{refresh_token:String(v.refresh_token)}:{}),
|
|
87
|
+
...(v.expires_in?{expires_at:now+Number(v.expires_in)*1000}:{}),...(v.scope?{scope:String(v.scope)}:{})});
|
|
88
|
+
|
|
89
|
+
/** Waits for one request to /callback on a loopback port. Returns {redirect, wait(): Promise<URL>, close()}. */
|
|
90
|
+
async function loopback(){
|
|
91
|
+
let resolve;const got=new Promise(r=>{resolve=r});
|
|
92
|
+
const server=createServer((req,res)=>{
|
|
93
|
+
const u=new URL(req.url,'http://127.0.0.1');
|
|
94
|
+
if(u.pathname!=='/callback'){res.writeHead(404).end();return}
|
|
95
|
+
res.writeHead(200,{'content-type':'text/html; charset=utf-8'}).end('<!doctype html><title>ML AI Code</title><p style="font:16px system-ui;margin:40px">Signed in. You can close this tab and go back to the terminal.</p>');
|
|
96
|
+
resolve(u);
|
|
97
|
+
});
|
|
98
|
+
await new Promise((ok,fail)=>{server.once('error',fail);server.listen(0,'127.0.0.1',ok)});
|
|
99
|
+
return {redirect:'http://127.0.0.1:'+server.address().port+'/callback',wait:()=>got,close:()=>server.close()};
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Signs in to a server. spec is the server's config ({url, oauth?:{clientId, clientSecret, scopes}}).
|
|
104
|
+
* open(url) opens a browser (skipped with noBrowser); prompt(question) reads a pasted line (for --no-browser);
|
|
105
|
+
* print(text) shows progress. Returns the stored record without its tokens.
|
|
106
|
+
*/
|
|
107
|
+
export async function login(name,spec,{fetcher=fetch,open=()=>{},prompt=null,print=()=>{},noBrowser=false,clientId=null,scope=null,now=()=>Date.now(),timeout=300000}={}){
|
|
108
|
+
if(!spec?.url)throw new Error(name+' is not a remote (URL) server; only those use sign-in.');
|
|
109
|
+
const meta=await discover(spec.url,{fetcher});
|
|
110
|
+
const cb=await loopback();
|
|
111
|
+
try{
|
|
112
|
+
const prev=readAuth()[name];
|
|
113
|
+
let client=clientId||spec.oauth?.clientId?{clientId:clientId||spec.oauth.clientId,...(spec.oauth?.clientSecret?{clientSecret:spec.oauth.clientSecret}:{})}
|
|
114
|
+
:prev?.clientId&&prev.issuer===meta.issuer&&prev.redirect===cb.redirect?{clientId:prev.clientId,...(prev.clientSecret?{clientSecret:prev.clientSecret}:{})}:null;
|
|
115
|
+
if(!client){
|
|
116
|
+
if(!meta.registration_endpoint)throw new Error(name+' does not offer client registration. Set "oauth": {"clientId": "..."} for it in the MCP config, or pass --client-id.');
|
|
117
|
+
client=await register(meta,cb.redirect,fetcher);
|
|
118
|
+
}
|
|
119
|
+
const verifier=b64url(randomBytes(32)),state=b64url(randomBytes(16));
|
|
120
|
+
const challenge=b64url(createHash('sha256').update(verifier).digest());
|
|
121
|
+
const scopes=scope||(Array.isArray(spec.oauth?.scopes)?spec.oauth.scopes.join(' '):meta.scopes.join(' '));
|
|
122
|
+
const auth=new URL(meta.authorization_endpoint);
|
|
123
|
+
for(const [k,v] of Object.entries({response_type:'code',client_id:client.clientId,redirect_uri:cb.redirect,code_challenge:challenge,code_challenge_method:'S256',state,resource:meta.resource,...(scopes?{scope:scopes}:{})}))auth.searchParams.set(k,v);
|
|
124
|
+
print((noBrowser?'Open this link in a browser to sign in to ':'Opening your browser to sign in to ')+name+':\n '+auth+'\n');
|
|
125
|
+
if(!noBrowser)open(auth.toString());
|
|
126
|
+
const pasted=noBrowser&&prompt?(async()=>{const line=await prompt('After signing in, paste the address the browser ended on (it starts with '+cb.redirect+'): ');if(!line)throw new Error('Sign-in cancelled.');return new URL(line.trim())})():null;
|
|
127
|
+
const timer=new Promise((_,fail)=>{const t=setTimeout(()=>fail(new Error('Sign-in timed out after '+Math.round(timeout/60000)+' minutes.')),timeout);t.unref?.()});
|
|
128
|
+
const back=await Promise.race([cb.wait(),...(pasted?[pasted]:[]),timer]);
|
|
129
|
+
if(back.searchParams.get('error'))throw new Error('Sign-in refused: '+(back.searchParams.get('error_description')||back.searchParams.get('error')));
|
|
130
|
+
if(back.searchParams.get('state')!==state)throw new Error('Sign-in failed: the reply does not match this request (state). Try again.');
|
|
131
|
+
const code=back.searchParams.get('code');if(!code)throw new Error('Sign-in failed: no authorization code in the reply.');
|
|
132
|
+
const tok=await tokenRequest(meta.token_endpoint,{grant_type:'authorization_code',code,redirect_uri:cb.redirect,client_id:client.clientId,code_verifier:verifier,resource:meta.resource,...(client.clientSecret?{client_secret:client.clientSecret}:{})},fetcher);
|
|
133
|
+
const rec={url:spec.url,issuer:meta.issuer,resource:meta.resource,tokenEndpoint:meta.token_endpoint,...(meta.revocation_endpoint?{revocationEndpoint:meta.revocation_endpoint}:{}),
|
|
134
|
+
clientId:client.clientId,...(client.clientSecret?{clientSecret:client.clientSecret}:{}),redirect:cb.redirect,...stamp(tok,now()),saved:new Date(now()).toISOString()};
|
|
135
|
+
await update(name,()=>rec);
|
|
136
|
+
const {access_token,refresh_token,clientSecret,...shown}=rec;return shown;
|
|
137
|
+
}finally{cb.close()}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** Refreshes tokens that expire within `margin` ms. Failures are kept quiet here and show as "expired" in /mcp. */
|
|
141
|
+
export async function refreshDue(names=null,{fetcher=fetch,now=Date.now(),margin=60000}={}){
|
|
142
|
+
const all=readAuth();const done=[];
|
|
143
|
+
for(const [name,t] of Object.entries(all)){
|
|
144
|
+
if(names&&!names.includes(name))continue;
|
|
145
|
+
if(!isObj(t)||!t.refresh_token||!t.expires_at||t.expires_at>now+margin)continue;
|
|
146
|
+
try{
|
|
147
|
+
const v=await tokenRequest(t.tokenEndpoint,{grant_type:'refresh_token',refresh_token:t.refresh_token,client_id:t.clientId,...(t.resource?{resource:t.resource}:{}),...(t.clientSecret?{client_secret:t.clientSecret}:{})},fetcher);
|
|
148
|
+
await update(name,cur=>({...cur,...stamp(v,now),refresh_token:v.refresh_token||cur.refresh_token}));done.push(name);
|
|
149
|
+
}catch{}
|
|
150
|
+
}
|
|
151
|
+
return done;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** Forgets a server's sign-in, telling the server when it supports revocation (RFC 7009). */
|
|
155
|
+
export async function logout(name,{fetcher=fetch}={}){
|
|
156
|
+
const t=readAuth()[name];if(!t)return false;
|
|
157
|
+
if(t.revocationEndpoint)for(const [token,hint] of [[t.refresh_token,'refresh_token'],[t.access_token,'access_token']]){
|
|
158
|
+
if(!token)continue;
|
|
159
|
+
try{await fetcher(t.revocationEndpoint,{method:'POST',headers:{'content-type':'application/x-www-form-urlencoded'},body:new URLSearchParams({token,token_type_hint:hint,client_id:t.clientId}).toString(),signal:AbortSignal.timeout(10000)})}catch{}
|
|
160
|
+
}
|
|
161
|
+
await update(name,()=>null);return true;
|
|
162
|
+
}
|