A Model Context Protocol (MCP) library for the Zig ecosystem.
Overview
A Model Context Protocol (MCP) library for the Zig ecosystem. Documentation | API Reference | Quick Start | Contributing is an open-source standard for connecting AI applications to external systems. Just as USB-C provides a standardized way to connect electronic devices, MCP provides a standardized way to connect AI applications to external systems. 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, .
README
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
- MRTR Support - Multi Round-Trip Requests via InputRequiredResult for interactive workflows
- 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 (httpx.zig)
- 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
# Zig 0.17.x (recommended)
zig fetch --save https://github.com/muhammad-fiaz/mcp.zig/archive/refs/tags/0.0.8.tar.gz
# Zig 0.16.x
zig fetch --save https://github.com/muhammad-fiaz/mcp.zig/archive/refs/tags/0.0.6.tar.gz
# Zig 0.15.x
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(init: std.process.Init) void {
run(init.io, init.gpa) catch |err| {
mcp.reportError(err);
};
}
fn run(io: std.Io, allocator: std.mem.Allocator) !void {
// Create server
var server: mcp.Server = .init(allocator, .{
.name = "my-server",
.version = "1.0.0",
});
defer server.deinit();
// Add a tool
try server.addTool(.{
.name = "greet",
.description = "Greet a user",
.handler = greetHandler,
});
// Run with STDIO transport
try server.run(io, allocator, .stdio);
}
fn greetHandler(
_: ?*anyopaque,
_: std.Io,
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(init: std.process.Init) void {
run(init.io, init.gpa) catch |err| {
mcp.reportError(err);
};
}
fn run(io: std.Io, allocator: std.mem.Allocator) !void {
var client: mcp.Client = .init(io, allocator, .{
.name = "my-client",
.version = "1.0.0",
});
defer client.deinit();
// Enable capabilities
client.enableSampling();
client.enableRoots(true); // Supports list changed notifications
// Connect to server
try client.connectStdio("my-server-binary", &.{});
// Discover server capabilities (2026-07-28)
try client.discover();
// List tools
try client.listTools();
}
Examples
The examples/ directory contains several example implementations:
| Example | Description | Run step |
|---|---|---|
| simple_server.zig | Basic server with greeting tool | run-server |
| simple_client.zig | Basic client setup | run-client |
| weather_server.zig | Weather information server | run-weather |
| calculator_server.zig | Calculator with arithmetic operations | run-calc |
| advanced_server.zig | Advanced schemas and task support | run-advanced |
| filesystem_server.zig | Filesystem resources server | run-filesystem |
| notes_server.zig | In-memory notes server | run-notes |
| http_server.zig | HTTP transport server | run-http |
| middleware_server.zig | Middleware usage server | run-middleware |
| batch_client.zig | Batch request client | run-batch |
| rate_limiter_example.zig | Rate limiter example | run-rate-limiter |
| health_check_example.zig | Health check example | run-health-check |
| shutdown_example.zig | Graceful shutdown example | run-shutdown |
| validator_example.zig | Request validator example | run-validator |
Run examples:
# Build all examples
zig build run-all-examples
# Run examples
zig build run-server
zig build run-weather
zig build run-calc
zig build run-advanced
Architecture
src/
├── mcp.zig # Main entry point
├── version.zig # Library version
├── report.zig # Error reporting
├── 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 (httpx.zig)
├── server/
│ ├── server.zig # Server implementation
│ ├── tools.zig # Tool primitive
│ ├── resources.zig # Resource primitive
│ └── prompts.zig # Prompt primitive
├── client/
│ ├── client.zig # Client implementation
│ ├── elicitation.zig # Elicitation support
│ ├── roots.zig # Roots support
│ └── sampling.zig # Sampling support
└── utils/
├── mod.zig # Utility module index
├── errors.zig # Error definitions
├── logging.zig # Logging helpers
├── middleware.zig # Middleware, batching, validation
├── network.zig # Network helpers
└── progress.zig # Progress reporting
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(allocator, "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
Generating Documentation
Generate native, interactive HTML API documentation for the library:
zig build docs
The generated files (including index.html, main.js, and main.wasm) will be located in the zig-out/docs/ directory. You can view them using any standard web browser.
Protocol Version
This library implements MCP protocol version 2026-07-28.
| Version | Status |
|---|---|
| 2026-07-28 | Supported |
| 2025-11-25 | Compatible |
| 2025-06-18 | Compatible |
| 2025-03-26 | Compatible |
| 2024-11-05 | Compatible |
What’s New in 2026-07-28
- Stateless Protocol - No more
initialize/notifications/initializedhandshake. Every request carries protocol version and client info in_meta. server/discover- Mandatory RPC that servers MUST implement. ReturnssupportedVersions,capabilities,serverInfo.- MRTR (Multi Round-Trip Requests) - Servers use
InputRequiredResultwithresultType: "input_required"andinputRequestsinstead of server-initiated JSON-RPC requests. subscriptions/listen- Replacesresources/subscribe/resources/unsubscribeand HTTP GET endpoint.- Caching -
ttlMsandcacheScoperequired on list/read results. - OAuth 2.1 authorization framework with Protected Resource Metadata.
Deprecated Features
initialize/notifications/initializedhandshake (useserver/discover)pingmethodlogging/setLevelmethodresources/subscribe/resources/unsubscribe(usesubscriptions/listen)- HTTP+SSE transport (deprecated, use Streamable HTTP)
- Roots, Sampling, Logging (still functional but new implementations should not adopt)
Contributing
Contributions are welcome! Please feel free to submit issues and pull requests.
See CONTRIBUTING.md and the Contributing Guide for guidelines. For security vulnerabilities, see SECURITY.md — report privately to [email protected].
Support
If you find this project helpful, consider supporting its development:
License
This project is licensed under the MIT License. See LICENSE for details.
Resources
Install
This server does not publish a one-line install command.
Open the repository installation guide