commands

package
v0.7.1 Latest Latest
Warning

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

Go to latest
Published: May 5, 2025 License: MIT Imports: 30 Imported by: 0

Documentation

Overview

Package commands implements individual commands for the MCP CLI.

Package commands implements individual commands for the MCP CLI.

Index

Constants

View Source
const (
	FlagAllow      = "--allow"
	FlagAllowShort = "-a"
	FlagDeny       = "--deny"
	FlagDenyShort  = "-d"
)

Guard flags.

View Source
const (
	FlagFormat      = "--format"
	FlagFormatShort = "-f"
	FlagParams      = "--params"
	FlagParamsShort = "-p"
	FlagHelp        = "--help"
	FlagHelpShort   = "-h"
	FlagServerLogs  = "--server-logs"
)

flags.

View Source
const (
	EntityTypeTool   = "tool"
	EntityTypePrompt = "prompt"
	EntityTypeRes    = "resource"
)

entity types.

Variables

View Source
var (
	// FormatOption is the format option for the command, valid values are "table", "json", and
	// "pretty".
	// Default is "table".
	FormatOption = "table"
	// ParamsString is the params for the command.
	ParamsString string
	// ShowServerLogs is a flag to show server logs.
	ShowServerLogs bool
)
View Source
var ConfigFileOption string

ConfigFileOption stores the path to the configuration file.

View Source
var CreateClientFunc = func(args []string, _ ...client.ClientOption) (*client.Client, error) {
	if len(args) == 0 {
		return nil, ErrCommandRequired
	}

	if len(args) == 1 {
		server, found := alias.GetServerCommand(args[0])
		if found {
			args = ParseCommandString(server)
		}
	}

	var c *client.Client
	var err error

	if len(args) == 1 && IsHTTP(args[0]) {
		c, err = client.NewSSEMCPClient(args[0])
		if err != nil {
			return nil, err
		}
		err = c.Start(context.Background())
	} else {
		c, err = client.NewStdioMCPClient(args[0], nil, args[1:]...)
	}

	if err != nil {
		return nil, err
	}

	stdErr, ok := client.GetStderr(c)
	if ok && ShowServerLogs {
		go func() {
			scanner := bufio.NewScanner(stdErr)
			for scanner.Scan() {
				fmt.Printf("[>] %s\n", scanner.Text())
			}
		}()
	}

	done := make(chan error, 1)

	go func() {
		_, err := c.Initialize(context.Background(), mcp.InitializeRequest{})
		done <- err
	}()

	select {
	case err := <-done:
		if err != nil {
			return nil, fmt.Errorf("init error: %w", err)
		}
	case <-time.After(10 * time.Second):
		return nil, fmt.Errorf("initialization timed out")
	}

	return c, nil
}

CreateClientFunc is the function used to create MCP clients. This can be replaced in tests to use a mock transport.

View Source
var EnvOption string

EnvOption stores the environment variables.

View Source
var (
	ErrCommandRequired = fmt.Errorf("command to execute is required when using stdio transport")
)

sentinel errors.

View Source
var HeadersOption string

HeadersOption stores the headers for URL-based servers.

View Source
var TemplatesPath = getHomeDirectory() + "/.mcpt/templates"

TemplatesPath information placeholder.

View Source
var URLOption string

URLOption stores the URL for URL-based servers.

View Source
var Version = "dev"

Version information placeholder.

Functions

func AliasCmd

func AliasCmd() *cobra.Command

AliasCmd creates the alias command.

func CallCmd

func CallCmd() *cobra.Command

CallCmd creates the call command.

func ConfigsCmd added in v0.5.0

func ConfigsCmd() *cobra.Command

ConfigsCmd creates the configs command.

func ConvertJSONToMap added in v0.7.0

func ConvertJSONToMap(jsonData any) map[string]any

ConvertJSONToMap converts a JSON serialized object to a map of strings to any type.

func ConvertJSONToSlice added in v0.7.0

func ConvertJSONToSlice(jsonData any) []any

ConvertJSONToSlice converts a JSON serialized object to a slice of any type.

func FormatAndPrintResponse

func FormatAndPrintResponse(cmd *cobra.Command, resp any, err error) error

FormatAndPrintResponse formats and prints an MCP response in the format specified by FormatOption.

func GetPromptCmd

func GetPromptCmd() *cobra.Command

GetPromptCmd creates the get-prompt command.

func GuardCmd added in v0.6.0

func GuardCmd() *cobra.Command

GuardCmd creates the guard command to filter tools, prompts, and resources.

func IsHTTP added in v0.6.0

func IsHTTP(str string) bool

IsHTTP returns true if the string is a valid HTTP URL.

func IsValidFormat added in v0.4.2

func IsValidFormat(format string) bool

IsValidFormat returns true if the format is valid.

func LoadProxyConfig

func LoadProxyConfig() (map[string]map[string]string, error)

LoadProxyConfig loads the proxy configuration from the config file.

func MockCmd

func MockCmd() *cobra.Command

MockCmd creates the mock command.

func NewCmd

func NewCmd() *cobra.Command

NewCmd returns a new 'new' command for scaffolding MCP projects.

func ParseCommandString added in v0.7.0

func ParseCommandString(cmdStr string) []string

ParseCommandString splits a command string into separate arguments, respecting spaces as argument separators. Note: This is a simple implementation that doesn't handle quotes or escapes.

func ProcessFlags

func ProcessFlags(args []string) []string

ProcessFlags processes command line flags, sets the format option, and returns the remaining arguments. Supported format options: json, pretty, and table.

For example, if the input arguments are ["tools", "--format", "pretty", "npx", "-y", "@modelcontextprotocol/server-filesystem", "~"], it would return ["npx", "-y", "@modelcontextprotocol/server-filesystem", "~"] and set the format option to "pretty".

func PromptsCmd

func PromptsCmd() *cobra.Command

PromptsCmd creates the prompts command.

func ProxyCmd

func ProxyCmd() *cobra.Command

ProxyCmd creates the proxy command.

func ProxyStartCmd

func ProxyStartCmd() *cobra.Command

ProxyStartCmd creates the proxy start command.

func ProxyToolCmd

func ProxyToolCmd() *cobra.Command

ProxyToolCmd creates the proxy tool command.

func ReadResourceCmd

func ReadResourceCmd() *cobra.Command

ReadResourceCmd creates the read-resource command.

func ResourcesCmd

func ResourcesCmd() *cobra.Command

ResourcesCmd creates the resources command.

func RootCmd

func RootCmd() *cobra.Command

RootCmd creates the root command.

func SaveProxyConfig

func SaveProxyConfig(config map[string]map[string]string) error

SaveProxyConfig saves the proxy configuration to the config file.

func ShellCmd

func ShellCmd() *cobra.Command

ShellCmd creates the shell command.

func ToolsCmd

func ToolsCmd() *cobra.Command

ToolsCmd creates the tools command.

func VersionCmd

func VersionCmd() *cobra.Command

VersionCmd creates the version command.

func WebCmd added in v0.6.5

func WebCmd() *cobra.Command

WebCmd creates the web command.

Types

type ConfigAlias added in v0.5.0

type ConfigAlias struct {
	Path     string `json:"path"`
	JSONPath string `json:"jsonPath"`
	Source   string `json:"source,omitempty"`
}

ConfigAlias represents a configuration alias.

type ConfigsFile added in v0.5.0

type ConfigsFile struct {
	Aliases map[string]ConfigAlias `json:"aliases"`
}

ConfigsFile represents the structure of the configs file.

type MCPClientCache added in v0.6.5

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

MCPClientCache provides thread-safe access to the MCP client.

type MockTransport

type MockTransport struct {
	ExecuteFunc func(method string, params any) (map[string]any, error)
}

MockTransport implements the transport.Transport interface for testing.

func (*MockTransport) Close added in v0.7.0

func (m *MockTransport) Close() error

Close is a no-op for the mock transport.

func (*MockTransport) SendNotification added in v0.7.0

func (m *MockTransport) SendNotification(_ context.Context, _ mcp.JSONRPCNotification) error

SendNotification is a no-op for the mock transport.

func (*MockTransport) SendRequest added in v0.7.0

SendRequest overrides the default implementation of the transport.SendRequest method.

func (*MockTransport) SetNotificationHandler added in v0.7.0

func (m *MockTransport) SetNotificationHandler(_ func(notification mcp.JSONRPCNotification))

SetNotificationHandler is a no-op for the mock transport.

func (*MockTransport) Start added in v0.7.0

func (m *MockTransport) Start(_ context.Context) error

Start is a no-op for the mock transport.

type ServerConfig added in v0.4.1

type ServerConfig struct {
	Headers     map[string]string      `json:"headers,omitempty"`
	Env         map[string]string      `json:"env,omitempty"`
	Config      map[string]interface{} `json:"config,omitempty"`
	Source      string                 `json:"source"`
	Type        string                 `json:"type,omitempty"`
	Command     string                 `json:"command,omitempty"`
	URL         string                 `json:"url,omitempty"`
	Path        string                 `json:"path,omitempty"`
	Name        string                 `json:"name,omitempty"`
	Description string                 `json:"description,omitempty"`
	Args        []string               `json:"args,omitempty"`
}

ServerConfig represents a configuration for a server.

Jump to

Keyboard shortcuts

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