mcp

package
v0.1.8 Latest Latest
Warning

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

Go to latest
Published: Oct 28, 2025 License: MIT Imports: 10 Imported by: 0

README

MCP Extension for Forge v2

The MCP (Model Context Protocol) extension automatically exposes your Forge application's REST API as MCP-compatible tools, resources, and prompts for use with AI assistants like Claude.

Features

  • Automatic Tool Generation: Converts REST routes to MCP tools
  • Tool Execution: Actually executes the underlying HTTP endpoints
  • Input Schema Generation: Generates JSON schemas from route metadata
  • Resources & Prompts: Support for data access and prompt templates
  • Authentication: Token-based authentication for MCP endpoints
  • Rate Limiting: Per-client rate limiting (requests per minute)
  • Custom Handlers: Register custom resource readers and prompt generators
  • Observability: Integrated metrics and logging
  • Pattern Matching: Include/exclude routes with glob patterns

Installation

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

Quick Start

Basic Setup
package main

import (
    "context"
    
    "github.com/xraph/forge"
    "github.com/xraph/forge/extensions/mcp"
)

func main() {
    // Create Forge app
    app := forge.NewApp(forge.AppConfig{
        Name:    "my-api",
        Version: "1.0.0",
    })
    
    // Add some routes
    app.Router().GET("/users/:id", getUserHandler)
    app.Router().POST("/users", createUserHandler)
    
    // Enable MCP extension (auto-exposes routes as tools)
    app.RegisterExtension(mcp.NewExtension(
        mcp.WithEnabled(true),
        mcp.WithAutoExposeRoutes(true),
    ))
    
    // Start the app
    app.Start(context.Background())
    app.Run(context.Background(), ":8080")
}

This automatically creates MCP tools like:

  • get_users_idGET /users/:id
  • create_usersPOST /users
Access MCP Endpoints

The MCP server exposes these HTTP endpoints:

Endpoint Method Description
/_/mcp/info GET Server info and capabilities
/_/mcp/tools GET List available tools
/_/mcp/tools/:name POST Execute a tool
/_/mcp/resources GET List resources (if enabled)
/_/mcp/resources/read POST Read a resource (if enabled)
/_/mcp/prompts GET List prompts (if enabled)
/_/mcp/prompts/:name POST Get a prompt (if enabled)

Configuration

In config.yaml:

extensions:
  mcp:
    enabled: true
    base_path: "/_/mcp"
    auto_expose_routes: true
    tool_prefix: "myapi_"
    exclude_patterns:
      - "/_/*"
      - "/internal/*"
    max_tool_name_length: 64
    enable_resources: true
    enable_prompts: true
    require_auth: false
    rate_limit_per_minute: 100

Then in code:

// Config loaded automatically from ConfigManager
app.RegisterExtension(mcp.NewExtension())
Programmatic Configuration
app.RegisterExtension(mcp.NewExtension(
    mcp.WithEnabled(true),
    mcp.WithBasePath("/_/mcp"),
    mcp.WithAutoExposeRoutes(true),
    mcp.WithToolPrefix("api_"),
    mcp.WithExcludePatterns([]string{"/_/*", "/internal/*"}),
    mcp.WithIncludePatterns([]string{"/api/*"}), // Only expose /api/* routes
    mcp.WithResources(true),
    mcp.WithPrompts(true),
    mcp.WithAuth("X-API-Key", []string{"secret-token"}),
    mcp.WithRateLimit(100), // 100 requests per minute
))
Configuration Options
Option Type Default Description
Enabled bool true Enable/disable MCP server
BasePath string "/_/mcp" Base path for MCP endpoints
AutoExposeRoutes bool true Auto-generate tools from routes
ToolPrefix string "" Prefix for tool names
ExcludePatterns []string [] Patterns to exclude from tools
IncludePatterns []string [] Only expose matching patterns
MaxToolNameLength int 64 Max length for tool names
EnableResources bool false Enable resources endpoint
EnablePrompts bool false Enable prompts endpoint
RequireAuth bool false Require authentication
AuthHeader string "Authorization" Auth header name
AuthTokens []string [] Valid auth tokens
RateLimitPerMinute int 0 Rate limit (0 = unlimited)
EnableMetrics bool true Enable metrics collection
SchemaCache bool true Cache generated schemas

Usage Examples

Tool Execution

Call a tool via HTTP:

curl -X POST http://localhost:8080/_/mcp/tools/get_users_id \
  -H "Content-Type: application/json" \
  -d '{
    "name": "get_users_id",
    "arguments": {
      "id": "123",
      "query": {
        "include": "profile"
      }
    }
  }'

Response:

{
  "content": [
    {
      "type": "text",
      "text": "Tool executed: GET /users/123?include=profile"
    }
  ],
  "isError": false
}
Custom Resource Readers
// Register a custom resource reader
ext := app.Extensions().Get("mcp").(*mcp.Extension)
server := ext.Server()

