lake-gate 0.0.0-stage → 0.2.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/src/mcp.js ADDED
@@ -0,0 +1,312 @@
1
+ // lake-gate MCP server (stdio). Lets Claude Code, Cursor or any MCP client:
2
+ // author side: request review on a plan, wait for the verdict, read anchored feedback, submit a revision;
3
+ // reviewer side: read a plan with its threads, reply, approve or request changes from the agent chat.
4
+ // Everything is read from and written to the PR (the single source of truth), with the GitHub token
5
+ // already on this machine (GITHUB_TOKEN, GH_TOKEN or `gh auth token`). No Lake server.
6
+ import fs from 'node:fs';
7
+ import path from 'node:path';
8
+ import { execFileSync } from 'node:child_process';
9
+ import { repoRoot, loadPlan, getState, exportPlan, listPlans } from './store.js';
10
+ import { client } from './github.js';
11
+ import { parseRemote, applyEvents } from './sync.js';
12
+ import { collectEvents, nativeDigests } from './github.js';
13
+ import { loadPr, actions } from './workspace.js';
14
+ import { loadConfig } from './config.js';
15
+ import { range, money, estimatePlan } from './estimate.js';
16
+ import { costSuggestions, modelOptions, applyPatch, resolveModel, describePatch } from './models.js';
17
+ import { stripEstimate } from './plan.js';
18
+ import { acceptBody } from './review.js';
19
+
20
+ const VERSION = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
21
+ const sh = (cmd, args, cwd) => { try { return execFileSync(cmd, args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim(); } catch { return null; } };
22
+
23
+ const S = (props, required = []) => ({ type: 'object', properties: props, required, additionalProperties: false });
24
+ const str = (d) => ({ type: 'string', description: d });
25
+
26
+ // Four tools, on purpose. Author side: request_review → review_status → submit_revision. Reviewer side: review.
27
+ export const TOOLS = [
28
+ { name: 'lake_request_review', description: 'Save a plan (markdown) as a versioned lake-gate plan and ask teammates to review it on the PR. Returns the plan id, version, model and cost estimate, and the review link. Use after planning, before implementing. Tip: add a "Model: <name>" line to declare which model runs it.',
29
+ inputSchema: S({ plan_markdown: str('Full plan in markdown. Omit to request review of an existing plan.'), plan_id: str('Plan id (defaults to the active plan, or derived from the title)'),
30
+ reviewers: { type: 'array', items: { type: 'string' }, description: 'GitHub logins to request review from' }, note: str('Short note to reviewers'),
31
+ push: { type: 'boolean', description: 'Commit only the plan file and push the current branch (so the PR shows this version)' } }), annotations: { openWorldHint: true } },
32
+ { name: 'lake_review_status', description: 'Review state of a plan: status, verdicts with notes, open comment threads anchored to plan lines, reviewer suggestions, budget approval, and the model/cost view with Lake\'s cost-cutting suggestion ids. Works locally before a PR exists. Set wait_seconds to wait for a decision or new feedback. Also syncs approvals so the lake-gate hook opens once approved.',
33
+ inputSchema: S({ plan_id: str('Plan id (defaults to the active plan)'), wait_seconds: { type: 'number', minimum: 0, maximum: 240, description: 'Wait up to this long for a change (polls every 20s)' } }), annotations: { readOnlyHint: true, openWorldHint: true } },
34
+ { name: 'lake_submit_revision', description: 'As the author, save a new plan version (earlier approvals no longer apply) and tell reviewers. Either pass the full revised plan_markdown, or apply a suggestion in one step: thread_id (a reviewer suggestion), suggestion_id (from lake_review_status) or model (run the whole plan on that model). Can also reply to threads and mark them resolved.',
35
+ inputSchema: S({ plan_markdown: str('Full revised plan in markdown'), plan_id: str('Plan id (defaults to the active plan)'),
36
+ thread_id: str('Accept this reviewer suggestion thread'), suggestion_id: str('Apply this Lake suggestion, e.g. models-2-4, cap-12, drop-5'), model: str('Run the whole plan on this model, e.g. sonnet'),
37
+ addressed_threads: { type: 'array', items: { type: 'string' }, description: 'Thread ids this revision addresses (marked resolved)' },
38
+ note: str('What changed, for reviewers'), push: { type: 'boolean', description: 'Commit only the plan file and push' } }), annotations: { openWorldHint: true } },
39
+ { name: 'lake_review', description: 'As a reviewer, act on a plan PR: approve, request_changes, comment (optionally on lines), reply (in a thread) or suggest (a structured change the author accepts in one click: suggestion_id or model). approve and request_changes post as the human GitHub account on this machine: ONLY use them when the user explicitly said so in this conversation, and pass the exact version they saw.',
40
+ inputSchema: S({ action: { type: 'string', enum: ['approve', 'request_changes', 'comment', 'reply', 'suggest'] }, plan_id: str('Plan id'), version: str('8-character version (approve / request_changes)'),
41
+ text: str('Comment, reply, or verdict note (required for request_changes)'), line: { type: 'number', description: 'First plan line to anchor a comment' }, end_line: { type: 'number' },
42
+ thread_id: str('Thread to reply in'), suggestion_id: str('Lake suggestion id to propose'), model: str('Propose running the plan on this model') }, ['action']), annotations: { openWorldHint: true } },
43
+ ];
44
+ // Older tool names still work (not listed): lake_approve, lake_request_changes, lake_comment, lake_reply, lake_cost, lake_suggest, lake_apply_suggestion.
45
+ const ALIASES = {
46
+ lake_approve: (a) => ['lake_review', { ...a, action: 'approve', text: a.comment }],
47
+ lake_request_changes: (a) => ['lake_review', { ...a, action: 'request_changes', text: a.comment }],
48
+ lake_comment: (a) => ['lake_review', { ...a, action: 'comment' }],
49
+ lake_reply: (a) => ['lake_review', { ...a, action: 'reply' }],
50
+ lake_suggest: (a) => ['lake_review', { ...a, action: 'suggest', text: a.comment }],
51
+ lake_apply_suggestion: (a) => ['lake_submit_revision', a],
52
+ lake_cost: (a) => ['lake_cost', a],
53
+ };
54
+
55
+ export function formatCost(est, config, sugg = costSuggestions(est, config), budget) {
56
+ const L = [];
57
+ L.push(`Cost: ${est.declared ? `${range(est.plannedUsd)} with the planned model${est.model ? ` (${est.model.name})` : 's'}` : `${range(est.usd)} with Lake's pick per step (no model declared; add a "Model: <name>" line)`}${est.cap != null ? `, capped at ${money(est.cap)}` : ''}.`);
58
+ L.push('Steps:', ...est.steps.map((s) => ` ${s.n}. ${s.title.slice(0, 70)} · ${s.complexity} · ${s.planned ? s.planned.name + (s.fit === 'risky' ? ' (may be too weak)' : s.fit === 'overkill' ? ' (more than needed)' : '') : 'not set'} · Lake pick ${s.model} · ${range(s.planned ? s.planned.usd : s.usd)}`));
59
+ L.push('Model options (whole plan):', ...modelOptions(est, config).slice(0, 7).map((o) => ` ${o.key}: ${range(o.usd)} · ${o.fit} · ${o.note}`));
60
+ if (sugg.length) L.push('Suggestions:', ...sugg.map((x) => ` [${x.id}] ${x.title}, saves up to ${money(x.saving[1])}`));
61
+ if (budget?.required) L.push(`Budget approval: up to ${money(budget.exposure)} > ${money(budget.threshold)}. ${budget.satisfied ? `Approved by @${budget.approvedBy.join(', @')}.` : `Needs one of ${budget.approvers.map((x) => '@' + x).join(', ')} to approve this version.`}`);
62
+ for (const n of est.modelNotes || []) L.push(`Note: ${n}`);
63
+ return L.join('\n');
64
+ }
65
+ function patchFor(a, est, config) {
66
+ if (a.model) { const m = resolveModel(a.model, config); if (!m) throw new Error(`Unknown model ${a.model}`); return { title: `Run the plan on ${m.name}`, patch: { type: 'planModel', model: m.name }, saving: null }; }
67
+ const s = costSuggestions(est, config).find((x) => x.id === a.suggestion_id);
68
+ if (!s) throw new Error(`No suggestion ${a.suggestion_id}. Current ones: ${costSuggestions(est, config).map((x) => x.id).join(', ') || 'none'}`);
69
+ return s;
70
+ }
71
+
72
+ // Context: repo root + lazily resolved GitHub client and PR. Tests inject gh/prNumber/sleep.
73
+ export function createContext({ root = repoRoot(), gh, prNumber, sleep = (ms) => new Promise((r) => setTimeout(r, ms)), clientName = 'MCP client', token } = {}) {
74
+ const ctx = { root, sleep, clientName };
75
+ ctx.github = () => {
76
+ if (gh) return gh;
77
+ const repo = parseRemote(sh('git', ['remote', 'get-url', 'origin'], root));
78
+ if (!repo) throw new Error('No GitHub remote named origin.');
79
+ const t = token || process.env.GITHUB_TOKEN || process.env.GH_TOKEN || sh('gh', ['auth', 'token'], root);
80
+ if (!t) throw new Error('Need GitHub access: set GITHUB_TOKEN or run `gh auth login`.');
81
+ gh = client({ token: t, repo });
82
+ return gh;
83
+ };
84
+ ctx.pr = async () => {
85
+ if (prNumber) return prNumber;
86
+ const g = ctx.github();
87
+ const branch = sh('git', ['rev-parse', '--abbrev-ref', 'HEAD'], root);
88
+ const prs = await g.req('GET', `/pulls?state=open&head=${encodeURIComponent(`${g.owner}:${branch}`)}`);
89
+ if (!prs || !prs.length) return null;
90
+ prNumber = prs[0].number;
91
+ return prNumber;
92
+ };
93
+ return ctx;
94
+ }
95
+
96
+ const reviewLink = (cfg, repo, pr, id, act) => (cfg.reviewUrl && repo && pr ? `${cfg.reviewUrl}#/pr/${repo}/${pr}/${encodeURIComponent(id)}${act ? `?do=${act}` : ''}` : null);
97
+
98
+ function resolveId(ctx, id) {
99
+ const pid = id || getState(ctx.root).active;
100
+ if (!pid) throw new Error('No plan id given and no active plan.');
101
+ return pid;
102
+ }
103
+
104
+ function pushPlan(ctx, id, message) {
105
+ const p = `.lake/plans/${id}.md`;
106
+ sh('git', ['add', p], ctx.root);
107
+ const c = sh('git', ['commit', '-m', message, '--only', p], ctx.root);
108
+ const pushed = sh('git', ['push', '-u', 'origin', 'HEAD'], ctx.root);
109
+ return c !== null && pushed !== null ? `Committed and pushed ${p}.` : `Could not commit/push ${p} automatically; commit and push it yourself.`;
110
+ }
111
+
112
+ async function prModel(ctx, id) {
113
+ const number = await ctx.pr();
114
+ if (!number) return { number: null, model: null };
115
+ const r = await loadPr(ctx.github(), number);
116
+ return { number, model: r.plans.find((p) => p.id === id) || null, config: r.config, events: r.events, pr: r.pr };
117
+ }
118
+
119
+ export function formatReview(m, { localDigest, link } = {}) {
120
+ const L = [];
121
+ L.push(`Plan ${m.id} · v${m.short} (round ${m.round}) · status: ${m.status}${m.policy.needed && m.status === 'in-review' ? ` · needs ${m.policy.needed} more approval(s)` : ''}`);
122
+ L.push(`Estimate: ${m.estimate.complexity} complexity, ${range(m.estimate.declared ? m.estimate.plannedUsd : m.estimate.usd)}${m.estimate.model ? ` on ${m.estimate.model.name}` : ''}`);
123
+ if (m.budget?.required) L.push(`Budget approval: ${m.budget.satisfied ? `done by @${m.budget.approvedBy.join(', @')}` : `needed from one of ${m.budget.approvers.map((x) => '@' + x).join(', ')} (up to ${money(m.budget.exposure)} > ${money(m.budget.threshold)})`}`);
124
+ if (m.suggestions?.length) L.push(`Lake suggestions: ${m.suggestions.map((x) => `[${x.id}] ${x.title} (saves up to ${money(x.saving[1])})`).join('; ')}`);
125
+ const sg = m.threads.filter((t) => t.suggestion && !t.resolved);
126
+ if (sg.length) L.push(`Reviewer suggestions (accept with lake_submit_revision thread_id): ${sg.map((t) => `[${t.id}] ${t.suggestion.title} by @${t.suggestion.by}`).join('; ')}`);
127
+ if (localDigest && localDigest !== m.digest) L.push(`Note: your local plan file is a different version (${localDigest.slice(0, 8)}) than the PR (${m.short}). Push it so reviewers see it.`);
128
+ const cur = m.verdicts.filter((v) => v.version === m.digest && v.action !== 'revoke');
129
+ if (cur.length) { L.push('', 'Verdicts on this version:'); for (const v of cur) L.push(`- @${v.login} ${v.action === 'approve' ? 'approved' : 'requested changes'}${v.self ? ' (author, does not count)' : ''} via ${v.via}${v.text ? `: ${v.text.replace(/\n+/g, ' ')}` : ''}`); }
130
+ const prev = m.verdicts.filter((v) => v.version !== m.digest && v.action === 'reject');
131
+ if (prev.length) { L.push('', 'Earlier rounds:'); for (const v of prev) L.push(`- round ${v.n}: @${v.login} requested changes${v.text ? `: ${v.text.replace(/\n+/g, ' ')}` : ''}`); }
132
+ const open = m.threads.filter((t) => !t.resolved);
133
+ if (open.length) {
134
+ L.push('', `Open threads (${open.length}):`);
135
+ for (const t of open) {
136
+ const where = t.anchor ? `${t.anchor.heading ? `"${t.anchor.heading}", ` : ''}line ${t.current ? t.current.start : t.anchor.start}${t.outdated ? ' (outdated: text changed)' : ''}` : 'whole plan';
137
+ L.push(`- [${t.id}] round ${t.n}, ${where}${t.anchor?.quote ? ` on: "${t.anchor.quote.split('\n')[0].slice(0, 120)}"` : ''}`);
138
+ for (const c of t.comments) L.push(` @${c.login}: ${String(c.text).replace(/\n+/g, ' ')}`);
139
+ }
140
+ }
141
+ const lines = String(m.body).split('\n');
142
+ L.push('', 'Plan text with line numbers (for anchoring comments):', ...lines.slice(0, 400).map((l, i) => `${String(i + 1).padStart(3)}| ${l}`).filter((l) => !/lake:estimate/.test(l)));
143
+ if (link) L.push('', `Review page: ${link}`);
144
+ return L.join('\n');
145
+ }
146
+
147
+ export async function callTool(ctx, name, a = {}) {
148
+ if (ALIASES[name]) [name, a] = ALIASES[name](a);
149
+ if (!fs.existsSync(path.join(ctx.root, '.git'))) return `lake-gate: ${ctx.root} is not a git repository. Open your project folder (the repo with .lake/, set up with \`npx lake-gate init\`) in Claude Code or Cursor, then try again.`;
150
+ const via = `${ctx.clientName} (MCP)`;
151
+ if (name === 'lake_review') {
152
+ const act = a.action;
153
+ if (act === 'approve' || act === 'request_changes') return callTool(ctx, act === 'approve' ? '_approve' : '_changes', { ...a, comment: a.text });
154
+ if (act === 'comment') return callTool(ctx, '_comment', a);
155
+ if (act === 'reply') return callTool(ctx, '_reply', a);
156
+ if (act === 'suggest') return callTool(ctx, '_suggest', { ...a, comment: a.text });
157
+ throw new Error('action must be approve, request_changes, comment, reply or suggest');
158
+ }
159
+ if (name === 'lake_submit_revision' && !a.plan_markdown) {
160
+ if (a.thread_id || a.suggestion_id || a.model) return callTool(ctx, '_apply', a);
161
+ throw new Error('Pass plan_markdown, or one of thread_id / suggestion_id / model.');
162
+ }
163
+ switch (name) {
164
+ case 'lake_request_review': {
165
+ let plan; let note = '';
166
+ if (a.plan_markdown) { const r = exportPlan(ctx.root, a.plan_markdown, { id: a.plan_id, source: 'mcp' }); plan = r.plan; }
167
+ else { plan = loadPlan(ctx.root, resolveId(ctx, a.plan_id)); if (!plan) throw new Error(`No plan ${a.plan_id}`); }
168
+ const cfg = loadConfig(ctx.root);
169
+ if (a.push) note += '\n' + pushPlan(ctx, plan.id, `Plan: ${plan.title} (v${plan.short})`);
170
+ const number = await ctx.pr().catch(() => null);
171
+ if (!number) return `Saved .lake/plans/${plan.id}.md as v${plan.short}.${note}\nNo open PR for this branch yet: commit and push the plan, open a (draft) PR, then call lake_request_review again or lake_review_status.`;
172
+ const g = ctx.github();
173
+ if (a.reviewers?.length) await g.req('POST', `/pulls/${number}/requested_reviewers`, { reviewers: a.reviewers }).catch(() => null);
174
+ const link = reviewLink(cfg, g.repo, number, plan.id);
175
+ await g.req('POST', `/issues/${number}/comments`, { body: [`**Plan ready for review:** ${plan.title} · \`${plan.id}\` v${plan.short}`, a.reviewers?.length ? a.reviewers.map((r) => '@' + r).join(' ') : null,
176
+ a.note ? `\n${a.note}` : null, link ? `\n[Open the plan review](${link})` : null, `\n<sub>via lake-gate · ${via}</sub>`].filter(Boolean).join('\n') });
177
+ return `Review requested on PR #${number} for ${plan.id} v${plan.short}.${note}${link ? `\nReview page: ${link}` : ''}\nCall lake_review_status with wait_seconds to wait for feedback. Do not implement until it is approved.`;
178
+ }
179
+ case 'lake_review_status': {
180
+ const id = resolveId(ctx, a.plan_id);
181
+ const local = loadPlan(ctx.root, id);
182
+ let { number, model, config, events, pr } = await prModel(ctx, id);
183
+ const localCost = () => { if (!local) return ''; const cfg = loadConfig(ctx.root); return `\n\n${formatCost(estimatePlan(local.body, cfg), cfg)}`; };
184
+ if (!number) return `No open PR for this branch yet. Push the plan and open a PR so teammates can review it.${local ? ` Local plan ${id} is v${local.short}.` : ''}${localCost()}`;
185
+ if (!model) return `PR #${number} does not contain .lake/plans/${id}.md yet. Push the plan file.`;
186
+ const wait = Math.min(240, Math.max(0, Number(a.wait_seconds) || 0));
187
+ const sig = (m) => `${m.status}|${m.digest}|${m.verdicts.length}|${m.threads.reduce((n, t) => n + t.comments.length, 0)}`;
188
+ const start = sig(model); let waited = 0;
189
+ while (waited < wait && sig(model) === start) {
190
+ await ctx.sleep(20000); waited += 20;
191
+ ({ model, config, events, pr } = await prModel(ctx, id));
192
+ }
193
+ // Sync locally so the Claude Code hook sees the decision.
194
+ try {
195
+ const digestAt = {}; const raw = await collectEvents(ctx.github(), number);
196
+ for (const p of listPlans(ctx.root)) digestAt[p.id] = await nativeDigests(ctx.github(), raw, `.lake/plans/${p.id}.md`, { headSha: pr.head.sha, config });
197
+ applyEvents(ctx.root, { events: raw, prAuthor: pr.user.login, prNumber: number, digestAt });
198
+ } catch { /* status is still useful without a local sync */ }
199
+ const changed = waited && sig(model) !== start ? `Changed after ${waited}s.\n` : waited ? `No change after ${waited}s.\n` : '';
200
+ return changed + formatReview(model, { localDigest: local?.digest, link: reviewLink(config, ctx.github().repo, number, id) });
201
+ }
202
+ case 'lake_submit_revision': {
203
+ const id = resolveId(ctx, a.plan_id);
204
+ const { plan } = exportPlan(ctx.root, a.plan_markdown, { id, source: 'mcp' });
205
+ let note = '';
206
+ if (a.push) note = '\n' + pushPlan(ctx, plan.id, `Plan revision: ${plan.title} (v${plan.short})`);
207
+ const number = await ctx.pr().catch(() => null);
208
+ if (number) {
209
+ const g = ctx.github();
210
+ await g.req('POST', `/issues/${number}/comments`, { body: [`**Revised plan \`${plan.id}\` → v${plan.short}.** Earlier approvals no longer apply.`, a.note ? `\n${a.note}` : null,
211
+ a.addressed_threads?.length ? `\nAddressed ${a.addressed_threads.length} thread(s).` : null, `\n<sub>via lake-gate · ${via}</sub>`,
212
+ ...(a.addressed_threads || []).map((t) => `<!-- lake:resolve ${JSON.stringify({ p: plan.id, t, r: true })} -->`)].filter(Boolean).join('\n') });
213
+ }
214
+ return `Saved ${plan.id} v${plan.short}.${note}${number ? ` Posted the revision on PR #${number}.` : ' No PR found to notify.'}${a.push ? '' : ' Push the plan file so reviewers see this version.'} Call lake_review_status with wait_seconds to wait.`;
215
+ }
216
+ case '_reply': {
217
+ const number = await ctx.pr(); if (!number) throw new Error('No open PR for this branch.');
218
+ await actions.reply(ctx.github(), number, { planId: resolveId(ctx, a.plan_id), thread: a.thread_id, text: a.text, via });
219
+ return `Replied in thread ${a.thread_id} on PR #${number}.`;
220
+ }
221
+ case '_comment': {
222
+ const id = resolveId(ctx, a.plan_id);
223
+ const { number, model } = await prModel(ctx, id);
224
+ if (!model) throw new Error(`No PR with plan ${id}.`);
225
+ const lines = String(model.body).split('\n'); const s = Math.max(1, Math.floor(a.line)); const e = Math.max(s, Math.floor(a.end_line || s));
226
+ await actions.comment(ctx.github(), number, { planId: id, version: model.digest, anchor: { start: s, end: e, quote: lines.slice(s - 1, e).join('\n') }, text: a.text, via });
227
+ return `Commented on ${id} v${model.short}, line ${s}${e > s ? `–${e}` : ''}.`;
228
+ }
229
+ case '_approve': case '_changes': {
230
+ const id = a.plan_id;
231
+ const { number, model } = await prModel(ctx, id);
232
+ if (!model) throw new Error(`No open PR with plan ${id}.`);
233
+ const v = String(a.version || '').toLowerCase();
234
+ if (v.length < 7 || !model.digest.startsWith(v)) return `Not posted: version ${a.version || '(none)'} is not the current version of ${id}. The current version is ${model.short}. Show the user what changed and ask again.`;
235
+ if (name === '_changes' && !String(a.comment || '').trim()) return 'Not posted: say what needs to change.';
236
+ await actions.verdict(ctx.github(), number, { action: name === '_approve' ? 'approve' : 'reject', planId: id, version: model.digest, text: a.comment, via });
237
+ return `${name === '_approve' ? 'Approved' : 'Requested changes on'} ${id} v${model.short} on PR #${number}. The PR check updates in a few seconds. If you are the PR author it will not count.`;
238
+ }
239
+ case 'lake_cost': {
240
+ const id = resolveId(ctx, a.plan_id);
241
+ const plan = loadPlan(ctx.root, id); if (!plan) throw new Error(`No plan ${id}`);
242
+ const cfg = loadConfig(ctx.root); const est = estimatePlan(plan.body, cfg);
243
+ return `Plan ${id} v${plan.short}\n` + formatCost(est, cfg, undefined, est.exposure > (cfg.budget?.approverAbove ?? Infinity) ? { required: true, exposure: est.exposure, threshold: cfg.budget.approverAbove, approvers: (cfg.budget.approvers || []).map((x) => String(x).replace(/^@/, '')), satisfied: false } : null);
244
+ }
245
+ case '_suggest': {
246
+ const { number, model, config } = await prModel(ctx, a.plan_id);
247
+ if (!model) throw new Error(`No open PR with plan ${a.plan_id}.`);
248
+ const s = patchFor(a, model.estimate, config);
249
+ await actions.suggest(ctx.github(), number, { planId: model.id, version: model.digest, title: s.title, patch: s.patch, saving: s.saving, text: a.comment, via });
250
+ return `Suggested on PR #${number}: ${s.title}. The author can accept it in one click in Lake or with lake_submit_revision.`;
251
+ }
252
+ case '_apply': {
253
+ const id = resolveId(ctx, a.plan_id);
254
+ const plan = loadPlan(ctx.root, id); if (!plan) throw new Error(`No plan ${id}`);
255
+ const cfg = loadConfig(ctx.root);
256
+ let s; let number = null;
257
+ if (a.thread_id) {
258
+ const r = await prModel(ctx, id); number = r.number;
259
+ const t = r.model?.threads.find((x) => x.id === a.thread_id);
260
+ if (!t?.suggestion) throw new Error(`Thread ${a.thread_id} is not a suggestion.`);
261
+ s = { title: t.suggestion.title, patch: t.suggestion.patch };
262
+ } else s = patchFor(a, estimatePlan(plan.body, cfg), cfg);
263
+ const next = applyPatch(stripEstimate(plan.body).replace(/\s+$/, '') + '\n', s.patch);
264
+ const { plan: np, estimate } = exportPlan(ctx.root, next, { id, source: 'mcp' });
265
+ let note = '';
266
+ if (a.push) note = '\n' + pushPlan(ctx, id, `Plan ${id}: ${s.title || describePatch(s.patch, cfg)} (v${np.short})`);
267
+ if (a.thread_id && number) await ctx.github().req('POST', `/issues/${number}/comments`, { body: acceptBody({ planId: id, thread: a.thread_id, title: s.title, newVersion: np.digest, via }) });
268
+ return `Applied "${s.title}" to ${id}: new version v${np.short}, ${range(estimate.declared ? estimate.plannedUsd : estimate.usd)}.${note}${a.push ? '' : ' Push the plan file so reviewers see it.'} Earlier approvals no longer apply.`;
269
+ }
270
+ default: throw new Error(`Unknown tool ${name}`);
271
+ }
272
+ }
273
+
274
+ // Minimal MCP stdio transport: newline-delimited JSON-RPC 2.0.
275
+ export function serve({ input = process.stdin, output = process.stdout, ctxOptions = {} } = {}) {
276
+ let ctx = null;
277
+ const send = (m) => output.write(JSON.stringify(m) + '\n');
278
+ let buf = '';
279
+ const handle = async (msg) => {
280
+ const { id, method, params } = msg;
281
+ if (id === undefined) return; // notification
282
+ try {
283
+ if (method === 'initialize') {
284
+ ctx = createContext({ ...ctxOptions, clientName: params?.clientInfo?.name || 'MCP client' });
285
+ return send({ jsonrpc: '2.0', id, result: { protocolVersion: params?.protocolVersion || '2025-06-18', capabilities: { tools: {} }, serverInfo: { name: 'lake-gate', version: VERSION },
286
+ instructions: 'Plan review for coding agents. Request review after planning, wait for approval with lake_review_status, revise with lake_submit_revision. Only approve when the human explicitly says so.' } });
287
+ }
288
+ if (method === 'ping') return send({ jsonrpc: '2.0', id, result: {} });
289
+ if (method === 'tools/list') return send({ jsonrpc: '2.0', id, result: { tools: TOOLS } });
290
+ if (method === 'tools/call') {
291
+ ctx = ctx || createContext(ctxOptions);
292
+ try {
293
+ const text = await callTool(ctx, params.name, params.arguments || {});
294
+ return send({ jsonrpc: '2.0', id, result: { content: [{ type: 'text', text }] } });
295
+ } catch (e) { return send({ jsonrpc: '2.0', id, result: { content: [{ type: 'text', text: `lake-gate: ${e.message}` }], isError: true } }); }
296
+ }
297
+ send({ jsonrpc: '2.0', id, error: { code: -32601, message: `Method not found: ${method}` } });
298
+ } catch (e) { send({ jsonrpc: '2.0', id, error: { code: -32603, message: e.message } }); }
299
+ };
300
+ input.setEncoding?.('utf8');
301
+ input.on('data', (chunk) => {
302
+ buf += chunk;
303
+ let i;
304
+ while ((i = buf.indexOf('\n')) >= 0) {
305
+ const line = buf.slice(0, i).trim(); buf = buf.slice(i + 1);
306
+ if (!line) continue;
307
+ let msg; try { msg = JSON.parse(line); } catch { send({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } }); continue; }
308
+ handle(msg);
309
+ }
310
+ });
311
+ return new Promise((resolve) => input.on('end', resolve));
312
+ }