게시 2026-11-16Published 2026-11-16AIML읽는 시간 14분14 min read직접 테스트: Claude Code v2.1.325와 Sonnet 5.5, 작업마다 모드별 3회 실행Tested first-hand: Claude Code v2.1.325 with Sonnet 5.5, 3 runs per task and mode

Claude Code의 Code Mode 기능 기반의 토큰 절감Token savings with the Code Mode feature in Claude Code

Claude Code의 Code Mode를 켜면 토큰과 비용의 절감 효과를 실제 테스트 해 보았습니다. 실제 사용 중인 환경에서 적용해 보면 API 요청에 실리는 도구가 16개에서 3개로 줄어 기본 도구 작업에서는 총 토큰이 42%, 비용이 13% 줄었습니다. 하지만 MCP 도구 작업에서는 도구를 찾는 왕복이 더해져 총 토큰이 19% 늘었습니다. 현재 이 기능은 Anthropic API에 직접 연결한 대화형 터미널 세션에서만 동작합니다. 지원 모델은 Claude Opus 5.5, Sonnet 5.5, Haiku 5.5, Fable 5.2이고 이 글의 측정에는 Sonnet 5.5를 사용했습니다.I turned on Code Mode in Claude Code and tested how much it saves in tokens and cost. Applied in an environment in actual use, the tools in each API request went from 16 to 3, so tasks on built-in tools used 42% fewer total tokens and cost 13% less. However, tasks on MCP tools needed extra round trips to find the tools and used 19% more total tokens. This feature currently runs only in an interactive terminal session connected directly to the Anthropic API. It supports Claude Opus 5.5, Sonnet 5.5, Haiku 5.5, and Fable 5.2, and the measurements in this post used Sonnet 5.5.

#Claude Code#Code Mode#MCP#Prompt Caching#Token Economics

들어가며

Claude Code v2.1.323에 Code Mode가 추가됐습니다. npm 게시일은 2026년 11월 12일입니다. Changelog는 이 기능을 Claude가 JavaScript를 작성해 도구를 호출하는 실험적 옵트인 기능으로 소개합니다.

이 방식으로 줄이려는 것은 왕복(round trip)과 도구 정의(tool definitions)입니다. 여러 도구 호출을 코드 하나로 묶으면 모델과 주고받는 왕복이 줄고 요청마다 실리는 도구 정의도 줄어듭니다. 필자는 이 효과가 얼마나 되는지 확인하려고 같은 작업을 Code Mode를 끈 세션과 켠 세션에서 실행해 토큰, 비용, 왕복 횟수를 비교했습니다. 버전은 v2.1.325, 모델은 Sonnet 5.5이고 측정은 54회입니다.

Code Mode는 실험 기능이고 기본값은 비활성화 입니다. 공식 문서는 어느 릴리스에서든 바뀌거나 없어질 수 있다고 공지하고 있습니다. 이 글의 수치는 2026년 11월 15일에 v2.1.325에서 측정한 값입니다.

01

Code Mode가 바꾸는 것

공식 문서에 따르면 Code Mode가 없을 때 Claude는 Bash, Read, Edit 같은 도구 호출을 직접 요청하고 결과를 하나씩 읽은 뒤 다음 행동을 정합니다. Code Mode에서는 Claude가 도구 호출을 담은 JavaScript를 작성하고 Claude Code가 그 코드를 세션 안에서 실행합니다. 코드 하나가 명령을 병렬로 실행하고 앞 호출의 결과를 다음 호출에 넘기며 Claude가 읽어야 할 부분만 돌려줍니다.

아래는 공식 문서의 예시입니다. 재시도 한도를 올려 달라는 요청에 Claude가 파일을 찾아 수정하고 테스트까지 실행하는 코드를 작성합니다. 마지막 줄이 수정한 파일의 경로와 테스트 출력을 Claude에게 돌려줍니다.

javascript
const files = await $`rg -l "function retryPolicy" src`.text();
const target = files.trim().split("\n")[0];
await edit(target, "maxAttempts: 3", "maxAttempts: 5");
({ edited: target, tests: $`npm test -- retryPolicy`.nothrow() });

대화 화면에는 코드 대신 수정 diff 같은 도구 호출이 표시됩니다. 코드를 보려면 Ctrl+O로 기록 보기(transcript viewer)를 열고 접혀 있는 Code 행을 펼칩니다.

API 요청에서 달라지는 것

Claude Code는 세션 기록 파일에 API로 보낸 요청의 형태를 남깁니다. 같은 프로젝트에서 Code Mode를 끈 세션과 켠 세션의 기록을 비교했습니다.

Code Mode를 끈 세션은 요청마다 도구 정의 16개를 싣고 도구 호출 결과를 읽을 때마다 모델에 다시 요청합니다. 켠 세션은 도구 3개만 싣고 스크립트 하나가 여러 도구를 호출한 뒤 필요한 결과만 돌려주는 구조를 나란히 놓은 그림
그림 1. Code Mode를 끈 세션과 켠 세션의 요청 구조
항목Code Mode 끔Code Mode 켬
API 요청의 도구 수16개3개 (REPL, Poll, advisor)
도구 정의 크기74,886자36,392자. 이 가운데 REPL 설명문이 32,392자
첫 요청의 입력 토큰35.0k22.8k
/context의 System tools 추정치21.9k6.1k
MCP 도구 9개를 연결했을 때이름만 먼저 싣고 ToolSearch 뒤에 스키마를 불러와 26개그대로 3개

표 1. Code Mode를 끈 세션과 켠 세션의 API 요청 비교. v2.1.325, Sonnet 5.5, 플러그인과 MCP 서버를 뺀 구성

Code Mode를 끈 세션에서도 응답 하나에 도구 호출 여러 개를 담을 수 있습니다. 요청마다 도구 정의와 앞선 대화를 다시 보내지만 이 부분은 프롬프트 캐시(prompt cache)에서 읽혀 낮은 단가로 계산됩니다. 측정 결과가 기대와 달랐던 이유가 이 두 가지입니다. 요청마다 앞부분을 다시 보내는 구조와 캐시의 관계는 Claude Code 토큰 비용 최적화하기 1부에서 다뤘습니다.

REPL 도구 하나에 담긴 것

Claude가 작성한 코드는 REPL이라는 도구로 실행됩니다. 도구 수는 줄었지만 기존 도구가 없어진 것은 아닙니다. REPL 설명문 안에 Bash, Read, Edit, Write, Glob, Grep, Agent를 포함한 도구 15개가 TypeScript 시그니처로 들어 있습니다. 덜 사용하는 기본 도구 20개는 이름만 나열돼 있고 describeTool(name)으로 스키마를 조회합니다. MCP 도구는 이름도 실리지 않으며 설명문은 searchTools로 찾으라고 안내합니다.

설명문은 비용 구조도 모델에게 직접 알려 줍니다. REPL 호출 하나하나가 모델 왕복이고 그때마다 대화 전체를 다시 읽지만 스크립트 안에서 하는 일은 상대적으로 비용이 들지 않는다는 내용입니다. 왕복을 줄이는 것이 설계 의도라는 점은 여기서 확인됩니다.

