服务器去
- 作者仓库星标 0
- 作者仓库 skills-registry
- 领域
- 人工智能
- 作者声明的智能体
- 未找到明确声明;不据此推断已兼容或已测试
- 静态检查
- 88 / 100 · 启发式扫描,不代表运行安全
- 运行环境证据
- 未执行;当前没有隔离运行测试证据
- 作者 / 版本 / 许可证
- @tomevault-io · 未声明许可证
- 上下文用量评级
- 低消耗
- 接入复杂程度
- 需手动接入
- 是否需要外部接口密钥
- 不需要
- 兼容的系统
- Windows · Docker
- 运行环境要求
- Docker
- 检测到的文件与系统行为
-
- 只读
- 允许写入 / 修改
- 命令执行
- 读取环境变量
- 网络行为
- 允许外网请求
- 安装命令数
- 无(仅作为资料)
需要注意: 未声明工具权限范围;实际权限由运行环境决定。
# mcp-server-go — building MCP servers in Go
This skill answers the questions that block productive MCP server work in Go. Verified against the 2025-11-25 spec and the official `modelcontextprotocol/go-sdk` v1.6.0 (released 2026-05-08).
## When to load
- Editing or building Go code in `projects/pg-ai-stewards/cmd/stewards-mcp/`
- Adding a new MCP tool to an existing server
- Wiring up a new MCP server to Claude Code or another MCP client
- Hitting "tool not found" / "JSON-RPC error" / silent connection failures
- Reading another project's MCP server code to understand its shape
## The four facts that change everything
### 1. Use the official Go SDK
`github.com/modelcontextprotocol/go-sdk` — maintained jointly by Anthropic and Google. v1.6.0 as of 2026-05-08. Schema reflection from struct tags, transport handling, capability negotiation, error wrapping all built in. Going from scratch in Go is ~250 lines for a tools-only stdio server; using the SDK is ~30. Use the SDK.
```go
import "github.com/modelcontextprotocol/go-sdk/mcp"
```
### 2. stdio transport is newline-delimited JSON
NOT LSP-style with `Content-Length` headers. One JSON-RPC message per line, embedded newlines forbidden inside messages. The SDK handles this for you via `mcp.StdioTransport{}`. If you ever roll your own:
- Read stdin line by line
- Write each response as one line to stdout
- **Never write to stdout from anywhere else** — that corrupts the protocol stream
- **stderr is for logs**
### 3. The `initialize` handshake is mandatory and ordered
Three steps, in order, before any tool call:
1. Client → server: `initialize` request (protocol version, capabilities)
2. Server → client: `initialize` response (protocol version, server capabilities, serverInfo)
3. Client → server: `notifications/initialized` (one-way, no response)
Only after step 3 may the client send `tools/list` or `tools/call`. The SDK enforces this. If you hand-roll, **do not** let `tools/list` succeed before `initialized` arrives — strict clients reject early-tool servers.
### 4. Two error kinds, don't conflate them
- **JSON-RPC errors** (code `-32602` etc.): protocol-level. "Unknown tool", "malformed params". Returned via the JSON-RPC `error` object.
- **Tool execution errors** (`isError: true` inside `result`): runtime. "DB connection failed", "Tool returned no results". The model SEES these and can self-correct.
Mixing them up means the model treats DB outages as unrecoverable system errors. Use `mcp.NewToolResultError(...)` for the latter.
## Minimum viable server (uses official SDK)
```go
package main
import (
"context"
"log"
"os"
"github.com/modelcontextprotocol/go-sdk/mcp"
)
// Tool input. SDK reflects struct tags into JSON Schema 2020-12.
type SearchInput struct {
Query string `json:"query" jsonschema:"description=topic to search"`
Limit int `json:"limit,omitempty" jsonschema:"description=max results,minimum=1,maximum=100"`
}
// Tool output. SDK reflects struct tags into outputSchema if you declare it.
type SearchOutput struct {
Results []map[string]any `json:"results"`
}
// Tool handler. Three returns: optional pre-built result, structured output,
// optional error. SDK builds the standard {content, structuredContent, isError}
// shape automatically.
func studySearch(
ctx context.Context,
req *mcp.CallToolRequest,
in SearchInput,
) (*mcp.CallToolResult, SearchOutput, error) {
// ... query DB, build results ...
return nil, SearchOutput{Results: []map[string]any{}}, nil
}
func main() {
// CRITICAL: pin logger to stderr. Anything to stdout corrupts the protocol.
logger := log.New(os.Stderr, "stewards-mcp: ", log.LstdFlags)
s := mcp.NewServer(&mcp.Implementation{
Name: "pg-ai-stewards",
Version: "0.1.0",
}, nil)
mcp.AddTool(s, &mcp.Tool{
Name: "study_search",
Description: "Find studies in the substrate by topic.",
}, studySearch)
if err := s.Run(context.Background(), &mcp.StdioTransport{}); err != nil {
logger.Fatalf("server.Run: %v", err)
}
}
```
That's a fully spec-compliant tools-only MCP server. Build, register in `.mcp.json`, restart Claude Code session.
## Tool registration patterns
**Tool name regex:** `[A-Za-z0-9_.-]{1,128}`. Slashes and spaces are silently rejected by some clients. Pick a convention (`study_search`, `study.search`, or `study-search`) and stick to it.
**Input schema is auto-generated from the struct.** Use `json:"..."` tags and `jsonschema:"..."` for descriptions, ranges, enums.
**Output schema is optional.** If you declare it, you MUST return `structuredContent` matching it. Strict clients reject mismatches. Either:
- Declare and validate (best for typed APIs)
- Omit and rely on the auto-generated text block (best for free-form results)
**Tool list changes** can be announced at runtime via `notifications/tools/list_changed` if your server has dynamic tool sets. For static tool sets, declare `capabilities.tools.listChanged: false` (the SDK default — don't override unless needed).
## Claude Code integration
Three scopes for registering an MCP server:
| Scope | File | Use for |
|-------|------|---------|
| Project | `.mcp.json` (repo root) | Servers that ship with the project, work for all teammates |
| Local user | `~/.claude.json` | Personal experiments, tools |
| Global user | `~/.claude/settings.json` (rarely used) | System-wide tools |
For project sidecars (the case here), use **`.mcp.json` at repo root**:
```json
{
"mcpServers": {
"pg-ai-stewards": {
"type": "stdio",
"command": "${WORKSPACE_FOLDER}/projects/pg-ai-stewards/bin/stewards-mcp.exe",
"args": ["--dsn", "${STEWARDS_DSN:-postgres://stewards:stewards@localhost:55433/stewards?sslmode=disable}"],
"env": {}
}
}
}
```
Env-var expansion: `${VAR}` and `${VAR:-default}`. Project-scoped servers prompt for approval on first run; clear with `claude mcp reset-project-choices` if testing a config change.
**Restart the Claude Code session** after editing `.mcp.json`. The MCP client only re-reads the config at session start. The skill listing in subsequent turns will then show the new tools.
## Gotchas (recurring failures)
1. **stderr discipline.** Any `fmt.Println` or default-logger call writes to stdout and corrupts the protocol. Pin all logging to `os.Stderr`. Audit dependencies — pgx's default logger writes to stdout in some configurations.
2. **Don't respond to notifications.** `notifications/initialized` and `notifications/cancelled` arrive without `id`. Sending a response is a protocol violation. The SDK handles this; rolled-your-own constantly breaks it.
3. **Tool name characters.** Stick to `[A-Za-z0-9_.-]`. Underscores are safest.
4. **`isError: true` vs JSON-RPC error.** Tool-execution failures use `isError: true` so the model can react. JSON-RPC errors are for protocol violations. `mcp.NewToolResultError(...)` is the SDK helper.
5. **Buffered stdout.** Go's stdout is fully buffered when not connected to a TTY (Claude Code spawns you as a pipe). The SDK flushes after each message. If you write a custom transport, wrap stdout in a `bufio.Writer` and flush every line.
6. **Initialize before tools.** Do not let `tools/list` succeed before `notifications/initialized` arrives. Strict clients enforce ordering.
7. **`outputSchema` is a contract.** If declared, validate matches before sending. Either be rigorous or omit the schema.
8. **First-run approval dialog.** Project-scoped MCP servers prompt the user for approval on first invocation. Document this for teammates so they don't think the server is broken.
9. **pgx connection lifecycle.** Use `pgxpool.New(ctx, dsn)` for connection pooling. Close the pool on `s.Run()` exit. Don't share `*pgx.Conn` across goroutines — use the pool.
10. **Context cancellation.** The SDK passes `context.Context` through to handlers. Honor it. If a tool call is mid-flight and the client cancels, abort cleanly via `ctx.Done()`.
## Real-world references
When in doubt, look at how production Go MCP servers are structured:
- **[subnetmarco/pgmcp](https://github.com/subnetmarco/pgmcp)** — Postgres MCP using the official Go SDK. Closest analog to what we're building. Has CI, Docker, schema fixtures.
- **[mark3labs/mcp-go examples/](https://github.com/mark3labs/mcp-go/tree/main/examples)** — even if you use the official SDK, the example servers are clean reference implementations of the protocol flow.
- **[modelcontextprotocol/go-sdk examples/](https://github.com/modelcontextprotocol/go-sdk/tree/main/examples)** — the official SDK's bundled examples.
## Project-specific (pg-ai-stewards)
**Binary location:** `projects/pg-ai-stewards/cmd/stewards-mcp/main.go`. Compiled to `projects/pg-ai-stewards/bin/stewards-mcp.exe` on Windows.
**Connection string:** `STEWARDS_DSN` env var, defaulting to `postgres://stewards:stewards@localhost:55433/stewards?sslmode=disable` (the docker-compose port mapping).
**First tools to register (Phase 3e.1):**
- `study_search` — wraps `stewards.study_search_text(query, kinds, limit)`, returns matched study slugs + titles + scores
- `study_get` — wraps `stewards.study_get(slug)`, returns body + frontmatter + citations
**Future tools (Phase 3e.2-3e.5):** `gospel_passthrough`, `stewards_brain`, `stewards_work_item`, `gospel_search`, `gospel_get` (the latter two via outbound MCP-client to gospel-engine-v2).
**Findings doc:** `projects/pg-ai-stewards/docs/3e-mcp-findings.md` (created when 3e.1 ships).
---
> Source: [cpuchip/scripture-study](https://github.com/cpuchip/scripture-study) — distributed by [TomeVault](https://tomevault.io).
<!-- tomevault:4.0:skill_md:2026-05-23 -->
章节与文件索引
按说明文件中的顺序排列。
何时加载
1.使用官方Go SDK
2. stdio 传输是换行符分隔的 JSON
3、初始化握手是强制的、有序的
4.两种错误,不要混为一谈
文件/命令 -> modelcontextprotocol/go-sdk · projects/pg-ai-stewards/cmd/stewards-mcp/ · github.com/modelcontextprotocol/go-sdk · Content-Length · mcp.StdioTransport{} · initialize · notifications/initialized · tools/list
内容校验值 -> 80028225ebc5
当前原文的自动摘译,尚未人工审校。
何时加载
在
projects/pg-ai-stewards/cmd/stewards-mcp/中编辑或构建 Go 代码 将新的 MCP 工具添加到现有服务器 将新的 MCP 服务器连接到 Claude Code 或另一个 MCP 客户端 点击“工具未找到”/“JSON-RPC 错误”/静默连接失败 读取另一个项目的 MCP 服务器代码以了解其形状1.使用官方Go SDK
github.com/modelcontextprotocol/go-sdk— 由 Anthropic 和 Google 共同维护。 v1.6.0 截至 2026 年 5 月 8 日。来自结构标签的模式反射、传输处理、能力协商、错误包装全部内置。对于纯工具的 stdio 服务器来说,从头开始在 Go 中大约需要 250 行;使用 SDK 约为 30。使用 SDK。2. stdio 传输是换行符分隔的 JSON
不是具有
Content-Length标头的 LSP 样式。每行一条 JSON-RPC 消息,禁止在消息内嵌入换行符。 SDK 通过mcp.StdioTransport{}为您处理此问题。如果您曾经自己推出过: 逐行读取 stdin 将每个响应作为一行写入到 stdout 切勿从其他任何地方写入 stdout - 这会破坏协议流 stderr 用于日志3、初始化握手是强制的、有序的
在任何工具调用之前,按顺序执行三个步骤: 客户端 → 服务器:
initialize请求(协议版本、功能) 服务器 → 客户端:initialize响应(协议版本、服务器功能、服务器信息) 客户端 → 服务器:notifications/initialized(单向,无响应) 只有在第 3 步之后,客户端才可以发送tools/list或tools/call。 SDK 强制执行此操作。如果你手卷,不要让tools/list在initialized到达之前成功——严格的客户端拒绝早期工具服务器。4.两种错误,不要混为一谈
JSON-RPC 错误(代码
-32602等):协议级别。 “未知工具”,“格式错误的参数”。通过 JSON-RPCerror对象返回。工具执行错误(result内的isError: true):运行时。 “数据库连接失败”,“工具未返回结果”。模型看到这些并且可以自我纠正。将它们混合在一起意味着模型将数据库中断视为不可恢复的系统错误。对于后者使用mcp.NewToolResultError(...)。