mcp

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Sep 9, 2025 License: Apache-2.0 Imports: 15 Imported by: 0

README

Genkit MCP Plugin

Model Context Protocol (MCP) integration for Go Genkit - connect to MCP servers and expose Genkit tools as MCP servers.

GenkitMCPClient - Single Server Connection

Connect to and use tools/prompts from a single MCP server:

package main

import (
    "context"
    "log"
    
    "github.com/firebase/genkit/go/genkit"
    "github.com/firebase/genkit/go/plugins/mcp"
)

func main() {
    ctx := context.Background()
    g, _ := genkit.Init(ctx)
    
    // Connect to the MCP everything server
    client, err := mcp.NewGenkitMCPClient(mcp.MCPClientOptions{
        Name: "everything-server",
        Stdio: &mcp.StdioConfig{
            Command: "npx",
            Args: []string{"-y", "@modelcontextprotocol/server-everything"},
        },
    })
    if err != nil {
        log.Fatal(err)
    }
    
    // Get specific tools from the everything server
    echoTool, err := client.GetTool(ctx, g, "echo")
    if err != nil {
        log.Fatal(err)
    }
    
    addTool, err := client.GetTool(ctx, g, "add")
    if err != nil {
        log.Fatal(err)
    }
    
    // Get specific prompts from the everything server
    simplePrompt, err := client.GetPrompt(ctx, g, "simple_prompt")
    if err != nil {
        log.Fatal(err)
    }
    
    // Get all available tools
    tools, err := client.GetActiveTools(ctx, g)
    if err != nil {
        log.Fatal(err)
    }
    
}

GenkitMCPManager - Multiple Server Management

Manage connections to multiple MCP servers:

package main

import (
    "context"
    "log"
    
    "github.com/firebase/genkit/go/genkit"
    "github.com/firebase/genkit/go/plugins/mcp"
)

func main() {
    ctx := context.Background()
    g, _ := genkit.Init(ctx)
    
    // Create manager with multiple servers
    manager, err := mcp.NewMCPManager(mcp.MCPManagerOptions{
        Name: "my-app",
        MCPServers: map[string]mcp.MCPClientOptions{
            "everything": {
                Name: "everything-server",
                Stdio: &mcp.StdioConfig{
                    Command: "npx",
                    Args: []string{"-y", "@modelcontextprotocol/server-everything"},
                },
            },
            "filesystem": {
                Name: "fs-server",
                Stdio: &mcp.StdioConfig{
                    Command: "npx",
                    Args: []string{"@modelcontextprotocol/server-filesystem", "/tmp"},
                },
            },
        },
    })
    if err != nil {
        log.Fatal(err)
    }
    
    // Connect to new server at runtime
    err = manager.ConnectServer(ctx, "weather", mcp.MCPClientOptions{
        Name: "weather-server",
        Stdio: &mcp.StdioConfig{
            Command: "python",
            Args: []string{"weather_server.py"},
        },
    })
    if err != nil {
        log.Fatal(err)
    }
    
    // Temporarily disable/enable servers
    manager.DisableServer("filesystem")
    manager.EnableServer("filesystem")
    
    // Disconnect server
    manager.DisconnectServer("weather")
    
    // Get tools from all active servers
    tools, err := manager.GetActiveTools(ctx, g)
    if err != nil {
        log.Fatal(err)
    }
}

GenkitMCPServer - Expose Genkit Tools

Turn your Genkit app into an MCP server:

package main

import (
    "context"
    "log"
    
    "github.com/firebase/genkit/go/genkit"
    "github.com/firebase/genkit/go/plugins/mcp"
    "github.com/firebase/genkit/go/ai"
)

func main() {
    ctx := context.Background()
    g, _ := genkit.Init(ctx)
    
    // Define some tools
    addTool := genkit.DefineTool(g, "add", "Add two numbers",
        func(ctx *ai.ToolContext, input struct{A, B int}) (int, error) {
            return input.A + input.B, nil
        })
    
    multiplyTool := genkit.DefineTool(g, "multiply", "Multiply two numbers",
        func(ctx *ai.ToolContext, input struct{X, Y int}) (int, error) {
            return input.X * input.Y, nil
        })
    
    // Option 1: Auto-expose all tools
    server := mcp.NewMCPServer(g, mcp.MCPServerOptions{
        Name:    "genkit-calculator",
        Version: "1.0.0",
    })
    
    // Option 2: Expose specific tools only
    server = mcp.NewMCPServer(g, mcp.MCPServerOptions{
        Name:    "genkit-calculator", 
        Version: "1.0.0",
        Tools:   []ai.Tool{addTool, multiplyTool},
    })
    
    // Start MCP server
    log.Println("Starting MCP server...")
    if err := server.ServeStdio(ctx); err != nil {
        log.Fatal(err)
    }
}

