mcp

package
v2.0.0 Latest Latest
Warning

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

Go to latest
Published: Oct 22, 2026 License: Apache-2.0 Imports: 38 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// LocalProxyPath 是 stdio 主进程上给「同机其它 stdio 进程」留的转发入口(POST,一次一条 JSON-RPC 消息)。
	// 刻意不放在 /mcp/ 之下:那个前缀归 `/mcp/*path`(路径里带令牌)所有。
	LocalProxyPath = "/mcp-local"
	// LocalProxyKeyHeader 携带钥匙。
	LocalProxyKeyHeader = "X-RelayMesh-Local-Key"
	// LocalProxyHostHeader 携带转发进程自己的主机名(RELAYMESH_HOST_NAME),让每个窗口按自己的身份开会话。
	LocalProxyHostHeader = "X-RelayMesh-Host-Name"
	// LocalProxyInfoFile 是接入凭证在数据目录里的文件名。
	LocalProxyInfoFile = "stdio-hub.json"
)
View Source
const (
	TierRelayMesh = "relaymesh" // 只有治理类工具(默认)
	TierExecMesh  = "execmesh"  // 只有终端类工具
	TierHybrid    = "hybrid"    // 两类都有(自定义)
	TierNone      = "none"      // 什么都没有
)

令牌「档位」,决定 initialize 返回哪一版指引。

View Source
const DefaultTerminalCompatInstructions = `` /* 2154-byte string literal not displayed */

DefaultTerminalCompatInstructions 是开启「ExecMesh 兼容命名」的 ExecMesh 档令牌收到的指引: 与 DefaultTerminalInstructions 同样精简、不含治理文本,只是工具名换成 ExecMesh 的名字。

View Source
const DefaultTerminalFilesInstructions = `【RelayMesh · ExecMesh 文件指引】
本令牌只开放「终端文件」工具 terminal_files(以及只读的 terminal_targets),用来查看、拉取和写入已被人工授权的主机上、令牌允许目录内的文件。每一次调用都会被审计,文件内容不会被 RelayMesh 保存。

- terminal_targets:先调用它,查看本令牌可用的主机(机器码、名称 name、在线状态、系统、家目录与路径分隔符)、每台主机上 terminal_files 此刻是否可用(files / files_blocked),以及允许访问的目录(limits.allowed_paths;limits.whole_fs=true 表示允许整个文件系统)。本令牌不能执行命令,usable=false 只说明这一点。
` + terminalFilesSection + `

使用要点:
1. target 填主机的机器码,或 terminal_targets 里该主机的 name(管理员在 Web 上写的备注;没有备注时是主机名);name 重复(duplicate_name=true)时必须用机器码;令牌只授权了一台主机时可以省略;
2. 路径用绝对路径(Windows 主机用 C:\路径 形式);
3. 需要确认文件完整性时,先 hash,再下载后比对;
4. 被拒绝(path_not_allowed、mode_not_allowed、host_denied 等)请如实向用户报告,不要换用绕过限制的方式重试。`

DefaultTerminalFilesInstructions 是只带文件权限(没有终端执行权限)的令牌收到的精简指引。

View Source
const DefaultTerminalInstructions = `` /* 1989-byte string literal not displayed */

DefaultTerminalInstructions 是「ExecMesh 档」令牌(只带终端权限)在 initialize 时收到的精简指引。 这类令牌没有 interactive_feedback 等治理工具,因此不会收到 RelayMesh 的人机交互治理文本。

View Source
const MaxRequestBytes = 8 << 20

MaxRequestBytes 是一个 MCP 请求体的大小上限。最大的合法请求是带长摘要的 interactive_feedback,远小于此。

View Source
const (
	// MaxStdioMessageSize sets the upper limit for a single JSON-RPC message line (16MB).
	MaxStdioMessageSize = 16 * 1024 * 1024
)
View Source
const ServerInstructions = store.DefaultServerInstructions

ServerInstructions is the fallback constant pointing to store.DefaultServerInstructions

Variables

