mcpclient

package
v1.8.3 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: AGPL-3.0 Imports: 41 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 mcpclient is the assistant's client of remote MCP servers (assistant brief D2, §3.6; milestone B5). Integration managers connect servers (Streamable HTTP, or HTTP with SSE; never a local process) with no authentication, a shared header secret, or OAuth per member; a sync lists their tools, each of which waits for a manager to mark it read-only, writes or blocked. A tool that changes after it was decided on is off until a manager decides again: each call lists the server's tools first, in its own session, and servers without a person's sign-in are synced every hour. A sign-in removed (disconnected, or its member gone) has its refresh token revoked when the authorization server can. Every request goes through the SSRF guard; secrets and tokens are sealed and never returned.

Index

Constants

View Source
const (
	CodeUnreachable = "mcp_unreachable"
	CodeSignIn      = "mcp_sign_in"
	CodeToolChanged = "mcp_tool_changed"
	CodeToolBlocked = "mcp_tool_blocked"
	CodeTimeout     = "mcp_timeout"
	CodeTooLarge    = "mcp_too_large"
)

Problem codes.

View Source
const (
	// MaxResult bounds a tool's result as the model reads it.
	MaxResult = 32 << 10
)

Variables

This section is empty.

Functions

func CallDigest

func CallDigest(callID string, toolID uuid.UUID, args json.RawMessage) []byte

CallDigest identifies a call in the audit log without its content: its arguments, salted with the call's id (which the log doesn't keep).

func MayUse

func MayUse(ctx context.Context, q *store.Queries, ws uuid.UUID, user uuid.UUID, roles []string) (bool, error)

MayUse reports whether a person may use a server: they use AI features, and the server is for everyone or for their role.

func Register

func Register(h huma.API, s *Service)

Register adds the MCP servers' operations: managers add, sync and review servers; members sign in to OAuth servers and pick the servers their threads use. People only: API keys and MCP agents can't.

Types

type MCPClientMetadataDocument

type MCPClientMetadataDocument struct {
	ClientID                string   `json:"client_id"`
	ClientName              string   `json:"client_name"`
	RedirectURIs            []string `json:"redirect_uris"`
	GrantTypes              []string `json:"grant_types"`
	ResponseTypes           []string `json:"response_types"`
	TokenEndpointAuthMethod string   `json:"token_endpoint_auth_method"`
}

MCPClientMetadataDocument is ReputeCast's OAuth client as an authorization server reads it (OAuth Client ID Metadata Document, draft-ietf-oauth-client-id-metadata-document-00): client_id is this document's own address. A public client: PKCE, no secret.

type MCPOAuthCallbackInput

type MCPOAuthCallbackInput struct {
	Code  string `query:"code" maxLength:"4000"`
	State string `query:"state" maxLength:"200"`
	Error string `query:"error" maxLength:"200"`
}

MCPOAuthCallbackInput is the authorization server's answer.

type PurgeArgs

type PurgeArgs struct{}

PurgeArgs is the hourly removal of sign-ins that were never finished.

func (PurgeArgs) InsertOpts

func (PurgeArgs) InsertOpts() river.InsertOpts

InsertOpts runs it once at a time.

func (PurgeArgs) Kind

func (PurgeArgs) Kind() string

Kind implements river.JobArgs.

type PurgeWorker

type PurgeWorker struct {
	river.WorkerDefaults[PurgeArgs]
	S *Service
}

PurgeWorker runs the purge.

func (*PurgeWorker) Work

func (w *PurgeWorker) Work(ctx context.Context, _ *river.Job[PurgeArgs]) error

Work implements river.Worker.

type RemoteMCPOAuthStart

type RemoteMCPOAuthStart struct {
	AuthorizationURL string `json:"authorizationUrl"`
}

RemoteMCPOAuthStart is where the person signs in.

type RemoteMCPServer

