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:- MCPClient: Manages connection to MCP servers and tool execution
- OllamaAPIClient: Handles communication with the Ollama API
- 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
- Error Handling: Always wrap MCP tool calls in try-catch blocks
- Logging: Use structured logging for debugging function calls
- Model Selection: Use models that support function calling (Mistral, Llama 3 70B)
- Tool Naming: Prefix MCP tools with
mcp_to avoid conflicts - 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
- Explore Python + Ollama integration
- Learn about basic TypeScript client
- Build custom MCP tools for your use case