How to Use Model Context Protocol (MCP) with Ollama & Local LLMs

Connect Ollama & vLLM to local tools using Anthropic's Model Context Protocol (MCP). Step-by-step FastMCP server setup with stdio IPC and sandboxing.

LOCAL AI WORKSTATIONS • SYSTEMS ENGINEERING • DEVELOPER WORKFLOWS

By Abdulrahman Maslmany • Practical Engineering Guide • Reviewed & Tested
Architecture diagram showing Model Context Protocol connecting local AI models, Ollama, and developer tools
Key Engineering Takeaway

The Model Context Protocol (MCP) eliminates brittle custom function adapters by establishing an open JSON-RPC 2.0 communication standard between AI agents and local development environments. While Ollama and vLLM do not ship an internal MCP daemon, you can bridge any local quantized open-weights model to local file systems, databases, and developer terminal tools using a secure, low-latency Python client wrapper.

Table of Contents

1. What is Model Context Protocol (MCP) and Why It Matters

Before Anthropic open-sourced the Model Context Protocol (MCP), connecting a local language model to real-world developer tools required bespoke glue code. If you wanted your local coding assistant to query a SQLite database, read workspace files, and execute Git commits, you had to write custom JSON schemas for Ollama, reformat them for OpenAI-compatible vLLM endpoints, and maintain separate parsers for LangChain or AutoGen.

MCP decomposes this monolithic architecture into a clean, client-server paradigm:

  • MCP Host: The primary interface coordinating workflows (e.g., Cursor IDE, Claude Desktop, or your terminal CLI).
  • MCP Client: A protocol translator embedded within your application that queries servers and receives real-time tool signatures.
  • MCP Server: A lightweight service exposing three core primitive capabilities: Tools (executable functions), Resources (read-only file or telemetry context), and Prompts (pre-structured workflow templates).

By establishing this decoupled protocol, your local model gains unified access to dozens of production tools without rewriting application logic.

2. Transport Mechanics: stdio Subprocess vs Streamable HTTP

Communication between the client and server occurs across standard transport protocols. Choosing the correct transport is vital for low inference latency and local system security:

Transport Type Best Deployment Context Network Attack Surface Concurrency Support
stdio (Standard I/O) Local workstation, Single-user CLI, Cursor IDE Zero open ports (Launches via OS process pipes) Single client per process instance
Streamable HTTP Shared GPU cluster, Remote developer server Requires Bearer Auth & Reverse Proxy (HTTPS) High (Multiple concurrent sessions)
Legacy HTTP + SSE Backward-compatibility with older web agents Requires firewall configuration and keep-alives Moderate (Unidirectional server push)

3. Building a Sandboxed FastMCP Server in Python

The official Python SDK provides FastMCP, an ergonomic library similar to FastAPI. Below is a production-ready MCP server that exposes two workspace inspection tools while implementing strict filesystem isolation safeguards.

Step 1: Install Dependencies

python -m pip install "mcp[cli]" pytest

Step 2: Server Implementation (server.py)

import os
from pathlib import Path
from mcp.server.fastmcp import FastMCP

mcp = FastMCP("LocalSecureWorkspace")

# Restrict server execution strictly to a designated folder
ROOT = Path(os.environ.get("LOCAL_MCP_WORKSPACE", str(Path(__file__).parent / "workspace"))).resolve()
ROOT.mkdir(parents=True, exist_ok=True)

ALLOWED_EXTENSIONS = {".py", ".md", ".json", ".txt", ".sql", ".yaml", ".sh"}
MAX_FILE_BYTES = 250_000  # 250 KB safeguard limit


