content-md 0.0.0-stage → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/server.js ADDED
@@ -0,0 +1,229 @@
1
+ // MCP server over stdio. The host's own model (Codex, Cursor, Claude Code...) does the writing;
2
+ // this server gives it the playbooks, shipped examples, style-guide rules and a linter.
3
+ import { readFileSync } from "node:fs";
4
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
5
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
6
+ import { z } from "zod";
7
+ import { findReferenceV2Async, decideTone, HAS_ENRICHED, INDUSTRIES } from "./reference2.js";
8
+ import { readProduct, auditCopy } from "./product.js";
9
+ import { saveProductBrief, askPerson, readSavedBrief } from "./context.js";
10
+ import { readConfig } from "./repo.js";
11
+ import { normElement, META, PATTERNS, ELEMENTS, HAS_EXAMPLES, findExamples, findRules, getGuide, lintCopy, findReference, compareToReference } from "./tools.js";
12
+
13
+ const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
14
+
15
+ const INSTRUCTIONS_FULL = `Use these tools whenever you write or review interface copy: buttons, errors, empty states, dialogs, onboarding, permissions, paywalls, checkout, notifications, tooltips, loading states or AI chat UI, including strings in code.
16
+ The repo's own copy rules, glossary and voice guide come first: where they differ from this guidance, follow them, and reuse the product's own words. read_product lists the files where the repo states its rules.
17
+ Write from the rules, the tone decision and the pattern playbook. Shipped copy is optional evidence, not a template.
18
+ 0. In a codebase, call read_product once per session. Use the saved brief if there is one; otherwise fill its slots from the repo, write the short brief, ask the person at most two questions that would change the copy (ask_person; otherwise state your assumption), and save it with save_product_brief (it writes .content-md/product.md, not your instruction files) unless the person said not to touch files. Write for that product, its audience and its own words, and keep its voice. To improve existing copy, call audit_copy and fix the worst lines first; leave unflagged lines alone.
19
+ 1. Call get_guide with the pattern once per task and follow it.
20
+ 2. If the moment has stakes or feeling (an error, money, a deletion, a success), call decide_tone with the facts of the moment, and use its tone words and instruction.
21
+ 3. State-check before you write: name the screen state and what the product actually knows. Do not claim more than that.
22
+ 4. Write every piece the screen needs. When rewriting, keep labels, buttons and titles that already work.
23
+ 5. Optional: call find_reference when you want evidence for a decision, or pass the tool state when the copy describes progress or an outcome, to get a correction example. If it returns nothing, write from the rules.
24
+ 6. Run lint_copy on every draft and fix each block and warn, or say why you kept it. Run a promise audit only when a claim goes beyond what the state says. In a codebase, back each claim in help, policy or onboarding copy with a file and line, and drop what you can't back. Never invent a source, name, date or figure as an example. Score each string 1-3 with the rubric in the guide and return nothing below 2.
25
+ Lead with paste-ready copy. If you quote a shipped line, quote it exactly as a tool returned it.`;
26
+ const INSTRUCTIONS = HAS_EXAMPLES ? INSTRUCTIONS_FULL : `Use these tools whenever you write or review interface copy, including strings in code.
27
+ The repo's own copy rules, glossary and voice guide come first: where they differ from this guidance, follow them.
28
+ 0. In a codebase, call read_product once and write the product brief it asks for; to improve existing copy, call audit_copy and fix the worst lines first.
29
+ 1. Call get_guide with the pattern once per task and follow it.
30
+ 2. If the moment has stakes or feeling, call decide_tone first.
31
+ 3. State-check, write every piece the screen needs, then run lint_copy on every draft and fix each block and warn, or say why you kept it. Score each string 1-3 with the rubric in the guide and return nothing below 2.
32
+ Lead with paste-ready copy, recommend one option, and cite the rule behind it.`;
33
+
34
+ // the repo's industry, from .content-md.json or the saved product brief, so references stay on-domain by default
35
+ function repoIndustry(root = process.cwd()) {
36
+ const c = readConfig(root).industry || readSavedBrief(root)?.fields?.industry;
37
+ return c && INDUSTRIES.includes(c) ? c : undefined;
38
+ }
39
+ const json = (data) => ({ content: [{ type: "text", text: JSON.stringify(data, null, 1) }] });
40
+ const pattern = z.enum(PATTERNS);
41
+ // accepts the common words agents guess ("button", "title", "link") and maps them to the element names
42
+ const element = z.string().transform((e, ctx) => {
43
+ const n = normElement(e);
44
+ if (!ELEMENTS.includes(n)) { ctx.addIssue({ code: "custom", message: `Unknown element '${e}'. Use one of: ${ELEMENTS.join(", ")} (button, title, link, error and similar are accepted too).` }); return z.NEVER; }
45
+ return n;
46
+ }).describe(`One of ${ELEMENTS.join(", ")}. Common words like button, title, heading, link, error and description are accepted.`);
47
+
48
+ export async function serve() {
49
+ const server = new McpServer({ name: "content-md", version: pkg.version }, { instructions: INSTRUCTIONS });
50
+
51
+ server.registerTool("get_guide", {
52
+ title: "UX writing guide",
53
+ description: `The voice, workflow, universal rules and the playbook for one UI pattern, built from ${META.sources} public style guides and a labeled set of shipped interface copy. Call once at the start of any copy task.`,
54
+ inputSchema: {
55
+ pattern: pattern.optional().describe("The UI situation. Omit to get the universal rules and the list of patterns."),
56
+ full: z.boolean().optional().describe("Also return every topic in the pattern index (about 18,000 more characters). Rarely needed."),
57
+ },
58
+ annotations: { readOnlyHint: true },
59
+ }, async ({ pattern, full }) => ({ content: [{ type: "text", text: getGuide({ pattern, full }) }] }));
60
+
61
+ if (HAS_EXAMPLES) server.registerTool("find_examples", {
62
+ title: "Find shipped examples",
63
+ description: `Optional evidence: search labeled shipped screens for how a situation was worded. Returns whole screens (headline, body and buttons together); each piece is rated gold, strong, solid or weak, with labeler notes. Use quality 'weak' to see what to avoid. For a single line, use find_reference. Cite a product only if a tool returned it.`,
64
+ inputSchema: {
65
+ pattern,
66
+ element: element.optional().describe("Only screens containing this piece"),
67
+ query: z.string().optional().describe("Key nouns of the situation, e.g. 'card declined refund'"),
68
+ platform: z.enum(["ios", "web"]).optional(),
69
+ quality: z.enum(["best", "weak"]).optional(),
70
+ limit: z.number().int().min(1).max(10).optional(),
71
+ industry: z.enum(INDUSTRIES).optional().describe("Only screens from this industry. Defaults to the repo's saved brief or .content-md.json; if that leaves nothing, all industries are searched and each result says its industry."),
72
+ },
73
+ annotations: { readOnlyHint: true },
74
+ }, async (args) => {
75
+ const industry = args.industry || repoIndustry();
76
+ let res = industry ? findExamples({ ...args, industry }) : [];
77
+ if (!res.length) res = findExamples({ ...args, industry: undefined });
78
+ return json(res);
79
+ });
80
+
81
+ if (HAS_EXAMPLES) server.registerTool("find_reference", {
82
+ title: "Find the closest reference",
83
+ description: `Optional evidence for one element in one situation. Returns the closest shipped lines, best first (often none: then write from the rules), each with its shape (opening move, sentence count, target length), the headline it sat under, a labeler note and its link. Use them to check a decision, not as a template. Pass the old line as draft when rewriting, and the tool state when copy describes progress or an outcome.`,
84
+ inputSchema: {
85
+ element: element.optional().describe("The piece you are writing, e.g. body, helper-text, headline, primary-cta"),
86
+ situation: z.string().describe("The moment in plain words, about the person's goal, not your feature name. Write it the way the references are tagged: a short clause saying what the line does for the person, e.g. 'promising a reminder before the free trial ends', 'telling the person what the page holds and what they can do there', 'promise that their data is never sold'. Call again with a second wording if the first list looks off."),
87
+ state: z.object({}).passthrough().optional().describe("What the product's own tool or API reports about the item (e.g. {status: \"submitted\", reviewed: false}). Used to find a correction example when the copy could claim more than that state supports."),
88
+ pattern: pattern.optional().describe("Boosts this pattern; omit to search every pattern"),
89
+ draft: z.string().optional().describe("The current line, when rewriting"),
90
+ platform: z.enum(["ios", "web"]).optional(),
91
+ limit: z.number().int().min(1).max(8).optional(),
92
+ role: z.string().optional().describe("The line's job inside its component, e.g. screen-title, explanation, field-helper, primary-action. Takes the place of element."),
93
+ brief: z.object({}).passthrough().optional().describe("Facts of the moment: screen_state, stakes, risk[], cause, reversibility, user_mindset, user_emotion, journey_stage, trigger. Gives tone- and situation-aware matching."),
94
+ tone: z.array(z.string()).optional().describe("Wanted tone words; omit to let the tone decider choose from the brief"),
95
+ target_words: z.number().int().optional(),
96
+ industry: z.enum(INDUSTRIES).optional().describe("The product's industry, as read_product returns it. Keeps references to comparable products and drops lines about another industry's world (a booking, a workout). Defaults to the repo's saved brief or .content-md.json."),
97
+ },
98
+ annotations: { readOnlyHint: true },
99
+ }, async (args) => {
100
+ const industry = args.industry || repoIndustry();
101
+ return json(HAS_ENRICHED ? await findReferenceV2Async({ ...args, element: normElement(args.element), industry }) : findReference(args));
102
+ });
103
+
104
+ if (HAS_ENRICHED) server.registerTool("decide_tone", {
105
+ title: "Decide the tone for a moment",
106
+ description: "Call this before find_reference when the moment has stakes or feeling (an error, a payment, a deletion, a success). Give the facts of the moment; get back two tone words, one concrete instruction, the tones to avoid and the mistakes writers are tempted to make. Voice stays the product's; tone moves with the moment.",
107
+ inputSchema: {
108
+ screen_state: z.enum(["default", "empty", "loading", "success", "error", "offline", "blocked", "confirming"]).optional(),
109
+ stakes: z.enum(["low", "medium", "high"]).optional(),
110
+ risk: z.array(z.enum(["money", "data-loss", "privacy", "security", "access", "commitment"])).optional(),
111
+ cause: z.enum(["user", "product", "third-party", "none"]).optional().describe("Who caused the problem"),
112
+ reversibility: z.enum(["reversible", "hard-to-undo", "irreversible", "n/a"]).optional(),
113
+ user_mindset: z.enum(["exploring", "evaluating", "task-focused", "hesitant", "worried", "frustrated", "stuck", "accomplished", "elsewhere"]).optional(),
114
+ user_emotion: z.string().optional(),
115
+ journey_stage: z.enum(["discover", "sign-up", "sign-in", "onboarding", "first-use", "core-task", "transaction", "upgrade", "account", "re-engagement", "support", "offboarding"]).optional(),
116
+ trigger: z.enum(["user-action", "system-event", "error", "first-launch", "time-based", "milestone"]).optional(),
117
+ audience: z.enum(["consumer", "professional", "developer"]).optional(),
118
+ voice: z.string().optional().describe("The product's voice key, e.g. plain, playful, formal; omit for plain"),
119
+ },
120
+ annotations: { readOnlyHint: true },
121
+ }, async (args) => { const d = decideTone(args); if (d.error) return json(d); return json({ tones: d.tones, also_fits: d.also_fits, instruction: d.instruction, register: d.register, purpose: d.purpose, mood: d.mood, avoid: d.wrong, tempting_mistakes: d.tempting, brief: d.brief }); });
122
+
123
+ server.registerTool("compare_to_reference", {
124
+ title: "Compare a line to its reference",
125
+ description: "Deterministic shape check of a candidate against its reference: same opening move (verb, subject, frame, noun), same sentence count, length within 30%, same ending (statement or question), plus the words they share. Run on every candidate before presenting it.",
126
+ inputSchema: {
127
+ reference: z.string().describe("The reference line exactly as shipped"),
128
+ candidate: z.string().describe("Your line"),
129
+ },
130
+ annotations: { readOnlyHint: true },
131
+ }, async (args) => json(compareToReference(args)));
132
+
133
+ server.registerTool("find_rules", {
134
+ title: "Find style-guide rules",
135
+ description: `Look up rules from ${META.sources} public style guides (NN/g, Apple HIG, Material, Polaris, GOV.UK, Atlassian, Carbon, Microsoft, Mailchimp and more), with do/don't examples. Use to settle a doubt or justify a choice.`,
136
+ inputSchema: {
137
+ pattern: pattern.optional(),
138
+ element: element.optional(),
139
+ query: z.string().optional().describe("Topic words, e.g. 'apology', 'button casing'"),
140
+ limit: z.number().int().min(1).max(20).optional(),
141
+ },
142
+ annotations: { readOnlyHint: true },
143
+ }, async (args) => json(findRules(args)));
144
+
145
+ server.registerTool("lint_copy", {
146
+ title: "Lint copy",
147
+ description: "Deterministic pass/fail checks on one screen's copy (pass the tool state, stakes and expected pieces for the full set): state overclaim, tone fence at high stakes, plural handling, verb-only buttons, missing pieces, template leaks, raw error codes, filler, generic buttons, blame words, 'Are you sure', body repeating headline, casing, length, emoji at high stakes. Severity block > warn > note. Run on every draft before presenting it.",
148
+ inputSchema: {
149
+ pattern: pattern.optional(),
150
+ units: z.array(z.object({ element, text: z.string() })).min(1).describe("Every piece of copy on the screen, in order"),
151
+ state: z.object({}).passthrough().optional().describe("What the product's tool or API reports about the item. Turns on the state-overclaim check: copy that claims approved, delivered, charged, live, complete etc. without that evidence is blocked."),
152
+ stakes: z.enum(["low", "medium", "high"]).optional().describe("From decide_tone. At high, exclamation marks and light words are flagged."),
153
+ expected_pieces: z.array(element).optional().describe("The pieces the screen needs; any missing one is blocked."),
154
+ original: z.array(z.object({ element: z.string(), text: z.string() })).optional().describe("When rewriting: the old pieces. Short originals that were changed are noted."),
155
+ allow: z.array(z.string()).optional().describe("Words or whole lines the repo's own rules or glossary accept (e.g. 'Continue', 'Inbox'); they are never flagged. Entries in the repo's .content-md.json are added automatically."),
156
+ },
157
+ annotations: { readOnlyHint: true },
158
+ }, async (args) => {
159
+ const findings = lintCopy({ ...args, allow: [...(args.allow || []), ...readConfig(process.cwd()).allow] });
160
+ const pass = !findings.some((f) => f.severity === "block" || f.severity === "warn");
161
+ return json({ pass, findings: findings.length ? findings : "No findings.", ...(pass ? {} : { next: "Fix every block and warn, then run lint_copy again, or say why you kept one." }) });
162
+ });
163
+
164
+ server.registerTool("read_product", {
165
+ title: "Read the product",
166
+ description: "Read the codebase you are working in to learn what the product is, who uses it and how it already sounds: manifest, README, landing copy, a sample of its own UI strings with file:line, and voice numbers (casing, 'we', exclamation marks, contractions, the product's own words). Call it once per session before writing or reviewing copy in a repo, then write the short product brief it asks for.",
167
+ inputSchema: {
168
+ root: z.string().optional().describe("Project root; defaults to the folder the server was started in"),
169
+ sample: z.number().int().min(5).max(80).optional(),
170
+ },
171
+ annotations: { readOnlyHint: true },
172
+ }, async (args) => json(readProduct(args)));
173
+
174
+ server.registerTool("save_product_brief", {
175
+ title: "Save the product brief",
176
+ description: "Save the product brief (and any answers the person gave) to .content-md/product.md, its own file, so later sessions start from it instead of asking again. It never edits AGENTS.md or CLAUDE.md unless you pass file. Tell the person where you saved it.",
177
+ inputSchema: {
178
+ root: z.string().optional(),
179
+ file: z.string().optional().describe("Relative path to write to; defaults to wherever the brief already is, else .content-md/product.md. Only pass AGENTS.md or CLAUDE.md if the person asks."),
180
+ fields: z.object({
181
+ product: z.string(), audience: z.string(), industry: z.string().optional(), job: z.string().optional(), voice: z.string(),
182
+ terms: z.string().optional(), stakes: z.string().optional(), constraints: z.string().optional(),
183
+ "examples of current voice": z.string().optional(),
184
+ }).passthrough(),
185
+ },
186
+ }, async (args) => json(saveProductBrief(args)));
187
+
188
+ server.registerTool("ask_person", {
189
+ title: "Ask the person",
190
+ description: "Ask the person up to two questions from read_product's `questions`, as a short form with options, where the client supports it. If it can't, it returns the questions for you to ask in chat. Only call it after checking the conversation, saved brief and repo yourself, and only for answers that change the copy.",
191
+ inputSchema: {
192
+ questions: z.array(z.object({ question: z.string(), slot: z.string().optional().describe("The read_product slot this answers; defaults to q1, q2"), options: z.array(z.string()).optional(), default: z.string().optional(), why: z.string().optional() })).min(1).max(2),
193
+ },
194
+ }, async ({ questions }) => json(await askPerson(server, questions)));
195
+
196
+ server.registerTool("audit_copy", {
197
+ title: "Audit existing copy",
198
+ description: "Find the user-facing strings in the codebase (locale files, JSX/HTML text, titles, labels, placeholders, toasts, alerts) or in a list you pass, run every lint and AI-voice check on each, and rank them worst first, weighting lines where money, data or access is at stake. Use it to decide which copy to rewrite and which to leave alone.",
199
+ inputSchema: {
200
+ root: z.string().optional(),
201
+ path_filter: z.string().optional().describe("Only strings from files whose path contains this, e.g. 'settings' or 'checkout'"),
202
+ strings: z.array(z.union([z.string(), z.object({ text: z.string(), element: element.optional() })])).optional().describe("Audit these instead of scanning the repo"),
203
+ limit: z.number().int().min(1).max(100).optional(),
204
+ },
205
+ annotations: { readOnlyHint: true },
206
+ }, async (args) => json(auditCopy(args)));
207
+
208
+ server.registerPrompt("write-copy", {
209
+ title: "Write UX copy",
210
+ description: "Write the copy for a screen or component",
211
+ argsSchema: { situation: z.string().describe("What the screen is for and what just happened") },
212
+ }, ({ situation }) => ({
213
+ messages: [{ role: "user", content: { type: "text", text: `Write the interface copy for this situation, using the content-md tools (get_guide, decide_tone when the moment has stakes, lint_copy):\n\n${situation}` } }],
214
+ }));
215
+
216
+ server.registerPrompt("review-copy", {
217
+ title: "Review UX copy",
218
+ description: "Review existing copy and fix it",
219
+ argsSchema: { copy: z.string().describe("The copy, a file path, or a description of where it lives") },
220
+ }, ({ copy }) => ({
221
+ messages: [{ role: "user", content: { type: "text", text: `Review this interface copy with the content-md tools (get_guide, lint_copy). Give a one-line verdict, then findings as original -> problem -> fix, most harmful first, then the revised copy:\n\n${copy}` } }],
222
+ }));
223
+
224
+ server.registerResource("guide", "content-md://guide", {
225
+ title: "UX writing guide", description: "Full voice guide and all pattern playbooks", mimeType: "text/markdown",
226
+ }, async (uri) => ({ contents: [{ uri: uri.href, mimeType: "text/markdown", text: getGuide({ full: true }) }] }));
227
+
228
+ await server.connect(new StdioServerTransport());
229
+ }