使用 Zig 和 Gemini CLI 进行本地 MCP 开发
I’m happy to translate the article for you, but I’ll need the full text of the post (the content after the source line) in order to do so. Could you please paste the article’s body here? Once I have it, I’ll provide a Simplified Chinese translation while preserving the original formatting, markdown, and code blocks.
概览
- Python 传统上在机器学习/人工智能工具中占主导地位,但 MCP 协议是语言无关的。
- 本指南展示如何使用 Zig——一种现代的开源系统语言——作为 MCP 的开发语言。
- 你将得到一个小型的 “Hello World” 风格的 Zig MCP 服务器,它通过 stdio 与 Gemini CLI 通信。
资源
| 资源 | 描述 |
|---|---|
| ZigMCP library | Comprehensive MCP library for Zig |
| Zig home page | |
| Debian Zig install guide | |
| Gemini CLI (npm) | npm install -g @google/gemini-cli |
| Node Version Manager (nvm) | |
| MCP Zig docs & samples |
先决条件
-
Zig(最新稳定版)– 通过操作系统的包管理器或上面的 Debian 指南进行安装。
-
Node.js – 一个近期的、最新的版本。使用 nvm 来管理它:
# Install nvm (if not already present) curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash # Load nvm and install Node LTS source ~/.bashrc # or ~/.zshrc nvm install --lts -
Gemini CLI – 使用 npm 全局安装:
npm install -g @google/gemini-cli -
身份验证 – 运行一次
gemini以使用 Google 账户或 API 密钥登录。
设置开发环境
# Clone the helper repository (contains init scripts and sample code)
cd ~
git clone https://github.com/xbill9/gemini-cli-codeassist
cd gemini-cli-codeassist
# Initialise environment variables for your shell
source init.sh
如果您的会话过期或需要稍后重新认证:
source set_env.sh # resets PROJECT_ID, credentials, etc.
构建最小化 MCP stdio 服务器
1. 创建 Zig 项目
示例项目位于 gemini-cli-codeassist/mcp-stdio-zig。
进入该目录并运行默认的 Make 目标:
cd mcp-stdio-zig
make # runs `zig build`
你应该会看到类似如下的输出:
Linked zig-out/bin/mcp-stdio-zig to server
2. 源代码要点
// src/main.zig
const std = @import("std");
const mcp = @import("mcp");
// Run the server using stdio transport
try server.run(.{ .stdio = {} });
服务器导入了标准 Zig 库 (std) 和 MCP 库 (mcp),随后启动基于 stdio 的 MCP 服务器。
3. Lint / 格式化
make lint
# → zig fmt --check .
# → zig build -Doptimize=ReleaseFast
4. 测试服务器
make test
# Output (truncated):
# Testing 'greet' tool...
# ✓ initialize successful
# ✓ notifications/initialized sent
# ✓ tools/list successful
# ✓ tools/call (greet) successful
# All tests passed!
测试脚本 (python3 test_server.py) 会验证 greet 工具的功能。
在 Gemini CLI 中注册服务器
添加一条记录到 ~/.config/gemini-cli/settings.json(或默认位置):
{
"mcpServers": {
"mcp-stdio-zig": {
"command": "$HOME/gemini-cli-codeassist/mcp-stdio-zig/server"
}
}
}
重启 Gemini CLI 以加载新配置。
使用 MCP 服务器
# Start a Gemini CLI session
gemini
> /mcp schema
Configured MCP servers:
🟢 mcp-stdio-zig - Ready (1 tool)
Tools:
- greet
Get a greeting from a local stdio server.
Parameters:
{
"type": "object"
}
现在调用该工具:
> greet Carmen!
✦ I will read the src/main.zig file to understand how the greet tool is implemented and what parameters it expects.
╭─────────────────────────────────────────────────────────────────────╮
│ ✓ ReadFile src/main.zig │
╰─────────────────────────────────────────────────────────────────────╯
服务器返回问候语,确认 MCP stdio 传输能够端到端工作。
回顾与后续步骤
- 环境 – 已安装并认证 Zig、Node(通过 nvm)以及 Gemini CLI。
- 服务器 – 已编译并测试了最小的 Zig MCP stdio 服务器。
- 集成 – 已在 Gemini CLI 中注册,并通过
/mcp schema和工具调用验证。
接下来,你可以:
- 添加更多 MCP 工具(例如
summarize、translate)。 - 使用相同的高层 MCP API 切换到其他传输方式(TCP、WebSocket)。
- 将 Gemini LLM 直接嵌入 Zig 代码,以实现更紧密的集成。
祝编码愉快! 🚀
MCP Tools Extension – Summary
1️⃣ Greeting Test
Command
✦ I will call the greet tool with the parameter param set to "Carmen!".
Tool Invocation
✓ greet (mcp-stdio-zig MCP Server) {"param":"Carmen!"}
Result
Carmen!
Note: 该工具返回了 “Carmen!”,证明基本的 MCP 功能正常。
2️⃣ Adding New MCP Tools
Zig 项目新增了三个工具:
| Tool | Purpose |
|---|---|
zig-info | Returns Zig version, OS, and architecture |
server-info | Returns server name and version |
current-time | Returns the current system timestamp |
Code Diff (added to src/main.zig)
+ fn serverInfoHandler(allocator: std.mem.Allocator, _: ?std.json.Value) mcp.tools.ToolError!mcp.tools.ToolResult {
+ logInfo("Executed server-info tool");
+
+ const info = "Server: mcp-stdio-zig, Version: 0.1.0";
+ var items = allocator.alloc(mcp.types.ContentItem, 1) catch return mcp.tools.ToolError.OutOfMemory;
+ items[0] = .{ .text = .{ .text = try allocator.dupe(u8, info) } };
+
+ return mcp.tools.ToolResult{
+ .content = items,
+ .is_error = false,
+ };
+ }
这些更改已提交,并验证了新工具。
3️⃣ Build & List Tools
xbill@penguin:~/gemini-cli-codeassist/mcp-stdio-zig$ make
zig build
Linked zig-out/bin/mcp-stdio-zig to server
List Available MCP Tools
/mcp list
Configured MCP servers:
🟢 mcp-stdio-zig - Ready (4 tools)
Tools:
- current-time
- greet
- server-info
- zig-info
4️⃣ Running the New Tools
current-time
✓ current-time (mcp-stdio-zig MCP Server) {}
Timestamp: 1769875173
zig-info
✓ zig-info (mcp-stdio-zig MCP Server) {}
Zig Version: 0.15.2, OS: linux, Arch: x86_64
Result: 已确认你正在 Linux x86_64 上运行 Zig 0.15.2。
server-info
✓ server-info (mcp-stdio-zig MCP Server) {}
Server: mcp-stdio-zig, Version: 0.1.0
Result: 已确认服务器名称和版本。
5️⃣ Summarizing the Zig Environment
Using the MCP tools and the codebase:
✓ ReadFile src/main.zig
✓ ReadFile build.zig
✓ ReadFile build.zig.zon
Summary
- Zig Version: 0.15.2
- Operating System: Linux (x86_64)
- MCP Server:
mcp-stdio-zig(v0.1.0) - Primary Dependency:
mcp.zig(v0.0.1) – 一个为 Zig 实现的 Model Context Protocol。 - Communication: 标准输入/输出(stdio),并将结构化 JSON 日志写入
stderr。 - Exposed Tools:
greet– 返回问候语(可参数化)。zig-info– 报告 Zig 版本、操作系统和架构。server-info– 返回服务器名称和版本。current-time– 提供当前系统时间戳。
6️⃣ The Ultimate Showdown: Ferris vs. Carmen
Google Search (for context)
✓ GoogleSearch Searching the web for: "who is carmen programming language mascot"
Search results for "who is carmen programming language mascot" returned.
Result
在一次假想的对决中,Rust 螃蟹 Ferris 与 Zig 分配器吉祥物 Carmen 将展开 安全性 vs. 控制 的较量。
Tale of the Tape
| Contestant | Signature Move | Defense | Weakness |
|---|---|---|---|
| 🦀 Ferris (Rust) | “Borrow Checker” (Hold) – you can’t move data until it’s proven safe. | Very high – the type system makes memory corruption nearly impossible. | Long compile times; slower to get ready for the fight. |
| 🐊 Carmen (Zig) | “Defer Deinit” (Death Roll) – resources are cleaned up when you explicitly tell her. | High – manual control gives power but requires discipline. | Requires explicit management; mistakes can lead to leaks or crashes. |
Bottom line: Ferris 带来了铁壁般的安全性。
ety,Carmen 提供细粒度的控制。最终的胜者取决于你更看重保证安全性(Rust)还是确定性、低开销的控制(Zig)。
使用 Zig 进行 MCP 开发(Gemini CLI)
- 从 Zig 源代码启动了一个最小的
stdio传输 MCP 服务器,并在同一本地环境中使用 Gemini CLI 作为 MCP 客户端进行验证。 - 然后使用 Gemini CLI 为示例 Zig 代码添加了多个 MCP 工具,并在底层大语言模型的上下文中使用这些工具。