mcp

package module
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Sep 21, 2025 License: Apache-2.0 Imports: 20 Imported by: 6

README

MCP (Model Context Protocol) for Go

MCP is a Go implementation of the Model Context Protocol — a standardized way for applications to communicate with AI models. It allows developers to seamlessly bridge applications and AI models using a lightweight, JSON-RPC–based protocol.

This repository contains the shared protocol definitions and schemas for MCP. It is used by MCP, which provides the actual implementation of the MCP server and client framework.

Official Model Context Protocol Specification

Overview

MCP (Model Context Protocol) is designed to provide a standardized communication layer between applications and AI models. The protocol simplifies the integration of AI capabilities into applications by offering a consistent interface for resource access, prompt management, model interaction, and tool invocation.

Key features:

  • JSON-RPC 2.0–based communication
  • Support for multiple transport protocols (HTTP/SSE, stdio)
  • Server-side features:
    • Resource management
    • Model prompting and completion
    • Tool invocation
    • Subscriptions for resource updates
    • Logging
    • Progress reporting
    • Request cancellation
  • Client-side features:
    • Roots
    • Sampling

Architecture

For detailed guides on custom server implementations and authentication, see docs/implementer.md and docs/authentication.md.

MCP is built around the following components:

  1. Server: Handles incoming requests and dispatches to the protocol implementation
  2. Client: Makes requests to MCP-compatible servers
  3. Protocol Implementation (server.Handler): Provides the actual functionality behind each protocol method
High-Level Architecture
graph LR
    Client[MCP Client] -->|JSON-RPC / HTTP/SSE| Server[MCP Server]
    Server -->|Dispatches to| Handler[MCP Server]
    subgraph Auth[Authentication / Authorization]
      OAuth2[OAuth2 / OIDC]
    end
    Client -.->|Bearer Token| OAuth2
    Server -.->|Token Validation| OAuth2

Getting Started

Installation
go get github.com/viant/mcp

If you just need to connect **existing tools** to a remote MCP server you might prefer to use the standalone **Bridge** binary instead of embedding the Go package.  See [Bridge Guide](docs/bridge.md) for details.
Creating a Server
Quick Start: Default Server

DefaultHandler can be used to quickly set up an MCP server. It provides no-op stubs for all methods, allowing you to focus on implementing only the methods you need. Register handlers inline without writing a custom server type:

package main

import (
  "context"
  "encoding/json"
  "fmt"
  "github.com/viant/jsonrpc"
  "github.com/viant/mcp-protocol/schema"
  serverproto "github.com/viant/mcp-protocol/server"
  "github.com/viant/mcp/server"
  "log"
)

func main() {

  type Addition struct {
    A int `json:"a"`
    B int `json:"b"`
  }

  type Output struct {
    Result int
  }

  newHandler := serverproto.WithDefaultHandler(context.Background(), func(server *serverproto.DefaultHandler) error {
    // Register a simple resource
    server.RegisterResource(schema.Resource{Name: "hello", Uri: "/hello"},
      func(ctx context.Context, request *schema.ReadResourceRequest) (*schema.ReadResourceResult, *jsonrpc.Error) {
        return &schema.ReadResourceResult{Contents: []schema.ReadResourceResultContentsElem{{Text: "Hello, world!"}}}, nil
      })

    type Addition struct {
      A int `json:"a"`
      B int `json:"b"`
    }

    type Result struct {
      Result int `json:"acc"`
    }
    // Register a simple calculator tool: adds two integers
    if err := serverproto.RegisterTool[*Addition, *Result](server.Registry, "add", "Add two integers", func(ctx context.Context, input *Addition) (*schema.CallToolResult, *jsonrpc.Error) {
      sum := input.A + input.B
      out := &Result{Result: sum}
      data, err := json.Marshal(out)
      if err != nil {
        return nil, jsonrpc.NewInternalError(fmt.Sprintf("failed to marshal result: %v", err), nil)
      }
      return &schema.CallToolResult{Content: []schema.CallToolResultContentElem{{Text: string(data)}}}, nil
    }); err != nil {
      return err
    }
    return nil
  })

  srv, err := server.New(
    server.WithNewHandler(newHandler),
    server.WithImplementation(schema.Implementation{"default", "1.0"}),
  )
  if err != nil {
    log.Fatalf("Failed to create server: %v", err)
  }

  log.Fatal(srv.HTTP(context.Background(), ":4981").ListenAndServe())

}
Further Reading