02

활성화 방법과 시작 조건

환경 변수 CLAUDE_CODE_EXPERIMENTAL_CODE_MODE를 1로 설정하고 claude를 시작합니다. 한 번 시험할 때는 셸에 넣고 새 세션마다 켜려면 사용자 설정 ~/.claude/settings.json의 env에 넣습니다. 프로젝트 설정 파일에 넣은 값은 무시됩니다. 내려받은 저장소가 사용자 모르게 Code Mode를 켜지 못하게 막는 동작입니다.

bash
CLAUDE_CODE_EXPERIMENTAL_CODE_MODE=1 claude

처음 실행하면 확인 화면이 나타납니다. 켜지 않고 시작(No, start without it)이 기본 선택이어서 Enter만 누르면 켜지지 않습니다. Code Mode 켜기(Yes, turn on Code Mode)를 고르면 Claude Code가 다시 시작하고 세션 위쪽에 아래 문구가 표시됩니다.

text
Code Mode (experimental) is on · this session can be resumed only with Code Mode on

/status에도 상태가 나옵니다. 필자의 화면에는 Code Mode: on (experimental)과 함께 변수를 셸 환경에서 읽었다는 설명이 표시됐습니다.

요구 사항

공식 문서가 밝힌 요구 사항을 옮겼습니다.

  • 버전: Claude Code v2.1.323 이상
  • 계정: Claude 구독 또는 Console 계정. 게이트웨이, Amazon Bedrock, Claude Platform on AWS, Google Cloud의 Agent Platform, Microsoft Foundry를 거치면 사용할 수 없습니다.
  • 조직: HIPAA 구성이나 무보존(zero data retention)을 사용하지 않는 조직
  • 모델: Claude Opus 5.5, Sonnet 5.5, Haiku 5.5, Fable 5.2
  • 실행 환경: 터미널의 대화형 claude 세션. -p, Agent SDK, VS Code 패널, 데스크톱 앱, 클라우드 세션에서는 동작하지 않습니다.
  • 설치: 네이티브 빌드. Windows에서는 Git for Windows가 필요합니다.
  • 함께 켤 수 없는 설정: API 키 헬퍼, 에이전트 팀, OpenTelemetry 내보내기, DISABLE_TELEMETRY

Code Mode 세션에서는 Remote Control, Claude in Chrome, computer use도 사용할 수 없습니다. 세션을 데스크톱 앱이나 백그라운드 세션으로 옮기지도 못합니다. 백그라운드로 실행되지 않는 코드는 10분이 지나면 멈춥니다.

시작되지 않는 조건을 화면에서 확인

조건이 맞지 않으면 Claude Code는 Code Mode 없이 시작하고 세션 위쪽에 Code Mode (experimental) isn't available과 이유를 표시합니다. 표 2는 프롬프트를 보내지 않고 시작 화면만 확인한 결과입니다.

조건결과화면에 표시된 이유
OpenTelemetry 내보내기 켬 (CLAUDE_CODE_ENABLE_TELEMETRY=1)시작 안 됨OpenTelemetry is on (...), and Code Mode doesn't yet send it an event for each tool call
Amazon Bedrock (CLAUDE_CODE_USE_BEDROCK=1)시작 안 됨for now it only works with the Anthropic API
Sonnet 4.5시작 안 됨for now it only works with Opus 5.5, Sonnet 5.5 and later models
claude -p적용 안 됨문구 없음. 도구 목록에 REPL이 없고 기존 도구로 실행
셸에는 1, --settings에는 0비활성화문구 없음

표 2. 시작 조건 시험 결과. v2.1.325에서 2026년 11월 15일에 확인

필자의 장비는 평소 OpenTelemetry Collector로 사용량을 내보내고 있어서 환경 변수만 넣어서는 켜지지 않았습니다. 사용자 설정은 그대로 두고 --settings로 텔레메트리 변수만 0으로 덮어쓰자 시작됐습니다.

bash
CLAUDE_CODE_EXPERIMENTAL_CODE_MODE=1 claude --settings '{"env":{"CLAUDE_CODE_ENABLE_TELEMETRY":"0"}}'

사용량 수집이 조직의 정책이라면 이 방법을 사용하지 않는 것을 권고합니다. 이렇게 시작한 세션의 사용량은 OpenTelemetry로 나가지 않기 때문입니다.

세션 재개

Code Mode로 시작한 세션은 Code Mode를 켠 터미널에서만 재개됩니다. 변수 없이 claude --resume을 실행하자 세션이 재개되지 않고 종료 코드 1로 끝났습니다. 화면 문구는 This session was started in Code Mode (experimental), which is off, so it can't be resumed.입니다. 일반 세션을 변수를 켠 채 재개하면 기존 도구로 계속 진행합니다.

조직 단위로 막기

관리 설정(managed settings)의 env에 같은 변수를 값 0으로 넣으면 조직의 누구도 Code Mode를 사용하지 못합니다. 문서에 따르면 이미 Code Mode 세션 안에 있는 사용자는 종료하거나 다시 시작할 때까지 그대로 유지됩니다. 그 뒤로는 Code Mode 없이 시작하고 기존 Code Mode 세션도 재개하지 못합니다. 관리 설정으로 사용자의 Code Mode를 켜 주는 방법은 없습니다.

json
{
  "env": {
    "CLAUDE_CODE_EXPERIMENTAL_CODE_MODE": "0"
  }
}

필자는 조직 관리 설정 자체는 시험하지 않았습니다. 설정을 바꾸면 조직 전체에 적용되기 때문입니다. --settings로 넘긴 0이 셸의 1보다 우선한다는 것까지만 확인했습니다.

03

측정 방법

Code Mode는 -p에서 동작하지 않고 OpenTelemetry가 켜져 있으면 시작되지 않습니다. 평소에 사용하던 헤드리스 실행과 OTel 지표를 둘 다 사용할 수 없어서 방법을 바꿨습니다.

대화형 세션은 의사 터미널(PTY)에서 시작하고 터미널 에뮬레이터 라이브러리(pexpect, pyte)로 화면을 읽어 확인 화면과 권한 화면을 넘겼습니다. 토큰은 세션 기록 파일에 남은 응답별 usage를 더해 구했습니다. 두 세션의 실행 옵션은 같고 켠 세션에만 CLAUDE_CODE_EXPERIMENTAL_CODE_MODE=1을 넣었습니다.

bash
claude --session-id <uuid> --setting-sources project,local --strict-mcp-config --model sonnet "<prompt>"
항목값
버전과 모델Claude Code v2.1.325, Sonnet 5.5, effort medium(기본값), 권한 모드 auto
계정Claude 구독 계정. Anthropic API에 직접 연결
구성사용자 설정 제외(플러그인, 훅, MCP 서버 없음), 자동 메모리 끔
실험 프로젝트파일 54개인 Node 프로젝트. 서비스 모듈 20개, Markdown 25개. 정답은 생성 스크립트가 미리 계산
MCP 서버주문, 고객, 상품, 재고, 배송을 조회하는 읽기 전용 도구 9개. 서버가 받은 호출을 파일에 기록
반복작업마다 모드별 3회. 어느 모드를 먼저 실행할지 번갈아 바꿈
총 토큰주 대화의 모든 API 응답에서 입력, 캐시 쓰기, 캐시 읽기, 출력 토큰을 더한 값
비용세션 기록의 totalCostUSD. Claude Code가 계산한 세션 전체 값이며 구독 계정이므로 API 요금 기준 환산치
턴 시간세션 기록의 turn_duration

