← 返回新闻
ZBuild News

在 30 分钟内使用 OpenCode 构建 Full-Stack 书签管理器(分步指南)

一个基于项目的 OpenCode 教程,你将使用终端中的 OpenCode AI agent 构建一个包含 tags、search 和 REST API 的完整书签管理器。每个功能都会在需要时引入,而不是仅列出功能清单。

Published
2026-03-27
Author
ZBuild Team
Reading Time
9 min read
opencode tutorialopencode guideopencode installopencode setupopencode configurationopencode ai coding agent
在 30 分钟内使用 OpenCode 构建 Full-Stack 书签管理器(分步指南)
ZBuild Teamzh
XLinkedIn

我们正在构建什么

忘掉功能列表吧。学习工具最好的方法就是用它构建一些东西。

在本教程中,你将使用 OpenCode —— 这款拥有 120K+ GitHub 星标的开源 AI 编程代理 —— 从头开始构建一个完整的书签管理器。该应用将包含:

  • 一个使用 Express.js 和 TypeScript 构建的 REST API
  • 一个具有全文搜索功能的 SQLite 数据库
  • 一个用于组织书签的标签系统
  • 一个简单但功能齐全的前端
  • 单元测试

每个 OpenCode 功能都会在需要时引入,而不是放在抽象的功能章节中。到最后,你将了解如何安装 OpenCode、配置模型、使用 Build 和 Plan 模式、设置 MCP 服务器以及创建自定义代理 —— 这一切都是因为你使用它们构建了一个真实的项目。

时间: ~30 分钟 先决条件: 已安装 Node.js 18+、终端(macOS、Linux 或 Windows 上的 WSL) 成本: 免费(使用 OpenCode Zen 模型)


第一阶段:安装 OpenCode 并设置项目 (5 分钟)

安装 OpenCode

打开你的终端并运行以下命令之一:

# 选项 1: npm (推荐)
npm i -g opencode-ai@latest

# 选项 2: Homebrew (macOS/Linux)
brew install sst/tap/opencode

# 选项 3: 一键安装程序
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(终端用户界面)—— 一个使用 Bubble Tea 构建的全屏交互式界面。你会看到底部有一个聊天输入框,主区域有一个对话面板。

选择模型

首次启动时,OpenCode 会要求你选择一个模型。你有三条路径:

免费 (Zen 模型): 输入 /models 并选择一个 免费 Zen 模型。对于本教程,Grok Code Fast 1GLM 4.7 效果很好。这些是免费的,不需要 API key。

本地 (Ollama): 如果你安装了 Ollama,OpenCode 会自动检测到它。推荐用于 Ollama 的模型glm-4.7:cloud

付费 (自备密钥): 输入 /connect 来链接你的 Anthropic、OpenAI 或 Google API key。密钥本地存储在 ~/.local/share/opencode/auth.json 中。

对于本教程,任何模型都可以。更高能力的模型(Claude Sonnet 4.6, GPT-5.4)在复杂任务上会产生更好的结果,但免费的 Zen 模型可以处理我们在这里构建的所有内容。


第二阶段:使用 Build 模式构建项目脚手架 (4 分钟)

OpenCode 默认以 Build 模式 启动。Build 模式赋予 AI 代理创建文件、编辑代码和运行命令的完整权限。这就是我们构建脚手架所需要的。

你的第一个提示词

在 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 将会:

  1. 创建一个 tsconfig.json
  2. 使用 npm install 安装依赖
  3. 创建包含 Express 服务器设置的 src/index.ts
  4. 使用启动脚本更新 package.json

观察 TUI —— 你将看到代理正在执行终端命令、创建文件,并解释每一步的操作。这不是在真空中的代码生成;OpenCode 拥有访问你的文件系统和终端的完整权限。

验证它是否工作

一旦 OpenCode 完成,告诉它:

Run the server and verify it starts correctly on port 3000.

OpenCode 将运行 npx nodemon src/index.ts 并确认服务器正在监听。你应该看到类似 Server running on http://localhost:3000 的输出。

刚才发生了什么(功能:Build 模式)

