Terminal AI Coding Agent in Practice: Installation and Model Integration
A practical guide to installing a terminal-based AI coding agent, connecting it to model services, securing credentials, extending it with MCP, Skills, project context, automation, and end-to-end browser and device validation.
Foreword: The value of an Agent lies in action, not conversation
Over the past two years, AI coding tools have evolved through three stages: first, completing a few lines in an editor; then generating entire functions; today, reading and writing files, executing commands, and running tests directly in a terminal. With each shift, the human role moves back: from writing line by line, to directing, and then to setting a goal and letting the agent work.
The biggest gain is not faster typing; the workflow itself is rewritten. Steps that used to be remembered and executed manually can now be described in a sentence, then planned, executed, and verified by the agent. For individuals, output covers more stages; for teams, repetitive work becomes reusable scripts and rules.
But a tool is useful only if it can run. Many developers get stuck in two places: installing and configuring the runtime environment, and connecting their model service in a stable and controllable way. This article follows a practical order: set up the environment, connect the model, extend capabilities, and embed the agent into workflows. Environment variable names, command parameters, and directory structures in this article are illustrative. Always refer to the official documentation of the tool you use. Secrets are shown as masked placeholders.
1. The foundation: three layers of automation capability
Before installation, keep one judgment in mind: how much an agent can automate depends on what it can see and touch. The model is only an inference engine. It can answer questions, but it needs “eyes” and “hands” to complete tasks. The capabilities an agent can call can be divided into three layers.
| Layer | Core capability | Typical sources | What happens if it is missing |
|---|---|---|---|
| Information layer | Search documents, fetch web pages | Built-in model search, standalone search tools | It can only rely on training data and cannot answer time-sensitive questions such as latest releases or current errors |
| Interface layer | Open pages, click, fill forms, take screenshots | Browser automation tools | It cannot operate web systems without APIs, and frontend changes are hard to verify end to end |
| Device layer | Install apps, simulate input, read logs | Mobile device debugging tools | It cannot verify behavior on real devices, and mobile automation breaks here |
These three layers form a complete execution loop:
- Search: find official documentation, version notes, or known fixes for an error.
- Execute: operate in a browser or on a device, and feed the result back.
- Verify: screenshots, logs, and test results give the model evidence for whether the task was done correctly.
The following flow shows a typical path:
User request│▼Search information layer ──► Understand codebase / review latest docs│▼Generate changes ──► Run tests and builds (self-check)│ ││ failure ─┴─► Read error logs ──► Revise plan▼Interface layer / Device layer: web regression, real-device validation│▼Summary (change notes / screenshots / verification conclusion)
Understanding these layers explains why tool extension and end-to-end validation matter later. They are not optional extras; they determine whether the agent can really do the work.
2. Installation: getting the agent running in your terminal
2.1 Environment preparation
Most command-line agents are distributed through the Node.js ecosystem, so they have runtime requirements. Prepare as follows:
- Runtime: install a supported Node.js version. Prefer the current LTS release, or use a version manager to switch as needed.
- Terminal: any familiar terminal works. Windows users can use Windows Terminal, which supports tabs and panes. For Unix-style commands, use Git Bash included with Git for Windows, or a Linux environment in WSL.
- Code hosting and package management: ensure Git is installed. If you use npm, you can configure a registry mirror before installing global packages to improve download speed.
- Network: make sure the network can reach the model service endpoint. If your environment uses a proxy, verify the proxy settings.
Note: this environment is only the baseline used for this article. The exact requirements depend on the official documentation of the tool you use.
2.2 Install command and project directory
Install from the terminal (use the package name from the official documentation):
# Install globallynpm install -g <package-name># Verify the installationclaude --version
When starting for the first time in a project directory, the tool usually scans the project and generates a configuration file. You can specify the working directory:
cd /path/to/your-projectclaude
After startup, the project usually contains a structure like this (names may vary by tool):
your-project/├── .claude/│ ├── settings.json # Project-level settings: permissions, environment variables, tool toggles│ └── commands/ # Custom slash commands (Markdown files)├── .mcp.json # Shared tool extension configuration for the team└── CLAUDE.md # Project guide that tells the agent how the project works
In .claude/settings.json, the permissions field controls what the agent can execute and is central to safety boundaries. Example:
{"permissions": {"allow": ["Bash(npm run test:*)", "Bash(git status)"],"deny": ["Bash(rm -rf *)", "Read(./.env)"]}}
The deny list takes priority over allow, and can block dangerous operations and sensitive files. Put all changes under version control so every team member gets a consistent environment.
2.3 First-run checklist
- Start in a new empty directory and confirm the interactive interface opens.
- Run a simple instruction, such as “list the files in the current directory”, and check whether it actually calls a tool and returns a result.
- Check the model name and API endpoint in the output to confirm requests are going to the expected endpoint.
3. Connecting a model service: from runnable to practical
After installation, the default configuration usually calls the official model service. Many developers switch to another compatible model service for reasons such as internal compliance requirements, data residency requirements, cost control, lower latency, or easier procurement and billing. There are two main approaches.
First: configure a custom endpoint following the official documentation. This applies when the tool explicitly supports specifying an API endpoint through environment variables or configuration files.
Second: use a third-party multi-model configuration tool. Such tools provide a graphical interface for managing credentials, base URLs, and model mappings for different providers, and can write the configuration in one step. They are useful when you frequently switch services, or when the current version of the tool does not support custom endpoints. If you change tools, clean up old environment variables to avoid conflicts.
3.1 Before connecting: check whether the model can support the agent
Before connecting, understand the hard requirements the agent has for the model. In addition to text understanding, it usually depends on:
- Tool calling / function calling: the agent reads and writes files and executes commands by asking the model to emit structured instructions, running tools, and feeding results back. Models without tool calling support cannot drive this kind of agent.
- Context length: codebase indexes, error logs, and documentation snippets consume context. A small context window makes long tasks lose track frequently.
- Stability in long conversations: when a task drifts midway, the issue is often not that the model cannot write code, but that the context contains too much irrelevant information.
If you are using a model service such as Baidu AI Cloud Qianfan, you can usually check whether models support tool calling and what their context windows are in the platform console, then create an application and obtain credentials. Refer to the latest platform documentation for exact fields and entry points.
3.2 Three integration patterns: direct, routing, and aggregation
Connecting a model can be reduced to three patterns. Understanding the differences helps you choose based on need.
Pattern 1: Direct connection
Configure one model endpoint and one credential. All requests go to the same model; switching models means changing the configuration:
# Example: Linux / macOSexport ANTHROPIC_BASE_URL="https://your-gateway.example.com/anthropic"export ANTHROPIC_AUTH_TOKEN="sk-****"# Example: Windows PowerShell$env:ANTHROPIC_BASE_URL = "https://your-gateway.example.com/anthropic"$env:ANTHROPIC_AUTH_TOKEN = "sk-****"
You can also put these values in the env field of .claude/settings.json. The advantage is simplicity and control. The disadvantage is that capability is limited to a single model, and you cannot choose different models for different task types.
Pattern 2: Routing
Use a third-party integration tool or a self-hosted proxy to distribute requests to different endpoints according to rules. For example, route code generation to a coding model, code review to a reasoning model, and documentation work to a lightweight model:
{"routes": {"reasoning": { "endpoint": "https://provider-a.example.com/v1", "model": "reasoning-model" },"default": { "endpoint": "https://provider-b.example.com/v1", "model": "general-model" }},"rule": "Route code review and design tasks to reasoning; route everything else to default"}
Routing lets expensive but powerful models and fast but economical models do what they do best. The cost is more complex rules and operations, plus maintaining multiple sets of credentials.
Pattern 3: Aggregation
Use an aggregation gateway, such as open-source options like One API or New API, or a commercial model gateway, as the single entry point. The gateway handles authentication, rate limiting, billing, and failover across multiple endpoints. The agent side only needs one address:
# Example: point the agent to a self-hosted aggregation gatewayexport ANTHROPIC_BASE_URL="https://llm-gateway.internal.example.com/anthropic"export ANTHROPIC_AUTH_TOKEN="sk-****"
The value of aggregation is “configure once, choose from many.” The same configuration can switch to any backend, and credentials do not need to be scattered across every machine. The gateway should be deployed in an owned or trusted environment, with access control and log auditing in place.
The trade-offs are summarized below:
| Pattern | Configuration complexity | Model selection flexibility | Cost control | Main risk | Typical scenario |
|---|---|---|---|---|---|
| Direct | Low | Single model | Simple and controllable | Limited to one model | Personal use, single project |
| Routing | Medium | High | Optimize by task | Rule maintenance | Team division by scenario |
| Aggregation | High | Highest | Unified metering and switching | Gateway becomes bottleneck | Multiple projects and members |
3.3 Credential security: more important than integration
- Do not put credentials in code or commit them to a repository. Prefer environment variables or the system keychain, and ignore configuration files in
.gitignore. - Least privilege: if the service supports it, create a dedicated sub-account for the credential and grant only necessary model-calling permissions.
- Rotate regularly: this limits damage if a leak occurs.
- Separate environments: use different credentials for development, testing, and production to avoid consuming production quota during debugging.
Reminder: if a credential appears in a chat window or screenshot, revoke it immediately in the console and generate a new one. Specific credential-management features, such as key grouping, usage statistics, and quota settings, depend on the console of the service you use.
4. Turning the agent into a workbench: MCP, Skills, and project context
Once installed and connected, the real efficiency divide is whether the agent is just a coding novice, or an experienced colleague who knows your project rules and can call internal systems. The answer lies in three things.
4.1 MCP: one protocol for external capabilities
MCP (Model Context Protocol) is an open protocol for standardizing how models connect to external tools and data sources. You can think of an MCP server as a plugin: once attached, the agent can read databases, query internal documentation, operate browsers, manage issues, and more.
Add an example configuration to .mcp.json in the project root (actual fields follow the documentation):
{"mcpServers": {"browser": {"command": "npx","args": ["-y", "@playwright/mcp@latest"],"env": {}},"device": {"command": "npx","args": ["-y", "@modelcontextprotocol/server-adb"]},"search": {"command": "npx","args": ["-y", "@modelcontextprotocol/server-brave-search"],"env": { "BRAVE_API_KEY": "your-brave-key" }}}}
Keep shared team configuration in .mcp.json. Put personal services, such as ones containing your own credentials, in personal configuration to avoid committing secrets. Common management commands:
claude mcp list # View configured MCP serversclaude mcp add <name> <command> # Add an MCP serverclaude mcp get <name> # Check the connection status of a server
4.2 Skills: reusable methods packaged as capabilities
A Skill packages instructions, scripts, and resources into a capability. The agent loads it by description when needed. The difference from MCP is that MCP provides tools (what can be done), while Skills provide methods (how to do it). A typical Skill directory:
.claude/skills/deploy-check/├── SKILL.md # Describes when to use this skill and the steps├── checklist.md # Detailed checklist, read on demand└── scripts/└── verify.py # Executable script
SKILL.md starts with metadata and then describes steps:
---name: deploy-checkdescription: Automated pre-deployment check. Use when the user says "prepare to release" or "check whether we can ship".---# Pre-deployment check1. Run `scripts/verify.py` and confirm the build artifacts are complete;2. Check configuration items against `checklist.md`;3. Output a check report listing passed items and risks.
A good Skill has an accurate description so the agent knows when to use it, concrete steps that can be executed directly, and a clear output structure. Teams can turn processes such as pre-release checks, database migration reviews, and API documentation generation into Skills so new members can reuse them consistently.
4.3 CLAUDE.md: project-level context
Every project should have a CLAUDE.md at the root. It works like an onboarding manual for the agent. It usually includes:
- Tech stack and directory structure: framework versions, package manager, responsibilities of core modules.
- Build and test commands: dependency installation, tests, linting, and release packaging.
- Code conventions: naming, logging, error handling, and commit message rules.
- Forbidden areas and preferences: directories not to modify, patterns not to introduce, and requirements for adding or removing dependencies.
- Known issues and pitfalls: build traps, environment dependencies.
Example:
# Project guide- Tech stack: Node.js 20 + TypeScript + Express + PostgreSQL- Package manager: pnpm (do not use npm install)- Tests: `pnpm test` for unit tests, `pnpm test:e2e` for end-to-end tests- Directories: `src/api` for API layer, `src/services` for business logic, `src/dao` for data access- Conventions: use pino for logging; do not write SQL directly in controllers- Note: do not modify already committed files under `migrations`
The more specific CLAUDE.md is, the less likely the agent is to drift. It is also passed to subagents, so subtasks follow the same project rules. Subagents are context-isolated specialist teams suitable for time-consuming tasks such as code review, batch refactoring, and documentation retrieval: the main session only receives conclusions and is not polluted by large amounts of intermediate content.
You can also create custom slash commands in .claude/commands/ to template frequent instructions:
---description: Review current changesallowed-tools: Bash(git diff:*), Read, Grep---Review the current uncommitted changes and focus on:1. Whether they affect compatibility with existing APIs;2. Whether there are unhandled exception paths;3. Whether corresponding tests are missing.Output a list of issues by severity.
5. Common commands and workflows
| Command | Purpose | Typical scenario |
|---|---|---|
claude |
Start an interactive session | Main daily development entry point |
claude "task description" |
Start with an initial task | Jump directly into a requirement |
claude -p "task" |
Run once and output the result | Scripts, CI, scheduled jobs |
claude -c |
Continue the last session | Resume an unfinished task |
claude -r <id> |
Restore a specific session | Review history or switch task branches |
claude update |
Update to the latest version | Regular maintenance |
claude mcp list |
View tool extensions | Troubleshoot tool connections |
Common in-session slash commands are also worth remembering: /init generates project documentation, /agents manages subagents, /config adjusts settings, /permissions views permissions, /resume restores a session, and /doctor checks the environment. The exact slash-command list changes by version; refer to the built-in help of the tool.
6. Scheduled and persistent execution: from human direction to autonomous runs
6.1 Unattended execution: one-shot mode
Non-interactive mode is useful for automation. Example:
# Every night, organize open issues and suggest priorities; write the result to a fileclaude -p "Read all open issues under docs/issues/, sort them by impact and urgency, and output a Markdown table" \--output-format json > report.json
Combined with OS scheduling tools, such as cron on Linux or Task Scheduler on Windows, you can run daily inspections:
# Example: run inspection every day at 02:000 2 * * * cd /path/to/project && /usr/local/bin/claude -p "Run tests and generate a summary" >> logs/inspect.log 2>&1
For unattended execution, pay attention to three things: limit the maximum number of turns with parameters such as --max-turns to avoid infinite loops, set a timeout, and write logs to disk for later tracing.
6.2 Self-driving: loop mode
In an interactive session, loop mode lets the agent keep working by itself. For example:
/loop Every 10 minutes, check the build pipeline. If it fails, pull the logs, find the cause, fix it, and retrigger it until it passes.
Loop mode turns “a human watching progress” into “a human reviewing results.” It must be paired with permission limits and a clear termination condition; otherwise, it can become a costly loop that continuously consumes quota.
6.3 Hooks: writing rules into the workflow
Hooks run commands automatically when specific events occur. Example:
{"hooks": {"PostToolUse": [{"matcher": "Write|Edit","hooks": [{ "type": "command", "command": "npx prettier --write \"$CLAUDE_FILE_PATHS\"" }]}]}}
This formats files automatically after every write or edit, so consistent style no longer depends on manual reminders.
6.4 Session and context management
In long tasks, context management often decides success or failure:
/compact: manually compact history while retaining key conclusions.- Subagent splitting: break a large task into smaller tasks with isolated contexts.
- Externalize intermediate results: write them to files and pass information through files rather than conversation history.
- Regular
/clear: clear context when switching tasks to avoid old context interfering.
7. The complete loop: web and device automation
Return to the three foundational layers. You have already handled the information layer with search tools. This section focuses on the interface layer and device layer.
7.1 Operating web pages: browser automation
After attaching a browser automation tool through MCP, the agent gains “eyes” and “hands.” Example instruction:
Open the admin dashboard at http://localhost:3000, sign in with admin/test1234,go to the order list page, filter orders with status "pending shipment",take a screenshot to confirm the result, and tell me how many records there are.
The underlying execution path is roughly:
Instruction ──► Plan steps ──► Launch browser ──► Fill login form ──► Apply filter▲ │└────────── Screenshot / DOM snapshot ◄─────────────────────┘
For developers, the most valuable use is end-to-end validation: after changing the frontend, you do not need to click through everything yourself. Let the agent run the critical path and return screenshots and errors together, making problem localization faster. In production, use a dedicated test account, restrict the range of actions, and mask sensitive pages.
7.2 Operating devices: mobile automation
After attaching a mobile device debugging tool, the agent can list connected devices, install packages, launch apps, simulate clicks and input, and capture logs. Example:
List the currently connected devices; install the built package on a real device;launch the app, go to "Me - Settings", take a screenshot, and check for layout misalignment;if there is a crash, capture the crash log and analyze the cause.
Underlying actions include listing devices, installing apps, launching components, simulating taps and swipes, and capturing screens and logs. This addresses common issues such as “the code works in the emulator but shows a blank screen on a real device,” and is a typical automation step in mobile CI.
7.3 Coordinating both: one intent, autonomous planning
Once the three layers are connected, the most direct change is that you only need to state the goal, and the model plans the path. For example:
Perform pre-release validation for the order export feature:1. Start the backend service and confirm the health check passes;2. Sign in to the browser as a normal user and export the last 7 days of orders to Excel;3. Validate the exported file's column names and row count;4. Open the "My Orders" page in the app on a real device and confirm the list renders correctly;5. Summarize everything into a validation report with screenshots, logs, and conclusions.
The agent will roughly execute like this:
Plan: start service → health check → sign in → export → validate → real-device screenshot → summarize│├─ Information layer: check documentation for auth requirements of the export API├─ Interface layer: browser signs in, filters, exports, and captures screenshots as evidence├─ Device layer: real-device screenshot confirms the mobile list renders correctly└─ Summary layer: generate a report marking passed items and risks
This is what a “complete loop” means: not every step needs a human click. The human only defines what counts as success.
8. Production practices and pitfalls to avoid
When using agents in production workflows, keep these lessons in mind:
- Start small: begin with a real but low-risk task, such as generating unit tests, organizing documentation, or fixing lint errors. Expand to core workflows after it runs reliably.
- Default to strict permissions: deny dangerous operations by default and open them only as needed. Use the
denylist to protect red lines such as deletion, force-push, and production releases. - Commit configuration:
CLAUDE.md, Skills, custom commands, and MCP configuration should be committed to the repository so the team’s agent behavior is reproducible and reviewable. - Keep humans in the loop: critical changes must pass code review, and CI pipelines should keep human approval gates. Agent output must not bypass existing quality gates.
- Make cost observable: review usage statistics regularly and set budget limits for long tasks to avoid unexpected expenses caused by runaway loops.
- Validate after upgrades: after upgrading the tool, rerun critical workflows to confirm configuration and permissions still work.
- Privacy and compliance: do not upload more code or data than necessary. When internal systems are involved, confirm data flow and retention policies first.
Final thoughts
The value of these tools is not how smart they are today, but how much scope you are willing to let them act in. From installation to model integration, and then to connecting search, web, and device capabilities into a complete loop, no single step is difficult. The hard part is actually handing over the process.
A practical criterion is this: each week, find at least one step that you would normally do manually, and try to hand it to an agent. As this list grows, your role changes from executor to workflow designer. The right way to use these tools is to get involved, move along the capability boundary, and let the agent take on more while you retain control.