표 3. 측정 조건. 2026년 11월 15일, Linux aarch64

작업프롬프트 요지성격
T1모든 Markdown 파일에서 존재하지 않는 로컬 파일을 가리키는 링크 찾기(공식 문서의 예시 프롬프트)여러 파일 읽기와 검사
T2서비스 20개의 maxAttempts를 3에서 5로 바꾸고 npm test 실행반복 수정
T3src 아래 할 일 주석을 담당자별로 집계검색 후 집계
T4package.json의 버전 확인호출 한 번인 대조군
T5실패하는 테스트의 원인을 찾아 고치고 통과 확인단계가 서로 의존
M12026년 10월 출고 주문의 매출 합계와 상위 고객 3곳MCP 호출 13회, 여러 도구 조합
M2주문 한 건의 상태와 운송사MCP 호출 2회인 대조군
M3재고가 재주문 기준보다 적은 상품MCP 호출 31회, 상품마다 한 번씩 조회
S1한 세션에서 M2, M3, M1을 차례로 요청여러 턴 세션

표 4. 측정에 사용한 작업. T는 기본 도구, M은 MCP 도구, S는 여러 턴 세션

세션 기록에서 토큰 읽기

세션 기록은 ~/.claude/projects/ 아래에 세션 ID 이름으로 저장되고 한 줄에 JSON 하나씩 쌓입니다. 필자가 v2.1.325의 기록에서 확인한 바로는 requestId가 있는 assistant 줄이 API 응답이고 message.usage에 토큰이 들어 있습니다. 응답 하나가 여러 줄로 나뉘어 기록되므로 message.id로 묶어야 중복으로 세지 않습니다. Code Mode 스크립트 안에서 일어난 도구 호출은 requestId가 없는 줄로 남고 토큰은 0입니다.

python
import json, sys

seen = {}
for line in open(sys.argv[1]):
    try:
        r = json.loads(line)
    except json.JSONDecodeError:
        continue
    # requestId가 없는 줄은 스크립트 안에서 일어난 도구 호출입니다
    if r.get("type") != "assistant" or r.get("isSidechain") or not r.get("requestId"):
        continue
    m = r["message"]
    seen[m["id"]] = m.get("usage", {})   # 한 응답이 여러 줄로 나뉘므로 message.id로 묶습니다

keys = ["input_tokens", "cache_creation_input_tokens", "cache_read_input_tokens", "output_tokens"]
total = {k: sum(u.get(k, 0) for u in seen.values()) for k in keys}
print(len(seen), "API responses", total, "total", sum(total.values()))

이 형식은 문서로 공개된 규격이 아니어서 버전이 바뀌면 달라질 수 있습니다.

04

기본 도구 작업의 결과

30회 모두 정답이었습니다. 표 5의 각 칸은 앞 값이 Code Mode를 끈 세션, 뒤 값이 켠 세션입니다.

작업API 왕복총 토큰총 토큰 변화출력 토큰 변화비용(USD)비용 변화턴 시간(초)
T1 깨진 링크3.0에서 2.0108,433에서 48,185-56%-22%0.0604에서 0.0488-19%11.0에서 11.5
T2 반복 수정3.0에서 3.0107,340에서 71,316-34%-16%0.0480에서 0.0435-9%6.2에서 10.0
T3 할 일 주석 집계2.0에서 2.070,570에서 46,551-34%+30%0.0389에서 0.0369-5%4.4에서 5.4
T4 단일 조회2.0에서 2.070,261에서 45,984-35%-28%0.0322에서 0.0283-12%2.9에서 3.5
T5 버그 수정3.7에서 3.0133,797에서 73,335-45%-28%0.0578에서 0.0488-16%8.6에서 8.8
합계13.7에서 12.0490,401에서 285,372-42%-18%0.2372에서 0.2062-13%

표 5. 기본 도구 작업 5종의 결과. 각 칸은 Code Mode 끔과 켬의 순서이고 작업마다 3회 평균. 비용은 API 요금 기준 환산치

총 토큰은 다섯 작업 모두에서 34% 이상 줄었지만 왕복은 두 작업에서만 줄었습니다.

  • 절감은 대부분 도구 정의에서 나옵니다. 첫 요청의 입력이 켠 세션에서 12.2k 토큰 작고 이 차이가 왕복마다 반복됩니다. T2, T3, T4는 왕복 횟수가 같아서 절감분 전체가 이 차이로 설명됩니다. T1은 절감분의 41%, T5는 61%가 도구 정의 몫이고 나머지가 왕복 감소 몫입니다.
  • 끈 세션도 이미 묶어서 처리합니다. T1에서 끈 세션은 Bash 안에 Python 스크립트를 작성해 파일 25개를 한 번에 검사했고 T2에서는 sed 한 줄로 파일 20개를 고쳤습니다. 켠 세션은 같은 일을 REPL 스크립트 하나로 했습니다. T1의 스크립트는 한 번 실행에 내부 도구 호출이 126회였습니다.
  • 토큰 감소율과 비용 감소율은 다릅니다. 줄어든 205,030 토큰 가운데 204,767 토큰이 캐시 읽기 토큰입니다. 요금표에 따르면 Sonnet 5.5의 캐시 읽기 단가는 기본 입력 단가의 0.05배입니다. 단가가 높은 캐시 쓰기 토큰(약 3.3만)과 출력 토큰은 두 세션이 비슷했습니다. 토큰 42% 절감을 비용 42% 절감으로 옮기면 틀립니다.
  • 빨라지지는 않았습니다. 턴 시간은 같거나 길었습니다. T2는 edit()를 20번 차례로 호출하느라 6.2초에서 10.0초로 늘었습니다.

아래는 T2에서 Claude가 작성한 스크립트입니다. 대상 파일을 찾아 차례로 수정한 뒤 남은 곳이 없는지 확인하고 테스트를 실행합니다. 결과가 모델에게 전달되는 것은 마지막 줄 한 번입니다.

javascript
const files = (await $`grep -rl "maxAttempts: 3," src/services`.text()).trim().split('\n');
for (const f of files) await edit(f, 'maxAttempts: 3,', 'maxAttempts: 5,');
const left = await $`grep -rn "maxAttempts" src/services | grep -v "maxAttempts: 5,"`.nothrow().text();
const t = await $`npm test 2>&1`.nothrow();
({n: files.length, left, code: t.exitCode, out: t.stdout.slice(-2500)})

05

MCP 도구 작업의 결과

18회 모두 정답이었습니다. M3의 4회는 검증 스크립트가 답변의 설명 문장에 나온 상품 ID까지 목록으로 세는 문제가 있었습니다. 검증 스크립트를 고친 뒤 저장해 둔 답변으로 다시 판정했습니다.

