spill

package
v0.7.1 Latest Latest
Warning

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

Go to latest
Published: Nov 2, 2026 License: MIT Imports: 25 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

spill — Large-result spill plugin

简体中文 | English

The spill plugin writes tool results above a threshold to local files and replaces the response with a summary, preview, and spill ID/download entry point. This keeps multi-megabyte results out of the model context. It also exposes host APIs (Put, Create, CreatePath, Open, and URLFor) and the read-only spill_explore tool.

Placement and size decision

Install spill last, as the innermost plugin. On return it is then the first middleware awakened and sees the untouched result, allowing it to decide from the actual serialized size. Installing it outside audit would make audit observe the rewritten summary rather than the original large result.

The threshold is based on serialized wire bytes, not payload bytes. JSON escaping and base64 can expand data; the estimator covers text, images, audio, embedded resources, resource links, metadata, annotations, and structuredContent, and returns an intentionally conservative upper bound. Unknown or unserializable content is treated as very large. It short-circuits once over threshold.

Error-state tool results (IsError) are spilled too and retain IsError after rewriting. Only successful tools/call results enter the decision; protocol errors, nil results, and non-call results such as tools/list are not spilled. The rewritten response drops structuredContent deliberately: generated tools may duplicate the payload there, so changing only Content would still leak the large payload.

Configuration

[spill]
dir             = "/home/work/app/data/spill"
threshold_bytes = 32768
ttl             = "6h"
gc_interval     = "5m"
preview_bytes   = 2048
max_file_mib    = 64
max_total_mib   = 512
on_error        = "deny"
Field Semantics
dir Storage directory. If omitted, uses SetDefaultDir when set, otherwise <system temp>/mcp-toolify/spill. At startup it is created/secured as 0700, must be owned by the process, and is held through os.OpenRoot; later symlink replacement cannot redirect storage. Explicit configuration wins over SetDefaultDir.
threshold_bytes Serialized-result threshold; results strictly larger are spilled. Default 65536 (64 KiB); 0 selects the default; negative values fail. There is no disable-spill setting.
ttl Positive Go duration from the last write. Default 30m; zero, negative, or invalid values fail.
gc_interval Positive scan duration. Default 5m; invalid or non-positive values fail. Shutdown stops GC but does not delete files; the next startup's initial scan handles leftovers.
preview_bytes Text preview budget in bytes. Default 2048; 0 selects the default; negative values fail. Non-text content is described by type/MIME/size rather than exposing base64.
max_file_mib Per-file hard limit in MiB. Default 64; negative values fail. Writes beyond the limit fail.
max_total_mib Directory-wide hard limit in MiB. Default 512; negative values fail. Oldest files are evicted first; failure is returned if space cannot be made.
on_error deny (default, fail-closed) or warn. Any other value fails startup.

max_file_mib must not exceed max_total_mib. MiB values are integers, not strings such as "64MiB"; values that overflow int64 during conversion fail startup rather than disabling quota protection.

deny logs the storage failure and returns an error without returning the oversized original. The error intentionally omits storage details and warns that the tool may already have executed; callers must not blindly retry. warn logs the failure and returns the original result, knowingly allowing one oversized response. Neither mode is silent.

Download endpoint and security

The plugin registers GET /spill/<id> (typically /mcp/plugin/spill/<id> after host mount) through Registry.RoutePublic — no Authorization required. A browser can open the link directly. Protection is the unguessable spill ID (random segment; owned IDs also embed the producing replica), directory mode 0700, and TTL. Download no longer checks call-subject ownership: browsers have no MCP Subject, and that check would 404 every direct link.

The summary's absolute URL comes from PublicBaseURL (derived from SelfAddr when unset) plus RoutePath("/spill/") (the prefix set by Mount). A domain or VIP is fine for PublicBaseURL: the owner lives in the ID, so a download landing on any replica is proxied to the owner. SelfAddr itself must stay this replica's directly dialable host:port because it is the replica identity. With multiple replicas, the owned ID embeds the producing replica address; requests received by another replica are proxied by the base's owner routing (RegisterOwnerRoutedRoute) before reaching this handler — only when that address is in the peer allowlist, with loop protection, and never when the file is already present locally. The plugin carries no forwarding implementation of its own. Inter-replica forwarding currently uses cleartext http://; use TLS between peers for cross-host deployments.

Files contain the original tool result for the full TTL. Directory mode 0700, file mode 0600, unguessable IDs, and TTL are the protection boundary. Use a short TTL for sensitive data and separate directories per deployment where possible.

