Skip to main content

Overview

The Ollama TypeScript client demonstrates how to integrate local language models with MCP tools, enabling LLMs to execute server-side functions. This creates a powerful agentic system where the model can autonomously call tools to accomplish tasks.

Source Code

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

Prerequisites

  • Node.js (v16 or higher)
  • Ollama installed and running
  • A compatible LLM model (e.g., mistral:latest, llama3:latest)
  • An MCP server

Installation

Package Configuration

Architecture

The implementation consists of three main components:
  1. MCPClient: Manages connection to MCP servers and tool execution
  2. OllamaAPIClient: Handles communication with the Ollama API
  3. OllamaAgent: Orchestrates the interaction between Ollama and MCP tools

MCP Client Implementation

Class Structure

Connecting to MCP Server

Listing and Executing Tools

Ollama API Client

Creating the Client

Chat with Function Calling

Processing Responses

Tool Manager

The ToolManager converts MCP tools to Ollama’s function calling format:

Ollama Agent

Initialization

Executing MCP Tools

Function Execution Flow

Execute Function Handler

Processing Function Calls

Interactive Chat

Running the Application

Main Entry Point

Build and Start

Environment Variables

Message Roles

Best Practices

  1. Error Handling: Always wrap MCP tool calls in try-catch blocks
  2. Logging: Use structured logging for debugging function calls
  3. Model Selection: Use models that support function calling (Mistral, Llama 3 70B)
  4. Tool Naming: Prefix MCP tools with mcp_ to avoid conflicts
  5. Resource Cleanup: Always call cleanup() in the finally block

Troubleshooting

Ollama not responding

MCP connection errors

  • Verify the server path is correct
  • Check that the MCP server is compiled
  • Ensure Node.js can execute the server

Function calling not working

  • Verify your model supports function calling
  • Check tool definitions are properly formatted
  • Review message history for proper structure

Next Steps