작업API 왕복총 토큰총 토큰 변화출력 토큰 변화비용(USD)비용 변화턴 시간(초)
M1 매출 집계 (호출 13회)4.0에서 5.7152,134에서 150,826-1%-26%0.0825에서 0.08220%12.1에서 14.9
M2 단건 조회 (호출 2회)3.0에서 6.7117,766에서 210,486+79%+184%0.0675에서 0.1012+50%4.8에서 14.3
M3 재고 점검 (호출 31회)4.0에서 5.7153,171에서 144,088-6%-57%0.0939에서 0.0716-24%15.6에서 13.3
합계11.0에서 18.0423,072에서 505,400+19%-29%0.2439에서 0.2550+5%

표 6. MCP 도구 작업 3종의 결과. 각 칸은 Code Mode 끔과 켬의 순서이고 작업마다 3회 평균. 비용은 API 요금 기준 환산치

작업 8종의 총 토큰을 Code Mode를 끈 세션과 켠 세션으로 나눠 비교한 막대 그래프. 기본 도구 작업 5종은 34%에서 56% 줄었고 MCP 도구 작업 3종은 6% 감소에서 79% 증가까지 갈렸다
그림 2. 작업별 총 토큰 비교. 기본 도구 작업은 모두 줄었고 MCP 도구 작업은 결과가 갈렸습니다

세 작업 모두 켠 세션의 왕복이 더 많았습니다. Code Mode에서는 MCP 도구가 프롬프트에 없기 때문입니다. MCP 서버를 연결해도 켠 세션의 첫 요청은 17 토큰만 늘었습니다. 끈 세션은 도구 이름 목록이 실려 150 토큰 늘었습니다. MCP 문서에 따르면 끈 세션에서도 도구 검색(tool search)이 기본값이어서 시작할 때는 도구 이름만 실립니다.

그림 3은 호출 2회짜리 작업 M2의 한 실행을 왕복 순서대로 놓은 것입니다. 끈 세션은 ToolSearch 한 번으로 스키마를 받고 두 도구를 한 응답에서 병렬로 호출해 3회 만에 끝났습니다. 켠 세션은 7회가 걸렸습니다.

주문 한 건을 조회하는 작업에서 Code Mode를 끈 세션은 도구 검색, 병렬 호출, 답변의 3회 왕복으로 끝나고 켠 세션은 도구 검색, 목록 확인, 인자 이름 오류, 재호출, 스키마 조회, 배송 조회, 답변의 7회 왕복이 걸리는 과정을 비교한 그림
그림 3. 주문 한 건을 조회하는 작업 M2의 왕복 순서. 실행 한 번의 기록

켠 세션에서 Claude가 차례로 작성한 스크립트 여섯 개입니다. 한 줄이 왕복 한 번입니다.

javascript
// 1. 도구 찾기
const r = await searchTools("acme order status shipment carrier", 10); r
// 2. 도구 목록과 주변 파일 확인
const l = tools.list().filter(n=>/acme|order|ship/i.test(n)); ({l, all: tools.list().length, ls: await $`ls -la; cat .mcp.json 2>/dev/null; ls ~/.claude 2>/dev/null`.nothrow().text()})
// 3. 인자 이름을 추측해 호출. 서버에 보내지 않고 거부됨 ("does not declare `order_id` ... It takes: id")
const o = await tools.mcp__acme__get_order({order_id:"ORD-1017"}); o
// 4. 이름을 고쳐 다시 호출
const o2 = await tools.mcp__acme__get_order({id:"ORD-1017"}); o2
// 5. 다음 도구는 스키마부터 조회
const d = await describeTool('mcp__acme__get_shipment'); d.inputSchema
// 6. 배송 조회
await tools.mcp__acme__get_shipment({orderId:"ORD-1017"})
  • 탐색에 왕복을 사용합니다. 켠 세션은 처음 두세 번의 왕복을 searchTools, tools.list(), describeTool에 사용했습니다. 반환 형태를 몰라 o.items||o.lines||o.lineItems처럼 여러 이름을 대비한 스크립트도 나왔습니다.
  • 끈 세션은 병렬 호출로 왕복을 줄입니다. ToolSearch로 스키마를 받은 뒤 응답 하나에 호출 10개 또는 30개를 담았습니다. 왕복 횟수로는 Code Mode가 유리하지 않았습니다.
  • 유리한 지점은 출력 토큰입니다. 호출이 31회인 M3에서 끈 세션은 도구 호출 블록 30개를 출력해야 해서 출력 토큰이 평균 2,338이었습니다. 켠 세션은 반복문 하나로 끝내 평균 1,011이었습니다. 출력 토큰의 단가가 높아서 왕복이 더 많았는데도 비용이 24% 줄었습니다.
  • 호출이 적으면 탐색 비용만 남습니다. 호출이 2회뿐인 M2는 총 토큰이 79% 늘었습니다.

한 세션에서 이어서 실행하면

도구 탐색 비용이 첫 턴 뒤로 분산되는지 보려고 M2, M3, M1을 한 세션에서 차례로 요청했습니다.

모드정답API 왕복총 토큰출력 토큰비용(USD)실행별 API 왕복
끔2/39.7430,2884,1980.181310, 9, 10
켬3/314.7513,3462,9040.180417, 15, 12
변화+52%+19%-31%0%

표 7. MCP 작업 3개를 한 세션에서 이어서 실행한 결과. 모드별 3회 평균

세 턴으로 늘려도 켠 세션의 왕복과 총 토큰이 더 많았고 비용은 같은 수준이었습니다. 탐색은 첫 턴에 몰리지만 뒤 턴에서도 처음 사용하는 도구는 다시 조회했습니다. 켠 세션은 실행마다 12회에서 17회로 편차가 컸고 끈 세션은 9회에서 10회로 일정했습니다. 끈 세션의 오답 1건은 매출 합계와 상위 고객 3곳을 맞혔지만 고객 이름 대신 고객 ID만 적은 답입니다.

06

권한 규칙과 훅

스크립트 하나가 도구를 수십 번 호출한다면 권한 규칙이 그대로 적용되는지가 중요합니다. 문서에 따르면 Claude의 코드가 하는 도구 호출 하나하나가 deny와 ask 권한 규칙, PreToolUse 훅을 거칩니다. auto 모드에서는 분류기가 도구 호출이 아니라 코드를 실행 전에 검토합니다.

필자는 curl 차단 규칙과 모든 도구 호출을 기록하는 PreToolUse 훅을 걸고 git --version과 curl --version을 실행하게 했습니다.

권한 모드Code Mode를 켠 세션에서 일어난 일
default훅이 REPL 호출(스크립트 원문 포함)과 스크립트 안의 Bash 호출을 모두 받았습니다. 차단 규칙은 스크립트 안의 curl 호출만 거부했고 스크립트는 계속 실행됐습니다. 스크립트 안의 git 호출에는 평소와 같은 승인 화면이 나타났습니다.
auto분류기가 스크립트를 실행 전에 통째로 거부했습니다. git도 실행되지 않았고 훅은 REPL 호출만 받았습니다.

