Skip to content

ai.mcp #

Model Context Protocol (MCP) Implementation

This module provides a V language implementation of the Model Context Protocol (MCP) specification. MCP is a protocol designed to standardize communication between AI models and their context providers.

Overview

The MCP module serves as a core library for building MCP-compliant servers in V. Its main purpose is to provide all the boilerplate MCP functionality, so implementers only need to define and register their specific handlers. The module handles the Standard Input/Output (stdio) transport as described in the MCP transport specification, enabling standardized communication between AI models and their context providers.

The module implements all the required MCP protocol methods (resources/list, tools/list, prompts/list, etc.) and manages the underlying JSON-RPC communication, allowing developers to focus solely on implementing their specific tools and handlers. The module itself is not a standalone server but rather a framework that can be used to build different MCP server implementations. The subdirectories within this module (such as baobab and developer) contain specific implementations of MCP servers that utilize this core framework.

to test

curl -fsSL https://bun.sh/install | bash
  source /root/.bashrc

Key Components

  • Server: The main MCP server struct that handles JSON-RPC requests and responses
  • Backend Interface: Abstraction for different backend implementations (memory-based by default)
  • Model Configuration: Structures representing client and server capabilities according to the MCP specification
  • Protocol Handlers: Implementation of MCP protocol handlers for resources, prompts, tools, and initialization
  • Factory: Functions to create and configure an MCP server with custom backends and handlers

Features

  • Complete implementation of the MCP protocol version 2024-11-05
  • Handles all boilerplate protocol methods (resources/list, tools/list, prompts/list, etc.)
  • JSON-RPC based communication layer with automatic request/response handling
  • Support for client-server capability negotiation
  • Pluggable backend system for different storage and processing needs
  • Generic type conversion utilities for MCP tool content
  • Comprehensive error handling
  • Logging capabilities
  • Minimal implementation requirements for server developers

Usage

To create a new MCP server using the core module:

import freeflowuniverse.herolib.ai.mcp
import freeflowuniverse.herolib.schemas.jsonrpc

// Create a backend (memory-based or custom implementation)
backend := mcp.MemoryBackend{
    tools: {
        'my_tool': my_tool_definition
    }
    tool_handlers: {
        'my_tool': my_tool_handler
    }
}

// Create and configure the server
mut server := mcp.new_server(backend, mcp.ServerParams{
    config: mcp.ServerConfiguration{
        server_info: mcp.ServerInfo{
            name: 'my_mcp_server'
            version: '1.0.0'
        }
    }
})!

// Start the server
server.start()!

fn array_to_mcp_tool_contents #

fn array_to_mcp_tool_contents[U](array []U) []ToolContent

fn error_tool_call_result #

fn error_tool_call_result(err IError) ToolCallResult

fn new_server #

fn new_server(backend Backend, params ServerParams) !&Server

new_server creates a new MCP server

fn resource_not_found #

fn resource_not_found(uri string) jsonrpc.RPCError

resource_not_found indicates that the requested resource doesn't exist. This error is returned when the resource specified in the request is not found. Error code: -32002

fn result_to_mcp_tool_content #

fn result_to_mcp_tool_content[T](result T) ToolContent

fn result_to_mcp_tool_contents #

fn result_to_mcp_tool_contents[T](result T) []ToolContent

type PromptHandler #

type PromptHandler = fn (arguments []string) ![]PromptMessage

type SamplingHandler #

type SamplingHandler = fn (params map[string]json2.Any) !SamplingCreateMessageResult

type ToolHandler #

type ToolHandler = fn (arguments map[string]json2.Any) !ToolCallResult

struct ClientCapabilities #

struct ClientCapabilities {
pub:
	roots        RootsCapability        // Ability to provide filesystem roots
	sampling     SamplingCapability     // Support for LLM sampling requests
	experimental ExperimentalCapability // Describes support for non-standard experimental features
}

ClientCapabilities represents the client capabilities

struct ClientConfiguration #

struct ClientConfiguration {
pub:
	protocol_version string @[json: 'protocolVersion']
	capabilities     ClientCapabilities
	client_info      ClientInfo @[json: 'clientInfo']
}

ClientConfiguration represents the parameters for the initialize request

struct ClientInfo #

struct ClientInfo {
pub:
	name    string
	version string
}

ClientInfo represents the client information

struct ExperimentalCapability #