View Source
var (
	// ErrHubUnreachable:连不上(那个端口没有进程在听)。请求一定没有发出去,可以放心重试,或改由自己接管。
	ErrHubUnreachable = errors.New("连不上本机的 RelayMesh 主进程")
	// ErrHubLost:请求发出后连接断了(主进程中途退出)。这次调用有没有执行未知,不能自动重发。
	ErrHubLost = errors.New("RelayMesh 主进程在处理这次调用时断开了")
	// ErrNotStdioHub:端口那头不是 RelayMesh 的 stdio 主进程(别的程序、常驻服务,或版本太旧没有转发入口)。
	ErrNotStdioHub = errors.New("端口上的服务不是 RelayMesh 的 stdio 主进程")
	// ErrKeyRejected:钥匙文件读到了,但主进程不认(不是同一份数据目录,或主进程刚换人)。
	ErrKeyRejected = errors.New("本机转发入口不接受这把钥匙")
	// ErrNoKey:数据目录里读不到可用的接入凭证。
	ErrNoKey = errors.New("读不到本机转发入口的接入凭证")
)

Functions

func CompatToolNames

func CompatToolNames() []string

CompatToolNames 返回兼容命名下的全部工具名(用于测试与文档)。

func NewLocalProxyKey

func NewLocalProxyKey() (string, error)

NewLocalProxyKey 生成一把 32 字节的随机钥匙(十六进制)。

func ParseAnchor

func ParseAnchor(raw string) (hash, subject string, ok bool)

ParseAnchor 解析 commit 参数,返回小写哈希与单行摘要。

规则:把输入按空白切词,第一个(去掉两侧包裹字符后)匹配 `^[0-9a-f]{7,40}$` 的词是哈希, 其余词按原顺序拼成摘要并截断到 200 个字符。没有任何词匹配时 ok 为 false。

输出一定是单行且不含控制字符 / 不可见格式字符——摘要会被回显到模型可见的响应头里, 绝不能让一个提交标题伪造出新的「头字段」或「=== 标记 ===」行。

func RemoveLocalProxyInfo

func RemoveLocalProxyInfo(dataDir, key string)

RemoveLocalProxyInfo 只在文件里还是这把钥匙时才删除:新的主进程可能已经换了新钥匙,不能被老进程的收尾删掉。

func RunStdio

func RunStdio(ctx context.Context, server *Server, in io.Reader, out io.Writer) error

RunStdio runs the stdio loop for the given MCP Server until EOF or ctx cancellation.

func StdioErrorResponse

func StdioErrorResponse(id any, code int, message string) []byte

StdioErrorResponse 生成一条 JSON-RPC 错误响应(单行 JSON)。转发进程在主进程暂时不可用时用它回复请求。

func TierForPermissions

func TierForPermissions(p model.Permissions) string

TierForPermissions 按权限位推导令牌档位。档位不落库,永远由权限推导,避免两处真源。

func WithClientIP

func WithClientIP(ctx context.Context, ip string) context.Context

WithClientIP 把经可信代理解析后的客户端 IP 放进上下文,由 HTTP 接入层(Gin)在转交给 MCP 服务前调用。 MCP 服务自身不解析 X-Forwarded-For:信任哪些代理是接入层的职责。

func WriteLocalProxyInfo

func WriteLocalProxyInfo(dataDir string, info LocalProxyInfo) error

WriteLocalProxyInfo 把接入凭证原子地写进数据目录(文件权限 0600)。

Types

type CredentialContext

type CredentialContext struct {
	CredentialID   uint
	CredentialName string
	HostName       string
	TokenString    string
	BaseURL        string
	Permissions    model.Permissions
	Source         string // "db_credential", "env_token", "open_access", "local_stdio"

	// 以下字段服务于终端类工具的审计与限额。
	Credential *model.MCPCredential // 数据库凭据的快照;环境变量 / 开放访问 / stdio 来源为 nil
	// ViaCapability 表示这次调用是经「能力 URL」(/mcp/c/<令牌>)进来的;仅用于审计线索。
	ViaCapability bool
	RemoteIP      string // 请求来源 IP(经可信代理解析)
	UserAgent     string // 客户端自报的 User-Agent,只作展示线索,不作身份依据
}

func CredentialFromContext

func CredentialFromContext(ctx context.Context) *CredentialContext

func LocalStdioCredential

func LocalStdioCredential(defaultHost ...string) *CredentialContext

LocalStdioCredential returns the trusted local stdio credential context with full permissions.

type EventNotifier

type EventNotifier interface {
	NotifyNotice(s *model.FeedbackSession)
	NotifyAsk(item *model.ConfirmItem)
}

EventNotifier 接收「没有人在等」的通知来源:非阻塞的 notice 文本(interactive_feedback 的 wait:false)与 async_ask 卡片。 它们是否真的打扰你由通知闸按偏好(免打扰 / 会话静音)决定。约束同 RequestNotifier:立即返回、自行复制字段。

type GroupNotice