표 8. 권한 모드별 동작. curl 차단 규칙과 PreToolUse 훅을 건 상태

default 모드의 결과는 문서의 설명과 일치합니다. auto 모드의 결과는 1회 관측이고 프롬프트 문구가 default 시험과 조금 달랐으므로 일반화하기는 어렵습니다.

문서에 따르면 auto 모드의 분류기는 검색 결과에서 얻은 경로처럼 실행 중에 계산되는 값을 보지 못합니다. 반드시 통제해야 하는 호출에는 규칙이나 훅을 남겨 둡니다. 스크립트 자체를 검사하려면 REPL에 매칭되는 PreToolUse 훅을 작성하고 tool_input.code에서 JavaScript를 읽습니다.

07

활성화 기준

이번 측정을 근거로 한 필자의 판단입니다. 모델과 작업이 달라지면 결과도 달라질 수 있습니다.

  • 기본 도구 위주의 작업에는 활성화 해 볼 만합니다. 다섯 작업 모두 총 토큰과 비용이 줄었고 정답률은 같았습니다. 속도는 기대하지 않는 편이 맞습니다.
  • MCP 도구를 수십 번 호출하는 반복 작업에서는 출력 토큰이 줄어 비용이 내려갈 가능성이 있습니다. 호출이 가장 많았던 작업 M3에서 비용이 줄었습니다.
  • MCP 도구를 한두 번 호출하는 짧은 조회가 많다면 비활성화 하는 편이 낫습니다. 호출이 가장 적었던 작업 M2에서 총 토큰과 비용이 모두 늘었습니다.
  • Amazon Bedrock, claude -p 자동화, OpenTelemetry로 사용량을 수집하는 환경에서는 지금은 사용할 수 없습니다.

다른 구현의 수치를 옮길 때

Code Mode라는 이름은 다른 도구에서도 사용됩니다. Nuxt MCP Toolkit 문서는 Claude Sonnet 벤치마크(도구 9개, 작업 7개)에서 전체 토큰 15%, 복잡한 배치 작업에서 최대 33% 절감을 보고합니다. 이 기능은 MCP 서버 쪽에 구현한 것이고 문서에 모델 버전, 총 토큰의 정의, 원자료가 없습니다. Claude Code의 기대 절감률로 옮기기는 어렵습니다. 이번 측정에서 도구 9개인 MCP 서버 조건에서는 총 토큰이 늘었습니다.

08

한계

  • 측정한 모델: Code Mode는 Opus 5.5, Sonnet 5.5, Haiku 5.5, Fable 5.2를 지원하지만 이 글은 Sonnet 5.5로만 측정했습니다. 다른 세 모델에서는 호출을 묶는 성향이 달라 결과가 다를 수 있습니다.
  • 반복 횟수: 작업마다 3회입니다. 기본 도구 작업은 실행 간 차이가 거의 없었지만 MCP 작업의 켠 세션은 편차가 컸습니다.
  • 작업 크기: 왕복 2회에서 7회로 끝나는 짧은 작업이고 프로젝트도 파일 54개로 작습니다. 긴 세션, 큰 출력, 오래 실행되는 스크립트는 측정하지 않았습니다.
  • 구성: 플러그인과 MCP 서버를 뺀 구성입니다. 플러그인 40개를 설치한 평소 설정에서는 /context 추정치만 비교했고 시작 컨텍스트가 50.1k에서 35.2k로 줄었습니다.
  • MCP 서버: 도구 9개인 시험용 서버이고 출력 스키마가 없습니다. 출력 스키마가 있으면 탐색 비용이 달라지는지는 확인하지 않았습니다.
  • 비용: Claude Code가 계산한 환산치입니다. 캐시 유지 시간이 1시간이어서 조건마다 첫 실행만 캐시 쓰기 비용을 더 냈고 이 영향은 두 세션에 비슷하게 들어갔습니다.
  • 시험하지 않은 조건: 조직 관리 설정으로 막는 동작, HIPAA와 무보존 조직, API 키 헬퍼, 에이전트 팀, Windows입니다.

마치며

Code Mode가 토큰을 얼마나 줄이는지는 작업이 어떤 도구를 사용하는지에 따라 달랐습니다. 기본 도구만 사용하는 작업에서는 요청에 실리는 도구 정의가 줄어 총 토큰이 줄었습니다. MCP 도구를 사용하는 작업에서는 도구를 찾는 왕복이 더해져 총 토큰이 늘었습니다. 비용 변화는 두 경우 모두 토큰 변화보다 작았습니다.

왕복을 줄인다는 설계 의도는 분명하지만 Code Mode를 끈 세션도 셸 한 줄과 병렬 호출로 이미 왕복을 줄이고 있습니다. 필자의 측정에서 차이를 만든 것은 왕복 횟수보다 요청마다 실리는 도구 정의의 크기였습니다. 자신의 작업에서 켜기 전에 세션 기록으로 두 모드의 토큰을 직접 비교해 보는 것을 권고합니다.

Introduction

Claude Code v2.1.323 added Code Mode. It was published to npm on November 12, 2026. The changelog introduces it as an experimental opt-in in which Claude writes JavaScript to call its tools.

The approach aims to cut two things: round trips and tool definitions. When several tool calls are packed into one piece of code, the model is consulted fewer times, and fewer tool definitions ride along with each request. To see how large the effect is, I ran the same tasks in sessions with Code Mode off and on and compared tokens, cost, and round trips. The version was v2.1.325, the model was Sonnet 5.5, and there were 54 measured runs.

Code Mode is experimental and disabled by default. The official documentation gives notice that it may change or be removed in any release. The numbers in this post were measured on November 15, 2026 with v2.1.325.

01

What Code Mode changes

According to the official documentation, without Code Mode Claude asks for tool calls such as Bash, Read, or Edit directly and reads each result before it decides what to do next. With Code Mode, Claude writes JavaScript that makes the tool calls, and Claude Code runs that code in the session. One piece of code can run commands in parallel, pass one result to the next call, and return only the part that Claude needs to read.

The example below is from the official documentation. Asked to raise a retry limit, Claude writes code that finds the file, edits it, and runs the tests. The last line returns the path of the edited file and the test output to Claude.

javascript
const files = await $`rg -l "function retryPolicy" src`.text();
const target = files.trim().split("\n")[0];
await edit(target, "maxAttempts: 3", "maxAttempts: 5");
({ edited: target, tests: $`npm test -- retryPolicy`.nothrow() });

The conversation shows the tool calls, such as the diff of an edit, in place of the code. To read the code, press Ctrl+O to open the transcript viewer and expand a collapsed Code row.

What changes in the API request

Claude Code records the shape of each request it sends to the API in the session transcript. I compared the transcripts of a session with Code Mode off and a session with it on, in the same project.

Side by side: a session with Code Mode off sends 16 tool definitions with every request and goes back to the model after each tool result, and a session with Code Mode on sends 3 tools while one script calls several tools and returns only the needed result
Figure 1. Request shape in sessions with Code Mode off and on
ItemCode Mode offCode Mode on
Tools in the API request163 (REPL, Poll, advisor)
Size of the tool definitions74,886 characters36,392 characters, of which the REPL description is 32,392
Input tokens of the first request35.0k22.8k
System tools estimate in /context21.9k6.1k
With 9 MCP tools connectedNames only at first, then 26 tools after ToolSearch loads the schemasStill 3

