我們正在構建的項目
忘記功能列表吧。學習工具最好的方式就是用它來構建一些東西。
在本教程中,你將使用 OpenCode — 擁有 120K+ GitHub 星星的開源 AI coding agent — 從頭開始構建一個完整的書籤管理器。這個應用程序將包含:
- 一個使用 Express.js 和 TypeScript 的 REST API
- 一個具備全文搜索功能的 SQLite 數據庫
- 一個用於組織書籤的標籤系統
- 一個簡單但功能齊全的 frontend
- Unit tests
每個 OpenCode 功能都會在需求出現時立即引入,而不是放在抽象的功能章節中。到最後,你將了解如何安裝 OpenCode、配置模型、使用 Build 和 Plan modes、設置 MCP servers 以及創建自定義 agents — 這些都是因為你曾使用它們構建過一個真實的項目。
時間: ~30 minutes 先決條件: 已安裝 Node.js 18+、終端機 (macOS, Linux, 或 Windows 上的 WSL) 費用: 免費 (使用 OpenCode Zen models)
階段 1:安裝 OpenCode 並設置項目 (5 minutes)
安裝 OpenCode
打開你的終端機並運行以下命令之一:
# Option 1: npm (recommended)
npm i -g opencode-ai@latest
# Option 2: Homebrew (macOS/Linux)
brew install sst/tap/opencode
# Option 3: One-line installer
curl -fsSL https://opencode.ai/install.sh | bash
驗證安裝:
opencode --version
你應該會看到版本號。截至 March 2026,最新的穩定版本可在 OpenCode GitHub repository 上獲得。
創建項目目錄
mkdir bookmark-manager && cd bookmark-manager
git init
npm init -y
首次啟動 OpenCode
opencode
這將打開 OpenCode 的 TUI (Terminal User Interface) — 一個使用 Bubble Tea 構建的全屏交互式界面。你會在底部看到聊天輸入框,在主區域看到對話面板。
選擇模型
首次啟動時,OpenCode 會要求你選擇模型。你有三條路徑:
免費 (Zen models): 輸入 /models 並選擇其中一個 免費 Zen models。在本教程中,Grok Code Fast 1 或 GLM 4.7 效果很好。這些是免費的,且不需要 API key。
本地 (Ollama): 如果你安裝了 Ollama,OpenCode 會自動檢測到它。推薦用於 Ollama 的模型 是 glm-4.7:cloud。
付費 (自備密鑰): 輸入 /connect 來連結你的 Anthropic, OpenAI, 或 Google API key。Keys 本地存儲在 ~/.local/share/opencode/auth.json。
在本教程中,任何模型都可以使用。能力較強的模型 (Claude Sonnet 4.6, GPT-5.4) 在處理複雜任務時會產生更好的結果,但免費的 Zen models 足以處理我們在這裡構建的所有內容。
階段 2:使用 Build Mode 搭建項目腳手架 (4 minutes)
OpenCode 默認以 Build mode 啟動。Build mode 賦予 AI agent 完整的權限來創建文件、編輯代碼和運行命令。這正是我們搭建腳手架所需要的。
你的第一個 Prompt
在 OpenCode 聊天框中輸入:
Set up a TypeScript Node.js project with Express for a bookmark manager REST API.
Use SQLite via better-sqlite3 for the database. Add TypeScript, ts-node, and
nodemon as dev dependencies. Create a src/ directory with an index.ts entry point
that starts an Express server on port 3000.
OpenCode 將會:
- 創建一個
tsconfig.json - 使用
npm install安裝依賴項 - 創建帶有 Express server 設置的
src/index.ts - 使用啟動腳本更新
package.json
觀察 TUI — 你將看到 agent 執行終端命令、創建文件,並在每個步驟解釋其操作。這不是真空中的代碼生成;OpenCode 擁有對你的文件系統和終端機的完整訪問權限。
驗證是否有效
當 OpenCode 完成後,告訴它:
Run the server and verify it starts correctly on port 3000.
OpenCode 將運行 npx nodemon src/index.ts 並確認 server 正在監聽。你應該會看到類似 Server running on http://localhost:3000 的輸出。
剛才發生了什麼 (功能:Build Mode)
Build mode 是 OpenCode 的默認 agent。它可以訪問所有工具:文件讀取/寫入、終端執行和代碼編輯。根據 OpenCode documentation,你可以將其視為一個擁有開發環境完整訪問權限的 AI 配對編程夥伴。
階段 3:創建數據模型和數據庫 (4 minutes)
設計 Schema
輸入此 prompt:
Create a database module at src/db.ts that:
1. Initializes a SQLite database at ./data/bookmarks.db
2. Creates a bookmarks table with: id (auto-increment), url (text, unique),
title (text), description (text, nullable), created_at (datetime),
updated_at (datetime)
3. Creates a tags table with: id (auto-increment), name (text, unique)
4. Creates a bookmark_tags junction table for many-to-many relationships
5. Enables WAL mode for concurrent read performance
6. Creates an FTS5 virtual table for full-text search on title and description
Export a function to get the database instance.
OpenCode 將生成完整的數據庫模組。請注意它如何處理 FTS5 (Full-Text Search 5) 設置 — 這是 SQLite 的一項功能,稍後將為我們的搜索功能提供動力。
在 Server 啟動時初始化數據庫
Import the database module in index.ts and initialize it when the server starts.
Log a confirmation message.
創建 opencode.json 配置
現在是引入項目配置的好時機。通過告訴 OpenCode 來創建一個文件:
Create an opencode.json file in the project root with the project name
"bookmark-manager" and a rule that says "This is a TypeScript Express API
using better-sqlite3. Follow RESTful conventions. Use async/await. Return
JSON responses with consistent error formatting."
這會創建 OpenCode 在啟動時讀取的 project configuration file。它為 AI 提供了關於你項目的持久上下文 — 編碼標準、架構決策和約束 — 這樣你就不用在每個 prompt 中重複它們。
階段 4:構建 REST API Endpoints (5 minutes)
生成 Routes
Create a routes module at src/routes/bookmarks.ts with these endpoints:
- POST /api/bookmarks — create a bookmark (validate url and title are present)
- GET /api/bookmarks — list all bookmarks with pagination (page, limit params)
- GET /api/bookmarks/:id — get a single bookmark with its tags
- PUT /api/bookmarks/:id — update a bookmark
- DELETE /api/bookmarks/:id — delete a bookmark and its tag associations
Use proper HTTP status codes. Return JSON with a consistent shape:
{ success: boolean, data: any, error?: string }
註冊 Routes
Import the bookmark routes in index.ts and register them. Also add
express.json() middleware and a global error handler.
使用 curl 測試
Start the server, then create a test bookmark using curl:
curl -X POST http://localhost:3000/api/bookmarks \
-H "Content-Type: application/json" \
-d '{"url": "https://opencode.ai", "title": "OpenCode - AI Coding Agent"}'
Then fetch all bookmarks to verify it was saved.
OpenCode 將在你的終端機中執行這些命令並顯示響應。這正是該工具的閃光之處 — 你永遠不需要離開終端機,且 AI 會驗證自己的工作。
階段 5:使用 FTS5 添加搜索功能 (4 minutes)
引入 Plan Mode
在構建搜索功能之前,讓我們使用 Plan mode 來思考實現方案。切換模式:
/plan
現在你處於 Plan mode。AI 可以讀取並分析你的代碼,但不能修改任何文件。這對於 在做出更改前進行規劃 非常有用。
Analyze my current database schema and FTS5 table. Plan how to implement a
search endpoint that queries the FTS5 table and returns bookmarks ranked by
relevance. Consider edge cases: empty queries, special characters, partial
matches.
OpenCode 將檢查你的代碼,將計劃寫入 .opencode/plans/,並在不觸動任何文件的情況下解釋其方法。閱讀計劃,根據需要進行調整,然後切換回來:
/build
實現搜索
Based on the plan, implement a GET /api/bookmarks/search?q=query endpoint
that uses the FTS5 virtual table for full-text search. Include snippet
highlighting and relevance ranking. Handle edge cases from the plan.
測試搜索
Create three more test bookmarks with different titles and descriptions,
then test the search endpoint with a query that should match two of them.
剛才發生了什麼 (功能:Plan Mode)
Plan/Build 工作流是資深開發者在處理複雜任務時使用 OpenCode 的方式。先規劃,審查方法,然後構建。計劃文件保存在 .opencode/plans/ 並 可以在稍後被引用 供 build agent 使用。這可以防止 AI 隨意做出重大的結構性決策。
階段 6:實現標籤系統 (4 minutes)
創建標籤 Endpoints
Create a routes module at src/routes/tags.ts with:
- POST /api/tags — create a new tag
- GET /api/tags — list all tags with bookmark counts
- POST /api/bookmarks/:id/tags — add a tag to a bookmark
- DELETE /api/bookmarks/:id/tags/:tagId — remove a tag from a bookmark
- GET /api/bookmarks?tag=tagname — filter bookmarks by tag (update existing
list endpoint to support this query parameter)
Register the tag routes in index.ts.
測試標籤流程
Create two tags: "dev-tools" and "tutorials". Add the "dev-tools" tag to
the OpenCode bookmark. Then fetch bookmarks filtered by the "dev-tools" tag.
階段 7:構建一個簡單的 Frontend (5 minutes)
生成 Frontend
Create a public/ directory with a single-page frontend:
- index.html with a clean, minimal design (no framework, just HTML/CSS/JS)
- A form to add bookmarks (url, title, description)
- A search bar that queries the search endpoint with debounced input
- A list of bookmarks showing title, url, tags, and a delete button
- A tag filter sidebar that shows all tags with counts
- Use fetch() for API calls. Mobile responsive. No build step needed.
Serve the public/ directory as static files from Express.
OpenCode 將一次性生成完整的 frontend — HTML 結構、CSS 樣式和用於 API 交互的 JavaScript。使用 AI agent 在終端機中構建的好處是,它可以立即測試 frontend 是否成功連接到 API。
測試全棧功能
Start the server, open http://localhost:3000 in a description, and verify
that adding a bookmark from the form, searching, and filtering by tag all
work correctly.
階段 8:使用自定義 Agent 添加測試 (5 minutes)
創建自定義測試 Agent
這就是 OpenCode 的 custom agents 功能派上用場的地方。我們不使用通用的 Build agent 進行測試,而是創建一個專門的 agent。
將此內容添加到你的 opencode.json:
{
"agents": {
"test": {
"name": "Test Writer",
"instructions": "You are a testing specialist. Write comprehensive tests using Vitest. Focus on edge cases and error paths. Never modify source code — only create and edit test files.",
"tools": ["read", "write", "terminal"]
}
}
}
現在切換到測試 agent:
/agent test
生成測試
Write comprehensive tests for the bookmark API using Vitest and supertest.
Cover:
- Creating a bookmark with valid data
- Creating a bookmark with missing required fields
- Fetching all bookmarks with pagination
- Searching with FTS5 (matching and non-matching queries)
- Adding and removing tags
- Deleting a bookmark removes its tag associations
Use an in-memory SQLite database for test isolation.
運行測試
Install vitest and supertest as dev dependencies, add a test script to
package.json, then run the test suite.
剛才發生了什麼 (功能:Custom Agents)
Custom agents 允許你創建具有特定指令和工具訪問權限的專注角色。我們創建的測試 agent 只能讀取文件、編寫測試文件和運行終端命令 — 它不能修改源代碼。這種約束防止了 AI 在測試失敗時「修復」你的源代碼而不是修復測試的常見問題。
你可以為任何專業工作流創建 agents:代碼審查、文檔編寫、數據庫遷移、DevOps 腳本。OpenCode agents documentation 有更多示例。
加分項目:連接 MCP Server 以增強功能
如果你想擴展你的書籤管理器,可以通過 MCP (Model Context Protocol) servers 連接外部工具。
示例:添加連結預覽 MCP Server
想像一下,你希望 OpenCode 在創建書籤時自動從 URL 獲取元數據 (標題、描述、favicon)。你可以連接一個執行 HTTP 獲取的 MCP server:
將此內容添加到你的 opencode.json:
{
"mcp": {
"link-preview": {
"type": "local",
"command": ["npx", "link-preview-mcp-server"]
}
}
}
現在 OpenCode 有了一個新工具:它可以將獲取 URL 元數據作為其工作流的一部分。當你要求它「為 https://example.com 添加書籤並自動填充標題和描述」時,它將使用 MCP server 來獲取該數據。
遠程 MCP Servers
對於雲端服務,請使用具有 自動 OAuth 處理 功能的遠程 MCP servers:
{
"mcp": {
"cloud-storage": {
"type": "remote",
"url": "https://mcp.example.com/storage",
"headers": {
"Authorization": "Bearer ${STORAGE_TOKEN}"
}
}
}
}
如果服務器支持動態客戶端註冊 (Dynamic Client Registration),OpenCode 會檢測到 401 響應並自動啟動 OAuth 流程。
加分項目:在 CI/CD 中使用 OpenCode
OpenCode 具有一個可以在沒有 TUI 的情況下運行的 CLI mode — 非常適合自動化。你可以在 GitHub Actions 或任何 CI 管道中使用它:
# 運行單個 prompt 並退出
opencode -p "Review the changes in the last commit for security issues" --no-tui
# 使用特定模型
opencode -m "claude-sonnet-4-6" -p "Generate a changelog entry for this release" --no-tui
對於我們的書籤管理器,你可以添加一個 CI 步驟,運行 OpenCode 來自動審查 PR。 OpenCode GitHub integration 提供了此工作流的更精簡版本。
完整的項目結構
按照本教程操作後,你的項目應該如下所示:
bookmark-manager/
opencode.json # OpenCode 項目配置 + 自定義 agents + MCP
package.json
tsconfig.json
src/
index.ts # Express server 入口點
db.ts # 帶有 FTS5 的 SQLite 數據庫模組
routes/
bookmarks.ts # CRUD + 搜索 endpoints
tags.ts # 標籤管理 endpoints
public/
index.html # 單頁 frontend
tests/
bookmarks.test.ts # API 測試套件
data/
bookmarks.db # SQLite 數據庫 (gitignored)
.opencode/
plans/ # 來自 Plan mode 會話的計劃
你學到了什麼
通過構建一個真實的項目,你練習了這些 OpenCode 功能:
| 功能 | 你在哪裡使用它 |
|---|---|
| Installation | 階段 1 — npm, Homebrew, 或 curl |
| Zen models (免費) | 階段 1 — 在沒有 API key 的情況下選擇模型 |
| Build mode | 階段 2-7 — 具有文件和終端訪問權限的完整開發 |
| Plan mode | 階段 5 — 在實現之前分析代碼並規劃搜索 |
| opencode.json | 階段 3 — 具有一致 AI 行為規則的項目配置 |
| Custom agents | 階段 8 — 一個不能修改源代碼的測試編寫 agent |
| MCP servers | 加分項目 — 使用外部工具擴展 OpenCode |
| CLI mode | 加分項目 — 在沒有 TUI 的情況下在 CI/CD 中運行 OpenCode |
OpenCode 與其他 AI 編碼工具的主要區別在於它是 完全開源的,在你的終端機中運行,並且不會存儲你的代碼或上下文數據。你控制模型,數據保留在本地,且擁有 800+ 貢獻者的社區使其快速進化。
對於使用多種 AI 工具的團隊,OpenCode 是 IDE 助手的終端補充。在 ZBuild,我們經常在開發工作流的不同部分將它與基於編輯器的工具並行使用。
下一步
現在你已經有了一個可以運行的書籤管理器並對 OpenCode 有了紮實的理解,這裡有一些值得探索的方向:
- 添加身份驗證 — 使用 Build agent 添加基於 JWT 的用戶帳戶驗證
- 部署到生產環境 — 要求 OpenCode 生成 Dockerfile 並部署到 Fly.io 或 Railway
- 構建瀏覽器擴展 — 創建一個通過 API 添加書籤的 Chrome 擴展
- 探索更多 Zen models — 嘗試 Big Pickle, MiniMax M2.1,或通過 Ollama 運行本地模型
- 創建更多自定義 agents — 「重構」agent、「文檔」agent 或「安全審計」agent
OpenCode documentation 和 awesome-opencode repository 有更多插件、主題和社區配置供你探索。
來源
- OpenCode — Official Documentation
- OpenCode — GitHub Repository
- OpenCode — Zen Models
- OpenCode — Agents Documentation
- OpenCode — MCP Servers
- OpenCode — CLI Mode
- OpenCode — Configuration
- OpenCode — GitHub Integration
- Ollama — OpenCode Integration
- awesome-opencode — Community Resources
- Composio — MCP with OpenCode
- Computing for Geeks — Setup OpenCode AI