Testing Your Server

# Run your server
go run main.go

# Test with MCP Inspector
npx @modelcontextprotocol/inspector go run main.go

Transport Options

Stdio (Standard)
Stdio: &mcp.StdioConfig{
    Command: "uvx",
    Args: []string{"mcp-server-time"},
    Env: []string{"DEBUG=1"},
}
SSE (Web clients)
SSE: &mcp.SSEConfig{
    BaseURL: "http://localhost:3000/sse",
}

Documentation

Overview

Package mcp provides a client for integration with the Model Context Protocol.

Package mcp provides a client for integration with the Model Context Protocol.

Package mcp provides a client for integration with the Model Context Protocol.

Package mcp provides a client for integration with the Model Context Protocol.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ExtractTextFromContent

func ExtractTextFromContent(content mcp.Content) string

ExtractTextFromContent extracts text content from MCP Content

Types

type GenkitMCPClient

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

GenkitMCPClient represents a client for interacting with MCP servers.

func NewGenkitMCPClient

func NewGenkitMCPClient(options MCPClientOptions) (*GenkitMCPClient, error)

NewGenkitMCPClient creates a new GenkitMCPClient with the given options. Returns an error if the initial connection fails.

func (*GenkitMCPClient) Disable

func (c *GenkitMCPClient) Disable()

Disable temporarily disables the client by closing the connection

func (*GenkitMCPClient) Disconnect

func (c *GenkitMCPClient) Disconnect() error

Disconnect closes the connection to the MCP server

func (*GenkitMCPClient) GetActivePrompts

func (c *GenkitMCPClient) GetActivePrompts(ctx context.Context) ([]mcp.Prompt, error)

GetActivePrompts retrieves all prompts available from the MCP server

func (*GenkitMCPClient) GetActiveResources added in v1.0.0

func (c *GenkitMCPClient) GetActiveResources(ctx context.Context) ([]ai.Resource, error)

GetActiveResources fetches resources from the MCP server

func (*GenkitMCPClient) GetActiveTools

func (c *GenkitMCPClient) GetActiveTools(ctx context.Context, g *genkit.Genkit) ([]ai.Tool, error)

GetActiveTools retrieves all tools available from the MCP server

func (*GenkitMCPClient) GetPrompt

func (c *GenkitMCPClient) GetPrompt(ctx context.Context, g *genkit.Genkit, promptName string, args map[string]string) (ai.Prompt, error)

GetPrompt retrieves a prompt from the MCP server

func (*GenkitMCPClient) GetPromptNameWithNamespace

func (c *GenkitMCPClient) GetPromptNameWithNamespace(promptName string) string

GetPromptNameWithNamespace returns a prompt name prefixed with the client's namespace

func (*GenkitMCPClient) GetResourceNameWithNamespace added in v1.0.0

func (c *GenkitMCPClient) GetResourceNameWithNamespace(resourceName string) string

GetResourceNameWithNamespace returns a resource name prefixed with the client's namespace

func (*GenkitMCPClient) GetToolNameWithNamespace

func (c *GenkitMCPClient) GetToolNameWithNamespace(toolName string) string

GetToolNameWithNamespace returns a tool name prefixed with the client's namespace

func (*GenkitMCPClient) IsEnabled

func (c *GenkitMCPClient) IsEnabled() bool

IsEnabled returns whether the client is enabled

func (*GenkitMCPClient) Name

func (c *GenkitMCPClient) Name() string

Name returns the client name

func (*GenkitMCPClient) Reenable

func (c *GenkitMCPClient) Reenable()

Reenable re-enables a previously disabled client by reconnecting

func (*GenkitMCPClient) Restart

func (c *GenkitMCPClient) Restart(ctx context.Context) error

Restart restarts the transport connection

type GenkitMCPServer

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

GenkitMCPServer represents an MCP server that exposes Genkit tools, prompts, and resources

func NewMCPServer

func NewMCPServer(g *genkit.Genkit, options MCPServerOptions) *GenkitMCPServer

NewMCPServer creates a new GenkitMCPServer with the provided options

func (*GenkitMCPServer) Close added in v1.0.0

func (s *GenkitMCPServer) Close() error

Close shuts down the MCP server

func (*GenkitMCPServer) GetServer added in v1.0.0

func (s *GenkitMCPServer) GetServer() *server.MCPServer

GetServer returns the underlying MCP server instance

func (*GenkitMCPServer) ListRegisteredResources added in v1.0.0

func (s *GenkitMCPServer) ListRegisteredResources() []string

ListRegisteredResources returns the names of all discovered resources

func (*GenkitMCPServer) ListRegisteredTools

