wastebin-mcp-go/internal/wastebin/schema.go
xlion-bot-renovate[bot] eaf8788a07
chore(deps): update dependency go to v1.27.1 (#251)
* chore(deps): update dependency go to v1.27.1

* Fixed lints; `just verify` passes.

Co-authored-by: xlionjuan <[email protected]>

* Re-enabled exhaustruct_v5; just verify passes.

Co-authored-by: xlionjuan <[email protected]>

* Fixed lint config; verify passes.

Co-authored-by: xlionjuan <[email protected]>

* Explicit DisableBuiltinBlocklist; verify passes 0 issues.

Co-authored-by: xlionjuan <[email protected]>

---------

Co-authored-by: xlion-bot-renovate[bot] <218815870+xlion-bot-renovate[bot]@users.noreply.github.com>
Co-authored-by: opencode-agent[bot] <opencode-agent[bot]@users.noreply.github.com>
Co-authored-by: xlionjuan <[email protected]>
2026-09-06 23:13:47 +08:00

249 lines
7.5 KiB
Go

package wastebin
import (
"encoding/json"
"fmt"
"strings"
)
// JSON Schema key literals reused across the generated property maps.
const (
schemaKeyType = "type"
schemaTypeString = "string"
schemaTypeBoolean = "boolean"
schemaKeyDescription = "description"
)
// SchemaBuilder builds JSON Schema and tool descriptions for the create_paste
// MCP tool based on server configuration.
type SchemaBuilder struct {
cfg *Config
}
// NewSchemaBuilder creates a new SchemaBuilder for the given config.
func NewSchemaBuilder(cfg *Config) *SchemaBuilder {
return &SchemaBuilder{cfg: cfg}
}
// BuildToolSchema generates the JSON Schema for the create_paste tool input
// dynamically based on the server configuration.
//
//nolint:funlen // Schema assembled verbatim as a map; extraction would obscure the generated document
func (b *SchemaBuilder) BuildToolSchema() (json.RawMessage, error) {
props := map[string]any{}
var required []string
// content -- always included
if b.cfg.FileReadEnabled {
props["content"] = map[string]any{
schemaKeyType: schemaTypeString,
schemaKeyDescription: "The text content of the paste. Provide this OR file_path (not both).",
}
} else {
props["content"] = map[string]any{
schemaKeyType: schemaTypeString,
schemaKeyDescription: "The text content of the paste.",
}
required = append(required, "content")
}
// file_path -- only when FileReadEnabled
if b.cfg.FileReadEnabled {
filePathDesc := "Path to a local file to read and upload as paste content. " +
"Provide this OR content (not both). The file must be a text file."
if len(b.cfg.SandboxMounts) > 0 && !b.cfg.SandboxTransparent {
filePathDesc += " Sandbox path translation is available: when " +
"`translate_sandbox_path` is set to `true`, the path is " +
"translated to the corresponding host path."
}
filePathDesc += b.describePathSecurity()
props["file_path"] = map[string]any{
schemaKeyType: schemaTypeString,
schemaKeyDescription: filePathDesc,
}
}
// extension -- optional
extDesc := "File extension for syntax highlighting (e.g. 'go', 'py', 'js', 'md')."
if b.cfg.FileReadEnabled {
extDesc += " When using file_path, the extension is detected from the " +
"file name if not provided."
}
props["extension"] = map[string]any{
schemaKeyType: schemaTypeString,
schemaKeyDescription: extDesc,
}
// expires -- optional
defaultExpiresDesc := DescribeDefaultExpires(b.cfg.DefaultExpires)
props["expires"] = map[string]any{
schemaKeyType: schemaTypeString,
schemaKeyDescription: "Expiration time: bare number (seconds) or number plus unit " +
"suffix (s, m, h, d, w, M=30d, y=365d). Examples: '3600', '1h', " +
"'7d', '30M'. Defaults to " + defaultExpiresDesc + ". " +
"Configured via WASTEBIN_MCP_DEFAULT_EXPIRES.",
}
// title -- optional
props["title"] = map[string]any{
schemaKeyType: schemaTypeString,
schemaKeyDescription: "Optional title for the paste.",
}
// burn_after_reading -- optional
props["burn_after_reading"] = map[string]any{
schemaKeyType: schemaTypeBoolean,
schemaKeyDescription: "If true, the paste is deleted automatically after being " +
"retrieved via any access method (raw, web, API) for the first " +
"time. The agent's own reads also count -- creating a " +
"burn-after-reading paste and then reading it back will delete it.",
}
// password -- optional, must be non-empty when provided
props["password"] = map[string]any{
schemaKeyType: schemaTypeString,
"minLength": 1,
schemaKeyDescription: "Optional password to protect the paste. " +
"Password-protected pastes require the Wastebin-Password header for retrieval.",
}
// translate_sandbox_path -- only when mounts configured and not transparent
if b.cfg.FileReadEnabled && len(b.cfg.SandboxMounts) > 0 && !b.cfg.SandboxTransparent {
props["translate_sandbox_path"] = map[string]any{
schemaKeyType: schemaTypeBoolean,
schemaKeyDescription: "Set to true if file_path is a sandbox-internal " +
"path that should be translated to the corresponding host " +
"path using configured sandbox mounts.",
}
}
schema := map[string]any{
schemaKeyType: "object",
"properties": props,
"additionalProperties": false,
}
if len(required) > 0 {
schema["required"] = required
}
data, err := json.Marshal(schema)
if err != nil {
return nil, fmt.Errorf("marshal paste schema: %w", err)
}
return json.RawMessage(data), nil
}
// DescribeDefaultExpires returns a human-readable description of a default
// expiration value in seconds for use in MCP tool descriptions.
func DescribeDefaultExpires(seconds int) string {
if seconds == 0 {
return "no expiration (paste persists until manually deleted)"
}
years := seconds / secondsPerYear
rem := seconds % secondsPerYear
days := rem / secondsPerDay
rem %= secondsPerDay
hours := rem / secondsPerHour
rem %= secondsPerHour
minutes := rem / secondsPerMinute
secs := rem % secondsPerMinute
var parts []string
if years == 1 {
parts = append(parts, "1 year")
} else if years > 1 {
parts = append(parts, fmt.Sprintf("%d years", years))
}
if days == 1 {
parts = append(parts, "1 day")
} else if days > 1 {
parts = append(parts, fmt.Sprintf("%d days", days))
}
if hours == 1 {
parts = append(parts, "1 hour")
} else if hours > 1 {
parts = append(parts, fmt.Sprintf("%d hours", hours))
}
if minutes == 1 {
parts = append(parts, "1 minute")
} else if minutes > 1 {
parts = append(parts, fmt.Sprintf("%d minutes", minutes))
}
if secs == 1 {
parts = append(parts, "1 second")
} else if secs > 1 {
parts = append(parts, fmt.Sprintf("%d seconds", secs))
}
human := strings.Join(parts, ", ")
return fmt.Sprintf("%d seconds (%s)", seconds, human)
}
// BuildToolDescription returns the tool-level description for create_paste.
func (b *SchemaBuilder) BuildToolDescription() string {
desc := "Create a text paste on the configured Wastebin instance. " +
"Content supports multiple lines naturally -- include newlines " +
"directly in the string value. " +
"The response includes 'hostname', " +
"'id', 'url', and 'raw' fields. Reconstruct full URLs as " +
"{hostname}{url} or {hostname}{raw}. " +
"When 'extension' is 'md' or 'markdown', a 'markdown_rendered' " +
"field appears with the rendered view URL. " +
"Password-protected pastes require the Wastebin-Password header " +
"for retrieval."
if b.cfg.FileReadEnabled {
desc += " Use 'content' for inline text or 'file_path' to upload a local file." +
" File paths are validated against the configured path policy."
} else {
desc += " Use 'content' for inline text."
}
return desc
}
// describePathSecurity returns the security section of the file_path
// description based on the configured path policy.
func (b *SchemaBuilder) describePathSecurity() string {
if len(b.cfg.AllowedPaths) > 0 {
desc := " SECURITY: Only paths under ALLOWED_PATHS are accepted."
if !b.cfg.DisableBuiltinBlocklist {
desc += " Sensitive components remain blocked."
}
return desc
}
if !b.cfg.DisableBuiltinBlocklist {
desc := " SECURITY: The built-in blocklist rejects system paths (/etc, /proc, /sys, /dev) " +
"and sensitive components (.ssh, .gnupg, .aws, .kube, .docker, .git)."
if len(b.cfg.BlockedPaths) > 0 {
desc += " User-defined BLOCKED_PATHS also apply."
}
return desc
}
if len(b.cfg.BlockedPaths) > 0 {
return " SECURITY: Paths are validated against user-defined BLOCKED_PATHS."
}
return " SECURITY: No additional path restrictions are configured." +
" Path traversal (`..`) is still unconditionally blocked."
}