Skip to content

muhammad-fiaz/mcp.zig

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

20 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
logo

MCP.zig

Documentation Zig Version GitHub stars GitHub issues GitHub pull requests GitHub last commit License Docs Supported Platforms Latest Release Sponsor GitHub Sponsors Repo Visitors

A Model Context Protocol (MCP) library for the Zig ecosystem.

📚 Documentation | API Reference | Quick Start | Contributing


🔌 What is MCP?

Model Context Protocol (MCP) is an open-source standard for connecting AI applications to external systems. Think of MCP like a USB-C port for AI applications. Just as USB-C provides a standardized way to connect electronic devices, MCP provides a standardized way to connect AI applications to external systems.

🎯 Why mcp.zig?

The Model Context Protocol (MCP) is an open standard by Anthropic for connecting AI applications to external systems. While MCP has official SDKs for TypeScript, Python, and other languages, Zig currently lacks proper MCP support.

mcp.zig aims to fill this gap by providing a native, high-performance MCP implementation for the Zig programming language, enabling Zig developers to:

  • 🔧 Build MCP servers that expose tools, resources, and prompts to AI applications
  • 🔌 Create MCP clients that connect to any MCP-compatible server
  • ⚡ Leverage Zig's performance and safety features for AI integrations

✨ Features

  • 🛠️ Server Framework - Build MCP servers that expose tools, resources, and prompts
  • 🔌 Client Framework - Create MCP clients that connect to servers
  • 📡 Transport Layer - STDIO and HTTP transport support
  • 📋 Full Protocol Support - JSON-RPC 2.0, capability negotiation, lifecycle management
  • Native Performance - Written in pure Zig for optimal performance
  • 🧪 Comprehensive Testing - Unit tests for all components

📚 Documentation

Full documentation is available at muhammad-fiaz.github.io/mcp.zig

For the official MCP specification and resources, visit:

🚀 Quick Start

Installation

Run the following command to add mcp.zig to your project:

# Latest development branch
zig fetch --save git+https://github.com/muhammad-fiaz/mcp.zig.git

# Or specific release
zig fetch --save https://github.com/muhammad-fiaz/mcp.zig/archive/refs/tags/0.0.2.tar.gz

Then in your build.zig:

const mcp_dep = b.dependency("mcp", .{
    .target = target,
    .optimize = optimize,
});
exe.root_module.addImport("mcp", mcp_dep.module("mcp"));

Creating a Server

const std = @import("std");
const mcp = @import("mcp");

pub fn main() void {
    if (run()) {} else |err| {
        mcp.reportError(err);
    }
}

fn run() !void {
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    defer _ = gpa.deinit();
    const allocator = gpa.allocator();

    // Check for updates
    _ = mcp.report.checkForUpdates(allocator);

    // Create server
    var server = mcp.Server.init(.{
        .name = "my-server",
        .version = "1.0.0",
        .allocator = allocator,
    });
    defer server.deinit();

    // Enable tools capability
    server.enableTools();

    // Add a tool
    try server.addTool(.{
        .name = "greet",
        .description = "Greet a user",
        .handler = greetHandler,
    });

    // Run with STDIO transport
    try server.run(.stdio);
}

fn greetHandler(
    allocator: std.mem.Allocator,
    args: ?std.json.Value
) mcp.tools.ToolError!mcp.tools.ToolResult {
    const name = mcp.tools.getString(args, "name") orelse "World";
    const message = try std.fmt.allocPrint(allocator, "Hello, {s}!", .{name});
    return .{ .content = &.{mcp.Content.createText(message)} };
}

Creating a Client

const std = @import("std");
const mcp = @import("mcp");

pub fn main() void {
    if (run()) {} else |err| {
        mcp.reportError(err);
    }
}

fn run() !void {
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    defer _ = gpa.deinit();
    const allocator = gpa.allocator();

    var client = mcp.Client.init(.{
        .name = "my-client",
        .version = "1.0.0",
        .allocator = allocator,
    });
    defer client.deinit();

    // Enable capabilities
    client.enableSampling();
    client.enableRoots(true); // Supports list changed notifications

    // Add roots
    try client.addRoot("file:///projects", "Projects");
}

📁 Examples

The examples/ directory contains several example implementations:

Example Description
simple_server.zig Basic server with greeting tool
simple_client.zig Basic client setup
weather_server.zig Weather information server
calculator_server.zig Calculator with arithmetic operations

Run examples:

# Build all examples
zig build

# Run examples
./zig-out/bin/example-server
./zig-out/bin/weather-server
./zig-out/bin/calculator-server

🏗️ Architecture

src/
├── mcp.zig              # Main entry point
├── protocol/
│   ├── protocol.zig     # MCP protocol definitions
│   ├── types.zig        # Type definitions
│   ├── jsonrpc.zig      # JSON-RPC 2.0 implementation
│   └── schema.zig       # JSON Schema utilities
├── transport/
│   └── transport.zig    # STDIO and HTTP transports
├── server/
│   ├── server.zig       # Server implementation
│   ├── tools.zig        # Tool primitive
│   ├── resources.zig    # Resource primitive
│   └── prompts.zig      # Prompt primitive
└── client/
    └── client.zig       # Client implementation

🛠️ Server Features

Tools

Tools are executable functions that AI applications can invoke:

try server.addTool(.{
    .name = "search_files",
    .description = "Search for files matching a pattern",
    .handler = searchHandler,
});

Resources

Resources provide read-only data to AI applications:

try server.addResource(.{
    .uri = "file:///docs/readme.md",
    .name = "README",
    .mimeType = "text/markdown",
    .handler = readFileHandler,
});

Prompts

Prompts are reusable templates for LLM interactions:

try server.addPrompt(.{
    .name = "summarize",
    .description = "Summarize a document",
    .arguments = &.{
        .{ .name = "document", .required = true },
    },
    .handler = summarizeHandler,
});

🔌 Client Features

Roots

Define filesystem boundaries:

client.enableRoots(true);
try client.addRoot("file:///projects", "Projects");

Sampling

Allow servers to request LLM completions:

client.enableSampling();

🧪 Testing

Run the test suite:

zig build test

📖 Protocol Version

This library implements MCP protocol version 2025-11-25.

Version Status
2025-11-25 ✅ Supported
2024-11-05 ✅ Compatible

🤝 Contributing

Contributions are welcome! Please feel free to submit issues and pull requests.

See Contributing Guide for guidelines.

💖 Support

If you find this project helpful, consider supporting its development:

Sponsor GitHub Sponsors

📄 License

MIT License - see LICENSE for details.

🔗 Resources

About

A comprehensive Model Context Protocol (MCP) library for Zig — bringing MCP support to the Zig ecosystem.

Topics

Resources

License

Code of conduct

Contributing

Stars

Watchers

Forks

Sponsor this project

  •  

Packages

 
 
 

Contributors

Languages