toolify

package module
v0.8.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 17, 2026 License: MIT Imports: 2 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

mcp-toolify

English | 简体中文 Go Reference MCP

mcp-toolify turns ordinary Go functions into Model Context Protocol tools. It consists of a code generator and a runtime: the generator reads function signatures and godoc comments, while the runtime serves MCP over Streamable HTTP. It uses the official Go MCP SDK and can run as a standalone server or be embedded in an existing HTTP service.

Core capabilities

  • Annotation-driven generation: add // mcp:tool to an exported function, run go generate, and generate a typed wrapper, input struct, JSON Schema, and registration code.
  • No reflection at runtime: generated wrappers call the target function directly; signature changes are reported by the compiler.
  • Shared runtime: Streamable HTTP, tool registration, token authentication, selector admission, W3C trace context, owner routing, and middleware are provided in one runtime.
  • Plugin policies: auditing, large-result storage, and deployment-specific policies are installed as plugins rather than built into the base.
  • Deployment options: run independently, mount into another HTTP server, or deploy multiple replicas.

How it works

The basic flow is:

// mcp:tool
    ↓ go generate
wrapper, input struct, JSON Schema, RegisterAll
    ↓
toolify.New(..., tools.RegisterAll)   // or tools.NewRegistrar(...) when method tools exist
    ↓
Start(ctx) or Handlers()

Quick start

Requires Go 1.25 or later.

  1. Define a tool function:
package greeter

import "fmt"

// Greet builds a greeting.
//
// param: name — the name to greet
// param: excited — whether to add an exclamation mark
//
// mcp:tool
// mcp:labels=capability=read,risk=none
func Greet(name string, excited bool) (string, error) {
	if name == "" {
		return "", fmt.Errorf("name is required")
	}
	msg := "Hello, " + name
	if excited {
		msg += "!"
	}
	return msg, nil
}
  1. Create mcpgen.yaml in the module:
output:
  dir: ./tools
packages:
  - github.com/you/yourmod/greeter
  1. Add a generation directive in a Go file in the same directory:
//go:generate go run github.com/fzxbl/mcp-toolify/cmd/mcpgen -config ./mcpgen.yaml
  1. Prepare mcp.toml. Token authentication is always enabled, so the file must contain at least one [[tokens]] entry:
[[tokens]]
token = "replace-with-a-random-secret"
name = "readonly-agent"
applicant = "your-id"
allow = ["capability=read,risk=none"]
deny = ["!capability", "!risk"]

To keep the token out of the file, replace token = ... with token_env = "MCP_TOKEN_READONLY" to read it from an environment variable.

  1. Assemble and run the server:
package main
import (
	"context"
	"log"
	toolify "github.com/fzxbl/mcp-toolify"
	"github.com/you/yourmod/tools"
)
func main() {
	r := toolify.New(toolify.Config{Addr: ":8011", ConfigPath: "./mcp.toml"}, tools.RegisterAll)
	if err := r.Start(context.Background()); err != nil {
		log.Fatal(err)
	}
}
go generate ./example/...
go run ./example/cmd/server -addr :8011 -config ./example/conf/mcp.toml
curl -sS localhost:8011 \
  -H 'Authorization: Bearer replace-me-readonly' \
  -H 'Content-Type: application/json' \
  -H 'Accept: application/json, text/event-stream' \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"greeter.greet","arguments":{"name":"world","excited":true}}}'

The runnable example is under example/.

The example also contains a method tool, so it assembles with tools.NewRegistrar(tools.Impls{...}) instead of tools.RegisterAll; see method tools.

Annotation overview

Annotations are written in the godoc comment of an exported function:

  • mcp:tool: expose the function (or a method of an exported type) as an MCP tool. A leading context.Context parameter receives the request context and is not part of the schema. Method tools need a host-supplied instance via tools.NewRegistrar(tools.Impls{...}) (which replaces RegisterAll).
  • mcp:name=<name>: override the default name, which is <package>.<function_name> in snake case.
  • mcp:labels=k=v,k2=v2: attach opaque labels used by registration filters, token admission, and plugins.
  • mcp:bind=<param>:<Type>: bind an interface parameter to a concrete type that can be built from JSON.
  • mcp:import=<path>: import a package needed by a mcp:bind type.
  • mcp:optional=<p1>,<p2>: make the listed parameters optional (not required, null accepted). Pointer parameters are optional automatically.
  • mcp:output=text: emit the return value as plain text (strings verbatim, other values as indented JSON) without structuredContent.
  • param: <name> — <description>: add a description to the generated JSON Schema parameter. Labels are opaque key-value pairs. The base does not assign meaning to custom keys. name and pkg are built-in projected labels; matching overwrites tool-provided values for those keys, so they should not be set manually. Selectors use Kubernetes-style semantics: conditions in one selector are ANDed, selector entries in a list are ORed, and != and notin also match missing keys. An empty selector matches every tool. See the code generation documentation for the complete generation behavior.

