説明なし

clanker d06761781e Install GIR 1 ヶ月 前
docs 92b1147690 Repo cleanup 1 ヶ月 前
examples 3c0a8b6a4d Fix prompts 1 ヶ月 前
src d06761781e Install GIR 1 ヶ月 前
.gitignore 3e11b594c3 Initial commit 1 ヶ月 前
README.md 92b1147690 Repo cleanup 1 ヶ月 前
meson.build 91cdf5a2c9 Fix tools 1 ヶ月 前

README.md

MCP Vala Library

A comprehensive Vala implementation of the Model Context Protocol (MCP) version "2025-11-25" using jsonrpc-gobject for STDIO communication.

Introduction

The MCP Vala Library provides a complete implementation of the Model Context Protocol (MCP) in Vala, enabling developers to create MCP servers with minimal boilerplate code. MCP is a protocol that allows language models to securely interact with external resources, tools, and prompts through a standardized JSON-RPC interface.

This library offers a clean, type-safe, and asynchronous API that follows Vala's programming conventions while maintaining full compliance with the MCP specification.

Features

  • Core MCP Protocol Support: Full implementation of MCP v2025-11-25 specification
  • JSON-RPC 2.0: Standard-compliant implementation using jsonrpc-glib-1.0
  • STDIO Transport: Standard input/output communication with proper handling
  • Type Safety: Leverages Vala's type system while using Json-Glib for JSON handling
  • Asynchronous Design: Non-blocking operations throughout
  • Extensible Architecture: Clean interfaces for custom providers and executors
  • Resource Management: Built-in file system provider with extensible provider interface
  • Tool Execution: Simple tool registration and execution framework
  • Prompt Handling: Template-based prompt system with argument support
  • Error Handling: Comprehensive error domain with proper JSON-RPC error codes
  • IO Reliability: Robust error handling and message parsing through jsonrpc-glib-1.0

Quick Start

Installation

From Source

# Clone the repository
git clone https://github.com/your-repo/mcp-vala.git
cd mcp-vala

# Configure and build
meson setup builddir
meson compile -C builddir

# Install (optional)
sudo meson install -C builddir

Dependencies

  • Vala compiler (valac) >= 0.56
  • Meson build system (meson) >= 0.59
  • Required dependencies:
    • glib-2.0 >= 2.70
    • gobject-2.0 >= 2.70
    • gio-2.0 >= 2.70
    • json-glib-1.0 >= 1.6
    • jsonrpc-glib-1.0 >= 3.34
    • gio-unix-2.0 (for STDIO transport)
    • gee-0.8 (for collections)

Minimal Example

Create a minimal MCP server with just a few lines of code:

using Mcp;

int main (string[] args) {
    // Create server info
    var server_info = new Mcp.Types.Protocol.ServerInfo (
        "minimal-server",
        "1.0.0",
        "A minimal MCP server"
    );
    
    // Create capabilities
    var capabilities = new Mcp.Types.Protocol.ServerCapabilities ();
    
    // Create and start server
    var server = new Mcp.Core.Server (server_info, capabilities);
    
    // Start the server (blocking)
    bool started = yield server.start ();
    
    // Keep the main loop running
    var loop = new MainLoop ();
    loop.run ();
    
    return 0;
}

Compile and run:

valac --pkg mcp-vala --pkg json-glib-1.0 --pkg jsonrpc-glib-1.0 --pkg gio-unix-2.0 --pkg gee-0.8 minimal.vala -o minimal-server
./minimal-server

Main Features

Resources

Resources represent data that can be read by clients, such as files, database entries, or API responses. The library provides:

  • Built-in file system resource provider
  • Extensible resource provider interface
  • Resource templates for dynamic resource creation
  • Subscription support for resource change notifications

    // Register a file system provider
    var provider = new Mcp.Resources.Provider.FilesystemProvider ("/path/to/directory");
    server.resource_manager.register_provider (provider);
    

Tools

Tools are functions that clients can execute, such as running commands, performing calculations, or interacting with external services.