Build 模式是 OpenCode 的默认代理。它可以访问所有工具:文件读/写、终端执行和代码编辑。根据 OpenCode documentation,你可以将其视为一个拥有开发环境完整访问权限的 AI 结对编程者。


第三阶段:创建数据模型和数据库 (4 分钟)

设计 Schema

输入此提示词:

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(全文搜索 5)设置 —— 这是一个 SQLite 功能,稍后将驱动我们的搜索功能。

在服务器启动时初始化数据库

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 在启动时读取的 项目配置文件。它为 AI 提供了关于你项目的持久上下文 —— 编码标准、架构决策和约束 —— 这样你就不用在每个提示词中重复它们。


第四阶段:构建 REST API 端点 (5 分钟)

生成路由

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 }

注册路由

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 会验证它自己的工作。


第五阶段:使用 FTS5 添加搜索 (4 分钟)

引入 Plan 模式

在构建搜索之前,让我们使用 Plan 模式来思考实现方案。切换模式:

/plan

现在你处于 Plan 模式。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 模式)

Plan/Build 工作流是经验丰富的开发者在处理复杂任务时使用 OpenCode 的方式。先规划,审查方案,然后构建。计划文件保存在 .opencode/plans/ 中,并且 稍后可以被引用 由 build 代理使用。这可以防止 AI 在运行中做出重大的结构性决策。


第六阶段:实现标签系统 (4 分钟)

创建标签端点

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.

第七阶段:构建一个简单的前端 (5 分钟)

生成前端

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 将一次性生成完整的前端 —— HTML 结构、CSS 样式和用于 API 交互的 JavaScript。在终端中使用 AI 代理构建的优势在于,它可以立即测试前端是否连接到了 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.

第八阶段:使用自定义代理添加测试 (5 分钟)

创建自定义测试代理

这就是 OpenCode 的 custom agents 功能发挥作用的地方。我们将创建一个专门的代理,而不是使用通用的 Build 代理来进行测试。

将此添加到你的 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 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.

刚才发生了什么(功能:自定义代理)

自定义代理允许你创建具有特定指令和工具访问权限的专注角色。我们创建的测试代理只能读取文件、编写测试文件和运行终端命令 —— 它不能修改源代码。这种约束防止了当测试失败时 AI “修复”你的源代码而不是修复测试的常见问题。

你可以为任何专门的工作流创建代理:代码审查、文档撰写、数据库迁移、DevOps 脚本。OpenCode agents documentation 有更多示例。


额外加分:连接 MCP 服务器以增强功能

如果你想扩展你的书签管理器,你可以通过 MCP (Model Context Protocol) 服务器连接外部工具。

示例:添加链接预览 MCP 服务器

假设你希望 OpenCode 在创建书签时自动从 URL 获取元数据(标题、描述、图标)。你可以连接一个执行 HTTP 获取的 MCP 服务器:

将此添加到你的 opencode.json

{
  "mcp": {
    "link-preview": {
      "type": "local",
      "command": ["npx", "link-preview-mcp-server"]
    }
  }
}

现在 OpenCode 有了一个新工具:它可以将获取 URL 元数据作为其工作流的一部分。当你要求它“为 https://example.com 添加书签并自动填充标题和描述”时,它将使用 MCP 服务器来获取该数据。

远程 MCP 服务器

对于云服务,使用具有 automatic OAuth handling 的远程 MCP 服务器:

{
  "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 流水线中使用它:

# 运行单个提示词并退出
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 项目配置 + 自定义代理 + MCP
  package.json
  tsconfig.json
  src/
    index.ts             # Express 服务器入口点
    db.ts                # 带有 FTS5 的 SQLite 数据库模块
    routes/
      bookmarks.ts       # CRUD + 搜索端点
      tags.ts            # 标签管理端点
  public/
    index.html           # 单页面前端
  tests/
    bookmarks.test.ts    # API 测试套件
  data/
    bookmarks.db         # SQLite 数据库 (gitignored)
  .opencode/
    plans/               # 来自 Plan 模式会话的计划

你学到了什么

通过构建一个真实的项目,你练习了这些 OpenCode 能力:

功能你在哪里使用了它
安装第一阶段 — npm, Homebrew, 或 curl
Zen 模型 (免费)第一阶段 — 在没有 API key 的情况下选择模型
Build 模式第二至七阶段 — 具有文件和终端访问权限的完整开发
Plan 模式第五阶段 — 在实现前分析代码并规划搜索
opencode.json第三阶段 — 带有规则的项目配置,以实现一致的 AI 行为
自定义代理第八阶段 — 一个无法修改源代码的测试编写代理
MCP 服务器额外加分 — 使用外部工具扩展 OpenCode
CLI 模式额外加分 — 在没有 TUI 的情况下在 CI/CD 中运行 OpenCode

OpenCode 与其他 AI 编程工具的关键区别在于它是 entirely open source,在你的终端运行,并且不存储你的代码或上下文数据。你控制模型,数据保留在本地,800+ 名贡献者的社区使其快速进化。

对于使用多种 AI 工具的团队,OpenCode 可以作为 IDE 助手的终端补充。在 ZBuild,我们经常在开发工作流的不同部分将其与基于编辑器的工具一起使用。


下一步

现在你已经拥有一个可以工作的书签管理器并对 OpenCode 有了深入的了解,这里有一些可以探索的方向:

  1. 添加身份验证 — 使用 Build 代理为用户帐户添加基于 JWT 的认证
  2. 部署到生产环境 — 让 OpenCode 生成 Dockerfile 并部署到 Fly.io 或 Railway
  3. 构建浏览器扩展 — 创建一个通过 API 添加书签的 Chrome 扩展
  4. 探索更多 Zen 模型 — 尝试 Big Pickle, MiniMax M2.1,或通过 Ollama 运行本地模型
  5. 创建更多自定义代理 — 一个“重构”代理、一个“文档”代理或一个“安全审计”代理

OpenCode documentationawesome-opencode repository 有更多插件、主题和社区配置供你探索。


来源

返回所有新闻
喜欢这篇文章?
FAQ

Common questions

我们在本教程中构建什么?+
一个包含 Node.js/Express REST API、SQLite 数据库、tag 系统、full-text search 和简单 HTML/CSS/JS frontend 的 Full-Stack 书签管理器。整个应用是使用 OpenCode 作为终端中的 AI coding agent 构建的,展示的是实际工作流而非功能列表。
学习本教程需要 API key 吗?+
不需要。OpenCode 提供免费的 Zen 模型,包括无需 API keys 即可运行的 Grok Code Fast、GLM 4.7 和 Big Pickle。你也可以通过 Ollama 使用 local models 完全离线运行。如果你有 Claude、GPT 或 Gemini API key,可以使用它们来获得更高质量的输出。
构建整个项目需要多长时间?+
如果你按部就班地操作,大约需要 30 分钟。本教程分为 7 个阶段:project setup、data model、API endpoints、search、tags、frontend 和测试。在 OpenCode 处理代码生成的情况下,每个阶段需要 3-5 分钟。
我可以在 VS Code 或 Cursor 中使用 OpenCode 吗?+
可以。OpenCode 可以在任何集成终端中运行。在 VS Code(Mac 上为 Cmd+Esc)或 Cursor 中打开拆分终端,并从中启动 OpenCode。它会自动与 AI agent 共享你的 selection 和打开的 file context。
Build mode 和 Plan mode 之间有什么区别?+
Build mode 赋予 AI agent 读取、写入和执行代码的完全权限。Plan mode 将其限制为只读分析——agent 可以检查你的代码并创建计划文件,但不能修改任何内容。在本教程的大型 refactoring 步骤之前,我们会使用 Plan mode。
如何向 OpenCode 添加 MCP servers?+
在你的 opencode.json config 中的 mcp 键下添加它们。每个 MCP server 都需要一个唯一的名称、类型(local 或 remote)和连接详情。Local servers 使用 command 字段;remote servers 使用带可选 headers 的 url 字段。OpenCode 会自动处理远程 MCP servers 的 OAuth。
Recommended Tools

Useful follow-ups related to this article.

Browse All Tools

用 ZBuild 搞定

把你的想法变成可运行的应用——无需编程。

46,000+ 人已经在用 ZBuild 造东西了

现在自己试试

有想法?我们帮你变现。

46,000+ 人已经在用 ZBuild 造东西了
More Reading

Related articles