mcp

package module
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Oct 14, 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

go-rotini/mcp

Serve a rotini program's commands as Model Context Protocol tools, so an AI agent can call them.

Rotini's tools feature writes the tool definitions: tools/mcp.json, an MCP tools/list result built from the program's spec, with each command's effects as annotations and, under _meta["dev.rotini/invoke"], what a server needs to turn a call back into a command line. This module serves that file. Each call is checked against the tool's input schema, written as a command line and run as a child process; what the program prints becomes the result.

Features

  • Two ways to serve: the rotini-mcp command serves a tools file for any built program, and a program can serve its own tools from a command it declares (taskr mcp)
  • Command lines built the way rotini reads them: attached --flag=value, lists and maps by repeating the flag, counts by repeating, --no-flag for false on a negatable bool (else --flag=false), -- before positionals so a value that looks like a flag stays a value, @@ for a literal @ on a parameter that reads @file
  • Arguments validated against the input schema (JSON Schema 2020-12) before anything runs; output checked against the output schema
  • Structured results: stdout as structuredContent (an array for a streaming command), and a StructuredReporter error line on stderr with an error result
  • Safe runs: secrets refused on the command line, the server's stdin never passed on, SIGTERM on cancel or timeout so the program's signal handling runs, capped output
  • MCP revision 2026-07-28, with 2025-11-25 for older clients
  • Selectors for tools and parameters, and middleware around each call
  • rotini-mcp config writes the server into Claude Desktop, Claude Code, Cursor and VS Code configuration
  • Built on the official MCP Go SDK

Installation

go install github.com/go-rotini/mcp/cmd/rotini-mcp@latest   # the command
go get github.com/go-rotini/mcp                             # the library

Requires Go 1.27 or later and rotini v1.5.0 or later.

Writing the tools file

Turn on the tools feature in the program's .rotini.conf.yaml and run rotini generate:

generate:
  features:
    - type: tools
      enabled: true
      go: true       # also generate var ToolsMCP, for a program that serves itself

Declare what each command does (effects), which flag selects JSON output (role: machine-output), and keep commands and inputs from agents with agent: false. See rotini's guide, "Agent-ready CLIs".

Serving with rotini-mcp

rotini-mcp serve --tools tools/mcp.json --bin ./taskr
Flag Default
--tools the tools file (required)
--bin the program to run for each call; a path, or a name on PATH (required)
--env KEY=value add a variable to the program's environment (repeatable)
--tool NAME every tool serve only these tools (repeatable)
--timeout 0s (none) stop a call that runs longer
--grace 5s time between SIGTERM and kill for a stopped call (0 kills it at once)
--output-limit 10Mi the most a call may write on each of stdout and stderr
--concurrency 0 (none) run at most this many calls at once; more wait their turn
--revision 2026-07-28 the MCP revision to serve for (2025-11-25 for older clients)

Add it to a client:

rotini-mcp config enable claude-desktop taskr --tools tools/mcp.json --bin ./taskr
rotini-mcp config enable claude-code taskr --command taskr --arg mcp   # a program serving itself
rotini-mcp config list cursor --scope project
rotini-mcp config disable vscode taskr

