mcp #
mcp
mcp is a Model Context Protocol module for V.
It provides:
- typed JSON-RPC request, notification, response, and initialize payload helpers
- a synchronous
Clientthat performs the MCP initialize handshake automatically - a server-side
Serverwith tool, resource, resource template, and prompt registration - streamable HTTP and stdio transports behind a common transport interface
- queues for server notifications and server-initiated requests
- buffered while waiting for a response
HTTP example
import mcp
fn main() {
mut client := mcp.connect('http://localhost:8000/mcp')!
init := client.initialize()!
println(init.server_info.name)
client.close()
}
Stdio example
import mcp
fn main() {
mut client := mcp.connect_stdio('my-mcp-server', ['--stdio'], mcp.ClientConfig{})!
client.notify('notifications/cancelled', {
'requestId': 1
})!
client.close()
}
Server example
import mcp
fn main() {
mut server := mcp.new_server(
name: 'my-v-mcp-server'
version: '1.0.0'
)
server.add_tool(mcp.Tool{
name: 'say_hello'
description: 'Greets a user by name'
}, fn (_ mcp.Context, _ string) !mcp.ToolResult {
return mcp.tool_text_result('Hello, user!')
})!
server.serve_stdio()!
}
Notes
Client.requestauto-initializes when needed.Client.take_notificationsandClient.take_requestsdrain queued server messages.- The HTTP transport supports JSON responses and
text/event-streamPOST responses. Server.serve_httpuses a single MCP endpoint, returns JSON by default, and will return SSE for POST requests that accept onlytext/event-stream.
Constants #
const jsonrpc_version = '2.0'
const protocol_version = '2025-11-25'
const parse_error = ResponseError{
code: -32700
message: 'Invalid JSON.'
}
const invalid_request = ResponseError{
code: -32600
message: 'Invalid request.'
}
const method_not_found = ResponseError{
code: -32601
message: 'Method not found.'
}
const invalid_params = ResponseError{
code: -32602
message: 'Invalid params.'
}
const internal_error = ResponseError{
code: -32603
message: 'Internal error.'
}
const server_not_initialized = ResponseError{
code: -32002
message: 'Server not initialized.'
}
const null = Null{}
const empty = Empty{}
const empty_object = EmptyObject{}
fn connect #
fn connect(url string) !Client
connect creates an MCP client for a streamable HTTP endpoint.
fn connect_http #
fn connect_http(url string, config ClientConfig) !Client
connect_http creates an MCP client for a streamable HTTP endpoint.
fn connect_stdio #
fn connect_stdio(command string, args []string, config ClientConfig) !Client
connect_stdio creates an MCP client that talks to a local stdio server process.
fn decode_notification #
fn decode_notification(raw string) !Notification
decode_notification decodes a JSON payload into an MCP notification.
fn decode_request #
fn decode_request(raw string) !Request
decode_request decodes a JSON payload into an MCP request.
fn decode_response #
fn decode_response(raw string) !Response
decode_response decodes a JSON payload into an MCP response.
fn new_client #
fn new_client(transport Transport, config ClientConfig) Client
new_client constructs an MCP client on top of a custom transport.
fn new_notification #
fn new_notification[P](method string, params P) Notification
new_notification constructs an MCP notification with a typed params payload.
fn new_request #
fn new_request[I, P](id I, method string, params P) Request
new_request constructs an MCP request with a typed id and params payload.
fn new_response #
fn new_response[I, R](id I, result R, err ResponseError) Response
new_response constructs an MCP response with a typed id and result payload.
fn new_server #
fn new_server(config ServerConfig) Server
new_server constructs a new MCP server.
fn prompt_text_message #
fn prompt_text_message(role string, text string) PromptMessage
prompt_text_message creates a prompt message with text content.
fn text_content #
fn text_content(text string) string
text_content creates a raw MCP text content item.
fn tool_text_result #
fn tool_text_result(text string) ToolResult
tool_text_result wraps plain text in an MCP tool result.
fn SessionTransport.from #
fn SessionTransport.from[W](input W) !SessionTransport
interface Transport #
interface Transport {
mut:
send(message string) !
receive() !string
close()
}
Transport is the boundary between MCP messages and the wire format.
type PromptHandler #
type PromptHandler = fn (ctx Context, arguments string) !GetPromptResult
PromptHandler handles prompts/get for a registered prompt.
type ResourceHandler #
type ResourceHandler = fn (ctx Context, uri string) !ReadResourceResult
ResourceHandler handles resources/read for a registered resource URI.
type ToolHandler #
type ToolHandler = fn (ctx Context, arguments string) !ToolResult
ToolHandler handles tools/call for a registered tool.
enum SessionTransport #
enum SessionTransport {
stdio
http
}
SessionTransport identifies how an MCP session is connected.
struct Client #
struct Client {
mut:
transport Transport
config ClientConfig
next_id int = 1
initialized bool
init_result InitializeResult
pending_responses map[string]Response
notifications []Notification
server_requests []Request
}
fn (Client) initialize #
fn (mut c Client) initialize() !InitializeResult
initialize starts the MCP initialization handshake using the client's config.
fn (Client) initialize_with #
fn (mut c Client) initialize_with[X](capabilities X, client_info Implementation) !InitializeResult
initialize_with starts the MCP initialization handshake using typed capabilities.
fn (Client) send_request #
fn (mut c Client) send_request(request Request) !Response
send_request sends a typed request and waits for its response.
fn (Client) request_message #
fn (mut c Client) request_message[P](method string, params P) !Response
request_message sends a method call and returns the raw MCP response.
fn (Client) request #
fn (mut c Client) request[P, R](method string, params P) !R
request sends a method call and decodes its result into Result.
fn (Client) send_notification #
fn (mut c Client) send_notification(notification Notification) !
send_notification sends a typed notification message.
fn (Client) notify #
fn (mut c Client) notify[P](method string, params P) !
notify sends a method notification with a typed params payload.
fn (Client) take_notifications #
fn (mut c Client) take_notifications() []Notification
take_notifications drains notifications queued while waiting for responses.
fn (Client) take_requests #
fn (mut c Client) take_requests() []Request
take_requests drains server initiated requests queued while waiting for responses.
fn (Client) close #
fn (mut c Client) close()
close releases the underlying transport.
struct ClientConfig #
struct ClientConfig {
pub mut:
protocol_version string = protocol_version
client_info Implementation = Implementation{
name: default_client_name
version: default_client_version
}
capabilities string = '{}'
headers map[string]string
}
struct Context #
struct Context {
pub:
session_id string @[json: sessionId]
request_id string @[json: requestId]
method string
transport SessionTransport
protocol_version string @[json: protocolVersion]
client_info Implementation @[json: clientInfo]
client_capabilities string @[json: clientCapabilities; raw]
}
Context provides request-scoped server metadata to handlers.
struct Empty #
struct Empty {}
Empty omits a JSON-RPC field when used with MCP helpers.
fn (Empty) str #
fn (e Empty) str() string
str returns the empty string.
struct EmptyObject #
struct EmptyObject {}
EmptyObject encodes to an empty JSON object.
fn (EmptyObject) str #
fn (e EmptyObject) str() string
str returns the JSON empty object literal.
struct GetPromptResult #
struct GetPromptResult {
pub:
description string @[omitempty]
messages []PromptMessage
}
GetPromptResult is returned by prompts/get.
struct Implementation #
struct Implementation {
pub:
name string
version string
}
Implementation identifies an MCP client or server implementation.
struct InitializeParams #
struct InitializeParams {
pub:
protocol_version string @[json: protocolVersion]
capabilities string @[raw]
client_info Implementation @[json: clientInfo]
}
InitializeParams is the typed payload for the initialize request.
struct InitializeResult #
struct InitializeResult {
pub:
protocol_version string @[json: protocolVersion]
capabilities string @[raw]
server_info Implementation @[json: serverInfo]
instructions string
}
InitializeResult is the typed result returned by an MCP server after initialization.
struct Notification #
struct Notification {
pub:
jsonrpc string = jsonrpc_version
method string
params string @[omitempty; raw]
}
Notification is a JSON-RPC notification encoded for MCP.
fn (Notification) encode #
fn (notification Notification) encode() string
encode serializes the notification to JSON.
fn (Notification) decode_params #
fn (notification Notification) decode_params[T]() !T
decode_params decodes the raw notification params into T.
struct Null #
struct Null {}
Null represents the JSON null literal.
fn (Null) str #
fn (n Null) str() string
str returns the JSON null literal.
struct Prompt #
struct Prompt {
pub:
name string
title string @[omitempty]
description string @[omitempty]
arguments []PromptArgument
}
Prompt describes an MCP prompt exposed by the server.
struct PromptArgument #
struct PromptArgument {
pub:
name string
description string @[omitempty]
required bool
}
PromptArgument describes one prompt argument.
struct PromptMessage #
struct PromptMessage {
pub:
role string
content string @[raw]
}
PromptMessage is one message returned by prompts/get.
struct ReadResourceResult #
struct ReadResourceResult {
pub:
contents []ResourceContents
}
ReadResourceResult is returned by resources/read.
struct Request #
struct Request {
pub:
jsonrpc string = jsonrpc_version
id string @[raw]
method string
params string @[omitempty; raw]
}
Request is a JSON-RPC request message encoded for MCP.
fn (Request) encode #
fn (req Request) encode() string
encode serializes the request to JSON.
fn (Request) decode_params #
fn (req Request) decode_params[T]() !T
decode_params decodes the raw request params into T.
struct Resource #
struct Resource {
pub:
uri string
name string
title string @[omitempty]
description string @[omitempty]
mime_type string @[json: mimeType; omitempty]
}
Resource describes a concrete MCP resource exposed by the server.
struct ResourceContents #
struct ResourceContents {
pub:
uri string
mime_type string @[json: mimeType; omitempty]
text string @[omitempty]
blob string @[omitempty]
}
ResourceContents contains the result of resources/read.
struct ResourceTemplate #
struct ResourceTemplate {
pub:
uri_template string @[json: uriTemplate]
name string
title string @[omitempty]
description string @[omitempty]
mime_type string @[json: mimeType; omitempty]
}
ResourceTemplate describes a parameterized MCP resource URI template.
struct Response #
struct Response {
pub:
jsonrpc string = jsonrpc_version
id string @[raw]
result string @[raw]
error ResponseError
}
Response is a JSON-RPC response message encoded for MCP.
fn (Response) encode #
fn (resp Response) encode() string
encode serializes the response to JSON.
fn (Response) decode_result #
fn (resp Response) decode_result[T]() !T
decode_result decodes the response result into T.
struct ResponseError #
struct ResponseError {
pub:
code int
message string
data string @[raw]
}
ResponseError is the JSON-RPC error payload used by MCP responses.
fn (ResponseError) code #
fn (err ResponseError) code() int
code returns the JSON-RPC error code.
fn (ResponseError) msg #
fn (err ResponseError) msg() string
msg returns the JSON-RPC error message.
fn (ResponseError) err #
fn (err ResponseError) err() IError
err casts the response error to IError.
struct Server #
struct Server {
mut:
server_info Implementation
protocol_version string
capabilities_override string
instructions string
http_path string
http_server &http.Server = unsafe { nil }
tools map[string]RegisteredTool
tool_names []string
resources map[string]RegisteredResource
resource_uris []string
resource_templates map[string]ResourceTemplate
resource_template_ids []string
prompts map[string]RegisteredPrompt
prompt_names []string
state shared ServerState
}
Server handles MCP protocol requests for stdio and HTTP transports.
fn (Server) add_tool #
fn (mut s Server) add_tool(tool Tool, handler ToolHandler) !
add_tool registers a tool and its handler.
fn (Server) add_resource #
fn (mut s Server) add_resource(resource Resource, handler ResourceHandler) !
add_resource registers a concrete resource and its read handler.
fn (Server) add_resource_template #
fn (mut s Server) add_resource_template(template ResourceTemplate) !
add_resource_template registers a resource template exposed by resources/templates/list.
fn (Server) add_prompt #
fn (mut s Server) add_prompt(prompt Prompt, handler PromptHandler) !
add_prompt registers a prompt and its handler.
fn (Server) serve_stdio #
fn (mut s Server) serve_stdio() !
serve_stdio starts serving MCP messages over stdio using Content-Length framing.
fn (Server) serve_http #
fn (mut s Server) serve_http(addr string) !
serve_http starts serving MCP over a single HTTP endpoint.
fn (Server) close #
fn (mut s Server) close()
close stops the HTTP server if it is running.
fn (Server) wait_till_running #
fn (mut s Server) wait_till_running(params http.WaitTillRunningParams) !int
wait_till_running waits until the HTTP server transitions to the running state.
struct ServerConfig #
struct ServerConfig {
pub:
name string
version string
protocol_version string = protocol_version
capabilities string
instructions string
http_path string = default_http_path
}
ServerConfig configures an MCP server instance.
struct Tool #
struct Tool {
pub:
name string
title string @[omitempty]
description string @[omitempty]
input_schema string = default_tool_input_schema @[json: inputSchema; raw]
output_schema string @[json: outputSchema; omitempty; raw]
}
Tool describes an MCP tool exposed by the server.
struct ToolResult #
struct ToolResult {
pub:
content string @[omitempty; raw]
structured_content string @[json: structuredContent; omitempty; raw]
is_error bool @[json: isError]
}
ToolResult is returned by tools/call.
- README
- Constants
- fn connect
- fn connect_http
- fn connect_stdio
- fn decode_notification
- fn decode_request
- fn decode_response
- fn new_client
- fn new_notification
- fn new_request
- fn new_response
- fn new_server
- fn prompt_text_message
- fn text_content
- fn tool_text_result
- fn SessionTransport.from
- interface Transport
- type PromptHandler
- type ResourceHandler
- type ToolHandler
- enum SessionTransport
- struct Client
- struct ClientConfig
- struct Context
- struct Empty
- struct EmptyObject
- struct GetPromptResult
- struct Implementation
- struct InitializeParams
- struct InitializeResult
- struct Notification
- struct Null
- struct Prompt
- struct PromptArgument
- struct PromptMessage
- struct ReadResourceResult
- struct Request
- struct Resource
- struct ResourceContents
- struct ResourceTemplate
- struct Response
- struct ResponseError
- struct Server
- struct ServerConfig
- struct Tool
- struct ToolResult