public class CalculatorTool : Mcp.Tools.BaseExecutor {
    public CalculatorTool () {
        // Define input schema using Variant
        var input_schema = Mcp.Types.VariantUtils.new_dict_builder ();
        input_schema.add ("{sv}", "type", new Variant.string ("object"));
        
        var properties = Mcp.Types.VariantUtils.new_dict_builder ();
        
        var expr_prop = Mcp.Types.VariantUtils.new_dict_builder ();
        expr_prop.add ("{sv}", "type", new Variant.string ("string"));
        expr_prop.add ("{sv}", "description", new Variant.string ("Mathematical expression to evaluate"));
        properties.add ("{sv}", "expression", expr_prop.end ());
        
        var required = new VariantBuilder (new VariantType ("as"));
        required.add_value ("s", "expression");
        input_schema.add ("{sv}", "properties", properties.end ());
        input_schema.add ("{sv}", "required", required.end ());
        
        base (new Mcp.Tools.Types.ToolDefinition ("calculator", input_schema.end ()));
    }
    
    protected override async Mcp.Tools.Types.CallToolResult do_execute (Variant arguments) throws Error {
        string expression = get_string_arg (arguments, "expression");
        
        // Simple evaluation (in production, use a proper math parser)
        string result = eval_expression (expression);
        
        return create_text_result ("Result: %s".printf (result));
    }
}

// Register the tool
server.tool_manager.register_executor (new CalculatorTool ());

Prompts

Prompts are templates that can be filled with arguments to generate consistent messages for language models.

public class CodeReviewPrompt : Mcp.Prompts.BaseTemplate {
    public CodeReviewPrompt () {
        var arguments = new Gee.ArrayList<Mcp.Prompts.Types.PromptArgument> ();
        
        var code_arg = new Mcp.Prompts.Types.PromptArgument ("code");
        code_arg.description = "The code to review";
        code_arg.required = true;
        arguments.add (code_arg);
        
        var style_arg = new Mcp.Prompts.Types.PromptArgument ("style");
        style_arg.description = "Review style (strict, moderate, relaxed)";
        arguments.add (style_arg);
        
        base ("code_review", "Generate a code review for the provided code", arguments);
    }
    
    protected override async Mcp.Prompts.Types.GetPromptResult do_render (Variant arguments) throws Error {
        string code = Mcp.Types.VariantUtils.get_string (arguments, "code");
        string style = Mcp.Types.VariantUtils.has_key (arguments, "style")
            ? Mcp.Types.VariantUtils.get_string (arguments, "style")
            : "moderate";
        
        string prompt_text = @"Please review the following code using a $style style:\n\n$code\n\nProvide feedback on:\n1. Code quality\n2. Potential bugs\n3. Performance considerations\n4. Best practices";
        
        var content = new Mcp.Types.Common.TextContent (prompt_text);
        var message = new Mcp.Prompts.Types.PromptMessage ("user", content);
        var messages = new Gee.ArrayList<Mcp.Prompts.Types.PromptMessage> ();
        messages.add (message);
        
        return new Mcp.Prompts.Types.GetPromptResult (messages);
    }
}

// Register the prompt
server.prompt_manager.register_template (new CodeReviewPrompt ());

API Overview

Core Classes

Manager Classes

Base Classes

Type Definitions

Tool Execution Classes

Building and Testing

Build Commands

# Configure the build
meson setup builddir

# Build the library
meson compile -C builddir

# Run tests (when available)
meson test -C builddir

# Build examples
meson compile -C builddir examples

# Install
sudo meson install -C builddir

Building Examples

The library includes several examples that demonstrate different aspects of the MCP protocol:

# Build all examples
meson compile -C builddir examples

# Run specific examples
./builddir/examples/minimal-server
./builddir/examples/filesystem-server
./builddir/examples/calculator-server
./builddir/examples/chat-server

Usage Patterns

Server Initialization

// Create server information
var server_info = new Mcp.Types.Protocol.ServerInfo (
    "my-server",
    "1.0.0",
    "Description of my MCP server",
    "https://my-server.example.com"  // Optional website URL
);

