Skip to main content

Overview

The Ollama Python client integrates local language models with MCP tools, enabling LLMs to autonomously execute server-side functions. This creates a powerful agentic system for building AI applications with tool-calling capabilities.

Source Code

The implementation can be found at ~/workspace/source/clients/ollama-py/.

Prerequisites

  • Python 3.11 or higher
  • Ollama installed and running
  • A compatible LLM model (e.g., mistral:latest)
  • An MCP server

Installation

Using pip

Architecture

The implementation consists of four main components:
  1. MCPClient: Manages MCP server connections and tool execution
  2. OllamaAPIClient: Handles Ollama API communication
  3. ToolManager: Converts MCP tools to Ollama format
  4. OllamaAgent: Orchestrates LLM and tool interactions

MCP Client Implementation

Class Structure

Connecting to MCP Server

Tool Operations

Context Manager Support

Ollama API Client

Client Implementation

Chat with Tools

Response Processing

Tool Manager

Ollama Agent

Agent Class

Setup and Context Manager

Tool Execution

Function Execution Flow

Execute Function Handler

Processing Function Calls

Interactive Chat

Main Application

Running the Application

Set Environment Variables

Run the Application

Configuration

Best Practices

  1. Use Context Managers: Always use async with for proper cleanup
  2. Error Handling: Wrap tool calls in try-except blocks
  3. Logging: Use the logging module instead of print statements
  4. Type Hints: Include type hints for better IDE support
  5. Model Selection: Use models with function calling support

Troubleshooting

Ollama Connection Issues

MCP Connection Errors

  • Verify server path in environment variable
  • Check that Node.js is installed
  • Ensure MCP server is properly compiled

Function Calling Not Working

  • Use models that support function calling (Mistral, Llama 3 70B)
  • Check tool definitions are properly formatted
  • Verify message history structure

Next Steps