Table 1. API requests in sessions with Code Mode off and on. v2.1.325, Sonnet 5.5, plugins and MCP servers removed

A session with Code Mode off can also put several tool calls into one reply. Each request resends the tool definitions and the conversation so far, but that part is read from the prompt cache and billed at a low rate. These two points are why the measured results differed from what I expected. I covered how each request resends its prefix and how the cache relates to that in Optimizing Claude Code token costs, Part 1.

What the single REPL tool holds

The code Claude writes runs through a tool named REPL. There are fewer tools, but the existing ones are not gone. The REPL description holds TypeScript signatures of 15 tools, including Bash, Read, Edit, Write, Glob, Grep, and Agent. Twenty less used built-in tools are listed by name only, and describeTool(name) returns their schemas. MCP tools are not listed even by name, and the description says to find them with searchTools.

The description also tells the model the cost structure directly. Each REPL call is a model round trip that rereads the whole conversation, while the work inside a script costs comparatively little. This confirms that fewer round trips is the design intent.

02

Enabling it, and what it needs

Set the environment variable CLAUDE_CODE_EXPERIMENTAL_CODE_MODE to 1 and start claude. To try it once, set it in the shell. To turn it on for every new session, put it in env in the user settings file ~/.claude/settings.json. A value in a project settings file is ignored. This keeps a repository you cloned from turning on Code Mode without your knowing.

bash
CLAUDE_CODE_EXPERIMENTAL_CODE_MODE=1 claude

The first run shows a confirmation screen. The default choice is "No, start without it", so pressing Enter alone does not turn it on. If you select "Yes, turn on Code Mode", Claude Code restarts and shows the line below near the top of the session.

text
Code Mode (experimental) is on · this session can be resumed only with Code Mode on

/status shows the state too. On my screen it showed Code Mode: on (experimental) together with a note that the variable was read from the shell environment.

Requirements

These are the requirements stated in the official documentation.

  • Version: Claude Code v2.1.323 or later
  • Account: a Claude subscription or Console account. It cannot be used through a gateway, Amazon Bedrock, Claude Platform on AWS, Google Cloud's Agent Platform, or Microsoft Foundry.
  • Organization: an organization that does not use the HIPAA configuration or zero data retention
  • Model: Claude Opus 5.5, Sonnet 5.5, Haiku 5.5, or Fable 5.2
  • Surface: an interactive claude session in a terminal. It does not work with -p, the Agent SDK, the VS Code panel, the Desktop app, or cloud sessions.
  • Installation: the native build. On Windows, Git for Windows is required.
  • Settings that cannot be on at the same time: an API key helper, agent teams, OpenTelemetry export, DISABLE_TELEMETRY

A Code Mode session also cannot use Remote Control, Claude in Chrome, or computer use. The session cannot be moved to the Desktop app or turned into a background session. Code that does not run in the background stops after ten minutes.

Checking on screen when it does not start

When a condition is not met, Claude Code starts without Code Mode and shows Code Mode (experimental) isn't available with the reason near the top of the session. Table 2 lists what the start screen showed, with no prompt sent.

ConditionResultReason shown on screen
OpenTelemetry export on (CLAUDE_CODE_ENABLE_TELEMETRY=1)Does not startOpenTelemetry is on (...), and Code Mode doesn't yet send it an event for each tool call
Amazon Bedrock (CLAUDE_CODE_USE_BEDROCK=1)Does not startfor now it only works with the Anthropic API
Sonnet 4.5Does not startfor now it only works with Opus 5.5, Sonnet 5.5 and later models
claude -pNot appliedNo message. The tool list has no REPL, and the run uses the ordinary tools
1 in the shell, 0 in --settingsDisabledNo message

Table 2. Start conditions tested. Checked on November 15, 2026 with v2.1.325

My machine normally exports usage to an OpenTelemetry Collector, so setting the environment variable alone did not turn Code Mode on. It started once I left the user settings as they were and overrode only the telemetry variable to 0 with --settings.

bash
CLAUDE_CODE_EXPERIMENTAL_CODE_MODE=1 claude --settings '{"env":{"CLAUDE_CODE_ENABLE_TELEMETRY":"0"}}'

If collecting usage is your organization's policy, I recommend not using this method. The usage of a session started this way is not sent to OpenTelemetry.

Resuming a session

A session started in Code Mode resumes only in a terminal with Code Mode on. When I ran claude --resume without the variable, the session did not resume and the command exited with code 1. The message was This session was started in Code Mode (experimental), which is off, so it can't be resumed. An ordinary session resumed with the variable set continues with the ordinary tools.

Blocking it for an organization

Putting the same variable with the value 0 in env of the managed settings keeps everyone in the organization from using Code Mode. According to the documentation, users who are already in a Code Mode session stay in it until they exit or restart. After that they start without Code Mode and cannot resume their Code Mode sessions. Managed settings cannot turn Code Mode on for users.

json
{
  "env": {
    "CLAUDE_CODE_EXPERIMENTAL_CODE_MODE": "0"
  }
}

I did not test the organization's managed settings themselves, because a change there applies to the whole organization. I only confirmed that a 0 passed with --settings wins over a 1 in the shell.

03

How I measured

Code Mode does not work with -p and does not start while OpenTelemetry is on. Neither headless runs nor OTel metrics, my usual tools, were available, so I changed the method.

I started each interactive session in a pseudo-terminal (PTY) and read the screen with terminal emulation libraries (pexpect, pyte) to get past the confirmation and permission screens. Tokens came from adding up the usage of each response in the session transcript. Both sessions used the same launch options, and only the session with Code Mode on had CLAUDE_CODE_EXPERIMENTAL_CODE_MODE=1.

bash
claude --session-id <uuid> --setting-sources project,local --strict-mcp-config --model sonnet "<prompt>"
ItemValue
Version and modelClaude Code v2.1.325, Sonnet 5.5, effort medium (the default), permission mode auto
AccountA Claude subscription account, connected directly to the Anthropic API
ConfigurationUser settings left out (no plugins, hooks, or MCP servers), auto memory off
Test projectA Node project of 54 files: 20 service modules and 25 Markdown files. A generator script computed the right answers in advance
MCP serverNine read-only tools that look up orders, customers, products, inventory, and shipments. The server logs each call it receives to a file
RepetitionsThree runs per task and mode, alternating which mode runs first
Total tokensInput, cache write, cache read, and output tokens added over every API response of the main conversation
CosttotalCostUSD in the session transcript. It is the whole-session value computed by Claude Code, and since this is a subscription account it is an API-price equivalent
Turn timeturn_duration in the session transcript

Table 3. Measurement conditions. November 15, 2026, Linux aarch64