type GroupNotice struct {
	GroupID        string
	GroupTitle     string
	MessageID      string
	SenderLabel    string
	Text           string
	MentionsHuman  bool // 点名了你(或 @all):穿透免打扰
	CoolingStarted bool // 这条触发了群冷却:穿透通知你
}

GroupNotice 是群里 Agent 发言的通知素材:交给通知闸决定打不打扰你。

type GroupNotifier

type GroupNotifier interface {
	NotifyGroup(n GroupNotice)
}

GroupNotifier 接收群聊里 Agent 发言的通知出口。实现必须立即返回、自行复制字段。

type LocalForwarder

type LocalForwarder struct {
	// contains filtered or unexported fields
}

LocalForwarder 把 stdio 消息转发给同机另一个 stdio 进程里的 Hub。

func NewLocalForwarder

func NewLocalForwarder(baseURL, dataDir, hostName string) *LocalForwarder

NewLocalForwarder 创建转发端。baseURL 形如 http://127.0.0.1:18775;dataDir 是读接入凭证的数据目录; hostName 是本进程自己的主机名,随每条消息带给主进程,让每个窗口按自己的身份开会话。

func (*LocalForwarder) BaseURL

func (f *LocalForwarder) BaseURL() string

BaseURL 返回主进程的根地址。

func (*LocalForwarder) CheckKey

func (f *LocalForwarder) CheckKey() error

CheckKey 确认数据目录里能读到接入凭证(不发网络请求)。

func (*LocalForwarder) CloseIdleConnections

func (f *LocalForwarder) CloseIdleConnections()

CloseIdleConnections 丢掉连接池里闲置的连接。主进程退出后,传输层要等读循环看到对端关闭才会把闲置连接作废; 在这个空档里发的请求会写进一条已经半关的连接,得到「发出去后断了」(ErrHubLost:结果未知、不能自动重发)。 真实场景里主进程退出与下一次调用之间隔着很久,空档早已过去;测试要「主进程刚走、立刻再调用」时,先调用它把空档收掉。

func (*LocalForwarder) Forward

func (f *LocalForwarder) Forward(ctx context.Context, msg StdioMessage) ([]byte, error)

Forward 把一条消息转给主进程:请求返回主进程给出的单行 JSON 响应;通知返回 (nil, nil)。 ctx 取消会中断这次 HTTP 调用,主进程那头的请求上下文随连接断开而取消(等价于 notifications/cancelled)。

func (*LocalForwarder) Probe

func (f *LocalForwarder) Probe(ctx context.Context) (LocalHubInfo, error)

Probe 读端口那头的 /api/v1/auth/status(匿名公开接口),用来确认对面是不是 RelayMesh 以及它的运行方式与版本。

func (*LocalForwarder) ResetKey

func (f *LocalForwarder) ResetKey()

ResetKey 丢掉缓存的钥匙,下次发送前重新读文件(主进程换人后使用)。

type LocalHubInfo

type LocalHubInfo struct {
	RunMode   string `json:"run_mode"`
	Version   string `json:"version"`
	ProjectID string `json:"project_id"`
}

LocalHubInfo 是端口那头 /api/v1/auth/status 里我们关心的几个公开字段。

type LocalProxyInfo

type LocalProxyInfo struct {
	Key       string `json:"key"`
	PID       int    `json:"pid"`
	Port      int    `json:"port"`
	Version   string `json:"version"`
	StartedAt string `json:"started_at"`
}

LocalProxyInfo 是主进程写在数据目录里的接入凭证。Key 是机密:任何日志 / 报错都不得带上它。

func ReadLocalProxyInfo

func ReadLocalProxyInfo(dataDir string) (LocalProxyInfo, error)

ReadLocalProxyInfo 读取数据目录里的接入凭证。

type PresetRunActor

type PresetRunActor struct {
	IdentityID uint
	Label      string
	WorkflowID string
	ProjectID  uint
}

PresetRunActor 是经 preset_run 发起操作的调用方;MCP 一侧已经确认它是 ProjectID 这个项目的管理 Agent。

type PresetRunOutcome

type PresetRunOutcome struct {
	Result     any
	Preset     string
	Name       string
	WorkflowID string
	RunID      string
	State      string
}

PresetRunOutcome 是运行提交成功后的结果:Result 原样放进回执,其余字段给 MCP 一侧写项目审计用(不含提示词与命令)。

type PresetRunner

