WIPIVERSE All articles

NEPOMUK (software)

Overview

Ollama MCP Bridge is a Python-based API proxy service that bridges Ollama (local LLM server) with MCP (Model Context Protocol) servers. It acts as a drop-in replacement for the Ollama API, transparently injecting tools from multiple MCP servers into every /api/chat request.

Version: 0.9.3.dev1
License: MIT
Author: Jonathan Gastón Löwenstern


Architecture

┌─────────────┐     ┌──────────────────┐     ┌─────────────┐
│   Client    │────▶│ Ollama MCP Bridge │────▶│   Ollama    │
│ (curl/UI)   │     │  (FastAPI Proxy)  │     │  (LLM API)  │
└─────────────┘     └────────┬─────────┘     └─────────────┘
                             │
                    ┌────────▼────────┐
                    │   MCP Servers   │
                    │  (Tools via     │
                    │   stdio/HTTP)   │
                    └─────────────────┘

Project Structure

/app/
├── pyproject.toml              # Project config, dependencies, build
├── README.md                   # Full documentation
├── mcp-config.json             # MCP server configuration
├── Dockerfile                  # Docker build
├── docker-compose.yml          # Docker Compose setup
├── CI.md / CONTRIBUTING.md     # Dev docs
│
├── src/ollama_mcp_bridge/      # Main package
│   ├── __init__.py             # Package init, version import
│   ├── _version.py             # Auto-generated version
│   ├── main.py                 # CLI entry point (Typer)
│   ├── api.py                  # FastAPI application
│   ├── mcp_manager.py          # MCP server connections & tool management
│   ├── proxy_service.py        # Ollama proxy with tool integration
│   ├── lifecycle.py             # FastAPI lifespan (startup/shutdown)
│   ├── schemas.py              # API examples
│   └── utils.py                # Utilities (health, CORS, version check, env expansion)
│
├── tests/                      # Test suite
│   ├── conftest.py             # Pytest fixtures
│   ├── test_unit.py            # Unit tests (no external deps)
│   ├── test_api.py             # Integration tests (require running server)
│   ├── test_tool_filtering.py  # Tool filtering tests
│   ├── test_error_handling.py  # Error handling tests
│   ├── test_env_expansion.py   # Env var expansion tests
│   └── test_ollama_proxy_timeout_env.py  # Timeout config tests
│
├── mock-weather-mcp-server/    # Example MCP server
│   └── main.py                 # Simple weather tool
│
└── mcp_servers/                # Additional MCP servers
    └── web-search-mcp.py

Key Components

1. main.py - CLI Entry Point

  • Uses Typer for CLI with options: --config, --host, --port, --ollama-url, --max-tool-rounds, --system-prompt, --reload, --version
  • Validates inputs, checks port availability, verifies Ollama health
  • Stores config in app.state for the FastAPI lifespan to access

2. api.py - FastAPI Application

  • GET /health - Health check (Ollama status + tool count)
  • POST /api/chat - The only endpoint with MCP tool integration - injects all tools, handles multi-round tool execution
  • GET /version - Version info + update check
  • /{path_name} - Transparent proxy for all other Ollama endpoints (e.g., /api/tags, /api/generate)

3. mcp_manager.py - MCP Server Management

  • load_servers(config_path) - Reads JSON config, connects to all MCP servers
  • _connect_server(name, config) - Connects via:
    • stdio (local processes) - command + args + env
    • StreamableHTTP - url (default for remote URLs)
    • SSE - url ending with /sse
  • call_tool(tool_name, arguments) - Executes a tool on the appropriate MCP server
  • Tool Filtering - Include/exclude modes per server
  • Tool names are prefixed with server name: {server}.{tool_name}

4. proxy_service.py - Ollama Proxy Logic

  • proxy_chat_with_tools() - Main chat handler (streaming + non-streaming)
  • Multi-round tool execution loop:
    1. Sends messages + tools to Ollama
    2. Checks response for tool_calls
    3. If tool calls found, executes them via MCP manager
    4. Feeds results back to Ollama
    5. Repeats until no more tool calls or max rounds reached
  • _maybe_prepend_system_prompt() - Prepends system prompt if configured
  • proxy_generic_request() - Transparent proxy for all other endpoints

5. lifecycle.py - FastAPI Lifespan

  • Startup: Initializes MCPManager, loads servers, creates ProxyService
  • Shutdown: Cleans up HTTP clients and MCP sessions
  • Global singletons: mcp_manager, proxy_service

6. utils.py - Utilities

  • get_ollama_proxy_timeout_config() - Reads OLLAMA_PROXY_TIMEOUT env var (in ms)
  • is_port_in_use() - Port availability check
  • configure_cors() - CORS middleware from CORS_ORIGINS env var
  • check_ollama_health() - Sync/async health checks
  • iter_ndjson_chunks() - NDJSON streaming parser
  • check_for_updates() - PyPI version check
  • expand_env_vars() / expand_dict_env_vars() - ${env:VAR} and ${workspaceFolder} expansion
  • validate_cli_inputs() - CLI input validation

Configuration (mcp-config.json)

{
  "mcpServers": {
    "server_name": {
      "command": "uv",           // For stdio transport
      "args": ["run", "..."],
      "env": {"KEY": "value"},
      "toolFilter": {            // Optional filtering
        "mode": "include|exclude",
        "tools": ["tool_name"]
      }
    },
    "remote_server": {
      "url": "https://...",      // StreamableHTTP (default) or SSE (/sse suffix)
      "headers": {"X-Key": "value"}
    }
  }
}

Key Features

Feature Description
Multi-transport stdio, StreamableHTTP, SSE
Tool Filtering Include/exclude modes per server
Multi-round execution Automatic loop until completion
Streaming Real-time NDJSON streaming
System Prompt Configurable via CLI/env
CORS Configurable origins
Timeout Configurable Ollama request timeout
Version Check Automatic PyPI update check
Env Expansion ${env:VAR} and ${workspaceFolder} in config
Cloud Models Works with Ollama cloud via OLLAMA_API_KEY

Dependencies

Package Version Purpose
fastapi ~0.119.0 Web framework
httpx ~0.28.0 Async HTTP client
loguru ~0.7.3 Structured logging
mcp >=1.9.4,<2.0.0 MCP protocol client
typer ~0.20.0 CLI framework
uvicorn ~0.38.0 ASGI server
packaging >=25.0 Version comparison

Test Coverage

Test File Type What It Tests
test_unit.py Unit Config loading, imports, tool structure, CLI validation, port checking, system prompt
test_api.py Integration Health endpoint, chat endpoint, tags proxy
test_tool_filtering.py Unit Include/exclude modes, case sensitivity, missing tools, config validation
test_error_handling.py Unit Invalid JSON, missing config keys, connection failures
test_env_expansion.py Unit ${env:VAR} and ${workspaceFolder} expansion
test_ollama_proxy_timeout_env.py Unit Timeout env var parsing, HTTP client construction

Current MCP Servers in Config

  1. filesystem - @modelcontextprotocol/server-filesystem (npx) - Excludes delete_file, write_file
  2. web_search_and_fetch - Custom Python MCP server (uv run)
  3. duckduckgo - duckduckgo-mcp-server (uvx)

This is a mature, well-architected project with clean separation of concerns, comprehensive testing, and thorough documentation. It effectively bridges the gap between local LLMs (Ollama) and the growing MCP ecosystem of tool servers.

Browse

More topics to explore

    Browse all articles