Skip to content

udhaykumarbala/claude-code-parser

Repository files navigation

claude-code-parser

npm version bundle size

Parse Claude Code's --output-format stream-json NDJSON output into fully typed TypeScript events. Zero dependencies. 9 kB.

Documentation | Protocol Reference

Includes the first standalone documentation of Claude Code's undocumented stream-json protocol.

Install

npm install claude-code-parser

Quick Start

import { spawn } from 'child_process'
import { createInterface } from 'readline'
import { parseLine, Translator, createMessage } from 'claude-code-parser'

const claude = spawn('claude', [
  '-p', '--input-format', 'stream-json',
  '--output-format', 'stream-json', '--verbose',
], { stdio: ['pipe', 'pipe', 'inherit'] })

const translator = new Translator()

const rl = createInterface({ input: claude.stdout! })
rl.on('line', (line) => {
  const event = parseLine(line)
  if (!event) return

  for (const relay of translator.translate(event)) {
    switch (relay.type) {
      case 'text_delta':    process.stdout.write(relay.content); break
      case 'tool_use':      console.log(`\n[tool] ${relay.toolName}`); break
      case 'turn_complete': console.log(`\n[done] $${relay.costUsd?.toFixed(4)}`); break
    }
  }
})

claude.stdin!.write(createMessage.user('What is 2 + 2?'))

API

Export Description
parseLine(line) NDJSON line → ClaudeEvent | null
Translator Stateful dedup translator → RelayEvent[]
createMessage.user(text) Construct stdin user message
createMessage.approve(id) Approve pending tool execution
createMessage.deny(id) Deny pending tool execution
createMessage.toolResult(id, content) Send tool result
extractContent(raw) Normalize polymorphic tool_result content

RelayEvent Types

text_delta | thinking_delta | tool_use | tool_result | session_meta | turn_complete | error

Full API docs

Why This Exists

The official SDK (@anthropic-ai/claude-code) couples parsing with subprocess management. This library only parses — for developers building custom relays, dashboards, CI tools, or browser viewers who need raw event access.

Key problems it solves:

  • --verbose deduplication — cumulative snapshots require stateful content tracking
  • Multi-agent interleaving — sub-agents produce interleaved events on the same stdout
  • Polymorphic contenttool_result.content can be string, array, or null
  • Double-encoded results — the result field is JSON inside JSON

Documentation

License

MIT

This is an unofficial community package. Not affiliated with or endorsed by Anthropic.

About

Parse Claude Code's --output-format stream-json into fully typed TypeScript events. Zero dependencies.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors