Build CLIs and MCP servers from one core, and choose daemon or per-client deliberately
The same capability often needs three front ends: a CLI people and shell-using agents can run, an MCP server for MCP clients, and sometimes an MCP App that renders a UI in the conversation. Build the capability once and keep the front ends thin, so behaviour, validation and tests do not drift apart. For whether you need MCP at all, see BP-0055; for CLI design rules, BP-0001.
One core, thin adapters
Section titled “One core, thin adapters”- MUST put the logic, validation and business rules in a library with its own tests. The CLI, the MCP server and any MCP App call it; none of them contains logic of its own.
- MUST keep the adapters consistent: the same names, limits, defaults and error meanings in every front end, tested through each adapter as well as the core.
Target the current protocol
Section titled “Target the current protocol”- MUST build MCP servers on an official, maintained SDK and the current specification (2026-07-28 at the time of writing), pin the SDK version, and re-test on SDK and spec updates.
- MUST design for the stateless core: there are no protocol-level sessions in 2026-07-28, and every request carries its own protocol version and client capabilities. If a tool needs state across calls, return an explicit handle and take it back as an argument.
- MUST treat state handles as data, not credentials: generate them randomly, expire them, bind them server-side to the authenticated user, and reject a handle presented by anyone else.
- MUST NOT build new servers on deprecated features (the HTTP+SSE transport; Roots, Sampling and Logging, deprecated in 2026-07-28). Use Streamable HTTP for remote servers.
Design tools for models
Section titled “Design tools for models”- MUST offer a few task-shaped tools rather than one tool per API endpoint, named
verb_noun, each with a description that says what it does, when to use it and when not to. - MUST declare strict input schemas (types, enums, bounds, formats, defaults) and an output schema, and return structured content that matches it alongside a text form.
- MUST return bad input as a tool error with a message that says what to change, so the model can correct itself. Reserve protocol errors for protocol failures.
- MUST bound results: default limits, pagination, summaries, or a resource link for large content.
- MUST set tool annotations truthfully (read-only, destructive, idempotent). They are hints for clients and approval prompts, not security controls; enforce access in the server.
- SHOULD evaluate tool use with real models: given realistic tasks, does the model pick the right tool and fill the arguments correctly? Fix the description or schema when it does not.
Secure it
Section titled “Secure it”- MUST treat every tool argument as untrusted: validate paths against an allowed root, never build shell commands from arguments, and protect any URL fetch against server-side request forgery. Mark content from outside sources as untrusted in results (BP-0005).
- MUST, for remote servers, follow the MCP authorization specification: accept only tokens issued for this server, never pass a client’s token through to a downstream API, require per-client consent in proxy servers, and start with minimal scopes, stepping up when a privileged tool is first used.
- MUST keep downstream credentials in a vault or the environment, never in tool results, logs or descriptions (BP-0063).
Choose: per-client or daemon
Section titled “Choose: per-client or daemon”-
MUST decide how the server runs, and write the choice down:
Per client (stdio, launched by the client) Daemon (long-running, Streamable HTTP, local or remote) Lifetime Starts and stops with the client session Runs under a service manager (launchd, systemd, a container) Exposure No network port; only the parent client can talk to it A listening endpoint that other processes, users or hosts can reach State and warm caches Rebuilt each launch Shared and kept warm (code indexes, embeddings, connections) Clients One Many, concurrently Auth The OS process boundary Required: tokens or OAuth; local daemons on a Unix socket or loopback with a token Upgrades and failure New version on next launch; a crash affects one session Rolling restarts, health checks, monitoring; a crash affects every client Fits Personal tools, workspace-scoped tools, anything touching local files Expensive start-up, shared indexes, team or remote services -
MUST, for any daemon: bind to loopback or a Unix socket unless remote access is intended, require authentication even on localhost (other local processes and DNS rebinding can reach it), validate the Origin header for HTTP, run it as a least-privilege service account, and add health checks, logs and a restart policy.
-
SHOULD start per-client and move to a daemon only for a measured reason: start-up time, shared warm state or many clients.
MCP Apps
Section titled “MCP Apps”- SHOULD add an MCP App only when a person needs to see or act on something a text answer cannot show well (a chart, a form, a review table). Declare the UI as a
ui://resource referenced from the tool’s metadata, and always return a usable text or structured result for hosts that do not render UI. - MUST route any action the UI triggers back through tools with the same validation, authorization and approval as a model-initiated call, keep secrets out of the UI, and declare the smallest set of external origins it needs.
Ship it
Section titled “Ship it”- MUST test through a real client: an in-memory or stdio client in automated tests, and the MCP Inspector or your target clients by hand.
- MUST version and release like any dependency: changelog, signed or pinned releases, and published metadata (for example a registry entry) so users can verify what they install (BP-0044).
When to apply
Section titled “When to apply”Building a CLI, an MCP server or an MCP App, or exposing an existing library or API to agents.
Examples
Section titled “Examples”One core, two adapters (Bun, MCP TypeScript SDK v2). Core:
// author: Stephen Eaton// core.ts — the logic. No CLI or MCP code here; both front ends call this.export type Note = { id: string; title: string; body: string; updated: string };const notes: Note[] = [ { id: 'n1', title: 'Change window', body: 'Saturday 02:00-04:00 AWST', updated: '2026-11-20' }, { id: 'n2', title: 'Backup check', body: 'Restore test passed', updated: '2026-11-22' },];
export function searchNotes(query: string, limit = 10): Note[] { if (!query.trim()) throw new Error('query must not be empty'); const q = query.toLowerCase(); return notes.filter((n) => (n.title + ' ' + n.body).toLowerCase().includes(q)).slice(0, limit);}MCP adapter, served per client over stdio:
// author: Stephen Eaton// mcp.ts — thin MCP adapter over the core (TypeScript SDK v2, MCP 2026-07-28).import { McpServer } from '@modelcontextprotocol/server';import * as z from 'zod/v4';import { searchNotes } from './core';
export function buildServer() { const server = new McpServer({ name: 'notes', version: '1.0.0' }); server.registerTool( 'search_notes', { description: 'Search team notes by keyword in title or body. Use for finding change windows, procedures and status notes. Read-only.', inputSchema: z.object({ query: z.string().min(1).describe('Keyword or phrase, e.g. "change window"'), limit: z.number().int().min(1).max(50).default(10), }), outputSchema: z.object({ notes: z.array(z.object({ id: z.string(), title: z.string(), updated: z.string() })), }), annotations: { readOnlyHint: true, idempotentHint: true }, }, async ({ query, limit }) => { const output = { notes: searchNotes(query, limit).map(({ id, title, updated }) => ({ id, title, updated })) }; return { content: [{ type: 'text', text: JSON.stringify(output) }], structuredContent: output }; }, ); return server;}
if (import.meta.main) { const { serveStdio } = await import('@modelcontextprotocol/server/stdio'); serveStdio(() => buildServer()); // stdio: launched per client, no network port}CLI adapter over the same core:
// author: Stephen Eaton// cli.ts — thin CLI adapter over the same core (see BP-0001 for CLI rules).import { parseArgs } from 'node:util';import { searchNotes } from './core';
const { positionals, values } = parseArgs({ args: Bun.argv.slice(2), allowPositionals: true, options: { limit: { type: 'string', default: '10' }, json: { type: 'boolean' } },});try { const res = searchNotes(positionals.join(' '), Number(values.limit)); console.log(values.json ? JSON.stringify(res) : res.map((n) => `${n.id}\t${n.title}`).join('\n'));} catch (e) { console.error(`notes: ${(e as Error).message}`); process.exit(2);}Test through an in-memory client:
import { test, expect } from 'bun:test';import { Client, InMemoryTransport } from '@modelcontextprotocol/client';import { buildServer } from './mcp';
async function connect() { const [clientT, serverT] = InMemoryTransport.createLinkedPair(); await buildServer().connect(serverT); const client = new Client({ name: 'test', version: '0.0.0' }); await client.connect(clientT); return client;}
test('lists the tool with its annotations', async () => { const c = await connect(); const { tools } = await c.listTools(); expect(tools.map((t) => t.name)).toEqual(['search_notes']); expect(tools[0].annotations?.readOnlyHint).toBe(true);});test('returns structured content', async () => { const c = await connect(); const r: any = await c.callTool({ name: 'search_notes', arguments: { query: 'change' } }); expect(r.structuredContent.notes[0].id).toBe('n1');});test('bad input comes back as a tool error the model can fix', async () => { const c = await connect(); const r: any = await c.callTool({ name: 'search_notes', arguments: { query: 'x', limit: 500 } }); expect(r.isError).toBe(true);});Tested with Bun 1.4 and @modelcontextprotocol/server 2.4.0: the three tests pass, the stdio server answers a real stdio client, and the CLI exits with code 2 on an empty query.
Running the same server as a local daemon (systemd user unit, illustrative):
# author: Stephen Eaton[Unit]Description=notes MCP server (Streamable HTTP on a Unix socket)
[Service]ExecStart=/usr/local/bin/notes-mcp --http --socket %t/notes-mcp.sockEnvironmentFile=%h/.config/notes-mcp/env # token from the vault agent, not committedRestart=on-failureNoNewPrivileges=yes
[Install]WantedBy=default.targetAnti-patterns
Section titled “Anti-patterns”- Business logic copied into the CLI and again into the MCP server, then drifting.
- One MCP tool per REST endpoint, with descriptions like “calls GET /items”.
- Relying on protocol sessions or server-assigned session IDs in a new server.
- A localhost daemon with no authentication.
readOnlyHint: trueon a tool that writes.- An MCP App whose buttons call the backend directly, bypassing tool approval.
Checklist
Section titled “Checklist”- Logic in one tested core; CLI, MCP server and MCP App are thin adapters
- Official SDK, current spec, pinned; stateless design with bound, expiring handles; no deprecated features
- Few task-shaped tools; strict schemas; structured output; fixable tool errors; bounded results; truthful annotations
- Inputs untrusted; token audience checked; no token passthrough; minimal scopes; credentials in a vault
- Per-client vs daemon decided and recorded; daemons authenticated, loopback or socket, monitored
- MCP Apps with text fallback; UI actions through tools
- Tested through real clients; versioned, signed or pinned, published