Skip to content

muhammad-fiaz/mcp.zig

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

30 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
logo

MCP.zig

Documentation Zig Version CI 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 with full support for roots, sampling, and elicitation
  • Tasks System - Advanced support for long-running, interactive tasks
  • Rich Content - Full support for text, images, audio, and embedded resources
  • 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:

Related Zig Projects

  • For API framework support, check out api.zig.

  • For web framework support, check out zix.

  • For logging support, check out logly.zig.

  • For data validation and serialization support, check out zigantic.

  • For Http Client and Server support, check out httpx.zig.

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.3.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();

    // 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 mcp.tools.textResult(allocator, 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 build run-server
zig build run-weather
zig build run-calc

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

Compile tests for a target without executing them (useful for cross-target validation):

zig build test-compile -Dtarget=x86_64-linux
zig build test-compile -Dtarget=x86_64-windows
zig build test-compile -Dtarget=x86_64-macos

Protocol Version

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

Version Status
2025-11-25 Supported
2025-06-18 Compatible
2025-03-26 Compatible
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

This project is licensed under the MIT License. See LICENSE for details.

Resources

Sponsor this project

  •  

Packages

 
 
 

Contributors

Languages