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
- func AddMcpServerConfig(path, name string, config extension.McpServerConfig) (bool, error)
- func AddMcpServerConfigJSON(path, name string, config json.RawMessage) (bool, error)
- func ConvertMcpResult(server, tool string, result *mcp.CallToolResult, ...) (agent.AgentToolResult, error)
- func CreateDefaultTransport(entry McpServerEntry, cwd string, authProvider mcp.AuthProvider) (mcp.Transport, error)
- func CreateMcpExtension(options Options) extension.ExtensionFactory
- func CreateMcpResourceToolDefinitions(options ResourceToolsOptions) []extension.ToolDefinition
- func CreateMcpResultSchema(structuredContentSchema json.RawMessage) json.RawMessage
- func CreateMcpToolDefinition(options McpToolOptions) extension.ToolDefinition
- func CreateMcpToolName(server, tool string, isTaken func(string) bool) string
- func Factory(options Options) func(api API) *Extension
- func FormatMcpLogMessage(server string, params json.RawMessage, now time.Time) string
- func IsMcpAppResource(uri, mimeType string) bool
- func LimitMcpContent(content []ai.ToolResultMessageContent, saveOutput McpOutputSaver) ([]ai.ToolResultMessageContent, string)
- func RemoveMcpServerConfig(path, name string) (bool, error)
- func RenderServersSection(servers []McpServerListing) (string, bool)
- func RunMcpCommand(ctx context.Context, args []string, options McpCommandOptions) int
- func SaveToTempFile(data []byte, extension string) (string, error)
- func SignInMcpServer(ctx context.Context, options SignInOptions) (err error)
- func ToModelContent(server string, blocks []mcp.ContentBlock, options ConvertMcpResultOptions) []ai.ToolResultMessageContent
- func ToToolExposure(exposure extension.McpExposure) extension.ToolExposure
- func UpdateMcpServerConfig(path, name string, patch McpServerConfigPatch, ...) error
- type API
- type AuthStorageBackend
- type CommandContext
- type Connection
- func (c *Connection) AllResourceTemplates(ctx context.Context, options mcp.RequestOptions) ([]mcp.ResourceTemplate, error)
- func (c *Connection) AllResources(ctx context.Context, options mcp.RequestOptions) ([]mcp.Resource, error)
- func (c *Connection) CallTool(ctx context.Context, name string, args any, options mcp.RequestOptions) (*mcp.CallToolResult, error)
- func (c *Connection) Challenge() *oauth.OAuthChallenge
- func (c *Connection) ClearChallenge()
- func (c *Connection) Close()
- func (c *Connection) Error() string
- func (c *Connection) GetClient(ctx context.Context) (*mcp.Client, error)
- func (c *Connection) HasResources() bool
- func (c *Connection) Instructions() string
- func (c *Connection) Name() string
- func (c *Connection) OAuthSettings() (McpOAuthSettings, error)
- func (c *Connection) OAuthURL() string
- func (c *Connection) ReadResource(ctx context.Context, uri string, options mcp.RequestOptions) (*mcp.ReadResourceResult, error)
- func (c *Connection) Reconnect(ctx context.Context) error
- func (c *Connection) ResourceTemplatesPage(ctx context.Context, cursor *string, options mcp.RequestOptions) (*mcp.ListResourceTemplatesResult, error)
- func (c *Connection) ResourcesPage(ctx context.Context, cursor *string, options mcp.RequestOptions) (*mcp.ListResourcesResult, error)
- func (c *Connection) SignOut()
- func (c *Connection) State() ServerState
- func (c *Connection) Timeout() time.Duration
- func (c *Connection) Tools() []mcp.Tool
- type ConnectionOptions
- type ConvertMcpResultOptions
- type EventContext
- type Extension
- func (e *Extension) BeforeAgentStart(ctx EventContext, options *extension.BuildSystemPromptOptions)
- func (e *Extension) CompleteCommand(prefix string) []extension.AutocompleteItem
- func (e *Extension) DescribeState(name string, withError bool) string
- func (e *Extension) EnsureDiscoveryActive(ctx EventContext)
- func (e *Extension) FormatStatus() string
- func (e *Extension) Manage(ctx context.Context, ui McpUi, ec EventContext) error
- func (e *Extension) McpServersChange(ctx EventContext)
- func (e *Extension) Notices() []string
- func (e *Extension) Pending()
- func (e *Extension) Reconnect(ctx context.Context, name string) string
- func (e *Extension) RunCommand(ctx context.Context, args string, c CommandContext) error
- func (e *Extension) Servers() []ServerView
- func (e *Extension) SessionShutdown()
- func (e *Extension) SessionStart(ctx EventContext)
- func (e *Extension) SetEnabled(ctx EventContext, name string, enabled bool, inProject ...bool) string
- func (e *Extension) SetExposure(name string, exposure extension.McpExposure) string
- func (e *Extension) SetMessage(name, message string)
- func (e *Extension) SignIn(ctx context.Context, name string, prompt McpSignInPrompt) string
- func (e *Extension) SignOut(name string) (bool, error)
- func (e *Extension) Subscribe(listener func()) (unsubscribe func())
- func (e *Extension) ToolCall(ctx context.Context, toolName string, input json.RawMessage)
- func (e *Extension) TurnStart(ctx EventContext)
- type FileAuthStorageBackend
- type Host
- type InMemoryAuthStorageBackend
- type LoadOptions
- type LoadedMcpConfig
- type McpAuthProvider
- type McpAuthProviderOptions
- type McpCommandOptions
- type McpMenu
- type McpMenuItem
- type McpOAuthCredentialStore
- type McpOAuthServerStore
- type McpOAuthSettings
- type McpOutputSaver
- type McpResourceServer
- type McpServerConfigPatch
- type McpServerEntry
- type McpServerListing
- type McpServerLog
- type McpSignInCancelledError
- type McpSignInPrompt
- type McpToolCaller
- type McpToolDetails
- type McpToolOptions
- type McpUi
- type Options
- type ResourceToolsOptions
- type ServerState
- type ServerView
- type SignInOptions
- type SignInPrompt
- type Terminal
- type TransportFactory
- type UpdateMcpServerConfigOptions
Constants ¶
const ( // CodemodeToolName and ToolSearchToolName are the tools that reach MCP tools that are not declared. CodemodeToolName = "codemode" ToolSearchToolName = "tool_search" )
const ( ListMcpResourcesTool = extension.ListMcpResourcesTool ListMcpResourceTemplatesTool = extension.ListMcpResourceTemplatesTool )
Names of the resource tools.
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 = extension.ReadMcpResourceTool )
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).
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).
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 CreateMcpExtension ¶
func CreateMcpExtension(options Options) extension.ExtensionFactory
CreateMcpExtension is upstream's createMcpExtension (extensions/mcp/index.ts:280): the extension factory of the MCP extension, which registers its events, `/mcp` command and tools on the api it is given. Factory is the same registration for a caller that also needs the extension's actions.
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 (without `_meta`, which ConvertMcpResult drops), with the tool's own output schema as `structuredContent`. upstream: tools.ts createMcpResultSchema
func CreateMcpToolDefinition ¶
func CreateMcpToolDefinition(options McpToolOptions) extension.ToolDefinition
CreateMcpToolDefinition adapts one MCP tool to a tool definition.
func CreateMcpToolName ¶
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 Factory ¶
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 ¶
FormatMcpLogMessage formats one `notifications/message` from server as a log line; continuation lines are indented.
func IsMcpAppResource ¶
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 RemoveMcpServerConfig ¶
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 ¶
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) (err 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. Ending ctx stops the sign-in at any step with McpSignInCancelledError; requests to the authorization server are also time-limited.
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) GetClient ¶
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, which the resource tools list and read on demand. They are not listed at connect: listing every resource can take long (a large drive, say).
func (*Connection) Instructions ¶
func (c *Connection) Instructions() string
Instructions are the server instructions from `initialize`, describing its tools as a group.
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) 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) 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) 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 {
// Context is the handler's context, which carries the extension context (extension.FromContext). A zero EventContext has none.
Context context.Context
// 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 NewHeadless ¶
NewHeadless is the headless entry point: it returns the extension for host with no terminal presentation, whatever options.Terminal says. Connections, discovery, sign-in, tool registration and execution, and the session lifecycle work as in New; tools have no renderers and `/mcp` has no manager view. This package imports neither package tui nor mcptui directly. It still links tui through coding/extension (see docs/design/extension-api-tui-split.md), so an embedder that must not link tui at all uses package mcp, which has no such dependency.
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 ¶
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 ¶
FormatStatus is the plain status of every server, for `/mcp` without a terminal manager.
func (*Extension) Manage ¶
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 ¶
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 ¶
Reconnect connects a server again. It returns a message describing a failure, or "" on success.
func (*Extension) RunCommand ¶
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 ends the session, which stops running sign-ins, 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 ¶
SetMessage records the result of a failed action for the manager.
func (*Extension) SignIn ¶
SignIn signs in to a server through the browser flow and reconnects. It returns a message describing a failure, or "" on success. Ending ctx (the caller's cancellation) or the session stops the sign-in.
func (*Extension) SignOut ¶
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 ¶
ToolCall is the `tool_call` handler. A tool that reaches other tools (ReachesTools) waits for the servers it may reach, so their tools are registered before it runs: a codemode script for the servers it names, or for every server when it searches or enumerates tools, and tool_search for every server. The resource tools reach every server, so they wait for all of them. Direct MCP calls wait only for their own server, including a reconnect still closing its old transport. It returns when the servers settled or ctx ends. input is the call's input as JSON in its member order (extension.CustomToolCallEvent.InputJSON), which a tool's ReachesTools reads as upstream's reachesTools reads event.input.
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)
// RegisterTools registers tools as one change: the Session's tools change once, to include all of them, as after the
// synchronous run of registerTool calls in Pi's registerTools (extensions/mcp/index.ts:387-463).
RegisterTools(definitions []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 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 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 []McpMenuItem
// Empty is shown when there are no items; a non-empty Empty or HasEmpty replaces the default "Nothing to show.", so an empty message can be shown.
Empty string
HasEmpty bool
// 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 McpMenuItem ¶
McpMenuItem is one row of a McpMenu; it has the fields of tui.SelectItem so a terminal view converts it directly.
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 *oauth.URL
}
McpOAuthSettings are the OAuth settings of one server, resolved.
type McpOutputSaver ¶
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 oauth.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 or the sign-in is
// cancelled. 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
// Renderers draws the call and the result in the terminal; nil leaves the tool without renderers (headless).
Renderers func(label string) *extension.ToolRenderers
}
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. With onCancel, the cancel key calls it.
Status(title, message string, onCancel func())
// 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. Its context carries the extension context (extension.FromContext), as a handler's does.
LoadConfig func(ctx context.Context) 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
// StartupWaitMs is how many milliseconds the first prompt waits for servers that are still connecting at startup. Their tools
// become available when they connect. Nil waits 10000 ms; 0 does not wait for a server that is not yet ready
// (index.ts:90, 294 `options.startupWaitMs ?? DEFAULT_STARTUP_WAIT_MS`).
StartupWaitMs *int
// 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
// Terminal adds the terminal presentation (tool renderers, the `/mcp` manager view). Nil is headless.
Terminal *Terminal
}
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 Terminal ¶
type Terminal struct {
// Renderers returns the renderers of calls to the MCP tool labeled `server/tool`.
Renderers func(label string) *extension.ToolRenderers
// ToolRendererResolver renders calls to MCP tools before their server connected (a resumed session).
ToolRendererResolver extension.ToolRendererResolver
// ShowManager runs manage in the manager view until it returns.
ShowManager func(ctx context.Context, ui extension.UIContext, events EventContext, copyToClipboard func(text string) error, manage func(McpUi) error) error
}
Terminal is the terminal presentation of the extension: the renderers of MCP tool calls, the resolver for tools of a server that is not connected yet, and the `/mcp` manager view. A nil Terminal (the default of Options) leaves the extension headless: tools have no renderers and `/mcp` has no manager view. Package mcptui supplies the terminal one.
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.