fix(tooling): emit NDJSON MCP responses for agentctl and jev

Cursor IDE loads pi-subagents (NDJSON) but not agentctl/jev which replied
with Content-Length framing. Align send() and mark type=stdio in mcp.json.
This commit is contained in:
weichen
2026-09-24 10:39:43 +00:00
parent 03fd135593
commit 36793a4ea5
7 changed files with 91 additions and 6 deletions
+6 -2
View File
@@ -42,9 +42,13 @@ The executor resolves `agentctl` helpers from the git main worktree scripts dire
Scoped reads: `scripts/pi-subagent-readonly.ts` — builtin `path` only; `@`/`~` denied; directory walks must contain only allowlisted regular files. Approved tests use a separate snapshot; model evidence stays pristine.
### Cursor CLI compatibility (pi-subagents)
### Cursor CLI / IDE compatibility
Real Cursor CLI `2026.09.18` (and `2026.09.23` verified here) does **not** expand `${workspaceFolder}` in MCP `args`. The `pi-subagents` entry therefore uses workspace-relative `args: ["scripts/mcp/pi-subagents-mcp.mjs"]` with `type: "stdio"` / `command: "node"`. Absolute `${workspaceFolder}/…` paths fail with `Cannot find module '…/${workspaceFolder}/scripts/mcp/pi-subagents-mcp.mjs'`. After `agent mcp enable pi-subagents`, `agent mcp list-tools pi-subagents` must report exactly three tools: `pi_subagent_roles`, `pi_subagent_run`, `pi_subagent_result`. Older `agentctl` / `jev` entries may still use `${workspaceFolder}` until separately corrected.
Real Cursor CLI `2026.09.18+` does **not** expand `${workspaceFolder}` in MCP `args`. All Node MCP entries use workspace-relative `args: ["scripts/mcp/….mjs"]` with `"type": "stdio"`.
**Response framing:** Cursor stdio MCP expects **newline-delimited JSON-RPC** responses (same as `pi-subagents-mcp.mjs`). `agentctl-mcp.mjs` / `jev-mcp.mjs` historically replied with `Content-Length` framing, which prevented IDE loading even after path fixes; they now emit NDJSON while still accepting Content-Length *requests* on stdin.
After reload + enable: `agent mcp list-tools agentctl` / `jev` / `pi-subagents` should list tools. Older Connection-failed notes that only cited `${workspaceFolder}` are incomplete without the framing check.
### Limitations (v1)
+3 -2
View File
@@ -4,7 +4,6 @@
* lease_run passes command as argv after `--` — no extra shell.
*/
import { spawnSync } from 'node:child_process';
import { createInterface } from 'node:readline';
import { fileURLToPath } from 'node:url';
import path from 'node:path';
import fs from 'node:fs';
@@ -339,8 +338,10 @@ function callTool(name, args = {}) {
}
function send(msg) {
// Cursor IDE/CLI stdio MCP expects newline-delimited JSON-RPC (same as pi-subagents).
// Still accept Content-Length framed *requests* on stdin for compatibility.
const body = JSON.stringify(msg);
process.stdout.write(`Content-Length: ${Buffer.byteLength(body, 'utf8')}\r\n\r\n${body}`);
process.stdout.write(body + '\n');
}
function handle(msg) {
+3 -1
View File
@@ -165,8 +165,10 @@ async function callTool(name, args = {}) {
}
function send(msg) {
// Cursor IDE/CLI stdio MCP expects newline-delimited JSON-RPC (same as pi-subagents).
// Still accept Content-Length framed *requests* on stdin for compatibility.
const body = JSON.stringify(msg);
process.stdout.write(`Content-Length: ${Buffer.byteLength(body, 'utf8')}\r\n\r\n${body}`);
process.stdout.write(body + '\n');
}
function handle(msg) {
+70
View File
@@ -0,0 +1,70 @@
"""Stdio MCP framing: Cursor expects NDJSON responses (pi-subagents style)."""
from __future__ import annotations
import json
import subprocess
import unittest
from pathlib import Path
REPO = Path(__file__).resolve().parents[2]
MCP = REPO / "scripts" / "mcp"
class McpNdjsonFramingTest(unittest.TestCase):
def _handshake(self, script: Path) -> dict:
"""Send NDJSON initialize; expect a single NDJSON JSON-RPC response line."""
req = {
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2024-11-05",
"capabilities": {},
"clientInfo": {"name": "unittest", "version": "0"},
},
}
r = subprocess.run(
["node", str(script)],
input=json.dumps(req) + "\n",
capture_output=True,
text=True,
cwd=str(REPO),
timeout=10,
check=False,
)
out = (r.stdout or "").strip()
# Must not use Content-Length response framing for Cursor IDE.
self.assertFalse(
out.lower().startswith("content-length:"),
f"{script.name} still uses Content-Length response: {out[:120]!r}",
)
lines = [ln for ln in out.splitlines() if ln.strip()]
self.assertTrue(lines, f"{script.name} produced no stdout: stderr={r.stderr!r}")
msg = json.loads(lines[0])
self.assertEqual(msg.get("jsonrpc"), "2.0")
self.assertEqual(msg.get("id"), 1)
self.assertIn("result", msg)
return msg
def test_agentctl_initialize_ndjson(self):
msg = self._handshake(MCP / "agentctl-mcp.mjs")
self.assertEqual(msg["result"]["serverInfo"]["name"], "agentctl")
def test_jev_initialize_ndjson(self):
msg = self._handshake(MCP / "jev-mcp.mjs")
self.assertEqual(msg["result"]["serverInfo"]["name"], "jev")
def test_pi_subagents_initialize_ndjson(self):
msg = self._handshake(MCP / "pi-subagents-mcp.mjs")
self.assertEqual(msg["result"]["serverInfo"]["name"], "pi-subagents")
def test_mcp_json_stdio_type_for_all_node_servers(self):
cfg = json.loads((REPO / ".cursor" / "mcp.json").read_text(encoding="utf-8"))
for name in ("agentctl", "jev", "pi-subagents"):
entry = cfg["mcpServers"][name]
self.assertEqual(entry.get("type"), "stdio", name)
self.assertTrue(any(a.startswith("scripts/") for a in entry["args"]), name)
if __name__ == "__main__":
unittest.main()