Introduction
Claude Code is Anthropic’s official AI coding CLI. At the time of writing, I considered its coding capabilities the strongest available. Its strict access restrictions make it difficult for users in mainland China. Here’s how to configure Claude Code and use it domestically by replacing the default model.
Official site: https://www.anthropic.com/claude-code
Installing Claude Code
1. Install Node.js
Required version: 18 or higher.
# 下载安装 nvm
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.3/install.sh | bash
# 加载 nvm(或重启终端)
\. "$HOME/.nvm/nvm.sh"
# 安装 Node.js 18
nvm install 18
# 验证版本
node -v # 应显示 v18.x.x
npm -v # 应显示 10.x.x
2. Install Claude Code
npm install -g @anthropic-ai/claude-code
Using the official API
If you have an official Anthropic API key, set the environment variable directly:
# 添加到 ~/.zshrc 或 ~/.bashrc
export ANTHROPIC_API_KEY=your_api_key
Replacing the default model for use in mainland China
Because the official API is heavily restricted in mainland China, you can replace the default model with a third-party service compatible with the Anthropic API.
An example using Moonshot AI’s Kimi K2
-
Obtain an API key from Moonshot’s developer console: https://platform.moonshot.cn/console/api-keys
-
Mark the initial Claude Code onboarding as complete.
On first launch, some versions of Claude Code enter an onboarding flow with login options even if a third-party API is configured. The following marks initial onboarding as complete. Actual requests still require valid credentials for the third-party service. It doesn’t bypass API authentication or guarantee that every interactive prompt disappears. The official repository’s issue #4714 documents this behavior and workaround.
Edit ~/.claude.json and add the field:
{
"hasCompletedOnboarding": true
}
Or set it from the command line:
# 方式一:文件不存在时使用
echo '{"hasCompletedOnboarding": true}' > ~/.claude.json
# 方式二(推荐):使用 Python 一键设置
python3 -c "import json,os;p=os.path.expanduser('~/.claude.json');d=json.load(open(p)) if os.path.exists(p) else {};d['hasCompletedOnboarding']=True;json.dump(d,open(p,'w'),indent=2)"
📓 Note: I recommend the Python approach because it preserves the file’s existing settings. The echo approach overwrites the entire file.
- Configure the custom API provider.
Edit ~/.claude/settings.json and add the following settings:
{
"env": {
"ANTHROPIC_BASE_URL": "https://api.moonshot.cn/anthropic/",
"ANTHROPIC_API_KEY": "your_moonshot_api_key"
},
"model": "kimi-k2"
}
📓 Note: Replace
your_moonshot_api_keywith the API key from Moonshot’s console. Setmodelto a name supported by the provider.
Kimi rate limits
Moonshot applies relatively strict limits to free accounts:
| Account type | RPM (requests per minute) | TPM (tokens per minute) |
|---|---|---|
| Free | 3 | 32,000 |
| Paid | Higher | Higher |
Although signup included 15 yuan in credit, a free account could make at most three requests per minute and use no more than 32,000 tokens per minute. That’s tight for a tool like Claude Code that interacts frequently.
My suggestion: If you plan to use it heavily, topping up 50 yuan should make it a much smoother experience.
Starting the tool
cd your_project
claude
Installing Claude Code and connecting a third-party model automatically in a dev container
Once manual configuration worked, I wanted the steps in the project. Creating a dev container should install Claude Code and mark onboarding complete so I don’t have to repeat the work on every rebuild. The example keeps my combination of Python, Node.js, uv, and Spec Kit, and moves the long command formerly squeezed into postCreateCommand into a separate script.
I added this section on November 13, 2026, based on the supplied configuration. The article’s archive date does not mean the example had already been verified then. It retains the npm installation method. Verify specific versions and provider settings in your own environment.
1. Put the configuration in the project’s .devcontainer directory
Create two files at the root of the project:
your-project/
└── .devcontainer/
├── devcontainer.json
└── post-create.sh
.devcontainer/devcontainer.json:
{
"name": "Python 3 + Claude Code",
"image": "mcr.microsoft.com/devcontainers/python:2-3.14-trixie",
"features": {
"ghcr.io/devcontainers/features/node:1": {}
},
"remoteUser": "vscode",
"remoteEnv": {
"PATH": "/home/vscode/.local/bin:${containerEnv:PATH}",
"ANTHROPIC_BASE_URL": "${localEnv:ANTHROPIC_BASE_URL}",
"ANTHROPIC_API_KEY": "${localEnv:ANTHROPIC_API_KEY}",
"ANTHROPIC_MODEL": "${localEnv:ANTHROPIC_MODEL}"
},
"postCreateCommand": "bash .devcontainer/post-create.sh"
}
The Python image provides the base environment, and the Node Feature supplies the toolchain for installing packages with npm. Keep the comma after the features object before the remaining configuration. The example explicitly uses the image’s vscode user, so the ~/.claude.json written by the script belongs to the same account that subsequently runs Claude Code in the terminal.
remoteEnv passes the host’s API endpoint, key, and model name to the VS Code container terminal, tasks, and other child processes. It does not set environment variables for the entire container. The example adds the user tools directory to PATH so the terminal can find uv and Specify CLI. ${localEnv:...} reads host environment variables. It does not automatically load a project .env file. VS Code environment variable documentation
2. Use a script for installation and first-run preparation
.devcontainer/post-create.sh:
#!/usr/bin/env bash
set -euo pipefail
# 安装 Claude Code;沿用这份配置中的 npm 安装方式。
npm install -g @anthropic-ai/claude-code
# 保留已有配置,只更新首次引导完成标记。
python3 - <<'PY'
import json
from pathlib import Path
path = Path.home() / ".claude.json"
data = json.loads(path.read_text(encoding="utf-8")) if path.exists() else {}
if not isinstance(data, dict):
raise SystemExit("~/.claude.json 必须是 JSON 对象,请先检查已有文件")
data["hasCompletedOnboarding"] = True
path.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
PY
# 可选:我的 Python / Spec Kit 工具组合。
# 只需要 Claude Code 时,可以删掉以下三行。
curl -LsSf https://astral.sh/uv/install.sh | sh
export PATH="$HOME/.local/bin:$PATH"
uv tool install specify-cli --from git+https://github.com/github/spec-kit.git
Calling the script with bash eliminates the need to set its executable permission. set -euo pipefail stops execution if an installation or configuration step fails, making the creation log easier to diagnose. The Python snippet can run repeatedly while preserving other configuration fields. If an existing file is invalid JSON it stops with an error rather than overwriting the damaged file as though it were empty.
hasCompletedOnboarding addresses first-run behavior and needs to be checked against the Claude Code version. It is not a stable public unattended interface. Project trust, tool permissions, and API authentication remain separate. First-run issue report
uv and Spec Kit are tools I chose for development. They are not Claude Code dependencies. I’ve kept the installation of Specify CLI from its Git repository here. This installs only the CLI and does not initialize Spec Kit files in the project. See the official uv instructions and Spec Kit repository.
3. Pass the third-party API configuration from the host environment
The JSON above contains variable names, not real keys. In Bash on the host, set the provider’s Anthropic-compatible endpoint and model identifier, then enter the key:
export ANTHROPIC_BASE_URL="https://your-provider.example/anthropic"
export ANTHROPIC_MODEL="your-provider-model-id"
read -r -s -p "第三方 API Key: " ANTHROPIC_API_KEY
printf '\n'
export ANTHROPIC_API_KEY
# 在这个终端进入项目后启动 VS Code。
code .
The address and model name are placeholders. Replace both. This example assumes the provider accepts ANTHROPIC_API_KEY. If it expects a bearer token, follow its documentation and use ANTHROPIC_AUTH_TOKEN, updating the host variable and matching remoteEnv entry. An endpoint providing only the OpenAI format also needs a protocol adapter. Changing the address alone is insufficient. Claude Code gateway guide, environment variable reference
Make sure the VS Code process launching Dev Containers can read those variables. If VS Code is already running, code . may reuse its old process. Quit it entirely and relaunch from the terminal where you set the variables. The key stays in the local environment and the two project configuration files can be committed.
Since this example passes the connection details through environment variables, there’s no need to write the same keys into the container’s ~/.claude/settings.json. When reusing an existing Claude configuration, check for old endpoints, authentication variables, or model settings so the two providers’ configurations don’t get mixed.
4. Create, verify, and rebuild
Run Dev Containers: Reopen in Container in VS Code, wait for creation and installation to finish, then check in the container terminal:
claude --version
uv --version
specify --help
# 只检查变量是否存在,不打印密钥。
python3 - <<'PY'
import os
for name in ("ANTHROPIC_BASE_URL", "ANTHROPIC_API_KEY", "ANTHROPIC_MODEL"):
print(f"{name}: {'已设置' if os.environ.get(name) else '未设置'}")
PY
claude
If you omitted the optional tools, skip the uv and Specify checks too. A variable’s presence doesn’t prove protocol compatibility. Send a short request after opening Claude Code and verify the actual model and provider authentication.
postCreateCommand runs when the container is created, not on an ordinary restart. Rebuilding runs the installation and writes the marker again. After changing container configuration, run Dev Containers: Rebuild Container. To retry just the script in the current container, run bash .devcontainer/post-create.sh from the project root. Dev Container lifecycle specification
This example does not mount the Claude user directory. A rebuild can regenerate the onboarding marker but won’t preserve the previous container’s session history or other personal settings. The npm package, Node Feature default version, uv installer, and Spec Kit’s default Git branch can all change. The setup repeats installation steps without guaranteeing the same software versions. For stable team use, pin tested versions before considering a prebuilt image.
For host-side Podman, VS Code, and proxy settings, see Mac development environment setup notes. To preinstall tools in a shared image, continue with Building cross-platform dev container images with GitHub Actions.
Configuration files
~/.claude.json
User-level state and configuration, including first-run status:
| Field | Description |
|---|---|
hasCompletedOnboarding | Marks initial onboarding complete. API authentication still applies. Verify behavior for the version in use |
~/.claude/settings.json
Claude Code settings:
| Field | Description |
|---|---|
env.ANTHROPIC_API_KEY | API key |
env.ANTHROPIC_BASE_URL | API base URL for the alternate model service |
model | Name of the model to use |
Things to keep in mind
-
Concurrency limits: Some third-party APIs cap concurrency. A paid tier with a higher cap may be necessary for smooth use.
-
Differences in use: The programming ability of a third-party model may fall short of native Claude, but the author reports avoiding domestic-use account suspensions with this route.
-
Price: Third-party services tend to be cheaper.
-
How it works: Claude Code itself is an AI agent framework with many coding workflows and tools. We replace only the LLM that makes decisions. The other workflows still use Claude Code’s implementations.
Common questions
The API key is reported as invalid. What should I check?
Check that the configuration file is correct:
cat ~/.claude/settings.json
Verify both ANTHROPIC_API_KEY and ANTHROPIC_BASE_URL.
The connection times out. What should I check?
- Check connectivity.
- Verify the
ANTHROPIC_BASE_URLaddress. - Some services may require a proxy.
How do I switch back to the official API?
Remove the env configuration in ~/.claude/settings.json, or remove ANTHROPIC_BASE_URL and use an official API key.
What does 429 Too Many Requests mean?
The API provider’s rate limit has been exceeded.
Common causes:
- Requests too frequent: Too many API calls in a short period.
- Token limit exceeded: A single request or cumulative usage crossed the threshold.
- Growing conversations: Long chat history caused excessive token use.
- Insufficient balance: Credit for the paid service ran out.
Possible fixes:
- Wait and retry: Pause for a few minutes. Rate limits usually reset fairly quickly.
- Shorten the request: Reduce prompt length or start a new conversation.
- Top up or upgrade: Add credit in Moonshot’s console to raise the rate limit.
- Use exponential backoff: Developers can automatically retry in code, gradually increasing the delay between attempts.
References
- 杰森写代码. (2025, July 12). 国内终于能用 Claude Code,我用 Kimi K2 替换了 Claude Code 默认模型 [Blog post on replacing Claude Code’s default model with Kimi K2]. 稀土掘金. https://juejin.cn/post/7525733315133177866
- Official Claude Code documentation: https://docs.anthropic.com/claude-code
- Moonshot developer platform: https://platform.moonshot.cn