spill_explore

The plugin registers a read-only tool with labels capability=read, risk=none, and plugin=spill. Token rules must allow the tool by name spill_explore. In multi-replica mode, id owner routing sends exploration to the producing replica.

Input fields are id, op, line_offset, limit, pattern, jq_expr, depth, and max_bytes. If omitted, op is stat. Supported operations:

  • stat: returns id, name, format, size, modified, and download.
  • read: reads up to limit lines from zero-based line_offset, returning content, next_line_offset, eof, and truncated.
  • grep: applies a regular expression and returns line:content matches, up to 2,000 lines.
  • schema: infers a bounded structure; json parses the whole value and jsonl uses its first non-empty line. text is unsupported.
  • jq: evaluates a gojq expression for json or each jsonl record. text is unsupported.

max_bytes defaults to 1 MiB and is capped at 8 MiB. A scanner accepts lines up to 4 MiB; longer lines fail rather than being silently truncated. For JSON, schema/jq may need the whole document within the budget; use grep or the download endpoint when it is too large. Explore errors cover missing/expired content and invalid operation or arguments.

The stored format for middleware results is json.

Host API

The content format is one of FormatJSON (json), FormatJSONL (jsonl), or FormatText (text). It controls download Content-Type and supported exploration operations:

id, err := spill.Put("export", spill.FormatJSONL, data)
w, err := spill.Create("export", spill.FormatJSONL)
_, _ = w.Write(chunk)
_ = w.Close()
rc, info, err := spill.Open(id)
url := spill.URLFor(id)
spill.SetDefaultDir(dir) // before Install, only when [spill].dir is absent
  • Put writes a complete payload. Create allocates an ID immediately and supports incremental writes; content is readable while status=running. Writer is not concurrency-safe.
  • Put/Create mark content as shared in the file header. PutFor/CreateFor still record a subject for audit, but the public download endpoint no longer enforces subject ownership — possession of the ID is enough.
  • CreatePath returns an ID and path for third-party writers that only accept filenames. The plugin cannot enforce the write process or per-file limit; sibling files such as .wf share the ID and TTL, but only the returned path is downloadable/explorable.
  • Open returns an io.ReadSeekCloser over the payload plus Info; URLFor returns an empty string, not an error, when no usable outward address exists.
  • Info includes ID, Name, Format, payload Size, ModTime, and Shared. ModTime drives TTL.
  • Before Install, or after OnStop, storage APIs return ErrNotInstalled; the package never lazily creates a store in the system temporary directory.

Each format uses the following media type: JSON application/json; charset=utf-8, JSONL application/x-ndjson; charset=utf-8, and text text/plain; charset=utf-8.

Lifecycle, quotas, and garbage collection

Install creates the store, registers the stop hook, starts GC, registers spill_explore, owner-routes it by id, and registers /spill/. GC removes expired eligible files. It does not delete files merely because the process stopped, so an in-progress download survives a restart. Shared directories are protected by deleting only files created by this process, files whose ID belongs to this replica, or ownerless files older than ttl + 24h; separate directories are still recommended. Total quota enforcement uses oldest-first eviction, and both automatic middleware writes and host Writer.Close participate in the same ledger.

Metadata and startup observability

When middleware spills a result, it writes the ID to Call.Meta under spill.MetaID ("spill.id"); it is absent when no spill occurs. The summary contains the estimated serialized size, threshold, ID, retention, a download URL when available (public link, openable in a browser), otherwise the local replica path, plus a bounded non-base64 preview.

Startup logs use [mcp] spill: and report effective on_error, serialized-byte threshold, TTL, GC interval, preview size, file/total MiB quotas, and directory. A separate startup line reports that the download endpoint is public (no Authorization) and prints the actual path (e.g. /mcp/plugin/spill/). Storage failures are logged at Error level ([mcp] spill: 落盘失败 …) with tool, size and strategy, plus a logid field; the caller-facing deny error does not reveal directory details. All lines go through the host's Config.Logger; the per-download-URL diagnostic is Debug.

Documentation

Overview

Package spill 是大结果落盘插件:超过阈值的工具返回值写进本地文件,返回值改写为 摘要 + 可下载的 spill id/URL,避免把几十兆内容塞进模型上下文。

安装位置:应**最后**安装,位于洋葱最内层——返回时第一个被唤醒,拿到的是未经改写的 原始结果,才能按真实大小判断是否落盘。装在 audit 之外会让审计记到大结果原文。

