mcpext

package
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Oct 5, 2026 License: MIT Imports: 47 Imported by: 0

Documentation

Overview

Package mcpext is the built-in MCP integration (`builtin:mcp`).

It connects the servers from `mcp.json` and the servers extensions register with registerMcpServer, and registers their tools as `mcp__<server>__<tool>`. The package depends on the MCP client (package mcp) and on a small Host interface, not on the extension runner, so a Piglet can leave the package out of its build or disable it at startup without touching any other code: one registration seam links it, and nothing else imports it.

The `/mcp` command and its terminal manager view are registered by Factory. The `pi mcp` CLI is wired by the CLI family; this package exposes what it needs: the connections, the server list and its change notifications, sign-in and sign-out, reconnect, enable and exposure changes, and the config editors.

Index

Constants

View Source
const (

	// CodemodeToolName and ToolSearchToolName are the tools that reach MCP tools that are not declared.
	CodemodeToolName   = "codemode"
	ToolSearchToolName = "tool_search"
)
View Source
const (
	ListMcpResourcesTool         = "list_mcp_resources"
	ListMcpResourceTemplatesTool = "list_mcp_resource_templates"
)

Names of the resource tools.

View Source
const (

	// McpOutputMaxBytes: model-facing text of an MCP result beyond this is cut in the middle.
	// upstream: packages/coding-agent/src/extensions/mcp/tools.ts:MCP_OUTPUT_MAX_BYTES
	McpOutputMaxBytes = 20 * 1024
	// ReadMcpResourceTool is the tool that reads the resources named by resource links.
	ReadMcpResourceTool = "read_mcp_resource"
)
View Source
const MaxServersSectionChars = 4096

MaxServersSectionChars is the size of the whole `mcp_servers` section in UTF-16 code units. Descriptions shrink to fit; when the server lines alone do not fit, the last servers are left out and counted in a closing line.

Ports packages/coding-agent/src/extensions/mcp/index.ts (MAX_SERVERS_SECTION_CHARS).

View Source
const McpServersSection = "mcp_servers"

McpServersSection is the name of the system prompt section that lists the servers whose tools are not declared.

Ports packages/coding-agent/src/extensions/mcp/index.ts (MCP_SERVERS_SECTION).

View Source
const McpUsage = "Usage: /mcp, /mcp login [server], /mcp logout [server], /mcp reconnect [server]"

McpUsage is MCP_USAGE. upstream: packages/coding-agent/src/extensions/mcp/index.ts:160

Variables

This section is empty.

Functions

func AddMcpServerConfig

func AddMcpServerConfig(path, name string, config extension.McpServerConfig) (bool, error)

AddMcpServerConfig adds a server to an `mcp.json`, creating the file when missing. An existing entry with the same name is replaced. It returns true when an entry was replaced.

func AddMcpServerConfigJSON

func AddMcpServerConfigJSON(path, name string, config json.RawMessage) (bool, error)

AddMcpServerConfigJSON is AddMcpServerConfig for a config given as JSON text: the entry is written with its members in the given order.

func ConvertMcpResult

func ConvertMcpResult(server, tool string, result *mcp.CallToolResult, options ConvertMcpResultOptions) (agent.AgentToolResult, error)

ConvertMcpResult converts an MCP result. `isError` results become error results that keep the structured result.

func CreateDefaultTransport

func CreateDefaultTransport(entry McpServerEntry, cwd string, authProvider mcp.AuthProvider) (mcp.Transport, error)

CreateDefaultTransport builds the stdio or streamable HTTP transport a server's config asks for.

func CreateMcpResourceToolDefinitions

func CreateMcpResourceToolDefinitions(options ResourceToolsOptions) []extension.ToolDefinition

CreateMcpResourceToolDefinitions builds the three resource tools.

func CreateMcpResultSchema

func CreateMcpResultSchema(structuredContentSchema json.RawMessage) json.RawMessage

CreateMcpResultSchema is the output schema of every MCP tool: the `CallToolResult` scripts receive, with the tool's own output schema as `structuredContent`. Codemode detects this shape to render `CallToolResult<T>` declarations.

func CreateMcpToolDefinition

func CreateMcpToolDefinition(options McpToolOptions) extension.ToolDefinition

CreateMcpToolDefinition adapts one MCP tool to a tool definition.

func CreateMcpToolName

func CreateMcpToolName(server, tool string, isTaken func(string) bool) string

CreateMcpToolName is `mcp__<server>__<tool>`, sanitized and shortened with a hash suffix when too long. Like Codex, everything but `[A-Za-z0-9_]` becomes `_`, so the name is also the identifier codemode scripts call it by. isTaken reports names used by a different MCP tool: sanitizing can map two tools to one name (`a-b` and `a_b`), which then get the hash suffix.

func CreateMcpToolRenderers

func CreateMcpToolRenderers(label string) *extension.ToolRenderers

CreateMcpToolRenderers returns the renderers of calls to an MCP tool, labeled `server/tool`, also used before the tool is registered. upstream: packages/coding-agent/src/extensions/mcp/tools.ts:createMcpToolRenderers

func Factory

func Factory(options Options) func(api API) *Extension

Factory returns the extension factory for `builtin:mcp`: it subscribes the extension's handlers, exactly the events upstream's index.ts subscribes to. It returns the extension so a host can reach its actions.

