mcpserver

package
v2.57.1 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2026 License: MIT Imports: 35 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.

Documentation

Index

Constants

View Source
const (
	ToolRead    = "c8y_read"
	ToolWrite   = "c8y_write"
	ToolSession = "c8y_session"

	// PromptSwitchSession prompt to let the user switch the session (stdio mode)
	PromptSwitchSession = "switch_session"
)
View Source
const DefaultConfirmTimeout = 2 * time.Minute

DefaultConfirmTimeout how long the user has to confirm a device command

View Source
const DefaultPickerTimeout = 3 * time.Minute

DefaultPickerTimeout how long the user has to select a session in the browser

View Source
const EnvDeniedPaths = "C8Y_SETTINGS_FILES_DENIEDPATHS"

EnvDeniedPaths environment variable which sets the settings.files.deniedPaths setting of the commands, so they can't read files in the denied paths

Variables

View Source
var DefaultDenyCommands = []string{
	"mcp",
	"sessions",
	"settings",
	"cli",
	"alias",
	"completion",
	"extensions",
	"microservices getBootstrapUser",
	"deviceregistration getCredentials",
	"remoteaccess connect run",
	"remoteaccess server",
}

DefaultDenyCommands commands which are not available to the agent by default. They either expose secrets, change the local configuration, or open local network services.

View Source
var DefaultReadCommands = []string{
	"version",
	"template",
	"util",
	"* subscribe",
	"* subscribeAll",
	"operations wait",
	"realtime subscribe",
	"realtime subscribeAll",
}

DefaultReadCommands commands which never write to Cumulocity, in addition to any command whose name starts with a read verb (see readVerbPrefixes)

View Source
var DeniedFlags = []string{
	"session",
	"sessionUsername",
	"sessionPassword",
	"sessionMode",
	"host",
	"proxy",
	"noProxy",
	"insecure",
	"outputFile",
	"outputFileRaw",
	"noLog",
	"logMessage",
	"force",
	"confirm",
	"confirmText",
	"debug",
}

DeniedFlags global flags the agent is not allowed to set, as they would allow the agent to escape the policy (e.g. switching session or mode), write local files, or disable the audit trail

View Source
var DeniedShortFlags = []rune{'U', 'P', 'k', 'f', 'l'}

DeniedShortFlags shorthand versions of DeniedFlags

View Source
var DeviceShellCommands = []string{
	"remoteaccess connect ssh",
}

DeviceShellCommands commands which run a shell command on a device through a Cumulocity remote access (ssh) tunnel. The agent can only use them non-interactively, with the command to run on the device after "--", e.g. "remoteaccess connect ssh --device 1234 -- systemctl status". They are always treated as write commands, as the shell command can change anything on the device, and their dry run mode would still run the command.

View Source
var ErrPickerCancelled = errors.New("the user cancelled the session selection")

ErrPickerCancelled the user cancelled the session selection

View Source
var ErrPickerTimeout = errors.New("the user did not select a session in time")

ErrPickerTimeout the user did not select a session in time

ErrTOTPRequired the login needs a two-factor authentication code

Functions

func CapMode

func CapMode(policyMode, sessionMode config.SessionMode) config.SessionMode

CapMode returns the more restrictive of the policy mode and the session mode. An unset policy mode uses the session mode, and an unset session mode is prod (read only). The ci mode is treated like dev so the agent never gets more than dev.

func CheckDeviceShellArgs

func CheckDeviceShellArgs(commandPath string, args []string) error

CheckDeviceShellArgs checks that a device shell command is only used non-interactively and doesn't open local listeners

func CheckFlags

func CheckFlags(args []string) error

CheckFlags rejects any flags the agent is not allowed to use. Arguments after the argument terminator "--" are not c8y flags, so they are not checked.

func DesktopNotification

func DesktopNotification(title string, message string)

DesktopNotification shows a desktop notification, if supported (best effort). The values are passed as arguments, so they are never interpreted as a script.

