mcp

package
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2026 License: Apache-2.0 Imports: 36 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package mcp owns the live lifecycle of the MCP servers a workspace declares.

Architecture

A Manager is created per open workspace and keeps one connection per effective warp.MCP resource. It is the runtime behind the workspace's MCP endpoints and the source of everything the /mcp inspector shows.

  • Non-blocking workspace open: Servers connect and discover in the background, so opening or reloading a workspace is never delayed by a slow or unreachable server. A server whose connection fails reports status error with the failure reason instead of failing the workspace.

  • Catalog synchronization: Discovered tools are converted into raw warp.Tool definitions and registered with the workspace registry through SetMCPTools, which applies spec.policies filtering, names tools "<server>__<tool>", and resolves effective annotations. After discovery the workspace catalog is refreshed so tool lists and token counts reflect what the server actually offers.

  • Prohibited items stay visible: Tools, prompts, and resources blocked by spec.policies are still reported with Allowed false, so callers can show everything a server offers and why an item is restricted. Blocking itself is enforced by the daemon against the manifest definition, which keeps the guarantee independent of this package.

  • Authentication: Static bearer, api-key, and basic credentials resolve from spec.auth env or file entries and are sent as headers. OAuth flows are delegated to the MCP SDK handlers, with acquired tokens and dynamically registered clients persisted per server so daemon restarts do not force a browser re-login. Interactive authorization never blocks a connection attempt: the server moves to status auth_required and exposes the URL the user should open.

  • Environment isolation: spec.env and spec.headers values expand ${VAR} placeholders from the workspace's isolated .env map, consulting the host environment only for names the manifest explicitly references, so stdio subprocesses never inherit unreferenced host variables.

Relationship to the workspace

Manager implements the workspace MCPService contract. The daemon attaches it to a workspace runtime once manifests are loaded, calls Manager.Sync after every reload to reconcile servers with the current declarations, and Manager.Close when the runtime shuts down.

Index

Constants

View Source
const DefaultConnectTimeout = 30 * time.Second

DefaultConnectTimeout bounds a single connection and discovery attempt.

Variables

View Source
var ErrAuthRequired = errors.New("mcp authentication required")

ErrAuthRequired marks a failure whose cause is authentication rather than a broken server. Connection attempts wrap their credential-resolution and handshake failures with it so [Manager.failureStatus] can park the server in api.MCPStatusAuthRequired, which is what makes the CLI offer the user an actionable "authenticate this server" path instead of a generic error.

View Source
var ErrManagerClosed = errors.New("mcp manager is closed")

ErrManagerClosed reports that the manager has been shut down with its workspace.

View Source
var ErrManifestReadOnly = errors.New("mcp manifest is not writable")

ErrManifestReadOnly reports that an MCP server's declaration cannot be edited on disk, either because it is built-in, has no backing file, or the file is not writable.

View Source
var ErrNoSafePolicyEdit = errors.New("no safe policy edit")

ErrNoSafePolicyEdit reports that no automatic manifest edit can permit an item without also widening what the server exposes.

View Source
var ErrServerNotFound = errors.New("mcp server not found")

ErrServerNotFound reports that the workspace declares no MCP server with the requested name.

Functions

This section is empty.

Types

type CredentialStore

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

CredentialStore persists MCP OAuth tokens and client credentials in the application data directory with owner-only permissions.

func NewCredentialStore

func NewCredentialStore() (*CredentialStore, error)

NewCredentialStore returns a store backed by $XDG_DATA_HOME/tasksmith/mcp/credentials.json.

func NewCredentialStoreAt

func NewCredentialStoreAt(path string) *CredentialStore

NewCredentialStoreAt returns a store backed by an explicit file, used by tests.

func (*CredentialStore) Forget

func (s *CredentialStore) Forget(key string) error

Forget removes persisted credentials for key.

func (*CredentialStore) Get

func (s *CredentialStore) Get(key string) (storedServer, bool)

Get returns the persisted credentials for key.

func (*CredentialStore) Path

func (s *CredentialStore) Path() string

Path returns the file backing the store.

func (*CredentialStore) Put

func (s *CredentialStore) Put(key string, entry storedServer) error

Put persists credentials for key, writing the whole store atomically with owner-only permissions.

type Definer

type Definer interface {
	// MCPDef resolves the effective MCP definition for a short or qualified name.
	MCPDef(name string) (*warp.MCP, bool)
	// MCPDefinitions returns every effective MCP definition in scope.
	MCPDefinitions() []*warp.MCP
}

Definer resolves the effective MCP definitions in a workspace.

type Manager

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