Authentication & Authorization Summary

MCP supports transport-agnostic authentication and authorization (HTTP or HTTP-SSE) via OAuth2/OIDC in two modes:

  • Global Resource Protection (spec-based):

    • github.com/viant/mcp/server/auth.AuthServer enforces a Bearer token across all endpoints, except those excluded via ExcludeURI (e.g. /sse).
    • Configure by creating an auth.Service from authorization.Policy and wiring it with: server.WithProtectedResourcesHandler(service.ProtectedResourcesHandler), server.WithAuthorizer(service.Middleware), and server.WithJRPCAuthorizer(service.EnsureAuthorized).
    • Exposes /.well-known/oauth-protected-resource for metadata discovery (RFC 9728).
  • Fine-Grained Tool/Resource Control (experimental):

    • Implements auth.Authorizer in AuthServer.EnsureAuthorized, returning 401 Unauthorized per JSON-RPC request.
    • Configure per-tool/resource metadata via Config.Tools or Config.Tenants in authorization.Policy.
  • Fallback Token Fetching:

    • github.com/viant/mcp/server/auth.FallbackAuth wraps a strict AuthServer.
    • On 401 challenge, fetches tokens via ProtectedResourceTokenSource and optional ID tokens via IdTokenSource, then retries.
    • Create with auth.NewFallbackAuth(strictAuthServer, tokenSource, idTokenSource).
  • Client-Side Support:

    • Use github.com/viant/mcp/client/auth/transport.New with:
      • WithStore(store.Store): handles client config, metadata & token caching.
      • WithAuthFlow(flow.AuthFlow): selects interactive auth flow (e.g., browser PKCE).
    • The RoundTripper automatically:
      1. Handles the initial 401 challenge (WWW-Authenticate header).
      2. Discovers protected resource and auth server metadata.
      3. Acquires tokens and retries the original request with Authorization: Bearer <token>.
  • Example SSE integration:

    rt, _ := transport.New(
        transport.WithStore(myStore),
        transport.WithAuthFlow(flow.NewBrowserFlow()),
    )
    httpClient := &http.Client{Transport: rt}
    sseTransport, _ := sse.New(ctx, "https://myapp.example.com/sse", sse.WithClient(httpClient))
    mcpClient := client.New("MyClient", "1.0", sseTransport, client.WithCapabilities(schema.ClientCapabilities{}))
    

These features are transport-agnostic and apply equally over HTTP, SSE, or other supported transports.

Protocol Methods

MCP supports the following Server Side methods:

  • initialize - Initialize the connection
  • ping - Check server status
  • resources/list - List available resources
  • resources/read - Read resource contents
  • resources/templates/list - List resource templates
  • resources/subscribe - Subscribe to resource updates
  • resources/unsubscribe - Unsubscribe from resource updates
  • prompts/list - List available prompts
  • prompts/get - Get prompt details
  • tools/list - List available tools
  • tools/call - Call a specific tool
  • complete - Get completions from the model
  • logging/setLevel - Set logging level

MCP supports the following Client Side methods:

  • roots/list - List available roots
  • sampling/createMessage - A standardized way for servers to request LLM sampling (“completions” or “generations”) from language models via clients.
  • elicitation/create - Ask the client to perform an elicitation (model completion) using provided prompts.
  • interaction/create - Initiate a user-interaction request, allowing the server to prompt the user via the client UI.

can

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

This project is licensed under the Apache License 2.0.

Credits

Author: Adrian Witas

This project is maintained by Viant.

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:

  1. NewClient – returns a fully configured MCP client instance and
  2. 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

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewClient

func NewClient(handler pclient.Handler, options *ClientOptions) (*client.Client, error)

NewClient creates an MCP client with transport and authorization configured via ClientOptions.

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 bool     `` /* 149-byte string literal not displayed */
}

ClientAuth defines authentication options for an MCP client.

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"`
}

ClientOptions

defines options for configuring an MCP client.

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.

type ClientTransport

type ClientTransport struct {
	Type                 string `` /* 165-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       `` /* 165-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"`
}

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/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.

Jump to

Keyboard shortcuts

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