Clients: claude-desktop, claude-code (the project's .mcp.json), cursor and vscode (--scope user or project). A file is backed up to <file>.bak before it is rewritten, replacing an earlier backup; the rewrite keeps every other setting in its order, but comments are not kept. Enabling a server that is already there updates its command, arguments and env and keeps its other settings (such as disabled or autoApprove). A file that is a symbolic link stays one: the file it links to is rewritten. --env values are written into the file, and a project's file is often committed, so keep secrets out of them. The entry names the rotini-mcp executable that wrote it, so run an installed one, not one from go run.

Serving from the program itself

Declare a command for it, kept from agents so it isn't a tool:

commands:
  - name: mcp
    summary: serve this program's commands over MCP
    agent: false

and serve the generated ToolsMCP from its handler:

func (*taskrMcpHandler) Run(ctx context.Context, rtx *rotini.Context) {
	err := mcp.Serve(ctx, []byte(ToolsMCP),
		mcp.WithStdio(rtx.Stdin, rtx.Stdout),
		mcp.WithEnv(rtx.Environ()),
		mcp.WithServingCommand("mcp"))
	if err != nil {
		rtx.HaltWith(err)
	}
}

Each call re-runs the program's own executable. rtx.Stdin and rtx.Stdout are the MCP transport, so the handler must write nothing else to stdout. Rotini's signal handling cancels ctx on SIGTERM, and Serve returns cleanly.

Calls and results

  • Arguments must match the tool's input schema, or the call is an error result and nothing runs. A null parameter counts as left out.
  • The command line is the command's path, the tool's fixed flags (such as --format=json from the machine-output role), one attached occurrence per flag value in parameter-name order, then -- and the positionals. A passthrough command reads every word after its name as typed, so its flags come before its name and its words follow it with no --; when the program reads response files, a word starting with the prefix has it doubled. A count of 0 writes nothing, so it is refused on a count flag with a default, and an empty list or map has no spelling on a flag without a separator, so it is refused too. A secret parameter is refused: supply secrets through the server's environment, which each run gets.
  • Stdin is the stdin parameter for a command that reads stdin, and empty otherwise.
  • A zero exit is a success. With an output schema, stdout's JSON is the structured content and its text; text after it (such as the default reporter's messages) goes in the result's _meta["dev.rotini/trailing_stdout"]. Use rotini's StructuredReporter so stdout holds only the output. Without an output schema, stdout is the text.
  • A non-zero exit is an error result: its text is stderr, and a StructuredReporter error line on stderr is its structured content. A tool with an output schema puts the error line in _meta["dev.rotini/error"] instead, since clients check structured content against the output schema even on an error result. _meta["dev.rotini/exit_code"] has the exit code.
  • A canceled call, one past the timeout or its context's deadline (a middleware may set one), or one past the output limit sends SIGTERM to the program and every process it started (they share a process group), and kills them after the grace period, or once they have all exited (at once with a grace period of 0). A canceled call ends with the cancellation as an error; otherwise the result's text ends with the last few KiB the program wrote on stderr (or stdout). On plan9, js and wasip1 only the program itself is stopped. Windows can't send SIGTERM, so there the program and the processes it started (a job object holds them) are killed at once. There is no timeout unless one is set.
  • A program that can't be started, a parameter left out by the parameter selector and a value holding a NUL byte are error results, not protocol errors.
  • Revisions: a client that negotiates a revision before 2026-07-28 is served the {"result": …} form of a tool whose output isn't an object, in tools/list and in results. That is every client that starts with initialize, whatever revision it asks for, since initialize never settles on 2026-07-28 or later.
  • A background process the program started that keeps its stdout or stderr open doesn't hold the call: once the program exits, the result has the output read within the grace period (a second with a grace period of 0) and the program's exit status. Such a process keeps running unless the call was stopped.

Library options

Option
WithExecutable(path) the program to run (default: the running program)
WithEnv(env) / WithDir(dir) each run's environment and directory (default: the server's)
WithTimeout(d) / WithGrace(d) stop long runs; time between SIGTERM and kill (0: kill at once)
WithOutputLimit(n) cap each of stdout and stderr per run
WithMaxConcurrent(n) run at most n calls at once; more wait their turn
WithStdio(in, out) serve on these streams instead of the process's stdin and stdout
WithSelector(fn) / WithParameterSelector(fn) serve only some tools or parameters
WithMiddleware(mw...) wrap each call, with its command line built, for logging or policy
WithRevision(rev) Revision20260728 (default) or Revision20251125
WithServingCommand(path...) refuse a tool that would run the serving command
WithImplementation(name, version) / WithLog(w) the server's name; its log

NewServer returns the SDK server for other transports, ParseTools reads a tools document, and Invoke.Argv builds a call's command line.

Contributing