// Configure capabilities
var capabilities = new Mcp.Types.Protocol.ServerCapabilities ();
capabilities.logging = true;
capabilities.completions = new Mcp.Types.Protocol.CompletionsCapabilities ();
capabilities.resources = new Mcp.Types.Protocol.ResourcesCapabilities ();
capabilities.tools = new Mcp.Types.Protocol.ToolsCapabilities ();
capabilities.prompts = new Mcp.Types.Protocol.PromptsCapabilities ();

// Create server
var server = new Mcp.Core.Server (server_info, capabilities);

Error Handling

The library provides a comprehensive error domain with proper JSON-RPC error codes:

try {
    var result = yield server.tool_manager.call_tool ("calculator", arguments);
    // Handle result
} catch (Mcp.Core.Error e) {
    // Handle MCP-specific errors
    stderr.printf ("MCP Error: %s (code: %d)\n", e.message, e.code);
} catch (Error e) {
    // Handle other errors
    stderr.printf ("Error: %s\n", e.message);
}

Asynchronous Operations

All operations that involve I/O are asynchronous:

// List resources
var resource_list = yield server.resource_manager.list_resources ();

// Call a tool
var tool_result = yield server.tool_manager.call_tool ("my_tool", arguments);

// Get a prompt
var prompt = yield server.prompt_manager.get_prompt ("my_prompt", arguments);

Architecture

The implementation follows these key design principles:

  1. Standard JSON-RPC Implementation: Uses jsonrpc-glib-1.0 for standard-compliant JSON-RPC 2.0 communication
  2. Interface-Based Design: Extensible providers and executors with well-defined contracts
  3. Type Safety: Strong typing with Vala's type system
  4. Error Handling: Comprehensive error domain with proper JSON-RPC error codes
  5. Asynchronous Operations: Non-blocking I/O and async method signatures
  6. Protocol Compliance: Full MCP v2025-11-25 specification support
  7. IO Reliability: Robust STDIO transport and message handling through jsonrpc-glib-1.0

Project Structure

mcp-vala/
├── src/
│   ├── core/
│   │   ├── compat.vala            # Compatibility utilities (InjectContentLength, StripContentLength)
│   │   ├── error.vala            # Error domain and utilities
│   │   └── server.vala           # Main server class using Jsonrpc.Server
│   ├── types/
│   │   ├── common.vala           # Common content types
│   │   ├── protocol.vala         # Protocol types (ServerInfo, Capabilities)
│   │   └── variant_utils.vala    # Variant utility functions
│   ├── resources/
│   │   ├── manager.vala          # Resource manager
│   │   ├── provider.vala         # Resource provider interface and base class
│   │   └── types.vala            # Resource data types
│   ├── tools/
│   │   ├── executor.vala         # Tool executor interface and base class
│   │   ├── manager.vala          # Tool manager
│   │   └── types.vala            # Tool data types
│   ├── prompts/
│   │   ├── manager.vala          # Prompt manager
│   │   ├── template.vala         # Prompt template interface and base class
│   │   └── types.vala            # Prompt data types
│   └── meson.build               # Library build configuration
├── examples/
│   ├── minimal-server.vala       # Minimal server example
│   ├── simple-server.vala        # Simple server with resources
│   ├── filesystem-server.vala    # File system resource example
│   ├── calculator-server.vala    # Tool execution example
│   ├── chat-server.vala          # Prompt handling example
│   └── meson.build              # Examples build configuration
├── docs/
│   ├── api-reference.md         # API documentation
│   ├── developer-guide.md       # Developer guide
│   └── meson.build              # Documentation build configuration
├── meson.build                  # Main build configuration
├── .gitignore                   # Git ignore file
└── README.md                    # This file

License

This library is licensed under the GNU Lesser General Public License v2.1 or later. See individual source files for specific license information.

Contributing

Contributions are welcome! Please ensure:

  • Code follows Vala naming conventions
  • Comprehensive documentation with Valadoc comments
  • Tests for new functionality
  • Adherence to the architecture design

Status

The core MCP server functionality is implemented and ready for use. The library now uses jsonrpc-glib-1.0 for standard-compliant JSON-RPC 2.0 communication, providing improved IO reliability and error handling. This provides a solid foundation for building MCP servers in Vala with proper protocol compliance and extensibility.