Documentation
¶
Overview ¶
Package mcp provides high-level helpers for working with the Model Context Protocol (MCP).
The package glues the low-level protocol types defined in the github.com/viant/mcp-protocol module with concrete transports, authentication layers and convenience configuration structures. In practice it is used as an umbrella package that exposes two primary entry-points:
- NewClient – returns a fully configured MCP client instance and
- NewServer – returns a fully configured MCP server instance.
Both constructors accept option structures that can be populated from CLI flags or configuration files, making it straightforward to spin up an MCP client/server with support for HTTP(SSE) or stdio transports, OAuth2 / "backend-for-frontend" flows and custom metadata.
Example:
srv, _ := mcp.NewServer(myImplementation, &mcp.ServerOptions{ /* … */ })
cli, _ := mcp.NewClient(srv, &mcp.ClientOptions{ /* … */ })
See the README for a more complete introduction.
Index ¶
- func NewClient(handler pclient.Handler, options *ClientOptions) (*client.Client, error)
- func NewClientWithContext(ctx context.Context, handler pclient.Handler, options *ClientOptions) (*client.Client, error)
- func NewServer(newHandler protoserver.NewHandler, options *ServerOptions) (*server.Server, error)
- type ClientAuth
- type ClientOptions
- type ClientTransport
- type ClientTransportHTTP
- type ClientTransportStdio
- type ServerOptionAuth
- type ServerOptions
- type ServerTransport
- type ServerTransportOptions
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func NewClient ¶
NewClient creates an MCP client with transport and authorization configured via ClientOptions.
func NewClientWithContext ¶ added in v0.16.0
func NewClientWithContext(ctx context.Context, handler pclient.Handler, options *ClientOptions) (*client.Client, error)
NewClientWithContext creates an MCP client and runs discovery (or the legacy initialize handshake) with the supplied context so per-request auth tokens and other caller state are available during negotiation.
func NewServer ¶
func NewServer(newHandler protoserver.NewHandler, options *ServerOptions) (*server.Server, error)
NewServer creates a new MCP server with the given implementer and options.
Types ¶
type ClientAuth ¶
type ClientAuth struct {
OAuth2ConfigURL []string `yaml:"oauth2ConfigURL,omitempty" json:"oauth2ConfigURL,omitempty" short:"c" long:"config" description:"oauth2 config file"`
EncryptionKey string `yaml:"encryptionKey,omitempty" json:"encryptionKey,omitempty" short:"k" long:"key" description:"encryption key"`
UseIdToken bool `yaml:"useIdToken,omitempty" json:"useIdToken,omitempty"`
// BackendForFrontend enables BFF auth mode. When nil (not configured),
// defaults to true if an auth RoundTripper is injected via SetAuthTransport.
// Set explicitly to false to disable BFF and use standard OAuth2 flow.
BackendForFrontend *bool `` /* 149-byte string literal not displayed */
// PassUserToken controls whether the logged-in user's auth token is
// forwarded to this MCP server. When nil (not configured), defaults to
// true — the app user's token is sent as Bearer on the first probe so
// MCP servers sharing the same IDP can authenticate without a separate
// OAuth flow. Set explicitly to false to disable token forwarding.
//
// PassUserToken is a legacy forwarding flag: it is meaningful only for
// the built-in (non-delegated) auth paths. In delegated mode (Mode
// "oauth" with ProviderRef/InlineProvider, or an installed
// ExternalResolver) it is rejected when true and ShouldPassUserToken
// always reports false — validated host-token reuse is requested through
// WorkspaceTokenReuse and implemented by the external resolver, which
// owns token provenance.
PassUserToken *bool `yaml:"passUserToken,omitempty" json:"passUserToken,omitempty" description:"forward logged-in user token to MCP server"`
// Store allows injecting a persistent token store so tokens survive
// across multiple client instances (e.g., per-user cache in caller).
Store store.Store `yaml:"-" json:"-"`
// Mode selects the auth mode. Empty preserves legacy behaviour
// (OAuth2ConfigURL/BFF); "oauth" enables delegated multi-provider OAuth
// driven by an external CredentialResolver.
Mode string `yaml:"mode,omitempty" json:"mode,omitempty" description:"auth mode: empty (legacy) or oauth (delegated)"`
// ProviderRef references an OAuth provider registered with the host's
// ProviderRegistry. Mutually exclusive with InlineProvider.
ProviderRef string `yaml:"providerRef,omitempty" json:"providerRef,omitempty" description:"registered oauth provider reference"`
// ClientRef selects a client registration within the referenced or
// inline provider; empty resolves the provider default client.
ClientRef string `yaml:"clientRef,omitempty" json:"clientRef,omitempty" description:"oauth client reference within the provider"`
// InlineProvider defines the OAuth provider inline instead of by
// reference. Mutually exclusive with ProviderRef.
InlineProvider *authcfg.OAuthProvider `yaml:"inlineProvider,omitempty" json:"inlineProvider,omitempty"`
// Resource is the protected resource (audience) the credential must
// target; defaults to the MCP transport URL when empty.
Resource string `yaml:"resource,omitempty" json:"resource,omitempty" description:"protected resource / audience"`
// Scopes lists the OAuth scopes required for this MCP server.
Scopes []string `yaml:"scopes,omitempty" json:"scopes,omitempty" description:"required oauth scopes"`
// TokenType selects accessToken (default) or idToken.
TokenType string `yaml:"tokenType,omitempty" json:"tokenType,omitempty" description:"accessToken or idToken"`
// Resolution selects eager (default: resolve before initialize/discovery)
// or challenge (resolve only after a 401).
Resolution string `yaml:"resolution,omitempty" json:"resolution,omitempty" description:"eager or challenge"`
// WorkspaceTokenReuse tells the external resolver whether a host token
// may satisfy this requirement: never (default) or ifCompatible.
WorkspaceTokenReuse string `yaml:"workspaceTokenReuse,omitempty" json:"workspaceTokenReuse,omitempty" description:"never or ifCompatible"`
// AllowCrossOriginResource permits Resource to have a different origin
// than the MCP transport URL (host-side allowlisting decision).
AllowCrossOriginResource bool `yaml:"allowCrossOriginResource,omitempty" json:"allowCrossOriginResource,omitempty"`
// ExternalResolver, when set, delegates credential acquisition, refresh
// and invalidation to the host. viant/mcp then disables its legacy
// interactive/browser fallback for this client, attaches only the
// resolved credential, and coordinates 401 recovery: in eager mode
// (default Resolution) it resolves proactively before
// initialize/discovery/every request and performs at most one refresh
// plus one retry after 401; in challenge mode (Resolution "challenge")
// the first request carries no Authorization and the resolver is
// consulted only after a 401, with at most one authenticated retry.
// Afterwards a typed *config.OAuthLinkRequiredError is returned;
// Invalidate fires only after a resolved/refreshed credential is
// terminally rejected. The resolved value is never installed into any
// host identity context.
ExternalResolver authcfg.CredentialResolver `yaml:"-" json:"-"`
// ProviderRegistry optionally resolves ProviderRef during requirement
// compilation so the issuer is known before the first request.
ProviderRegistry authcfg.ProviderRegistry `yaml:"-" json:"-"`
}
ClientAuth defines authentication options for an MCP client.
func (*ClientAuth) CompileRequirement ¶ added in v0.20.0
func (c *ClientAuth) CompileRequirement(ctx context.Context, serverName, transportURL string) (*authcfg.Requirement, error)
CompileRequirement compiles this configuration into the host-neutral credential requirement resolved before transport use. serverName labels the MCP definition; transportURL supplies the default resource and the origin check reference.
func (*ClientAuth) IsDelegated ¶ added in v0.20.0
func (c *ClientAuth) IsDelegated() bool
IsDelegated reports whether this configuration selects the delegated OAuth path (external resolver owns credentials; legacy interactive/BFF flows are disabled). Legacy configurations — no Mode, no provider references, no installed resolver — are never delegated.
func (*ClientAuth) ShouldPassUserToken ¶ added in v0.14.0
func (c *ClientAuth) ShouldPassUserToken() bool
ShouldPassUserToken reports whether the logged-in user's token should be forwarded to this MCP server. Defaults to true when not configured. Delegated mode always reports false: only the credential returned by the external resolver may reach a delegated MCP server, and host-token reuse is decided by the resolver through the WorkspaceTokenReuse policy.
func (*ClientAuth) Validate ¶ added in v0.20.0
func (c *ClientAuth) Validate() error
Validate checks the auth configuration for structural conflicts. Legacy configurations (OAuth2ConfigURL/BFF/PassUserToken only) always pass.
type ClientOptions ¶
type ClientOptions struct {
Name string `yaml:"name" json:"name,omitempty" short:"n" long:"name" description:"mcp name"`
Version string `yaml:"version,omitempty" json:"version,omitempty" short:"v" long:"version" description:"mcp version"`
ProtocolVersion string `yaml:"protocol,omitempty" json:"protocol,omitempty" short:"p" long:"protocol" description:"mcp protocol"`
Namespace string `yaml:"namespace,omitempty" json:"namespace,omitempty" short:"N" long:"namespace" description:"mcp namespace"`
Transport ClientTransport `yaml:"transport,omitempty" json:"transport,omitempty" short:"t" long:"transport" description:"mcp transport options"`
Auth *ClientAuth `yaml:"auth,omitempty" json:"auth,omitempty" short:"a" long:"auth" description:"mcp auth options"`
// CookieJar, if set, is attached to the underlying HTTP client so that
// servers using cookies (e.g., BFF flows) can persist session cookies
// across reconnects and calls.
CookieJar http.CookieJar `yaml:"-" json:"-"`
// PingIntervalSeconds overrides the default background ping interval
// used to keep MCP sessions warm and detect transport failures.
// If <= 0, the default is used (currently 60 seconds).
PingIntervalSeconds int `yaml:"pingIntervalSeconds,omitempty" json:"pingIntervalSeconds,omitempty"`
// contains filtered or unexported fields
}
ClientOptions
defines options for configuring an MCP client.
func (*ClientOptions) AuthStore ¶ added in v0.7.3
func (c *ClientOptions) AuthStore() store.Store
AuthStore exposes the underlying token store used by the auth transport. It allows callers to persist and reuse tokens across client instances.
func (*ClientOptions) Init ¶
func (c *ClientOptions) Init()
func (*ClientOptions) Options ¶
func (c *ClientOptions) Options(authRT *authtransport.RoundTripper) []client.Option
Options builds client options (metadata and auth interceptor) based on ClientOptions.Auth and Namespace.
func (*ClientOptions) SetAuthTransport ¶ added in v0.12.0
func (c *ClientOptions) SetAuthTransport(rt *authtransport.RoundTripper, httpClient *http.Client)
SetAuthTransport injects a pre-built auth RoundTripper and HTTP client into the options so that getTransport reuses them instead of building new ones. This is the safe way for managers to inject per-user auth without leaking the internal cachedAuthRT/cachedHTTPClient fields.
type ClientTransport ¶
type ClientTransport struct {
Type string `` /* 167-byte string literal not displayed */
ClientTransportStdio `yaml:",inline"`
ClientTransportHTTP `yaml:",inline"`
}
ClientTransport defines transport options for an MCP client.
type ClientTransportHTTP ¶
type ClientTransportHTTP struct {
URL string `yaml:"url" json:"url" short:"u" long:"url" description:"mcp url"`
}
ClientTransportHTTP defines options for a server-sent events transport for an MCP client.
type ClientTransportStdio ¶
type ClientTransportStdio struct {
Command string `yaml:"command" json:"command" short:"C" long:"command" description:"mcp command"`
Arguments []string `yaml:"arguments" json:"arguments" short:"A" long:"arguments" description:"mcp command arguments"`
}
ClientTransportStdio defines options for a standard input/output transport for an MCP client.
type ServerOptionAuth ¶
type ServerOptionAuth struct {
ProtectedResourcesHandler http.HandlerFunc
Authorizer server.Middleware
JRPCAuthorizer auth.JRPCAuthorizer //experimental
UseJRPCAuthorizer bool // if true, JRPCAuthorizer will be used for JSON-RPC requests
//Optional metadata for protected resources
Policy *authorization.Policy
}
type ServerOptions ¶
type ServerOptions struct {
Name string `yaml:"name" json:"name"`
Version string `yaml:"version" json:"version"`
ProtocolVersion string `yaml:"protocol" json:"protocol" short:"p" long:"protocol" description:"mcp protocol"`
LoggerName string `yaml:"loggerName" json:"loggerName"`
Transport *ServerTransport `yaml:"transport" json:"transport"`
}
ServerOptions defines options for configuring an MCP server.
type ServerTransport ¶
type ServerTransport struct {
Type string `yaml:"type" json:"type"`
Options *ServerTransportOptions `yaml:"options" json:"options"`
Auth *ServerOptionAuth `yaml:"-" json:"-"`
CustomHandlers map[string]http.HandlerFunc `yaml:"-" json:"-"`
}
type ServerTransportOptions ¶
type ServerTransportOptions struct {
Type string `` /* 167-byte string literal not displayed */
Port int `yaml:"port" json:"port"`
Endpoint string `yaml:"endpoint" json:"endpoint"`
MessageEndpoint string `yaml:"messageEndpoint" json:"messageEndpoint"`
Cors *server.Cors `yaml:"cors" json:"cors"`
// Optional HTTP transport configuration
SSEURI string `yaml:"sseURI" json:"sseURI"`
SSEMessageURI string `yaml:"sseMessageURI" json:"sseMessageURI"`
StreamableURI string `yaml:"streamableURI" json:"streamableURI"`
RootRedirect bool `yaml:"rootRedirect" json:"rootRedirect"`
}
Directories
¶
| Path | Synopsis |
|---|---|
|
Command bridge is a standalone binary that runs an MCP bridge.
|
Command bridge is a standalone binary that runs an MCP bridge. |
|
mcp
Package mcp provides the implementation of the `bridge` proxy service.
|
Package mcp provides the implementation of the `bridge` proxy service. |
|
Package clientHandler implements a high-level Go clientHandler for the Model Context Protocol (MCP).
|
Package clientHandler implements a high-level Go clientHandler for the Model Context Protocol (MCP). |
|
auth
Package auth contains supporting helpers that enable fine-grained client side authorization when talking to an MCP server.
|
Package auth contains supporting helpers that enable fine-grained client side authorization when talking to an MCP server. |
|
auth/config
Package config defines host-neutral OAuth configuration, requirement and credential types shared by MCP clients.
|
Package config defines host-neutral OAuth configuration, requirement and credential types shared by MCP clients. |
|
auth/mock
Package mock provides in-memory and stub implementations that facilitate unit testing of the client-side authorization flow.
|
Package mock provides in-memory and stub implementations that facilitate unit testing of the client-side authorization flow. |
|
auth/store
Package store defines simple token and client-configuration stores used by the authorization helpers in the parent `auth` package.
|
Package store defines simple token and client-configuration stores used by the authorization helpers in the parent `auth` package. |
|
auth/transport
Package transport implements an http.RoundTripper that performs the OAuth 2.1 [Protected Resource Metadata](https://www.rfc-editor.org/rfc/rfc9728) discovery, token acquisition and automatic request retry logic required by MCP when a server challenges the client with `401 Unauthorized`.
|
Package transport implements an http.RoundTripper that performs the OAuth 2.1 [Protected Resource Metadata](https://www.rfc-editor.org/rfc/rfc9728) discovery, token acquisition and automatic request retry logic required by MCP when a server challenges the client with `401 Unauthorized`. |
|
Package example contains self-contained snippets and integration tests that demonstrate how to use the MCP client/server libraries.
|
Package example contains self-contained snippets and integration tests that demonstrate how to use the MCP client/server libraries. |
|
auth/experimental
Package term shows an experimental end-to-end flow that exercises the MCP authorization stack using a browser-based OAuth 2.1 flow.
|
Package term shows an experimental end-to-end flow that exercises the MCP authorization stack using a browser-based OAuth 2.1 flow. |
|
auth/percall
Package percall demonstrates per-call token usage.
|
Package percall demonstrates per-call token usage. |
|
auth/term
Package term demonstrates how to integrate terminal-based user interaction with an MCP server secured by OAuth2/OIDC.
|
Package term demonstrates how to integrate terminal-based user interaction with an MCP server secured by OAuth2/OIDC. |
|
custom
Package custom shows how to implement a fully custom MCP tool and register it with a server.
|
Package custom shows how to implement a fully custom MCP tool and register it with a server. |
|
fs
Package fs contains examples that treat a local filesystem subtree as an MCP resource provider.
|
Package fs contains examples that treat a local filesystem subtree as an MCP resource provider. |
|
resource
Package resource contains helper types used by other examples to model simple resources exposed over MCP.
|
Package resource contains helper types used by other examples to model simple resources exposed over MCP. |
|
tool
Package tool implements a very small sample tool that can be registered with an MCP server for demonstration purposes (see tests in the parent example packages).
|
Package tool implements a very small sample tool that can be registered with an MCP server for demonstration purposes (see tests in the parent example packages). |
|
internal
|
|
|
conv
Package conv collects tiny helper functions that are not part of the public API but aid internal conversions.
|
Package conv collects tiny helper functions that are not part of the public API but aid internal conversions. |
|
Package handler provides a configurable MCP handler implementation.
|
Package handler provides a configurable MCP handler implementation. |
|
auth
Package auth exposes helpers that make it easy to protect an MCP server with OAuth2/OIDC.
|
Package auth exposes helpers that make it easy to protect an MCP server with OAuth2/OIDC. |
|
namespace
Package namespace provides a reusable, policy-aware namespace resolution utility for MCP servers and services.
|
Package namespace provides a reusable, policy-aware namespace resolution utility for MCP servers and services. |
|
oob
Package oob provides minimal, generic primitives to manage out-of-band (OOB) interactions using typed pending entries bound to a namespace.
|
Package oob provides minimal, generic primitives to manage out-of-band (OOB) interactions using typed pending entries bound to a namespace. |