func FormatMcpLogMessage

func FormatMcpLogMessage(server string, params json.RawMessage, now time.Time) string

FormatMcpLogMessage formats one `notifications/message` from server as a log line; continuation lines are indented.

func IsMcpAppResource

func IsMcpAppResource(uri, mimeType string) bool

IsMcpAppResource reports an MCP App user interface, which only hosts that render them can use. uri is the resource's `uri` or a template's `uriTemplate`.

func LimitMcpContent

func LimitMcpContent(content []ai.ToolResultMessageContent, saveOutput McpOutputSaver) ([]ai.ToolResultMessageContent, string)

LimitMcpContent keeps model-facing text within McpOutputMaxBytes. Longer text becomes one text block in Codex's truncation format, followed by the path of the file with the full text; images follow it.

func NewBuiltin

func NewBuiltin(options Options) (extension.Extension, error)

NewBuiltin builds the `builtin:mcp` extension: Factory registered on an in-process API, so the extension's event handlers, `/mcp` command and tools reach a Session's runner like those of any extension. The loader names it and supplies its source.

Ports packages/coding-agent/src/extensions/index.ts (the `mcp` entry of builtInExtensions).

func RemoveMcpServerConfig

func RemoveMcpServerConfig(path, name string) (bool, error)

RemoveMcpServerConfig removes a server from an `mcp.json`. It returns false when the file does not define it.

func RenderServersSection

func RenderServersSection(servers []McpServerListing) (string, bool)

RenderServersSection is the `mcp_servers` section: every enabled server with codemode or deferred tools, with how its tools are reached and a one-line summary. The model learns of the servers from it, since neither codemode nor tool_search lists them. It reports false when there are no such servers.

Ports packages/coding-agent/src/extensions/mcp/index.ts (renderServersSection).

func RunMcpCommand

func RunMcpCommand(ctx context.Context, args []string, options McpCommandOptions) int

RunMcpCommand runs `mcp <args>` and returns the exit code.

func SaveToTempFile

func SaveToTempFile(data []byte, extension string) (string, error)

SaveToTempFile is the default McpOutputSaver. Results can carry private data, so only the user may read the file.

func SignInMcpServer

func SignInMcpServer(ctx context.Context, options SignInOptions) error

SignInMcpServer signs in to an MCP server. It uses the stored refresh token when possible; otherwise it runs the browser authorization code flow. Tokens are saved to the store.

func ToModelContent

func ToModelContent(server string, blocks []mcp.ContentBlock, options ConvertMcpResultOptions) []ai.ToolResultMessageContent

ToModelContent is the model-facing content of server's content blocks, before the output limit.

func ToToolExposure

func ToToolExposure(exposure extension.McpExposure) extension.ToolExposure

ToToolExposure is the tool exposure of an MCP exposure. `codemode` and `deferred` both leave tools out of the codemode description; they differ only in which tool the MCP extension activates to reach them.

func UpdateMcpServerConfig

func UpdateMcpServerConfig(path, name string, patch McpServerConfigPatch, options ...UpdateMcpServerConfigOptions) error