Manager owns the live connections for one workspace's MCP servers and satisfies the workspace MCPService contract.

func New

func New(opts Options) (*Manager, error)

New creates a manager for a workspace's declared MCP servers. With Options.AutoConnect, servers begin connecting in the background so opening a workspace is never blocked by a slow or unreachable server.

func (*Manager) AllowPolicyItem

func (m *Manager) AllowPolicyItem(ctx context.Context, name string, req api.MCPAllowPolicyRequest) (api.MCPServer, error)

AllowPolicyItem permits one item in the named server's manifest, reloads the workspace so the new policy takes effect, reconnects the server, and returns the refreshed state.

func (*Manager) AuthenticateMCP

func (m *Manager) AuthenticateMCP(ctx context.Context, name string) (api.MCPAuthResponse, error)

AuthenticateMCP starts or resumes interactive authorization for the named server and reports the URL the user should open. A server already authorized with stored credentials reports its connected status and no URL. A server that authenticates with static or machine-to-machine credentials has no browser flow to open, so it answers with the credential the user must supply instead of a dead end.

func (*Manager) CallMCPTool

func (m *Manager) CallMCPTool(ctx context.Context, serverName, toolName string, args map[string]any) (tool.ToolStream, error)

CallMCPTool executes a tool on a server and returns its streaming result. A tool prohibited by spec.policies.tools is rejected here as defense in depth, even though prohibited tools are never registered as callable agent tools.

func (*Manager) Close

func (m *Manager) Close() error

Close disconnects every server.

func (*Manager) GetMCPPrompt

func (m *Manager) GetMCPPrompt(ctx context.Context, name, prompt string, args map[string]string, _ bool) (api.MCPPromptResponse, error)

GetMCPPrompt renders a prompt discovered on a server. Policy enforcement is the daemon's responsibility, so a prohibited prompt reaches this point only when a user explicitly authorized that single use.

func (*Manager) HasAllowedMCPResources

func (m *Manager) HasAllowedMCPResources() bool

HasAllowedMCPResources reports whether any server exposes a resource that spec.policies permits, which decides whether the resource-reading built-in tool is worth loading.

func (*Manager) ListMCPs

func (m *Manager) ListMCPs(_ context.Context) []api.MCPServer

ListMCPs returns every declared server with live status and everything discovered on it, sorted by name. A server whose connection failed reports status error with the reason, and items blocked by spec.policies are listed with Allowed false so callers can show what a server offers and why an item is restricted.

func (*Manager) ReadMCPResource

func (m *Manager) ReadMCPResource(ctx context.Context, name string, req api.MCPResourceRequest) (api.MCPResourceResponse, error)

ReadMCPResource reads one resource URI from a server.

func (*Manager) RestartMCP

func (m *Manager) RestartMCP(ctx context.Context, name string) (api.MCPServer, error)

RestartMCP reconnects the named server, re-discovers its tools, prompts, and resources, and returns the refreshed state.

func (*Manager) SetRuntimeContext

func (m *Manager) SetRuntimeContext(env map[string]string, render warp.MCPRenderOptions)

SetRuntimeContext updates the workspace-derived inputs a manager uses after a reload: the isolated environment map and the render context for commands and endpoints. Connected servers keep their current connection; values apply to the next connection and to what listing reports.

func (*Manager) SubmitMCPAuthCallback

func (m *Manager) SubmitMCPAuthCallback(_ context.Context, name, callbackURL string) error

SubmitMCPAuthCallback completes an in-flight interactive authorization with a redirect URL the user pasted from their browser. It exists for the case the loopback listener cannot serve: the browser is on another machine, a proxy or firewall blocks localhost, or the redirect page simply failed to load. The waiting flow is unchanged by this — it receives the code exactly as if the browser had reached the daemon.

func (*Manager) Sync

func (m *Manager) Sync(ctx context.Context)

Sync reconciles managed servers with the workspace's current declarations: new servers start connecting, removed servers close, and changed definitions reconnect. Call it on workspace open and after every reload.

func (*Manager) SyncTo

func (m *Manager) SyncTo(syncer Syncer) error

SyncTo registers every already-discovered MCP server's tools onto syncer so a sibling workspace runtime opened after discovery still receives all tools.

type Options

type Options struct {
	// Definer resolves MCP definitions. Required.
	Definer Definer
	// Syncer receives discovered tools. Optional; without it tools are still
	// discovered and reported, but the workspace registry is not updated.
	Syncer Syncer
	// ReloadWorkspace re-reads manifests from disk after a policy edit. Optional.
	ReloadWorkspace func(context.Context) error
	// Env is the workspace's isolated environment map, used to expand spec.env and
	// spec.headers placeholders and to resolve credentials.
	Env map[string]string
	// RenderOptions supplies workspace and project context for rendering commands
	// and endpoints.
	RenderOptions warp.MCPRenderOptions
	// ConnectTimeout bounds one connection and discovery attempt. Defaults to
	// [DefaultConnectTimeout].
	ConnectTimeout time.Duration
	// Credentials overrides the OAuth credential store, mainly for tests.
	Credentials *CredentialStore
	// AutoConnect starts background connections on [Manager.Sync]. When false,
	// servers connect only on demand.
	AutoConnect bool
	// OnDiscover runs after a server's discovered tools have been registered with the
	// workspace, which is the moment those tools become callable. A workspace whose
	// sessions are already open uses it to rebuild their tool containers; without it,
	// a server that finishes connecting after a session started would stay invisible
	// to that session. Optional.
	OnDiscover func()
}

Options configures a Manager.

type PolicyChange

type PolicyChange struct {
	// Section is the spec.policies section that was edited.
	Section string
	// Value is the item the manifest now permits.
	Value string
	// RemovedExclude is an exclude pattern deleted because it named the value
	// exactly.
	RemovedExclude string
	// Included is true when the value was appended to the section's include list.
	Included bool
	// Unchanged is true when the manifest already permitted the value.
	Unchanged bool
}

PolicyChange describes an applied manifest policy edit.

func AllowPolicyItem

func AllowPolicyItem(def *warp.MCP, kind, value string) (PolicyChange, error)

AllowPolicyItem updates the manifest file backing def so value is permitted under the policy section for kind ("tool", "prompt", or "resource").

The edit preserves comments and formatting by mutating the file's YAML node tree, and applies the smallest change that can help: an exclude entry naming the value exactly is removed, and when the value is restricted by an include list it is appended to that list. The edited document is re-parsed through the same loader the daemon uses and re-checked before anything is written, so a caller never reports a permission that is not actually in effect.

Some blocks have no safe automatic edit. An exclude *pattern* such as delete_* keeps matching the value even after it is listed in include, because exclusion runs after inclusion, and deleting the pattern would silently expose every other item it covers. Those cases fail with an error wrapping ErrNoSafePolicyEdit naming the patterns to narrow by hand.

Built-in servers and manifests without a writable local file are rejected with an error wrapping ErrManifestReadOnly.

func (PolicyChange) String

func (c PolicyChange) String() string

String renders a short human-readable summary of the edit.

type Syncer

type Syncer interface {
	// SyncMCPTools registers the discovered raw tools for one MCP server and
	// refreshes the workspace catalog. An empty slice clears the server's tools.
	SyncMCPTools(def *warp.MCP, rawTools []*warp.Tool) error
}

Syncer receives discovered tools into the workspace registry and refreshes the catalog so tool lists, statuses, and token counts reflect live discovery.

type ToolRuntime

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

ToolRuntime adapts a Manager to the narrow MCP contract the tool container needs. The manager's own resource reader takes an api.MCPResourceRequest because it backs the HTTP API, while the container calls with plain arguments, so the adapter keeps each side's surface honest instead of widening either one.

A nil *Manager adapts to a runtime that reports no resources and rejects calls, so wiring a session never needs a nil check at every call site.

func NewToolRuntime

func NewToolRuntime(m *Manager) *ToolRuntime

NewToolRuntime returns the tool-facing view of m. It returns nil when m is nil so a workspace without an MCP manager leaves the container's MCP tools unregistered.

func (*ToolRuntime) CallMCPTool

func (r *ToolRuntime) CallMCPTool(ctx context.Context, serverName, rawToolName string, args map[string]any) (tool.ToolStream, error)

CallMCPTool executes rawToolName on the named server.

func (*ToolRuntime) GetMCPPrompt

func (r *ToolRuntime) GetMCPPrompt(ctx context.Context, serverName, prompt string, args map[string]string, allowProhibited bool) (api.MCPPromptResponse, error)

GetMCPPrompt renders one prompt discovered on the named server.

func (*ToolRuntime) HasAllowedMCPResources

func (r *ToolRuntime) HasAllowedMCPResources() bool

HasAllowedMCPResources reports whether any server exposes a permitted resource.

func (*ToolRuntime) ReadMCPResource

func (r *ToolRuntime) ReadMCPResource(ctx context.Context, serverName, uri string, allowProhibited bool) (api.MCPResourceResponse, error)

ReadMCPResource reads one resource URI from the named server.

Jump to

Keyboard shortcuts

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