// Register resource
server.RegisterResource(&mcp.Resource{
    URI:         "file://config/settings.json",
    Name:        "App Settings",
    Description: "Application configuration",
    MimeType:    "application/json",
})

// Register custom reader
server.RegisterResourceReader("file://config/settings.json", 
    func(ctx context.Context, resource *mcp.Resource) (mcp.Content, error) {
        data, err := os.ReadFile("config/settings.json")
        if err != nil {
            return mcp.Content{}, err
        }
        
        return mcp.Content{
            Type: "text",
            Text: string(data),
            MimeType: "application/json",
        }, nil
    })
Custom Prompt Generators
// Register a prompt
server.RegisterPrompt(&mcp.Prompt{
    Name:        "generate-user-query",
    Description: "Generates a SQL query to find users",
    Arguments: []mcp.PromptArgument{
        {Name: "filter", Description: "Filter criteria", Required: true},
        {Name: "limit", Description: "Max results", Required: false},
    },
})

// Register custom generator
server.RegisterPromptGenerator("generate-user-query",
    func(ctx context.Context, prompt *mcp.Prompt, args map[string]interface{}) ([]mcp.PromptMessage, error) {
        filter := args["filter"].(string)
        limit := 10
        if l, ok := args["limit"].(int); ok {
            limit = l
        }
        
        query := fmt.Sprintf("SELECT * FROM users WHERE %s LIMIT %d", filter, limit)
        
        return []mcp.PromptMessage{
            {
                Role: "assistant",
                Content: []mcp.Content{
                    {Type: "text", Text: query},
                },
            },
        }, nil
    })

Security

Authentication

Enable token-based authentication:

mcp.NewExtension(
    mcp.WithAuth("X-API-Key", []string{
        "prod-token-abc123",
        "dev-token-xyz789",
    }),
)

Clients must include the header:

curl -H "X-API-Key: prod-token-abc123" \
  http://localhost:8080/_/mcp/tools

Or Bearer token format:

curl -H "Authorization: Bearer prod-token-abc123" \
  http://localhost:8080/_/mcp/tools
Rate Limiting

Limit requests per client per minute:

mcp.NewExtension(
    mcp.WithRateLimit(100), // 100 requests/minute
)

Rate limit headers in response:

X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1234567890

When exceeded, returns 429 Too Many Requests with Retry-After header.

Pattern Matching

Exclude Patterns

Exclude internal/system routes:

mcp.NewExtension(
    mcp.WithExcludePatterns([]string{
        "/_/*",        // Exclude /_/health, /_/metrics, etc.
        "/internal/*", // Exclude /internal/admin, etc.
        "/debug/*",    // Exclude debug routes
    }),
)
Include Patterns

Only expose specific API routes:

mcp.NewExtension(
    mcp.WithIncludePatterns([]string{
        "/api/*",      // Only expose /api/* routes
        "/public/*",   // And /public/* routes
    }),
)

Note: If IncludePatterns is set, only matching routes are exposed.

Tool Naming

Tools are named based on HTTP method and path:

Route Method Tool Name
/users GET get_users
/users POST create_users
/users/:id GET get_users_id
/users/:id PUT update_users_id
/users/:id DELETE delete_users_id
/users/:id PATCH patch_users_id
/api/v1/posts GET get_api_v1_posts

With ToolPrefix:

mcp.WithToolPrefix("myapi_")
// Results in: myapi_get_users, myapi_create_users, etc.

Input Schemas

The extension automatically generates JSON schemas for tool inputs:

{
  "type": "object",
  "properties": {
    "id": {
      "type": "string",
      "description": "Path parameter: id"
    },
    "body": {
      "type": "object",
      "description": "Request body"
    },
    "query": {
      "type": "object",
      "description": "Query parameters (optional)"
    }
  },
  "required": ["id"]
}

Observability

Metrics

The extension automatically records:

  • mcp_tools_total - Total number of registered tools (gauge)
  • mcp_resources_total - Total resources (gauge)
  • mcp_prompts_total - Total prompts (gauge)
  • mcp_tool_calls_total{status} - Tool calls by status (counter)
  • mcp_rate_limit_exceeded_total - Rate limit violations (counter)
Logging

All MCP operations are logged with structured fields:

logger.Debug("mcp: tool registered", forge.F("tool", toolName))
logger.Warn("mcp: rate limit exceeded", forge.F("client", clientID))
logger.Error("mcp: tool execution failed", forge.F("tool", toolName), forge.F("error", err))

Advanced Usage

Manual Tool Registration

Register tools manually without auto-exposure:

server := ext.Server()

server.RegisterTool(&mcp.Tool{
    Name:        "complex-operation",
    Description: "Performs a complex multi-step operation",
    InputSchema: &mcp.JSONSchema{
        Type: "object",
        Properties: map[string]*mcp.JSONSchema{
            "step1": {Type: "string", Description: "First step"},
            "step2": {Type: "integer", Description: "Second step"},
        },
        Required: []string{"step1", "step2"},
    },
})
Accessing from AI