UpdateMcpServerConfig changes one server's settings in the `mcp.json` that defines or overrides it. With options' Override (upstream's optional `options`), a missing entry is added as an override. Overrides keep default values, since they replace the global server's. Other content is kept; the file is rewritten with its indentation.

Types

type API

type API interface {
	OnSessionStart(handler func(ctx context.Context, evt extension.SessionStartEvent) error)
	OnBeforeAgentStart(handler func(ctx context.Context, evt extension.BeforeAgentStartEvent) (extension.BeforeAgentStartEventResult, error))
	OnToolCall(handler func(ctx context.Context, evt extension.ToolCallEvent) (extension.ToolCallEventResult, error))
	OnTurnStart(handler func(ctx context.Context, evt extension.TurnStartEvent) error)
	OnMcpServersChange(handler func(ctx context.Context, evt extension.McpServersChangeEvent) error)
	OnSessionShutdown(handler func(ctx context.Context, evt extension.SessionShutdownEvent) error)
	RegisterCommand(name string, options extension.CommandOptions)
	RegisterTool(tool extension.ToolDefinition)
	GetAllTools() []extension.ToolInfo
	GetActiveTools() []string
	SetActiveTools(names []string)
	GetMcpServers() []extension.RegisteredMcpServer
	RegisterToolRenderer(resolver extension.ToolRendererResolver)
}

API is the part of the extension API the built-in extension registers on: the events upstream's index.ts subscribes to, the `/mcp` command, the tool registry and the MCP server registry (`registerMcpServer` and its `mcp_servers_change` event).

type AuthStorageBackend

type AuthStorageBackend interface {
	// WithLock calls fn with the current content (exists is false when there is
	// none) while no other holder reads or writes it. When fn returns a non-nil
	// next, it replaces the content.
	WithLock(fn func(current string, exists bool) (next *string, err error)) error
}

AuthStorageBackend gives exclusive read-modify-write access to one stored document.

type CommandContext

type CommandContext struct {
	EventContext
	// Mode is the mode the command runs in; the manager view opens only in the terminal UI.
	Mode extension.ExtensionMode
	// HasUI reports whether the mode can ask the user.
	HasUI bool
	// Select shows a selector (ctx.ui.select) and returns the choice; ok is false when the user cancelled.
	Select func(ctx context.Context, title string, options []string) (choice string, ok bool)
	// Input shows a text input (ctx.ui.input) that ends when ctx is done; ok is false when the user cancelled.
	Input func(ctx context.Context, title, placeholder string) (value string, ok bool)
	// ShowManager runs manage in the manager view (showMcpManager) and returns when it does.
	ShowManager func(ctx context.Context, manage func(ui McpUi) error) error
}

CommandContext is the part of ExtensionCommandContext the `/mcp` handler uses.

type Connection

type Connection struct {
	// Entry is the server's configuration.
	Entry McpServerEntry
	// contains filtered or unexported fields
}

Connection is one configured server. It reconnects lazily when a call finds the connection gone. It is safe for concurrent use.

func NewConnection

func NewConnection(options ConnectionOptions) (*Connection, error)

NewConnection returns a connection in the connecting state. It does not connect until the first call to Connection.GetClient.

func (*Connection) AllResourceTemplates

func (c *Connection) AllResourceTemplates(ctx context.Context, options mcp.RequestOptions) ([]mcp.ResourceTemplate, error)

AllResourceTemplates lists every resource template.

func (*Connection) AllResources

func (c *Connection) AllResources(ctx context.Context, options mcp.RequestOptions) ([]mcp.Resource, error)

AllResources lists every resource.

func (*Connection) CallTool

func (c *Connection) CallTool(ctx context.Context, name string, args any, options mcp.RequestOptions) (*mcp.CallToolResult, error)

CallTool calls a tool, reconnecting when needed. Tool calls are not retried after a transient HTTP error, since they may have run.

func (*Connection) Challenge

func (c *Connection) Challenge() *oauth.OAuthChallenge

Challenge is the last OAuth challenge from the server; sign-in uses its resource metadata URL and scope.

func (*Connection) ClearChallenge

func (c *Connection) ClearChallenge()

ClearChallenge drops the challenge that asked for a sign-in, once it is answered.

func (*Connection) Close

func (c *Connection) Close()

Close shuts the connection down and waits for its background work.

func (*Connection) Error

func (c *Connection) Error() string

Error is the last error, or "".

func (*Connection) GetClient

func (c *Connection) GetClient(ctx context.Context) (*mcp.Client, error)

GetClient returns the connected client, connecting first when needed. Concurrent callers share one connection attempt.

func (*Connection) HasResources

func (c *Connection) HasResources() bool

HasResources reports whether the server offers resources.

func (*Connection) Instructions

func (c *Connection) Instructions() string

Instructions are the server instructions from `initialize`, describing its tools as a group.

func (*Connection) Name

func (c *Connection) Name() string

Name is the server's name.

func (*Connection) OAuthSettings

func (c *Connection) OAuthSettings() (McpOAuthSettings, error)

OAuthSettings resolves the server's OAuth settings. A client secret that fails to resolve is an error.

func (*Connection) OAuthURL

func (c *Connection) OAuthURL() string

OAuthURL is the server URL when the server authenticates with OAuth, or "".

func (*Connection) ReadResource

func (c *Connection) ReadResource(ctx context.Context, uri string, options mcp.RequestOptions) (*mcp.ReadResourceResult, error)

ReadResource reads a resource.

func (*Connection) Reconnect

func (c *Connection) Reconnect(ctx context.Context) error

Reconnect connects again with fresh credentials, for example after signing in.

func (*Connection) ResourceTemplates

func (c *Connection) ResourceTemplates() []mcp.ResourceTemplate

ResourceTemplates returns the templates listed at the last connect or change.

func (*Connection) ResourceTemplatesPage

func (c *Connection) ResourceTemplatesPage(ctx context.Context, cursor *string, options mcp.RequestOptions) (*mcp.ListResourceTemplatesResult, error)

ResourceTemplatesPage lists one page of resource templates.

func (*Connection) Resources

func (c *Connection) Resources() []mcp.Resource

Resources returns the resources listed at the last connect or change, without MCP App resources.

func (*Connection) ResourcesPage

func (c *Connection) ResourcesPage(ctx context.Context, cursor *string, options mcp.RequestOptions) (*mcp.ListResourcesResult, error)

ResourcesPage lists one page of resources.

func (*Connection) SignOut

func (c *Connection) SignOut()

SignOut disconnects after the stored credentials were removed.

func (*Connection) State

func (c *Connection) State() ServerState

State is the connection state.

func (*Connection) Timeout

func (c *Connection) Timeout() time.Duration

Timeout is the per-request timeout.

func (*Connection) Tools

func (c *Connection) Tools() []mcp.Tool

Tools returns the tools the server offered at the last connect or change.

type ConnectionOptions

type ConnectionOptions struct {
	Entry           McpServerEntry
	Cwd             string
	CreateTransport TransportFactory
	Credentials     *McpOAuthCredentialStore
	// ProviderToken is the current token of a pi provider, for servers with `auth.provider`. It returns "" when the
	// provider has none.
	ProviderToken func(ctx context.Context, provider string) string
	// OnTools is called when the server's tools or resources change.
	OnTools func(*Connection)
	// OnChange is called when the state, error, or tools change.
	OnChange func(*Connection)
	// Log receives the server's log messages (`notifications/message`).
	Log *McpServerLog
	// ClientName and ClientVersion identify this client to servers. Defaults:
	// "pig" and the PiG version (upstream sends its VERSION).
	ClientName    string
	ClientVersion string
}

ConnectionOptions configure a Connection.

type ConvertMcpResultOptions

type ConvertMcpResultOptions struct {
	// SaveOutput saves truncated text and binary resources. Default: a temp file.
	SaveOutput McpOutputSaver
	// ReadableResources says whether the server's resources can be read with
	// `read_mcp_resource`, which resource links then name.
	ReadableResources bool
}

ConvertMcpResultOptions configure ConvertMcpResult.

type EventContext

type EventContext struct {
	// Cwd is the working directory of the session, for stdio servers.
	Cwd string
	// ProviderToken is the current token of a pi provider of the session's model registry, for servers with
	// `auth.provider`. It returns "" when the provider has none.
	ProviderToken func(ctx context.Context, provider string) string
	// IsProjectTrusted reports whether project configuration may be read.
	IsProjectTrusted func() bool
	// Notify shows a message to the user. Level is "info", "warning", or "error".
	Notify func(message, level string)
}

EventContext is the extension context an event handler receives.

type Extension

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

Extension is the MCP integration of one session. Its event methods are what upstream registers with `pi.on(...)`. It is safe for concurrent use.

func New

func New(host Host, options Options) *Extension

New returns the extension for host.

func (*Extension) BeforeAgentStart

func (e *Extension) BeforeAgentStart(ctx EventContext, options *extension.BuildSystemPromptOptions)

BeforeAgentStart is the `before_agent_start` handler. The first prompt waits for the servers with direct tools ([Extension.waitForDirectServers]). Every prompt lists the servers in the `mcp_servers` section as they are when it starts; the session appends the section to the conversation when it changed, for example after a server connected.

func (*Extension) CompleteCommand

func (e *Extension) CompleteCommand(prefix string) []extension.AutocompleteItem

CompleteCommand is the argument completion of `/mcp`; it returns nil where upstream returns null. upstream: packages/coding-agent/src/extensions/mcp/index.ts:904-924

func (*Extension) DescribeState

func (e *Extension) DescribeState(name string, withError bool) string

DescribeState is the short state of a server, for lists.

func (*Extension) EnsureDiscoveryActive

func (e *Extension) EnsureDiscoveryActive(ctx EventContext)

EnsureDiscoveryActive activates the tool that reaches the connected servers' tools that are not declared, after a `/mcp` action.

func (*Extension) FormatStatus

func (e *Extension) FormatStatus() string

FormatStatus is the plain status of every server, for `/mcp` without a terminal manager.

func (*Extension) Manage

func (e *Extension) Manage(ctx context.Context, ui McpUi, ec EventContext) error

Manage runs the manager in ui until the user closes it. upstream: packages/coding-agent/src/extensions/mcp/index.ts:687-701 (manage)

func (*Extension) McpServersChange

func (e *Extension) McpServersChange(ctx EventContext)

McpServersChange is the `mcp_servers_change` handler. Servers registered or unregistered during the session connect or disconnect right away.

func (*Extension) Notices

func (e *Extension) Notices() []string

Notices are the config errors and overridden registrations, for the manager.

func (*Extension) Pending

func (e *Extension) Pending()

Pending waits for the startup connections, or returns at once when there are none.

func (*Extension) Reconnect

func (e *Extension) Reconnect(ctx context.Context, name string) string

Reconnect connects a server again. It returns a message describing a failure, or "" on success.

func (*Extension) RunCommand

func (e *Extension) RunCommand(ctx context.Context, args string, c CommandContext) error

RunCommand is the handler of `/mcp`. It returns what upstream's handler throws: a manager view that could not be shown and a sign-out whose credentials could not be removed. The runner reports it as a command error. upstream: packages/coding-agent/src/extensions/mcp/index.ts:925-977

func (*Extension) Servers

func (e *Extension) Servers() []ServerView

Servers returns the configured servers, in order.

func (*Extension) SessionShutdown

func (e *Extension) SessionShutdown()

SessionShutdown is the `session_shutdown` handler: it closes every connection and waits for the extension's background work.

func (*Extension) SessionStart

func (e *Extension) SessionStart(ctx EventContext)

SessionStart is the `session_start` handler. It loads the configuration and connects the enabled servers on a goroutine the extension owns and drains in Extension.SessionShutdown; the first prompt waits for them in Extension.BeforeAgentStart.

func (*Extension) SetEnabled

func (e *Extension) SetEnabled(ctx EventContext, name string, enabled bool, inProject ...bool) string

SetEnabled enables or disables a server and saves the choice, as a project override with inProject (upstream's optional `inProject`, default false). It returns an error message when the config could not be saved; connection errors show in the state.

func (*Extension) SetExposure

func (e *Extension) SetExposure(name string, exposure extension.McpExposure) string

SetExposure changes a server's exposure and saves the choice. It returns an error message when the config could not be saved.

func (*Extension) SetMessage

func (e *Extension) SetMessage(name, message string)

SetMessage records the result of a failed action for the manager.

func (*Extension) SignIn

func (e *Extension) SignIn(ctx context.Context, name string, prompt McpSignInPrompt) string

SignIn signs in to a server through the browser flow and reconnects. It returns a message describing a failure, or "" on success.

func (*Extension) SignOut

func (e *Extension) SignOut(name string) (bool, error)

SignOut removes a server's stored credentials and disconnects it. It returns whether credentials were stored.

func (*Extension) Subscribe

func (e *Extension) Subscribe(listener func()) (unsubscribe func())

Subscribe registers a function called whenever the servers or their state change. The returned function removes it.

func (*Extension) ToolCall

func (e *Extension) ToolCall(ctx context.Context, toolName string, input map[string]any)

ToolCall is the `tool_call` handler: a codemode script waits for the servers it names, or for every server when it searches or enumerates tools, so their tools are registered before the script runs. tool_search and the resource tools reach every server, so they wait for all of them. It returns when the servers settled or ctx ends.

Ports packages/coding-agent/src/extensions/mcp/index.ts (pi.on("tool_call")).

func (*Extension) TurnStart

func (e *Extension) TurnStart(ctx EventContext)

TurnStart is the `turn_start` handler. It picks up sign-ins done outside the session, such as `pi mcp login` run by the agent.

type FileAuthStorageBackend

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

FileAuthStorageBackend stores the document in a file guarded by Pi's directory lock protocol. The file is created private (0600) in a private directory (0700).

func NewFileAuthStorageBackend

func NewFileAuthStorageBackend(path string) *FileAuthStorageBackend

NewFileAuthStorageBackend returns a backend for path.

func (*FileAuthStorageBackend) WithLock

func (b *FileAuthStorageBackend) WithLock(fn func(current string, exists bool) (*string, error)) (err error)

WithLock implements AuthStorageBackend.

type Host

type Host interface {
	// RegisterTool registers a tool, replacing an earlier registration of the
	// name. Tools with `direct` exposure are activated on registration.
	RegisterTool(definition extension.ToolDefinition)
	// GetAllTools returns every registered tool.
	GetAllTools() []extension.ToolInfo
	GetActiveTools() []string
	SetActiveTools(names []string)
	// GetMcpServers returns the servers extensions registered.
	GetMcpServers() []extension.RegisteredMcpServer
}

Host is the part of the extension API the MCP extension uses. The runner implements it; a Piglet that leaves the extension out never needs it.

type InMemoryAuthStorageBackend

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

InMemoryAuthStorageBackend keeps the document in memory.

func (*InMemoryAuthStorageBackend) WithLock

func (b *InMemoryAuthStorageBackend) WithLock(fn func(current string, exists bool) (*string, error)) error

WithLock implements AuthStorageBackend.

type LoadOptions

type LoadOptions struct {
	AgentDir string
	Cwd      string
	// ProjectTrusted reads the project's `mcp.json` too. Untrusted projects
	// cannot add or override servers, since stdio servers run commands.
	ProjectTrusted bool
	// ConfigDirName is the per-project configuration directory, `.pi` upstream.
	ConfigDirName string
}

LoadOptions locate the configuration.

type LoadedMcpConfig

type LoadedMcpConfig struct {
	Servers []McpServerEntry
	// AutoEnableCodemode activates the codemode tool when `codemode` servers
	// connect. Nil means the default, true.
	AutoEnableCodemode *bool
	Errors             []string
	// ProjectConfig is the project `mcp.json` when the project is trusted,
	// where `/mcp` saves project overrides.
	ProjectConfig string
}

LoadedMcpConfig is the result of LoadMcpConfig.

func LoadMcpConfig

func LoadMcpConfig(options LoadOptions) LoadedMcpConfig

LoadMcpConfig loads global and (when trusted) project MCP configuration. Disabled servers are included with `enabled: false`, so they can be enabled again.

type ManagerHost

type ManagerHost interface{ RequestRender() }

ManagerHost is the terminal the manager view asks to draw again.

type McpAuthProvider

type McpAuthProvider interface {
	mcp.AuthProvider
	mcp.UnauthorizedHandler
	// Settled returns when no refresh is running, so shutdown does not drop
	// rotated tokens before they are saved.
	Settled(ctx context.Context)
}

McpAuthProvider is the auth provider of MCP connections.

func NewMcpAuthProvider

func NewMcpAuthProvider(options McpAuthProviderOptions) McpAuthProvider

NewMcpAuthProvider returns the auth provider for MCP connections: it sends the stored access token and refreshes it when it is about to expire or after a 401. It fails with oauth.McpOAuthAuthorizationRequiredError when the user has to sign in, including when the server asks for more scope (`insufficient_scope`).

Many servers rotate refresh tokens, so two refreshes with the same refresh token lose the grant. Requests in this process share one refresh, and other processes are kept out by the store's refresh lock, held from reading the tokens to saving new ones. Tokens that changed meanwhile (another process refreshed them, or the user signed in) are used without refreshing.

type McpAuthProviderOptions

type McpAuthProviderOptions struct {
	ServerURL string
	Store     McpOAuthServerStore
	// Settings is only called when a refresh is needed, so a secret that fails
	// to resolve fails the refresh instead of the whole connection setup.
	Settings func() (McpOAuthSettings, error)
	// OnChallenge receives the server's WWW-Authenticate challenge so sign-in
	// can use its resource metadata URL and scope.
	OnChallenge func(oauth.OAuthChallenge)
	// AppName is the OAuth client name. Default: "pig".
	AppName string
}

McpAuthProviderOptions configure NewMcpAuthProvider.

type McpCommandOptions

type McpCommandOptions struct {
	Cwd      string
	AgentDir string
	// AppName and ConfigDirName are the CLI name and the per-project configuration directory, `pi` and `.pi` upstream. Defaults: "pig" and ".pig".
	AppName       string
	ConfigDirName string
	// Credentials defaults to `mcp-auth.json` in AgentDir.
	Credentials *McpOAuthCredentialStore
	// OpenURL opens the sign-in URL in the platform browser. Nil opens nothing.
	OpenURL func(url string)
	// IsProjectTrusted reports whether the project at cwd is trusted; an error ends the command with exit code 1. Nil means untrusted.
	IsProjectTrusted func(cwd string) (bool, error)
	// Interactive lets `login` read a pasted redirect URL from Stdin. Upstream's condition is a terminal on stdin and no injected URL opener, which the caller decides.
	Interactive bool
	// Stdin is where a pasted redirect URL is read from; PromptOutput receives the question. Defaults: standard input and standard error.
	Stdin        io.Reader
	PromptOutput io.Writer
	// Color styles the help text and hints as a terminal renders chalk.bold and chalk.dim.
	Color bool
	// Log and Error receive the output lines. Defaults: standard output and standard error.
	Log   func(line string)
	Error func(line string)
}

McpCommandOptions configure RunMcpCommand.

type McpManagerView

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

McpManagerView is the `/mcp` manager view: menus that rebuild while servers connect, a read-only status screen, and the sign-in screen that accepts a pasted redirect URL. The manager calls Menu, Status and RedirectURL from its own goroutine; Render and HandleInput run on the interactive loop. upstream: packages/coding-agent/src/extensions/mcp/ui.ts:McpManagerView

func NewMcpManagerView

func NewMcpManagerView(host ManagerHost, theme *tui.Theme, keybindings *tui.TUIKeybindingsManager) *McpManagerView

NewMcpManagerView returns the view, showing "Loading…" until the manager shows its first menu.

func (*McpManagerView) HandleInput

func (v *McpManagerView) HandleInput(data string)

HandleInput passes a key to what the view is showing.

func (*McpManagerView) Invalidate

func (v *McpManagerView) Invalidate()

Invalidate clears what the content cached.

func (*McpManagerView) Menu

func (v *McpManagerView) Menu(ctx context.Context, build func() McpMenu, subscribe func(listener func()) (unsubscribe func())) (string, bool)

Menu shows a menu, rebuilding it on every change and keeping the selected item.

func (*McpManagerView) RedirectURL

func (v *McpManagerView) RedirectURL(ctx context.Context, title, authorizationURL string) (string, bool)

RedirectURL shows the authorization URL and waits for a pasted redirect URL.

func (*McpManagerView) Render

func (v *McpManagerView) Render(width int) []string

Render draws the current content, cutting rows to the width.

func (*McpManagerView) SetCopyToClipboard

func (v *McpManagerView) SetCopyToClipboard(copyToClipboard func(text string) error)

SetCopyToClipboard supplies the clipboard writer `app.message.copy` uses for the authorization URL on the sign-in screen. Without one, the key is ignored.

func (*McpManagerView) SetFocused

func (v *McpManagerView) SetFocused(focused bool)

SetFocused records whether the view holds focus, and passes it on to the input that is showing.

func (*McpManagerView) Status

func (v *McpManagerView) Status(title, message string)

Status shows a message while an operation runs.

type McpMenu

type McpMenu struct {
	Title string
	// Details is shown below the title.
	Details string
	// Error is shown below the details in the error color.
	Error string
	Items []tui.SelectItem
	// Empty is shown when there are no items.
	Empty string
	// Selected is the value of the item selected when the menu opens.
	Selected string
	// ConfirmLabel and CancelLabel are what the confirm and cancel keys do, for the key hint.
	ConfirmLabel string
	CancelLabel  string
}

McpMenu is one menu of the manager view. upstream: packages/coding-agent/src/extensions/mcp/ui.ts:McpMenu

type McpOAuthCredentialStore

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

McpOAuthCredentialStore keeps per-server OAuth state (client registration, tokens, pending PKCE verifier) in `mcp-auth.json`.

func NewMcpOAuthCredentialStore

func NewMcpOAuthCredentialStore(agentDir string) *McpOAuthCredentialStore

NewMcpOAuthCredentialStore returns a store over the file at `<agentDir>/mcp-auth.json`, with refresh locks in agentDir.

func NewMcpOAuthCredentialStoreWithBackend

func NewMcpOAuthCredentialStoreWithBackend(backend AuthStorageBackend, lockDir string) *McpOAuthCredentialStore

NewMcpOAuthCredentialStoreWithBackend returns a store over backend. Refresh locks live in lockDir; an empty lockDir serializes refreshes in this process only.

func (*McpOAuthCredentialStore) ForServer

func (c *McpOAuthCredentialStore) ForServer(name, serverURL string) (McpOAuthServerStore, error)

ForServer returns the store of the server with the given name and URL.

func (*McpOAuthCredentialStore) Remove

func (c *McpOAuthCredentialStore) Remove(name, serverURL string) (bool, error)

Remove deletes the stored state of the server with the given name and URL, or the legacy state it would take over. It returns whether credentials were stored for it.

func (*McpOAuthCredentialStore) Tokens

func (c *McpOAuthCredentialStore) Tokens(name, serverURL string) *oauth.OAuthTokens

Tokens returns the stored tokens of the server with the given name and URL, for noticing sign-ins done by another process. It does not take over legacy state.

type McpOAuthServerStore

type McpOAuthServerStore interface {
	oauth.McpOAuthStateStore
	// WithRefreshLock runs fn while no other process refreshes the server's tokens.
	WithRefreshLock(ctx context.Context, fn func(ctx context.Context) error) error
}

McpOAuthServerStore is the state store of one server plus its refresh lock.

type McpOAuthSettings

type McpOAuthSettings struct {
	ClientID string
	// ClientSecret is already resolved.
	ClientSecret string
	CallbackPort *int
	// CallbackURL is a loopback redirect URI; see [extension.McpOAuthConfig].
	CallbackURL string
	// Scope lists the scopes to request, separated by spaces.
	Scope string
	// ClientName is the `client_name` of dynamic client registration. Default: the app name.
	ClientName string
	// ClientRegistration is `dcr` (default) or `cimd`; see [extension.McpOAuthConfig].
	ClientRegistration string
	// AuthServerMetadataURL is the authorization server metadata document to
	// use instead of discovery; see [extension.McpOAuthConfig].
	AuthServerMetadataURL *url.URL
}

McpOAuthSettings are the OAuth settings of one server, resolved.

type McpOutputSaver

type McpOutputSaver func(data []byte, extension string) (string, error)

McpOutputSaver saves the full text of a truncated result, or a binary resource, and returns the file path. extension includes the dot, for example `.txt`.

type McpResourceServer

type McpResourceServer interface {
	Name() string
	Timeout() time.Duration
	ResourcesPage(ctx context.Context, cursor *string, options mcp.RequestOptions) (*mcp.ListResourcesResult, error)
	ResourceTemplatesPage(ctx context.Context, cursor *string, options mcp.RequestOptions) (*mcp.ListResourceTemplatesResult, error)
	AllResources(ctx context.Context, options mcp.RequestOptions) ([]mcp.Resource, error)
	AllResourceTemplates(ctx context.Context, options mcp.RequestOptions) ([]mcp.ResourceTemplate, error)
	ReadResource(ctx context.Context, uri string, options mcp.RequestOptions) (*mcp.ReadResourceResult, error)
}

McpResourceServer is a connected server that offers resources.

type McpServerConfigPatch

type McpServerConfigPatch struct {
	Enabled  *bool
	Exposure extension.McpExposure
}

McpServerConfigPatch is the settings `/mcp` changes. `Enabled: true` and `Exposure: codemode` are the defaults and remove the key.

type McpServerEntry

type McpServerEntry struct {
	Name   string
	Config extension.McpServerConfig
	// Source is the config file that defined the entry, or the path of the
	// extension that registered it.
	Source string
	// Scope is "global" or "project" for an `mcp.json`, or "extension" for
	// servers registered with `pi.registerMcpServer()`. Changes to extension
	// servers are not saved.
	Scope string
	// Override is the project `mcp.json` with an override of this global
	// server's `enabled`, `exposure`, or `toolExposure`.
	Override string
}

McpServerEntry is one configured server.

type McpServerListing

type McpServerListing struct {
	Entry McpServerEntry
	// Instructions are the server instructions of a connected server.
	Instructions string
}

McpServerListing is what the `mcp_servers` section needs of a server.

type McpServerLog

type McpServerLog struct {
	// Path is the log file.
	Path string
	// contains filtered or unexported fields
}

McpServerLog appends server log messages to one file. Write errors are ignored: logging must not break tools.

func NewMcpServerLog

func NewMcpServerLog(path string) *McpServerLog

NewMcpServerLog returns a log that writes to path.

func (*McpServerLog) Write

func (l *McpServerLog) Write(server string, params json.RawMessage)

Write appends the message of one `notifications/message` from server.

type McpSignInCancelledError

type McpSignInCancelledError struct{}

McpSignInCancelledError reports a cancelled sign-in.

func (*McpSignInCancelledError) Error

func (e *McpSignInCancelledError) Error() string

type McpSignInPrompt

type McpSignInPrompt interface {
	// ShowAuthorizationURL shows the authorization URL to the user and opens it
	// in a browser.
	ShowAuthorizationURL(u *url.URL)
	// PromptForRedirectURL asks for the redirect URL from the browser address
	// bar, for when the browser cannot reach the loopback callback (for example
	// over SSH). The context ends once the callback arrives. It returns an
	// empty string when the user cancels.
	PromptForRedirectURL(ctx context.Context) (string, error)
}

McpSignInPrompt is how a sign-in reaches the user.

type McpToolCaller

type McpToolCaller interface {
	CallTool(ctx context.Context, name string, args any, options mcp.RequestOptions) (*mcp.CallToolResult, error)
}

McpToolCaller calls tools of one server.

type McpToolDetails

type McpToolDetails struct {
	Server string `json:"server"`
	Tool   string `json:"tool"`
	// FullOutputPath is the temp file with the full text output, when the
	// model-facing text was truncated.
	FullOutputPath string `json:"fullOutputPath,omitempty"`
}

McpToolDetails are the details of an MCP tool result.

type McpToolOptions

type McpToolOptions struct {
	Server    string
	Tool      mcp.Tool
	Name      string
	Exposure  extension.McpExposure
	Namespace extension.ToolNamespace
	Timeout   int // milliseconds
	GetClient func(ctx context.Context) (McpToolCaller, error)
	// Lane orders the calls to the server; nil leaves them unordered.
	Lane *extension.CallLane
	// ReadableResources says whether `read_mcp_resource` can read the server's resources.
	ReadableResources func() bool
}

McpToolOptions configure CreateMcpToolDefinition.

type McpUi

type McpUi interface {
	// Menu shows a menu and returns the chosen item's value; ok is false when the user cancelled or ctx ended.
	// subscribe rebuilds the menu on every change, keeping the selected item.
	Menu(ctx context.Context, build func() McpMenu, subscribe func(listener func()) (unsubscribe func())) (value string, ok bool)
	// Status shows a message while an operation runs.
	Status(title, message string)
	// RedirectURL shows the authorization URL and waits for a pasted redirect URL; ok is false when the user
	// cancelled or ctx ended (the browser reached the callback).
	RedirectURL(ctx context.Context, title, authorizationURL string) (value string, ok bool)
}

McpUi is what the manager needs from its view. upstream: packages/coding-agent/src/extensions/mcp/ui.ts:McpUi

type Options

type Options struct {
	// LoadConfig defaults to reading `mcp.json` from the agent directory and the trusted project.
	LoadConfig func(ctx EventContext) LoadedMcpConfig
	// CreateTransport defaults to stdio and streamable HTTP transports built from the server config.
	CreateTransport TransportFactory
	// Credentials defaults to `mcp-auth.json` in the agent directory.
	Credentials *McpOAuthCredentialStore
	// LogPath is the file server log messages are appended to. Defaults to `mcp.log` in the agent directory.
	LogPath string
	// OpenURL opens the OAuth authorization URL. Defaults to doing nothing; the host supplies the platform browser.
	OpenURL func(url string)
	// CopyToClipboard copies the OAuth authorization URL when `app.message.copy` is pressed on the sign-in screen.
	// Defaults to nil, which ignores the key; the host supplies the system clipboard.
	CopyToClipboard func(text string) error
	// UpdateConfig saves `/mcp` changes to the server's config file: its project Override when set, else its
	// Source. Defaults to editing that `mcp.json`.
	UpdateConfig func(entry McpServerEntry, patch McpServerConfigPatch) error
	// StartupWait is how long the first prompt waits for servers that are still
	// connecting at startup. Their tools become available when they connect.
	// Default: 10 seconds.
	StartupWait time.Duration
	// AgentDir and ConfigDirName locate the configuration and the credentials.
	AgentDir      string
	ConfigDirName string
	// ClientName and ClientVersion identify this client to servers.
	ClientName    string
	ClientVersion string
	// IsCodemodeTool and IsToolSearchTool tell the built-in tools from another
	// extension's tool of the same name. The defaults match the built-in
	// extensions' source paths.
	IsCodemodeTool   func(extension.ToolInfo) bool
	IsToolSearchTool func(extension.ToolInfo) bool
}

Options configure the extension.

type ResourceToolsOptions

type ResourceToolsOptions struct {
	Exposure extension.McpExposure
	// Servers returns the servers whose resources the tools reach, at call time.
	Servers func() []McpResourceServer
}

ResourceToolsOptions configure CreateMcpResourceToolDefinitions.

type ServerState

type ServerState string

ServerState is the state of one Connection. `disconnected` means the connection dropped (for example the stdio server exited); the next call reconnects.

const (
	StateConnecting   ServerState = "connecting"
	StateConnected    ServerState = "connected"
	StateDisconnected ServerState = "disconnected"
	StateNeedsAuth    ServerState = "needs-auth"
	StateFailed       ServerState = "failed"
	StateClosed       ServerState = "closed"
)

Connection states.

type ServerView

type ServerView struct {
	Entry McpServerEntry
	// Connection is nil for a disabled server.
	Connection *Connection
	Enabled    bool
	// Message is the result of the last action that failed.
	Message string
}

ServerView is a snapshot of one configured server.

type SignInOptions

type SignInOptions struct {
	ServerURL string
	Store     oauth.McpOAuthStateStore
	Settings  McpOAuthSettings
	Challenge *oauth.OAuthChallenge
	Prompt    McpSignInPrompt
	// AppName is the OAuth client name. Default: "pig".
	AppName string
}

SignInOptions configure SignInMcpServer.

type SignInPrompt

type SignInPrompt = McpSignInPrompt

SignInPrompt is McpSignInPrompt.

type TransportFactory

type TransportFactory func(entry McpServerEntry, cwd string, authProvider mcp.AuthProvider) (mcp.Transport, error)

TransportFactory creates the transport of a server.

type UpdateMcpServerConfigOptions

type UpdateMcpServerConfigOptions struct {
	// Override adds a missing entry as an override of a global server.
	Override bool
}

UpdateMcpServerConfigOptions are the options of UpdateMcpServerConfig.

Jump to

Keyboard shortcuts

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