DEV Community

Tamiz Uddin
Tamiz Uddin

Posted on • Originally published at tamiz.pro

From MCP to LSP: Securing AI Agents, Standardizing Context, and the Rise of Rust-Powered Infrastructure

Originally published on tamiz.pro.

The landscape of AI-assisted development is undergoing a structural shift. We are moving from isolated, prompt-based interactions to interconnected, protocol-driven ecosystems. At the heart of this shift are two critical standards: the Model Context Protocol (MCP) by Anthropic, which standardizes how AI models connect to external data, and the Language Server Protocol (LSP), which has long standardized how developers interact with code intelligence.

Simultaneously, the infrastructure layer powering these interactions is increasingly dominated by Rust. Why? Because as AI agents gain access to file systems, APIs, and database connections, the security and performance requirements for the transport layers become non-negotiable. This article dives deep into the convergence of these technologies, examining how MCP and LSP are evolving to support secure, context-aware AI agents, and why Rust is becoming the de facto language for building the infrastructure that makes this possible.

The Evolution of AI Connectivity: From Prompts to Protocols

Historically, integrating AI into software engineering workflows was a fragile process. Developers wrote scripts to call OpenAI or Anthropic APIs, parsing JSON responses and injecting them into their IDEs or CI/CD pipelines. This approach was brittle, insecure, and difficult to scale.

The Language Server Protocol (LSP): The Foundation

LSP was introduced by Microsoft in 2016 to solve a specific problem: how to provide intelligent code features (autocomplete, go-to-definition, refactoring) across different editors and language servers. By abstracting the communication between the editor (client) and the language analysis engine (server) into a JSON-RPC protocol, LSP enabled the rich IDE experiences we take for granted today.

LSP proved that standardizing the interface between code and intelligence was more valuable than any single implementation. It created a modular ecosystem where VS Code, Neovim, and IntelliJ could all share the same underlying language servers.

The Model Context Protocol (MCP): The New Standard

MCP, launched by Anthropic in mid-2024, addresses a similar problem but for AI models. Before MCP, connecting an LLM to external data sources (like a PostgreSQL database or a REST API) required custom, ad-hoc integrations. Each integration had its own authentication, error handling, and data formatting logic.

MCP standardizes this connection. It defines a protocol where:

  1. Hosts (like Claude Desktop or VS Code with an AI extension) request data.
  2. Clients (the AI application) facilitate the connection.
  3. Servers (resource providers) expose data and tools to the model.

This three-tier architecture mirrors the LSP model but is designed specifically for the stochastic, context-window-constrained nature of LLMs. It allows models to dynamically discover and interact with tools and resources without hard-coded integrations.

Convergence: When LSP Meets MCP

The real power emerges when LSP and MCP converge. Modern AI agents don’t just need to generate code; they need to understand the codebase, navigate its structure, and interact with its runtime environment.

Standardizing Context for AI Agents

One of the biggest challenges in AI-assisted development is context management. LLMs have limited context windows, and feeding them an entire codebase is inefficient and expensive.

LSP provides structured information about the codebase: symbols, types, references, and definitions. MCP can expose this LSP-derived data as a resource or tool to the AI model. For example:

  • MCP Resource: A file:// URI that points to a specific file, with metadata about its size and language.
  • MCP Tool: A find_references tool that queries the LSP server to find all usages of a symbol.

This convergence allows AI agents to operate with the precision of a static analysis tool while maintaining the flexibility of natural language interaction. Instead of asking an LLM to "find all bugs related to authentication," the agent can query the LSP server for all functions marked with @auth decorators, then ask the LLM to analyze the logic within those functions.

The Security Implications

This integration introduces new security risks. If an AI agent can query your codebase via LSP and execute tools via MCP, it effectively has read/write access to your development environment.

  • Privilege Escalation: An MCP server might expose a tool to delete files or restart services. If the LLM misinterprets a prompt, it could execute destructive actions.
  • Data Exfiltration: An MCP server might expose sensitive configuration files or database schemas. If the LLM is compromised, this data could be leaked.
  • Supply Chain Attacks: Malicious MCP servers could be packaged and distributed, similar to npm packages, injecting harmful tools into the AI workflow.

The Rise of Rust-Powered Infrastructure

To mitigate these risks and handle the high-throughput, low-latency requirements of AI agents, the infrastructure layer is increasingly built in Rust. Rust offers several advantages that make it ideal for this role:

1. Memory Safety and Performance

AI agents often handle large volumes of data (codebases, logs, metrics) and must process them quickly. Rust’s ownership model ensures memory safety without a garbage collector, leading to predictable performance and reduced latency. This is critical for real-time AI interactions in IDEs.

2. Security by Design

Rust’s type system prevents common vulnerabilities like buffer overflows and data races. When building MCP servers or LSP clients that interact with sensitive systems, Rust provides a safer foundation than Python or JavaScript, which are more prone to runtime errors and security exploits.

