gopher-mcp-rust - Rust SDK
Rust SDK for Gopher Orch - AI Agent orchestration framework with native C++ performance.
Table of Contents
- Features
- When to Use This SDK
- Architecture
- Installation
- Quick Start
- Building from Source
- Native Library Details
- API Documentation
- Examples
- Development
- Troubleshooting
- Contributing
- License
- Links
- Acknowledgments
Features
- Native Performance - Powered by C++ core with Rust bindings via libloading
- AI Agent Framework - Build intelligent agents with LLM integration
- MCP Protocol - Model Context Protocol client and server support
- Tool Orchestration - Manage and execute tools across multiple MCP servers
- State Management - Built-in state graph for complex workflows
- Memory Safety - Rust's ownership system with zero-cost abstractions
- OAuth 2.0 Authentication - JWT validation with JWKS support (feature-gated)
When to Use This SDK
This SDK is ideal for:
- Rust applications that need high-performance AI agent orchestration
- Systems programming requiring MCP protocol support with memory safety
- CLI tools integrating AI agents with native performance
- WebAssembly targets (with appropriate native library builds)
- Embedded systems needing lightweight agent infrastructure
Architecture
┌─────────────────────────────────────────────────────────────┐
│ Your Application │
└─────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ Rust SDK (gopher_mcp_rust) │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────────────┐ │
│ │ GopherAgent │ │ConfigBuilder│ │ Error Types │ │
│ └─────────────┘ └─────────────┘ └─────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
│ FFI (libloading)
▼
┌─────────────────────────────────────────────────────────────┐
│ Native Library (libgopher-orch) │
│ ┌───────────────┐ ┌───────────────┐ ┌─────────────────┐ │
│ │ Agent Engine │ │ LLM Providers │ │ MCP Client │ │
│ │ │ │ - Anthropic │ │ - HTTP/SSE │ │
│ │ │ │ - OpenAI │ │ - Tool Registry │ │
│ └───────────────┘ └───────────────┘ └─────────────────┘ │
└─────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ MCP Servers │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────────────┐ │
│ │ Weather API │ │ Database │ │ Custom Tools │ │
│ └─────────────┘ └─────────────┘ └─────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
Installation
Option 1: From crates.io
[]
= "0.1.2"
Option 2: Git Dependency
[]
= { = "https://github.com/GopherSecurity/gopher-mcp-rust.git" }
Option 3: Build from Source
See Building from Source section below.
With Auth Feature
Enable OAuth 2.0 / JWT authentication support:
[]
= { = "0.1.2", = ["auth"] }
# Or with git
= { = "https://github.com/GopherSecurity/gopher-mcp-rust.git", = ["auth"] }
Quick Start
use ;
Building from Source
This SDK wraps a native C++ library via libloading. You must build the native library before using the SDK.
Prerequisites
| Requirement | Version | Notes |
|---|---|---|
| Rust | >= 1.64 | Stable toolchain |
| Cargo | Latest | Comes with Rust |
| Git | Latest | For cloning and submodules |
| CMake | >= 3.15 | Native library build system |
| C++ Compiler | C++14+ | Clang (macOS), GCC (Linux), MSVC (Windows) |
Platform-specific requirements:
- macOS: Xcode Command Line Tools (
xcode-select --install) - Linux:
build-essential,libssl-dev - Windows: Visual Studio 2019+ with C++ workload
Step 1: Clone the Repository
Step 2: Build Everything
Using build.sh (recommended)
The build.sh script handles everything automatically:
Using build.sh with Multiple GitHub Accounts:
If you have multiple GitHub accounts configured with SSH host aliases, use the GITHUB_SSH_HOST environment variable:
# Use custom SSH host alias for cloning private submodules
GITHUB_SSH_HOST=your-ssh-alias
# Example: if your ~/.ssh/config has "Host github-work" for work account
GITHUB_SSH_HOST=github-work
What happens during build:
- Submodule update - Initializes and updates submodules (with SSH URL rewriting if
GITHUB_SSH_HOSTis set) - CMake configure - Configures the C++ build with Release settings
- Native compilation - Compiles C++ to shared libraries
- Library installation - Copies libraries to
native/lib/ - Dependency copying - Copies required dependencies (gopher-mcp, fmt)
- macOS fixes - Fixes dylib install names for proper runtime loading
- Cargo build - Compiles Rust SDK
- Tests - Runs Cargo tests
Step 3: Verify the Build
# Check native libraries were built
# Expected output (macOS):
# libgopher-orch.dylib
# libgopher-mcp.dylib
# libgopher-mcp-event.dylib
# libfmt.dylib
# Verify Rust build
Step 4: Run Tests
Native Library Details
Library Location
After building, native libraries are installed to:
native/
├── lib/ # Shared libraries
│ ├── libgopher-orch.dylib # Main orchestration library (macOS)
│ ├── libgopher-orch.so # Main orchestration library (Linux)
│ ├── libgopher-mcp.dylib # MCP protocol library
│ ├── libgopher-mcp-event.dylib # Event handling
│ └── libfmt.dylib # Formatting library
└── include/ # C++ headers (for development)
└── orch/
└── core/
Platform-Specific Library Names
| Platform | Library Extension | Example |
|---|---|---|
| macOS | .dylib |
libgopher-orch.dylib |
| Linux | .so |
libgopher-orch.so |
| Windows | .dll |
gopher-orch.dll |
Library Search Order
The SDK searches for the native library in this order:
native/lib/relative to executable./native/lib/relative to working directoryCARGO_MANIFEST_DIR/native/lib/(compile time)- System library paths
API Documentation
GopherAgent
The main struct for creating and running AI agents:
use ;
// Initialize the library (called automatically on first create)
init?;
// Create with API key (fetches server config from remote API)
let config = new
.with_provider
.with_model
.with_api_key
.build;
let agent = create?;
// Or create with JSON server config
let server_config = r#"
{
"succeeded": true,
"data": {
"servers": [{
"serverId": "server1",
"name": "My MCP Server",
"transport": "http_sse",
"config": {"url": "http://localhost:3001/mcp"}
}]
}
}
"#;
let agent = create_with_server_config?;
// Run a query
let result = agent.run?;
// Run with custom timeout (default: 60000ms)
let result = agent.run_with_timeout?;
// Run with detailed result information
let detailed: AgentResult = agent.run_detailed;
// Returns AgentResult with: response(), status(), iteration_count(), tokens_used()
// Manual cleanup (optional - happens automatically on drop)
drop;
// Shutdown library
shutdown;
ConfigBuilder
Builder for creating agent configurations:
use ConfigBuilder;
// With API key
let config = new
.with_provider
.with_model
.with_api_key
.build;
// With server config
let config = new
.with_provider
.with_model
.with_server_config
.build;
// Check configuration
assert!;
assert!;
Error Handling
The SDK provides typed errors for different failure scenarios:
use ;
Examples
Basic Usage with API Key
use ;
use env;
Using Local MCP Servers
use ;
const SERVER_CONFIG: &str = r#"{
"succeeded": true,
"code": 200,
"message": "OK",
"data": {
"servers": [
{
"version": "1.0.0",
"serverId": "weather-server",
"name": "Weather Service",
"transport": "http_sse",
"config": {
"url": "http://localhost:3001/mcp",
"headers": {}
},
"connectTimeout": 5000,
"requestTimeout": 30000
}
]
}
}"#;
Running the Example
# Run with the convenience script (starts servers automatically)
# Or manually:
# Terminal 1: Start server3001
&& &&
# Terminal 2: Start server3002
&& &&
# Terminal 3: Run the Rust client
ANTHROPIC_API_KEY=your-key
Auth MCP Server Example
The examples/auth directory contains a complete OAuth 2.0 protected MCP server example using Axum:
# Run with auth disabled (development mode)
# Run with full OAuth support
Features:
- OAuth 2.0 / OIDC discovery endpoints (RFC 8414, RFC 9728)
- JWT token validation via native library
- Scope-based authorization for MCP tools
- Example weather tools with different scope requirements
Available Tools:
| Tool | Scope Required | Description |
|---|---|---|
get-weather |
None | Get current weather for a city |
get-forecast |
mcp:read |
Get 5-day weather forecast |
get-weather-alerts |
mcp:admin |
Get weather alerts for a region |
Using the Auth Client:
use GopherAuthClient;
// Create auth client with JWKS endpoint
let client = new?;
// Validate a JWT token
let result = client.validate_token;
if result.valid
// Extract payload without validation
let payload = client.extract_payload?;
See examples/auth/README.md for full documentation.
Development
Project Structure
gopher-mcp-rust/
├── src/
│ ├── lib.rs # Library entry point
│ ├── agent.rs # GopherAgent implementation
│ ├── config.rs # Configuration builder
│ ├── error.rs # Error types
│ ├── result.rs # AgentResult types
│ └── ffi.rs # FFI bindings (libloading)
├── tests/
│ └── ffi_tests.rs # Integration tests
├── native/ # Native libraries (generated)
│ ├── lib/ # Shared libraries (.dylib, .so, .dll)
│ └── include/ # C++ headers
├── third_party/ # Git submodules
│ └── gopher-orch/ # C++ implementation
├── examples/ # Example code
│ ├── client_example_json.rs
│ ├── client_example_json_run.sh
│ ├── server3001/ # Mock weather MCP server
│ └── server3002/ # Mock tools MCP server
├── build.sh # Build orchestration script
├── Cargo.toml # Cargo build configuration
└── README.md
Build Scripts
| Script | Description |
|---|---|
./build.sh |
Full build (submodules + native + Rust SDK) |
GITHUB_SSH_HOST=alias ./build.sh |
Build with custom SSH host |
cargo build |
Compile Rust SDK |
cargo test |
Run tests |
cargo build --release |
Release build |
cargo run --example client_example_json |
Run example |
Rebuilding Native Library
If you modify the C++ code or switch branches:
# Clean and rebuild
Updating Submodules
To pull latest changes from native libraries:
# Update to latest commit
# Rebuild
Troubleshooting
"Library not found" Error
Cause: Native library not built or not in expected location.
Solution:
# Rebuild native library
# Verify library exists
"Submodule is empty" Error
Cause: Git submodules not initialized.
Solution:
CMake Configuration Fails
Cause: Missing dependencies or wrong CMake version.
Solution:
# macOS
# Linux (Ubuntu/Debian)
# Verify version
Linking Error at Runtime
Cause: libloading can't find the native library.
Solution:
# Run from project root
# Or set library path
# macOS
# Linux
Build Fails on Apple Silicon (M1/M2)
Cause: Architecture mismatch.
Solution:
# Ensure using native arm64 toolchain
Rust Version Compatibility
Cause: Using older Rust toolchain.
Solution:
# Update Rust
# Or use minimum supported version
Contributing
Contributions are welcome! Please read our contributing guidelines.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Ensure submodules are initialized (
git submodule update --init --recursive) - Make your changes
- Run tests (
cargo test) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
License
Apache License 2.0 - see LICENSE file for details.
Links
- GitHub Repository
- Java SDK
- Python SDK
- TypeScript SDK
- Native C++ Implementation
- Model Context Protocol
Acknowledgments
- Built on gopher-orch C++ framework
- Uses gopher-mcp for MCP protocol
- Inspired by LangChain and LangGraph
- FFI bindings via libloading