struct ExperimentalCapability {}

ExperimentalCapability represents the experimental capability

struct LoggingCapability #

struct LoggingCapability {
}

LoggingCapability represents the logging capability

struct MemoryBackend #

struct MemoryBackend {
pub mut:
	// Resource related fields
	resources          map[string]Resource
	subscriptions      []string // list of subscribed resource uri's
	resource_contents  map[string][]ResourceContent
	resource_templates map[string]ResourceTemplate

	// Prompt related fields
	prompts         map[string]Prompt
	prompt_messages map[string][]PromptMessage
	prompt_handlers map[string]PromptHandler

	// Tool related fields
	tools         map[string]Tool
	tool_handlers map[string]ToolHandler

	// Sampling related fields
	sampling_handler SamplingHandler
}

fn (MemoryBackend) register_sampling_handler #

fn (mut b MemoryBackend) register_sampling_handler(handler SamplingHandler)

register_sampling_handler registers a handler for sampling requests

struct Message #

struct Message {
pub:
	role    string
	content MessageContent
}

struct MessageContent #

struct MessageContent {
pub:
	typ      string @[json: 'type']
	text     string
	data     string
	mimetype string @[json: 'mimeType']
}

Sampling related structs

struct ModelHint #

struct ModelHint {
pub:
	name string
}

struct ModelPreferences #

struct ModelPreferences {
pub:
	hints                 []ModelHint
	cost_priority         f32 @[json: 'costPriority']
	speed_priority        f32 @[json: 'speedPriority']
	intelligence_priority f32 @[json: 'intelligencePriority']
}

struct Prompt #

struct Prompt {
pub:
	name        string
	description string
	arguments   []PromptArgument
}

Prompt related structs

struct PromptArgument #

struct PromptArgument {
pub:
	name        string
	description string
	required    bool
}

struct PromptContent #

struct PromptContent {
pub:
	typ      string @[json: 'type']
	text     string
	data     string
	mimetype string @[json: 'mimeType']
	resource ResourceContent
}

struct PromptGetParams #

struct PromptGetParams {
pub:
	name      string
	arguments map[string]string
}

Prompt Get Handler

struct PromptGetResult #

struct PromptGetResult {
pub:
	description string
	messages    []PromptMessage
}

struct PromptListParams #

struct PromptListParams {
pub:
	cursor string
}

Prompt List Handler

struct PromptListResult #

struct PromptListResult {
pub:
	prompts     []Prompt
	next_cursor string @[json: 'nextCursor']
}

struct PromptMessage #

struct PromptMessage {
pub:
	role    string
	content PromptContent
}

struct PromptsCapability #

struct PromptsCapability {
pub:
	list_changed bool = true @[json: 'listChanged']
}

PromptsCapability represents the prompts capability

struct Resource #

struct Resource {
pub:
	uri         string
	name        string
	description string
	mimetype    string @[json: 'mimeType']
}

struct ResourceContent #

struct ResourceContent {
pub:
	uri      string
	mimetype string @[json: 'mimeType']
	text     string
	blob     string // Base64-encoded binary data
}

struct ResourceListParams #

struct ResourceListParams {
pub:
	cursor string
}

Resource List Handler

struct ResourceListResult #

struct ResourceListResult {
pub:
	resources   []Resource
	next_cursor string @[json: 'nextCursor']
}

struct ResourceReadParams #

struct ResourceReadParams {
pub:
	uri string
}

Resource Read Handler

struct ResourceReadResult #

struct ResourceReadResult {
pub:
	contents []ResourceContent
}

struct ResourceSubscribeParams #

struct ResourceSubscribeParams {
pub:
	uri string
}

Resource Subscription Handler

struct ResourceSubscribeResult #

struct ResourceSubscribeResult {
pub:
	subscribed bool
}

struct ResourceTemplate #

struct ResourceTemplate {
pub:
	uri_template string @[json: 'uriTemplate']
	name         string
	description  string
	mimetype     string @[json: 'mimeType']
}

struct ResourceTemplatesListResult #

struct ResourceTemplatesListResult {
pub:
	resource_templates []ResourceTemplate @[json: 'resourceTemplates']
}

Resource Templates Handler

struct ResourceUpdatedParams #

struct ResourceUpdatedParams {
pub:
	uri string
}

struct ResourcesCapability #

