{"id":"add-ollama-tool","name":"add-ollama-tool","summary":"Ollama MCPサーバーを追加して、コンテナエージェントがローカルモデルを呼び出し、オプションでOllamaモデルライブラリを管理できるようにします。","body":"# Add Ollama Integration\n\nThis skill adds a stdio-based MCP server that exposes local [Ollama](https://ollama.com) models as tools for the container agent. Claude remains the orchestrator but can offload work to local models served by the Ollama daemon on the host, and can optionally manage the model library directly. Ollama runs locally and is keyless — there are no credentials to thread; the only configuration is the daemon's base URL.\n\nCore tools (always available):\n- `ollama_list_models` — list installed models with name, size, and family (`GET /api/tags`)\n- `ollama_generate` — send a prompt to a specified model and return the response (`POST /api/generate`)\n\nManagement tools (opt-in via `OLLAMA_ADMIN_TOOLS=true`):\n- `ollama_pull_model` — pull (download) a model from the Ollama registry (`POST /api/pull`)\n- `ollama_delete_model` — delete a locally installed model to free disk space (`DELETE /api/delete`)\n- `ollama_show_model` — show model details: modelfile, parameters, and architecture info (`POST /api/show`)\n- `ollama_list_running` — list models currently loaded in memory with memory usage and processor type (`GET /api/ps`)\n\nThe skill ships the MCP server source (and its tests) in this folder and copies them into the agent-runner tree at install time, then registers the server in `index.ts` and forwards host env vars in `container-runner.ts`. Registering the server is enough to expose its tools — the agent's allow-pattern (`mcp__ollama__*`) is derived from the registered server name.\n\n## Phase 1: Pre-flight\n\n### Check if already applied\n\nCheck if `container/agent-runner/src/ollama-mcp-stdio.ts` exists. If it does, skip to Phase 3 (Configure).\n\n### Check prerequisites\n\nVerify Ollama is installed and its daemon is reachable. On the host:\n\n```bash\ncurl -s http://127.0.0.1:11434/api/tags | head\n```\n\nIf the request fails:\n\n1. Install Ollama from https://ollama.com/download.\n2. Start it (the desktop app runs the daemon, or run `ollama serve`).\n3. Confirm the daemon answers: `curl -s http://127.0.0.1:11434/api/tags`.\n\nIf no models are installed, suggest pulling one:\n\n> You need at least one model. For example:\n>\n> ```bash\n> ollama pull gemma3:1b        # Small, fast (~1GB)\n> ollama pull llama3.2         # Good general purpose (~2GB)\n> ollama pull qwen3-coder:30b  # Best for code tasks (~18GB)\n> ```\n\n## Phase 2: Apply Code Changes\n\n### Copy the skill's source and tests into both trees\n\nThis skill reaches into both the container (Bun) tree and the host (Node) tree, so its\nfiles go into both, alongside the integration points they cover.\n\n```bash\nS=.claude/skills/add-ollama-tool\n# Container (Bun) tree — the MCP server and the registration wiring test\ncp $S/ollama-mcp-stdio.ts       container/agent-runner/src/ollama-mcp-stdio.ts\ncp $S/ollama-registration.test.ts container/agent-runner/src/ollama-registration.test.ts\n# Host (Node) tree — the env-forwarding helper and the wiring test\ncp $S/ollama-env.ts             src/ollama-env.ts\ncp $S/ollama-wiring.test.ts     src/ollama-wiring.test.ts\n```\n\n### Register the MCP server in the agent-runner\n\nEdit `container/agent-runner/src/index.ts`. Find the `mcpServers` object that currently looks like this:\n\n```ts\n  const mcpServers: Record<string, { command: string; args: string[]; env: Record<string, string> }> = {\n    nanoclaw: {\n      command: 'bun',\n      args: ['run', mcpServerPath],\n      env: {},\n    },\n  };\n```\n\nAdd an `ollama` entry alongside `nanoclaw`:\n\n```ts\n  const mcpServers: Record<string, { command: string; args: string[]; env: Record<string, string> }> = {\n    nanoclaw: {\n      command: 'bun',\n      args: ['run', mcpServerPath],\n      env: {},\n    },\n    ollama: {\n      command: 'bun',\n      args: ['run', path.join(__dirname, 'ollama-mcp-stdio.ts')],\n      env: {\n        ...(process.env.OLLAMA_HOST ? { OLLAMA_HOST: process.env.OLLAMA_HOST } : {}),\n        ...(process.env.OLLAMA_ADMIN_TOOLS ? { OLLAMA_ADMIN_TOOLS: process.env.OLLAMA_ADMIN_TOOLS } : {}),\n      },\n    },\n  };\n```\n\n`ollama-registration.test.ts` asserts this entry is present and points at the server module — the tool only appears to the agent if it is registered here.\n\n### Forward host env vars into the container\n\nThe container receives `TZ` and OneCLI networking vars by default; any other host env\nvar the MCP subprocess needs must be forwarded explicitly. The forwarding logic lives in\nthe copied `src/ollama-env.ts` (`ollamaEnv()`) — `OLLAMA_HOST` (the daemon base URL)\nand `OLLAMA_ADMIN_TOOLS` (the library-management opt-in flag). Both are configuration, not\ncredentials (Ollama itself is local and keyless), so they belong on the composed `env`\nliteral — a credential-NAMED key would need the `contributedEnv` lane instead (see\n`add-atomic-chat-tool` for that shape).\n\nImport it in `src/container-runner.ts` (alongside the other local imports):\n\n```ts\nimport { ollamaEnv } from './ollama-env.js';\n```\n\nThen, in `composeSessionSpec`, find the `env` literal (the `TZ` line) and spread the helper right after it:\n\n```ts\n  const env: Record<string, string> = {\n    TZ: containerConfig.timezone ?? TIMEZONE,\n    ...ollamaEnv(),\n  };\n```\n\n`ollama-wiring.test.ts` asserts this `...ollamaEnv()` spread exists inside `composeSessionSpec`.\n\n### Surface `[OLLAMA]` log lines at info level\n\n> **Shared block.** This rewrites the driver's container-stderr logger, which other local-model tools (e.g. `add-atomic-chat-tool` for `[ATOMIC]`) also edit to surface their own prefix. Touch only the `[OLLAMA]` branch and leave the rest of the block intact, so the edits coexist and removal restores it cleanly.\n\nContainer stderr now lands in the Docker driver: in `src/drivers/docker-driver.ts`, inside `DockerHandle.start()`, find the stderr handler:\n\n```ts\n    proc.onStderr((line) => {\n      log.debug(line, { container: this.name });\n      this.#stderrTail.push(line);\n      if (this.#stderrTail.length > 10) this.#stderrTail.shift();\n    });\n```\n\nReplace the `log.debug` line with a prefix branch (leave the stderr-tail lines intact — they feed the non-zero-exit warning):\n\n```ts\n    proc.onStderr((line) => {\n      if (line.includes('[OLLAMA]')) {\n        log.info(line, { container: this.name });\n      } else {\n        log.debug(line, { container: this.name });\n      }\n      this.#stderrTail.push(line);\n      if (this.#stderrTail.length > 10) this.#stderrTail.shift();\n    });\n```\n\nIf `add-atomic-chat-tool` (or another local-model tool) has already turned this into a\nmulti-branch block, just add an `else if (line.includes('[OLLAMA]'))` branch instead of\nreplacing it.\n\n### Add env-var stubs to `.env.example`\n\nAppend to `.env.example`:\n\n```bash\n# Ollama MCP tool (.claude/skills/add-ollama-tool)\n# Override the host where the Ollama daemon listens.\n# Default: http://host.docker.internal:11434 (with fallback to localhost)\n# OLLAMA_HOST=http://host.docker.internal:11434\n\n# Opt in to library-management tools (pull, delete, show, list-running).\n# Leave unset to expose only list + generate.\n# OLLAMA_ADMIN_TOOLS=true\n```\n\n### Validate code changes\n\n```bash\npnpm run build\npnpm exec tsc -p container/agent-runner/tsconfig.json --noEmit\n# Host tree: composeSessionSpec wiring\npnpm exec vitest run src/ollama-wiring.test.ts\n# Container tree: index.ts registration\n(cd container/agent-runner && bun test src/ollama-registration.test.ts)\n./container/build.sh\n```\n\nAll must be clean before proceeding. The wiring and registration tests confirm the two\nintegration points — the `composeSessionSpec` spread and the `index.ts` registration — are\nactually in place; a failure means one drifted. (The MCP server's own request/response\nbehavior against the Ollama daemon is the author's build-time concern, not part of these\ntests — verify it manually in Phase 4.)\n\n## Phase 3: Configure\n\n### Enable library-management tools (optional)\n\nAsk the user:\n\n> Would you like the agent to be able to **manage Ollama models** (pull, delete, inspect, list running)?\n>\n> - **Yes** — adds tools to pull new models, delete old ones, show model info, and check what's loaded in memory\n> - **No** — the agent can only list installed models and generate responses (you manage models yourself on the host)\n\nIf the user wants management tools, add to `.env`:\n\n```bash\nOLLAMA_ADMIN_TOOLS=true\n```\n\nIf they decline (or don't answer), leave the variable unset — only list + generate are exposed.\n\n### Set Ollama host (optional)\n\nBy default, the MCP server connects to `http://host.docker.internal:11434` (Docker Desktop) with a fallback to `localhost`. To use a custom Ollama host, add to `.env`:\n\n```bash\nOLLAMA_HOST=http://your-ollama-host:11434\n```\n\n### Restart the service\n\nRun from your NanoClaw project root:\n\n```bash\nsource setup/lib/install-slug.sh\nlaunchctl kickstart -k gui/$(id -u)/$(launchd_label)  # macOS\n# Linux: systemctl --user restart $(systemd_unit)\n```\n\n## Phase 4: Verify\n\n### Test inference\n\nTell the user:\n\n> Send a message like: \"use ollama to tell me the capital of France\"\n>\n> The agent should use `ollama_list_models` to find available models, then `ollama_generate` to get a response.\n\n### Test model management (if enabled)\n\nIf `OLLAMA_ADMIN_TOOLS=true` was set, tell the user:\n\n> Send a message like: \"pull the gemma3:1b model\" or \"which ollama models are currently loaded in memory?\"\n>\n> The agent should call `ollama_pull_model` or `ollama_list_running` respectively.\n\n### Check logs if needed\n\n```bash\ntail -f logs/nanoclaw.log | grep -i ollama\n```\n\nLook for:\n- `[OLLAMA] Listing models...` — list request started\n- `[OLLAMA] Found N models` — models discovered\n- `[OLLAMA] >>> Generating with <model>` — generation started\n- `[OLLAMA] <<< Done: <model> | Xs | N tokens | M chars` — generation completed\n- `[OLLAMA] Pulling model:` — pull in progress (management tools)\n- `[OLLAMA] Deleted:` — model removed (management tools)\n\n## Troubleshooting\n\n### Agent says \"Ollama is not installed\" or tries to run a CLI\n\nThe agent is looking for an `ollama` CLI inside the container instead of using the MCP tools. This means:\n1. The MCP server wasn't copied — check `container/agent-runner/src/ollama-mcp-stdio.ts` exists\n2. The MCP server wasn't registered — check `container/agent-runner/src/index.ts` has the `ollama` entry in `mcpServers` (the allow-pattern is derived from this, so registration is the only thing to check)\n3. The container wasn't rebuilt — run `./container/build.sh`\n\n### \"Failed to connect to Ollama\"\n\n1. Verify the daemon is reachable: `curl http://127.0.0.1:11434/api/tags`\n2. Confirm Ollama is running (`ollama list` on the host)\n3. Check Docker can reach the host: `docker run --rm curlimages/curl curl -s http://host.docker.internal:11434/api/tags`\n4. If using a custom host, check `OLLAMA_HOST` in `.env`\n\n### `model not found` / 404 on generate\n\nThe model name passed to `ollama_generate` must exactly match one of the names returned by `ollama_list_models` (including any `:tag` suffix, e.g. `gemma3:1b`). Ask the agent to list models first, then pick one from that list.\n\n### `ollama_pull_model` times out on large models\n\nLarge models (7B+) can take several minutes. The tool uses `stream: false` so it blocks until the pull completes — this is intentional. For very large pulls, use the host CLI directly: `ollama pull <model>`.\n\n### Management tools not showing up\n\nEnsure `OLLAMA_ADMIN_TOOLS=true` is set in `.env` and the service was restarted after adding it. The management tools are only registered when that flag is present in the container's environment.\n\n### Slow first response\n\nOllama lazy-loads models into memory on first use. The initial call may take longer while the model warms up. Subsequent calls against the same model are fast.\n\n### Agent doesn't use Ollama tools\n\nThe agent may not know about the tools. Try being explicit: \"use the ollama_generate tool with gemma3:1b to answer: ...\"","author":"@nanocoai","ownerProfile":null,"authorContacts":null,"sourceUrl":"https://github.com/nanocoai/nanoclaw/tree/main/.claude/skills/add-ollama-tool","license":"MIT","category":null,"lang":"en","tokens":3041,"stars":0,"calls30d":2,"claimed":false,"visibility":"public","origin":"crawler","version":"0.1.0","createdAt":"2026-08-22","updatedAt":"2026-08-22","files":[{"path":"ollama-env.ts","size":958,"sha256":"685df4323d0c5213931191b43804b73944dbb8e06b361f18e0a03d9f8a47cb6c"},{"path":"ollama-mcp-stdio.ts","size":14052,"sha256":"3190d2a6102257b03b178540add15497ba699bf014e21b72397b8bbd6fda7b75"},{"path":"ollama-registration.test.ts","size":2291,"sha256":"e3e6b2ce56c1c9f8cb41db057dd37741805263afc948142bad475e0d779cc535"},{"path":"ollama-wiring.test.ts","size":2153,"sha256":"56924c6c4b5a2237373b1bd73740585861ebdb75f1822acbfe646155b19b1893"},{"path":"REMOVE.md","size":1711,"sha256":"4396872ee84cb5bf6887b989fa8dde521d2cb7113a49c87911fda17f94852877"}],"requires":{"mcp":["ollama"],"tools":[]},"safety":{"flags":[{"code":"net.endpoints","kind":"exfiltration","excerpt":"host.docker.internal, ollama.com","message":"bundled scripts reach 2 external host(s)","severity":"warn"}],"scannedAt":"2026-08-22","hasScripts":true,"networkEndpoints":["host.docker.internal","ollama.com"]}}