Authentication and admission

Token authentication is mandatory. Config.ConfigPath must point to a TOML file containing at least one [[tokens]]; missing configuration or tokens causes startup to fail. Each token controls access with allow and deny selectors:

  • deny takes precedence over allow.
  • A tool matching neither is denied.
  • tools/list and tools/call use the same rules, so visibility and execution stay consistent.
  • HTTP requests use Authorization: Bearer <token>. Caller-provided identity headers are not trusted by default. Enable trust_identity_header only behind a gateway that authenticates the caller and overwrites those headers. Service accounts and robots should use identity = "fixed:<id>" to bind an identity to the token.

Plugin mechanism

A plugin is an ordinary Go package that provides:

func Install(r *runtime.Registry) error

Installation order is middleware onion order: the first installed plugin is outermost. The recommended order is:

audit ▸ policy plugins ▸ spill

audit is normally outermost and delivers call context asynchronously to a host-registered sink. spill is normally innermost and writes oversized results to local storage before returning a summary and access URL. The bundled plugin documentation is available at audit plugin and spill plugin. Deployment-required plugins should be listed in required_plugins; startup fails if any is missing. Plugins run inside the process trust boundary and are not sandboxes: a plugin can rewrite Call.Tool and Call.Args, and those changes affect execution. Install only reviewed plugins. See the plugin development documentation.

Running and embedding

For standalone operation, call r.Start(ctx) and let the runtime create and manage the HTTP server. To embed the runtime in an existing service, call r.Mount(prefix, mountFunc): the host states its mount point once, and the base hands back the MCP endpoint plus every plugin route.

r := toolify.New(cfg, tools.RegisterAll)
defer r.RunStop(context.Background())
if err := r.Mount("/mcp", func(pattern string, h http.Handler) {
	mux.Handle(pattern, h) // routers that need a wildcard append it here: pattern+"*"
}); err != nil {
	log.Fatal(err)
}

The MCP endpoint lands on prefix itself; plugin routes land under prefix + "/plugin". That same prefix also drives the absolute URLs plugins hand to agents and the inter-replica forwarding target, so do not rewrite the pattern inside mountFunc (no extra StripPrefix, no additional prefix) — change the Mount argument instead. Mount also verifies at startup that every owner-routed pattern has a matching route, returning an error when they disagree.

Embedded deployments must call RunStop during shutdown so plugins can release files, connections, and background goroutines. If you need to assemble handlers entirely yourself, r.Handlers() is still available (with no mount prefix, i.e. mounted at the root). See the runtime documentation for lifecycle and configuration details.

All operational logs from the base and plugins (admission denials, tools/list filtering, startup summaries, lost audit events, spill failures) go through Config.Logger, with levels and a logid field. Pass a *slog.Logger directly, or adapt any other logger by implementing its single Log method — see Logging.

Multiple replicas

Stateful resources use owned IDs to encode the owning replica. Register a tool argument with RegisterOwnerRouted(tool, param), or register a plugin route with RegisterOwnerRoutedRoute(pattern, extractor). Requests are forwarded only to peers on the allow-list and are authenticated again on the owner replica.

