Token导航 LogoToken导航TokenDH.com
Go Guard logo
安全风控stdio官方级别未说明来源级核验

Go Guard

MCP Server

GoGuard是一款高性能的静态代码分析引擎,用于在运行时之前捕获nil/null解引用、未处理的错误、并发风险、资源泄漏和安全漏洞。

工具数

13

提示词数

0

GitHub Stars

1

资源数

0
静态分析RustClaudeClaudeCursorWindsurfVS Code

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

作者 / 组织

NextStat

提供方

NextStat

最后核验

2026/5/17 20:22

快速接入

先看主来源和安装命令,再打开仓库或文档;下面只保留这个条目的关键接入事实。

命令预览

pip install goguard

详细介绍

GoGuard

Go+TypeScript的数学数据流安全。

GoGuard是一个高性能的静态分析引擎,可以在运行前捕获nil/null解引用、未处理的错误、并发危险、资源泄漏和安全漏洞。

使用Rust分析核心构建,通过FlatBuffers桥(Go→ IR → Rust),GoGuard通过模型上下文协议(MCP)支持快速增量分析和AI代理工作流。

开源。麻省理工学院/阿帕奇-2.0。

创建者: NexStat项目.

______________________________________________________________________

目录

- 戈加德检查 - 戈加德汽车修理 - 戈加德修复 - 戈加德解释 - goguard查询 - 护目镜热 - goguard技能安装 - goguard设置 - 高加德发球 - goguard更新 - goguard更新代理md - 戈加德sdk

- goguard.toml参考 - 无模型 - 内联注释

- 无安全性(NIL001–NIL006) - 错误检查(ERR001–ERR002) - 并发(RACE001–RACE002,LEAK001–LEAK002,CHAN001–CHAN002) - 资源生命周期(OWN001–OWN004) - 彻底性(EXH001–EXH003) - Taint分析(TAINT001–TAINT004)

- 克劳德代码 - 光标 - 帆板运动 - 法典 - 泽德 - 开源代码 - VS代码(LSP) - MCP工具参考

______________________________________________________________________

为什么选择GoGuard?

Go的编译器可以捕获语法和类型错误,但允许出现一整类运行时恐慌和微妙的错误:

问题示例发生了什么
无指针解引用user, _ := GetUser(id); fmt.Println(user.Name)恐慌 运行时
默认忽略错误os.Open("/etc/passwd")Bug永远隐藏
数据竞争go func() { count++ }()间歇性腐败
Goroutine泄漏go func() { for { ... } }()内存泄漏,OOM
资源泄漏f, _ := os.Open(path) --没有 defer f.Close()文件描述符耗尽
SQL注入db.Query("SELECT * FROM users WHERE id=" + input)安全漏洞

GoGuard可以使用Go的SSA表单上的抽象解释(定点正向数据流分析)静态地捕捉这些问题。结果是保守的:目标是尽量减少假阴性和假阳性,但也有权衡。

主要特点

  • 22条分析规则 跨越6个类别(无、错误、并发、所有权、穷尽性、污染)
  • 快速增量分析 --电源由 莎莎舞 SHA-256桥接缓存
  • 差异感知模式 --仅分析受git更改影响的包
  • 人工智能原生 --用于Claude Code、Cursor、Windsurf、Codex、Zed、OpenCode的一流MCP服务器
  • 自动修复编排器 --自主分析→ fix → 构建→ test → 重复循环
  • 代码模式 --代理编写JavaScript来查询IR、调用图和诊断
  • SARIF输出 --与GitHub安全选项卡、CodeQL、SonarQube集成
  • 零拷贝FlatBuffers桥接器 --去吧 go/ssa 进行解析,Rust进行分析
  • 开发包 --非MCP代理的子流程包装器

______________________________________________________________________

安装

来源(需要Rust+Go)

# Clone
git clone https://github.com/NextStat/GoGuard.git
cd GoGuard

# Build Rust core
cargo build --release

# Build Go bridge
cd goguard-go-bridge && go build -o goguard-go-bridge && cd ..

# Install both binaries
cp target/release/goguard /usr/local/bin/
cp goguard-go-bridge/goguard-go-bridge /usr/local/bin/

来自GitHub发布

从下载适用于您平台的预构建二进制文件 发布:

# macOS (Apple Silicon)
curl -sSL https://github.com/NextStat/GoGuard/releases/latest/download/goguard-darwin-arm64.tar.gz | tar xz
sudo mv goguard goguard-go-bridge /usr/local/bin/

# macOS (Intel)
curl -sSL https://github.com/NextStat/GoGuard/releases/latest/download/goguard-darwin-amd64.tar.gz | tar xz
sudo mv goguard goguard-go-bridge /usr/local/bin/

# Linux (x86_64)
curl -sSL https://github.com/NextStat/GoGuard/releases/latest/download/goguard-linux-amd64.tar.gz | tar xz
sudo mv goguard goguard-go-bridge /usr/local/bin/

自我更新

goguard update

验证安装

goguard --version
# goguard 0.1.0 (abc1234)
先决条件: 必须安装Go工具链(1.22+)。GoGuard使用 go/packages 在引擎盖下通过桥接二进制。

______________________________________________________________________

快速开始

# Navigate to any Go project
cd ~/my-go-project

# Initialize GoGuard (creates goguard.toml + AGENTS.md + CLAUDE.md + Agent Skills)
goguard init

# Analyze your code
goguard check ./...

# See what changed since last commit
goguard check --diff ./...

# Get a detailed explanation of any rule
goguard explain NIL001

# Auto-fix all critical issues (with test verification)
goguard auto-fix --severity critical --test

# Output SARIF for CI/GitHub Security tab
goguard check --format sarif ./... > results.sarif

输出示例:

  ⚠ NIL001 handler.go:18:22 — nil pointer dereference
    user may be nil (from GetUser return)
    confidence: 0.95

  ✗ ERR001 server.go:42:5 — error return value not checked
    db.Close() returns error, which is ignored

  ⚠ TAINT001 api.go:55:12 — SQL injection
    tainted data flows from r.URL.Query().Get("id") to db.Query()

Found 3 issues (1 critical, 1 error, 1 warning) in 0.14s

______________________________________________________________________

CLI参考

goguard check

分析Go包的安全问题。

goguard check [OPTIONS] [PACKAGES...]

论据:

参数默认值描述
PACKAGES./...Go包进行分析

选项:

标志默认值描述
--diffoff仅分析已更改的包 .go git工作树中的文件
--format human输出格式: human, json, sarif, markdown (或 md)
--severity (all)要报告的最低严重程度: info, warning, error, critical
--max-diagnostics 100要报告的最大诊断数(0=无限制)
--strict-paramsoff将可忽略的参数视为MaybeNil(更多发现可能会增加误报)
--no-cacheoff禁用网桥缓存
--cache-dir auto覆盖网桥缓存目录
--no-color关闭禁用彩色输出

示例:

# Analyze entire project
goguard check ./...

# Only critical issues, JSON output
goguard check --severity critical --format json ./...

# CI pipeline — SARIF for GitHub Security tab
goguard check --format sarif ./... > results.sarif

# Diff-aware (only changed packages) — perfect for pre-commit hooks
goguard check --diff ./...

# Analyze a specific package
goguard check ./internal/handler

# Strict nil checking (catches more bugs, may have false positives)
goguard check --strict-params ./...

# Markdown output for AI agents
goguard check --format md ./...

退出代码:

代码含义
0未发现问题
1发现的问题
2使用错误

______________________________________________________________________

goguard auto-fix

自主修复循环:分析→ 生成修复程序→ 应用→ go buildgo test → 重复。

goguard auto-fix [OPTIONS] [PACKAGES...]

选项:

标志默认值描述
--severity error要修复的最小严重性
--max-iterations 10最大修复循环迭代次数
--max-fixes 50要应用的最大修复数
--max-time-secs 300时间预算(秒)(0=无限制)
--test关闭运行 go test 每次迭代后
--dry-runoff预览修复而不应用
-v, --verboseoff显示详细进度

示例:

# Fix all critical issues, verify with tests
goguard auto-fix --severity critical --test

# Preview what would be fixed (no changes)
goguard auto-fix --dry-run

# Quick mode — fix up to 5 issues, no tests, 60s budget
goguard auto-fix --max-fixes 5 --max-time-secs 60

# Fix a specific package
goguard auto-fix ./internal/handler

# Verbose output to see each iteration
goguard auto-fix -v --test

它是如何工作的:

  1. 分析项目
  2. 优先诊断(关键→ 错误→ 警告,尊重依赖顺序)
  3. 生成并应用修复(代码编辑)
  4. go build ./... --失败时,回滚修复并跳过
  5. 可选运行 go test ./... --关于失败、回滚和跳过
  6. 重复,直到预算用尽或没有更多可解决的问题

输出示例:

Iteration 1/10: analyzing...
  Fixed NIL001 handler.go:18 — added nil check
  go build: OK
  go test: OK (47 pass, 0 fail, 3 skip)

Iteration 2/10: analyzing...
  Fixed ERR001 server.go:42 — added error handling
  go build: OK
  go test: OK

Result: 2 fixes applied, 0 skipped
  Before: { critical: 3, error: 5, warning: 8 }
  After:  { critical: 1, error: 4, warning: 8 }
  Build: pass | Tests: 47 pass, 0 fail
  Time: 12.4s

______________________________________________________________________

goguard fix

为特定诊断生成并可选择应用修复程序。

goguard fix  [OPTIONS]

选项:

标志描述
--apply将修复程序直接写入磁盘
--patch输出统一差分(管道至 patch -p0)
--verify申请确认修复工程后重新分析

示例:

# Show the fix (preview)
goguard fix "NIL001-handler.go:18"

# Apply and verify
goguard fix "NIL001-handler.go:18" --apply --verify

# Generate a patch file
goguard fix "NIL001-handler.go:18" --patch > fix.patch
patch -p0 

示例:

goguard explain NIL001
goguard explain ERR001
goguard explain TAINT001
goguard explain OWN004

输出示例:

NIL001: Nil pointer dereference

A value that may be nil is used in a context that would cause a
runtime panic (field access, method call, index, etc.).

Example:
  user, _ := GetUser(id)
  fmt.Println(user.Name) // user may be nil

Fix: Check for nil before use:
  if user != nil {
      fmt.Println(user.Name)
  }

______________________________________________________________________

goguard query

根据分析结果运行GoGuard QL查询。支持交互式REPL模式。

goguard query [OPTIONS] [EXPRESSION]

选项:

标志描述
--repl交互模式——分析一次,运行多个查询
--project-dir 项目目录(默认:当前)

示例:

# Single query
goguard query 'diagnostics where severity == "critical"'

# Interactive REPL
goguard query --repl

# Inside the REPL:
> diagnostics where severity == "critical"
> diagnostics where rule == "NIL001"
> count
> callers of "(*Server).handleRequest"
> taint paths from "http.Request" to "database/sql"
> help
> quit

GoGuard QL语法:

查询描述
diagnostics列出所有诊断
diagnostics where severity == "critical"按严重程度筛选
diagnostics where rule == "NIL001"按规则筛选
diagnostics where file contains "handler"按文件名筛选
count统计当前诊断
callers of "pkg.FuncName"在调用图中显示调用者
taint paths from "source" to "sink"追踪污染传播
help显示所有命令

______________________________________________________________________

goguard init

在当前项目中初始化GoGuard(一次性设置)。

创建:

  • goguard.toml
  • AGENTS.md (若缺失)
  • CLAUDE.md (若缺失)
  • 由安装的第一方代理指导(SKILL.md+光标规则+Windsurf工作流) goguard init
goguard init

如果 goguard.toml 已经存在, goguard init 退出时出错(它不会覆盖)。 对于现有项目,使用 goguard skills installgoguard update-agents-md.

配置 对于所有选项。

______________________________________________________________________

goguard skills install

在项目中安装(或更新)第一方代理技能。

goguard skills install [--project-dir ] [--targets 
] [--update true|false]
  • --targets 是一个逗号分隔的列表: github, claude, opencode, agents, windsurf,或 all.
  • 默认目标为 claude,opencode,agents.

示例:

# Update/reinstall skills in default locations
goguard skills install --update

# Also install into Windsurf + visible repo tree
goguard skills install --targets cursor,windsurf,github --update

______________________________________________________________________

goguard setup

打印即可复制您的AI工具或编辑器的MCP/LSP配置。

goguard setup 

支持的目标: claude-code, cursor, windsurf, codex, zed, opencode, vscode

# Print config for Claude Code
goguard setup claude-code

# Print config for Cursor
goguard setup cursor

AI代理集成 有关完整的设置说明。

______________________________________________________________________

goguard serve

将GoGuard作为长时间运行的服务器(MCP或LSP)启动。

goguard serve [OPTIONS]
标志描述
--mcp以MCP服务器启动(适用于AI代理)
--lsp以LSP服务器启动(适用于编辑器)
# MCP server (usually called by the AI tool, not directly)
goguard serve --mcp

# LSP server
goguard serve --lsp

______________________________________________________________________

goguard update

自更新GoGuard至GitHub发布的最新版本。

goguard update

______________________________________________________________________

goguard update-agents-md

更新或创建项目中的GoGuard部分 AGENTS.md 文件,为AI代理提供有关项目分析结果和约定的上下文。

goguard update-agents-md [--path AGENTS.md]

______________________________________________________________________

goguard sdk

用于非MCP集成的SDK生成和CLI工具接口。

# Generate Python SDK
goguard sdk generate python

# Call an MCP tool via CLI (for SDK integration)
goguard sdk call  --params '' [--project-dir ]

示例:

# Analyze via SDK call
goguard sdk call goguard_analyze --params '{"packages": ["./..."]}'

# Explain a rule
goguard sdk call goguard_explain --params '{"rule": "NIL001"}'

# Fix a diagnostic
goguard sdk call goguard_fix --params '{"diagnostic_id": "NIL001-handler.go:18"}'

______________________________________________________________________

配置

goguard.toml 参考

GoGuard正在寻找 goguard.toml 在当前目录中,并向上遍历父目录。创建一个 goguard init.

[goguard]
# Minimum severity to report: "info", "warning", "error", "critical"
severity_threshold = "warning"

# Skip files starting with "// Code generated" (default: true)
skip_generated = true

# Maximum diagnostics to report (0 = unlimited)
# max_diagnostics = 0

# Bridge cache directory (auto-detected if omitted)
# cache_dir = "~/.cache/goguard/bridge-cache"

# Maximum cached bridge outputs to retain
# max_cache_entries = 20

# Disable bridge caching entirely
# no_cache = false

# ───────────────────────────────────────────────
# Nil Safety
# ───────────────────────────────────────────────
[rules.nil]
enabled = true

# Strict parameter mode (default: false).
# When false: all pointer parameters are assumed NonNil (fewer reports, may miss bugs).
# When true:  nilable parameters start as MaybeNil. GoGuard then applies entrypoint
#             models for known frameworks (net/http, gin, echo, fiber, grpc, testing)
#             to seed handler params back to NonNil — so framework handlers stay clean,
#             but internal functions that receive nil pointers are caught.
# strict_params = false

# User-provided nil models.
# Tell GoGuard whether specific functions return nil or not.
# Values: "nonnull" (never returns nil), "nilable" (can return nil)
# For multi-return functions, append #: "os.Open#0" = the *File return.
[rules.nil.models]
# "mycompany/internal/db.GetDB" = "nonnull"
# "mycompany/internal/cache.Get#0" = "nilable"
# "context.WithCancel#0" = "nonnull"

# ───────────────────────────────────────────────
# Error Checking
# ───────────────────────────────────────────────
[rules.errcheck]
enabled = true
# Glob patterns for functions whose error returns can be safely ignored
ignore = ["fmt.Print*", "fmt.Fprint*"]

# ───────────────────────────────────────────────
# Concurrency Analysis
# ───────────────────────────────────────────────
[rules.concurrency]
enabled = true

# ───────────────────────────────────────────────
# Resource Lifecycle / Ownership
# ───────────────────────────────────────────────
[rules.ownership]
enabled = true

# ───────────────────────────────────────────────
# Exhaustiveness Checking
# ───────────────────────────────────────────────
[rules.exhaustive]
enabled = true

# ───────────────────────────────────────────────
# Taint Analysis (Security)
# ───────────────────────────────────────────────
[rules.taint]
enabled = true

无模型

Nil模型让你告诉GoGuard它无法分析的函数(外部包、C绑定等)的Nil返回行为。

[rules.nil.models]
# Single-return: function never returns nil
"mycompany/pkg.NewClient" = "nonnull"

# Multi-return: the *File at index 0 is never nil when err==nil
# (GoGuard already handles the Go error convention for stdlib,
#  but for your own code you may need to specify)
"mycompany/pkg.Open#0" = "nonnull"

# Explicitly mark a function as possibly returning nil
"mycompany/pkg.FindUser#0" = "nilable"

内置stdlib模型 (无需配置):

GoGuard附带了用于常见stdlib功能的模型,包括 context.Background(), context.TODO(), context.WithCancel(), context.WithTimeout(), context.WithValue(), bytes.NewBuffer(), bytes.NewBufferString(), strings.NewReader(), errors.New(), fmt.Errorf(), json.NewEncoder(), json.NewDecoder()以及更多。

内联注释

在下一行或同一行中抑制特定诊断:

//goguard:nonnull
user := GetUser(id) // GoGuard will treat this as non-nil

result := riskyCall() //goguard:nonnull
注: 注释通过从磁盘读取Go源文件来工作。文件路径必须可以从工作目录解析。

______________________________________________________________________

分析规则

无安全性

规则严重性描述
NIL001关键无指针引用。 在可能导致运行时恐慌的上下文中使用可能为nil的值(字段访问、方法调用、索引、切片)。
NIL002关键未检查的类型断言。 x.(string) 如果没有逗号,ok模式会在断言失败时恐慌。
NIL004警告/严重无地图访问权限。 从nil映射读取返回零值(警告)。写一个无映射恐慌(关键)。
NIL006关键无通道操作。 在nil通道上发送或接收会永远阻塞,导致goroutine死锁。

NIL001——无指针引用:

// ✗ BAD: user may be nil
user, _ := GetUser(id)
fmt.Println(user.Name) // ← NIL001: nil pointer dereference

// ✓ GOOD: nil check before use
user, err := GetUser(id)
if err != nil {
    return err
}
fmt.Println(user.Name) // safe

NIL002——未检查的类型断言:

// ✗ BAD: panics if x is not a string
s := x.(string) // ← NIL002

// ✓ GOOD: comma-ok pattern
s, ok := x.(string)
if !ok {
    return errors.New("not a string")
}

NIL004-无地图访问:

// ✗ BAD: writing to nil map panics
var m map[string]int
m["key"] = 42 // ← NIL004: panic

// ✓ GOOD: initialize the map
m := make(map[string]int)
m["key"] = 42

______________________________________________________________________

错误检查

规则严重性描述
ERR001错误未检查错误返回值。 函数返回错误,但该返回被丢弃。
ERR002警告分配给空白标识符时出错。 该错误被明确地丢弃 _.
// ✗ BAD: error completely ignored
os.Open("/tmp/file") // ← ERR001

// ✗ BAD: error explicitly discarded
f, _ := os.Open("/tmp/file") // ← ERR002

// ✓ GOOD: error properly checked
f, err := os.Open("/tmp/file")
if err != nil {
    return fmt.Errorf("opening file: %w", err)
}
defer f.Close()

忽略特定功能:

[rules.errcheck]
ignore = ["fmt.Print*", "fmt.Fprint*", "(*log.Logger).Print*"]

______________________________________________________________________

并发

数据竞争

规则严重性描述
赛马001错误goroutine中的共享变量访问。 封闭作用域中的变量在不同步的情况下在goroutine中访问。
赛马002错误Goroutine捕获循环变量。 goroutine通过引用捕获循环变量——所有goroutine都会看到最终值。
// ✗ BAD: data race on count
count := 0
go func() { count++ }() // ← RACE001

// ✓ GOOD: use atomic
var count int64
go func() { atomic.AddInt64(&count, 1) }()
// ✗ BAD: all goroutines see the last item
for _, v := range items {
    go func() { process(v) }() // ← RACE002
}

// ✓ GOOD: pass as argument
for _, v := range items {
    go func(v Item) { process(v) }(v)
}

Goroutine泄漏

规则严重性描述
泄漏001警告Goroutine可能永远不会终止。 没有可见的终止路径(没有上下文、没有通道关闭、没有返回)。
泄漏002警告频道已创建,但从未使用过。 一个频道被分配了 make() 但从未发送或接收。
// ✗ BAD: goroutine runs forever
go func() { // ← LEAK001
    for {
        doWork()
    }
}()

// ✓ GOOD: use context for cancellation
go func(ctx context.Context) {
    for {
        select {
        case <-ctx.Done():
            return
        default:
            doWork()
        }
    }
}(ctx)

渠道问题

规则严重性描述
CHAN001关键在可能关闭的频道上发送。 运行时出现恐慌。
CHAN002警告选择无默认案例。 可能无限期封锁。

______________________________________________________________________

资源生命周期

规则严重性描述
OWN001错误资源已打开,但从未关闭。 文件、连接等泄漏。
下载002关键关闭后使用。 之后使用的资源 Close().
拥有003关键双重关闭。 资源关闭不止一次——可能会恐慌。
下载004警告资源关闭未推迟。 如果代码在打开和关闭之间出现恐慌,资源就会泄漏。
// ✗ BAD: f is never closed (OWN001)
f, err := os.Open(path)
if err != nil { return err }
data, _ := io.ReadAll(f)

// ✗ BAD: not using defer (OWN004)
f, err := os.Open(path)
if err != nil { return err }
data, _ := io.ReadAll(f)
f.Close() // if ReadAll panics, f leaks

// ✓ GOOD
f, err := os.Open(path)
if err != nil { return err }
defer f.Close()
data, _ := io.ReadAll(f)

______________________________________________________________________

精疲力竭

规则严重性描述
EXH001警告类型开关缺少接口实现器。 并非所有实现接口的类型都涵盖在内。
EXH002警告枚举开关缺少常数值。 并非所有枚举常量都会被处理。
EXH003资讯非穷举开关中缺少默认情况。
type Shape interface { Area() float64 }
type Circle struct { ... }
type Square struct { ... }
type Triangle struct { ... } // new type added

// ✗ BAD: Triangle not handled (EXH001)
switch s := shape.(type) {
case *Circle:  ...
case *Square:  ...
}

// ✓ GOOD: exhaustive or explicit default
switch s := shape.(type) {
case *Circle:   ...
case *Square:   ...
case *Triangle: ...
}

______________________________________________________________________

污点跟踪分析技术

规则严重性描述
污点001关键SQL注入。 受污染的数据流向SQL查询。
污点002关键指令注入。 受污染的数据流 exec.Command.
污点003错误路径遍历。 受污染的数据流向文件路径操作。
污点004错误跨站脚本(XSS)。 受污染的数据流到HTML输出。
// ✗ BAD: SQL injection (TAINT001)
id := r.URL.Query().Get("id")
db.Query("SELECT * FROM users WHERE id=" + id)

// ✓ GOOD: parameterized query
id := r.URL.Query().Get("id")
db.Query("SELECT * FROM users WHERE id=$1", id)
// ✗ BAD: command injection (TAINT002)
cmd := exec.Command("sh", "-c", userInput)

// ✓ GOOD: pass as separate arguments
cmd := exec.Command("grep", "-r", userInput, "/safe/dir")
// ✗ BAD: path traversal (TAINT003)
path := filepath.Join("/uploads", userInput)
os.ReadFile(path) // userInput = "../../etc/passwd"

// ✓ GOOD: validate the resolved path
path := filepath.Join("/uploads", filepath.Clean(userInput))
if !strings.HasPrefix(path, "/uploads/") {
    return errors.New("invalid path")
}

______________________________________________________________________

人工智能代理集成(MCP)

GoGuard公开了一个功能齐全的MCP(模型上下文协议)服务器。AI编码代理可以分析代码、获取解释、应用修复程序和运行查询——所有这些都是通过编程实现的。

克劳德代码

# Print the config snippet
goguard setup claude-code

增添 .mcp.json 在您的项目目录中(或 ~/.claude.json 全球):

{
  "mcpServers": {
    "goguard": {
      "command": "/usr/local/bin/goguard",
      "args": ["serve", "--mcp"]
    }
  }
}

光标

goguard setup cursor

增添 .cursor/mcp.json:

{
  "mcpServers": {
    "goguard": {
      "command": "/usr/local/bin/goguard",
      "args": ["serve", "--mcp"]
    }
  }
}

帆板运动

goguard setup windsurf

增添 ~/.codeium/windsurf/mcp_config.json:

{
  "mcpServers": {
    "goguard": {
      "command": "/usr/local/bin/goguard",
      "args": ["serve", "--mcp"]
    }
  }
}

法典

goguard setup codex

增添 ~/.codex/config.toml:

[mcp_servers.goguard]
command = "/usr/local/bin/goguard"
args = ["serve", "--mcp"]

泽德

goguard setup zed

增添 ~/.config/zed/settings.json:

{
  "context_servers": {
    "goguard": {
      "command": "/usr/local/bin/goguard",
      "args": ["serve", "--mcp"]
    }
  }
}

开源代码

goguard setup opencode

增添 opencode.json:

{
  "mcp": {
    "goguard": {
      "type": "local",
      "command": ["/usr/local/bin/goguard", "serve", "--mcp"],
      "enabled": true
    }
  }
}

VS代码(LSP)

goguard setup vscode

GoGuard还可以作为LSP服务器运行,用于标准编辑器集成:

{
  "goguard.path": "/usr/local/bin/goguard",
  "goguard.lsp.enabled": true,
  "goguard.lsp.args": ["serve", "--lsp"]
}

MCP工具参考

当作为MCP服务器连接时,GoGuard向AI代理公开以下工具:

工具说明
goguard_analyze对包运行分析。返回轻量级的“骨架”诊断(每个约50个令牌)以保留上下文窗口。
goguard_explain获取特定诊断的完整详细信息(解释、代码上下文、爆炸半径)。
goguard_fix生成并可选择应用修复程序。默认情况下自动验证。
goguard_verify重新分析特定文件以确认修复工作
goguard_batch按依赖关系顺序为多个诊断应用修复程序,最后验证一次。
goguard_rules列出所有可用的分析规则及其说明。
goguard_query根据分析结果运行GoGuard QL查询。
goguard_search探索GoGuard的API、规则目录、IR模式和示例。代理人的“说明书”。
goguard_execute根据分析数据(调用图、诊断、IR)运行JavaScript代码。代码模式。
goguard_autofix带有进度通知的长时间运行的自动修复循环。
goguard_snapshot保存/比较/差异分析快照(之前/之后)。
goguard_teach教GoGuard函数的nil返回行为(通过启发的用户模型)。

骨架与完整输出:

goguard_analyze 默认情况下返回轻量级骨架(每个诊断约50个令牌),保留代理的上下文窗口:

{
  "id": "NIL001-handler.go:18",
  "rule": "NIL001",
  "severity": "critical",
  "title": "nil pointer dereference",
  "location": {"file": "handler.go", "line": 18, "column": 22},
  "fix_available": true
}

然后,代理人打电话来 goguard_explaingoguard_fix 仅用于它想要调查的诊断——避免上下文窗口膨胀。

______________________________________________________________________

开发包

对于不使用MCP的AI代理(例如基于Python的CodeAct代理),GoGuard提供了一个基于子流程的Python SDK。

安装

pip install goguard

用法

from goguard import GoGuard

g = GoGuard("/path/to/go/project")

# Analyze
result = g.analyze(severity="error")
for d in result.diagnostics:
    print(f"{d.rule} {d.location.file}:{d.location.line} — {d.title}")

# Get full details
detail = g.explain(result.diagnostics[0].id)

# Fix a diagnostic
fix = g.fix(result.diagnostics[0].id)
fix.apply()  # writes to disk