func HasDryRun

func HasDryRun(args []string) bool

HasDryRun checks if the arguments activate the dry run mode

func IsDeviceShellCommand

func IsDeviceShellCommand(commandPath string) bool

IsDeviceShellCommand returns true if the command runs a shell command on a device

func IsHelp

func IsHelp(args []string) bool

IsHelp checks if the arguments only request help

func MatchCommand

func MatchCommand(pattern, commandPath string) bool

MatchCommand checks if a command path (e.g. "devices list") matches a pattern. Each word in the pattern is matched against the corresponding word of the command path and supports glob wildcards, e.g. "devices *", "* delete". A pattern also matches all sub commands, e.g. "devices" matches "devices list"

func ParseMode

func ParseMode(name string) (config.SessionMode, error)

ParseMode parses a mode name (prod, qual, dev). CI mode is not accepted

func ResolveSessionFile

func ResolveSessionFile(sessionFile string, sessionHome string) string

ResolveSessionFile returns the absolute path of the session file. A session can be given by name (e.g. --session my-tenant), in which case the matching file is looked up in the session home directory. The value is returned as is if no file is found.

func SessionKey

func SessionKey(sessionFile string) string

SessionKey name used to identify a session, derived from the session file. Only known session file extensions are removed, as session names can contain dots, e.g. "example.cumulocity.com-firstname.lastname"

func SplitAtTerminator

func SplitAtTerminator(args []string) (before []string, after []string, found bool)

SplitAtTerminator splits the arguments at the argument terminator "--". The arguments after it are not interpreted as c8y flags.

func SplitPipeline

func SplitPipeline(commandLine string) ([][]string, error)

SplitPipeline splits a command line into the individual c8y commands. The command is not passed to a shell, so only " | " (pipe surrounded by whitespace) between c8y commands is supported.

func TokenExpiresAt

func TokenExpiresAt(token string) *time.Time

TokenExpiresAt returns the expiry time of a JWT token, or nil if it can't be determined

Types

type Approval

type Approval string

Approval controls how write commands are approved before they are executed

const (
	// ApprovalAuto asks the user via MCP elicitation when the client supports it,
	// otherwise it relies on the MCP client's own tool permission prompt
	ApprovalAuto Approval = "auto"

	// ApprovalElicit always asks the user via MCP elicitation. If the client does
	// not support elicitation, then write commands are rejected
	ApprovalElicit Approval = "elicit"

	// ApprovalClient relies only on the MCP client's tool permission prompt
	// (the write tool is annotated as destructive)
	ApprovalClient Approval = "client"

	// ApprovalNone does not ask for any approval. Only use for trusted automation
	ApprovalNone Approval = "none"
)

func ParseApproval

func ParseApproval(v string) (Approval, error)

type AuthProvider

type AuthProvider interface {
	// AuthEnv returns the environment variables containing the credentials
	AuthEnv(ctx context.Context) ([]string, error)
}

AuthProvider provides the credentials for the commands run for the agent

type Classifier

type Classifier struct {
	Root   *cobra.Command
	Policy Policy
}

Classifier resolves commands against the c8y command tree and applies the policy

func (*Classifier) Plan

func (c *Classifier) Plan(commandLine string) (*Plan, error)

Plan parses and validates a command line

type CommandInput

type CommandInput struct {
	Command        string `` /* 238-byte string literal not displayed */
	Stdin          string `json:"stdin,omitempty" jsonschema:"Optional data piped to the first command, e.g. newline separated ids or json lines"`
	TimeoutSeconds int    `json:"timeoutSeconds,omitempty" jsonschema:"Optional timeout in seconds"`
}

CommandInput input for the read/write tools

type DeviceShellConfirmer

type DeviceShellConfirmer struct {
	// Timeout how long the user has to answer. Defaults to DefaultConfirmTimeout
	Timeout time.Duration
	// contains filtered or unexported fields
}

DeviceShellConfirmer asks the user to confirm commands which run on a device, with a native dialog (macOS, or Linux with zenity or kdialog). The MCP client can't answer it. Commands are rejected if no dialog is available.

func (*DeviceShellConfirmer) Confirm

func (c *DeviceShellConfirmer) Confirm(ctx context.Context, session SessionInfo, command string) error

Confirm returns nil if the user allows the command

type InteractiveLogin

type InteractiveLogin struct {
	// Executable path to the c8y binary
	Executable string

	// SessionFile session file to log in with. If empty, the session is read
	// from environment variables
	SessionFile string

	// SessionMode mode passed to the login command (to avoid the mode prompt)
	SessionMode string

	// Stderr receives the login's messages
	Stderr io.Writer

	// RenewBefore log in again when the token expires within this duration
	RenewBefore time.Duration

	// TempDir directory for the copy of the session file without secrets
	TempDir string

	// Renew optional function which logs in again when the token expires, instead of
	// logging in without secrets. It is used to ask the user for the secrets in the
	// browser. It must call login (which may be called several times, e.g. after a wrong
	// passphrase) and return its last error. It is called while the login is locked
	Renew func(ctx context.Context, login func(ctx context.Context, secrets LoginSecrets) error) error
	// contains filtered or unexported fields
}

InteractiveLogin logs in using the existing "c8y sessions login" command, then provides the resulting token to the commands. The server has no terminal, so the login can't prompt: an encrypted session is unlocked with the pin entry command (settings.pinEntry) or the passphrase given in LoginSecrets, and a two-factor code is generated from the session's TOTP secret or given in LoginSecrets. The login is repeated when the token is about to expire (see Renew).

func (*InteractiveLogin) AuthEnv

func (l *InteractiveLogin) AuthEnv(ctx context.Context) ([]string, error)

AuthEnv returns the credentials, logging in again if the token expires soon

func (*InteractiveLogin) ExpiresAt

func (l *InteractiveLogin) ExpiresAt() *time.Time

ExpiresAt returns when the current token expires (if known)

func (*InteractiveLogin) Login

func (l *InteractiveLogin) Login(ctx context.Context) error

Login runs the interactive login

func (*InteractiveLogin) LoginWith

func (l *InteractiveLogin) LoginWith(ctx context.Context, secrets LoginSecrets) error

LoginWith runs the login with the secrets entered by the user (if any). It returns ErrTOTPRequired if a two-factor code is needed

func (*InteractiveLogin) UsesToken

func (l *InteractiveLogin) UsesToken() bool

UsesToken returns true if the commands use a token (rather than basic auth)

type LoginFunc

type LoginFunc func(ctx context.Context, choice SessionChoice, secrets LoginSecrets) (value any, err error)

LoginFunc logs in to the selected session with the secrets entered on the page. The passphrase is only set for sessions which need it (see SessionChoice.NeedsPassphrase). It returns ErrTOTPRequired if a two-factor code is needed, and a value which is returned by Pick

type LoginSecrets

type LoginSecrets struct {
	// Passphrase to unlock an encrypted session
	Passphrase string
	// TOTPCode two-factor authentication code
	TOTPCode string
}

LoginSecrets secrets entered by the user for a login. They are passed to the login via an inherited pipe, and aren't kept

type Plan

type Plan struct {
	Segments []Segment
}

Plan the parsed and validated command(s) requested by the agent

func (*Plan) HasDeviceShell

func (p *Plan) HasDeviceShell() bool

HasDeviceShell returns true if any of the segments runs a shell command on a device

func (*Plan) MarkDeviceCommands

func (p *Plan) MarkDeviceCommands(stdin string)

