@contentgrapher-io/mcp-server 1.1.1

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/CHANGELOG.md ADDED
@@ -0,0 +1,28 @@
1
+ # Changelog
2
+
3
+ All notable changes to `@contentgrapher/mcp-server`.
4
+
5
+ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). This package follows [semantic versioning](https://semver.org/spec/v2.0.0.html) and tracks the ContentGrapher REST API major version.
6
+
7
+ ## [Unreleased]
8
+
9
+ ## [1.0.1]
10
+
11
+ ### Fixed
12
+
13
+ - Use `https://www.contentgrapher.io` as the API base URL. The apex host serves a Vercel-level 307 to `www`, and HTTP clients strip the `Authorization` header on cross-host redirects, causing `401 invalid_key` on every API call.
14
+
15
+ ## [1.0.0]
16
+
17
+ ### Added
18
+
19
+ - Initial implementation of v1.0.0.
20
+ - Targets ContentGrapher REST API v1.
21
+ - Five tools: `check_credits`, `analyze_url_phase1`, `complete_analysis`, `analyze_url`, `get_analysis`.
22
+ - Resource template: `contentgrapher://analyses/{id}`.
23
+ - stdio transport. Hosted Streamable HTTP transport deferred to v2.
24
+ - Progress notifications via `_meta.progressToken`.
25
+ - Local 4-slot concurrency semaphore.
26
+ - 60-second credit cache with pre-flight check on credit-bearing tools.
27
+ - Idempotency guard preventing double-billing on `complete_analysis`.
28
+ - SIGTERM and SIGINT drain handling.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ContentGrapher
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,193 @@
1
+ # @contentgrapher/mcp-server
2
+
3
+ Model Context Protocol server for [ContentGrapher](https://contentgrapher.io). Analyze web pages for structural concept completeness from Claude Code, Cursor, Windsurf, or VS Code Copilot.
4
+
5
+ ContentGrapher returns an observed concept map, 8-dimension question coverage, a coverage score (Shallow / Developing / Solid / Complete), and prioritized writing recommendations. Use it to audit documentation, technical writing, and any explanatory content that an LLM needs to retrieve from.
6
+
7
+ ## Requirements
8
+
9
+ - Node.js **20 or newer** (Node 18 reached end-of-life in April 2025).
10
+ - A ContentGrapher API key from [contentgrapher.io/account](https://contentgrapher.io/account). Generating an API key requires at least one purchased credit pack.
11
+ - An MCP-capable host (Claude Code, Cursor, Windsurf, VS Code Copilot, or any client that speaks the 2025-03-26 protocol over stdio).
12
+
13
+ ## Tools
14
+
15
+ | Tool | Cost | Returns |
16
+ |---|---|---|
17
+ | `check_credits` | Free | Purchased credits remaining, total purchased, key count, total analyses run |
18
+ | `analyze_url_phase1` | Free | Concept map, 8-question coverage, quality signals, `analysisId` |
19
+ | `complete_analysis` | 1 credit | Coverage score, prioritized recommendations, explanation framework |
20
+ | `analyze_url` | 1 credit | Phase 1 + Phase 2 in one call |
21
+ | `get_analysis` | Free | Retrieve a prior analysis result by ID |
22
+
23
+ Each tool that returns an analysis also returns an embedded `application/json` resource at `contentgrapher://analyses/{id}` containing the full response body.
24
+
25
+ ## Configuration
26
+
27
+ Generate a key at [contentgrapher.io/account](https://contentgrapher.io/account), then add the server to your IDE's MCP config.
28
+
29
+ ### Claude Code
30
+
31
+ `~/.claude/settings.json` (or project `.mcp.json`):
32
+
33
+ ```json
34
+ {
35
+ "mcpServers": {
36
+ "contentgrapher": {
37
+ "command": "npx",
38
+ "args": ["-y", "@contentgrapher/mcp-server@1"],
39
+ "env": {
40
+ "CONTENTGRAPHER_API_KEY": "cgk_your_key_here"
41
+ },
42
+ "timeout": 600000
43
+ }
44
+ }
45
+ }
46
+ ```
47
+
48
+ The `timeout: 600000` value (10 minutes in milliseconds) accommodates worst-case combined Phase 1 + Phase 2 latency.
49
+
50
+ ### Cursor
51
+
52
+ `.cursor/mcp.json`:
53
+
54
+ ```json
55
+ {
56
+ "mcpServers": {
57
+ "contentgrapher": {
58
+ "command": "npx",
59
+ "args": ["-y", "@contentgrapher/mcp-server@1"],
60
+ "env": {
61
+ "CONTENTGRAPHER_API_KEY": "cgk_your_key_here"
62
+ }
63
+ }
64
+ }
65
+ }
66
+ ```
67
+
68
+ > **Cursor timeout note:** Cursor does not expose a per-server MCP tool call timeout setting as of mid-2025, and its default timeout does not accommodate worst-case Phase 1 or Phase 2 latency. If you encounter timeout failures in Cursor, use `analyze_url_phase1` followed by `complete_analysis` in separate turns rather than `analyze_url`. Contact Cursor support for updates on configurable MCP timeouts.
69
+
70
+ ### Windsurf
71
+
72
+ `~/.codeium/windsurf/mcp_config.json`:
73
+
74
+ ```json
75
+ {
76
+ "mcpServers": {
77
+ "contentgrapher": {
78
+ "command": "npx",
79
+ "args": ["-y", "@contentgrapher/mcp-server@1"],
80
+ "env": {
81
+ "CONTENTGRAPHER_API_KEY": "${env:CONTENTGRAPHER_API_KEY}"
82
+ }
83
+ }
84
+ }
85
+ }
86
+ ```
87
+
88
+ ### VS Code Copilot
89
+
90
+ `.vscode/mcp.json` at workspace root:
91
+
92
+ ```json
93
+ {
94
+ "servers": {
95
+ "contentgrapher": {
96
+ "type": "stdio",
97
+ "command": "npx",
98
+ "args": ["-y", "@contentgrapher/mcp-server@1"],
99
+ "env": {
100
+ "CONTENTGRAPHER_API_KEY": "cgk_your_key_here"
101
+ }
102
+ }
103
+ }
104
+ }
105
+ ```
106
+
107
+ For hosts that do not support a per-server timeout field, the host's default must be at least **360 seconds**.
108
+
109
+ ## Quick examples
110
+
111
+ Once configured, ask your LLM:
112
+
113
+ > Run a ContentGrapher analysis on https://your-docs-site.com/getting-started for senior platform engineers.
114
+
115
+ The LLM calls `analyze_url` with the URL and audience. After 70-150 seconds you get the analysis ID, coverage score, top 5 recommendations, and remaining credits.
116
+
117
+ To preview the concept map without spending a credit:
118
+
119
+ > Use ContentGrapher Phase 1 on https://your-docs-site.com/getting-started.
120
+
121
+ To retrieve a prior result:
122
+
123
+ > Pull the ContentGrapher analysis with ID 550e8400-e29b-41d4-a716-446655440000.
124
+
125
+ ## API key handling
126
+
127
+ - The server reads `CONTENTGRAPHER_API_KEY` at startup, validates the format, and deletes it from `process.env`.
128
+ - The key is sent only to `https://contentgrapher.io` over HTTPS. It is never logged.
129
+ - The server is stateless. Analysis results are returned to your MCP host and not persisted by the server beyond a 60-second purchased-credits cache.
130
+
131
+ ### Pinning the version
132
+
133
+ The configuration examples above use `@1` to accept all v1.x updates. To pin to an exact version:
134
+
135
+ ```json
136
+ "args": ["-y", "@contentgrapher/mcp-server@1.0.0"]
137
+ ```
138
+
139
+ ## Concurrency
140
+
141
+ The server allows up to **4 concurrent analyses** per API key, leaving one slot in ContentGrapher's 5-request limit for the web UI and direct REST API access. A 5th in-flight `analyze_url`, `analyze_url_phase1`, or `complete_analysis` call returns a clear error immediately. `check_credits` and `get_analysis` do not consume a concurrency slot.
142
+
143
+ ## Configuration via Smithery or third-party directories
144
+
145
+ > Your API key is transmitted to and stored by Smithery (or any third-party MCP directory UI) under their own privacy policy and security controls. For maximum key security, configure the server locally via your IDE's config file as shown above, where the key is stored only on your local machine.
146
+
147
+ ## Data retention
148
+
149
+ ContentGrapher MCP is a pass-through. Analysis results are returned to your LLM host and are not stored by the MCP server. Content sent for analysis is stored in ContentGrapher's database and governed by the ContentGrapher Privacy Policy at [contentgrapher.io/legal](https://contentgrapher.io/legal).
150
+
151
+ ## Failure recovery
152
+
153
+ If a tool call is interrupted by a network failure or host timeout:
154
+
155
+ 1. Note the `analysisId` from the most recent progress notification or tool response.
156
+ 2. Call `get_analysis` with that ID:
157
+ - `status: "complete"` means Phase 2 finished and your credit was used. The full result is in the response.
158
+ - `status: "phase1_complete"` means only Phase 1 finished. Call `complete_analysis` with the same ID to run Phase 2 (this debits 1 credit).
159
+ 3. Do not call `analyze_url` again on the same URL without checking the prior `analysisId` first.
160
+
161
+ Calling `complete_analysis` on an analysis that is already `status: "complete"` returns the stored result without debiting a second credit.
162
+
163
+ ## Errors
164
+
165
+ The server maps every REST error to a plain-language tool result. Common cases:
166
+
167
+ - `Authentication failed` — check `CONTENTGRAPHER_API_KEY` is set and starts with `cgk_`.
168
+ - `No purchased credits remaining` — purchase a pack at [contentgrapher.io/pricing](https://contentgrapher.io/pricing). Only purchased credits work via the API; gift and admin credits visible in the web app cannot be debited.
169
+ - `Concurrent request limit reached` — wait for an in-flight request to complete. Stuck slots auto-recover within 15 minutes.
170
+ - `ContentGrapher could not analyze this page (422)` — the URL may be inaccessible, password-protected, JavaScript-heavy, or actively blocking crawlers.
171
+
172
+ ## Version policy
173
+
174
+ The major version of this package tracks the ContentGrapher REST API major version:
175
+
176
+ - v1.x wraps `/api/v1/`.
177
+ - A tool name change, required parameter rename, or output field rename triggers a major version bump.
178
+ - New optional parameters and new tools are minor bumps.
179
+ - Error message refinements are patch bumps.
180
+
181
+ See [CHANGELOG.md](CHANGELOG.md) for release history.
182
+
183
+ ## License
184
+
185
+ MIT — see [LICENSE](LICENSE).
186
+
187
+ ## Links
188
+
189
+ - ContentGrapher: [contentgrapher.io](https://contentgrapher.io)
190
+ - Account and key management: [contentgrapher.io/account](https://contentgrapher.io/account)
191
+ - Pricing: [contentgrapher.io/pricing](https://contentgrapher.io/pricing)
192
+ - Docs page for this MCP server: [contentgrapher.io/docs/mcp](https://contentgrapher.io/docs/mcp)
193
+ - Issues: [github.com/contentgrapher/mcp-server/issues](https://github.com/contentgrapher/mcp-server/issues)
@@ -0,0 +1,108 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { BASE_URL } from "./config.js";
5
+ import { ApiError, NetworkError, TimeoutError, } from "./errors.js";
6
+ // Pull version from package.json so the User-Agent always tracks the published
7
+ // release. The compiled output lives at dist/api-client.js; package.json is one
8
+ // level up. The contentgrapher.io admin reporting reads the `ContentGrapher-MCP/`
9
+ // prefix to distinguish MCP traffic from raw API key usage.
10
+ const pkgPath = join(dirname(fileURLToPath(import.meta.url)), "..", "package.json");
11
+ const { version: VERSION } = JSON.parse(readFileSync(pkgPath, "utf8"));
12
+ const USER_AGENT = `ContentGrapher-MCP/${VERSION}`;
13
+ async function readJsonBody(res) {
14
+ try {
15
+ const text = await res.text();
16
+ if (!text)
17
+ return null;
18
+ return JSON.parse(text);
19
+ }
20
+ catch {
21
+ return null;
22
+ }
23
+ }
24
+ export class ApiClient {
25
+ opts;
26
+ constructor(opts) {
27
+ this.opts = opts;
28
+ }
29
+ async request(opts) {
30
+ const controller = new AbortController();
31
+ const timeoutMs = opts.timeoutSeconds * 1000;
32
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
33
+ const onExternalAbort = () => controller.abort();
34
+ if (opts.signal)
35
+ opts.signal.addEventListener("abort", onExternalAbort);
36
+ try {
37
+ const res = await fetch(`${BASE_URL}${opts.path}`, {
38
+ method: opts.method,
39
+ headers: {
40
+ Authorization: `Bearer ${this.opts.apiKey}`,
41
+ Accept: "application/json",
42
+ ...(opts.body !== undefined
43
+ ? { "Content-Type": "application/json" }
44
+ : {}),
45
+ "User-Agent": USER_AGENT,
46
+ "X-MCP-Tool": opts.tool,
47
+ },
48
+ body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined,
49
+ signal: controller.signal,
50
+ });
51
+ if (!res.ok) {
52
+ const body = await readJsonBody(res);
53
+ throw new ApiError(res.status, body, `HTTP ${res.status} ${res.statusText}`);
54
+ }
55
+ const text = await res.text();
56
+ return (text ? JSON.parse(text) : {});
57
+ }
58
+ catch (err) {
59
+ if (err instanceof ApiError)
60
+ throw err;
61
+ if (err instanceof Error &&
62
+ (err.name === "AbortError" ||
63
+ err.code === "ABORT_ERR")) {
64
+ throw new TimeoutError(opts.timeoutSeconds);
65
+ }
66
+ throw new NetworkError(err);
67
+ }
68
+ finally {
69
+ clearTimeout(timer);
70
+ if (opts.signal)
71
+ opts.signal.removeEventListener("abort", onExternalAbort);
72
+ }
73
+ }
74
+ getMe(tool) {
75
+ return this.request({
76
+ method: "GET",
77
+ path: "/api/v1/me",
78
+ tool,
79
+ timeoutSeconds: 10,
80
+ });
81
+ }
82
+ createPhase1(body, tool) {
83
+ return this.request({
84
+ method: "POST",
85
+ path: "/api/v1/analyses",
86
+ tool,
87
+ body,
88
+ timeoutSeconds: 295,
89
+ });
90
+ }
91
+ completePhase2(analysisId, body, tool) {
92
+ return this.request({
93
+ method: "POST",
94
+ path: `/api/v1/analyses/${analysisId}/complete`,
95
+ tool,
96
+ body,
97
+ timeoutSeconds: 280,
98
+ });
99
+ }
100
+ getAnalysis(analysisId, tool) {
101
+ return this.request({
102
+ method: "GET",
103
+ path: `/api/v1/analyses/${analysisId}`,
104
+ tool,
105
+ timeoutSeconds: 10,
106
+ });
107
+ }
108
+ }
package/dist/config.js ADDED
@@ -0,0 +1,18 @@
1
+ import { validateKeyFormat } from "./key-validation.js";
2
+ export const BASE_URL = "https://www.contentgrapher.io";
3
+ export function reportUrlFor(analysisId) {
4
+ return `${BASE_URL}/report/${analysisId}`;
5
+ }
6
+ export function loadConfigOrExit() {
7
+ const apiKey = process.env.CONTENTGRAPHER_API_KEY;
8
+ if (!apiKey) {
9
+ process.stderr.write('ContentGrapher MCP Server: CONTENTGRAPHER_API_KEY is not set. Set this environment variable to a key starting with "cgk_" generated from https://contentgrapher.io/account.\n');
10
+ process.exit(1);
11
+ }
12
+ delete process.env.CONTENTGRAPHER_API_KEY;
13
+ if (!validateKeyFormat(apiKey)) {
14
+ process.stderr.write('ContentGrapher MCP Server: CONTENTGRAPHER_API_KEY is malformed. Expected format: "cgk_" followed by 43 base64url characters (letters, digits, hyphens, and underscores). Generate a key at https://contentgrapher.io/account.\n');
15
+ process.exit(1);
16
+ }
17
+ return { apiKey };
18
+ }
@@ -0,0 +1,17 @@
1
+ const TTL_MS = 60_000;
2
+ let entry = null;
3
+ export function getCachedCredits(now = Date.now()) {
4
+ if (!entry)
5
+ return null;
6
+ if (now - entry.storedAt > TTL_MS) {
7
+ entry = null;
8
+ return null;
9
+ }
10
+ return entry.creditsRemaining;
11
+ }
12
+ export function setCachedCredits(creditsRemaining, now = Date.now()) {
13
+ entry = { creditsRemaining, storedAt: now };
14
+ }
15
+ export function clearCachedCredits() {
16
+ entry = null;
17
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,105 @@
1
+ export class ApiError extends Error {
2
+ status;
3
+ body;
4
+ constructor(status, body, message) {
5
+ super(message);
6
+ this.status = status;
7
+ this.body = body;
8
+ this.name = "ApiError";
9
+ }
10
+ }
11
+ export class TimeoutError extends Error {
12
+ seconds;
13
+ constructor(seconds) {
14
+ super(`Request timed out after ${seconds} seconds`);
15
+ this.seconds = seconds;
16
+ this.name = "TimeoutError";
17
+ }
18
+ }
19
+ export class NetworkError extends Error {
20
+ cause;
21
+ constructor(cause) {
22
+ super("Network error");
23
+ this.cause = cause;
24
+ this.name = "NetworkError";
25
+ }
26
+ }
27
+ export class SemaphoreSaturatedError extends Error {
28
+ constructor() {
29
+ super("Local MCP semaphore saturated");
30
+ this.name = "SemaphoreSaturatedError";
31
+ }
32
+ }
33
+ const SERVER_DETAIL = (body) => {
34
+ const msg = body?.message ?? body?.error;
35
+ return msg ? `\n\nDetails from the server: ${msg}` : "";
36
+ };
37
+ export function describe400(body) {
38
+ return `The request was malformed. Common causes:
39
+ - Missing or empty url field
40
+ - Invalid URL format (must be http or https; private or localhost addresses are not supported)
41
+ - audience parameter exceeds 500 characters${SERVER_DETAIL(body)}`;
42
+ }
43
+ export const DESCRIBE_401 = 'Authentication failed. The ContentGrapher API key is missing or not recognized. Verify that CONTENTGRAPHER_API_KEY is set correctly in your MCP server configuration and starts with "cgk_". Generate a new key at https://contentgrapher.io/account if needed.';
44
+ export const DESCRIBE_402 = `No purchased credits remaining (balance: 0). Phase 2 analyses require purchased credits. Gift or admin credits visible in the web app cannot be debited via the API. Purchase a credit pack at https://contentgrapher.io/pricing:
45
+ - Starter: 10 credits / $29
46
+ - Growth: 50 credits / $59
47
+ - Studio: 150 credits / $149
48
+ Credits are available immediately after purchase.`;
49
+ export const DESCRIBE_403 = "This API key has been revoked. Generate a new key at https://contentgrapher.io/account. If you believe this is an error, check the key list on your account page.";
50
+ export function describe404(analysisId) {
51
+ return `Analysis ID "${analysisId}" was not found. Either the ID is incorrect, it belongs to a different account, or Phase 1 has not yet completed persisting the result. Verify the ID and try again.`;
52
+ }
53
+ export const DESCRIBE_409 = "Phase 2 cannot start because Phase 1 has not completed for this analysis ID. Use analyze_url_phase1 to run Phase 1 first, or use analyze_url to run both phases together.";
54
+ export const DESCRIBE_422 = `ContentGrapher could not analyze this page. The URL may be:
55
+ - Inaccessible or returning an error
56
+ - Password-protected or behind a login wall
57
+ - A JavaScript-heavy single-page app that does not render to a crawler
58
+ - Actively blocking crawlers
59
+
60
+ Verify the URL loads correctly in a browser with JavaScript disabled. Try a publicly accessible version of the page.`;
61
+ export const DESCRIBE_429 = "Concurrent request limit reached. ContentGrapher allows 5 simultaneous in-flight requests per API key. Your key currently has the maximum number of requests in progress. Wait for one to complete, then retry. If you believe requests are stuck, the server automatically recovers idle slots within 15 minutes (10 minutes stuck threshold plus up to 5 minutes until the next cleanup cycle).";
62
+ export function describe503(analysisId) {
63
+ const tail = analysisId
64
+ ? `\n\nAnalysis ID: ${analysisId}. Call get_analysis("${analysisId}") to confirm whether a result was saved despite the error.`
65
+ : "";
66
+ return `ContentGrapher pipeline error. The analysis did not complete. Any credit debited for this request has been automatically refunded. Verify with check_credits. Wait 30 seconds and retry. If the error persists on the same URL, the page content may be too large or structurally unusual for the current pipeline version.${tail}`;
67
+ }
68
+ export const DESCRIBE_SEMAPHORE_SATURATED = "Too many concurrent analyses in progress on this API key (maximum 4 via MCP server). Wait for a current analysis to complete before starting another.";
69
+ export function describePhase1Timeout() {
70
+ return "Phase 1 did not complete within 295 seconds. The analysis may still be running on the ContentGrapher server. There is no analysisId to recover with: Phase 1 did not persist a result before timing out. If this URL consistently times out, the page may be too large for reliable analysis. Try again or try a shorter page.";
71
+ }
72
+ export function describePhase2Timeout(analysisId) {
73
+ return `Phase 2 did not complete within 280 seconds. Analysis ID: ${analysisId}. The analysis may still be completing on the ContentGrapher server. Call get_analysis("${analysisId}") to check. If status is "complete", your credit was used and the full result is available. If status is "phase1_complete", Phase 2 did not finish: you can call complete_analysis("${analysisId}") to retry (note: this debits another credit). Your credit was debited; do not call analyze_url on this URL again without checking get_analysis first.`;
74
+ }
75
+ export function describePhase2NetworkError(analysisId) {
76
+ return `The connection to ContentGrapher was interrupted during Phase 2. Analysis ID: ${analysisId}. Call get_analysis("${analysisId}") to determine whether the analysis completed. If status is "complete", your credit was used. If status is "phase1_complete", the analysis did not finish; your credit may or may not have been refunded. Check your balance with check_credits and contact support if you believe a credit was lost.`;
77
+ }
78
+ export function describe402AfterPhase1(analysisId) {
79
+ return `Phase 1 completed successfully. Analysis ID: ${analysisId}. Phase 2 could not start: no purchased credits remaining. Your Phase 1 result is saved. Purchase credits at https://contentgrapher.io/pricing and call complete_analysis("${analysisId}") to run Phase 2 without repeating Phase 1. Your Phase 1 result is stored and will not expire.`;
80
+ }
81
+ export function describeApiError(err, ctx = {}) {
82
+ const aid = ctx.analysisId ?? null;
83
+ switch (err.status) {
84
+ case 400:
85
+ return describe400(err.body);
86
+ case 401:
87
+ return DESCRIBE_401;
88
+ case 402:
89
+ return ctx.phase1Complete && aid ? describe402AfterPhase1(aid) : DESCRIBE_402;
90
+ case 403:
91
+ return DESCRIBE_403;
92
+ case 404:
93
+ return aid ? describe404(aid) : describe404("unknown");
94
+ case 409:
95
+ return DESCRIBE_409;
96
+ case 422:
97
+ return DESCRIBE_422;
98
+ case 429:
99
+ return DESCRIBE_429;
100
+ case 503:
101
+ return describe503(aid);
102
+ default:
103
+ return `ContentGrapher returned an unexpected error (HTTP ${err.status}). Wait 30 seconds and retry. If the error persists, contact support at https://contentgrapher.io.`;
104
+ }
105
+ }
@@ -0,0 +1,107 @@
1
+ import { formatScoreLines } from "./coverage-score.js";
2
+ import { conceptMapHeading, summarizeConceptMap } from "./concept-map.js";
3
+ import { formatAudience, formatPhase1AudienceField } from "./audience.js";
4
+ import { summarizeQuestionCoverage } from "./question-labels.js";
5
+ import { formatQualitySignals } from "./quality-signals.js";
6
+ import { formatRecommendations } from "./recommendations.js";
7
+ import { formatBoundaryWarning, selectPrr } from "./page-architecture.js";
8
+ import { reportUrlFor } from "../config.js";
9
+ import { computeDone } from "../types.js";
10
+ const FULL_REPORT_HINT = "Open the full visual breakdown — concept graph, evidence panels, explanation framework — in the ContentGrapher web app";
11
+ const URL_NOT_AVAILABLE = "not available — retrieved by analysis ID only";
12
+ function blank(parts) {
13
+ return parts.filter((p) => Boolean(p && p.length > 0)).join("\n");
14
+ }
15
+ export function buildPhase1Text(opts) {
16
+ const r = opts.resource;
17
+ const map = summarizeConceptMap(r.observedMap);
18
+ const qc = summarizeQuestionCoverage(r.questionCoverage);
19
+ const qs = formatQualitySignals(r.qualitySignals);
20
+ const conceptBlock = blank([
21
+ conceptMapHeading(map.total),
22
+ ...map.lines,
23
+ ]);
24
+ const questionBlock = blank([
25
+ `Question coverage (${qc.addressedCount}/${qc.totalCount} addressed):`,
26
+ ...qc.addressedLabels.map((l) => `- ${l}`),
27
+ ]);
28
+ return blank([
29
+ `Analysis ID: ${r.analysisId}`,
30
+ `URL: ${opts.url ?? URL_NOT_AVAILABLE}`,
31
+ `Full report: ${reportUrlFor(r.analysisId)} — ${FULL_REPORT_HINT}.`,
32
+ formatPhase1AudienceField(opts.audience),
33
+ `Primary Retrieval Role: ${r.context.primaryRetrievalRole}`,
34
+ "",
35
+ conceptBlock,
36
+ "",
37
+ questionBlock,
38
+ "",
39
+ `Quality signals: ${qs}`,
40
+ "",
41
+ `To get writing recommendations and a coverage score, call complete_analysis with analysisId: ${r.analysisId} (costs 1 credit).`,
42
+ ]);
43
+ }
44
+ const DONE_REASON_LABEL = {
45
+ done: "all essential concepts covered, score in the complete band (≥ 70%)",
46
+ split: "page is flagged to split — two jobs, not one finished page",
47
+ missing_essentials: "one or more essential concepts are absent from the content",
48
+ partial_essentials: "one or more essential concepts are present but underdeveloped",
49
+ below_complete_band: "coverage score is below the complete band (< 70%)",
50
+ no_score: "coverage score unavailable",
51
+ };
52
+ export function buildPhase2Text(opts) {
53
+ const r = opts.resource;
54
+ const scoreLines = formatScoreLines(r.coverageScore);
55
+ const prr = selectPrr(r.context?.primaryRetrievalRole, r.pageArchitecture);
56
+ const warning = formatBoundaryWarning(r.pageArchitecture);
57
+ const recs = formatRecommendations(r.recommendations ?? [], r.analysisId);
58
+ const { done, reason } = computeDone(r);
59
+ const doneLabel = done
60
+ ? `DONE — ${DONE_REASON_LABEL["done"]}`
61
+ : `NOT DONE — ${DONE_REASON_LABEL[reason] ?? reason}`;
62
+ return blank([
63
+ `Analysis ID: ${r.analysisId}`,
64
+ `Status: complete`,
65
+ `Done: ${doneLabel}`,
66
+ `URL: ${opts.url ?? URL_NOT_AVAILABLE}`,
67
+ `Full report: ${reportUrlFor(r.analysisId)} — ${FULL_REPORT_HINT}.`,
68
+ formatAudience(opts.audience),
69
+ "",
70
+ ...scoreLines,
71
+ "",
72
+ `Primary Retrieval Role: ${prr}`,
73
+ warning,
74
+ "",
75
+ "Top recommendations (ordered by priority):",
76
+ "",
77
+ ...recs.lines,
78
+ recs.truncationNote ? "" : null,
79
+ recs.truncationNote,
80
+ "",
81
+ opts.creditsRemaining !== null
82
+ ? `Credits remaining after this call: ${opts.creditsRemaining}`
83
+ : null,
84
+ ]);
85
+ }
86
+ export function buildPhase1OnlyFromGetText(resource) {
87
+ const map = summarizeConceptMap(resource.observedMap);
88
+ const qc = summarizeQuestionCoverage(resource.questionCoverage);
89
+ const qs = formatQualitySignals(resource.qualitySignals);
90
+ return blank([
91
+ `Analysis ID: ${resource.analysisId}`,
92
+ "Status: Phase 1 complete — Phase 2 has not run yet.",
93
+ `URL: ${URL_NOT_AVAILABLE}`,
94
+ `Full report: ${reportUrlFor(resource.analysisId)} — ${FULL_REPORT_HINT}.`,
95
+ `Primary Retrieval Role: ${resource.context.primaryRetrievalRole}`,
96
+ "",
97
+ conceptMapHeading(map.total),
98
+ ...map.lines,
99
+ "",
100
+ `Question coverage (${qc.addressedCount}/${qc.totalCount} addressed):`,
101
+ ...qc.addressedLabels.map((l) => `- ${l}`),
102
+ "",
103
+ `Quality signals: ${qs}`,
104
+ "",
105
+ `To get writing recommendations and a coverage score, call complete_analysis with this analysisId (costs 1 credit).`,
106
+ ]);
107
+ }
@@ -0,0 +1,11 @@
1
+ export function formatAudience(audience) {
2
+ return audience && audience.length > 0
3
+ ? `Audience: ${audience}`
4
+ : "Audience: not specified";
5
+ }
6
+ export function formatPhase1AudienceField(audience) {
7
+ if (audience && audience.length > 0) {
8
+ return `Audience (for Phase 2 if passed to complete_analysis): ${audience}`;
9
+ }
10
+ return "Audience (for Phase 2 if passed to complete_analysis): not specified — pass audience to complete_analysis for targeted Phase 2 recommendations";
11
+ }
@@ -0,0 +1,31 @@
1
+ const ORDER = [
2
+ "well-integrated",
3
+ "weakly-integrated",
4
+ "underexplained",
5
+ "naming-inconsistent",
6
+ ];
7
+ const DISPLAY = {
8
+ "well-integrated": "Well integrated",
9
+ "weakly-integrated": "Weakly integrated",
10
+ underexplained: "Underexplained",
11
+ "naming-inconsistent": "Naming inconsistent",
12
+ };
13
+ export function summarizeConceptMap(map) {
14
+ const concepts = Array.isArray(map.concepts) ? map.concepts : [];
15
+ const counts = {
16
+ "well-integrated": 0,
17
+ "weakly-integrated": 0,
18
+ underexplained: 0,
19
+ "naming-inconsistent": 0,
20
+ };
21
+ for (const c of concepts) {
22
+ if (c.classification in counts) {
23
+ counts[c.classification] += 1;
24
+ }
25
+ }
26
+ const lines = ORDER.map((k) => `- ${DISPLAY[k]}: ${counts[k]}`);
27
+ return { total: concepts.length, lines };
28
+ }
29
+ export function conceptMapHeading(total) {
30
+ return `Concept map — ${total} concepts identified:`;
31
+ }