# Auto-fix all errors
report = g.auto_fix(severity="error", dry_run=True)
print(f"Would fix {report.fixes_applied} issues")

# Run JavaScript against analysis data (Code Mode)
result = g.execute("goguard.diagnostics().length")
print(result.output)

# Query with GoGuard QL
result = g.query('diagnostics where severity == "critical"')

API 参考

方法返回描述
analyze()AnalysisResult运行静态分析
explain(id)dict完整的诊断详细信息
fix(id)FixResult生成并验证修复
batch(...)BatchResult批量修复多个诊断
auto_fix(...)AutoFixResult全自动修复编排器
snapshot(...)dict保存/比较分析快照
rules(...)list[Rule]列出可用规则
search(code)SearchResult通过JavaScript探索API
execute(code)ExecuteResult对分析数据运行JS
query(expr)QueryResultGoGuard QL或JavaScript查询

______________________________________________________________________

建筑

┌──────────────────────────────────────────────────┐
│  goguard-go-bridge  (Go, "Fat Bridge")           │
│                                                  │
│  go/packages.Load() → go/types → go/ssa          │
│      ↓                                           │
│  SSA + CFG + Call Graph + Interface Table         │
│      ↓                                           │
│  Serialize → FlatBuffers IR                       │
└───────────────────┬──────────────────────────────┘
                    │ stdio
                    ▼
┌──────────────────────────────────────────────────┐
│  goguard  (Rust, analysis core)                  │
│                                                  │
│  Decode IR → Salsa DB                             │
│      ↓                                           │
│  Analysis passes:                                │
│    • Nil lattice (forward dataflow, fixpoint)    │
│    • Errcheck (error variable tracking)          │
│    • Concurrency (goroutine + shared state)      │
│    • Ownership (resource state machine)          │
│    • Exhaustiveness (enum/interface coverage)    │
│    • Taint (source → sink propagation)           │
│      ↓                                           │
│  Diagnostics → Formatters (human/JSON/SARIF/MD)  │
│      ↓                                           │
│  Output: CLI / MCP server / LSP server / Pipe    │
└──────────────────────────────────────────────────┘

为什么是两种语言?

  • 处理Go最擅长的一切:解析Go代码、类型检查、SSA构造。我们使用Go官方 go/packagesgo/ssa --这场战斗在数百万个Go项目上进行了测试。
  • 处理Rust最擅长的一切:并行数据流分析、增量缓存(Salsa)、丰富的诊断(ariadne)、LSP/MCP服务器基础设施(tower LSP、rmcp)。

FlatBuffers电桥 高效地连接它们:Go构建类型化程序图,Rust对其进行分析。

______________________________________________________________________

贡献

我们欢迎社区捐款!请阅读我们的 贡献.md 了解详情。

文档

  • 配置指南 --满 goguard.toml 引用、内联注释、CI/CD示例
  • 分析规则 --所有22条具有严重性的规则,Go代码示例,修复模式
  • MCP集成 --Claude Code、Cursor、Windsurf、Codex、Zed、OpenCode、VS Code的设置;带参数的MCP工具

快速启动:

# Run Rust tests
cargo test --workspace

# Run Go bridge tests
cd goguard-go-bridge && go test ./...

# Check formatting and lints
cargo fmt --check
cargo clippy -- -D warnings

______________________________________________________________________

许可证

双重许可 麻省理工学院Apache 2.0,由您选择。

目录标签

目录标签

静态分析RustClaude本地部署Go语言TypeScript代码安全并发分析

支持客户端

ClaudeCursorWindsurfVS Code

接入字段

传输方式(transport,传输协议)

stdio

鉴权方式(authType,认证方式)

none

工具数量(toolCount,工具数)

13

资源数量(resourceCount,资源数)

0

提示词数量(promptCount,提示词数)

0

权限和风险

stdionone部署方式未说明

接入前请确认传输方式、认证方式和部署位置,并根据实际工具能力限制访问范围。

安装前确认

不要直接授予不必要的文件、网络或账号权限;先核对安装命令和配置内容。

来源信息

继续浏览同类 MCP