Zero Labs
Industry News / AI

Building OmniPulse’s Rust Core: FFI Bridges, Optimal Transport, and a Real MCP Server

Source · Towards AI By Yash

From the publisher’s feed, collected in the ZeroLabs newsroom.

The audio data is 5MB. The JSON-RPC message is 28 bytes. That gap is the entire Rust layer.Generative audio (Suno, Udio, etc.) is outpacing provenance. Labels and platforms need to know if a generated track is a derivative of something they own. OmniPulse is the answer: it is a wavelet-scattering fingerprint plane that identifies, attributes, and licenses synthetic and human-authored media. It is a 3-tier architecture with rust in the middle layer. It handles FFI, distance computation, nearest-neighbor retrieval, and MCP tool serving. Four jobs, one binary.The C++ WST kernel lives in omni-ffi. Rust calls into it via cxx, a zero-overhead FFI crate that generates type-safe bindings between Rust and C++ at compile time. No unsafe string marshaling, no JSON serialization across the boundary. The bridge is a single function.unsafe fn run_wst_pipeline( input_plasma_ptr: u64, signal_len: i32, batch_size: i32, J: i32, Q: i32, depth: i32, use_jtfs: bool,) -> ResultThe input is a u64, a raw pointer to float32 data. On the CPU path this is just a heap address. On the GPU it’s a CUDA device pointer. The C++ side casts it backconst float* input = reinterpret_cast( static_cast(input_plasma_ptr));No copies. No serialization. The audio data never moves. Rust hands C++ a pointer, C++ reads from it, the kernel runs in place.The C++ side allocates the output with new float[] and returns a pointer inside WSTResult. Rust must call free_wst_result exactly once. Forget it and you leak. Call it twice and you get undefined behavior. The fix is a RAII wrapper.struct WstResultGuard(omni_ffi::WSTResult);impl Drop for WstResultGuard { fn drop(&mut self) { unsafe { omni_ffi::free_fingerprint(self.0) } }}This pattern is the difference between a memory-safe FFI boundary and one that leaks on every error path.Wrap the result immediately after the call. The guard owns the memory. When it goes out of scope whether normally or via panic, the free_fingerprint runs exactly once. Rust’s ownership model enforcing C++ memory safety.Before the FFI call, Rust reads the audio from POSIX shared memory. Python writes the float32 array into a shm segment and passes only the 28-character hex name over JSON-RPC. Rust opens it, reads it, and unlinks it:pub fn read_and_unlink(shm_name: &str, n_bytes: usize) -> Result, WstError> { let fd = libc::shm_open(c_name.as_ptr(), libc::O_RDONLY, 0); let ptr = libc::mmap(null_mut(), n_bytes, PROT_READ, MAP_SHARED, fd, 0); let data = slice::from_raw_parts(ptr as *const f32, n_bytes / 4).to_vec(); libc::munmap(ptr, n_bytes); libc::shm_unlink(c_name.as_ptr()); // Rust owns the unlink Ok(data)}let fd = libc::shm_open(c_name.as_ptr(), libc::O_RDONLY, 0);Raw audio never crosses the JSON-RPC boundary. Only the pointer name does, 28 characters instead of megabytes.SlicedWasserstein implements the Metric trait from vector-index. That one impl line is what makes HNSW metric-agnosticimpl Metric for SlicedWasserstein { type Point = PointCloud; fn distance(&self, a: &PointCloud, b: &PointCloud) -> f32 { self.distance(a.data(), b.data()) } fn dim(&self, point: &PointCloud) -> usize { point.dim() }}HNSW never knows what SW₁ is. It just calls metric.distance(a, b) and gets a float back.The CPU WST kernel returns signal_len floats which are the same size as input. For a 344-sample signal that’s 344 floats. PointCloud::new(data, dim) needs to know how to chunk that into points. We use dim=1 on the CPU path, each output float is treated as a 1D point. SW₁ then computes the 1D Wasserstein between two output distributions, which is exact (not an approximation) in 1D.#[derive(Clone)]pub struct OmniPulseServer { kernel: Arc, index: Arc>>, fingerprints: Arc>>>, fp_id_order: Arc>>, // ...}All fields are Arc-wrapped that are cheap to clone, safe to share across Tokio tasks. The RwLock allows many concurrent searches with occasional exclusive writes for inserts.HNSW returns neighbors by internal sequential integer ID. Our fingerprints have ULID string IDs. The fp_id_order: Vec is the bridge that pushes each ID in insertion order, then fp_id_order[n.id as usize] maps back to the string ID.zeros → zeros: 0.000000zeros → sine-low: 0.001942zeros → sine-high: 0.002710zeros → sine-mid: 0.008654zeros → noise-42: 0.026856Gaussian noise is most distant from silence because it activates every scattering path simultaneously. The ordering is physically correct.The server uses rmcp’s #[tool_router] and #[tool_handler] macros. The macro generates call_tool, list_tools, and dispatch logic automatically.#[tool_router]impl OmniPulseServer { #[tool(name = "generate_fingerprint", description = "...")] async fn generate_fingerprint_tool( &self, Parameters(req): Parameters, ) -> Result { let resp = self.generate_fingerprint(req).await?; Ok(CallToolResult::success(vec![Content::text( serde_json::to_string(&resp)? )])) }The server speaks JSON-RPC over stdin/stdout. Any MCP client spawns it as a subprocess. The MCP protocol requires an initialization handshake before any tool calls:initialize request, server responds with capabilities, client sends notifications/initialized. Skipping this causes the server to reject every tool call with “expected initialized request.” The Python client handles this in MCPClient.start().WstKernel::run is CPU-bound. Running it directly in an async handler would block the Tokio runtime. Every kernel call goes through spawn_blockinglet fingerprint = tokio::task::spawn_blocking(move || { kernel.run(&signal, &cfg)}).await.map_err(|e| ErrorData::internal_error(format!("kernel panicked: {e}"), None))?.map_err(ErrorData::from)?;kernel.run(&signal, &cfg)The double ? first unwraps the JoinError from the task, second unwraps the WstError from run.compute_fingerprint runs WST and returns the raw fingerprint without storing it. generate_fingerprint runs WST, stores the result in HNSW, returns a ULID. compare_fingerprints accepts either a stored ULID or a raw fingerprint vector, runs HNSW search, returns neighbors with SW₁ distances. issue_license_token signs a LicensePayload with Ed25519 via bincode serialization.The Python control plane sends query_hash and fingerprint_hash. A richer schema with query: {stored_id: …} and full license_terms is also supported. Custom Deserialize implementations accept either and resolve to the same internal types. The server never knows which client called it.The OmniFfiKernel implementation has the CPU path working. The GPU path (CUDA device pointers, Plasma store, cudaMemcpy) is behind the omni-ffi feature flag. The WstKernel trait means swapping CPU for GPU is one line in main.rs. The architecture doesn’t change.The index is in-memory only. Restart the server and fingerprints are gone. At 344-sample signals the current CPU WST output is signal_len floats, small enough that a sled or rocksdb backing store is straightforward.that a sled or rocksdb backing store is straightforward. The fp_id_order Vec and the HashMap> both serialize cleanly with bincode.The landing page at omnipulse describes the full commercial picture: Kubernetes control plane, GPU autoscaling driven by Prometheus queue depth, multi-tenant deployment.The Rust layer is three published crates and one binary. The full stack is on GitHub and the module stack is live at omnipulse.Building OmniPulse’s Rust Core: FFI Bridges, Optimal Transport, and a Real MCP Server was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.