type PresetRunner interface {
	// List 列出 actor 有资格运行的预设,presets / limits 原样放进回执。
	List(ctx context.Context, actor PresetRunActor) (presets any, limits any, err error)
	// Status 看一条预设此刻的现状。
	Status(ctx context.Context, actor PresetRunActor, preset string) (any, error)
	// Run 运行一条预设。
	Run(ctx context.Context, actor PresetRunActor, preset string) (*PresetRunOutcome, error)
}

PresetRunner 是 MCP 运行预设所需的终端 Hub 能力。错误可以实现 ErrorCode() string 以带上稳定的拒绝码。

type RPCExecutionResult

type RPCExecutionResult struct {
	Response       *jsonRPCResponse
	IsNotification bool
}

RPCExecutionResult represents the outcome of an RPC call.

type RequestNotifier

type RequestNotifier interface {
	NotifyRequest(s *model.FeedbackSession)
}

RequestNotifier 在智能体发起一条新的反馈请求(需要人来回复)时被调用,把提醒交给统一通知闸(浏览器 SSE、手机上的 ntfy 等)。 实现必须立即返回(不能在里面做网络请求),并且要自行复制需要的字段——会话对象随后还会被修改。

type Server

type Server struct {
	// contains filtered or unexported fields
}

func NewServer

func NewServer(cfg *config.Config, st *store.Store, onUpdate func(eventType string, data any)) *Server

func (*Server) GetActiveWaiterInfo

func (s *Server) GetActiveWaiterInfo(sessionID string) (bool, *time.Time, int)

func (*Server) GetLastKeepaliveTime

func (s *Server) GetLastKeepaliveTime(sessionID string) *time.Time

func (*Server) HandleRPCRequest

func (s *Server) HandleRPCRequest(ctx context.Context, credCtx *CredentialContext, req *jsonRPCRequest) RPCExecutionResult

HandleRPCRequest processes a parsed JSON-RPC request in a transport-neutral manner.

func (*Server) HasActiveWaiter

func (s *Server) HasActiveWaiter(sessionID string) bool

func (*Server) InstructionsForPermissions

func (s *Server) InstructionsForPermissions(ctx context.Context, perms model.Permissions) string

