Matrix Connector SDK for Rust
A Rust SDK for building connectors that integrate with the Matrix Connector Framework.
Features
- gRPC bidirectional streaming - Efficient communication with Matrix server
- Type-safe protobuf integration - Auto-generated types from protobuf definitions
- Async/await support - Built on Tokio for high-performance async operations
- Multiple payload encodings - JSON, RAW_BYTES, JSON_LINES, and more
- Automatic reconnection - Handles connection failures gracefully
- Session token support - Fast reconnection using session tokens
- Comprehensive error handling - Detailed error types and messages
Installation
From GitHub (Internal - Recommended)
Add to your Cargo.toml:
[]
= {
git = "https://github.com/Strike48/matrix-mcf-grpc-v1",
= "src/apps/matrix_connectors/sdks/rust"
}
For specific version/tag:
[]
= {
git = "https://github.com/Strike48/matrix-mcf-grpc-v1",
= "v0.1.0",
= "src/apps/matrix_connectors/sdks/rust"
}
For specific branch:
[]
= {
git = "https://github.com/Strike48/matrix-mcf-grpc-v1",
= "develop",
= "src/apps/matrix_connectors/sdks/rust"
}
For Private Repositories
Configure Git authentication for Cargo:
# Option 1: Use SSH (recommended)
# Cargo uses SSH by default if available
# Option 2: Use Personal Access Token via .netrc
# Option 3: Configure git credential helper
Then add to Cargo.toml:
[]
= {
git = "ssh://git@github.com/Strike48/matrix-mcf-grpc-v1",
= "src/apps/matrix_connectors/sdks/rust"
}
From Crates.io (Coming Soon)
[]
= "0.1.0"
From Local Path (Development)
[]
= { = "path/to/matrix-connector-sdk" }
From Source (Development)
# Build (proto stubs auto-generated via build.rs)
Prerequisites:
# Install protoc (macOS)
# Install protoc (Linux)
The Rust SDK uses tonic-build in build.rs to auto-generate protobuf stubs during compilation. No manual proto generation is needed.
Quick Start
Basic Echo Connector
use *;
use Arc;
;
async
Configuration
The SDK supports configuration via environment variables or programmatically:
Environment Variables
| Variable | Description | Default |
|---|---|---|
MATRIX_HOST or MATRIX_URL |
Matrix server URL | localhost:50061 |
TENANT_ID |
Tenant identifier | required |
INSTANCE_ID |
Connector instance ID | Auto-generated (see below) |
AUTH_TOKEN |
JWT token (optional) | Empty (uses approval flow) |
USE_TLS |
Enable TLS | false |
CONNECTOR_DISPLAY_NAME |
Human-readable name for UI | instance_id |
CONNECTOR_TAGS |
Comma-separated tags | Empty |
Instance ID
The INSTANCE_ID uniquely identifies your connector instance. This is critical for:
- Credential persistence - Saved credentials are keyed by instance ID
- Session management - Matrix server tracks sessions by instance
- Reconnection - Same instance ID allows seamless reconnection
If not provided, the SDK generates a random instance ID:
{connector_type}-{timestamp_millis}
Best Practice: Always set INSTANCE_ID for production connectors to enable auto-reconnection after restarts.
# Recommended: Stable instance ID
# Auto-generated: Random on each start (not recommended for production)
# (omit INSTANCE_ID)
Authentication & Private Key Storage
The SDK uses asymmetric authentication (private_key_jwt). On first connection:
- Admin approves the connector in Matrix Studio
- SDK generates an RSA key pair automatically
- Private key is saved for future reconnections
Default Storage Locations:
| Item | Location |
|---|---|
| Private Keys | ~/.matrix/keys/{connector_type}_{instance_id}.pem |
| Credentials | ~/.matrix/credentials/matrix_{tenant}_{type}_{instance}.json |
Override Storage Paths:
# Override keys directory
# Direct private key path (for cert-manager/K8s)
Reconnection Behavior
When the connector restarts with the same INSTANCE_ID:
- SDK loads saved credentials from
~/.matrix/credentials/ - Fetches a fresh JWT using the saved private key
- Reconnects to Matrix without requiring re-approval
This only works if:
INSTANCE_IDis the same as the previous run- Credentials file exists at the expected path
- Private key file exists at the expected path
Programmatic Configuration
let config = ConnectorConfig ;
Instance Metadata (Multi-Instance Routing)
Instance metadata enables multi-instance routing and better UI display:
let config = from_env
.display_name // Human-readable name for UI
.tag // Tags for grouping
.tag
.with_metadata // Key-value metadata
.with_metadata;
Available Builder Methods:
| Method | Description |
|---|---|
.display_name("Name") |
Human-readable name for UI (defaults to instance_id) |
.tag("prod") |
Add a single tag for grouping |
.tags(["prod", "us-east-1"]) |
Add multiple tags at once |
.with_metadata("key", "value") |
Add operator metadata |
.metadata_from_env("PREFIX_") |
Load metadata from env vars with prefix |
Example with Environment Metadata:
// Reads CONNECTOR_LOCATION, CONNECTOR_OWNER, etc.
let config = from_env
.display_name
.tags
.metadata_from_env;
Agent Routing Behavior:
- "run command" → round-robin across all instances
- "run command on prod-1" → route to specific instance_id
- "run command on Production Server 1" → route via display_name
- "run command on all prod servers" → broadcast to instances tagged "prod"
Examples
See the examples/ directory for complete examples:
echo_connector.rs- Simple echo connector that returns the input
Running Examples
# Set environment variables
# Run echo connector
Building
# Build the SDK
# Build with examples
# Run tests
# Run integration tests (requires running Matrix server)
Architecture
The SDK consists of several key components:
BaseConnector- Trait that connectors must implementConnectorRunner- Manages connector lifecycle and message handlingConnectorHandle- Safe handle for sending messages from callbacks (WebSocket frames, invoke)types- Type definitions matching protobuf schemasutils- Serialization, deserialization, and helper functionsprocess- Async process execution (non-blockingtokio::process::Commandwrappers)error- Comprehensive error types
Payload Encodings
The SDK supports multiple payload encodings:
JSON- Standard JSON encoding (default)RAW_BYTES- Raw byte arraysJSON_LINES- Newline-separated JSONARROW_IPC- Apache Arrow IPC formatPROTOBUF- Protocol BuffersMSGPACK- MessagePackPARQUET- Apache Parquet
Error Handling
All operations return Result<T, ConnectorError>:
match runner.run.await
Logging
The SDK uses the tracing crate for logging. Initialize with:
init_logger;
Control log level via RUST_LOG environment variable:
RUST_LOG=debug