{"slug": "build-your-own-chat-ui-for-claude-code-the-stdin-control-protocol-with-a-host", "title": "Build your own chat UI for Claude Code: the stdin control protocol, with a runnable host", "summary": "A developer documented how to drive Claude Code as a long-lived bidirectional child process using `claude -p` with stream-JSON input and output plus `--permission-prompt-tool stdio`, publishing a runnable Node host script that answers `can_use_tool` control requests itself. The writeup shows the CLI can pause mid-run to ask the host a question and wait for a reply, and warns that wrappers hang if they don't handle these control requests. The host was tested on Claude Code 2.1.332 on Windows.", "body_md": "`claude -p` looks like a one-shot command, but it can also be a long-lived child process that talks to your program in both directions. That is how you build your own chat UI, bot, or review tool around Claude Code without scraping a terminal.\n\nThe part that surprised me is that the CLI can **ask your program a question in the middle of a run and then wait for the answer**. If you don't know that, your wrapper hangs. If you do, you get proper question cards, plan approvals, and permission prompts.\n\nThis post shows the handshake with a runnable host, one real run I captured, and the mistakes that are easy to make. I tested it on Claude Code `2.1.332` on Windows.\n\nYou start the CLI with stream-JSON on both sides:\n\n```\nclaude -p --input-format stream-json --output-format stream-json \\\n  --verbose --permission-prompt-tool stdio\n```\n\n`system/init`, `assistant`, `user` (tool results), `result`, and the interesting one, `control_request`.\n`--permission-prompt-tool stdio` is what routes \"this tool needs a human\" decisions to you instead of handling them inside the CLI. Without a reply from you, those decisions can't be made.\n\nThis is the whole thing. It sends one prompt that forces the `AskUserQuestion` tool, answers the question itself, and prints every event with a timestamp.\n\n```\n// A tiny \"host\" for Claude Code: drives the CLI over stdin/stdout, answers can_use_tool itself.\n// Usage: node host-experiment.mjs <empty-working-dir>\nimport { spawn } from 'node:child_process';\nimport readline from 'node:readline';\n\nconst cwd = process.argv[2];\nconst env = { ...process.env };\ndelete env.CLAUDECODE; delete env.CLAUDE_CODE_ENTRYPOINT;\nconst child = spawn('claude', [\n  '-p', '--input-format', 'stream-json', '--output-format', 'stream-json',\n  '--verbose', '--permission-prompt-tool', 'stdio', '--model', 'haiku',\n], { cwd, env, shell: process.platform === 'win32' });\n\nconst send = (obj) => child.stdin.write(JSON.stringify(obj) + '\\n');\nconst t0 = Date.now();\nconst log = (...a) => console.log(`+${((Date.now() - t0) / 1000).toFixed(1)}s`, ...a);\n\nsend({ type: 'user', message: { role: 'user', content: [{ type: 'text',\n  text: 'Use the AskUserQuestion tool to ask me whether to name the project \"alpha\" or \"beta\" (two options). After I answer, reply with one short sentence naming my choice. Do not use any other tool.' }] } });\n\nreadline.createInterface({ input: child.stdout }).on('line', (line) => {\n  let m; try { m = JSON.parse(line); } catch { return log('non-json:', line.slice(0, 80)); }\n  const sub = m.subtype ? `/${m.subtype}` : m.request?.subtype ? `/${m.request.subtype}` : '';\n  log(m.type + sub);\n  if (m.type === 'control_request' && m.request.subtype === 'can_use_tool' && process.env.NO_REPLY) { log('  (not replying on purpose)'); return; }\n  if (m.type === 'control_request' && m.request.subtype === 'can_use_tool') {\n    log('  tool_name =', m.request.tool_name, '| input keys =', Object.keys(m.request.input).join(','));\n    log('  questions =', JSON.stringify(m.request.input.questions).slice(0, 400));\n    const q = m.request.input.questions[0];\n    send({ type: 'control_response', response: { subtype: 'success', request_id: m.request_id,\n      response: { behavior: 'allow', updatedInput: { ...m.request.input, answers: { [q.question]: q.options[1].label } } } } });\n    log('  -> replied allow + answers');\n  }\n  if (m.type === 'result') { log('  result =', JSON.stringify(m.result).slice(0, 200)); child.stdin.end(); setTimeout(() => { child.kill(); process.exit(0); }, 300); }\n});\nsetTimeout(() => { log('timeout, killing'); child.kill(); process.exit(0); }, Number(process.env.TIMEOUT_MS ?? 120000));\n```\n\nTwo details worth knowing:\n\n`CLAUDECODE` and `CLAUDE_CODE_ENTRYPOINT` from the environment only because I launch this from inside another Claude Code session. You probably don't need that.`NO_REPLY` switch exists for the experiment further down. It makes the host stay silent on purpose.\nHere is the output from a single run, which I then drew as a timeline:\n\n```\n+2.3s system/init\n+5.8s assistant\n+5.8s control_request/can_use_tool\n+5.8s   tool_name = AskUserQuestion | input keys = questions\n+5.8s   -> replied allow + answers\n+5.8s user\n+9.1s assistant\n+9.7s result/success\n+9.7s   result = \"You chose \\\"beta\\\" as the project name.\"\n```\n\nThe model called `AskUserQuestion`; the CLI turned that into a `control_request` and stopped; the host answered; the model read the answer and finished. The timings are from one run on a small model, so treat them as a shape, not a benchmark.\n\nThe request carries the tool name and the tool's input. For `AskUserQuestion` that input is a list of questions, each with a header, options, and a `multiSelect` flag.\n\nYour reply is a `control_response` that echoes the `request_id`. To allow the tool, return `behavior: \"allow\"` and an `updatedInput`, which is the original input plus an `answers` object keyed by the question text:\n\nIn our own host, a multi-select answer is joined with `\", \"` and any free-text note from the user is appended to the same string. I only ran a single-select question for this post, so check multi-select against your CLI version before relying on it.\n\n`can_use_tool` is not only for questions. It is the CLI's way of saying \"a tool wants to run and the decision belongs to the host\". Your policy is yours to define. This is what we settled on in AnBoWork, with the reason for each row:\n\nA few of these are worth explaining:\n\n`ExitPlanMode`, we render the plan as a card, then `interrupt: true` so the run ends instead of waiting forever.\nThe `message` you send with a deny is read by the model. Write it like an instruction, not like an error code.\n\nWhat happens if the host just doesn't reply? I ran the same script with `NO_REPLY=1`:\n\n```\n+2.5s system/init\n+6.2s assistant\n+6.2s control_request/can_use_tool\n+6.2s   (not replying on purpose)\n+25.0s timeout, killing\n```\n\nNothing happened for about 19 seconds, until my own timer killed the process. I didn't wait longer to find out whether the CLI has a timeout of its own, so I can't tell you what that limit is, only that a wrapper which forgets to answer looks exactly like a hung session.\n\n`request_id``--help` on `2.1.332` documents `--permission-prompts host` and `--permission-prompt-tool` as the way to receive these prompts. I would still re-run a script like this after every upgrade.\nIf you just want the same idea without parsing JSON lines yourself, the official Agent SDK exposes it as a `canUseTool` callback. Writing the host by hand is mostly useful when you want to understand what the SDK is doing, or when you are wrapping the binary in a language the SDK doesn't cover.\n\n`claude -p` with stream-JSON on both sides is a two-way protocol, not just a pipe.`control_response`.` allow` with `updatedInput.answers` is how a question gets answered; `deny` with a good message is how you steer the model.\n*Disclosure: I work on AnBoWork, a desktop workbench that drives the official Claude Code and Codex command-line programs and shows them as a chat interface. The policy table above is what our host does today. The host script is a minimal demo, not our production code.*", "url": "https://wpnews.pro/news/build-your-own-chat-ui-for-claude-code-the-stdin-control-protocol-with-a-host", "canonical_source": "https://dev.to/anbowork/build-your-own-chat-ui-for-claude-code-the-stdin-control-protocol-with-a-runnable-host-3npe", "published_at": "2026-12-01 00:39:22+00:00", "updated_at": "2026-12-01 00:44:30.678297+00:00", "lang": "en", "topics": ["ai-agents", "ai-tools", "developer-tools", "large-language-models"], "entities": ["Claude Code", "Anthropic", "Node.js"], "also_reported_by": [], "takeaway": "Spawn `claude -p` with `--input-format stream-json --output-format stream-json --permission-prompt-tool stdio` and answer each `control_request`/`can_use_tool` message with a `control_response` carrying `behavior: allow` and `updatedInput.answers`, or the wrapper hangs waiting on a decision.", "recommendation": {"advice": "When wrapping Claude Code, handle `control_request` messages with subtype `can_use_tool` by replying with a `control_response` that includes `request_id` and `updatedInput.answers`, since the CLI blocks until the host responds.", "playbook": "agent-architecture", "playbook_url": "https://wpnews.pro/playbooks/agent-architecture"}, "alternates": {"html": "https://wpnews.pro/news/build-your-own-chat-ui-for-claude-code-the-stdin-control-protocol-with-a-host", "markdown": "https://wpnews.pro/news/build-your-own-chat-ui-for-claude-code-the-stdin-control-protocol-with-a-host.md", "text": "https://wpnews.pro/news/build-your-own-chat-ui-for-claude-code-the-stdin-control-protocol-with-a-host.txt", "jsonld": "https://wpnews.pro/news/build-your-own-chat-ui-for-claude-code-the-stdin-control-protocol-with-a-host.jsonld"}}