geloforge 0.0.0-stage → 0.7.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/LICENSE +21 -0
- package/README.md +72 -2
- package/THIRD_PARTY_NOTICES.md +33 -0
- package/VERSION +1 -0
- package/adapters/n8n/staging-audit-error-workflow.json +132 -0
- package/core/adopt-project.mjs +458 -0
- package/core/audit-learning.mjs +68 -0
- package/core/audit-provider.mjs +88 -0
- package/core/autonomous-audit.mjs +214 -0
- package/core/checkpoint.mjs +448 -0
- package/core/codebase-map.mjs +886 -0
- package/core/compatibility.json +16 -0
- package/core/compatibility.mjs +123 -0
- package/core/context-cache.mjs +113 -0
- package/core/context-compiler.mjs +1315 -0
- package/core/evidence-capture.mjs +347 -0
- package/core/git-utils.mjs +167 -0
- package/core/handoff.mjs +815 -0
- package/core/json-schema-lite.mjs +119 -0
- package/core/mcp-init.mjs +251 -0
- package/core/mcp-server.mjs +915 -0
- package/core/operation-approval.mjs +102 -0
- package/core/path-safety.mjs +508 -0
- package/core/project-locator.mjs +231 -0
- package/core/project-lock.mjs +438 -0
- package/core/project-status.mjs +635 -0
- package/core/project-validator.mjs +544 -0
- package/core/promotion.mjs +90 -0
- package/core/runtime-files.mjs +40 -0
- package/core/skills-history.mjs +572 -0
- package/core/skills-lifecycle.mjs +2225 -0
- package/core/skills-lint.mjs +365 -0
- package/core/skills.mjs +1449 -0
- package/core/staging-audit.mjs +454 -0
- package/core/staging-evidence.mjs +127 -0
- package/core/task-manager.mjs +1044 -0
- package/core/template-utils.mjs +190 -0
- package/core/text-utils.mjs +48 -0
- package/core/verify-task.mjs +48 -0
- package/core/worktrees.mjs +64 -0
- package/core/yaml-subset.mjs +572 -0
- package/package.json +50 -4
- package/policies/approval-boundaries.md +42 -0
- package/policies/memory-policy.md +53 -0
- package/policies/token-efficiency.md +30 -0
- package/schemas/README.md +43 -0
- package/schemas/adr.schema.json +64 -0
- package/schemas/agent-handoff.schema.json +139 -0
- package/schemas/approval-record.schema.json +110 -0
- package/schemas/conflict-record.schema.json +60 -0
- package/schemas/context-pack-manifest.schema.json +194 -0
- package/schemas/evidence-manifest.schema.json +83 -0
- package/schemas/incident-record.schema.json +53 -0
- package/schemas/project-manifest.schema.json +90 -0
- package/schemas/project-state.schema.json +64 -0
- package/schemas/recovery-checkpoint.schema.json +49 -0
- package/schemas/research-record.schema.json +76 -0
- package/schemas/task-contract.schema.json +95 -0
- package/scripts/bootstrap-project.mjs +357 -0
- package/scripts/geloforge.mjs +2512 -0
- package/templates/profiles/README.md +19 -0
- package/templates/profiles/ai-system/brain/profile.md +21 -0
- package/templates/profiles/ai-system/gitignore.append +5 -0
- package/templates/profiles/ai-system/profile.json +6 -0
- package/templates/profiles/automation/brain/profile.md +19 -0
- package/templates/profiles/automation/gitignore.append +5 -0
- package/templates/profiles/automation/profile.json +6 -0
- package/templates/profiles/desktop/brain/profile.md +21 -0
- package/templates/profiles/desktop/gitignore.append +7 -0
- package/templates/profiles/desktop/profile.json +6 -0
- package/templates/profiles/mobile/brain/profile.md +20 -0
- package/templates/profiles/mobile/gitignore.append +8 -0
- package/templates/profiles/mobile/profile.json +6 -0
- package/templates/profiles/web/brain/profile.md +21 -0
- package/templates/profiles/web/gitignore.append +6 -0
- package/templates/profiles/web/profile.json +6 -0
- package/templates/project-starter/AGENTS.md +27 -0
- package/templates/project-starter/GEMINI.md +16 -0
- package/templates/project-starter/README.md +26 -0
- package/templates/project-starter/brain/INDEX.md +40 -0
- package/templates/project-starter/brain/architecture/overview.md +30 -0
- package/templates/project-starter/brain/decisions/.gitkeep +0 -0
- package/templates/project-starter/brain/manifest.yaml +36 -0
- package/templates/project-starter/brain/requirements/constraints.md +29 -0
- package/templates/project-starter/brain/requirements/prd.md +37 -0
- package/templates/project-starter/brain/state/current.yaml +19 -0
- package/templates/project-starter/gitignore.template +25 -0
- package/templates/project-starter/src/.gitkeep +0 -0
- package/templates/project-starter/tasks/.gitkeep +0 -0
- package/templates/project-starter/tests/.gitkeep +0 -0
|
@@ -0,0 +1,915 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Zero-dependency JSON-RPC 2.0 MCP stdio server for GeloForge (v0.5).
|
|
3
|
+
* Exposes read/advisory and explicitly disclosed bounded-mutating tools over stdin/stdout
|
|
4
|
+
* (supporting newline-delimited JSON and Content-Length LSP framing with strict size bounds),
|
|
5
|
+
* enforces pinned project-root confinement and optional --read-only mode, and strictly
|
|
6
|
+
* refuses privileged skill promotion, rollback, or key-signing operations over MCP.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import fs from "node:fs";
|
|
10
|
+
import path from "node:path";
|
|
11
|
+
import { fileURLToPath } from "node:url";
|
|
12
|
+
import { resolveProjectDir } from "./project-locator.mjs";
|
|
13
|
+
import { getProjectStatus, getProjectRecommendations } from "./project-status.mjs";
|
|
14
|
+
import { compileContext } from "./context-compiler.mjs";
|
|
15
|
+
import {
|
|
16
|
+
claimTaskLease,
|
|
17
|
+
completeTask,
|
|
18
|
+
createTask,
|
|
19
|
+
getTask,
|
|
20
|
+
listTaskLeases,
|
|
21
|
+
listTasks,
|
|
22
|
+
releaseTaskLease,
|
|
23
|
+
updateTask,
|
|
24
|
+
} from "./task-manager.mjs";
|
|
25
|
+
import { createCheckpoint, getCheckpoint, listCheckpoints } from "./checkpoint.mjs";
|
|
26
|
+
import { discoverSkills, resolveProjectForSkills } from "./skills.mjs";
|
|
27
|
+
import { lintDiscoveredSkills, lintSkill } from "./skills-lint.mjs";
|
|
28
|
+
import { draftSkillFromExperience, getSkillHistory, proposeSkillUpdate } from "./skills-lifecycle.mjs";
|
|
29
|
+
import { redactSecretContent } from "./path-safety.mjs";
|
|
30
|
+
|
|
31
|
+
const __filename = fileURLToPath(import.meta.url);
|
|
32
|
+
const __dirname = path.dirname(__filename);
|
|
33
|
+
const DEFAULT_HARNESS_DIR = path.resolve(__dirname, "..");
|
|
34
|
+
|
|
35
|
+
const MCP_PROTOCOL_VERSION = "2024-11-05";
|
|
36
|
+
const BLOCKED_SKILL_ACTIONS = new Set(["promote", "rollback", "keygen", "sign"]);
|
|
37
|
+
export const MAX_MCP_MESSAGE_BYTES = 1024 * 1024;
|
|
38
|
+
export const MAX_MCP_HEADER_BYTES = 4096;
|
|
39
|
+
|
|
40
|
+
const MUTATING_TASK_ACTIONS = new Set(["new", "update", "done", "claim", "release"]);
|
|
41
|
+
const MUTATING_CHECKPOINT_ACTIONS = new Set(["create"]);
|
|
42
|
+
const MUTATING_SKILLS_ACTIONS = new Set(["draft", "propose", "propose-update"]);
|
|
43
|
+
|
|
44
|
+
function getHarnessVersion(harnessDir) {
|
|
45
|
+
try {
|
|
46
|
+
return fs.readFileSync(path.join(harnessDir, "VERSION"), "utf8").trim();
|
|
47
|
+
} catch {
|
|
48
|
+
return "0.5.0";
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export const MCP_TOOLS = [
|
|
53
|
+
{
|
|
54
|
+
name: "geloforge_status",
|
|
55
|
+
description:
|
|
56
|
+
"[READ-ONLY] Inspect project validation health, operational state, active multi-IDE leases, pending human approvals inbox, and ranked next steps.",
|
|
57
|
+
annotations: {
|
|
58
|
+
readOnlyHint: true,
|
|
59
|
+
destructiveHint: false,
|
|
60
|
+
readOnlyActions: ["status"],
|
|
61
|
+
mutatingActions: [],
|
|
62
|
+
},
|
|
63
|
+
inputSchema: {
|
|
64
|
+
type: "object",
|
|
65
|
+
additionalProperties: false,
|
|
66
|
+
properties: {
|
|
67
|
+
project: { type: "string", description: "Target project directory (must match trusted project root when pinned)." },
|
|
68
|
+
},
|
|
69
|
+
},
|
|
70
|
+
},
|
|
71
|
+
{
|
|
72
|
+
name: "geloforge_recommend",
|
|
73
|
+
description:
|
|
74
|
+
"[READ-ONLY] Return ranked Human-in-the-Loop Co-Pilot recommendations, pending human approval items, and multi-IDE overlap warnings.",
|
|
75
|
+
annotations: {
|
|
76
|
+
readOnlyHint: true,
|
|
77
|
+
destructiveHint: false,
|
|
78
|
+
readOnlyActions: ["recommend"],
|
|
79
|
+
mutatingActions: [],
|
|
80
|
+
},
|
|
81
|
+
inputSchema: {
|
|
82
|
+
type: "object",
|
|
83
|
+
additionalProperties: false,
|
|
84
|
+
properties: {
|
|
85
|
+
project: { type: "string" },
|
|
86
|
+
},
|
|
87
|
+
},
|
|
88
|
+
},
|
|
89
|
+
{
|
|
90
|
+
name: "geloforge_context",
|
|
91
|
+
description:
|
|
92
|
+
"[READ-ONLY] Compile a deterministic, trust-tiered, token-budgeted context packet with automatic completed-task pruning and peer IDE lease awareness.",
|
|
93
|
+
annotations: {
|
|
94
|
+
readOnlyHint: true,
|
|
95
|
+
destructiveHint: false,
|
|
96
|
+
readOnlyActions: ["context"],
|
|
97
|
+
mutatingActions: [],
|
|
98
|
+
},
|
|
99
|
+
inputSchema: {
|
|
100
|
+
type: "object",
|
|
101
|
+
additionalProperties: false,
|
|
102
|
+
properties: {
|
|
103
|
+
project: { type: "string" },
|
|
104
|
+
task: { type: "string", description: "TASK-NNNN identifier." },
|
|
105
|
+
query: { type: "string", description: "Search query / goal." },
|
|
106
|
+
profile: { type: "string", enum: ["quick", "working", "deep"] },
|
|
107
|
+
budget: { type: "integer", minimum: 100 },
|
|
108
|
+
map: { type: "boolean" },
|
|
109
|
+
skills: { type: "boolean" },
|
|
110
|
+
pinnedSkills: { type: "array", items: { type: "string" } },
|
|
111
|
+
fromDiff: { type: "boolean" },
|
|
112
|
+
includeCompleted: { type: "boolean" },
|
|
113
|
+
excludeUnverified: { type: "boolean" },
|
|
114
|
+
},
|
|
115
|
+
},
|
|
116
|
+
},
|
|
117
|
+
{
|
|
118
|
+
name: "geloforge_task",
|
|
119
|
+
description:
|
|
120
|
+
"[READ + STATE-MUTATING] Manage scoped TASK-NNNN contracts and cooperative multi-IDE task/file-scope leases. Read-only actions: list, show, leases. Mutating actions (disabled in --read-only mode): new, update, done, claim, release.",
|
|
121
|
+
annotations: {
|
|
122
|
+
readOnlyHint: false,
|
|
123
|
+
destructiveHint: false,
|
|
124
|
+
readOnlyActions: ["list", "show", "leases"],
|
|
125
|
+
mutatingActions: ["new", "update", "done", "claim", "release"],
|
|
126
|
+
},
|
|
127
|
+
inputSchema: {
|
|
128
|
+
type: "object",
|
|
129
|
+
required: ["action"],
|
|
130
|
+
additionalProperties: false,
|
|
131
|
+
properties: {
|
|
132
|
+
action: {
|
|
133
|
+
type: "string",
|
|
134
|
+
enum: ["list", "show", "new", "update", "done", "claim", "release", "leases"],
|
|
135
|
+
},
|
|
136
|
+
project: { type: "string" },
|
|
137
|
+
task: { type: "string" },
|
|
138
|
+
title: { type: "string" },
|
|
139
|
+
objective: { type: "string" },
|
|
140
|
+
status: { type: "string" },
|
|
141
|
+
priority: { type: "string" },
|
|
142
|
+
role: { type: "string" },
|
|
143
|
+
budget: { type: "string" },
|
|
144
|
+
activate: { type: "boolean" },
|
|
145
|
+
evidenceRefs: { type: "array", items: { type: "string" } },
|
|
146
|
+
requireEvidence: { type: "boolean" },
|
|
147
|
+
tool: { type: "string" },
|
|
148
|
+
sessionId: { type: "string" },
|
|
149
|
+
scopes: { type: "array", items: { type: "string" } },
|
|
150
|
+
ttlMinutes: { type: "integer", minimum: 1, maximum: 1440 },
|
|
151
|
+
force: { type: "boolean" },
|
|
152
|
+
includeExpired: { type: "boolean" },
|
|
153
|
+
dryRun: { type: "boolean" },
|
|
154
|
+
},
|
|
155
|
+
},
|
|
156
|
+
},
|
|
157
|
+
{
|
|
158
|
+
name: "geloforge_checkpoint",
|
|
159
|
+
description:
|
|
160
|
+
"[READ + STATE-MUTATING] Create, list, or inspect CHKPT-NNNN session recovery checkpoints. Read-only actions: list, show. Mutating action (disabled in --read-only mode): create.",
|
|
161
|
+
annotations: {
|
|
162
|
+
readOnlyHint: false,
|
|
163
|
+
destructiveHint: false,
|
|
164
|
+
readOnlyActions: ["list", "show"],
|
|
165
|
+
mutatingActions: ["create"],
|
|
166
|
+
},
|
|
167
|
+
inputSchema: {
|
|
168
|
+
type: "object",
|
|
169
|
+
required: ["action"],
|
|
170
|
+
additionalProperties: false,
|
|
171
|
+
properties: {
|
|
172
|
+
action: { type: "string", enum: ["create", "list", "show"] },
|
|
173
|
+
project: { type: "string" },
|
|
174
|
+
checkpointId: { type: "string" },
|
|
175
|
+
summary: { type: "string" },
|
|
176
|
+
resumeInstructions: { type: "string" },
|
|
177
|
+
evidenceRef: { type: "string" },
|
|
178
|
+
createdBy: { type: "string" },
|
|
179
|
+
status: { type: "string" },
|
|
180
|
+
dryRun: { type: "boolean" },
|
|
181
|
+
},
|
|
182
|
+
},
|
|
183
|
+
},
|
|
184
|
+
{
|
|
185
|
+
name: "geloforge_skills",
|
|
186
|
+
description:
|
|
187
|
+
"[READ + QUARANTINED-DRAFT ONLY] Inspect, lint, view history, or stage quarantined skill drafts/updates from verified evidence. Read-only actions: list, show, validate, lint, history. Mutating (quarantine-only, disabled in --read-only): draft, propose. Refused: promote, rollback, keygen, sign.",
|
|
188
|
+
annotations: {
|
|
189
|
+
readOnlyHint: false,
|
|
190
|
+
destructiveHint: false,
|
|
191
|
+
readOnlyActions: ["list", "show", "validate", "lint", "history"],
|
|
192
|
+
mutatingActions: ["draft", "propose"],
|
|
193
|
+
refusedActions: ["promote", "rollback", "keygen", "sign"],
|
|
194
|
+
},
|
|
195
|
+
inputSchema: {
|
|
196
|
+
type: "object",
|
|
197
|
+
required: ["action"],
|
|
198
|
+
additionalProperties: false,
|
|
199
|
+
properties: {
|
|
200
|
+
action: {
|
|
201
|
+
type: "string",
|
|
202
|
+
enum: ["list", "show", "validate", "lint", "draft", "propose", "history"],
|
|
203
|
+
},
|
|
204
|
+
project: { type: "string" },
|
|
205
|
+
name: { type: "string" },
|
|
206
|
+
includeDrafts: { type: "boolean" },
|
|
207
|
+
strict: { type: "boolean" },
|
|
208
|
+
evidenceIds: { type: "array", items: { type: "string" } },
|
|
209
|
+
handoffIds: { type: "array", items: { type: "string" } },
|
|
210
|
+
title: { type: "string" },
|
|
211
|
+
description: { type: "string" },
|
|
212
|
+
reason: { type: "string" },
|
|
213
|
+
appendNote: { type: "string" },
|
|
214
|
+
steps: { type: "array", items: { type: "string" } },
|
|
215
|
+
tags: { type: "array", items: { type: "string" } },
|
|
216
|
+
triggers: { type: "array", items: { type: "string" } },
|
|
217
|
+
dryRun: { type: "boolean" },
|
|
218
|
+
},
|
|
219
|
+
},
|
|
220
|
+
},
|
|
221
|
+
];
|
|
222
|
+
|
|
223
|
+
function canonicalRealPath(dirPath) {
|
|
224
|
+
try {
|
|
225
|
+
return fs.realpathSync(dirPath);
|
|
226
|
+
} catch {
|
|
227
|
+
return path.resolve(dirPath);
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
function buildTrustedProjectRoots({
|
|
232
|
+
defaultProjectDir = null,
|
|
233
|
+
allowedProjectRoots = null,
|
|
234
|
+
cwd = process.cwd(),
|
|
235
|
+
harnessDir,
|
|
236
|
+
}) {
|
|
237
|
+
const roots = new Set();
|
|
238
|
+
if (Array.isArray(allowedProjectRoots)) {
|
|
239
|
+
for (const raw of allowedProjectRoots) {
|
|
240
|
+
if (typeof raw === "string" && raw.trim()) {
|
|
241
|
+
const resolved = resolveProjectDir({ project: raw.trim(), cwd, harnessDir }).projectDir;
|
|
242
|
+
roots.add(canonicalRealPath(resolved));
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
if (typeof defaultProjectDir === "string" && defaultProjectDir.trim()) {
|
|
247
|
+
const pinned = resolveProjectDir({ project: defaultProjectDir.trim(), cwd, harnessDir }).projectDir;
|
|
248
|
+
roots.add(canonicalRealPath(pinned));
|
|
249
|
+
} else if (roots.size === 0) {
|
|
250
|
+
try {
|
|
251
|
+
const cwdResolved = resolveProjectDir({ project: null, cwd, harnessDir }).projectDir;
|
|
252
|
+
roots.add(canonicalRealPath(cwdResolved));
|
|
253
|
+
} catch {
|
|
254
|
+
// Launched outside any recognized GeloForge project without --project; keep roots empty so callers fail closed
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
return roots;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
function resolveTargetProject(args, ctx) {
|
|
261
|
+
const { defaultProjectDir, allowedProjectRoots, cwd, harnessDir } = ctx;
|
|
262
|
+
const trustedRoots = buildTrustedProjectRoots({ defaultProjectDir, allowedProjectRoots, cwd, harnessDir });
|
|
263
|
+
if (trustedRoots.size === 0) {
|
|
264
|
+
throw new Error(
|
|
265
|
+
'Refusing MCP tool execution without a trusted project root: server was started outside a recognized GeloForge project without --project. Start with "geloforge mcp --project <dir>" or run from inside a project directory.'
|
|
266
|
+
);
|
|
267
|
+
}
|
|
268
|
+
const explicit =
|
|
269
|
+
typeof args?.project === "string" && args.project.trim() ? args.project.trim() : defaultProjectDir || null;
|
|
270
|
+
const resolvedTarget = resolveProjectDir({ project: explicit, cwd, harnessDir }).projectDir;
|
|
271
|
+
const canonicalTarget = canonicalRealPath(resolvedTarget);
|
|
272
|
+
if (!trustedRoots.has(canonicalTarget)) {
|
|
273
|
+
throw new Error(
|
|
274
|
+
`Refusing MCP tool execution outside trusted project root (${Array.from(trustedRoots).join(", ")}): requested "${resolvedTarget}".`
|
|
275
|
+
);
|
|
276
|
+
}
|
|
277
|
+
return resolvedTarget;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
function assertWritable(ctx, toolName, action) {
|
|
281
|
+
if (ctx.readOnly) {
|
|
282
|
+
throw new Error(`Refusing state-mutating MCP action "${toolName}:${action}" while server is in --read-only mode.`);
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
function invokeTaskTool(args, ctx) {
|
|
287
|
+
const action = String(args?.action || "").trim().toLowerCase();
|
|
288
|
+
if (MUTATING_TASK_ACTIONS.has(action)) {
|
|
289
|
+
assertWritable(ctx, "geloforge_task", action);
|
|
290
|
+
}
|
|
291
|
+
const projectDir = resolveTargetProject(args, ctx);
|
|
292
|
+
const harnessDir = ctx.harnessDir;
|
|
293
|
+
switch (action) {
|
|
294
|
+
case "list":
|
|
295
|
+
return listTasks({ projectDir, status: args.status, harnessDir });
|
|
296
|
+
case "show":
|
|
297
|
+
return getTask({ projectDir, taskId: args.task, harnessDir });
|
|
298
|
+
case "new":
|
|
299
|
+
return createTask({
|
|
300
|
+
projectDir,
|
|
301
|
+
harnessDir,
|
|
302
|
+
title: args.title,
|
|
303
|
+
objective: args.objective,
|
|
304
|
+
priority: args.priority,
|
|
305
|
+
assignedRole: args.role,
|
|
306
|
+
contextBudget: args.budget,
|
|
307
|
+
status: args.status,
|
|
308
|
+
activate: Boolean(args.activate),
|
|
309
|
+
dryRun: Boolean(args.dryRun),
|
|
310
|
+
});
|
|
311
|
+
case "update":
|
|
312
|
+
return updateTask({
|
|
313
|
+
projectDir,
|
|
314
|
+
harnessDir,
|
|
315
|
+
taskId: args.task,
|
|
316
|
+
status: args.status,
|
|
317
|
+
priority: args.priority,
|
|
318
|
+
assignedRole: args.role,
|
|
319
|
+
activate: Boolean(args.activate),
|
|
320
|
+
evidenceRefs: args.evidenceRefs,
|
|
321
|
+
requireEvidence: Boolean(args.requireEvidence),
|
|
322
|
+
tool: args.tool,
|
|
323
|
+
sessionId: args.sessionId,
|
|
324
|
+
force: Boolean(args.force),
|
|
325
|
+
dryRun: Boolean(args.dryRun),
|
|
326
|
+
});
|
|
327
|
+
case "done":
|
|
328
|
+
return completeTask({
|
|
329
|
+
projectDir,
|
|
330
|
+
harnessDir,
|
|
331
|
+
taskId: args.task,
|
|
332
|
+
evidenceRefs: args.evidenceRefs,
|
|
333
|
+
requireEvidence: Boolean(args.requireEvidence),
|
|
334
|
+
tool: args.tool,
|
|
335
|
+
sessionId: args.sessionId,
|
|
336
|
+
force: Boolean(args.force),
|
|
337
|
+
dryRun: Boolean(args.dryRun),
|
|
338
|
+
});
|
|
339
|
+
case "claim":
|
|
340
|
+
return claimTaskLease({
|
|
341
|
+
projectDir,
|
|
342
|
+
harnessDir,
|
|
343
|
+
taskId: args.task,
|
|
344
|
+
role: args.role,
|
|
345
|
+
tool: args.tool,
|
|
346
|
+
sessionId: args.sessionId,
|
|
347
|
+
scopes: args.scopes,
|
|
348
|
+
ttlMinutes: args.ttlMinutes,
|
|
349
|
+
force: Boolean(args.force),
|
|
350
|
+
dryRun: Boolean(args.dryRun),
|
|
351
|
+
});
|
|
352
|
+
case "release":
|
|
353
|
+
return releaseTaskLease({
|
|
354
|
+
projectDir,
|
|
355
|
+
harnessDir,
|
|
356
|
+
taskId: args.task,
|
|
357
|
+
tool: args.tool,
|
|
358
|
+
sessionId: args.sessionId,
|
|
359
|
+
role: args.role,
|
|
360
|
+
force: Boolean(args.force),
|
|
361
|
+
dryRun: Boolean(args.dryRun),
|
|
362
|
+
});
|
|
363
|
+
case "leases":
|
|
364
|
+
return listTaskLeases({
|
|
365
|
+
projectDir,
|
|
366
|
+
includeExpired: Boolean(args.includeExpired),
|
|
367
|
+
harnessDir,
|
|
368
|
+
});
|
|
369
|
+
default:
|
|
370
|
+
throw new Error(`Unsupported task action "${action}".`);
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
function invokeCheckpointTool(args, ctx) {
|
|
375
|
+
const action = String(args?.action || "").trim().toLowerCase();
|
|
376
|
+
if (MUTATING_CHECKPOINT_ACTIONS.has(action)) {
|
|
377
|
+
assertWritable(ctx, "geloforge_checkpoint", action);
|
|
378
|
+
}
|
|
379
|
+
const projectDir = resolveTargetProject(args, ctx);
|
|
380
|
+
const harnessDir = ctx.harnessDir;
|
|
381
|
+
switch (action) {
|
|
382
|
+
case "create":
|
|
383
|
+
return createCheckpoint({
|
|
384
|
+
projectDir,
|
|
385
|
+
harnessDir,
|
|
386
|
+
summary: args.summary,
|
|
387
|
+
resumeInstructions: args.resumeInstructions,
|
|
388
|
+
evidenceRef: args.evidenceRef,
|
|
389
|
+
createdBy: args.createdBy || "mcp-client",
|
|
390
|
+
role: args.role,
|
|
391
|
+
status: args.status,
|
|
392
|
+
dryRun: Boolean(args.dryRun),
|
|
393
|
+
});
|
|
394
|
+
case "list":
|
|
395
|
+
return listCheckpoints({ projectDir, status: args.status, harnessDir });
|
|
396
|
+
case "show":
|
|
397
|
+
return getCheckpoint({ projectDir, checkpointId: args.checkpointId, harnessDir });
|
|
398
|
+
default:
|
|
399
|
+
throw new Error(`Unsupported checkpoint action "${action}".`);
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
function invokeSkillsTool(args, ctx) {
|
|
404
|
+
const action = String(args?.action || "").trim().toLowerCase();
|
|
405
|
+
if (BLOCKED_SKILL_ACTIONS.has(action)) {
|
|
406
|
+
throw new Error(
|
|
407
|
+
`Refusing privileged skill mutation/signing over MCP (action "${action}"). Human must authorize via local CLI.`
|
|
408
|
+
);
|
|
409
|
+
}
|
|
410
|
+
if (MUTATING_SKILLS_ACTIONS.has(action)) {
|
|
411
|
+
assertWritable(ctx, "geloforge_skills", action);
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
const projectDir = resolveTargetProject(args, ctx);
|
|
415
|
+
const { harnessDir } = ctx;
|
|
416
|
+
|
|
417
|
+
if (action === "draft") {
|
|
418
|
+
return draftSkillFromExperience({
|
|
419
|
+
projectDir,
|
|
420
|
+
harnessDir,
|
|
421
|
+
evidenceIds: args.evidenceIds || [],
|
|
422
|
+
handoffIds: args.handoffIds || [],
|
|
423
|
+
skillName: args.name,
|
|
424
|
+
title: args.title,
|
|
425
|
+
description: args.description,
|
|
426
|
+
steps: args.steps,
|
|
427
|
+
tags: args.tags,
|
|
428
|
+
triggers: args.triggers,
|
|
429
|
+
dryRun: Boolean(args.dryRun),
|
|
430
|
+
});
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
if (action === "propose" || action === "propose-update") {
|
|
434
|
+
return proposeSkillUpdate({
|
|
435
|
+
projectDir,
|
|
436
|
+
harnessDir,
|
|
437
|
+
skillName: args.name,
|
|
438
|
+
evidenceIds: args.evidenceIds || [],
|
|
439
|
+
handoffIds: args.handoffIds || [],
|
|
440
|
+
reason: args.reason,
|
|
441
|
+
appendNote: args.appendNote,
|
|
442
|
+
dryRun: Boolean(args.dryRun),
|
|
443
|
+
});
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
if (action === "history") {
|
|
447
|
+
return getSkillHistory({ projectDir, skillName: args.name, harnessDir });
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
const loc = resolveProjectForSkills({ project: projectDir, harnessDir });
|
|
451
|
+
|
|
452
|
+
const discovery = discoverSkills({
|
|
453
|
+
projectDir: loc.projectDir,
|
|
454
|
+
proposalsDir: loc.proposalsDir,
|
|
455
|
+
includeDrafts: Boolean(args?.includeDrafts),
|
|
456
|
+
});
|
|
457
|
+
|
|
458
|
+
if (action === "list") {
|
|
459
|
+
return {
|
|
460
|
+
projectDir: discovery.projectDir,
|
|
461
|
+
skills: discovery.visibleSkills.map((s) => ({
|
|
462
|
+
name: s.name,
|
|
463
|
+
source: s.source,
|
|
464
|
+
trustTier: s.trustTier,
|
|
465
|
+
valid: s.valid,
|
|
466
|
+
blocked: s.blocked,
|
|
467
|
+
estimatedTokens: s.estimatedTokens,
|
|
468
|
+
})),
|
|
469
|
+
quarantinedCount: discovery.quarantinedSkills.length,
|
|
470
|
+
conflicts: discovery.conflicts,
|
|
471
|
+
};
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
if (action === "show") {
|
|
475
|
+
if (!args?.name) throw new Error('Missing "name" for geloforge_skills action "show".');
|
|
476
|
+
const found = discovery.visibleSkills.find((s) => s.name === args.name || s.folderName === args.name);
|
|
477
|
+
if (!found) {
|
|
478
|
+
throw new Error(`Skill "${args.name}" not found in visible skills.`);
|
|
479
|
+
}
|
|
480
|
+
return {
|
|
481
|
+
name: found.name,
|
|
482
|
+
source: found.source,
|
|
483
|
+
trustTier: found.trustTier,
|
|
484
|
+
valid: found.valid,
|
|
485
|
+
blocked: found.blocked,
|
|
486
|
+
body: found.hasSecrets ? "[REDACTED]" : found.body,
|
|
487
|
+
lint: lintSkill(found),
|
|
488
|
+
};
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
if (action === "validate") {
|
|
492
|
+
const pool = [...discovery.allSkills, ...(args?.includeDrafts ? discovery.quarantinedSkills : [])];
|
|
493
|
+
return {
|
|
494
|
+
valid: discovery.rootErrors.length === 0 && pool.every((s) => s.valid),
|
|
495
|
+
checkedCount: pool.length,
|
|
496
|
+
invalidCount: pool.filter((s) => !s.valid).length,
|
|
497
|
+
rootErrors: discovery.rootErrors,
|
|
498
|
+
rootWarnings: discovery.rootWarnings,
|
|
499
|
+
};
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
if (action === "lint") {
|
|
503
|
+
return lintDiscoveredSkills(discovery, {
|
|
504
|
+
strict: Boolean(args?.strict),
|
|
505
|
+
includeDrafts: Boolean(args?.includeDrafts),
|
|
506
|
+
});
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
throw new Error(`Unsupported skills action "${action}".`);
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
function executeToolCall(name, args, ctx) {
|
|
513
|
+
switch (name) {
|
|
514
|
+
case "geloforge_status": {
|
|
515
|
+
const projectDir = resolveTargetProject(args, ctx);
|
|
516
|
+
return getProjectStatus(projectDir);
|
|
517
|
+
}
|
|
518
|
+
case "geloforge_recommend": {
|
|
519
|
+
const projectDir = resolveTargetProject(args, ctx);
|
|
520
|
+
return getProjectRecommendations(projectDir);
|
|
521
|
+
}
|
|
522
|
+
case "geloforge_context": {
|
|
523
|
+
const projectDir = resolveTargetProject(args, ctx);
|
|
524
|
+
return compileContext({
|
|
525
|
+
projectDir,
|
|
526
|
+
harnessDir: ctx.harnessDir,
|
|
527
|
+
taskId: args?.task,
|
|
528
|
+
query: args?.query,
|
|
529
|
+
profile: args?.profile || "working",
|
|
530
|
+
budget: args?.budget,
|
|
531
|
+
includeMap: Boolean(args?.map),
|
|
532
|
+
includeSkills: Boolean(args?.skills) || (Array.isArray(args?.pinnedSkills) && args.pinnedSkills.length > 0),
|
|
533
|
+
pinnedSkills: args?.pinnedSkills || [],
|
|
534
|
+
fromDiff: Boolean(args?.fromDiff),
|
|
535
|
+
includeCompleted: Boolean(args?.includeCompleted),
|
|
536
|
+
excludeUnverified: Boolean(args?.excludeUnverified),
|
|
537
|
+
});
|
|
538
|
+
}
|
|
539
|
+
case "geloforge_task":
|
|
540
|
+
return invokeTaskTool(args, ctx);
|
|
541
|
+
case "geloforge_checkpoint":
|
|
542
|
+
return invokeCheckpointTool(args, ctx);
|
|
543
|
+
case "geloforge_skills":
|
|
544
|
+
return invokeSkillsTool(args, ctx);
|
|
545
|
+
default:
|
|
546
|
+
return null;
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
/**
|
|
551
|
+
* Handles a single parsed JSON-RPC 2.0 MCP message and returns the response object
|
|
552
|
+
* (or null for JSON-RPC notifications).
|
|
553
|
+
*/
|
|
554
|
+
export function handleMcpMessage(
|
|
555
|
+
msg,
|
|
556
|
+
{
|
|
557
|
+
defaultProjectDir = null,
|
|
558
|
+
allowedProjectRoots = null,
|
|
559
|
+
cwd = process.cwd(),
|
|
560
|
+
harnessDir = DEFAULT_HARNESS_DIR,
|
|
561
|
+
readOnly = false,
|
|
562
|
+
} = {}
|
|
563
|
+
) {
|
|
564
|
+
const absHarness = path.resolve(harnessDir || DEFAULT_HARNESS_DIR);
|
|
565
|
+
if (!msg || typeof msg !== "object" || Array.isArray(msg) || msg.jsonrpc !== "2.0") {
|
|
566
|
+
const safeId =
|
|
567
|
+
msg && !Array.isArray(msg) && (typeof msg.id === "string" || typeof msg.id === "number") ? msg.id : null;
|
|
568
|
+
return {
|
|
569
|
+
jsonrpc: "2.0",
|
|
570
|
+
id: safeId,
|
|
571
|
+
error: { code: -32600, message: "Invalid JSON-RPC 2.0 request." },
|
|
572
|
+
};
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
if (typeof msg.method !== "string" || msg.method.trim().length === 0) {
|
|
576
|
+
const safeId = typeof msg.id === "string" || typeof msg.id === "number" ? msg.id : null;
|
|
577
|
+
return {
|
|
578
|
+
jsonrpc: "2.0",
|
|
579
|
+
id: safeId,
|
|
580
|
+
error: { code: -32600, message: "Invalid JSON-RPC 2.0 request: missing method." },
|
|
581
|
+
};
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
const isNotification = msg.id === undefined || msg.id === null;
|
|
585
|
+
const method = msg.method;
|
|
586
|
+
|
|
587
|
+
if (method === "notifications/initialized" || method === "notifications/cancelled") {
|
|
588
|
+
return null;
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
if (isNotification && method.startsWith("notifications/")) {
|
|
592
|
+
return null;
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
const ctx = {
|
|
596
|
+
defaultProjectDir,
|
|
597
|
+
allowedProjectRoots,
|
|
598
|
+
cwd: cwd || process.cwd(),
|
|
599
|
+
harnessDir: absHarness,
|
|
600
|
+
readOnly: Boolean(readOnly),
|
|
601
|
+
};
|
|
602
|
+
|
|
603
|
+
try {
|
|
604
|
+
if (method === "initialize") {
|
|
605
|
+
return {
|
|
606
|
+
jsonrpc: "2.0",
|
|
607
|
+
id: msg.id,
|
|
608
|
+
result: {
|
|
609
|
+
protocolVersion: MCP_PROTOCOL_VERSION,
|
|
610
|
+
capabilities: { tools: {} },
|
|
611
|
+
serverInfo: {
|
|
612
|
+
name: "geloforge-mcp",
|
|
613
|
+
version: getHarnessVersion(absHarness),
|
|
614
|
+
},
|
|
615
|
+
},
|
|
616
|
+
};
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
if (method === "ping") {
|
|
620
|
+
return { jsonrpc: "2.0", id: msg.id, result: {} };
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
if (method === "tools/list") {
|
|
624
|
+
return {
|
|
625
|
+
jsonrpc: "2.0",
|
|
626
|
+
id: msg.id,
|
|
627
|
+
result: { tools: MCP_TOOLS },
|
|
628
|
+
};
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
if (method === "tools/call") {
|
|
632
|
+
const toolName = msg.params?.name;
|
|
633
|
+
const rawArgs = msg.params?.arguments;
|
|
634
|
+
if (rawArgs !== undefined && (rawArgs === null || typeof rawArgs !== "object" || Array.isArray(rawArgs))) {
|
|
635
|
+
return {
|
|
636
|
+
jsonrpc: "2.0",
|
|
637
|
+
id: msg.id,
|
|
638
|
+
error: { code: -32602, message: "Invalid tool params: arguments must be a plain object." },
|
|
639
|
+
};
|
|
640
|
+
}
|
|
641
|
+
const toolArgs = rawArgs || {};
|
|
642
|
+
if (typeof toolName !== "string" || !MCP_TOOLS.some((t) => t.name === toolName)) {
|
|
643
|
+
return {
|
|
644
|
+
jsonrpc: "2.0",
|
|
645
|
+
id: msg.id,
|
|
646
|
+
error: { code: -32602, message: `Unknown MCP tool "${String(toolName)}".` },
|
|
647
|
+
};
|
|
648
|
+
}
|
|
649
|
+
try {
|
|
650
|
+
const result = executeToolCall(toolName, toolArgs, ctx);
|
|
651
|
+
const serialized = redactSecretContent(JSON.stringify(result, null, 2));
|
|
652
|
+
return {
|
|
653
|
+
jsonrpc: "2.0",
|
|
654
|
+
id: msg.id,
|
|
655
|
+
result: {
|
|
656
|
+
content: [{ type: "text", text: serialized }],
|
|
657
|
+
isError: false,
|
|
658
|
+
},
|
|
659
|
+
};
|
|
660
|
+
} catch (err) {
|
|
661
|
+
return {
|
|
662
|
+
jsonrpc: "2.0",
|
|
663
|
+
id: msg.id,
|
|
664
|
+
result: {
|
|
665
|
+
content: [{ type: "text", text: redactSecretContent(err.message || "Tool execution failed") }],
|
|
666
|
+
isError: true,
|
|
667
|
+
},
|
|
668
|
+
};
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
if (isNotification) {
|
|
673
|
+
return null;
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
return {
|
|
677
|
+
jsonrpc: "2.0",
|
|
678
|
+
id: msg.id,
|
|
679
|
+
error: { code: -32601, message: `Method not found: ${method}` },
|
|
680
|
+
};
|
|
681
|
+
} catch (err) {
|
|
682
|
+
if (isNotification) return null;
|
|
683
|
+
return {
|
|
684
|
+
jsonrpc: "2.0",
|
|
685
|
+
id: msg.id,
|
|
686
|
+
error: { code: -32603, message: redactSecretContent(err.message || "Internal error") },
|
|
687
|
+
};
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
function writeFramedResponse(output, responseObj, framing) {
|
|
692
|
+
const payload = JSON.stringify(responseObj);
|
|
693
|
+
if (framing === "lsp") {
|
|
694
|
+
const byteLen = Buffer.byteLength(payload, "utf8");
|
|
695
|
+
output.write(`Content-Length: ${byteLen}\r\n\r\n${payload}`);
|
|
696
|
+
} else {
|
|
697
|
+
output.write(`${payload}\n`);
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
function parseLspContentLength(headersText, maxMessageBytes) {
|
|
702
|
+
const lines = headersText.split(/\r?\n/);
|
|
703
|
+
const contentLengths = [];
|
|
704
|
+
for (const rawLine of lines) {
|
|
705
|
+
if (!rawLine.trim()) continue;
|
|
706
|
+
const colonIdx = rawLine.indexOf(":");
|
|
707
|
+
if (colonIdx <= 0) {
|
|
708
|
+
return { ok: false, error: "Malformed LSP header line.", contentLength: 0 };
|
|
709
|
+
}
|
|
710
|
+
const name = rawLine.slice(0, colonIdx).trim().toLowerCase();
|
|
711
|
+
const val = rawLine.slice(colonIdx + 1).trim();
|
|
712
|
+
if (name === "content-length") {
|
|
713
|
+
if (!/^\d+$/.test(val)) {
|
|
714
|
+
return { ok: false, error: `Invalid Content-Length header "${val}".`, contentLength: 0 };
|
|
715
|
+
}
|
|
716
|
+
const n = Number(val);
|
|
717
|
+
if (!Number.isSafeInteger(n) || n <= 0) {
|
|
718
|
+
return { ok: false, error: `Invalid Content-Length value ${val} (must be >= 1).`, contentLength: 0 };
|
|
719
|
+
}
|
|
720
|
+
if (n > maxMessageBytes) {
|
|
721
|
+
return {
|
|
722
|
+
ok: false,
|
|
723
|
+
error: `MCP message Content-Length (${n} bytes) exceeds maxMessageBytes (${maxMessageBytes}).`,
|
|
724
|
+
contentLength: n,
|
|
725
|
+
skipBody: true,
|
|
726
|
+
};
|
|
727
|
+
}
|
|
728
|
+
contentLengths.push(n);
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
if (contentLengths.length === 0) {
|
|
732
|
+
return { ok: false, error: "Missing Content-Length header in LSP frame.", contentLength: 0 };
|
|
733
|
+
}
|
|
734
|
+
if (new Set(contentLengths).size > 1) {
|
|
735
|
+
return { ok: false, error: "Conflicting duplicate Content-Length headers.", contentLength: 0 };
|
|
736
|
+
}
|
|
737
|
+
return { ok: true, contentLength: contentLengths[0] };
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
function findHeaderSeparator(buffer) {
|
|
741
|
+
const crlf = buffer.indexOf("\r\n\r\n");
|
|
742
|
+
const lf = buffer.indexOf("\n\n");
|
|
743
|
+
if (crlf !== -1 && (lf === -1 || crlf <= lf)) {
|
|
744
|
+
return { index: crlf, len: 4 };
|
|
745
|
+
}
|
|
746
|
+
if (lf !== -1) {
|
|
747
|
+
return { index: lf, len: 2 };
|
|
748
|
+
}
|
|
749
|
+
return { index: -1, len: 0 };
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
/**
|
|
753
|
+
* Starts the synchronous-per-message MCP JSON-RPC 2.0 server over stdin/stdout streams.
|
|
754
|
+
* Enforces bounded message/header sizes and malformed frame recovery cleanly.
|
|
755
|
+
* Resolves when input stream ends cleanly.
|
|
756
|
+
*/
|
|
757
|
+
export function startMcpStdioServer({
|
|
758
|
+
defaultProjectDir = null,
|
|
759
|
+
allowedProjectRoots = null,
|
|
760
|
+
cwd = process.cwd(),
|
|
761
|
+
harnessDir = DEFAULT_HARNESS_DIR,
|
|
762
|
+
input = process.stdin,
|
|
763
|
+
output = process.stdout,
|
|
764
|
+
maxMessageBytes = MAX_MCP_MESSAGE_BYTES,
|
|
765
|
+
maxHeaderBytes = MAX_MCP_HEADER_BYTES,
|
|
766
|
+
readOnly = false,
|
|
767
|
+
} = {}) {
|
|
768
|
+
const safeMaxMsg =
|
|
769
|
+
Number.isInteger(maxMessageBytes) && maxMessageBytes >= 64 ? maxMessageBytes : MAX_MCP_MESSAGE_BYTES;
|
|
770
|
+
const safeMaxHdr =
|
|
771
|
+
Number.isInteger(maxHeaderBytes) && maxHeaderBytes >= 64 ? maxHeaderBytes : MAX_MCP_HEADER_BYTES;
|
|
772
|
+
|
|
773
|
+
return new Promise((resolve, reject) => {
|
|
774
|
+
let buffer = Buffer.alloc(0);
|
|
775
|
+
let discardRemainingBytes = 0;
|
|
776
|
+
let discardUntilNewline = false;
|
|
777
|
+
|
|
778
|
+
const emitError = (code, message, framing) => {
|
|
779
|
+
writeFramedResponse(output, { jsonrpc: "2.0", id: null, error: { code, message } }, framing);
|
|
780
|
+
};
|
|
781
|
+
|
|
782
|
+
const dispatchRaw = (rawJson, framing) => {
|
|
783
|
+
let msg;
|
|
784
|
+
try {
|
|
785
|
+
msg = JSON.parse(rawJson);
|
|
786
|
+
} catch {
|
|
787
|
+
emitError(-32700, "Parse error", framing);
|
|
788
|
+
return;
|
|
789
|
+
}
|
|
790
|
+
const reply = handleMcpMessage(msg, {
|
|
791
|
+
defaultProjectDir,
|
|
792
|
+
allowedProjectRoots,
|
|
793
|
+
cwd,
|
|
794
|
+
harnessDir,
|
|
795
|
+
readOnly,
|
|
796
|
+
});
|
|
797
|
+
if (reply !== null) {
|
|
798
|
+
writeFramedResponse(output, reply, framing);
|
|
799
|
+
}
|
|
800
|
+
};
|
|
801
|
+
|
|
802
|
+
const drainBuffer = () => {
|
|
803
|
+
while (buffer.length > 0) {
|
|
804
|
+
if (discardRemainingBytes > 0) {
|
|
805
|
+
const drop = Math.min(discardRemainingBytes, buffer.length);
|
|
806
|
+
buffer = buffer.subarray(drop);
|
|
807
|
+
discardRemainingBytes -= drop;
|
|
808
|
+
continue;
|
|
809
|
+
}
|
|
810
|
+
|
|
811
|
+
if (discardUntilNewline) {
|
|
812
|
+
const nlIdx = buffer.indexOf("\n");
|
|
813
|
+
if (nlIdx === -1) {
|
|
814
|
+
buffer = Buffer.alloc(0);
|
|
815
|
+
break;
|
|
816
|
+
}
|
|
817
|
+
buffer = buffer.subarray(nlIdx + 1);
|
|
818
|
+
discardUntilNewline = false;
|
|
819
|
+
continue;
|
|
820
|
+
}
|
|
821
|
+
|
|
822
|
+
// Trim leading whitespace before inspecting framing style
|
|
823
|
+
let skip = 0;
|
|
824
|
+
while (
|
|
825
|
+
skip < buffer.length &&
|
|
826
|
+
(buffer[skip] === 0x20 || buffer[skip] === 0x09 || buffer[skip] === 0x0d || buffer[skip] === 0x0a)
|
|
827
|
+
) {
|
|
828
|
+
skip += 1;
|
|
829
|
+
}
|
|
830
|
+
if (skip > 0) {
|
|
831
|
+
buffer = buffer.subarray(skip);
|
|
832
|
+
}
|
|
833
|
+
if (buffer.length === 0) break;
|
|
834
|
+
|
|
835
|
+
const headPreview = buffer.subarray(0, Math.min(32, buffer.length)).toString("utf8");
|
|
836
|
+
if (/^content-(?:length|type)\s*:/i.test(headPreview)) {
|
|
837
|
+
const { index: sepIndex, len: sepLen } = findHeaderSeparator(buffer);
|
|
838
|
+
if (sepIndex === -1) {
|
|
839
|
+
if (buffer.length > safeMaxHdr) {
|
|
840
|
+
buffer = Buffer.alloc(0);
|
|
841
|
+
emitError(-32600, `MCP header block exceeds maxHeaderBytes (${safeMaxHdr}).`, "lsp");
|
|
842
|
+
}
|
|
843
|
+
break;
|
|
844
|
+
}
|
|
845
|
+
if (sepIndex > safeMaxHdr) {
|
|
846
|
+
buffer = buffer.subarray(sepIndex + sepLen);
|
|
847
|
+
emitError(-32600, `MCP header block exceeds maxHeaderBytes (${safeMaxHdr}).`, "lsp");
|
|
848
|
+
continue;
|
|
849
|
+
}
|
|
850
|
+
const headersText = buffer.subarray(0, sepIndex).toString("utf8");
|
|
851
|
+
const parsedHdr = parseLspContentLength(headersText, safeMaxMsg);
|
|
852
|
+
if (!parsedHdr.ok) {
|
|
853
|
+
buffer = buffer.subarray(sepIndex + sepLen);
|
|
854
|
+
if (parsedHdr.skipBody && parsedHdr.contentLength > 0) {
|
|
855
|
+
discardRemainingBytes = parsedHdr.contentLength;
|
|
856
|
+
}
|
|
857
|
+
emitError(-32600, parsedHdr.error, "lsp");
|
|
858
|
+
continue;
|
|
859
|
+
}
|
|
860
|
+
const contentLen = parsedHdr.contentLength;
|
|
861
|
+
const bodyStart = sepIndex + sepLen;
|
|
862
|
+
if (buffer.length < bodyStart + contentLen) {
|
|
863
|
+
break;
|
|
864
|
+
}
|
|
865
|
+
const bodyText = buffer.subarray(bodyStart, bodyStart + contentLen).toString("utf8");
|
|
866
|
+
buffer = buffer.subarray(bodyStart + contentLen);
|
|
867
|
+
dispatchRaw(bodyText, "lsp");
|
|
868
|
+
} else {
|
|
869
|
+
const nlIdx = buffer.indexOf("\n");
|
|
870
|
+
if (nlIdx === -1) {
|
|
871
|
+
if (buffer.length > safeMaxMsg) {
|
|
872
|
+
buffer = Buffer.alloc(0);
|
|
873
|
+
discardUntilNewline = true;
|
|
874
|
+
emitError(-32600, `MCP message exceeds maxMessageBytes (${safeMaxMsg}).`, "jsonl");
|
|
875
|
+
}
|
|
876
|
+
break;
|
|
877
|
+
}
|
|
878
|
+
if (nlIdx > safeMaxMsg) {
|
|
879
|
+
buffer = buffer.subarray(nlIdx + 1);
|
|
880
|
+
emitError(-32600, `MCP message exceeds maxMessageBytes (${safeMaxMsg}).`, "jsonl");
|
|
881
|
+
continue;
|
|
882
|
+
}
|
|
883
|
+
const line = buffer.subarray(0, nlIdx).toString("utf8").trim();
|
|
884
|
+
buffer = buffer.subarray(nlIdx + 1);
|
|
885
|
+
if (line.length > 0) {
|
|
886
|
+
dispatchRaw(line, "jsonl");
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
}
|
|
890
|
+
};
|
|
891
|
+
|
|
892
|
+
input.on("data", (chunk) => {
|
|
893
|
+
const bufChunk = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk), "utf8");
|
|
894
|
+
buffer = Buffer.concat([buffer, bufChunk]);
|
|
895
|
+
drainBuffer();
|
|
896
|
+
});
|
|
897
|
+
|
|
898
|
+
input.on("end", () => {
|
|
899
|
+
if (!discardUntilNewline && discardRemainingBytes === 0 && buffer.length > 0) {
|
|
900
|
+
if (buffer.length > safeMaxMsg) {
|
|
901
|
+
emitError(-32600, `MCP message exceeds maxMessageBytes (${safeMaxMsg}).`, "jsonl");
|
|
902
|
+
} else {
|
|
903
|
+
const leftover = buffer.toString("utf8").trim();
|
|
904
|
+
if (leftover && !/^content-(?:length|type)\s*:/i.test(leftover)) {
|
|
905
|
+
dispatchRaw(leftover, "jsonl");
|
|
906
|
+
}
|
|
907
|
+
}
|
|
908
|
+
}
|
|
909
|
+
buffer = Buffer.alloc(0);
|
|
910
|
+
resolve();
|
|
911
|
+
});
|
|
912
|
+
|
|
913
|
+
input.on("error", reject);
|
|
914
|
+
});
|
|
915
|
+
}
|