MCP Server for Ollama at a Glance
An MCP server for Ollama is a lightweight program that exposes tools through the Model Context Protocol for an Ollama model to call.
People searching for this usually want one of two different setups. Pick yours first, because the steps do not overlap.
| Goal | Who is the MCP client | Who is the MCP server | Covered in |
|---|---|---|---|
| Give a local Ollama model tools such as disk checks, files or APIs | ollmcp or your own Python bridge | Your MCP server, for example the one built below | Most of this guide |
| Let Claude Desktop or another assistant use your local Ollama models | Claude Desktop, Cline or a similar app | An Ollama MCP server such as ollama-mcp | The Claude Desktop section |
This guide builds a working, read only MCP server in Python, checks it without any model, connects it to Ollama two ways and then covers the security limits. Every output block was captured on the test machine named in the tested line above.
What an MCP Server for Ollama Does
An MCP server for Ollama lists tools with a name, a description and a JSON Schema, then runs a tool when a client asks it to.
The Model Context Protocol (MCP) is an open protocol that carries JSON-RPC messages between a client and a server. The specification defines two standard transports. With stdio, the client launches the server as its own child process and the two exchange messages through standard input and output. With Streamable HTTP, the server is a separate long running process that replies to HTTP requests. Streamable HTTP replaced the older HTTP plus SSE transport, which is why tutorials built on SSE now look dated.
Tool calling is the Ollama side. You send /api/chat a list of tools, and a model that supports it can answer with a tool_calls entry instead of text. Your program then executes that tool and returns its output in a new message whose role is tool.
The MCP client joins the two. In practice the flow looks like this.
- DiscoverThe client sends
tools/listto the MCP server and gets each tool with its input schema. - OfferThe client passes those tools to Ollama in the
toolsfield of a chat request. - DecideThe model either answers in text or returns a tool call with arguments.
- RunThe client issues
tools/call, and the MCP server checks the arguments before executing the tool. - AnswerThe client adds the result to the chat and asks the model again, until it answers in text.
In this design the model does not touch your system directly. Whatever a tool can do, the model can ask for, so the safety of the whole setup rests on which tools the server offers and what the client lets through.
Choose an Ollama MCP Setup
Choose an Ollama MCP setup by who should hold the controls, a ready made client, your own code or another assistant.
| Option | Best for | Effort | Asks before running a tool |
|---|---|---|---|
| ollmcp (MCP Client for Ollama) | An interactive terminal agent for one or more MCP servers over stdio, SSE or Streamable HTTP, with tool approvals, prompts and resources | Low, one config file or one command per server | Yes by default, with an optional session or permanent bypass |
| Your own Python bridge | Scripts, automation and full control over every call | Medium, about 45 lines | Only if you add a prompt |
| ollama-mcp in Claude Desktop or Cline | Letting another assistant use your local models as tools | Low, one JSON entry | Depends on the app |
ollama launch with a coding agent or editor | Tools such as Claude Code, Codex, OpenCode, VS Code or Droid that run on Ollama models and keep their own MCP settings | Low | Depends on the tool |
The current Ollama CLI documentation lists OpenCode, Claude Code, Codex, VS Code and Droid integrations. Which integrations are available depends on the installed Ollama version. If your version has the launch command, run ollama launch --help to see its options. Older versions may not have this command. In that setup the launched tool is the MCP client, so you register MCP servers in that tool, not in Ollama.
Prerequisites and Tool Capable Ollama Models
The prerequisites are a running Ollama, a model with the tools capability and Python 3.10 or newer for the MCP server.
The MCP server and the bridge below run on Python 3.10 or newer with the SDK version shown. The ollmcp client separately needs Python 3.11 or newer.
The steps apply to Ubuntu 22.04 and 24.04 and other Linux systems that run Ollama. They also work on macOS with the same commands, apart from the systemd part. You need a shell account that can install Python packages in a virtual environment. Root is not needed for anything below except editing the Ollama service.
| Component | Version used | Note |
|---|---|---|
| Operating system | Ubuntu 24.04.5 LTS | 2 vCPUs, 7.8 GB RAM, CPU only |
| Ollama | 0.40.19 | Run on port 11634 because other services shared the machine |
| Model | qwen2.5:1.5b | 986 MB download, Q4_K_M |
| Python | 3.13.18 | The MCP SDK needs 3.10 or newer, ollmcp needs 3.11 or newer |
| MCP Python SDK | 2.3.0 | Package name mcp |
| ollama Python library | 0.6.4 | Package name ollama |
| ollmcp | 0.35.1 | Optional, for the ready made client |
Check That the Model Supports Tools
Check that the model supports tool calling with ollama show. The Ollama bridge needs a model that lists the tools capability to pass MCP tools to it.
ollama pull qwen2.5:1.5b
ollama show qwen2.5:1.5b Model
architecture qwen2
parameters 1.5B
context length 32768
embedding length 1536
quantization Q4_K_M
Capabilities
completion
toolsIf a model does not advertise the tools capability, Ollama rejects tool definitions for it. This is the real error from the tested version for a small model that only lists completion.
{"error":"registry.ollama.ai/library/smollm:135m does not support tools"}A small model is enough to prove the bridge works, but tool choice and argument accuracy vary between models. A tools line does not guarantee reliable tool selection. Before moving to a larger model, check its download size with ollama list, the free RAM on the machine, its context length and how fast it runs on your CPU or GPU.
Build the MCP Server in Python
Build the MCP server in Python with the official mcp package, inside its own virtual environment so versions stay fixed.
mkdir -p ~/mcp-ollama && cd ~/mcp-ollama
uv venv .venv
. .venv/bin/activate
uv pip install "mcp==2.3.0" "ollama==0.6.4"If you do not use uv, python3 -m venv .venv followed by pip install does the same job. On Ubuntu that needs the python3-venv package first.
Save this as server.py. It offers two read only tools. disk_usage only accepts paths on an allowlist, and load_average reads the system load.
import os
import shutil
from mcp.server import MCPServer
from mcp.server.mcpserver.exceptions import ToolError
ALLOWED = {"/", "/home", "/var"}
mcp = MCPServer("vps-tools")
@mcp.tool()
def disk_usage(path: str = "/") -> str:
"""Report used and free disk space for one allowed filesystem path."""
if path not in ALLOWED:
raise ToolError(f"Refused. Allowed paths: {', '.join(sorted(ALLOWED))}")
u = shutil.disk_usage(path)
gb = 1024 ** 3
return f"{path}: {u.used / gb:.1f} GB used, {u.free / gb:.1f} GB free of {u.total / gb:.1f} GB"
@mcp.tool()
def load_average() -> str:
"""Return the 1, 5 and 15 minute load averages of this server."""
one, five, fifteen = os.getloadavg()
return f"load average {one:.2f} {five:.2f} {fifteen:.2f} on {os.cpu_count()} CPUs"
if __name__ == "__main__":
mcp.run()This allowlist restricts which path strings the tool accepts. It is not a filesystem sandbox. Run MCP servers under a dedicated account without root and give that account access only to the data its tools need.
The refusal raises ToolError, which the SDK returns as a tool execution error with is_error: True. The MCP specification reports such failures in the result with isError, and the message tells the model why the call failed so it can correct its arguments.
With no arguments mcp.run() uses the stdio transport, so the client starts the server itself and you do not run it in a separate terminal. With stdio, anything printed to standard output that is not an MCP message breaks the connection. Send debug output to standard error, for example with print(..., file=sys.stderr) or the logging module.
Test the MCP Server Without a Model
Test the MCP server without a model first, so a server bug is never mistaken for a model that ignores its tools.
This short client, saved as list_tools.py, starts the server, lists its tools and calls one directly with a path that should be refused.
import asyncio
import sys
from mcp import Client, StdioServerParameters
SERVER = StdioServerParameters(command=sys.executable, args=["server.py"])
async def main() -> None:
async with Client(SERVER) as client:
print("server:", client.server_info.name, "protocol:", client.protocol_version)
for tool in (await client.list_tools()).tools:
print(tool.name, tool.input_schema.get("properties", {}))
result = await client.call_tool("disk_usage", {"path": "/etc"})
print("call disk_usage /etc -> is_error:", result.is_error, result.content[0].text)
asyncio.run(main())python list_tools.pyserver: vps-tools protocol: 2026-07-28
disk_usage {'path': {'default': '/', 'title': 'Path', 'type': 'string'}}
load_average {}
Tool 'disk_usage' failed: 'Error executing tool disk_usage: Refused. Allowed paths: /, /home, /var'
call disk_usage /etc -> is_error: True Error executing tool disk_usage: Refused. Allowed paths: /, /home, /varThree things are confirmed here. The server starts and agrees on protocol version 2026-07-28, both tools are listed with their schemas, and the allowlist blocks /etc with is_error: True. The line starting with Tool is the server log on standard error, which the terminal shows next to the client output.
A pass proves the server and its tools work. It does not prove a model will call them well, which is the next step.
Connect the MCP Server to an Ollama Model
To connect the MCP server to an Ollama model, a bridge script acts as the MCP client and feeds the tools to Ollama chat.
Save this as bridge.py. It converts each MCP tool into the Ollama tool format, runs the chat in a loop and stops after five rounds so a confused model cannot loop forever.
import asyncio
import sys
from mcp import Client, StdioServerParameters
from ollama import AsyncClient
MODEL = "qwen2.5:1.5b"
SERVER = StdioServerParameters(command=sys.executable, args=["server.py"])
async def main(question: str) -> None:
ollama = AsyncClient()
async with Client(SERVER) as mcp:
listed = await mcp.list_tools()
tools = [
{
"type": "function",
"function": {
"name": t.name,
"description": t.description or "",
"parameters": t.input_schema,
},
}
for t in listed.tools
]
print("MCP tools:", [t.name for t in listed.tools])
messages = [{"role": "user", "content": question}]
for _ in range(5):
resp = await ollama.chat(model=MODEL, messages=messages, tools=tools)
messages.append(resp.message)
if not resp.message.tool_calls:
print("Answer:", resp.message.content)
return
for call in resp.message.tool_calls:
name, args = call.function.name, dict(call.function.arguments)
print(f"Tool call: {name} {args}")
result = await mcp.call_tool(name, args)
text = "".join(c.text for c in result.content if c.type == "text")
if result.is_error:
text = "Tool error: " + text
print("Tool result:", text)
messages.append({"role": "tool", "tool_name": name, "content": text})
print("Stopped after 5 rounds")
asyncio.run(main(" ".join(sys.argv[1:]) or "What is the load average on this server?"))The script talks to Ollama at its default address. To reach another host or port, set OLLAMA_HOST before running it, as this test did for port 11634.
export OLLAMA_HOST=127.0.0.1:11634
python bridge.py "What is the load average on this server?"
python bridge.py "How much disk space is used under /etc?"MCP tools: ['disk_usage', 'load_average']
Tool call: load_average {}
Tool result: load average 2.44 3.32 3.49 on 2 CPUs
Answer: The current load average on your server is 2.44 (1-minute), 3.32 (5-minute), and 3.49 (15-minute). This indicates a somewhat stable but slightly busy system.
MCP tools: ['disk_usage', 'load_average']
Tool call: disk_usage {'path': '/etc'}
Tool result: Tool error: Error executing tool disk_usage: Refused. Allowed paths: /, /home, /var
Answer: There seems to be an issue with the tool. Allowed paths are /, /home, and /var. Please try again with one of those paths.The model picked the right tool both times, passed /etc as the argument and explained the refusal instead of making up a number. The tool results are exact. The wording of the answers comes from the model and changes from run to run.
The Tool call line is your audit trail. Hold on to it or write it to a log file, so you have a record of each request the model made and the arguments it passed.
Use ollmcp as a Ready Made Ollama MCP Client
ollmcp is a ready made Ollama MCP client for the terminal that loads servers from a JSON file and asks before each tool call.
uv tool install --upgrade ollmcp
ollmcp --versionollmcp 0.35.1That is the install the ollmcp README recommends. The test installed the same package into its own virtual environment with uv pip install ollmcp, which works too.
Describe the server in servers.json. Use absolute paths, and point command at the Python inside the virtual environment so the mcp package is found.
{
"mcpServers": {
"vps-tools": {
"command": "/root/mcp-ollama/.venv/bin/python",
"args": ["/root/mcp-ollama/server.py"]
}
}
}ollmcp -j servers.json -m qwen2.5:1.5b -H http://127.0.0.1:11634Connecting to server: vps-tools
Successfully connected to vps-tools with 2 tool(s)
Current model: qwen2.5:1.5b (ollama)
qwen2.5/2-tools❯ What is the load average on this server?
Executing Tool vps-tools.load_average
Human-in-the-Loop Confirmation
Tool to execute: vps-tools.load_average
Arguments: None
y/yes - Execute the tool call
n/no - Skip this tool call
s/session - Execute without asking for this session
d/disable - Disable HIL confirmations permanently
load average 3.23 3.41 3.52 on 2 CPUs
The load average on this server is 3.23 for the last minute, 3.41 for the next
5 minutes, and 3.52 for the next 15 minutes. There are 2 CPUs available.The tool result is correct, but the model wording is not. Load averages are trailing averages for the past 1, 5 and 15 minutes, not forecasts. Small models can paraphrase tool output loosely, so trust the tool result line over the prose.
The human in the loop prompt is the main reason to pick ollmcp. Each call is shown to you with its arguments, and nothing executes until you press y. Leave it on for any server whose tools can change files, call paid APIs or send data out. Without -H ollmcp uses the default Ollama address on port 11434.
Add More MCP Servers to ollmcp
To add more MCP servers to ollmcp, register each one with ollmcp mcp add, and the client offers the tools of all of them to the model.
ollmcp mcp add vps-tools -- /root/mcp-ollama/.venv/bin/python /root/mcp-ollama/server.py
ollmcp mcp listAdded MCP server 'vps-tools' to local scope
(/root/.config/ollmcp/mcp.local.json)
local (/root/.config/ollmcp/mcp.local.json)
vps-tools: /root/mcp-ollama/.venv/bin/python
/root/mcp-ollama/server.pyThe default local scope wrote to ~/.config/ollmcp/mcp.local.json in this test. In a separate test, --scope project wrote a .mcp.json file in the current folder, which you can share with a project, and the help also lists a --scope user option.
A remote server uses --transport http with its URL, and --header adds an authentication header. This form follows the built in help and was not run against a live server. The URL and token are placeholders.
ollmcp mcp add --transport http --header "Authorization: Bearer YOUR_TOKEN" remote-tools https://mcp.example.com/mcpRun ollmcp mcp remove with the name to delete an entry. Every extra server adds tool definitions to each request, so connect only the ones a task needs.
Expose Ollama to Claude Desktop With an MCP Server
To expose Ollama to Claude Desktop, add an Ollama MCP server such as ollama-mcp to the app config so it can call your local models.
This is the reverse direction. Claude Desktop is the MCP client, ollama-mcp is the MCP server and your Ollama install does the work. The project README gives this entry for claude_desktop_config.json. It was not run in this test.
In Claude Desktop, Settings then Developer then Edit Config opens or creates the file. The MCP documentation gives its location as ~/Library/Application Support/Claude/claude_desktop_config.json on macOS, %APPDATA%\Claude\claude_desktop_config.json on Windows and ~/.config/Claude/claude_desktop_config.json on Linux. Keep any mcpServers entries already in it. npx needs Node.js and npm, and the ollama-mcp README asks for Node.js 16 or newer.
{
"mcpServers": {
"ollama": {
"command": "npx",
"args": ["-y", "ollama-mcp"],
"env": {
"OLLAMA_HOST": "http://127.0.0.1:11434"
}
}
}
}Quit the app completely and start it again after saving. The README lists tools to list, show, pull, push, copy, create and delete models, as well as chat, generate and embed. That means the assistant can delete or push models, so keep the app approval prompts on.
npx -y fetches the newest published version each time it starts. For a stable setup, pin a version you have reviewed, written as ollama-mcp@ followed by the version number. The package is licensed AGPL-3.0, which matters if you plan to change and host it for others.
Run Ollama and MCP on a VPS
Running Ollama and MCP on a VPS keeps your models and tools online, so keep both on localhost and reach them over SSH.
Ollama binds to 127.0.0.1 on port 11434 by default, according to its FAQ. On the test machine the listener looked like this.
ss -ltn 'sport = :11634'State Recv-Q Send-Q Local Address:Port Peer Address:PortProcess
LISTEN 0 4096 127.0.0.1:11634 0.0.0.0:*On a default install use :11434 in the filter. 127.0.0.1 under Local Address means only programs on the server can connect. If it shows 0.0.0.0 or *, the API is reachable from the network, and the FAQ describes no login for the local API. Anyone who reaches the port could run your models or pull and delete them.
If Ollama runs as the systemd service, set its address with systemctl edit ollama.service, then reload and restart, as the Ollama FAQ describes.
[Service]
Environment="OLLAMA_HOST=127.0.0.1:11434"sudo systemctl daemon-reload
sudo systemctl restart ollamaTo use the server from your own computer, forward the port over SSH instead of opening it. The address is a documentation example, so replace it with your server address.
ssh -N -L 11434:127.0.0.1:11434 user@203.0.113.10While that runs, http://127.0.0.1:11434 on your computer reaches Ollama on the VPS through the encrypted tunnel. A stdio MCP server needs no port at all, because the client starts it on the same machine.
If the MCP server runs on a different machine from the client, use Streamable HTTP with authentication instead of an open endpoint, and give the client the server MCP endpoint URL and the header it needs. When the server only has to run next to Ollama and the client on the same VPS, stdio is simpler and opens no port. Set up SSH key login before you rely on the tunnel.
Model size decides the plan. The 1.5B model in this test ran on 2 vCPUs without a GPU, and the Ollama CPU benchmarks show what to expect from larger models on a CPU. An AI VPS for Ollama with dedicated resources gives you root access to set this up the same way.
Ollama MCP Security Limits
Ollama MCP security limits come from the tools you expose, because a model can request anything a tool allows.
Under the MCP specification, a server has to check tool inputs, enforce access controls, limit how often tools are called and clean up what they return. The specification also expects a person to be able to review and refuse tool calls. These measures help, and none of them is complete on its own.
| Safeguard | What it does | What it does not do |
|---|---|---|
| Read only tools | Prevents writes through those particular tools | Prevent reads of sensitive data, or changes through other tools in the same session |
| Allowlist of paths or values | Refuses arguments outside the list, as with /etc above | Protect what is inside the allowed paths |
| Human approval, as in ollmcp | Lets you see and block each call before it runs | Help if you approve calls without reading them |
| Ollama on 127.0.0.1 | Keeps the model API off the network | Protect against other users or programs on the same server |
| Origin check and localhost bind for HTTP servers | Blocks DNS rebinding from web pages, as the MCP transport spec requires | Replace real authentication for remote access |
| Pinned package versions | Stops an unreviewed update from changing your tools | Fix flaws in the version you pinned |
Prompt injection is the risk that is hardest to see. Text a tool returns, such as a web page or a log file, can contain instructions that the model then follows. For example, a tool that reads private files plus another that sends HTTP requests could leak those files if a document tells the model to post them somewhere. Keep secrets out of tool results, limit the network access of the server and require approval before any action that sends data out.
For an MCP server over Streamable HTTP, the transport specification requires the server to check the Origin header, and recommends listening on 127.0.0.1 for local use and authenticating every connection. SDK 2.x turns on DNS rebinding protection for localhost by default. Avoid tools that run free form shell commands, because no allowlist can cover what a shell can do.
Troubleshoot Ollama MCP Problems
Most Ollama MCP problems are a model without tool support, a server that cannot start or a client pointed at the wrong address.
| What you see | Likely cause | Fix |
|---|---|---|
does not support tools | The model has no tools capability | Check ollama show and switch to a model that lists tools |
No module named mcp.server.fastmcp | Code written for SDK 1.x on SDK 2.x | Import MCPServer from mcp.server, or pin an mcp release below version 2 to keep the 1.x API |
| Client connects then fails with JSON errors | The server prints to standard output on stdio | Log to standard error instead |
Connection refused to Ollama | Ollama is not running or listens on another port | Start it and check the address with ss -ltn, then set OLLAMA_HOST |
| Server not found when the client starts | Relative path or a Python without the mcp package | Use absolute paths and the virtual environment Python |
| Model answers without calling a tool | Vague tool description or a weak model | Describe each tool in one clear sentence, ask more directly or use a larger model |
| Model invents tool arguments | Small model or a loose schema | Use typed parameters and reject anything off the allowlist |
| Answers get cut or tools are ignored with many servers | Tool definitions fill the context window | Offer fewer tools or raise the context length, the tested CPU setup defaulted to 4096 tokens |
The context default comes from the Ollama server log on the test machine, which reported default_num_ctx=4096 for a machine with no GPU memory. Check your own log, because the default depends on the hardware and the version.
Questions people ask
Can Ollama support MCP?
Yes, through a client. Ollama provides tool calling, and an MCP client such as ollmcp or a Python bridge connects it to MCP servers.
Does Ollama have a built in MCP client?
Not in version 0.40.19 tested here. Its command list has no MCP command, so a separate client starts and talks to the MCP servers.
How do I run an MCP server with Ollama?
Write or install an MCP server and check that it lists its tools. Then start ollmcp with a tool capable model and that server in its config.
Does an MCP server run locally?
It can. A stdio server always lives on the client machine, because the client is what launches it. A Streamable HTTP server can run locally or remotely.
How do I run Ollama as a server?
Run ollama serve, or let the Linux installer set it up as a systemd service. It listens on 127.0.0.1 port 11434 by default.
Which Ollama models work with MCP tools?
Models that list tools under Capabilities in ollama show, such as Qwen 2.5 used in this test. How well they pick tools varies by model.
What is the difference between ollmcp and ollama-mcp?
ollmcp is an MCP client that gives Ollama models MCP tools. ollama-mcp is an MCP server that offers Ollama to other clients such as Claude Desktop.
Can one Ollama model use several MCP servers?
Yes. A client such as ollmcp connects to each server, merges their tools and passes them to the model. Fewer tools usually means better choices.
Sources
- Model Context Protocol specification, Transports
- Model Context Protocol specification, Tools
- Model Context Protocol, Connect to local MCP servers
- MCP Python SDK, migration guide to v2
- Ollama documentation, Tool calling
- Ollama documentation, FAQ
- Ollama documentation, CLI reference
- MCP Client for Ollama (ollmcp) on GitHub
- ollama-mcp on GitHub