Skip to main content

Ollama Integration with MCP

This guide shows how to integrate MCP (Model Context Protocol) servers with Ollama to enable function calling capabilities with local language models.

Overview

The Ollama integration allows you to:
  • Connect to MCP servers and expose their tools to Ollama models
  • Use local LLMs with function calling capabilities
  • Build interactive chat applications with tool support

Prerequisites

  • Ollama installed and running locally
  • Node.js 16+ (for TypeScript implementation)
  • Python 3.13+ (for Python implementation)
  • An MCP server running (e.g., the Game of Thrones quotes server)

TypeScript Implementation

Installation

First, install the required dependencies:
package.json

MCP Client Setup

Create a reusable MCP client to connect to MCP servers:
src/mcpClient.ts

Ollama API Client

Create a client to communicate with Ollama’s API:
src/ollamaClient.ts

Integrating MCP Tools with Ollama

The key is converting MCP tools to Ollama’s function calling format:
src/ollamaAgent.ts

Function Execution

Handle function calls from Ollama:

Python Implementation

Installation

Create a pyproject.toml file:
pyproject.toml
Install dependencies:

MCP Client

mcp_client.py

Ollama API Client

ollama_client.py

Python Agent

agent.py

Usage Example

Interactive Chat

Running the Application

TypeScript

Python

Key Concepts

  1. Tool Conversion: MCP tools are prefixed with mcp_ and converted to Ollama’s function format
  2. Bidirectional Communication: The agent handles both normal chat and function calls
  3. Recursive Processing: Function calls can trigger additional function calls
  4. State Management: Messages history maintains context across tool executions

Troubleshooting

  • Ensure Ollama is running: ollama serve
  • Check that your model supports function calling (e.g., mistral, llama3.1)
  • Verify MCP server path is correct
  • Check that all dependencies are installed

Next Steps