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 ¶
- Constants
- func NewServer(tools []byte, opts ...Option) (*sdk.Server, error)
- func Serve(ctx context.Context, tools []byte, opts ...Option) error
- type Argument
- type ArgvError
- type Call
- type Flag
- type Handler
- type Invoke
- type Middleware
- type Option
- func WithDir(dir string) Option
- func WithEnv(env []string) Option
- func WithExecutable(path string) Option
- func WithGrace(d time.Duration) Option
- func WithImplementation(name, version string) Option
- func WithLog(w io.Writer) Option
- func WithMaxConcurrent(n int) Option
- func WithMiddleware(mw ...Middleware) Option
- func WithOutputLimit(n int64) Option
- func WithParameterSelector(keep func(t Tool, param string) bool) Option
- func WithRevision(rev string) Option
- func WithSelector(keep func(Tool) bool) Option
- func WithServingCommand(path ...string) Option
- func WithStdio(in io.Reader, out io.Writer) Option
- func WithTimeout(d time.Duration) Option
- type Stdin
- type Tool
Examples ¶
Constants ¶
const ( Revision20260728 = "2026-07-28" Revision20251125 = "2025-11-25" )
The MCP revisions a tools document can be served for.
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.
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 ¶
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 ¶
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.
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 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 ¶
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 ¶
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 ¶
WithDir runs the program in dir. By default it runs in the server's working directory.
func WithEnv ¶
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 ¶
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 ¶
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 ¶
WithImplementation names the server to clients. By default it is the executable's base name and the main module's version.
func WithLog ¶
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
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 ¶
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 ¶
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 ¶
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 ¶
WithSelector serves only the tools keep returns true for.
func WithServingCommand ¶
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 ¶
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 ¶
WithTimeout stops a run that takes longer than d (zero, the default, for no limit).
type Stdin ¶
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 ¶
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 ¶
InputSchema is the tool's input schema, as a JSON value.
func (Tool) OutputSchema ¶
OutputSchema is the tool's output schema as a JSON value, or nil when it declares none.
func (Tool) Parameters ¶
Parameters lists the tool's parameter names, sorted.
Source Files
¶
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
|
|