add-atomic-chat-tool
Add Atomic Chat MCP server so the container agent can call local models served by the Atomic Chat desktop app via its OpenAI-compatible API.
Install
npx skills add https://github.com/nanocoai/nanoclaw/tree/main/.claude/skills/add-atomic-chat-tool
claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install nanocoai-nanoclaw@llmmart
git clone https://github.com/nanocoai/nanoclaw.git
The skills CLI installs just this skill, for any of its supported agents. Claude Code installs the whole nanocoai/nanoclaw collection as a plugin from our marketplace. Git is the plain clone.
Skill manifest
Add Atomic Chat Integration
This skill adds a stdio-based MCP server that exposes models running in the local Atomic Chat desktop app as tools for the container agent. Claude remains the orchestrator but can offload work to local models served by Atomic Chat on http://127.0.0.1:1337/v1 (OpenAI-compatible).
Tools exposed:
atomic_chat_list_models— list models currently available in Atomic Chat (GET /v1/models)atomic_chat_generate— send a prompt to a specified model and return the response (POST /v1/chat/completions)
Model management (download, delete) is done through the Atomic Chat desktop UI — the app is a fork of Jan and manages its own model library.
The skill ships the MCP server source (and its test) 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__atomic_chat__*) is derived from the registered server name.
Phase 1: Pre-flight
Check if already applied
Check if container/agent-runner/src/atomic-chat-mcp-stdio.ts exists. If it does, skip to Phase 3 (Configure).
Check prerequisites
Verify Atomic Chat is installed and its local API server is running. On the host:
curl -s http://127.0.0.1:1337/v1/models | head
If the request fails:
- Install Atomic Chat from the latest release (macOS only for now —
atomic-chat.dmg). - Open the app.
- Open Settings → Local API Server and make sure it's enabled on port
1337. - Go to the Hub (or Models) tab and download at least one model (e.g. Llama 3.2 3B, Qwen 2.5 Coder 7B).
- Load the model once by sending any message in Atomic Chat's UI to warm it up.
Phase 2: Apply Code Changes
Copy the skill's source and tests into both trees
This skill reaches into both the container (Bun) tree and the host (Node) tree, so its files go into both, alongside the integration points they cover.
S=.claude/skills/add-atomic-chat-tool
# Container (Bun) tree — the MCP server and the registration wiring test
cp $S/atomic-chat-mcp-stdio.ts container/agent-runner/src/atomic-chat-mcp-stdio.ts
cp $S/atomic-chat-registration.test.ts container/agent-runner/src/atomic-chat-registration.test.ts
# Host (Node) tree — the env-forwarding helper and the wiring test
cp $S/atomic-chat-env.ts src/atomic-chat-env.ts
cp $S/atomic-chat-wiring.test.ts src/atomic-chat-wiring.test.ts
Register the MCP server in the agent-runner
Edit container/agent-runner/src/index.ts. Find the mcpServers object that currently looks like this:
const mcpServers: Record<string, { command: string; args: string[]; env: Record<string, string> }> = {
nanoclaw: {
command: 'bun',
args: ['run', mcpServerPath],
env: {},
},
};
Add an atomic_chat entry alongside nanoclaw:
const mcpServers: Record<string, { command: string; args: string[]; env: Record<string, string> }> = {
nanoclaw: {
command: 'bun',
args: ['run', mcpServerPath],
env: {},
},
atomic_chat: {
command: 'bun',
args: ['run', path.join(__dirname, 'atomic-chat-mcp-stdio.ts')],
env: {
...(process.env.ATOMIC_CHAT_HOST ? { ATOMIC_CHAT_HOST: process.env.ATOMIC_CHAT_HOST } : {}),
...(process.env.ATOMIC_CHAT_API_KEY ? { ATOMIC_CHAT_API_KEY: process.env.ATOMIC_CHAT_API_KEY } : {}),
},
},
};
atomic-chat-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.
Forward host env vars into the container
The env-forwarding logic lives in the copied src/atomic-chat-env.ts (atomicChatEnv()), so the reach-in into composeSessionSpec is a single spread.
Import it in src/container-runner.ts (alongside the other local imports):
import { atomicChatEnv } from './atomic-chat-env.js';
Then, in composeSessionSpec, find the contributedEnv literal and spread the helper at the end. The contributed lane — not the composed env literal — because ATOMIC_CHAT_API_KEY is credential-NAMED and the composed lane's key-name check would refuse the spawn; the contributed lane exempts the name and still refuses credential-shaped values:
const contributedEnv: Record<string, string> = {
...(contribution.env ?? {}),
...(gateway.env ?? {}),
...atomicChatEnv(),
};
atomic-chat-wiring.test.ts asserts this ...atomicChatEnv() spread exists inside composeSessionSpec.
Surface [ATOMIC] log lines at info level
Shared block. This rewrites the driver's container-stderr logger, which other local-model tools (e.g.
add-ollama-toolfor[OLLAMA]) also edit to surface their own prefix. Touch only the[ATOMIC]branch and leave the rest of the block intact, so the edits coexist and removal restores it cleanly.
Container stderr now lands in the Docker driver: in src/drivers/docker-driver.ts, inside DockerHandle.start(), find the stderr handler:
proc.onStderr((line) => {
log.debug(line, { container: this.name });
this.#stderrTail.push(line);
if (this.#stderrTail.length > 10) this.#stderrTail.shift();
});
Replace the log.debug line with a prefix branch (leave the stderr-tail lines intact — they feed the non-zero-exit warning):
proc.onStderr((line) => {
if (line.includes('[ATOMIC]')) {
log.info(line, { container: this.name });
} else {
log.debug(line, { container: this.name });
}
this.#stderrTail.push(line);
if (this.#stderrTail.length > 10) this.#stderrTail.shift();
});
Add env-var stubs to .env.example
Append to .env.example:
# Atomic Chat MCP tool (.claude/skills/add-atomic-chat-tool)
# Override the host where Atomic Chat exposes its OpenAI-compatible API.
# Default: http://host.docker.internal:1337 (with fallback to localhost)
# ATOMIC_CHAT_HOST=http://host.docker.internal:1337
# Optional API key. Leave unset for a local Atomic Chat install — it does not require auth.
# ATOMIC_CHAT_API_KEY=
Validate code changes
pnpm run build
pnpm exec tsc -p container/agent-runner/tsconfig.json --noEmit
# Host tree: composeSessionSpec wiring
pnpm exec vitest run src/atomic-chat-wiring.test.ts
# Container tree: index.ts registration
(cd container/agent-runner && bun test src/atomic-chat-registration.test.ts)
./container/build.sh
All must be clean before proceeding. The wiring and registration tests confirm the two
integration points — the composeSessionSpec spread and the index.ts registration — are
actually in place; a failure means one drifted. (The MCP server's own request/response
behavior against Atomic Chat is the author's build-time concern, not part of these tests —
verify it manually in Phase 4.)
Phase 3: Configure
Set Atomic Chat host (optional)
By default, the MCP server connects to http://host.docker.internal:1337 (Docker Desktop) with a fallback to localhost. To use a custom host, add to .env:
ATOMIC_CHAT_HOST=http://your-atomic-chat-host:1337
Set API key (optional)
Atomic Chat does not require authentication when running locally — leave this unset. Only set it if you've put Atomic Chat behind a reverse proxy that enforces auth:
ATOMIC_CHAT_API_KEY=sk-...
Restart the service
Run from your NanoClaw project root:
source setup/lib/install-slug.sh
launchctl kickstart -k gui/$(id -u)/$(launchd_label) # macOS
# Linux: systemctl --user restart $(systemd_unit)
Phase 4: Verify
Test inference
Tell the user:
Send a message like: "use atomic chat to tell me the capital of France"
The agent should use
atomic_chat_list_modelsto find available models, thenatomic_chat_generateto get a response.
Check logs if needed
tail -f logs/nanoclaw.log | grep -i atomic
Look for:
[ATOMIC] Listing models...— list request started[ATOMIC] Found N models— models discovered[ATOMIC] >>> Generating with <model>— generation started[ATOMIC] <<< Done: <model> | Xs | N tokens | M chars— generation completed
Troubleshooting
Agent says "Atomic Chat is not installed" or tries to run a CLI
The agent is looking for a CLI that doesn't exist instead of using the MCP tools. This means:
- The MCP server wasn't copied — check
container/agent-runner/src/atomic-chat-mcp-stdio.tsexists - The MCP server wasn't registered — check
container/agent-runner/src/index.tshas theatomic_chatentry inmcpServers(the allow-pattern is derived from this, so registration is the only thing to check) - The container wasn't rebuilt — run
./container/build.sh
"Failed to connect to Atomic Chat"
- Verify the host API is reachable:
curl http://127.0.0.1:1337/v1/models - Confirm the Local API Server is enabled in Atomic Chat's settings
- Check Docker can reach the host:
docker run --rm curlimages/curl curl -s http://host.docker.internal:1337/v1/models - If using a custom host, check
ATOMIC_CHAT_HOSTin.env
model not found / 404 on generate
The model ID passed to atomic_chat_generate must exactly match one of the IDs returned by atomic_chat_list_models. Ask the agent to list models first, then pick one from that list.
Slow first response
Atomic Chat 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.
Agent doesn't use Atomic Chat tools
The agent may not know about the tools. Try being explicit: "use the atomic_chat_generate tool with llama3.2-3b-instruct to answer: ..."
Context window or output size issues
Atomic Chat respects each model's native context length. If you hit limits, pass max_tokens explicitly when calling atomic_chat_generate, or switch to a model with a larger context window in the Atomic Chat UI.
Files (nanoclaw)
-
atomic-chat-env.ts 1 KB
/** * Host-side env forwarding for the Atomic Chat MCP tool: any `ATOMIC_CHAT_*` * host overrides, as spec-shaped env (a record) — argv never crosses * composition anymore. * * The reach-in spreads this into the CONTRIBUTED env lane * (`ContainerSpec.contributedEnv`), not the composed literal: * `ATOMIC_CHAT_API_KEY` is credential-NAMED, and the composed lane's key-name * check would refuse it and deny the spawn. The contributed lane exempts the * name and still refuses credential-shaped VALUES — which is the right rule * for a local service token. * * Lives in its own file so the reach-in in `container-runner.ts` is a single * spread and this logic is behavior-testable in isolation. */ export function atomicChatEnv(): Record<string, string> { const env: Record<string, string> = {}; if (process.env.ATOMIC_CHAT_HOST) { env.ATOMIC_CHAT_HOST = process.env.ATOMIC_CHAT_HOST; } if (process.env.ATOMIC_CHAT_API_KEY) { env.ATOMIC_CHAT_API_KEY = process.env.ATOMIC_CHAT_API_KEY; } return env; } -
atomic-chat-mcp-stdio.ts 6.8 KB
/** * Atomic Chat MCP Server for NanoClaw * Exposes local Atomic Chat models (OpenAI-compatible, /v1) as tools for the container agent. * Uses host.docker.internal to reach the host's Atomic Chat desktop app from Docker. */ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'; import { z } from 'zod'; import fs from 'fs'; import path from 'path'; const ATOMIC_CHAT_HOST = process.env.ATOMIC_CHAT_HOST || 'http://host.docker.internal:1337'; const ATOMIC_CHAT_API_KEY = process.env.ATOMIC_CHAT_API_KEY || ''; const ATOMIC_CHAT_STATUS_FILE = '/workspace/ipc/atomic_chat_status.json'; function log(msg: string): void { console.error(`[ATOMIC] ${msg}`); } function writeStatus(status: string, detail?: string): void { try { const data = { status, detail, timestamp: new Date().toISOString() }; const tmpPath = `${ATOMIC_CHAT_STATUS_FILE}.tmp`; fs.mkdirSync(path.dirname(ATOMIC_CHAT_STATUS_FILE), { recursive: true }); fs.writeFileSync(tmpPath, JSON.stringify(data)); fs.renameSync(tmpPath, ATOMIC_CHAT_STATUS_FILE); } catch { /* best-effort */ } } async function atomicFetch( apiPath: string, options?: RequestInit, ): Promise<Response> { const url = `${ATOMIC_CHAT_HOST}${apiPath}`; const headers: Record<string, string> = { ...((options?.headers as Record<string, string>) || {}), }; if (ATOMIC_CHAT_API_KEY) { headers.Authorization = `Bearer ${ATOMIC_CHAT_API_KEY}`; } const finalOptions: RequestInit = { ...options, headers }; try { return await fetch(url, finalOptions); } catch (err) { // Fallback to localhost if host.docker.internal fails if (ATOMIC_CHAT_HOST.includes('host.docker.internal')) { const fallbackUrl = url.replace('host.docker.internal', 'localhost'); return await fetch(fallbackUrl, finalOptions); } throw err; } } const server = new McpServer({ name: 'atomic_chat', version: '1.0.0', }); server.tool( 'atomic_chat_list_models', 'List all models available in the local Atomic Chat desktop app. Use this to see which models are loaded before calling atomic_chat_generate.', {}, async () => { log('Listing models...'); writeStatus('listing', 'Listing available models'); try { const res = await atomicFetch('/v1/models'); if (!res.ok) { return { content: [ { type: 'text' as const, text: `Atomic Chat API error: ${res.status} ${res.statusText}`, }, ], isError: true, }; } const data = (await res.json()) as { data?: Array<{ id: string; owned_by?: string }>; }; const models = data.data || []; if (models.length === 0) { return { content: [ { type: 'text' as const, text: 'No models available. Open Atomic Chat on the host and download a model from the Hub.', }, ], }; } const list = models .map((m) => `- ${m.id}${m.owned_by ? ` (${m.owned_by})` : ''}`) .join('\n'); log(`Found ${models.length} models`); return { content: [ { type: 'text' as const, text: `Available models:\n${list}` }, ], }; } catch (err) { return { content: [ { type: 'text' as const, text: `Failed to connect to Atomic Chat at ${ATOMIC_CHAT_HOST}: ${err instanceof Error ? err.message : String(err)}`, }, ], isError: true, }; } }, ); server.tool( 'atomic_chat_generate', 'Send a prompt to a local Atomic Chat model and get a response. Good for cheaper/faster tasks like summarization, translation, or general queries. Use atomic_chat_list_models first to see available models.', { model: z .string() .describe( 'The model ID as returned by atomic_chat_list_models (e.g. "llama3.2-3b-instruct")', ), prompt: z.string().describe('The prompt to send to the model'), system: z .string() .optional() .describe('Optional system prompt to set model behavior'), temperature: z .number() .optional() .describe('Sampling temperature (0.0–2.0). Defaults to model default.'), max_tokens: z .number() .optional() .describe('Maximum number of tokens to generate in the response.'), }, async (args) => { log(`>>> Generating with ${args.model} (${args.prompt.length} chars)...`); writeStatus('generating', `Generating with ${args.model}`); try { const messages: Array<{ role: string; content: string }> = []; if (args.system) { messages.push({ role: 'system', content: args.system }); } messages.push({ role: 'user', content: args.prompt }); const body: Record<string, unknown> = { model: args.model, messages, stream: false, }; if (args.temperature !== undefined) body.temperature = args.temperature; if (args.max_tokens !== undefined) body.max_tokens = args.max_tokens; const startedAt = Date.now(); const res = await atomicFetch('/v1/chat/completions', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body), }); if (!res.ok) { const errorText = await res.text(); return { content: [ { type: 'text' as const, text: `Atomic Chat error (${res.status}): ${errorText}`, }, ], isError: true, }; } const data = (await res.json()) as { choices?: Array<{ message?: { content?: string } }>; usage?: { prompt_tokens?: number; completion_tokens?: number; total_tokens?: number; }; }; const response = data.choices?.[0]?.message?.content ?? ''; const elapsedSec = ((Date.now() - startedAt) / 1000).toFixed(1); const completionTokens = data.usage?.completion_tokens; const meta = `\n\n[${args.model} | ${elapsedSec}s${ completionTokens !== undefined ? ` | ${completionTokens} tokens` : '' }]`; log( `<<< Done: ${args.model} | ${elapsedSec}s | ${ completionTokens ?? '?' } tokens | ${response.length} chars`, ); writeStatus( 'done', `${args.model} | ${elapsedSec}s | ${completionTokens ?? '?'} tokens`, ); return { content: [{ type: 'text' as const, text: response + meta }] }; } catch (err) { return { content: [ { type: 'text' as const, text: `Failed to call Atomic Chat: ${err instanceof Error ? err.message : String(err)}`, }, ], isError: true, }; } }, ); const transport = new StdioServerTransport(); await server.connect(transport); -
atomic-chat-registration.test.ts 2.3 KB
/** * Wiring test for the MCP-server registration integration point (container/Bun tree). * * The handlers are behavior-tested in atomic-chat-mcp-stdio.test.ts, but that does not * prove the server is registered — delete the index.ts entry and the tool simply never * appears, yet the handler test stays green. index.ts is the container boot entry and is * not cheaply invocable, so we assert the registration structurally: the `mcpServers` * object literal has an `atomic_chat` property whose command runs `atomic-chat-mcp-stdio.ts`. */ import fs from 'fs'; import path from 'path'; import { describe, it, expect } from 'bun:test'; import ts from 'typescript'; function sourceFile(): ts.SourceFile { const p = path.join(import.meta.dir, 'index.ts'); return ts.createSourceFile(p, fs.readFileSync(p, 'utf8'), ts.ScriptTarget.Latest, true); } /** Find the object literal assigned to `const mcpServers = { ... }`. */ function mcpServersLiteral(sf: ts.SourceFile): ts.ObjectLiteralExpression | undefined { let found: ts.ObjectLiteralExpression | undefined; const visit = (node: ts.Node) => { if ( ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && node.name.text === 'mcpServers' && node.initializer && ts.isObjectLiteralExpression(node.initializer) ) { found = node.initializer; } if (!found) ts.forEachChild(node, visit); }; visit(sf); return found; } function property(obj: ts.ObjectLiteralExpression, name: string): ts.PropertyAssignment | undefined { return obj.properties.find( (p): p is ts.PropertyAssignment => ts.isPropertyAssignment(p) && ((ts.isIdentifier(p.name) && p.name.text === name) || (ts.isStringLiteral(p.name) && p.name.text === name)), ); } describe('index.ts registers the atomic_chat MCP server', () => { const obj = mcpServersLiteral(sourceFile()); it('finds the mcpServers object literal', () => { expect(obj).toBeDefined(); }); it('has an atomic_chat entry', () => { expect(obj && property(obj, 'atomic_chat')).toBeDefined(); }); it('points atomic_chat at atomic-chat-mcp-stdio.ts', () => { const entry = obj && property(obj, 'atomic_chat'); const text = entry ? entry.getText() : ''; expect(text).toContain('atomic-chat-mcp-stdio.ts'); }); }); -
atomic-chat-wiring.test.ts 2.1 KB
/** * Wiring test for the host-side env-forwarding integration point (host/vitest tree). * * The env helper is behavior-tested in isolation, but that does not prove * composeSessionSpec actually uses it — a direct unit test stays green even if * the reach-in is deleted. composeSessionSpec is entangled with the gateway * provider and not cheaply invocable here, so we assert the integration * structurally: inside composeSessionSpec there is a `...atomicChatEnv()` * spread. Delete the reach-in and this goes red. */ import fs from 'fs'; import path from 'path'; import { describe, it, expect } from 'vitest'; import ts from 'typescript'; function sourceFile(): ts.SourceFile { const p = path.resolve(process.cwd(), 'src/container-runner.ts'); return ts.createSourceFile(p, fs.readFileSync(p, 'utf8'), ts.ScriptTarget.Latest, true); } function findFunction(sf: ts.SourceFile, name: string): ts.FunctionDeclaration | undefined { let found: ts.FunctionDeclaration | undefined; const visit = (node: ts.Node) => { if (ts.isFunctionDeclaration(node) && node.name?.text === name) found = node; if (!found) ts.forEachChild(node, visit); }; visit(sf); return found; } /** Is this node a `...atomicChatEnv()` spread (object or array position)? */ function isEnvSpread(node: ts.Node): boolean { const spreadExpression = ts.isSpreadAssignment(node) || ts.isSpreadElement(node) ? node.expression : undefined; return ( spreadExpression !== undefined && ts.isCallExpression(spreadExpression) && ts.isIdentifier(spreadExpression.expression) && spreadExpression.expression.text === 'atomicChatEnv' ); } describe('container-runner.ts wires in atomicChatEnv', () => { const sf = sourceFile(); const fn = findFunction(sf, 'composeSessionSpec'); it('finds composeSessionSpec', () => { expect(fn).toBeDefined(); }); it('spreads ...atomicChatEnv() inside composeSessionSpec', () => { let wired = false; const visit = (node: ts.Node) => { if (isEnvSpread(node)) wired = true; if (!wired) ts.forEachChild(node, visit); }; if (fn?.body) visit(fn.body); expect(wired).toBe(true); }); }); -
REMOVE.md 1.6 KB
# Remove Atomic Chat Idempotent — safe to run even if some steps were never applied. ## 1. Delete the copied files (both trees) ```bash rm -f container/agent-runner/src/atomic-chat-mcp-stdio.ts \ container/agent-runner/src/atomic-chat-registration.test.ts \ src/atomic-chat-env.ts \ src/atomic-chat-wiring.test.ts ``` ## 2. Unregister the MCP server In `container/agent-runner/src/index.ts`, remove the `atomic_chat: { … }` entry from the `mcpServers` object (leave `nanoclaw` and any other entries). ## 3. Revert the host-side edits - Remove the `import { atomicChatEnv } from './atomic-chat-env.js';` import. - Remove the `...atomicChatEnv(),` spread from the `contributedEnv` literal in `composeSessionSpec`. - In `src/drivers/docker-driver.ts`, restore the driver's stderr handler to its single `log.debug(line, …)` form (remove the `[ATOMIC]` info-level branch; keep the stderr-tail lines). ## 4. Remove env vars Remove the Atomic Chat block from `.env.example`, and the `ATOMIC_CHAT_*` lines from `.env` if you set them. ## 5. Rebuild and restart Run from your NanoClaw project root: ```bash pnpm run build && ./container/build.sh source setup/lib/install-slug.sh # macOS launchctl kickstart -k gui/$(id -u)/$(launchd_label) # Linux systemctl --user restart $(systemd_unit) ``` ## Verification After removal, confirm the tool is gone — in a wired agent, asking it to "list atomic chat models" should report no such tool, and the logs should show no `[ATOMIC]` lines after the last restart: ```bash grep "\[ATOMIC\]" logs/nanoclaw.log | tail -5 ``` -
SKILL.md 10.2 KB
--- name: add-atomic-chat-tool description: Add Atomic Chat MCP server so the container agent can call local models served by the Atomic Chat desktop app via its OpenAI-compatible API. --- # Add Atomic Chat Integration This skill adds a stdio-based MCP server that exposes models running in the local [Atomic Chat](https://github.com/AtomicBot-ai/Atomic-Chat) desktop app as tools for the container agent. Claude remains the orchestrator but can offload work to local models served by Atomic Chat on `http://127.0.0.1:1337/v1` (OpenAI-compatible). Tools exposed: - `atomic_chat_list_models` — list models currently available in Atomic Chat (`GET /v1/models`) - `atomic_chat_generate` — send a prompt to a specified model and return the response (`POST /v1/chat/completions`) Model management (download, delete) is done through the **Atomic Chat desktop UI** — the app is a fork of Jan and manages its own model library. The skill ships the MCP server source (and its test) 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__atomic_chat__*`) is derived from the registered server name. ## Phase 1: Pre-flight ### Check if already applied Check if `container/agent-runner/src/atomic-chat-mcp-stdio.ts` exists. If it does, skip to Phase 3 (Configure). ### Check prerequisites Verify Atomic Chat is installed and its local API server is running. On the host: ```bash curl -s http://127.0.0.1:1337/v1/models | head ``` If the request fails: 1. Install Atomic Chat from the [latest release](https://github.com/AtomicBot-ai/Atomic-Chat/releases) (macOS only for now — `atomic-chat.dmg`). 2. Open the app. 3. Open **Settings → Local API Server** and make sure it's enabled on port `1337`. 4. Go to the **Hub** (or **Models**) tab and download at least one model (e.g. Llama 3.2 3B, Qwen 2.5 Coder 7B). 5. Load the model once by sending any message in Atomic Chat's UI to warm it up. ## Phase 2: Apply Code Changes ### Copy the skill's source and tests into both trees This skill reaches into both the container (Bun) tree and the host (Node) tree, so its files go into both, alongside the integration points they cover. ```bash S=.claude/skills/add-atomic-chat-tool # Container (Bun) tree — the MCP server and the registration wiring test cp $S/atomic-chat-mcp-stdio.ts container/agent-runner/src/atomic-chat-mcp-stdio.ts cp $S/atomic-chat-registration.test.ts container/agent-runner/src/atomic-chat-registration.test.ts # Host (Node) tree — the env-forwarding helper and the wiring test cp $S/atomic-chat-env.ts src/atomic-chat-env.ts cp $S/atomic-chat-wiring.test.ts src/atomic-chat-wiring.test.ts ``` ### Register the MCP server in the agent-runner Edit `container/agent-runner/src/index.ts`. Find the `mcpServers` object that currently looks like this: ```ts const mcpServers: Record<string, { command: string; args: string[]; env: Record<string, string> }> = { nanoclaw: { command: 'bun', args: ['run', mcpServerPath], env: {}, }, }; ``` Add an `atomic_chat` entry alongside `nanoclaw`: ```ts const mcpServers: Record<string, { command: string; args: string[]; env: Record<string, string> }> = { nanoclaw: { command: 'bun', args: ['run', mcpServerPath], env: {}, }, atomic_chat: { command: 'bun', args: ['run', path.join(__dirname, 'atomic-chat-mcp-stdio.ts')], env: { ...(process.env.ATOMIC_CHAT_HOST ? { ATOMIC_CHAT_HOST: process.env.ATOMIC_CHAT_HOST } : {}), ...(process.env.ATOMIC_CHAT_API_KEY ? { ATOMIC_CHAT_API_KEY: process.env.ATOMIC_CHAT_API_KEY } : {}), }, }, }; ``` `atomic-chat-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. ### Forward host env vars into the container The env-forwarding logic lives in the copied `src/atomic-chat-env.ts` (`atomicChatEnv()`), so the reach-in into `composeSessionSpec` is a single spread. Import it in `src/container-runner.ts` (alongside the other local imports): ```ts import { atomicChatEnv } from './atomic-chat-env.js'; ``` Then, in `composeSessionSpec`, find the `contributedEnv` literal and spread the helper at the end. The contributed lane — not the composed `env` literal — because `ATOMIC_CHAT_API_KEY` is credential-NAMED and the composed lane's key-name check would refuse the spawn; the contributed lane exempts the name and still refuses credential-shaped values: ```ts const contributedEnv: Record<string, string> = { ...(contribution.env ?? {}), ...(gateway.env ?? {}), ...atomicChatEnv(), }; ``` `atomic-chat-wiring.test.ts` asserts this `...atomicChatEnv()` spread exists inside `composeSessionSpec`. ### Surface `[ATOMIC]` log lines at info level > **Shared block.** This rewrites the driver's container-stderr logger, which other local-model tools (e.g. `add-ollama-tool` for `[OLLAMA]`) also edit to surface their own prefix. Touch only the `[ATOMIC]` branch and leave the rest of the block intact, so the edits coexist and removal restores it cleanly. Container stderr now lands in the Docker driver: in `src/drivers/docker-driver.ts`, inside `DockerHandle.start()`, find the stderr handler: ```ts proc.onStderr((line) => { log.debug(line, { container: this.name }); this.#stderrTail.push(line); if (this.#stderrTail.length > 10) this.#stderrTail.shift(); }); ``` Replace the `log.debug` line with a prefix branch (leave the stderr-tail lines intact — they feed the non-zero-exit warning): ```ts proc.onStderr((line) => { if (line.includes('[ATOMIC]')) { log.info(line, { container: this.name }); } else { log.debug(line, { container: this.name }); } this.#stderrTail.push(line); if (this.#stderrTail.length > 10) this.#stderrTail.shift(); }); ``` ### Add env-var stubs to `.env.example` Append to `.env.example`: ```bash # Atomic Chat MCP tool (.claude/skills/add-atomic-chat-tool) # Override the host where Atomic Chat exposes its OpenAI-compatible API. # Default: http://host.docker.internal:1337 (with fallback to localhost) # ATOMIC_CHAT_HOST=http://host.docker.internal:1337 # Optional API key. Leave unset for a local Atomic Chat install — it does not require auth. # ATOMIC_CHAT_API_KEY= ``` ### Validate code changes ```bash pnpm run build pnpm exec tsc -p container/agent-runner/tsconfig.json --noEmit # Host tree: composeSessionSpec wiring pnpm exec vitest run src/atomic-chat-wiring.test.ts # Container tree: index.ts registration (cd container/agent-runner && bun test src/atomic-chat-registration.test.ts) ./container/build.sh ``` All must be clean before proceeding. The wiring and registration tests confirm the two integration points — the `composeSessionSpec` spread and the `index.ts` registration — are actually in place; a failure means one drifted. (The MCP server's own request/response behavior against Atomic Chat is the author's build-time concern, not part of these tests — verify it manually in Phase 4.) ## Phase 3: Configure ### Set Atomic Chat host (optional) By default, the MCP server connects to `http://host.docker.internal:1337` (Docker Desktop) with a fallback to `localhost`. To use a custom host, add to `.env`: ```bash ATOMIC_CHAT_HOST=http://your-atomic-chat-host:1337 ``` ### Set API key (optional) Atomic Chat does **not require authentication** when running locally — leave this unset. Only set it if you've put Atomic Chat behind a reverse proxy that enforces auth: ```bash ATOMIC_CHAT_API_KEY=sk-... ``` ### Restart the service Run from your NanoClaw project root: ```bash source setup/lib/install-slug.sh launchctl kickstart -k gui/$(id -u)/$(launchd_label) # macOS # Linux: systemctl --user restart $(systemd_unit) ``` ## Phase 4: Verify ### Test inference Tell the user: > Send a message like: "use atomic chat to tell me the capital of France" > > The agent should use `atomic_chat_list_models` to find available models, then `atomic_chat_generate` to get a response. ### Check logs if needed ```bash tail -f logs/nanoclaw.log | grep -i atomic ``` Look for: - `[ATOMIC] Listing models...` — list request started - `[ATOMIC] Found N models` — models discovered - `[ATOMIC] >>> Generating with <model>` — generation started - `[ATOMIC] <<< Done: <model> | Xs | N tokens | M chars` — generation completed ## Troubleshooting ### Agent says "Atomic Chat is not installed" or tries to run a CLI The agent is looking for a CLI that doesn't exist instead of using the MCP tools. This means: 1. The MCP server wasn't copied — check `container/agent-runner/src/atomic-chat-mcp-stdio.ts` exists 2. The MCP server wasn't registered — check `container/agent-runner/src/index.ts` has the `atomic_chat` entry in `mcpServers` (the allow-pattern is derived from this, so registration is the only thing to check) 3. The container wasn't rebuilt — run `./container/build.sh` ### "Failed to connect to Atomic Chat" 1. Verify the host API is reachable: `curl http://127.0.0.1:1337/v1/models` 2. Confirm the Local API Server is enabled in Atomic Chat's settings 3. Check Docker can reach the host: `docker run --rm curlimages/curl curl -s http://host.docker.internal:1337/v1/models` 4. If using a custom host, check `ATOMIC_CHAT_HOST` in `.env` ### `model not found` / 404 on generate The model ID passed to `atomic_chat_generate` must exactly match one of the IDs returned by `atomic_chat_list_models`. Ask the agent to list models first, then pick one from that list. ### Slow first response Atomic Chat 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. ### Agent doesn't use Atomic Chat tools The agent may not know about the tools. Try being explicit: "use the atomic_chat_generate tool with llama3.2-3b-instruct to answer: ..." ### Context window or output size issues Atomic Chat respects each model's native context length. If you hit limits, pass `max_tokens` explicitly when calling `atomic_chat_generate`, or switch to a model with a larger context window in the Atomic Chat UI.
Comments (0)
Sign in to join the conversation.
Reviews (0)
No reviews yet.
No comments yet.