All replicas must use the same route prefix and configure SelfAddr (this replica's direct host:port, i.e. its identity) plus peer addresses or service discovery correctly; links handed outward come from PublicBaseURL, which may be a domain or VIP. Replica forwarding currently uses plain HTTP and passes through the caller's Bearer token. For cross-host deployments, add TLS between peers or replace pass-through with an internal credential. See the owner routing documentation.

Documentation index

License

MIT, see LICENSE.

Documentation

Overview

Package toolify 把带 `// mcp:tool` 标记的 Go 函数暴露为 MCP(Model Context Protocol)工具。生成器(cmd/mcpgen)扫描注解生成 wrapper 代码,本包提供把这些 wrapper 组装成一个 HTTP MCP server 的最小基座:MCP 协议、带不透明 labels 的工具 注册表、label selector 引擎、token 认证与准入、W3C trace context、owner 路由和一条中间件链。

审计、大结果落盘(spill)、配额、二次确认等能力都是独立插件,按需 Install; 不 Install 的插件不进编译产物。

典型用法:

//go:generate go run github.com/fzxbl/mcp-toolify/cmd/mcpgen -config ./mcpgen.yaml
func main() {
    r := toolify.New(toolify.Config{Addr: ":8080", ConfigPath: "mcp.toml"}, tools.RegisterAll)
    // audit.Install(r) / spill.Install(r) ... 顺序即中间件链的进入顺序
    _ = r.Start(context.Background())
}

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddTool added in v0.7.0

func AddTool[In, Out any](s *mcp.Server, t *mcp.Tool, h mcp.ToolHandlerFor[In, Out],
	pkg string, labels map[string]string)

AddTool 为「非注解生成、运行时注册」的外部工具注册到 MCP server 并登记 labels (准入判据),等同于 runtime.AddTool。必须在处理请求前调用。直接用 mcp.AddTool 注册的工具没有 labels,在 token 准入里一律不可见、不可执行(deny-by-default)。 labels 的 key 语义由配置里的 selector 与插件解释,基座不解释。

func SetPeerProvider added in v0.5.0

func SetPeerProvider(fn func() []string)

SetPeerProvider 注册 owner 路由的动态兄弟副本发现函数(返回可达 host:port 列表)。 多副本部署时用它对接任意服务发现作为反代白名单来源,无需静态配置;传 nil 清除。 静态白名单写在 Config.Peers 里,与本函数互为覆盖,后设置者生效。应在启动 server 前调用。

Types

type Call added in v0.5.0

type Call = runtime.Call

Call 是一次 MCP 请求的上下文,插件中间件的入参。

type Config

type Config = runtime.Config

Config 是 server 启动配置(runtime.Config 的别名,外部只需 import 本包)。

type Handler added in v0.5.0

type Handler = runtime.Handler

Handler 是中间件链上的一环。

type Logger

type Logger = runtime.Logger

Logger 是 Config.Logger 的类型:基座与插件的运维日志都经它输出。 *slog.Logger 直接满足;其它 logger 实现这一个 Log 方法即可。

type Middleware added in v0.5.0

type Middleware = runtime.Middleware

Middleware 是插件唯一的注入点。

type RegisterOptions

type RegisterOptions = runtime.RegisterOptions

RegisterOptions 控制启用哪些生成的工具(按包名 / label selector 过滤)。

type Registrar

type Registrar = runtime.Registrar

Registrar 是生成代码暴露的注册函数类型(通常是生成的 tools.RegisterAll)。

type Registry added in v0.5.0

type Registry = runtime.Registry

Registry 是插件的唯一依赖类型:注册中间件、MCP 工具、HTTP 路由与清理钩子。

func New added in v0.5.0

func New(cfg Config, registrar Registrar) *Registry

New 构造 Registry 并注册生成的工具,返回值交给各插件 Install。

type Result added in v0.5.0

type Result = runtime.Result

Result 是一次调用的结果。

type Subject added in v0.5.0

type Subject = runtime.Subject

Subject 是调用主体(人 + token 用途名 + 插件自定义标注)。

Directories

Path Synopsis
cmd
listtools command
listtools 用 in-memory transport 启动 mcp server,验证暴露给 MCP 客户端 (Cherry Studio / Claude Desktop 等)的完整元数据。
listtools 用 in-memory transport 启动 mcp server,验证暴露给 MCP 客户端 (Cherry Studio / Claude Desktop 等)的完整元数据。
mcpgen command
Package example wires code generation for the runnable sample: `go generate` reads mcpgen.yaml and writes the typed tool wrappers into ./tools.
Package example wires code generation for the runnable sample: `go generate` reads mcpgen.yaml and writes the typed tool wrappers into ./tools.
cmd/server command
Command server 是 mcp-toolify 的组装示例:基座 + spill(大结果落盘)。
Command server 是 mcp-toolify 的组装示例:基座 + spill(大结果落盘)。
greeter
Package greeter 是用 mcp-toolify 暴露工具的最小示例。
Package greeter 是用 mcp-toolify 暴露工具的最小示例。
plugins
audit
Package audit 是审计插件:把每次 MCP 调用的完整上下文交给使用方注册的落地函数。
Package audit 是审计插件:把每次 MCP 调用的完整上下文交给使用方注册的落地函数。
spill
Package spill 是大结果落盘插件:超过阈值的工具返回值写进本地文件,返回值改写为 摘要 + 可下载的 spill id/URL,避免把几十兆内容塞进模型上下文。
Package spill 是大结果落盘插件:超过阈值的工具返回值写进本地文件,返回值改写为 摘要 + 可下载的 spill id/URL,避免把几十兆内容塞进模型上下文。
Package runtime provides the hand-written runtime substrate for the auto-generated MCP tool registrations under mcp/tools.
Package runtime provides the hand-written runtime substrate for the auto-generated MCP tool registrations under mcp/tools.
Package selector 实现 k8s label selector 语法的解析与匹配。
Package selector 实现 k8s label selector 语法的解析与匹配。

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL