mcp

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Jul 9, 2026 License: MIT Imports: 31 Imported by: 0

Documentation

Index

Constants

View Source
const ServerAuthOAuth = "oauth"

ServerAuthOAuth is the value of an MCP server's auth field that selects the OAuth 2.0 + PKCE authorization-code flow.

Variables

This section is empty.

Functions

func FormatPermissionList

func FormatPermissionList(permissions []PermissionGrant) string

func FormatTokenStatuses

func FormatTokenStatuses(statuses []TokenStatus) string

FormatTokenStatuses renders a human-readable status table without leaking any token material.

func ResolvePermissionPath

func ResolvePermissionPath(env map[string]string) (string, error)

func ResolveTokenStorePath

func ResolveTokenStorePath(env map[string]string) (string, error)

ResolveTokenStorePath determines the on-disk location of the LEGACY OAuth token file, honoring an explicit override, XDG_CONFIG_HOME, then the user home dir. It is used to locate a pre-unification file for migration.

func SchemaFromMCP

func SchemaFromMCP(input map[string]any) tools.Schema

func SchemaToMCP

func SchemaToMCP(schema tools.Schema) map[string]any

func Serve

func Serve(ctx context.Context, input io.Reader, output io.Writer, registry *tools.Registry, options ServeOptions) error

func TextContent

func TextContent(content []Content) string

func ValidateServerName

func ValidateServerName(name string) error

Types

type CallToolResult

type CallToolResult struct {
	Content []Content `json:"content"`
	IsError bool      `json:"isError,omitempty"`
}

type CheckToolInput

type CheckToolInput struct {
	ServerName        string
	ServerIdentity    string
	ToolName          string
	RequestedAutonomy PermissionAutonomy
}

type Client

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

func (*Client) CallTool

func (client *Client) CallTool(ctx context.Context, name string, args map[string]any) (CallToolResult, error)

func (*Client) Close

func (client *Client) Close() error

func (*Client) ListTools

func (client *Client) ListTools(ctx context.Context) ([]RemoteTool, error)

type Content

type Content struct {
	Type string `json:"type"`
	Text string `json:"text,omitempty"`
}

type GrantServerInput

type GrantServerInput struct {
	ServerName     string
	ServerIdentity string
	MaxAutonomy    PermissionAutonomy
}

type GrantToolInput

type GrantToolInput struct {
	ServerName     string
	ServerIdentity string
	ToolName       string
	MaxAutonomy    PermissionAutonomy
}

type LoginOptions

type LoginOptions struct {
	ServerName string
	ServerURL  string
	Config     OAuthConfig
	HTTPClient *http.Client
	// OpenBrowser is invoked with the authorization URL. The default prints the
	// URL; tests inject a function that drives the loopback redirect.
	OpenBrowser func(authURL string) error
	Timeout     time.Duration
	Now         func() time.Time
}

LoginOptions configures a single interactive authorization-code login.

type OAuthConfig

type OAuthConfig struct {
	ClientID              string
	ClientSecret          string
	Scopes                []string
	AuthorizationEndpoint string
	TokenEndpoint         string
	RegistrationEndpoint  string
	// IssuerURL overrides the base URL used for metadata discovery. When empty
	// the MCP server URL is used.
	IssuerURL string
}

OAuthConfig describes how to authenticate to a remote MCP server using OAuth. Endpoints may be discovered from the server's metadata document; explicit values here override or fill in anything discovery cannot provide.

type PermissionAutonomy

type PermissionAutonomy string
const (
	AutonomyLow    PermissionAutonomy = "low"
	AutonomyMedium PermissionAutonomy = "medium"
	AutonomyHigh   PermissionAutonomy = "high"
)

type PermissionGrant

type PermissionGrant struct {
	Scope          PermissionScope    `json:"scope"`
	ServerName     string             `json:"serverName"`
	ServerIdentity string             `json:"serverIdentity"`
	ToolName       string             `json:"toolName,omitempty"`
	MaxAutonomy    PermissionAutonomy `json:"maxAutonomy"`
	ApprovedAt     string             `json:"approvedAt"`
}

type PermissionScope

type PermissionScope string
const (
	ScopeServer PermissionScope = "server"
	ScopeTool   PermissionScope = "tool"
)

type PermissionStore

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

func NewPermissionStore

func NewPermissionStore(options StoreOptions) (*PermissionStore, error)

func (*PermissionStore) Clear

func (store *PermissionStore) Clear() (int, error)

func (*PermissionStore) FilePath

func (store *PermissionStore) FilePath() string

func (*PermissionStore) GrantServer

func (store *PermissionStore) GrantServer(input GrantServerInput) (PermissionGrant, error)

func (*PermissionStore) GrantTool

func (store *PermissionStore) GrantTool(input GrantToolInput) (PermissionGrant, error)

func (*PermissionStore) IsToolPersistentlyApproved

func (store *PermissionStore) IsToolPersistentlyApproved(input CheckToolInput) (bool, error)

func (*PermissionStore) List

func (store *PermissionStore) List() ([]PermissionGrant, error)

func (*PermissionStore) RevokeServer

func (store *PermissionStore) RevokeServer(serverName string) (int, error)

func (*PermissionStore) RevokeTool

func (store *PermissionStore) RevokeTool(serverName string, toolName string) (int, error)

type Prompt

type Prompt struct {
	Name        string           `json:"name"`
	Description string           `json:"description"`
	Arguments   []PromptArgument `json:"arguments,omitempty"`
}

Prompt describes a curated prompt template advertised through prompts/list.

type PromptArgument

type PromptArgument struct {
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
	Required    bool   `json:"required,omitempty"`
}

PromptArgument describes one templated argument of a prompt.

type PromptMessage

type PromptMessage struct {
	Role    string               `json:"role"`
	Content PromptMessageContent `json:"content"`
}

PromptMessage is one message in a rendered prompt (prompts/get result).

type PromptMessageContent

type PromptMessageContent struct {
	Type string `json:"type"`
	Text string `json:"text"`
}

PromptMessageContent carries the rendered text of a prompt message.

type RegisterOptions

type RegisterOptions struct {
	PermissionStore *PermissionStore
	Autonomy        PermissionAutonomy
	ClientFactory   func(context.Context, Server) (ToolClient, error)
	// ConnectTimeout bounds the per-server connect+list at startup. Zero uses
	// defaultConnectTimeout.
	ConnectTimeout time.Duration
}

type RemoteTool

type RemoteTool struct {
	Name        string         `json:"name"`
	Description string         `json:"description,omitempty"`
	InputSchema map[string]any `json:"inputSchema,omitempty"`
}

type Resource

type Resource struct {
	URI         string `json:"uri"`
	Name        string `json:"name"`
	MimeType    string `json:"mimeType,omitempty"`
	Description string `json:"description,omitempty"`
}

Resource describes a workspace file advertised through resources/list. Only the fields ZERO populates are emitted; pagination cursors and icons are not used.

type ResourceContents

type ResourceContents struct {
	URI      string `json:"uri"`
	MimeType string `json:"mimeType,omitempty"`
	Text     string `json:"text,omitempty"`
	Blob     string `json:"blob,omitempty"`
}

ResourceContents is one entry in a resources/read result. Exactly one of Text or Blob is populated: Text for UTF-8 files, base64 Blob for binary files.

type Runtime

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

func RegisterTools

func RegisterTools(ctx context.Context, registry *tools.Registry, cfg config.MCPConfig, options RegisterOptions) (*Runtime, error)

func (*Runtime) Close

func (runtime *Runtime) Close() error

func (*Runtime) Skipped

func (runtime *Runtime) Skipped() []SkippedServer

Skipped returns the servers that were skipped during registration (unreachable or invalid), so the caller can warn the user without failing the launch.

type ServeOptions

type ServeOptions struct {
	Name              string
	Version           string
	PermissionGranted bool
	// WorkspaceRoot is the directory whose files are exposed as MCP resources.
	// Empty means the process working directory. Resource reads are confined to
	// this root (and any extra Scope roots).
	WorkspaceRoot string
	// Scope, when set, widens the resource roots beyond WorkspaceRoot using the
	// same multi-root scoping the sandbox/file tools use. nil means
	// workspace-only.
	Scope tools.PathScope
}

type Server

type Server struct {
	Name     string
	Type     ServerType
	Command  string
	Args     []string
	Env      map[string]string
	URL      string
	Headers  map[string]string
	Auth     string
	OAuth    *OAuthConfig
	Identity string
	// UnconfiguredDefault is true when this server is one of Zero's built-in
	// defaults (e.g. keyless Firecrawl) that the user never touched in their
	// config — no credentials, no overrides. Callers use it to avoid warning
	// loudly when a server nobody configured fails to connect.
	UnconfiguredDefault bool
}

func NormalizeConfig

func NormalizeConfig(cfg config.MCPConfig) ([]Server, error)

type ServerType

type ServerType string
const (
	ServerTypeStdio ServerType = "stdio"
	ServerTypeHTTP  ServerType = "http"
	ServerTypeSSE   ServerType = "sse"
)

type SkippedServer

type SkippedServer struct {
	Name string
	Err  error
	// UnconfiguredDefault mirrors Server.UnconfiguredDefault: true when this
	// server is an out-of-the-box default the user never configured, so a
	// caller can skip warning loudly about it.
	UnconfiguredDefault bool
}

SkippedServer records an MCP server that was not registered because it could not be reached or its tools could not be validated. Registration is best-effort per server: one unreachable server is skipped (and reported here) rather than aborting startup or disabling the others.

type StoreOptions

type StoreOptions struct {
	FilePath string
	Now      func() time.Time
	Env      map[string]string
}

type StoredToken

type StoredToken struct {
	AccessToken  string    `json:"access_token"`
	RefreshToken string    `json:"refresh_token,omitempty"`
	TokenType    string    `json:"token_type,omitempty"`
	Scopes       []string  `json:"scopes,omitempty"`
	ExpiresAt    time.Time `json:"expires_at,omitempty"`
}

StoredToken holds the credentials issued by an OAuth 2.0 authorization server for a single MCP server. The token fields are sensitive: they are tagged so the repo's redaction layer masks them, and they must never be written to logs or stream output.

func Login

func Login(ctx context.Context, options LoginOptions) (StoredToken, error)

Login runs the full OAuth 2.0 + PKCE authorization-code flow: it discovers (or falls back to configured) endpoints, optionally registers a client, starts a loopback redirect listener, opens the authorization URL, validates the callback state, and exchanges the code for tokens. Tokens are returned and are never logged.

type TokenStatus

type TokenStatus struct {
	ServerName      string    `json:"serverName"`
	HasToken        bool      `json:"hasToken"`
	HasRefreshToken bool      `json:"hasRefreshToken"`
	TokenType       string    `json:"tokenType,omitempty"`
	Scopes          []string  `json:"scopes,omitempty"`
	ExpiresAt       time.Time `json:"expiresAt,omitempty"`
	Expired         bool      `json:"expired"`
}

TokenStatus is a redaction-safe summary of a stored token. It deliberately omits the access and refresh token material so it can be printed by the CLI.

type TokenStore

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

TokenStore persists MCP OAuth tokens in the unified oauth store (internal/oauth) under the "mcp:" namespace, sharing one file with provider logins. On construction it transparently and non-destructively migrates a legacy mcp-oauth-tokens.json into the unified store.

func NewTokenStore

func NewTokenStore(options TokenStoreOptions) (*TokenStore, error)

NewTokenStore builds the unified-store-backed token store and runs a one-time migration from a legacy file when applicable.

func (*TokenStore) Delete

func (store *TokenStore) Delete(serverName string) (bool, error)

Delete removes the stored token for a server. It reports whether an entry was present before deletion.

func (*TokenStore) FilePath

func (store *TokenStore) FilePath() string

FilePath returns the resolved unified store path.

func (*TokenStore) Load

func (store *TokenStore) Load(serverName string) (StoredToken, bool, error)

Load returns the stored token for a server. The second return value is false when no token has been stored for the server.

func (*TokenStore) Save

func (store *TokenStore) Save(serverName string, token StoredToken) error

Save persists the token for a server, replacing any existing entry.

func (*TokenStore) Status

func (store *TokenStore) Status() ([]TokenStatus, error)

Status returns a redaction-safe summary of every stored MCP token, sorted by server name. It never includes the token material.

type TokenStoreOptions

type TokenStoreOptions struct {
	FilePath   string
	LegacyPath string
	Env        map[string]string
	Now        func() time.Time
}

TokenStoreOptions configures the unified token store backing MCP OAuth tokens. FilePath overrides the store path (default: the shared oauth store path). LegacyPath overrides the pre-unification file migrated on construction; when empty it defaults to the conventional mcp-oauth-tokens.json only for the default (FilePath-unset) store, so an explicit FilePath never triggers an unexpected migration from the real user config.

type ToolClient

type ToolClient interface {
	ListTools(context.Context) ([]RemoteTool, error)
	CallTool(context.Context, string, map[string]any) (CallToolResult, error)
	Close() error
}

func Connect

func Connect(ctx context.Context, server Server) (ToolClient, error)

Jump to

Keyboard shortcuts

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