Use with Claude Desktop or other MCP-compatible clients:

  1. Configure Claude Desktop (claude_desktop_config.json):
{
  "mcpServers": {
    "my-api": {
      "url": "http://localhost:8080/_/mcp",
      "headers": {
        "X-API-Key": "your-token-here"
      }
    }
  }
}
  1. Claude can now call your API via natural language:
    • "Get user with ID 123"
    • "Create a new user with name John"
    • "List all posts"

Testing

func TestMCPExtension(t *testing.T) {
    app := forge.NewApp(forge.AppConfig{
        Name: "test-app",
        Extensions: []forge.Extension{
            mcp.NewExtension(mcp.WithEnabled(true)),
        },
    })
    
    // Add test routes
    app.Router().GET("/test", func(ctx forge.Context) error {
        return ctx.JSON(200, map[string]string{"status": "ok"})
    })
    
    // Start app
    app.Start(context.Background())
    defer app.Stop(context.Background())
    
    // Test MCP endpoints
    req := httptest.NewRequest("GET", "/_/mcp/tools", nil)
    rec := httptest.NewRecorder()
    app.Router().ServeHTTP(rec, req)
    
    assert.Equal(t, 200, rec.Code)
}

Architecture

┌─────────────────────────────────────────────┐
│           Forge Application                 │
│  ┌──────────────────────────────────────┐  │
│  │     Router (REST API)                │  │
│  │  GET /users/:id                      │  │
│  │  POST /users                         │  │
│  │  PUT /users/:id                      │  │
│  └──────────────────────────────────────┘  │
│                    │                        │
│                    ▼                        │
│  ┌──────────────────────────────────────┐  │
│  │     MCP Extension                    │  │
│  │  • Auto-generate tools               │  │
│  │  • Execute via HTTP                  │  │
│  │  • Auth & Rate Limiting              │  │
│  └──────────────────────────────────────┘  │
│                    │                        │
│                    ▼                        │
│  ┌──────────────────────────────────────┐  │
│  │     MCP Server Endpoints             │  │
│  │  /_/mcp/info                         │  │
│  │  /_/mcp/tools                        │  │
│  │  /_/mcp/tools/:name (execute)        │  │
│  └──────────────────────────────────────┘  │
└─────────────────────────────────────────────┘
                    │
                    ▼
        ┌───────────────────────┐
        │   AI Assistant        │
        │   (Claude, etc.)      │
        └───────────────────────┘

Best Practices

  1. Security First: Always enable authentication in production
  2. Rate Limiting: Set appropriate limits to prevent abuse
  3. Pattern Matching: Exclude internal/debug routes
  4. Tool Naming: Use consistent prefixes for your API
  5. Custom Handlers: Register custom readers/generators for complex operations
  6. Monitoring: Track metrics to understand usage patterns
  7. Documentation: Add summaries to routes for better tool descriptions

License

MIT

Contributing

Contributions welcome! Please submit PRs to the main Forge repository.

Support

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AuthMiddleware

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

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

RateLimitMiddleware creates middleware for rate limiting

Types

type CallToolRequest

type CallToolRequest struct {
	Name      string                 `json:"name"`
	Arguments map[string]interface{} `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

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

	// ServerName is the name of the MCP server
	// Default: app name
	ServerName string

	// ServerVersion is the version of the MCP server
	// Default: app version
	ServerVersion string

	// AutoExposeRoutes automatically exposes routes as MCP tools
	// Default: true
	AutoExposeRoutes bool

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

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

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

	// MaxToolNameLength is the maximum length for tool names
	// Default: 64
	MaxToolNameLength int

	// EnableResources enables MCP resources (data access)
	// Default: false
	EnableResources bool

	// EnablePrompts enables MCP prompts (templates)
	// Default: false
	EnablePrompts bool

	// RequireAuth requires authentication for MCP endpoints
	// Default: false
	RequireAuth bool

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

	// AuthTokens are valid authentication tokens
	// Only used if RequireAuth is true
	AuthTokens []string

	// RateLimitPerMinute limits MCP tool calls per minute
	// 0 means unlimited
	// Default: 0
	RateLimitPerMinute int

	// EnableMetrics enables metrics collection for MCP operations
	// Default: true
	EnableMetrics bool

	// SchemaCache enables caching of generated JSON schemas
	// Default: true
	SchemaCache bool

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

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

func (*Extension) Health

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

Health checks if the MCP extension is healthy

func (*Extension) Register

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

Register registers the MCP extension with the app

func (*Extension) Server

func (e *Extension) Server() *Server

Server returns the MCP server instance

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 stops the MCP extension

type GetPromptRequest

type GetPromptRequest struct {
	Name      string                 `json:"name"`
	Arguments map[string]interface{} `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                 []interface{}          `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 interface{}            `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 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]interface{}) ([]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]interface{}) (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]interface{}) ([]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]interface{}

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]interface{} `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