struct ResourcesCapability {
pub:
	subscribe    bool = true @[json: 'subscribe']
	list_changed bool = true @[json: 'listChanged']
}

ResourcesCapability represents the resources capability

struct RootsCapability #

struct RootsCapability {
pub:
	list_changed bool @[json: 'listChanged']
}

RootsCapability represents the roots capability

struct SamplingCapability #

struct SamplingCapability {}

SamplingCapability represents the sampling capability

struct SamplingCreateMessageParams #

struct SamplingCreateMessageParams {
pub:
	messages          []Message
	model_preferences ModelPreferences @[json: 'modelPreferences']
	system_prompt     string           @[json: 'systemPrompt']
	include_context   string           @[json: 'includeContext']
	temperature       f32
	max_tokens        int      @[json: 'maxTokens']
	stop_sequences    []string @[json: 'stopSequences']
	metadata          map[string]json2.Any
}

struct SamplingCreateMessageResult #

struct SamplingCreateMessageResult {
pub:
	model       string
	stop_reason string @[json: 'stopReason']
	role        string
	content     MessageContent
}

struct Server #

@[heap]
struct Server {
	ServerConfiguration
pub mut:
	client_config ClientConfiguration
	handler       jsonrpc.Handler
	backend       Backend
}

Server is the main MCP server struct

fn (Server) send #

fn (mut s Server) send(response string)

send sends a response to the client

fn (Server) send_prompts_list_changed_notification #

fn (mut s Server) send_prompts_list_changed_notification() !

send_prompts_list_changed_notification sends a notification when the list of prompts changes

fn (Server) send_resource_updated_notification #

fn (mut s Server) send_resource_updated_notification(uri string) !

send_resource_updated_notification sends a notification when a subscribed resource is updated

fn (Server) send_resources_list_changed_notification #

fn (mut s Server) send_resources_list_changed_notification() !

send_resources_list_changed_notification sends a notification when the list of resources changes

fn (Server) send_tools_list_changed_notification #

fn (mut s Server) send_tools_list_changed_notification() !

send_tools_list_changed_notification sends a notification when the list of tools changes

fn (Server) start #

fn (mut s Server) start() !

start starts the MCP server

struct ServerCapabilities #

struct ServerCapabilities {
pub:
	logging   LoggingCapability
	prompts   PromptsCapability
	resources ResourcesCapability
	tools     ToolsCapability
}

ServerCapabilities represents the server capabilities

struct ServerConfiguration #

struct ServerConfiguration {
pub:
	protocol_version string = '2024-11-05' @[json: 'protocolVersion']
	capabilities     ServerCapabilities
	server_info      ServerInfo @[json: 'serverInfo']
}

ServerConfiguration represents the server configuration

struct ServerInfo #

struct ServerInfo {
pub:
	name    string = 'HeroLibMCPServer'
	version string = '1.0.0'
}

ServerInfo represents the server information

struct ServerParams #

@[params]
struct ServerParams {
pub:
	handlers map[string]jsonrpc.ProcedureHandler
	config   ServerConfiguration
}

struct Tool #

struct Tool {
pub:
	name         string
	description  string
	input_schema jsonschema.Schema @[json: 'inputSchema']
}

Tool related structs

struct ToolCallParams #

struct ToolCallParams {
pub:
	name      string
	arguments map[string]json2.Any
	meta      map[string]json2.Any @[json: '_meta']
}

Tool Call Handler

struct ToolCallResult #

struct ToolCallResult {
pub:
	is_error bool @[json: 'isError']
	content  []ToolContent
}

struct ToolContent #

struct ToolContent {
pub:
	typ        string @[json: 'type']
	text       string
	number     int
	boolean    bool
	properties map[string]ToolContent
	items      []ToolContent
}

struct ToolItems #

struct ToolItems {
pub:
	typ        string @[json: 'type']
	enum       []string
	properties map[string]ToolProperty
}

struct ToolListParams #

struct ToolListParams {
pub:
	cursor string
}

Tool List Handler

struct ToolListResult #

struct ToolListResult {
pub:
	tools       []Tool
	next_cursor string @[json: 'nextCursor']
}

struct ToolProperty #

struct ToolProperty {
pub:
	typ   string @[json: 'type']
	items ToolItems
	enum  []string
}

struct ToolsCapability #

struct ToolsCapability {
pub:
	list_changed bool = true @[json: 'listChanged']
}

ToolsCapability represents the tools capability