func (s *GenkitMCPServer) ListRegisteredTools() []string

ListRegisteredTools returns the names of all discovered tools

func (*GenkitMCPServer) Serve added in v1.0.0

func (s *GenkitMCPServer) Serve(transport interface{}) error

Serve starts the MCP server with a custom transport

func (*GenkitMCPServer) ServeStdio

func (s *GenkitMCPServer) ServeStdio() error

ServeStdio starts the MCP server using stdio transport

type MCPClientOptions

type MCPClientOptions struct {
	// Name for this client instance - ideally a nickname for the server
	Name string
	// Version number for this client (defaults to "1.0.0" if empty)
	Version string

	// Disabled flag to temporarily disable this client
	Disabled bool

	// Stdio contains config for starting a local server process using stdio transport
	Stdio *StdioConfig

	// SSE contains config for connecting to a remote server via SSE transport
	SSE *SSEConfig

	// StreamableHTTP contains config for connecting to a remote server via Streamable HTTP transport
	StreamableHTTP *StreamableHTTPConfig
}

MCPClientOptions holds configuration for the MCPClient.

type MCPHost added in v1.0.0

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

MCPHost manages connections to multiple MCP servers This matches the naming convention used in the JavaScript implementation

func NewMCPHost added in v1.0.0

func NewMCPHost(g *genkit.Genkit, options MCPHostOptions) (*MCPHost, error)

NewMCPHost creates a new MCPHost with the given options

func (*MCPHost) Connect added in v1.0.0

func (h *MCPHost) Connect(ctx context.Context, g *genkit.Genkit, serverName string, config MCPClientOptions) error

Connect connects to a single MCP server with the provided configuration and automatically registers tools, prompts, and resources from the server

func (*MCPHost) Disconnect added in v1.0.0

func (h *MCPHost) Disconnect(ctx context.Context, serverName string) error

Disconnect disconnects from a specific MCP server

func (*MCPHost) GetActiveResources added in v1.0.0

func (h *MCPHost) GetActiveResources(ctx context.Context) ([]ai.Resource, error)

GetActiveResources retrieves detached resources from all connected and enabled MCP clients

func (*MCPHost) GetActiveTools added in v1.0.0

func (h *MCPHost) GetActiveTools(ctx context.Context, gk *genkit.Genkit) ([]ai.Tool, error)

GetActiveTools retrieves all tools from all connected and enabled MCP clients

func (*MCPHost) GetPrompt added in v1.0.0

func (h *MCPHost) GetPrompt(ctx context.Context, gk *genkit.Genkit, serverName, promptName string, args map[string]string) (ai.Prompt, error)

GetPrompt retrieves a specific prompt from a specific server

func (*MCPHost) Reconnect added in v1.0.0

func (h *MCPHost) Reconnect(ctx context.Context, serverName string) error

Reconnect restarts a specific MCP server connection

type MCPHostOptions added in v1.0.0

type MCPHostOptions struct {
	// Name for this host instance - used for logging and identification
	Name string
	// Version number for this host (defaults to "1.0.0" if empty)
	Version string
	// MCPServers is an array of server configurations
	MCPServers []MCPServerConfig
}

MCPHostOptions holds configuration for MCPHost

type MCPServerConfig

type MCPServerConfig struct {
	// Name for this server - used as the key for lookups
	Name string
	// Config holds the client configuration options
	Config MCPClientOptions
}

MCPServerConfig holds configuration for a single MCP server

type MCPServerOptions

type MCPServerOptions struct {
	// Name for this server instance - used for MCP identification
	Name string
	// Version number for this server (defaults to "1.0.0" if empty)
	Version string
}

MCPServerOptions holds configuration for GenkitMCPServer

type SSEConfig

type SSEConfig struct {
	BaseURL    string
	Headers    map[string]string
	HTTPClient *http.Client // Optional custom HTTP client
}

SSEConfig contains options for the SSE transport

type ServerRef

type ServerRef struct {
	Client    *client.Client
	Transport transport.Interface
	Error     string
}

ServerRef represents an active connection to an MCP server

type StdioConfig

type StdioConfig struct {
	Command string
	Env     []string
	Args    []string
}

StdioConfig holds configuration for a stdio-based MCP server process.

type StreamableHTTPConfig added in v0.6.1

type StreamableHTTPConfig struct {
	BaseURL    string
	Headers    map[string]string
	HTTPClient *http.Client  // Optional custom HTTP client
	Timeout    time.Duration // HTTP request timeout
}

StreamableHTTPConfig contains options for the Streamable HTTP transport

Directories

Path Synopsis
fixtures
basic_server command
content_server command
policy_server command
server_a command
server_b command

Jump to

Keyboard shortcuts

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