使用方必须知道的七条:

  1. 判定按**序列化后(wire)总字节**算,不是 payload 字节:JSON 转义会让文本膨胀、 base64 会让二进制膨胀 4/3,按 payload 判定是**低估**(fail-open)。估算走零分配 的长度计算,覆盖 TextContent 之外的 ImageContent / AudioContent / EmbeddedResource / ResourceLink 与 structuredContent;无法序列化的值按「超大」 处理。只看文本的实现挡不住一张 8MB base64 图片。
  2. 错误态结果(IsError)**同样落盘**:一条几十兆的错误堆栈对上下文的伤害和成功结果 没有区别。改写后的结果保持 IsError 不变。
  3. 落盘失败绝不静默。默认 on_error = "deny"(fail-closed):宁可让这次调用失败, 也不把超过阈值的结果原样返回——那正是本插件要防的事。显式配成 "warn" 才降级为 「保留原结果 + 打告警日志」,此时上下文会被大结果撑一次。
  4. 磁盘有硬上限:max_file_mib(单文件)与 max_total_mib(目录总量),单位是 MiB。超单文件 上限直接失败(走 on_error),超总量上限先按最旧优先淘汰,腾不出空间才失败。 落盘文件按 ttl 到期回收(gc_interval 为扫描周期),进程退出时只停回收协程、 不删文件(正在下载的结果不该因一次重启消失),残留文件由下次启动的首轮扫描清掉。 回收只动「本进程创建的 / id 属主是本副本的 / 无属主信息且已超 ttl+24h 的」文件, 多个部署共享同一 dir 时不会互删;仍建议每个部署用独立 dir。
  5. 下载端点 /spill/<id> 用 Registry.RoutePublic 注册(浏览器直接打开,不要求 Bearer token)。保护边界是不可猜测的 spill id(含随机段;有归属时还内嵌 副本地址),外加目录权限与 TTL。不再做按调用主体的属主校验——公开下载 场景下浏览器没有 MCP Subject,属主校验只会把所有直链都拦成 404。
  6. 多副本部署:id 内嵌产出该文件的副本地址,请求打到别的副本时,若该地址在 peer 白名单内则反向代理到属主副本(带环路保护头),否则 404。 摘要里的绝对 URL 依赖 PublicBaseURL,它必须是**本副本可直连的地址**,配成负载 均衡入口会让下载随机落到非属主副本。 **已知风险(复审 M-3,与基座 owner_routing 的既有约定一致,本插件不单独改)**: 副本间转发走明文 http://;公开下载不再透传调用方 Bearer token。
  7. 落盘内容是工具结果原文,会以文件形式留在磁盘上 ttl 那么久。工具返回值里若有 敏感数据,落盘目录的权限(启动时收紧为 0700,目录不属于本进程或收紧失败则拒绝 启动)、不可猜测的 id 与 ttl 就是它的全部保护。目录在校验通过后被以句柄形式持有 (os.OpenRoot),启动之后把路径换成软链既改不了写入位置、也读不出别处的文件。

Index

Constants

View Source
const (
	// OnErrorDeny 为默认值:落盘失败即返回错误,不把超大结果交给模型。
	OnErrorDeny = "deny"
	// OnErrorWarn 保留原结果,但必然打出告警日志(不存在「静默」这一档)。
	OnErrorWarn = "warn"
)

落盘失败时的处置策略(对应 spill on_error)。

View Source
const MetaID = "spill.id"

MetaID 是本插件写进 Call.Meta 的键:本次调用落盘后的 spill id(未落盘时不写)。

关于「跨插件 key 该由谁声明」的澄清(基座 runtime/call.go 里的纪律要求跨插件读取的 key 在基座声明,而核心不允许 import 插件,两者看似冲突):那条纪律管的是**基座自己 参与的** key(如 DenyResult 写的 denied_by / deny_reason,基座写、插件读,必须由基座 声明常量)。插件自己产生的 key 属于插件私有命名空间,由插件导出常量、并按 「插件名.」前缀避免撞名;读取方是插件或宿主,它们**可以** import 本插件拿到这个常量 (只有核心不允许 import 插件)。不愿意 import 的读取方按字符串约定 "spill.id" 读。

View Source
const Name = "spill"

Name 是插件名,与 required_plugins 里的写法一致。

Variables

View Source
var ErrNotInstalled = errors.New("spill 插件尚未安装(或已停止):请先 spill.Install(r)")

