mcp

package module
v1.13.5 Latest Latest
Warning

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

Go to latest
Published: Nov 6, 2026 License: Apache-2.0 Imports: 16 Imported by: 0

README

Forge MCP, a Model Context Protocol extension for Go that lists Forge routes as tools for AI assistants

Forge MCP: Model Context Protocol tools from your Go API

Forge MCP is the Model Context Protocol extension for Forge, the Go backend framework. You add it to your app and every HTTP route you register shows up as an MCP-style tool, with a name, a description from the route summary and a JSON Schema for its path parameters, query and body. You can also publish MCP resources and prompts with your own Go readers and generators. The endpoints are plain JSON over HTTP, and calling a route-backed tool does not run your handler yet, so read Status before you connect an AI agent to it.

Go CI Go Reference Apache 2.0

Documentation · Quick start · Features · Endpoints · Resources and prompts · Status · Configuration · FAQ

Quick start

You need Go 1.26 or later and a Go module:

go get github.com/xraph/forge@latest
go get github.com/xraph/forge/extensions/mcp@latest

Save this as main.go:

package main

import (
	"log"
	"net/http"

	"github.com/xraph/forge"
	"github.com/xraph/forge/extensions/mcp"
)

func main() {
	app := forge.NewApp(forge.AppConfig{
		Name:        "orders-api",
		Version:     "1.0.0",
		HTTPAddress: ":8080",
		Extensions: []forge.Extension{
			mcp.NewExtension(
				mcp.WithExcludePatterns([]string{"/_/*"}),
			),
		},
	})

	r := app.Router()

	err := r.GET("/orders/:id", func(ctx forge.Context) error {
		return ctx.JSON(http.StatusOK, map[string]string{"id": ctx.Param("id")})
	}, forge.WithSummary("Fetch one order by ID"))
	if err != nil {
		log.Fatal(err)
	}

	err = r.POST("/orders", func(ctx forge.Context) error {
		return ctx.JSON(http.StatusCreated, map[string]string{"status": "created"})
	}, forge.WithSummary("Create an order"))
	if err != nil {
		log.Fatal(err)
	}

	if err := app.Run(); err != nil {
		log.Fatal(err)
	}
}

Run it and list the tools:

go mod tidy
go run .

# in another terminal
curl http://localhost:8080/_/mcp/info
curl http://localhost:8080/_/mcp/tools