InstructionsForPermissions 返回具有给定权限的凭据在 initialize 时应收到的指引。

  • 只有终端权限(ExecMesh 档):精简的终端指引,不含 RelayMesh 治理文本;
  • 治理 + 终端(混合):全局指引末尾追加终端章节;
  • 能使用 workflow_context / task_board 的令牌:再追加任务清单章节;能使用 workflow_context 且收件箱提示词条款开着的,再追加追加指令收件箱章节;
  • 能写正文的令牌(interactive_feedback / async_ask / task_board):再追加「正文里的引用链接」章节(任务 #N / 确认项 Q<N> / 文档 [[路径]] / 会话号);
  • 能使用 usage_guide 的令牌:再追加「使用手册」章节(12b,告诉它 Hub 自带只读手册、不会用时先查);
  • 能使用 interactive_feedback 的令牌:最后追加「等待用户回复的两种流程」章节(同步 1:1 / 异步回复窗口);
  • 其他:全局指引(应用设置里的自定义文本优先于内置默认)。

func (*Server) NotifySessionCompleted

func (s *Server) NotifySessionCompleted(sess *model.FeedbackSession)

func (*Server) PresencePlus

func (s *Server) PresencePlus(sessionID string) (totalSec int, ok bool)

PresencePlus 给 sessionID 当前的挂起加一分钟,返回加完后这次挂起的总时长(秒);没有人在挂着时返回 false。

func (*Server) PresenceTyping

func (s *Server) PresenceTyping(sessionID string) (totalSec int, ok bool)

PresenceTyping 记一次「正在输入」心跳:把距上一次心跳的间隔(不超过新鲜期)补进 extra,倒计时就等于暂停了。

func (*Server) RecordKeepaliveResponse

func (s *Server) RecordKeepaliveResponse(sessionID string)

RecordKeepaliveResponse 记下「智能体刚发出一次空回执(或放弃了这次长轮询)」的时刻。 前端据此显示「等待」计时:包括用户在智能体休眠期间提交回复之后——回复提交并不会清掉这个时刻, 要等智能体真正取走回复(markConsumedAndBroadcast)才忘掉它。

func (*Server) ServeHTTP

func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (*Server) ServeLocalProxy

func (s *Server) ServeLocalProxy(w http.ResponseWriter, r *http.Request)

ServeLocalProxy 处理同机其它 stdio 进程转发来的一条 JSON-RPC 消息:

  • 请求:200 + 单行 JSON 响应;
  • 通知(没有 id 或 notifications/*):202,没有响应体;
  • 客户端断开连接 = 取消这次调用(和 stdio 的 notifications/cancelled 等价,请求上下文随连接取消)。

func (*Server) SetEventNotifier

func (s *Server) SetEventNotifier(n EventNotifier)

SetEventNotifier 接入 notice / async_ask 的通知出口;启动时调用一次,传 nil 表示关闭。

func (*Server) SetGroupNotifier

func (s *Server) SetGroupNotifier(n GroupNotifier)

SetGroupNotifier 接入群聊通知出口;启动时调用一次,传 nil 表示关闭。

func (*Server) SetLocalProxyKey

func (s *Server) SetLocalProxyKey(key string)

SetLocalProxyKey 打开(非空)或关闭(空串)转发入口。只有 stdio 主进程会调用;其它场景不设置,入口一律 404。

func (*Server) SetPresetRunner

func (s *Server) SetPresetRunner(r PresetRunner)

SetPresetRunner 注入运行预设的能力;终端功能不可用时不注入,工具返回明确的错误。

func (*Server) SetRequestNotifier

func (s *Server) SetRequestNotifier(n RequestNotifier)

SetRequestNotifier 接入新请求提醒;启动时调用一次,传 nil 表示关闭。

func (*Server) SetTerminalExecutor

func (s *Server) SetTerminalExecutor(e termexec.Executor)

SetTerminalExecutor 注入终端执行能力。未注入(终端功能整体不可用)时三个工具返回明确的错误。

func (*Server) SetTerminalGuardHub

func (s *Server) SetTerminalGuardHub(h terminalGuardHub)

SetTerminalGuardHub 注入终端 Hub(唤醒许可等)。

type StdioHandler

type StdioHandler func(ctx context.Context, msg StdioMessage) []byte

StdioHandler 处理一条消息:请求返回完整的 JSON-RPC 响应(单行 JSON,不含换行);通知或不需要响应时返回 nil。 ctx 在客户端发来 notifications/cancelled、stdin 关闭或进程退出时取消。

func LocalStdioHandler

func LocalStdioHandler(server *Server) StdioHandler

LocalStdioHandler 返回在本进程内直接处理消息的处理器:用本机 stdio 的可信凭据调用 MCP 服务。

type StdioMessage

type StdioMessage struct {
	// Raw 是去掉首尾空白的原始一行 JSON(转发给别的进程时原样发送)。
	Raw []byte
	// Method 是 JSON-RPC 方法名。
	Method string
	// ID 是请求的 id(字符串 / 数字);通知为 nil。
	ID any
	// IsNotification 为真表示这条消息没有 id,或方法以 notifications/ 开头:不得产生响应。
	IsNotification bool
	// contains filtered or unexported fields
}

StdioMessage 是 stdio 读循环交给处理器的一条消息。

type StdioTransport

type StdioTransport struct {
	// contains filtered or unexported fields
}

StdioTransport manages the stdio JSON-RPC loop with concurrent execution, write serialization, and cancellation. 消息交给 StdioHandler 处理:本进程直接处理(NewStdioTransport),或转发给同机另一个进程里的 Hub(见 LocalForwarder)。

func NewStdioTransport

func NewStdioTransport(server *Server, in io.Reader, out io.Writer) *StdioTransport

NewStdioTransport creates a new StdioTransport instance that handles every message in this process.

func NewStdioTransportWithHandler

func NewStdioTransportWithHandler(handle StdioHandler, in io.Reader, out io.Writer) *StdioTransport

NewStdioTransportWithHandler 创建把消息交给指定处理器的传输层(读循环、并发、取消、写串行化行为与本进程直接处理时完全一致)。

func (*StdioTransport) Run

func (t *StdioTransport) Run(ctx context.Context) error

Run executes the stdio read loop until EOF or ctx cancellation.

type ToolDefinition

type ToolDefinition struct {
	Name            string          `json:"name"`
	Description     string          `json:"description"`
	InputSchema     json.RawMessage `json:"inputSchema"`
	SecuritySchemes json.RawMessage `json:"securitySchemes,omitempty"`
}

func AttachOAuthSecuritySchemes

func AttachOAuthSecuritySchemes(tools []ToolDefinition) []ToolDefinition

func GetToolDefinitionsForPermissions

func GetToolDefinitionsForPermissions(perms model.Permissions) []ToolDefinition

Jump to

Keyboard shortcuts

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