See CONTRIBUTING.md.

License

MIT

Documentation

Overview

Package mcp serves a rotini program's commands as Model Context Protocol tools.

Rotini's tools feature writes the tool definitions (`tools/mcp.json`, and with `go: true` the generated `ToolsMCP` string): an MCP tools/list result whose tools each carry, under `_meta["dev.rotini/invoke"]`, what a server needs to turn a call back into a command line. This package reads that document and serves it, over stdio by default. Each call is checked against the tool's input schema, written as a command line (Invoke.Argv) and run as a child process; its stdout becomes the result, checked against the output schema.

There are two ways to serve:

  • The rotini-mcp command serves a tools file for a built program: `rotini-mcp serve --tools tools/mcp.json --bin ./taskr`.
  • A program serves its own tools from a command it declares (such as `taskr mcp`, kept from agents with `agent: false`), whose handler calls Serve with ToolsMCP. Each call re-runs the program's own executable.

Runs

The program gets the server's environment (secrets and other env inputs come from there), stdin from the call's stdin parameter and never the server's own stdin, which is the MCP transport. A canceled call, or one past WithTimeout, its context's deadline or WithOutputLimit, sends SIGTERM to the program and every process it started, so rotini's signal handling runs, and kills them after WithGrace (at once with a grace period of 0), or once they have all exited. On Windows they are killed at once. A canceled call ends with the cancellation, not with the stopped program's output; one past a deadline, such as one a Middleware sets, ends like one past WithTimeout. A client that negotiates a revision before 2026-07-28 is served object outputs, as WithRevision describes.

Results

A zero exit is a success. When the tool declares output, stdout is its structured content (for a stream, one JSON value per line, as an array), checked against the output schema; text after the value, such as the default reporter's messages, goes in the result's _meta. Use rotini's StructuredReporter so stdout holds only the output. A non-zero exit is an error result whose text is stderr (stdout when stderr is empty); a StructuredReporter error line on stderr becomes its structured content, or, for a tool with an output schema (which clients check structured content against, even on an error result), its _meta["dev.rotini/error"].

Index

Examples

Constants

View Source
const (
	Revision20260728 = "2026-07-28"
	Revision20251125 = "2025-11-25"
)

The MCP revisions a tools document can be served for.

View Source
const (
	KindScalar = "scalar" // one attached value (--name=value), or a bool's bare flag
	KindCount  = "count"  // the bare flag, repeated
	KindList   = "list"   // one occurrence per item
	KindMap    = "map"    // one key=value occurrence per entry
	KindObject = "object" // JSON, one occurrence per element of a list of objects
)

The value kinds an invocation fact names: how a parameter's value is written on the command line.

View Source
const MetaKey = "dev.rotini/invoke"

MetaKey is the `_meta` key a tool's invocation facts live under in a tools document.

Variables

This section is empty.

Functions

func NewServer

func NewServer(tools []byte, opts ...Option) (*sdk.Server, error)