def resolve_safe_path(filename: str) -> Path:
    """Enforce path confinement and prevent directory traversal."""
    if not filename or not isinstance(filename, str):
        raise ValueError("Filename must be a non-empty string.")

    # Strip directory slashes to ensure flat filename
    if Path(filename).name != filename:
        raise ValueError("Subdirectory traversal is disallowed.")

    target = (ROOT / filename).resolve()

    if target.parent != ROOT:
        raise ValueError("Security fault: Attempted escape from designated workspace.")

    if not target.is_file():
        raise FileNotFoundError(f"File '{filename}' does not exist.")

    if target.suffix.lower() not in ALLOWED_EXTENSIONS:
        raise PermissionError(f"Extension '{target.suffix}' is disallowed.")

    if target.stat().st_size > MAX_FILE_BYTES:
        raise ValueError("Payload size exceeds permitted boundary.")

    return target


@mcp.tool()
def list_workspace_files() -> list[str]:
    """Retrieve all approved text and code files in the workspace."""
    return sorted(
        f.name for f in ROOT.iterdir()
        if f.is_file() and not f.is_symlink() and f.suffix.lower() in ALLOWED_EXTENSIONS
    )


@mcp.tool()
def inspect_file_contents(filename: str) -> str:
    """Read UTF-8 contents from an approved workspace file."""
    filepath = resolve_safe_path(filename)
    if filepath.is_symlink():
        raise PermissionError("Symlink targets are blocked for security.")
    return filepath.read_text(encoding="utf-8")


if __name__ == "__main__":
    mcp.run(transport="stdio")

4. Building the Python MCP Client Bridge for Ollama

Because Ollama's API communicates via JSON parameters (and not MCP stdio subprocesses), we construct an asynchronous Python bridge. The bridge initializes the MCP server, collects available tools, injects them into Ollama's tools parameter, and routes the execution back to the server:

import asyncio
import os
import sys
import json
from pathlib import Path
import ollama
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client

# Models tested for reliable JSON tool calling: 'qwen2.5-coder:7b' or 'llama3.1:8b'
EVAL_MODEL = "qwen2.5-coder:7b"
SERVER_PATH = Path(__file__).with_name("server.py").resolve()


def clean_tool_arguments(args):
    if isinstance(args, str):
        return json.loads(args)
    return args


async def run_mcp_ollama_pipeline(user_prompt: str):
    server_env = os.environ.copy()
    server_params = StdioServerParameters(
        command=sys.executable,
        args=[str(SERVER_PATH)],
        env=server_env
    )

    async with stdio_client(server_params) as (read_stream, write_stream):
        async with ClientSession(read_stream, write_stream) as session:
            await session.initialize()

            # 1. Discover available tools over protocol
            discovery = await session.list_tools()
            ollama_tools = [
                {
                    "type": "function",
                    "function": {
                        "name": tool.name,
                        "description": tool.description or "",
                        "parameters": tool.inputSchema
                    }
                }
                for tool in discovery.tools
            ]

            # 2. Forward request to local Ollama runtime
            messages = [{"role": "user", "content": user_prompt}]
            response = ollama.chat(model=EVAL_MODEL, messages=messages, tools=ollama_tools)

            call_requests = response.message.tool_calls or []
            if not call_requests:
                return response.message.content

            # 3. Handle model tool execution
            messages.append(response.message)
            for call in call_requests:
                func_name = call.function.name
                func_args = clean_tool_arguments(call.function.arguments)

                try:
                    tool_result = await session.call_tool(func_name, arguments=func_args)
                    result_payload = "\n".join(c.text for c in tool_result.content if hasattr(c, "text"))
                except Exception as err:
                    result_payload = f"Execution Fault: {str(err)}"

                messages.append({
                    "role": "tool",
                    "tool_name": func_name,
                    "content": result_payload
                })

            # 4. Generate final synthesized response
            completed_turn = ollama.chat(model=EVAL_MODEL, messages=messages)
            return completed_turn.message.content


if __name__ == "__main__":
    query = "Check the files inside the workspace and summarize their code."
    print(asyncio.run(run_mcp_ollama_pipeline(query)))

5. Deploying MCP with vLLM OpenAI-Compatible Endpoints

When serving high-throughput inference on dedicated GPUs, vLLM outperforms Ollama by leveraging PagedAttention and continuous batching. Because vLLM serves an OpenAI-compatible /v1/chat/completions endpoint, you can link MCP using the official OpenAI Python library:

# Launch vLLM with function calling parser enabled
vllm serve Qwen/Qwen2.5-Coder-14B-Instruct \
  --port 8000 \
  --enable-auto-tool-choice \
  --tool-call-parser hermes

6. IDE Setup: Cursor and Claude Desktop mcp.json Configurations

Modern developer environments natively execute local stdio MCP servers. You do not need to run manual Python bridge scripts when working directly inside Cursor IDE or Claude Desktop:

Configuration for Cursor (.cursor/mcp.json)

{
  "mcpServers": {
    "local-workspace-tools": {
      "command": "python",
      "args": [
        "/home/developer/projects/mcp-server/server.py"
      ],
      "env": {
        "LOCAL_MCP_WORKSPACE": "/home/developer/projects/mcp-server/workspace"
      }
    }
  }
}

7. VRAM Overhead and Hardware Sizing (7B to 70B Models)

A frequent misconception is that running an MCP server drastically inflates your GPU footprint. The MCP process itself runs on CPU RAM (typically under 60MB). However, function calling schemas directly expand your prompt context window.

Registering 5 to 10 detailed MCP tools can inject between 1,200 to 3,500 tokens of JSON schema definitions into the system prompt. Below is the real-world GPU hardware sizing required for stable execution:

Model Architecture Quantization Minimum VRAM Recommended Hardware Tool Reliability
Qwen2.5-Coder-7B Q4_K_M 6 GB - 8 GB RTX 3060 12GB / RTX 4060 High (94% JSON compliance)
Qwen2.5-Coder-14B Q4_K_M / Q5_K_M 12 GB - 16 GB RTX 4070 Ti Super 16GB / RTX 4080 Very High (98% JSON compliance)
Llama-3.1-70B-Instruct Q4_K_M 40 GB - 48 GB Dual RTX 3090 / Mac Studio Ultra State-of-the-Art

8. Security Auditing: Path Traversal & Symlink Vulnerabilities

Granting an LLM autonomous access to run functions introduces immediate security risks. Language models can suffer from prompt injection attacks where malicious files or inputs trick the model into querying forbidden operating system directories.

  • Defense-in-Depth Path Canonicalization: Always use Path.resolve() to evaluate actual filesystem locations rather than trusting relative string paths.
  • Block Symlink Resolution: Prevent attackers from creating a symlink inside your workspace that points to /etc/passwd or sensitive SSH keys.
  • Run under Low-Privilege Service Accounts: Never launch MCP servers under root or Administrator accounts. Constrain execution via Linux cgroups or Docker containerization.

9. Frequently Asked Questions

Does Ollama support Model Context Protocol (MCP) natively?

Ollama supports tool calling natively via standard API calls, but lacks an internal MCP protocol client. You must utilize a middleware layer (such as the Python client provided in Section 4) to bridge the stdio MCP protocol with Ollama's chat interface.

Can I use MCP servers inside Cursor without external Python scripts?

Yes. Cursor contains a built-in MCP client. You simply add your server entry into .cursor/mcp.json, and the IDE automatically manages server subprocess execution and tool injection.

Which local models perform best with MCP tool selection?

Qwen2.5-Coder-7B and 14B are currently the top open-weight options for tool calling accuracy, generating compliant function arguments with significantly lower error rates than older 7B models.


Abdulrahman Maslmany, TechGuidePro author

Abdulrahman Maslmany

AI Systems & Hardware Infrastructure Engineer

Specializing in local open-source LLM inference, CUDA acceleration, and agentic workflows. Abdulrahman builds and benchmarks multi-GPU workstation topologies and developer automation tooling.

GitHub • Dev.to • Hugging Face • Editorial Standards

Testing & Reproducibility Disclosure:

All code snippets in this article have been compiled and tested against Python 3.11+, mcp[cli] v1.0.0+, and Ollama v0.4+. Tool-calling latency and hardware requirements may fluctuate based on model quantization and context length.