3. Interoperability

Rust can easily compile to WebAssembly (Wasm), allowing AI infrastructure to run securely in browser-based environments or sandboxed containers. This is essential for running MCP servers in untrusted environments.

4. Ecosystem Maturity

The Rust ecosystem has matured significantly, with libraries like tower for async services, serde for serialization, and tokio for concurrency. These libraries make it straightforward to build robust, high-performance MCP and LSP servers.

Building a Secure MCP Server in Rust

Let’s look at a practical example of how to build a secure MCP server using Rust. We’ll use the mcp-rs library (hypothetical, based on current trends) to create a server that exposes a tool for reading code snippets from a local repository.

Prerequisites

  • Rust 1.70+ installed
  • Cargo package manager
  • Basic understanding of async Rust

Step 1: Initialize the Project

cargo new mcp-code-server
cd mcp-code-server
Enter fullscreen mode Exit fullscreen mode

Step 2: Add Dependencies

Add the necessary dependencies to your Cargo.toml:

[dependencies]
mcp = "0.1.0" # Hypothetical MCP library for Rust
tokio = { version = "1.0", features = ["full"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
tracing = "0.1"
Enter fullscreen mode Exit fullscreen mode

Step 3: Implement the MCP Server

use mcp::{Server, Tool, Resource};
use serde_json::json;
use std::fs;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Initialize the MCP server
    let mut server = Server::new("code-server", "0.1.0");

    // Define a secure tool to read code snippets
    let read_code_tool = Tool::new(
        "read_code",
        "Reads a code snippet from a specified file path",
        json!({
            "type": "object",
            "properties": {
                "path": {
                    "type": "string",
                    "description": "The absolute path to the code file"
                }
            },
            "required": ["path"]
        }),
        |args| async move {
            let path = args["path"].as_str().unwrap();

            // Security Check: Ensure the path is within the allowed directory
            let allowed_dir = std::env::current_dir()?.canonicalize()?;
            let resolved_path = std::path::Path::new(path).canonicalize()?;

            if !resolved_path.starts_with(&allowed_dir) {
                return Err("Access denied: Path outside allowed directory".into());
            }

            // Read the file content
            let content = fs::read_to_string(&resolved_path)?;
            Ok(json!({
                "content": content,
                "path": path
            }))
        }
    );

    // Register the tool
    server.register_tool(read_code_tool);

    // Start the server
    server.run().await?;
    Ok(())
}
Enter fullscreen mode Exit fullscreen mode

Step 4: Run and Test

cargo run
Enter fullscreen mode Exit fullscreen mode

This server exposes a read_code tool that allows AI models to read code files, but with a critical security restriction: it only allows access to files within the current directory. This prevents path traversal attacks and limits the scope of the AI’s access.

Best Practices for Securing AI Agent Infrastructure

As you integrate MCP and LSP into your development workflows, consider these best practices:

  1. Principle of Least Privilege: Grant AI agents access only to the resources they need. Use sandboxed environments for MCP servers.
  2. Audit Logs: Implement comprehensive logging for all MCP and LSP interactions. This helps detect unusual activity and debug issues.
  3. Input Validation: Strictly validate all inputs from AI models. Never trust LLM outputs blindly.
  4. Rate Limiting: Prevent abuse by limiting the number of requests an AI agent can make to MCP servers.
  5. Regular Updates: Keep your MCP and LSP libraries up to date to benefit from security patches and performance improvements.

The Future of AI-Driven Development

The convergence of MCP, LSP, and Rust is just the beginning. We can expect to see:

  • Cross-IDE AI Agents: AI agents that work seamlessly across VS Code, IntelliJ, and Neovim by leveraging standardized protocols.
  • Enterprise-Grade Security: Built-in security features in MCP servers, such as OAuth2 authentication and role-based access control (RBAC).
  • Performance Optimizations: Rust-based MCP servers that can handle millions of requests per second, enabling real-time AI assistance at scale.

Frequently Asked Questions

Is MCP compatible with existing LSP servers?

Yes, MCP is designed to be interoperable with LSP. MCP servers can query LSP servers for code intelligence, and LSP clients can use MCP tools for AI-driven features. This integration is facilitated through standardized JSON-RPC messages.

Why is Rust preferred for building MCP servers over Python?

Rust offers better performance, memory safety, and concurrency handling, which are critical for high-throughput, low-latency AI interactions. While Python is popular for AI model development, Rust is better suited for the infrastructure layer that powers these models.

How do I secure my MCP server against malicious prompts?

Implement strict input validation, sandbox the server environment, and limit the tools and resources exposed to the AI model. Regularly audit logs for unusual activity and use rate limiting to prevent abuse.

For more insights on building secure AI infrastructure, check out Tamiz's Insights for the latest trends in developer tooling and AI.

Top comments (0)