NewServer builds the MCP server for a tools document, for serving over another transport (sdk.Server.Run, or the SDK's HTTP handlers). WithStdio has no effect on it.

func Serve

func Serve(ctx context.Context, tools []byte, opts ...Option) error

Serve serves the tools document over MCP on stdio (the process's own, or WithStdio's) until the client disconnects or ctx is done; a stop because ctx is done returns nil. tools is the `tools/mcp.json` Rotini's tools feature writes, or the generated `ToolsMCP` string; each call runs the program with the command line its arguments make.

In a rotini program, a command can serve the program's own tools:

func (*mcpHandler) Run(ctx context.Context, rtx *rotini.Context) {
	err := mcp.Serve(ctx, []byte(ToolsMCP), mcp.WithStdio(rtx.Stdin, rtx.Stdout), mcp.WithServingCommand("mcp"))
	if err != nil {
		rtx.HaltWith(err)
	}
}

Types

type Argument

type Argument struct {
	Name        string   `json:"name"`
	Kind        string   `json:"kind"` // KindScalar, KindList, KindMap or KindObject
	Variadic    bool     `json:"variadic,omitempty"`
	Passthrough bool     `json:"passthrough,omitempty"` // it and every later word are taken as typed; "--" still comes first
	Secret      bool     `json:"secret,omitempty"`      // the value is a secret, which Argv refuses
	From        []string `json:"from,omitempty"`        // file: a leading @ reads a file; stdin: "-" reads stdin
	Separator   string   `json:"separator,omitempty"`   // each item is quoted on its own as an item of a list split on it
}

Argument is a positional parameter, in command-line order.

type ArgvError

type ArgvError struct {
	Param  string // the parameter, or "" when the problem isn't one parameter's
	Reason string
}

ArgvError is a tool call no command line can express: a parameter the tool doesn't have, a value its flag can't take, or a secret.

func (*ArgvError) Error

func (e *ArgvError) Error() string

Error returns "mcp: <param>: <reason>", leaving out an empty Param.

type Call

type Call struct {
	Tool      Tool
	Arguments map[string]any // as the client sent them, numbers as json.Number, nulls removed
	Argv      []string       // the command line, without the program name
	Stdin     []byte         // what the program reads on stdin
	Env       []string       // the program's environment, KEY=value entries
}

Call is one tool call on its way to the program, as middleware sees it. Middleware may change Argv, Stdin and Env before the program runs.

type Flag

type Flag struct {
	Flag       string   `json:"flag"`                  // the flag as written, such as --tag
	Kind       string   `json:"kind"`                  // one of the Kind constants
	Type       string   `json:"type,omitempty"`        // the rotini type, such as bool or []string
	Negated    string   `json:"negated,omitempty"`     // a negatable bool's form for false, such as --no-color
	Separator  string   `json:"separator,omitempty"`   // a list's separator, when it has one
	Role       string   `json:"role,omitempty"`        // the flag's role (such as dry-run or confirm), when it has one
	Secret     bool     `json:"secret,omitempty"`      // the value is a secret, which Argv refuses
	From       []string `json:"from,omitempty"`        // file: a leading @ reads a file; stdin: "-" reads stdin
	HasDefault bool     `json:"has_default,omitempty"` // a count with a default: leaving it out isn't 0
	DottedKeys bool     `json:"dotted_keys,omitempty"` // a map whose nested keys are written flattened: a.b=value
}

Flag is how one flag parameter is written.

type Handler

type Handler func(ctx context.Context, c *Call) (*sdk.CallToolResult, error)

Handler runs a call and returns its result.

type Invoke

type Invoke struct {
	Path           []string        `json:"path"`                      // the command's names below the root
	Arguments      []Argument      `json:"arguments,omitempty"`       // positional parameters
	Flags          map[string]Flag `json:"flags,omitempty"`           // flag parameters, by parameter name
	Fixed          []string        `json:"fixed,omitempty"`           // words added to every call: the machine-output flag
	Stdin          *Stdin          `json:"stdin,omitempty"`           // the parameter read on stdin, if any
	Passthrough    bool            `json:"passthrough,omitempty"`     // the command takes every word after its path as typed: no "--"
	Stream         bool            `json:"stream,omitempty"`          // stdout is a stream of output values, one per line
	Wrapped        bool            `json:"wrapped,omitempty"`         // the structured content is {"result": <stdout>}
	ResponsePrefix string          `json:"response_prefix,omitempty"` // the program reads response files: a raw word before "--" starting with it has it doubled
}

Invoke is how a tool call becomes a command line: rotini's `_meta["dev.rotini/invoke"]`.

func (Invoke) Argv

func (inv Invoke) Argv(args map[string]any) (argv []string, stdin []byte, err error)

Argv turns a tool call's arguments back into the command line that supplies them, the way github.com/go-rotini/rotini.ArgvOf does for a typed inputs value: argv (without the program name) and the bytes to write on stdin.

The command's path comes first, then the fixed flags (the machine-output flag), then one attached occurrence per flag value (--name=value), in parameter-name order. A list or map repeats the flag (key=value for a map, with nested keys flattened to a.b=value on a flag that takes dotted keys), a separator-split one quotes items that hold the separator, an object is JSON, a count repeats the bare flag (0 writes nothing), and a bool is its bare flag for true and its negated form (or --name=false) for false. A "--" comes before the positionals, so a value that looks like a flag stays a positional, also when the last argument is a passthrough one; a list argument with a separator quotes each item on its own. On a parameter whose `from` includes file, a value starting with @ is written with the @ doubled. A null or missing parameter is left out, as is an empty list for an argument.

A passthrough command reads every word after its name as typed, so its flags (all inherited: a passthrough command declares none) and the fixed flags come before its name, and its words follow it with no "--". When the program reads response files, a word before any "--" that starts with the prefix has it doubled, so the program doesn't read it as a file.

A call no command line can express is an *ArgvError: an unknown parameter, a secret (a command line is visible to other users of the machine; the program reads secrets from the server's environment), a count of 0 on a count flag with a default, an explicit empty list or map on a flag without a separator, "-" on a parameter that reads stdin from it, an argument given after one left out, any flag on a passthrough root command, and map keys or free-form values that don't read back as given, and a NUL byte in any value but stdin's.

Example
package main

import (
	"fmt"
	"os"
	"path/filepath"

	"github.com/go-rotini/mcp"
)

func main() {
	doc, err := os.ReadFile(filepath.Join("testdata", "taskr.mcp.json"))
	if err != nil {
		panic(err)
	}
	tools, err := mcp.ParseTools(doc)
	if err != nil {
		panic(err)
	}
	for _, t := range tools {
		if t.Name != "taskr_add" {
			continue
		}
		argv, _, err := t.Invoke.Argv(map[string]any{"title": "-write docs", "tag": []any{"work"}, "verbose": 2})
		if err != nil {
			panic(err)
		}
		fmt.Println(argv)
	}
}
Output:
[add --tag=work --verbose --verbose -- -write docs]

type Middleware

type Middleware func(next Handler) Handler

Middleware wraps the handler that runs the program, for logging, limits or policy. It sees a call after its arguments are checked and its command line is built.

type Option

type Option func(*config)

Option configures Serve and NewServer.

func WithDir

func WithDir(dir string) Option

WithDir runs the program in dir. By default it runs in the server's working directory.

func WithEnv

func WithEnv(env []string) Option

WithEnv sets the environment each run gets (KEY=value entries). By default it is the server's own, which is where secrets and other env inputs come from.

func WithExecutable

func WithExecutable(path string) Option

WithExecutable runs path for each call. By default it is the running program (os.Executable), so a program can serve its own tools.

func WithGrace

func WithGrace(d time.Duration) Option

WithGrace sets how long a stopped run has between SIGTERM and being killed (default 5s). Zero or less kills a stopped run at once, with no SIGTERM.

func WithImplementation

func WithImplementation(name, version string) Option

WithImplementation names the server to clients. By default it is the executable's base name and the main module's version.

func WithLog

func WithLog(w io.Writer) Option

WithLog writes the server's log (bad tool names, protocol problems) to w. By default nothing is logged; never log to the stdout the server speaks on.

func WithMaxConcurrent added in v0.1.2

func WithMaxConcurrent(n int) Option

WithMaxConcurrent runs at most n calls' programs at once; a call beyond that waits for a running one to finish, or for the client to cancel it. Zero or less, the default, means no limit.

func WithMiddleware

func WithMiddleware(mw ...Middleware) Option

WithMiddleware wraps each call's handler; the first middleware given is the outermost.

func WithOutputLimit

func WithOutputLimit(n int64) Option

WithOutputLimit caps each run's stdout and stderr at n bytes (default 10 MiB). A run that writes more is stopped, and the call is an error. Zero or less means no limit.

func WithParameterSelector

func WithParameterSelector(keep func(t Tool, param string) bool) Option

WithParameterSelector serves only the parameters keep returns true for: the others are left out of the tool's input schema, and a call that passes one is refused, whatever the schema says about extra properties. Leaving out a required parameter is an error.

func WithRevision

func WithRevision(rev string) Option

WithRevision serves the tools for an MCP revision: Revision20260728 (the default) or Revision20251125, which needs every output to be an object, so a tool whose output isn't one gets {"result": …}. Prefer writing the tools document for the revision you serve (the tools feature's mcp_revision); this converts one written for the newer revision.

The revision is the newest a client is served for. A client that negotiates an older revision than Revision20260728 is always served the {"result": …} form, in tools/list and in each result. Every client that starts with initialize negotiates an older revision, whatever it asks for.

func WithSelector

func WithSelector(keep func(Tool) bool) Option

WithSelector serves only the tools keep returns true for.

func WithServingCommand

func WithServingCommand(path ...string) Option

WithServingCommand names the command that serves the tools, by its command names below the root as a tool's Invoke.Path gives them (such as "mcp"). Serving a tool that would run it, and so start another server, is an error. The serving command should also be kept from agents with `agent: false`.

func WithStdio

func WithStdio(in io.Reader, out io.Writer) Option

WithStdio serves over in and out instead of the process's stdin and stdout. In a rotini handler, pass rtx.Stdin and rtx.Stdout; they must be the real streams the client connects to.

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout stops a run that takes longer than d (zero, the default, for no limit).

type Stdin

type Stdin struct {
	Param  string `json:"param"`
	Format string `json:"format"`
}

Stdin is the parameter whose value the command reads on stdin, and its format (json, yaml, lines, jsonl or text).

type Tool

type Tool struct {
	Name        string
	Title       string
	Description string
	Annotations *sdk.ToolAnnotations
	Invoke      Invoke
	// contains filtered or unexported fields
}

Tool is one tool of a tools document: its MCP definition and the facts that turn a call back into a command line.

func ParseTools

func ParseTools(doc []byte) ([]Tool, error)

ParseTools reads a tools document: the `tools/mcp.json` file Rotini's tools feature writes (or the generated `ToolsMCP` string), an MCP tools/list result whose tools carry their invocation facts.

Example
package main

import (
	"fmt"

	"github.com/go-rotini/mcp"
)

func main() {
	doc := []byte(`{"tools": [{
		"name": "taskr_list",
		"inputSchema": {"type": "object", "properties": {"page": {"type": "string"}}},
		"_meta": {"dev.rotini/invoke": {"path": ["list"], "fixed": ["--format=json"],
			"flags": {"page": {"flag": "--page", "kind": "scalar", "type": "string"}}}}
	}]}`)
	tools, err := mcp.ParseTools(doc)
	if err != nil {
		panic(err)
	}
	t := tools[0]
	fmt.Println(t.Name, t.Invoke.Path, t.Parameters(), t.OutputSchema() == nil)
}
Output:
taskr_list [list] [page] true

func (Tool) InputSchema

func (t Tool) InputSchema() map[string]any

InputSchema is the tool's input schema, as a JSON value.

func (Tool) OutputSchema

func (t Tool) OutputSchema() map[string]any

OutputSchema is the tool's output schema as a JSON value, or nil when it declares none.

func (Tool) Parameters

func (t Tool) Parameters() []string

Parameters lists the tool's parameter names, sorted.

Directories

Path Synopsis
Package clients adds, removes and lists MCP servers in the configuration files of MCP clients: Claude Desktop, Claude Code, Cursor and VS Code.
Package clients adds, removes and lists MCP servers in the configuration files of MCP clients: Claude Desktop, Claude Code, Cursor and VS Code.
cmd
rotini-mcp command
Command rotini-mcp serves a rotini program's tools over MCP, and adds that server to MCP clients' configuration.
Command rotini-mcp serves a rotini program's tools over MCP, and adds that server to MCP clients' configuration.
internal

Jump to

Keyboard shortcuts

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