ErrNotInstalled 表示还没有 Install(或已经 OnStop)就调用了写入/读取 API。

刻意不「按需自动初始化一个默认 store」:那会在没人配置落盘目录时悄悄往系统临时 目录写业务数据,且与配置认领制给出的目录不是同一个——宿主会看到 spill_explore 找不到自己刚写的文件。

Functions

func CreatePath

func CreatePath(f Format) (id, path string, err error)

CreatePath 在 spill 存储里预留一份内容,返回 id 与可直接写入的**文件路径**。

给路径而不是 io.Writer,是因为宿主侧真正的写入方常常是只接受文件名的第三方 (批量执行框架、日志库)。它们会自己创建/截断这个路径,所以这类内容里没有本 插件的文件头,格式记在文件名后缀里。

与 Create 的差别(选用判据):

  • Create 走本插件的 Writer:有单文件上限、内容可绑定属主(CreateFor)。
  • CreatePath 交出路径后本插件管不到写入过程:**没有**单文件上限(越界要靠 调用方自己或 ulimit 兜底),内容按共享处理(任何通过 token 认证的调用方 都能下载,见 Put 的说明)。

写入方顺带产生的兄弟文件(<path>.wf 之类)与本份内容共用同一个 id,会一起被 TTL 回收;但只有 path 这一个文件能被下载与 spill_explore 探索。

func Install

func Install(r *runtime.Registry) error

Install 安装 spill 插件。应**最后**安装,使其位于洋葱最内层——返回时第一个被唤醒, 拿到未经改写的原始结果才能按真实大小判断是否落盘。

func Put

func Put(name string, f Format, data []byte) (id string, err error)

Put 把一段宿主产生的内容写入 spill 存储,返回可用于下载与探索的 id。

典型用法是「工具自己产出了一份大结果,不想经中间件的自动落盘」:例如把一次 SQL 查询结果导成 CSV、把批量接口的返回摊平成 jsonl 交给 agent 逐行探索。

属主:写入方不是一次 MCP 调用,没有可比对的调用主体,因此这类内容是**共享**的 (见 Info.Shared)。下载端点本身已公开(靠不可猜测的 id),Put/Create 与 PutFor/CreateFor 在下载侧不再有差别;PutFor 仍可把主体写进文件头供审计/排查。

func PutFor

func PutFor(sub *runtime.Subject, name string, f Format, data []byte) (id string, err error)

PutFor 与 Put 相同,但把内容绑定到某个调用主体:只有同一个 token 用途名 (主体有身份时还要求同一个人)才能下载,与中间件自动落盘的属主判定一致。

在工具处理函数里能拿到 *runtime.Call 时优先用它——那时「这份内容是谁的」是确定的。

func SetDefaultDir

func SetDefaultDir(dir string)

SetDefaultDir 设置「配置里没写 dir 时」使用的落盘目录,必须在 Install 之前调用。

为什么需要它:落盘目录常常只有**运行期**才知道——框架可能把它算成 `<应用根目录>/data/spill`,容器里又可能是挂进来的卷。静态配置文件写不出这个值, 而缺了它就会退回系统临时目录:那是可预测路径、重启即清,工具结果原文不该落在那。

配置里显式写的 dir 优先:部署方在配置文件里写下的东西必须赢过代码里的默认值, 否则「我明明配了却不生效」。传空串清除。

func URLFor

func URLFor(id string) string

URLFor 返回该 id 的对外下载地址;未配置可用的 PublicBaseURL 时为空串。

空串不是错误:单副本本地场景没有对外地址,调用方仍可用 spill_explore 探索。 把空串直接拼进给模型的文案会得到 "下载:" 这种半句话,请自行判空。

Types

type Config

type Config struct {
	Spill Section `toml:"spill"`
}

Config 对应配置文件的 spill 段。

用具名字段结构体、且字段集与文档一致(基座的配置认领制要求):用 map 兜底解码会让 段内拼错的键被判为「已解码」,`[spill] threshhold_bytes = ...` 于是被完全吞掉、插件按默认 阈值上线;少声明一个文档承诺的字段,则部署方照文档写全反而启动失败。

type Format

type Format string

Format 是宿主写入内容的格式声明。它决定下载时的 Content-Type,也决定 spill_explore 能对它做哪些操作(jsonl 可逐行 jq、text 只能 read/grep)。