TaskPrompt in briefKind
T1Find links in every Markdown file that point to local files that do not exist (the example prompt in the official documentation)Reading and checking many files
T2Change maxAttempts from 3 to 5 in 20 services and run npm testRepeated edit
T3Count the to-do comments under src per ownerSearch, then aggregate
T4Read the version in package.jsonControl with a single call
T5Find why a test fails, fix it, and confirm it passesSteps that depend on each other
M1Total revenue of orders shipped in October 2026 and the top three customers13 MCP calls across several tools
M2The status and the carrier of one orderControl with 2 MCP calls
M3Products with inventory below their reorder level31 MCP calls, one lookup per product
S1M2, M3, and M1 asked in turn in one sessionMulti-turn session

Table 4. Tasks used. T uses built-in tools, M uses MCP tools, S is a multi-turn session

Reading tokens from the session transcript

A session transcript is stored under ~/.claude/projects/ in a file named after the session ID, one JSON object per line. From what I saw in v2.1.325 transcripts, an assistant line with a requestId is an API response, and message.usage holds its tokens. One response is written across several lines, so group by message.id to avoid counting it twice. A tool call made inside a Code Mode script is written as a line without a requestId, with zero tokens.

python
import json, sys

seen = {}
for line in open(sys.argv[1]):
    try:
        r = json.loads(line)
    except json.JSONDecodeError:
        continue
    # a line without a requestId is a tool call made inside a script
    if r.get("type") != "assistant" or r.get("isSidechain") or not r.get("requestId"):
        continue
    m = r["message"]
    seen[m["id"]] = m.get("usage", {})   # one response spans several lines, so group by message.id

keys = ["input_tokens", "cache_creation_input_tokens", "cache_read_input_tokens", "output_tokens"]
total = {k: sum(u.get(k, 0) for u in seen.values()) for k in keys}
print(len(seen), "API responses", total, "total", sum(total.values()))

This format is not a documented specification, so it can change between versions.

04

Results for tasks on built-in tools

All 30 runs gave the right answer. In each cell of Table 5, the first value is the session with Code Mode off and the second is the session with it on.

TaskAPI round tripsTotal tokensTotal token changeOutput token changeCost (USD)Cost changeTurn time (s)
T1 Broken links3.0 to 2.0108,433 to 48,185-56%-22%0.0604 to 0.0488-19%11.0 to 11.5
T2 Bulk edit3.0 to 3.0107,340 to 71,316-34%-16%0.0480 to 0.0435-9%6.2 to 10.0
T3 To-do report2.0 to 2.070,570 to 46,551-34%+30%0.0389 to 0.0369-5%4.4 to 5.4
T4 Single read2.0 to 2.070,261 to 45,984-35%-28%0.0322 to 0.0283-12%2.9 to 3.5
T5 Bug fix3.7 to 3.0133,797 to 73,335-45%-28%0.0578 to 0.0488-16%8.6 to 8.8
Total13.7 to 12.0490,401 to 285,372-42%-18%0.2372 to 0.2062-13%

Table 5. Results for the five tasks on built-in tools. Each cell reads Code Mode off, then on, as the mean of three runs per task. Cost is the API-price equivalent

Total tokens fell by 34% or more on all five tasks, but round trips fell on only two.

  • Most of the saving comes from the tool definitions. The first request's input is 12.2k tokens smaller in the session with Code Mode on, and that difference repeats on every round trip. T2, T3, and T4 had the same number of round trips, so this difference explains their whole saving. For T1 the tool definitions account for 41% of the saving and for T5 61%, and fewer round trips account for the rest.
  • The session with Code Mode off already batches. On T1 it wrote a Python script inside Bash and checked 25 files in one go, and on T2 it fixed 20 files with one sed line. The session with Code Mode on did the same work with one REPL script. The T1 script made 126 inner tool calls in a single run.
  • The token saving and the cost saving are different numbers. Of the 205,030 tokens saved, 204,767 were cache read tokens. According to the pricing table, a cache read on Sonnet 5.5 costs 0.05 times the base input price. Cache write tokens (about 33k) and output tokens, which are priced higher, were similar in both sessions. Turning a 42% token saving into a 42% cost saving is wrong.
  • It was not faster. Turn time was the same or longer. T2 went from 6.2 to 10.0 seconds because it called edit() 20 times in sequence.

Below is the script Claude wrote for T2. It finds the target files, edits them one by one, checks that none is left, and runs the tests. The result reaches the model once, in the last line.

javascript
const files = (await $`grep -rl "maxAttempts: 3," src/services`.text()).trim().split('\n');
for (const f of files) await edit(f, 'maxAttempts: 3,', 'maxAttempts: 5,');
const left = await $`grep -rn "maxAttempts" src/services | grep -v "maxAttempts: 5,"`.nothrow().text();
const t = await $`npm test 2>&1`.nothrow();
({n: files.length, left, code: t.exitCode, out: t.stdout.slice(-2500)})

05

Results for tasks on MCP tools

All 18 runs gave the right answer. For four runs of M3, the checking script also counted product IDs that the answer mentioned in its explanatory sentences. I fixed the checking script and judged those runs again from the saved answers.

TaskAPI round tripsTotal tokensTotal token changeOutput token changeCost (USD)Cost changeTurn time (s)
M1 Revenue (13 calls)4.0 to 5.7152,134 to 150,826-1%-26%0.0825 to 0.08220%12.1 to 14.9
M2 Order lookup (2 calls)3.0 to 6.7117,766 to 210,486+79%+184%0.0675 to 0.1012+50%4.8 to 14.3
M3 Low stock (31 calls)4.0 to 5.7153,171 to 144,088-6%-57%0.0939 to 0.0716-24%15.6 to 13.3
Total11.0 to 18.0423,072 to 505,400+19%-29%0.2439 to 0.2550+5%

Table 6. Results for the three tasks on MCP tools. Each cell reads Code Mode off, then on, as the mean of three runs per task. Cost is the API-price equivalent

Bar chart of total tokens for eight tasks in sessions with Code Mode off and on. The five tasks on built-in tools used 34% to 56% fewer tokens, and the three tasks on MCP tools ranged from 6% fewer to 79% more
Figure 2. Total tokens per task. Every task on built-in tools used fewer tokens, and the tasks on MCP tools went both ways

On all three tasks the session with Code Mode on made more round trips. The reason is that MCP tools are not in the prompt in Code Mode. With the MCP server connected, the first request of the session with Code Mode on grew by only 17 tokens. The session with it off grew by 150 tokens for the list of tool names. According to the MCP documentation, tool search is the default in that session as well, so only tool names load at the start.

Figure 3 lays out one run of M2, the task with two calls, in round-trip order. The session with Code Mode off got the schemas with one ToolSearch, called the two tools in parallel in one reply, and finished in 3 round trips. The session with Code Mode on took 7.

For a task that looks up one order, a session with Code Mode off finishes in 3 round trips: tool search, parallel calls, answer. A session with Code Mode on takes 7: tool search, listing tools, a call refused for a wrong argument name, a second call, a schema lookup, the shipment lookup, answer
Figure 3. Round trips of task M2, which looks up one order. The record of a single run

These are the six scripts Claude wrote in turn in the session with Code Mode on. Each line is one round trip.