/_/mcp/info returns the server name and version (the app's, unless you set your own) and its capabilities. /_/mcp/tools returns two tools, sorted by name:

{"tools":[
  {"name":"create_orders","description":"Create an order","inputSchema":{"type":"object","properties":{"body":{"type":"object","description":"Request body"},"query":{"type":"object","description":"Query parameters (optional)","additionalProperties":true}}}},
  {"name":"get_orders_id","description":"Fetch one order by ID","inputSchema":{"type":"object","properties":{"id":{"type":"string","description":"Path parameter: id"},"query":{"type":"object","description":"Query parameters (optional)","additionalProperties":true}},"required":["id"]}}
]}

The exclude pattern keeps Forge's own /_/health, /_/metrics and friends out of the list. The MCP endpoints under the base path are always skipped.

Features

You need Forge MCP gives you
A tool catalogue for an AI assistant Every route becomes a tool at startup, named from its method and path, described by its WithSummary text
Input schemas A JSON Schema per tool with required path parameters, a query object, and a body object for POST, PUT and PATCH
Control over what's exposed ExcludePatterns and IncludePatterns with exact paths or /prefix/* globs, plus a ToolPrefix for names
MCP resources RegisterResource and RegisterResourceReader, served from /resources and /resources/read
MCP prompts RegisterPrompt and RegisterPromptGenerator, served from /prompts and /prompts/:name
Deterministic output Tool lists are sorted by name, and query strings and prompt arguments are built in sorted key order
Metrics mcp_tools_total and mcp_tool_calls_total{status} through Forge's metrics

Endpoints

With the default base path /_/mcp:

Method and path What it does
GET /_/mcp/info Server name, version and capabilities
GET /_/mcp/tools {"tools": [...]}
POST /_/mcp/tools/:name Calls a tool. Body: {"name": "...", "arguments": {...}}. See Status
GET /_/mcp/resources Lists resources, when EnableResources is on
POST /_/mcp/resources/read Reads one. Body: {"uri": "..."}
GET /_/mcp/prompts Lists prompts, when EnablePrompts is on
POST /_/mcp/prompts/:name Renders one. Body: {"arguments": {...}}

Tool names are the HTTP verb mapped to a word (GET becomes get, POST becomes create, PUT becomes update, PATCH becomes patch, DELETE becomes delete), then the path with slashes turned into underscores and the : or {} around parameters dropped. So DELETE /users/:id is delete_users_id, and with WithToolPrefix("shop_") it's shop_delete_users_id. A name longer than MaxToolNameLength (64) is skipped with a warning in the log.

Resources and prompts

Resources and prompts are the parts you fill in yourself. Turn them on, then register them from a start hook, once the MCP service exists:

app := forge.NewApp(forge.AppConfig{
	Name: "orders-api",
	Extensions: []forge.Extension{
		mcp.NewExtension(mcp.WithResources(true), mcp.WithPrompts(true)),
	},
})

err := forge.OnStarted(app, "mcp-content", func(ctx context.Context, a forge.App) error {
	svc, err := forge.Inject[*mcp.MCPService](a.Container())
	if err != nil {
		return err
	}

	srv := svc.Server()

	if err := srv.RegisterResource(&mcp.Resource{
		URI:      "orders://schema",
		Name:     "Order schema",
		MimeType: "application/json",
	}); err != nil {
		return err
	}

	if err := srv.RegisterResourceReader("orders://schema",
		func(ctx context.Context, r *mcp.Resource) (mcp.Content, error) {
			return mcp.Content{Type: "text", MimeType: r.MimeType, Text: `{"id":"string","total":"number"}`}, nil
		}); err != nil {
		return err
	}

	if err := srv.RegisterPrompt(&mcp.Prompt{
		Name:        "summarize_order",
		Description: "Summarize an order for a support agent",
		Arguments:   []mcp.PromptArgument{{Name: "id", Required: true}},
	}); err != nil {
		return err
	}

	return srv.RegisterPromptGenerator("summarize_order",
		func(ctx context.Context, p *mcp.Prompt, args map[string]any) ([]mcp.PromptMessage, error) {
			return []mcp.PromptMessage{{
				Role:    "user",
				Content: []mcp.Content{{Type: "text", Text: fmt.Sprintf("Summarize order %v in two lines.", args["id"])}},
			}}, nil
		})
})

Then POST /_/mcp/resources/read with {"uri":"orders://schema"} runs your reader, and POST /_/mcp/prompts/summarize_order with {"arguments":{"id":"42"}} runs your generator. A resource without a reader returns its name, URI and description as text. A prompt without a generator returns one user message built from its name, arguments and description.

Status

You should know three things before you build on this extension.

Calling a route-backed tool does not call your route. POST /_/mcp/tools/get_orders_id with {"arguments":{"id":"42"}} substitutes the path parameters and query, then returns the text Tool executed: GET /orders/42 as the tool result. Your handler never runs. Tools you add by hand with Server().RegisterTool are listed but cannot be called at all, because they have no route behind them.

The transport is plain JSON over HTTP. There is no JSON-RPC 2.0 framing, no initialize handshake, and no stdio or Streamable HTTP transport, so an MCP client such as Claude Desktop cannot connect to these endpoints directly. You would need a small adapter in between.

WithAuth and WithRateLimit set config fields and validation checks them (auth needs at least one token), but the extension does not apply them to its endpoints. AuthMiddleware(cfg, logger) and RateLimitMiddleware(cfg, logger, metrics) are exported as forge.PureMiddleware for you to wire up, or you can put the base path behind your gateway's auth. Until then, treat /_/mcp as public.

Configuration

You can configure the extension in code with options, or in YAML under extensions.mcp (the extension also reads a top-level mcp key).

Option Sets Default
WithEnabled(bool) Enabled. When false the extension registers nothing true
WithBasePath(string) BasePath /_/mcp
WithServerInfo(name, version) ServerName, ServerVersion the app's name and version
WithAutoExposeRoutes(bool) AutoExposeRoutes true
WithToolPrefix(string) ToolPrefix empty
WithExcludePatterns([]string) ExcludePatterns, checked first none
WithIncludePatterns([]string) IncludePatterns. When set, only matching routes are exposed none
WithResources(bool), WithPrompts(bool) EnableResources, EnablePrompts false
WithAuth(header, tokens) RequireAuth, AuthHeader, AuthTokens (see Status) off, Authorization
WithRateLimit(int) RateLimitPerMinute (see Status) 0, unlimited
WithRequireConfig(bool) Fail at startup if no YAML config is found false
WithConfig(mcp.Config) Replaces the whole config

MaxToolNameLength (64), SchemaCache (true) and EnableMetrics (true) have no option of their own; set them through WithConfig. NewExtensionWithConfig(cfg) is the same as NewExtension(WithConfig(cfg)).

The YAML keys are the snake_case field names:

extensions:
  mcp:
    tool_prefix: shop_
    exclude_patterns: ["/_/*", "/internal/*"]
    enable_prompts: true

Older configs spelled them as Go field names (ToolPrefix). Those still work, and each one logs a warning at startup telling you the new key.

Options you set in code win over the file, and the file wins over DefaultConfig(), so BasePath: /mcp or Enabled: false in YAML takes effect with a plain mcp.NewExtension(). Fields you leave out keep their defaults. One edge case: an option set to exactly its default value looks the same as no option at all, so the file wins for that field.

Forge reads config.yaml only when EnableConfigAutoDiscovery is on. forge.DefaultAppConfig() turns it on, but an AppConfig literal like the one in the quick start leaves it off.

Documentation

Topic Where
Overview MCP docs
Features and usage MCP features
Configuration reference MCP configuration
Function reference MCP functions
Go API pkg.go.dev
The protocol itself Model Context Protocol specification

Examples

The MCP server example is a user-management API with OpenAPI turned on and the MCP extension exposing its routes. It has its own go.mod, so run it from its directory with GOWORK=off go run ., then query /_/mcp/tools on port 8087.

FAQ

How do I expose a Go REST API to an AI assistant with MCP?

Add mcp.NewExtension() to your Forge app and give your routes a forge.WithSummary. The tool list at /_/mcp/tools then describes every route with a name and input schema. Read Status first: tool calls do not run your handlers yet, and the transport is not the JSON-RPC one MCP clients speak.

Can Claude Desktop or another MCP client connect to Forge MCP?

Not directly. The endpoints are JSON over HTTP without the JSON-RPC 2.0 framing or the stdio and Streamable HTTP transports the protocol defines, so you would need an adapter.

How do I hide internal routes from the MCP tool list?

Use WithExcludePatterns([]string{"/_/*", "/internal/*"}). A pattern is an exact path or a prefix ending in /*. If you'd rather list what's allowed, use WithIncludePatterns and only matching routes become tools.

Does Forge MCP require authentication?

Not by default, and the auth settings are not enforced on the endpoints today. Wire mcp.AuthMiddleware yourself or protect the base path at your gateway.

Contributing

MCP is its own Go module inside the Forge repository. Build, vet and test it from its directory the way CI does:

cd extensions/mcp
GOWORK=off go build ./...
GOWORK=off go vet ./...
GOWORK=off go test -short -count=1 ./...
golangci-lint run ./...

Forge's AGENTS.md has the pinned lint version and the rest of the repository conventions. Commits follow Conventional Commits, for example fix(mcp): ....

License

Forge MCP is part of Forge and is available under the Apache License 2.0.

Documentation

Index

Constants

View Source
const (
	// ServiceKey is the DI key for the MCP service.
	ServiceKey = "mcp"
)

DI container keys for MCP extension services.

Variables

This section is empty.

Functions

func AuthMiddleware

func AuthMiddleware(config Config, logger forge.Logger) forge.PureMiddleware

AuthMiddleware creates middleware for MCP authentication.

func NewExtension

func NewExtension(opts ...ConfigOption) forge.Extension

NewExtension creates a new MCP extension with functional options. Config is loaded from ConfigManager by default, with options providing overrides.

Example:

// Load from ConfigManager (tries "extensions.mcp", then "mcp")
mcp.NewExtension()

// Override specific fields
mcp.NewExtension(
    mcp.WithEnabled(true),
    mcp.WithBasePath("/api/mcp"),
)

// Require config from ConfigManager
mcp.NewExtension(mcp.WithRequireConfig(true))

func NewExtensionWithConfig

func NewExtensionWithConfig(config Config) forge.Extension

NewExtensionWithConfig creates a new MCP extension with a complete config. This is for backward compatibility or when config is fully known at initialization.

func RateLimitMiddleware

func RateLimitMiddleware(config Config, logger forge.Logger, metrics forge.Metrics) forge.PureMiddleware

RateLimitMiddleware creates middleware for rate limiting.

Types

type CallToolRequest

type CallToolRequest struct {
	Name      string         `json:"name"`
	Arguments map[string]any `json:"arguments,omitempty"`
}

CallToolRequest represents a request to call a tool.

type CallToolResponse

type CallToolResponse struct {
	Content []Content `json:"content"`
	IsError bool      `json:"isError,omitempty"`
}

CallToolResponse represents the response from calling a tool.

type Capabilities

type Capabilities struct {
	Tools     *ToolsCapability     `json:"tools,omitempty"`
	Resources *ResourcesCapability `json:"resources,omitempty"`
	Prompts   *PromptsCapability   `json:"prompts,omitempty"`
}

Capabilities represents MCP server capabilities.

type Config

type Config struct {
	// Enabled enables or disables the MCP server
	Enabled bool `yaml:"enabled"`

	// BasePath is the base path for MCP endpoints
	// Default: "/_/mcp"
	BasePath string `yaml:"base_path"`

	// ServerName is the name of the MCP server
	// Default: app name
	ServerName string `yaml:"server_name"`

	// ServerVersion is the version of the MCP server
	// Default: app version
	ServerVersion string `yaml:"server_version"`

	// AutoExposeRoutes automatically exposes routes as MCP tools
	// Default: true
	AutoExposeRoutes bool `yaml:"auto_expose_routes"`

	// ToolPrefix is a prefix to add to all tool names
	// Example: "myapi_" -> "myapi_create_user"
	ToolPrefix string `yaml:"tool_prefix"`

	// ExcludePatterns are route patterns to exclude from MCP
	// Example: []string{"/_/*", "/internal/*"}
	ExcludePatterns []string `yaml:"exclude_patterns"`

	// IncludePatterns are route patterns to explicitly include in MCP
	// If set, only matching routes are exposed
	IncludePatterns []string `yaml:"include_patterns"`

	// MaxToolNameLength is the maximum length for tool names
	// Default: 64
	MaxToolNameLength int `yaml:"max_tool_name_length"`

	// EnableResources enables MCP resources (data access)
	// Default: false
	EnableResources bool `yaml:"enable_resources"`

	// EnablePrompts enables MCP prompts (templates)
	// Default: false
	EnablePrompts bool `yaml:"enable_prompts"`

	// RequireAuth requires authentication for MCP endpoints
	// Default: false
	RequireAuth bool `yaml:"require_auth"`

	// AuthHeader is the header to check for authentication
	// Default: "Authorization"
	AuthHeader string `yaml:"auth_header"`

	// AuthTokens are valid authentication tokens
	// Only used if RequireAuth is true
	AuthTokens []string `yaml:"auth_tokens"`

	// RateLimitPerMinute limits MCP tool calls per minute
	// 0 means unlimited
	// Default: 0
	RateLimitPerMinute int `yaml:"rate_limit_per_minute"`

	// EnableMetrics enables metrics collection for MCP operations
	// Default: true
	EnableMetrics bool `yaml:"enable_metrics"`

	// SchemaCache enables caching of generated JSON schemas
	// Default: true
	SchemaCache bool `yaml:"schema_cache"`

	// RequireConfig determines if config must exist in ConfigManager
	// If true, extension fails to start without config
	// If false, uses defaults when config is missing
	RequireConfig bool `yaml:"-"`
}

Config configures the MCP extension.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns a default MCP configuration.

func (Config) ShouldExpose

func (c Config) ShouldExpose(path string) bool

ShouldExpose determines if a route should be exposed as an MCP tool.

func (Config) Validate

func (c Config) Validate() error

Validate validates the configuration.

type ConfigOption

type ConfigOption func(*Config)

ConfigOption is a functional option for configuring the MCP extension.

func WithAuth

func WithAuth(authHeader string, tokens []string) ConfigOption

WithAuth enables authentication with tokens.

func WithAutoExposeRoutes

func WithAutoExposeRoutes(autoExpose bool) ConfigOption

WithAutoExposeRoutes sets whether to automatically expose routes.

func WithBasePath

func WithBasePath(basePath string) ConfigOption

WithBasePath sets the base path for MCP endpoints.

func WithConfig

func WithConfig(config Config) ConfigOption

WithConfig applies a complete config.

func WithEnabled

func WithEnabled(enabled bool) ConfigOption

WithEnabled sets whether MCP is enabled.

func WithExcludePatterns

func WithExcludePatterns(patterns []string) ConfigOption

WithExcludePatterns sets patterns to exclude from MCP.

func WithIncludePatterns

func WithIncludePatterns(patterns []string) ConfigOption

WithIncludePatterns sets patterns to include in MCP.

func WithPrompts

func WithPrompts(enable bool) ConfigOption

WithPrompts enables MCP prompts.

func WithRateLimit

func WithRateLimit(limit int) ConfigOption

WithRateLimit sets the rate limit per minute.

func WithRequireConfig

func WithRequireConfig(require bool) ConfigOption

WithRequireConfig sets whether config is required from ConfigManager.

func WithResources

func WithResources(enable bool) ConfigOption

WithResources enables MCP resources.

func WithServerInfo

func WithServerInfo(name, version string) ConfigOption

WithServerInfo sets server name and version.

func WithToolPrefix

func WithToolPrefix(prefix string) ConfigOption

WithToolPrefix sets the tool prefix.

type Content

type Content struct {
	Type     string `json:"type"` // "text", "image", "resource"
	Text     string `json:"text,omitempty"`
	Data     string `json:"data,omitempty"`
	MimeType string `json:"mimeType,omitempty"`
}

Content represents a piece of content in MCP.

type Extension

type Extension struct {
	*forge.BaseExtension
	// contains filtered or unexported fields
}

Extension implements forge.Extension for MCP (Model Context Protocol) server. The extension is now a lightweight facade that loads config and registers services.

func (*Extension) Health

func (e *Extension) Health(ctx context.Context) error

Health checks the extension health. Service health is managed by Vessel through MCPService.Health().

func (*Extension) Register

func (e *Extension) Register(app forge.App) error

Register registers the MCP extension with the app. This method loads configuration and registers service constructors.

func (*Extension) Start

func (e *Extension) Start(ctx context.Context) error

Start starts the MCP extension.

func (*Extension) Stop

func (e *Extension) Stop(ctx context.Context) error

Stop marks the extension as stopped. The actual service is stopped by Vessel calling MCPService.Stop().

type GetPromptRequest

type GetPromptRequest struct {
	Name      string         `json:"name"`
	Arguments map[string]any `json:"arguments,omitempty"`
}

GetPromptRequest represents a request to get a prompt.

type GetPromptResponse

type GetPromptResponse struct {
	Description string          `json:"description,omitempty"`
	Messages    []PromptMessage `json:"messages"`
}

GetPromptResponse represents the response from getting a prompt.

type JSONSchema

type JSONSchema struct {
	Type                 string                 `json:"type,omitempty"`
	Properties           map[string]*JSONSchema `json:"properties,omitempty"`
	Items                *JSONSchema            `json:"items,omitempty"`
	Required             []string               `json:"required,omitempty"`
	Description          string                 `json:"description,omitempty"`
	Enum                 []any                  `json:"enum,omitempty"`
	Format               string                 `json:"format,omitempty"`
	Pattern              string                 `json:"pattern,omitempty"`
	MinLength            *int                   `json:"minLength,omitempty"`
	MaxLength            *int                   `json:"maxLength,omitempty"`
	Minimum              *float64               `json:"minimum,omitempty"`
	Maximum              *float64               `json:"maximum,omitempty"`
	AdditionalProperties any                    `json:"additionalProperties,omitempty"`
}

JSONSchema represents a JSON Schema for input/output validation.

type ListPromptsResponse

type ListPromptsResponse struct {
	Prompts []Prompt `json:"prompts"`
}

ListPromptsResponse represents the response for listing prompts.

type ListResourcesResponse

type ListResourcesResponse struct {
	Resources []Resource `json:"resources"`
}

ListResourcesResponse represents the response for listing resources.

type ListToolsResponse

type ListToolsResponse struct {
	Tools []Tool `json:"tools"`
}

ListToolsResponse represents the response for listing tools.

type MCPService

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

MCPService wraps an MCP Server implementation and provides lifecycle management. It implements vessel's di.Service interface so Vessel can manage its lifecycle.

func NewMCPService

func NewMCPService(config Config, logger forge.Logger, metrics forge.Metrics) (*MCPService, error)

NewMCPService creates a new MCP service with the given configuration. This is the constructor that will be registered with the DI container.

func (*MCPService) Health

func (s *MCPService) Health(ctx context.Context) error

Health checks if the MCP service is healthy.

func (*MCPService) Name

func (s *MCPService) Name() string

Name returns the service name for Vessel's lifecycle management.

func (*MCPService) Server

func (s *MCPService) Server() *Server

Server returns the underlying MCP server implementation.

func (*MCPService) Start

func (s *MCPService) Start(ctx context.Context) error

Start starts the MCP service. This is called automatically by Vessel during container.Start().

func (*MCPService) Stop

func (s *MCPService) Stop(ctx context.Context) error

Stop stops the MCP service. This is called automatically by Vessel during container.Stop().

type Prompt

type Prompt struct {
	Name        string           `json:"name"`
	Description string           `json:"description,omitempty"`
	Arguments   []PromptArgument `json:"arguments,omitempty"`
}

Prompt represents an MCP prompt template.

type PromptArgument

type PromptArgument struct {
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
	Required    bool   `json:"required,omitempty"`
}

PromptArgument represents an argument for a prompt.

type PromptGenerator

type PromptGenerator func(ctx context.Context, prompt *Prompt, args map[string]any) ([]PromptMessage, error)

PromptGenerator is a function that generates prompt messages.

type PromptMessage

type PromptMessage struct {
	Role    string    `json:"role"` // "user" or "assistant"
	Content []Content `json:"content"`
}

PromptMessage represents a message in a prompt result.

type PromptsCapability

type PromptsCapability struct {
	ListChanged bool `json:"listChanged,omitempty"`
}

PromptsCapability represents prompts capability.

type RateLimiter

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

RateLimiter tracks request rates.

func NewRateLimiter

func NewRateLimiter(config Config, logger forge.Logger) *RateLimiter

NewRateLimiter creates a new rate limiter.

func (*RateLimiter) Allow

func (rl *RateLimiter) Allow(clientID string) bool

Allow checks if a request is allowed.

func (*RateLimiter) GetInfo

func (rl *RateLimiter) GetInfo(clientID string) *requestInfo

GetInfo returns rate limit info for a client.

func (*RateLimiter) Stop

func (rl *RateLimiter) Stop()

Stop stops the rate limiter cleanup goroutine.

type ReadResourceRequest

type ReadResourceRequest struct {
	URI string `json:"uri"`
}

ReadResourceRequest represents a request to read a resource.

type ReadResourceResponse

type ReadResourceResponse struct {
	Contents []Content `json:"contents"`
}

ReadResourceResponse represents the response from reading a resource.

type Resource

type Resource struct {
	URI         string      `json:"uri"`
	Name        string      `json:"name"`
	Description string      `json:"description,omitempty"`
	MimeType    string      `json:"mimeType,omitempty"`
	Schema      *JSONSchema `json:"schema,omitempty"`
}

Resource represents an MCP resource (data access).

type ResourceContents

type ResourceContents struct {
	URI      string    `json:"uri"`
	Contents []Content `json:"contents"`
}

ResourceContents represents the contents of a resource.

type ResourceReader

type ResourceReader func(ctx context.Context, resource *Resource) (Content, error)

ResourceReader is a function that reads resource content.

type ResourcesCapability

type ResourcesCapability struct {
	Subscribe   bool `json:"subscribe,omitempty"`
	ListChanged bool `json:"listChanged,omitempty"`
}

ResourcesCapability represents resources capability.

type Server

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

Server represents an MCP server that exposes tools, resources, and prompts.

func NewServer

func NewServer(config Config, logger forge.Logger, metrics forge.Metrics) *Server

NewServer creates a new MCP server.

func (*Server) CacheSchema

func (s *Server) CacheSchema(key string, schema *JSONSchema)

CacheSchema caches a generated JSON schema.

func (*Server) Clear

func (s *Server) Clear()

Clear clears all registered tools, resources, and prompts.

func (*Server) ExecuteTool

func (s *Server) ExecuteTool(ctx context.Context, tool *Tool, arguments map[string]any) (string, error)

ExecuteTool executes a tool by calling its underlying route.

func (*Server) GeneratePrompt

func (s *Server) GeneratePrompt(ctx context.Context, prompt *Prompt, args map[string]any) ([]PromptMessage, error)

GeneratePrompt generates prompt messages using registered generator or default.

func (*Server) GenerateToolFromRoute

func (s *Server) GenerateToolFromRoute(route forge.RouteInfo) (*Tool, error)

GenerateToolFromRoute generates an MCP tool from a Forge route.

func (*Server) GetCachedSchema

func (s *Server) GetCachedSchema(key string) (*JSONSchema, bool)

GetCachedSchema retrieves a cached schema.

func (*Server) GetPrompt

func (s *Server) GetPrompt(name string) (*Prompt, error)

GetPrompt retrieves a prompt by name.

func (*Server) GetResource

func (s *Server) GetResource(uri string) (*Resource, error)

GetResource retrieves a resource by URI.

func (*Server) GetServerInfo

func (s *Server) GetServerInfo() ServerInfo

GetServerInfo returns information about the MCP server.

func (*Server) GetTool

func (s *Server) GetTool(name string) (*Tool, error)

GetTool retrieves a tool by name.

func (*Server) ListPrompts

func (s *Server) ListPrompts() []Prompt

ListPrompts returns all registered prompts.

func (*Server) ListResources

func (s *Server) ListResources() []Resource

ListResources returns all registered resources.

func (*Server) ListTools

func (s *Server) ListTools() []Tool

ListTools returns all registered tools.

func (*Server) ReadResource

func (s *Server) ReadResource(ctx context.Context, resource *Resource) (Content, error)

ReadResource reads resource content using registered reader or default.

func (*Server) RegisterPrompt

func (s *Server) RegisterPrompt(prompt *Prompt) error

RegisterPrompt registers a new MCP prompt.

func (*Server) RegisterPromptGenerator

func (s *Server) RegisterPromptGenerator(name string, generator PromptGenerator) error

RegisterPromptGenerator registers a custom generator for a prompt.

func (*Server) RegisterResource

func (s *Server) RegisterResource(resource *Resource) error

RegisterResource registers a new MCP resource.

func (*Server) RegisterResourceReader

func (s *Server) RegisterResourceReader(uri string, reader ResourceReader) error

RegisterResourceReader registers a custom reader for a resource.

func (*Server) RegisterTool

func (s *Server) RegisterTool(tool *Tool) error

RegisterTool registers a new MCP tool.

func (*Server) Stats

func (s *Server) Stats() map[string]any

Stats returns statistics about the MCP server.

type ServerInfo

type ServerInfo struct {
	Name         string       `json:"name"`
	Version      string       `json:"version"`
	Capabilities Capabilities `json:"capabilities"`
}

ServerInfo represents MCP server information.

type Tool

type Tool struct {
	Name        string      `json:"name"`
	Description string      `json:"description"`
	InputSchema *JSONSchema `json:"inputSchema"`
}

Tool represents an MCP tool that can be called by AI assistants.

type ToolCall

type ToolCall struct {
	Name      string         `json:"name"`
	Arguments map[string]any `json:"arguments"`
}

ToolCall represents a request to execute a tool.

type ToolResult

type ToolResult struct {
	Content []Content `json:"content"`
	IsError bool      `json:"isError,omitempty"`
}

ToolResult represents the result of a tool execution.

type ToolsCapability

type ToolsCapability struct {
	ListChanged bool `json:"listChanged,omitempty"`
}

ToolsCapability represents tools capability.

Jump to

Keyboard shortcuts

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