const (
	FormatJSON  Format = "json"  // 单个 JSON 值(对象或数组)
	FormatJSONL Format = "jsonl" // 一行一个 JSON 值,可增量追加
	FormatText  Format = "text"  // 纯文本,按行读/grep
)

三种格式。刻意只有这三种:它们对应「一份 JSON」「一行一条记录」「纯文本日志」 这三类真实用法,多出来的格式没有对应的探索方式。

type Info

type Info struct {
	// ID 是内容 id(内嵌产出副本的地址,见 runtime.NewOwnedID)。
	ID string
	// Name 是宿主写入时给的名字,仅用于人读与下载文件名。
	Name string
	// Format 是写入时声明的格式。
	Format Format
	// Size 是 payload 字节数(不含内部头部)。
	Size int64
	// ModTime 是最后一次写入时间;TTL 从它开始算。
	ModTime time.Time
	// Shared 为真表示这份内容没有绑定调用主体,任何通过 token 认证的调用方都能下载。
	Shared bool
}

Info 是一份 spill 内容的元信息。

func Open

func Open(id string) (io.ReadSeekCloser, Info, error)

Open 按 id 打开一份 spill 内容(只读),返回的 ReadSeekCloser 只覆盖 payload。

宿主一般不需要它 —— agent 侧用 spill_explore 或下载端点。它存在是为了让宿主的 后续处理(例如把上一步的输出喂给下一步)不必绕回 HTTP。

type Section

type Section struct {
	// Dir 是落盘目录;省略则用 <系统临时目录>/mcp-toolify/spill。
	Dir string `toml:"dir"`
	// ThresholdBytes 是落盘阈值(字节):结果总字节超过它即落盘。省略或 0 取 64KiB。
	ThresholdBytes int `toml:"threshold_bytes"`
	// TTL 是落盘文件的保留时长(duration 字符串);省略取 30m。
	TTL string `toml:"ttl"`
	// GCInterval 是回收扫描周期(duration 字符串);省略取 5m。
	GCInterval string `toml:"gc_interval"`
	// PreviewBytes 是摘要里保留的预览字节数;省略或 0 取 2048。
	PreviewBytes int `toml:"preview_bytes"`
	// MaxFileMiB 是单个 spill 文件的上限(**MiB**);省略或 0 取 64。
	MaxFileMiB int64 `toml:"max_file_mib"`
	// MaxTotalMiB 是落盘目录的总量上限(**MiB**);省略或 0 取 512。
	MaxTotalMiB int64 `toml:"max_total_mib"`
	// OnError 是落盘失败时的处置策略:deny(默认,fail-closed)| warn。
	OnError string `toml:"on_error"`
}

Section 是 spill 段的字段集,即本插件的对外配置契约。

字段名自带单位,因为这些数字的量级差得很远:阈值/预览是「一份结果多大」(KiB 级, 用字节),磁盘上限是「这个部署最多占多少盘」(MiB 级,用 MiB)。写成统一的裸字节 会让 67108864 这类值必须心算,改的时候还容易多打或少打一个 0。

ttl / gc_interval 是**字符串**("30m"、"2h"):TOML 没有 duration 类型, 而 time.Duration 是 int64,写 ttl = "30m" 会直接解码失败、写 ttl = 1800 又会被 当成 1800 纳秒。字符串 + time.ParseDuration 是唯一不会被误读的写法。

type Writer

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

Writer 是一份正在写入的 spill 内容。

func Create

func Create(name string, f Format) (*Writer, error)

Create 创建一份可**增量写入**的 spill 内容,返回的 Writer 边写边可被 spill_explore 读到(status=running 时就能读,不必等写完)。

这是异步任务(批量探测、长时间导出)该用的入口:先拿到 id 交给调用方, 后台协程持续追加。Writer 不是并发安全的,多个协程写同一份内容请自行串行化。

func CreateFor

func CreateFor(sub *runtime.Subject, name string, f Format) (*Writer, error)

CreateFor 与 Create 相同,但把内容绑定到某个调用主体(见 PutFor)。

func (*Writer) Close

func (w *Writer) Close() error

Close 结束写入。多次调用是安全的(第二次起是 no-op)。

func (*Writer) ID

func (w *Writer) ID() string

ID 返回这份内容的 id(Create 返回时即已确定,可以先交给调用方再慢慢写)。

func (*Writer) Write

func (w *Writer) Write(p []byte) (int, error)

Write 追加内容。超出单文件上限时返回错误并停止写入(已写部分仍可读)。

Jump to

Keyboard shortcuts

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