javascript
// 1. find the tools
const r = await searchTools("acme order status shipment carrier", 10); r
// 2. list the tools and look at nearby files
const l = tools.list().filter(n=>/acme|order|ship/i.test(n)); ({l, all: tools.list().length, ls: await $`ls -la; cat .mcp.json 2>/dev/null; ls ~/.claude 2>/dev/null`.nothrow().text()})
// 3. call with a guessed argument name. Refused without being sent to the server ("does not declare `order_id` ... It takes: id")
const o = await tools.mcp__acme__get_order({order_id:"ORD-1017"}); o
// 4. call again with the right name
const o2 = await tools.mcp__acme__get_order({id:"ORD-1017"}); o2
// 5. read the schema of the next tool first
const d = await describeTool('mcp__acme__get_shipment'); d.inputSchema
// 6. shipment lookup
await tools.mcp__acme__get_shipment({orderId:"ORD-1017"})
  • Round trips go to discovery. The session with Code Mode on spent its first two or three round trips on searchTools, tools.list(), and describeTool. Not knowing the shape of a result, it also wrote scripts that allowed for several names, such as o.items||o.lines||o.lineItems.
  • The session with Code Mode off saves round trips with parallel calls. After ToolSearch returned the schemas, it put 10 or 30 calls into one reply. Counted in round trips, Code Mode had no advantage.
  • The advantage is in output tokens. On M3, with 31 calls, the session with Code Mode off had to write out 30 tool call blocks, so its output averaged 2,338 tokens. The session with Code Mode on finished with one loop and averaged 1,011. Output tokens are priced high, so cost fell 24% even with more round trips.
  • With few calls, only the discovery cost is left. M2, with just two calls, used 79% more total tokens.

Running the tasks one after another in one session

To see whether the discovery cost spreads out after the first turn, I asked for M2, M3, and M1 in turn in one session.

ModeCorrectAPI round tripsTotal tokensOutput tokensCost (USD)API round trips per run
Off2/39.7430,2884,1980.181310, 9, 10
On3/314.7513,3462,9040.180417, 15, 12
Change+52%+19%-31%0%

Table 7. Three MCP tasks run one after another in one session. Mean of three runs per mode

Even over three turns, the session with Code Mode on made more round trips and used more total tokens, and cost was about the same. Discovery is concentrated in the first turn, but in later turns the session looked up any tool it used for the first time again. The session with Code Mode on varied from 12 to 17 round trips between runs, and the session with it off stayed at 9 to 10. The one wrong answer in the session with Code Mode off had the right revenue total and the right top three customers, but gave customer IDs in place of customer names.

06

Permission rules and hooks

If one script calls tools dozens of times, it matters whether the permission rules still apply. According to the documentation, each tool call that Claude's code makes goes through the deny and ask permission rules and the PreToolUse hooks. In auto mode the classifier reviews the code before it runs, not each tool call.

I set a deny rule for curl and a PreToolUse hook that logs every tool call, then had Claude run git --version and curl --version.

Permission modeWhat happened in the session with Code Mode on
defaultThe hook received the REPL call (with the script text) and the Bash calls inside the script. The deny rule refused only the curl call inside the script, and the script kept running. The git call inside the script raised the usual approval prompt.
autoThe classifier refused the whole script before it ran. git did not run either, and the hook received only the REPL call.

Table 8. Behavior by permission mode, with a curl deny rule and a PreToolUse hook in place

The result in default mode matches the documentation. The result in auto mode is a single observation, and its prompt wording differed slightly from the default-mode test, so it is hard to generalize.

According to the documentation, the auto mode classifier does not see values computed at run time, such as a path taken from search output. Keep rules or hooks for the calls you must control. To check the script itself, write a PreToolUse hook that matches REPL and read the JavaScript from tool_input.code.

07

When to enable it

This is my judgment from these measurements. A different model or different tasks can give different results.

  • Work that is mostly built-in tools is worth enabling Code Mode for. On all five tasks total tokens and cost fell, with the same share of right answers. Do not expect it to be faster.
  • Repetitive work that calls MCP tools dozens of times may cost less because output tokens fall. On M3, the task with the most calls, cost fell.
  • If you mostly do short lookups that call an MCP tool once or twice, leaving it disabled is better. On M2, the task with the fewest calls, both total tokens and cost rose.
  • With Amazon Bedrock, claude -p automation, or usage collected through OpenTelemetry, it cannot be used for now.

Carrying over numbers from another implementation

The name Code Mode is used by other tools too. The Nuxt MCP Toolkit documentation reports that a Claude Sonnet benchmark (9 tools, 7 tasks) saved 15% of total tokens overall and up to 33% on complex batch operations. That feature is implemented on the MCP server side, and the documentation does not give the model version, the definition of total tokens, or the raw data. It is hard to carry those numbers over as the saving to expect from Claude Code. In my measurement, the condition with a 9-tool MCP server ended with more total tokens.

08

Limitations

  • Model measured: Code Mode supports Opus 5.5, Sonnet 5.5, Haiku 5.5, and Fable 5.2, but this post measured only Sonnet 5.5. The other three models may batch calls differently, so their results may differ.
  • Repetitions: three per task. Runs of the tasks on built-in tools barely differed, but the session with Code Mode on varied widely on the MCP tasks.
  • Task size: short tasks that end in 2 to 7 round trips, in a small project of 54 files. I did not measure long sessions, large outputs, or long-running scripts.
  • Configuration: plugins and MCP servers were removed. With my usual settings, which have 40 plugins installed, I compared only the /context estimates, and the starting context went from 50.1k to 35.2k.
  • MCP server: a 9-tool test server with no output schemas. I did not check whether output schemas change the discovery cost.
  • Cost: an equivalent computed by Claude Code. The cache lifetime was one hour, so only the first run of each condition paid more for cache writes, and this affected both sessions about equally.
  • Conditions not tested: blocking through the organization's managed settings, HIPAA and zero data retention organizations, an API key helper, agent teams, and Windows.

Conclusion

How many tokens Code Mode saves depended on which tools the task used. On tasks that use only built-in tools, total tokens fell because each request carries fewer tool definitions. On tasks that use MCP tools, the round trips spent finding tools added up to more total tokens. In both cases cost changed less than tokens did.

The design intent of fewer round trips is clear, but a session with Code Mode off already cuts round trips with one shell line and with parallel calls. In my measurement, what made the difference was the size of the tool definitions carried by each request more than the number of round trips. Before you turn it on for your own work, I recommend comparing the tokens of the two modes yourself from the session transcripts.

참고 자료References

No.출처Source종류Kind확인한 날Checked
1Run tool calls from code with Code Mode - Claude Code Docs공식 문서Official docs2026-11-16
2Connect Claude Code to tools via MCP - Claude Code Docs공식 문서Official docs2026-11-16
3Prompt caching - Claude Platform Docs공식 문서Official docs2026-11-16
4Claude Code CHANGELOG - anthropics/claude-codeChangelogChangelog2026-11-16
5@anthropic-ai/claude-code - npm (버전별 게시일)패키지 저장소Package registry2026-11-16
6Code Mode - Nuxt MCP Toolkit외부 문서Third-party docs2026-11-16