MarkDeviceCommands marks the segments which send a c8y_Command operation (a shell command run by the device's agent) as device shell commands. The data can come from the arguments or the input piped to the first command. This is a best effort check: a template can assemble the operation in other ways, so deny "operations create" to prevent device operations completely.

func (*Plan) ReadOnly

func (p *Plan) ReadOnly() bool

ReadOnly returns true if all of the segments are read-only

func (*Plan) String

func (p *Plan) String() string

String returns the command line which will be executed (without injected flags)

type Policy

type Policy struct {
	// Mode maximum session mode the agent may use. It can never exceed the
	// mode of the session itself. SessionModeUnset uses the session's mode
	Mode config.SessionMode

	// Allow if non-empty, only commands matching one of these patterns are allowed
	Allow []string

	// Deny commands matching any of these patterns are rejected (wins over Allow)
	Deny []string

	// ReadCommands additional commands which should be treated as read-only
	ReadCommands []string

	// Approval how write commands are approved
	Approval Approval

	// Timeout default timeout per tool call
	Timeout time.Duration

	// MaxTimeout upper limit for the timeout requested by the agent
	MaxTimeout time.Duration

	// MaxOutputBytes maximum number of bytes returned to the agent per call
	MaxOutputBytes int

	// DenyPaths additional local files and folders the commands can't read, e.g. with
	// --template, --data or --file. The session home folder and the active session
	// file are always denied
	DenyPaths []string

	// AllowDeviceShell allows commands which run a shell command on a device (see
	// DeviceShellCommands and c8y_Command operations). They still need a mode which
	// allows creating data, and are approved like other write commands
	AllowDeviceShell bool
}

Policy controls what the agent can and can't do

func DefaultPolicy

func DefaultPolicy() Policy

func (Policy) CheckCommand

func (p Policy) CheckCommand(commandPath string) error

CheckCommand checks if the command is allowed by the allow/deny lists

func (Policy) IsReadCommand

func (p Policy) IsReadCommand(commandPath string) bool

IsReadCommand checks if the command only reads data

type Result

type Result struct {
	Stdout   string
	Stderr   string
	ExitCode int
	// Truncated is true if the stdout was truncated
	Truncated bool
}

Result output of the executed command(s)

type Runner

type Runner struct {
	// Executable path to the c8y binary
	Executable string

	// SessionFile session file which is used for all commands
	SessionFile string

	// DeniedPaths local files and folders the commands can't read or write, e.g.
	// the session files, so their secrets can't be read with --template or --data
	DeniedPaths []string

	// SSHFallbackUser ssh user which device shell commands try if no user is given
	// and the login with the local user name fails (empty to disable)
	SSHFallbackUser string

	// Mode the maximum mode used for write commands
	Mode config.SessionMode

	// BaseEnv base environment for the child processes (defaults to os.Environ())
	BaseEnv []string

	// Auth optional credentials provider. When set, credentials inherited from
	// the server's environment are removed and the provider's credentials are
	// used instead
	Auth AuthProvider
}

Runner executes c8y commands as child processes

func (*Runner) Env

func (r *Runner) Env(mode config.SessionMode, authEnv []string) []string

Env builds the environment for a child process

func (*Runner) Run

func (r *Runner) Run(ctx context.Context, plan *Plan, stdin string, tag string, maxOutput int) (*Result, error)

Run executes the plan. Read-only commands are executed in prod (read-only) mode so the existing c8y mode checks reject any write request, even if the command was misclassified.

type Segment

type Segment struct {
	// Args arguments passed to c8y (without the leading "c8y")
	Args []string

	// CommandPath resolved command path, e.g. "devices list"
	CommandPath string

	// Read true if the command only reads data
	Read bool

	// DeviceShell true if the command runs a shell command on a device. It has no
	// dry run mode, so no preview can be shown
	DeviceShell bool
}

Segment a single c8y command within a pipeline

type Selection

type Selection struct {
	Choice SessionChoice
	// Value returned by the login (if any)
	Value any
}

Selection the session selected by the user

type Server

type Server struct {
	Version string

	// Session, Runner the session used by the commands. Use SetSession to change
	// them once the server is running
	Session SessionInfo
	Runner  *Runner

	Policy     Policy
	Classifier *Classifier

	// OnCall optional callback which is called after each tool call, e.g. to log the
	// agent's activity
	OnCall func(tool string, command string, outcome string)

	// Gate optional check which is run before each tool call, e.g. to wait until the
	// user has selected a session
	Gate func(ctx context.Context, ss *mcp.ServerSession) error

	// SwitchSession optional function which lets the user select another session. It is
	// offered as an MCP prompt (in Claude Code a slash command), which only the user can
	// run, not the agent. It returns a message for the conversation, and should not wait
	// for the user's selection: tool calls wait for it instead (see Gate)
	SwitchSession func(ctx context.Context) (string, error)

	// ConfirmDeviceShell optional confirmation by the user of commands which run a shell
	// command on a device, in addition to the normal approval. Unlike the approval, the
	// MCP client can't answer it
	ConfirmDeviceShell func(ctx context.Context, session SessionInfo, command string) error
	// contains filtered or unexported fields
}

Server MCP server which exposes go-c8y-cli to an agent

func (*Server) Active

func (s *Server) Active() (SessionInfo, *Runner)

Active returns the session and runner used for new tool calls

func (*Server) Instructions

func (s *Server) Instructions() string

Instructions returns the instructions sent to the MCP client

func (*Server) New

func (s *Server) New() *mcp.Server

New creates the MCP server

func (*Server) SetSession

func (s *Server) SetSession(info SessionInfo, runner *Runner)

SetSession changes the session used by the commands, e.g. when the user switches the session. Tool calls which have already started keep using the previous session, so a command always runs against the tenant it was approved for.

type SessionChoice

type SessionChoice struct {
	// Path session file
	Path     string
	Name     string
	Host     string
	Tenant   string
	Username string

	// Current true if it is the session which is currently used
	Current bool

	// Mode the mode the agent can use with the session, e.g. "dev", and a description
	// of what it allows
	Mode     string
	ModeInfo string

	// NeedsPassphrase true if the passphrase must be entered on the page to unlock the
	// session (it is encrypted and no pin entry command is configured)
	NeedsPassphrase bool

	// NeedsCode true if a two-factor authentication code is expected, e.g. because the
	// last login needed one. The code field is also shown when the login asks for it
	NeedsCode bool
}

SessionChoice a session the user can select

type SessionInfo

type SessionInfo struct {
	Host        string `json:"host"`
	Tenant      string `json:"tenant,omitempty"`
	Username    string `json:"username,omitempty"`
	SessionName string `json:"session,omitempty"`
	SessionMode string `json:"sessionMode"`
}

SessionInfo non-secret information about the session used by the server

type WebPicker

type WebPicker struct {
	// OpenBrowser opens the url in the browser. Defaults to the system browser
	OpenBrowser func(url string) error

	// Notify optional callback to draw the user's attention to the browser
	Notify func(message string)

	// Timeout how long the user has to select a session. Defaults to DefaultPickerTimeout
	Timeout time.Duration

	// Login optional function which logs in to the selected session, so the user sees
	// straight away whether the session works, and can retry (e.g. after entering a
	// wrong passphrase). The selection is only finished when the login succeeds
	Login LoginFunc
}

WebPicker lets the user select a session in the browser. It is used when the server has no terminal (stdio mode). A temporary web server listens on the loopback interface for a single selection. As other local processes can reach loopback ports, the page can only be opened with a random one-time code (passed in the URL which is opened in the browser), which is exchanged for a cookie, and the selection must come from the page itself (origin, host and csrf checks).

func (*WebPicker) Pick

func (w *WebPicker) Pick(ctx context.Context, title string, choices []SessionChoice) (*Selection, error)

Pick shows the sessions in the browser and returns the one the user selected (and logged in to, if Login is set)

func (*WebPicker) Unlock

func (w *WebPicker) Unlock(ctx context.Context, title string, message string, choice SessionChoice) (*Selection, error)

Unlock asks the user to log in to a single session again, e.g. to enter the passphrase when the token expires

Jump to

Keyboard shortcuts

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