type RemoteMCPServer struct {
	ID         uuid.UUID `json:"id"`
	Key        string    `json:"key" doc:"The prefix of its tools for the model: mcp__<key>__<tool>"`
	Name       string    `json:"name"`
	URL        string    `json:"url"`
	Transport  string    `json:"transport" enum:"streamable,sse"`
	Auth       string    `json:"auth" enum:"none,header,oauth"`
	HeaderName string    `json:"headerName,omitempty"`
	HeaderSet  bool      `json:"headerSet"`
	// ClientID is the OAuth client: entered by a manager, registered by
	// ReputeCast (ClientRegistered), or the instance's metadata document
	// (ClientMetadata).
	ClientID         string `json:"clientId,omitempty"`
	ClientSecretSet  bool   `json:"clientSecretSet"`
	ClientRegistered bool   `json:"clientRegistered"`
	// ClientMetadata: the client is the instance's Client ID Metadata
	// Document (clientId is its https address), as the authorization
	// server offered.
	ClientMetadata bool       `json:"clientMetadata"`
	Roles          []string   `json:"roles"`
	Enabled        bool       `json:"enabled"`
	Status         string     `json:"status" enum:"new,ok,unreachable,sign_in"`
	StatusDetail   string     `json:"statusDetail,omitempty"`
	SyncedAt       *time.Time `json:"syncedAt,omitempty"`
	// Connected: the caller's own OAuth sign-in is there (auth oauth).
	Connected bool `json:"connected"`
	// RedirectURI is the address to register with the authorization server
	// for a pre-registered client.
	RedirectURI string          `json:"redirectUri,omitempty"`
	Tools       []RemoteMCPTool `json:"tools"`
	// Waiting counts the tools a manager hasn't decided on, or that changed.
	Waiting int `json:"waiting"`
}

RemoteMCPServer is a server as managers and members see it: never its secrets.

type RemoteMCPServerInput

type RemoteMCPServerInput struct {
	Name string `json:"name" minLength:"1" maxLength:"80"`
	URL  string `json:"url" minLength:"1" maxLength:"500" doc:"The server's MCP endpoint (Streamable HTTP, or HTTP with SSE)"`
	// Transport is streamable unless the server only speaks the older
	// HTTP with SSE; a sync falls back to it by itself.
	Transport string `json:"transport,omitempty" enum:"streamable,sse"`
	Auth      string `json:"auth" enum:"none,header,oauth"`
	// HeaderName and HeaderValue are the shared secret's header (auth header).
	HeaderName  string `json:"headerName,omitempty" maxLength:"100" pattern:"^[A-Za-z0-9-]*$"`
	HeaderValue string `json:"headerValue,omitempty" maxLength:"4000"`
	// ClientID and ClientSecret are a client the manager registered with
	// the authorization server; without them, ReputeCast registers one.
	ClientID     string `json:"clientId,omitempty" maxLength:"500"`
	ClientSecret string `json:"clientSecret,omitempty" maxLength:"4000"`
	// Roles are the role keys who may use it; empty: everyone with Use AI
	// features.
	Roles []string `json:"roles,omitempty" maxItems:"50"`
}

RemoteMCPServerInput adds a server. HeaderValue and ClientSecret are write-only.

type RemoteMCPServerList

type RemoteMCPServerList struct {
	Servers []RemoteMCPServer `json:"servers"`
}

RemoteMCPServerList is the workspace's servers.

type RemoteMCPServerUpdate

type RemoteMCPServerUpdate struct {
	Name         *string   `json:"name,omitempty" minLength:"1" maxLength:"80"`
	Enabled      *bool     `json:"enabled,omitempty"`
	Roles        *[]string `json:"roles,omitempty" maxItems:"50"`
	HeaderValue  *string   `json:"headerValue,omitempty" maxLength:"4000"`
	ClientID     *string   `json:"clientId,omitempty" maxLength:"500"`
	ClientSecret *string   `json:"clientSecret,omitempty" maxLength:"4000"`
}

RemoteMCPServerUpdate changes a server; absent fields stay.

type RemoteMCPTool

type RemoteMCPTool struct {
	ID          uuid.UUID       `json:"id"`
	Name        string          `json:"name"`
	ModelName   string          `json:"modelName"`
	Description string          `json:"description"`
	InputSchema json.RawMessage `json:"inputSchema"`
	// Annotations are the server's hints (readOnlyHint, destructiveHint…),
	// never evidence.
	Annotations json.RawMessage `json:"annotations"`
	// Hash identifies the description, schema and annotations reviewed.
	Hash     string `json:"hash"`
	Decision string `json:"decision" enum:"pending,read_only,writes,blocked"`
	// Changed: it changed after a manager decided on it; it is off until
	// they decide again.
	Changed   bool       `json:"changed"`
	Removed   bool       `json:"removed"`
	DecidedAt *time.Time `json:"decidedAt,omitempty"`
	// Approved is the version decided on, for a tool that changed since:
	// what a manager approved, to compare with what the server says now.
	Approved *RemoteMCPToolVersion `json:"approved,omitempty"`
}

RemoteMCPTool is a tool of a server's catalog.

type RemoteMCPToolDecision

type RemoteMCPToolDecision struct {
	Decision string `json:"decision" enum:"read_only,writes,blocked"`
	Hash     string `json:"hash" doc:"The hash of the description, schema and annotations reviewed"`
}

RemoteMCPToolDecision decides on a tool, at the hash the manager reviewed.

type RemoteMCPToolVersion

type RemoteMCPToolVersion struct {
	Description string          `json:"description"`
	InputSchema json.RawMessage `json:"inputSchema"`
	Annotations json.RawMessage `json:"annotations"`
}

RemoteMCPToolVersion is a tool's description, schema and annotations as a manager reviewed them.

type Result

type Result struct {
	Text    string
	IsError bool
	Ms      int64
	Digest  []byte
}

Result is a call's result as the model may read it: text only, images and HTML stripped, at most MaxResult bytes.

type RevokeArgs

type RevokeArgs struct{}

RevokeArgs is the minute's revocation of removed sign-ins' tokens.

func (RevokeArgs) InsertOpts

func (RevokeArgs) InsertOpts() river.InsertOpts

InsertOpts runs it once at a time.

func (RevokeArgs) Kind

func (RevokeArgs) Kind() string

Kind implements river.JobArgs.

type RevokeWorker

type RevokeWorker struct {
	river.WorkerDefaults[RevokeArgs]
	S *Service
}

RevokeWorker runs the revocations, 100 a run.

func (*RevokeWorker) Work

func (w *RevokeWorker) Work(ctx context.Context, _ *river.Job[RevokeArgs]) error

Work implements river.Worker.

type Service

type Service struct {
	Pool  *pgxpool.Pool
	Q     *store.Queries
	Audit *audit.Logger
	Box   *secrets.Box
	Log   *slog.Logger
	// AllowPrivate allows servers on private addresses (the instance's
	// setting); PublicURL is the instance's address, for OAuth redirects.
	AllowPrivate func() bool
	PublicURL    func() string
	// Now is the clock, CallTimeout a call's (tests); zero values take the
	// wall clock and 30 seconds.
	Now         func() time.Time
	CallTimeout time.Duration
}

Service is the workspace's MCP servers.

func (*Service) Call

func (s *Service) Call(ctx context.Context, ws *store.Workspace, owner *authz.Principal, thread uuid.UUID, callID string, toolID uuid.UUID, hash []byte, args json.RawMessage) (Result, error)

Call calls a tool as the owner, at the hash it was offered with, within the call timeout. The call is audited with the digest of its arguments and its outcome, never their content.

func (*Service) Callback

Callback finishes a sign-in: the state must be this person's, from this session, unused and fresh. It returns where the browser goes next.

func (*Service) ClientMetadataDocument

func (s *Service) ClientMetadataDocument() (MCPClientMetadataDocument, bool)

ClientMetadataDocument is the document, when the public URL is https.

func (*Service) Create

Create adds a server. Its URL must pass the SSRF guard; its secrets are sealed. It has no tools until a sync.

func (*Service) Current

func (s *Service) Current(ctx context.Context, q *store.Queries, ws *store.Workspace, owner *authz.Principal, toolID uuid.UUID, hash []byte) (store.McpTool, store.McpServer, error)

Current is a tool as it is now, for a call the person decides on: a changed, blocked or removed tool, or a server they may no longer use, is a problem.

func (*Service) Decide

func (s *Service) Decide(ctx context.Context, ws *store.Workspace, p *authz.Principal, server, toolID uuid.UUID, in RemoteMCPToolDecision) (RemoteMCPServer, error)

Decide marks a tool read-only, writes or blocked, pinning the hash the manager reviewed; a tool that changed since gets a conflict.

func (*Service) Delete

func (s *Service) Delete(ctx context.Context, ws *store.Workspace, p *authz.Principal, id uuid.UUID) error

Delete removes a server, its tools and every member's sign-in to it, queueing their refresh tokens for revocation in the same transaction.

func (*Service) Disconnect

func (s *Service) Disconnect(ctx context.Context, ws *store.Workspace, p *authz.Principal, id uuid.UUID) error

Disconnect removes the person's own sign-in to a server, then revokes its refresh token at the authorization server when it has a revocation endpoint (best effort: the sign-in is gone whatever it answers).

func (*Service) MayRead

func (s *Service) MayRead(ctx context.Context, q *store.Queries, ws *store.Workspace, owner *authz.Principal, server uuid.UUID) (bool, error)

MayRead reports whether owner may still use a server (it is enabled and their role may use it): what its tools returned in a thread is sent to the model again only then.

func (*Service) Revoke

func (s *Service) Revoke(ctx context.Context, limit int32) (int, error)

Revoke revokes up to limit refresh tokens queued when sign-ins were removed (RFC 7009), each tried once: a token is off the queue before it is sent, and a failure is logged, never the token.

func (*Service) Servers

Servers lists the workspace's servers with their catalogs.

func (*Service) SignedOut

func (s *Service) SignedOut(ctx context.Context, srv uuid.UUID, user uuid.UUID)

SignedOut removes a person's sign-in the server refused (a 401).

func (*Service) StartOAuth

func (s *Service) StartOAuth(ctx context.Context, ws *store.Workspace, p *authz.Principal, id uuid.UUID) (RemoteMCPOAuthStart, error)

StartOAuth begins a person's sign-in to an OAuth server: they open the returned address in their browser; the authorization server sends them back to the callback.

func (*Service) Sync

Sync lists a server's tools into its catalog, as the manager who asks (an OAuth server needs their own sign-in). A new tool waits for a manager; one whose description, schema or annotations changed since it was decided on is off, and managers are told.

func (*Service) SyncDue

func (s *Service) SyncDue(ctx context.Context, limit int32) (int, error)

SyncDue syncs, as the system, up to limit enabled servers last synced over an hour ago that need no person's sign-in, so a tool changed after it was decided on is off even when nobody calls it. It reports how many it listed.

func (*Service) ThreadTools

func (s *Service) ThreadTools(ctx context.Context, q *store.Queries, ws *store.Workspace, owner *authz.Principal, thread uuid.UUID) ([]ThreadTool, error)

ThreadTools are the tools a thread may offer: on the servers its owner chose that they may still use, enabled, decided on at their current hash, with the owner's own sign-in where the server needs one.

func (*Service) Update

Update changes a server's name, switch, access or secrets.

func (*Service) Usable

Usable lists the servers a person may choose for their threads, with whether they still have to sign in.

type SyncArgs

type SyncArgs struct{}

SyncArgs is the hourly sync of servers without per-person sign-ins.

func (SyncArgs) InsertOpts

func (SyncArgs) InsertOpts() river.InsertOpts

InsertOpts runs it once at a time.

func (SyncArgs) Kind

func (SyncArgs) Kind() string

Kind implements river.JobArgs.

type SyncWorker

type SyncWorker struct {
	river.WorkerDefaults[SyncArgs]
	S *Service
}

SyncWorker runs the hourly sync, 20 servers a run.

func (*SyncWorker) Timeout

func (w *SyncWorker) Timeout(*river.Job[SyncArgs]) time.Duration

Timeout bounds a run: each server's listing has its own timeouts (a minute at most, with the fallback to HTTP with SSE).

func (*SyncWorker) Work

func (w *SyncWorker) Work(ctx context.Context, _ *river.Job[SyncArgs]) error

Work implements river.Worker.

type ThreadTool

type ThreadTool struct {
	ID          uuid.UUID
	ServerID    uuid.UUID
	ServerName  string
	Name        string
	ModelName   string
	Description string
	InputSchema map[string]any
	// Writes: each call waits for the person's confirmation.
	Writes bool
	Hash   []byte
}

ThreadTool is a tool a thread may offer the model.

Directories

Path Synopsis
Package mcptest has fake remote MCP servers and a fake OAuth authorization server for tests of the assistant's MCP client.
Package mcptest has fake remote MCP servers and a fake OAuth authorization server for tests of the assistant's MCP client.

Jump to

Keyboard shortcuts

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