@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.
@@ -0,0 +1,29 @@
1
+ export function bandForScore(score) {
2
+ if (score >= 0.70)
3
+ return "Complete";
4
+ if (score >= 0.55)
5
+ return "Solid";
6
+ if (score >= 0.35)
7
+ return "Developing";
8
+ return "Shallow";
9
+ }
10
+ const VERDICTS = {
11
+ Complete: "This page has strong structural coverage for its retrieval role.",
12
+ Solid: "This page covers most core concepts but has notable gaps.",
13
+ Developing: "This page covers foundational concepts but is missing significant depth.",
14
+ Shallow: "This page has substantial structural gaps that limit its retrieval effectiveness.",
15
+ };
16
+ export function verdictForBand(band) {
17
+ return VERDICTS[band];
18
+ }
19
+ export function formatScoreLines(score) {
20
+ if (score === null) {
21
+ return ["Coverage Score: not available (score could not be computed)"];
22
+ }
23
+ const band = bandForScore(score);
24
+ const percent = Math.round(score * 100);
25
+ return [
26
+ `Coverage Score: ${score.toFixed(2)} (${percent}%) — ${band}`,
27
+ verdictForBand(band),
28
+ ];
29
+ }
@@ -0,0 +1,16 @@
1
+ export function formatBoundaryWarning(pa) {
2
+ if (!pa || pa.structuralDecision !== "split")
3
+ return null;
4
+ const reasons = Array.isArray(pa.reasons) ? pa.reasons : [];
5
+ const reasonsLine = reasons.length > 0 ? reasons.join("; ") : "boundary violation detected";
6
+ const split = Array.isArray(pa.proposedPages)
7
+ ? ` Proposed split: ${pa.proposedPages.length} pages.`
8
+ : "";
9
+ return `Warning: ${reasonsLine}.${split}`;
10
+ }
11
+ export function selectPrr(contextPrr, pa) {
12
+ if (pa?.primaryRetrievalRole && pa.primaryRetrievalRole.length > 0) {
13
+ return pa.primaryRetrievalRole;
14
+ }
15
+ return contextPrr ?? "unknown";
16
+ }
@@ -0,0 +1,15 @@
1
+ function percent(v) {
2
+ return `${Math.round(v * 100)}%`;
3
+ }
4
+ export function formatQualitySignals(qs) {
5
+ const density = qs.conceptDensity.toFixed(1);
6
+ const parts = [
7
+ `Concept density ${density}/1,000 chars`,
8
+ `core concept ratio ${percent(qs.coreConceptRatio)}`,
9
+ `question coverage ${percent(qs.questionCoverageRate)}`,
10
+ ];
11
+ if (qs.anchorMatchRate !== null && qs.anchorMatchRate !== undefined) {
12
+ parts.push(`anchor match rate ${percent(qs.anchorMatchRate)}`);
13
+ }
14
+ return parts.join("; ") + ".";
15
+ }
@@ -0,0 +1,34 @@
1
+ export const QUESTION_LABELS = {
2
+ whatIsIt: "What is it?",
3
+ howDoesItWork: "How does it work?",
4
+ whatDoesItDependOn: "What does it depend on?",
5
+ whatDoesItAffectOrProduce: "What does it affect or produce?",
6
+ whoInteractsWithIt: "Who interacts with it?",
7
+ whatConstraintsMatter: "What constraints matter?",
8
+ whatAlternativesOrDistinctionsMatter: "What alternatives or distinctions matter?",
9
+ whatExampleGroundsIt: "What example grounds it?",
10
+ };
11
+ const ORDER = [
12
+ "whatIsIt",
13
+ "howDoesItWork",
14
+ "whatDoesItDependOn",
15
+ "whatDoesItAffectOrProduce",
16
+ "whoInteractsWithIt",
17
+ "whatConstraintsMatter",
18
+ "whatAlternativesOrDistinctionsMatter",
19
+ "whatExampleGroundsIt",
20
+ ];
21
+ export function summarizeQuestionCoverage(qc) {
22
+ const addressedLabels = [];
23
+ for (const key of ORDER) {
24
+ const item = qc[key];
25
+ if (item && item.covered === true) {
26
+ addressedLabels.push(QUESTION_LABELS[key]);
27
+ }
28
+ }
29
+ return {
30
+ addressedCount: addressedLabels.length,
31
+ totalCount: ORDER.length,
32
+ addressedLabels,
33
+ };
34
+ }
@@ -0,0 +1,20 @@
1
+ const PREFIXES = {
2
+ add: "[ADD]",
3
+ clarify: "[CLARIFY]",
4
+ restructure: "[RESTRUCTURE]",
5
+ };
6
+ const MAX_DISPLAYED = 5;
7
+ export function formatRecommendation(r, index) {
8
+ const prefix = PREFIXES[r.type] ?? `[${String(r.type).toUpperCase()}]`;
9
+ const section = r.section ? ` › ${r.section}` : "";
10
+ return `${index + 1}. ${prefix} ${r.conceptName}${section} — ${r.instruction}`;
11
+ }
12
+ export function formatRecommendations(recs, analysisId) {
13
+ const displayed = recs.slice(0, MAX_DISPLAYED);
14
+ const lines = displayed.map((r, i) => formatRecommendation(r, i));
15
+ const extra = recs.length - displayed.length;
16
+ const truncationNote = extra > 0
17
+ ? `${extra} additional recommendation${extra === 1 ? "" : "s"} are in the embedded JSON resource for this tool call (resource URI: contentgrapher://analyses/${analysisId}). Access the full list via the resource content item returned alongside this response.`
18
+ : null;
19
+ return { lines, truncationNote };
20
+ }
package/dist/index.js ADDED
@@ -0,0 +1,17 @@
1
+ #!/usr/bin/env node
2
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
3
+ import { loadConfigOrExit } from "./config.js";
4
+ import { createServer } from "./server.js";
5
+ import { registerSignalHandlers } from "./signals.js";
6
+ async function main() {
7
+ registerSignalHandlers();
8
+ const config = loadConfigOrExit();
9
+ const server = createServer({ apiKey: config.apiKey });
10
+ const transport = new StdioServerTransport();
11
+ await server.connect(transport);
12
+ }
13
+ main().catch((err) => {
14
+ const msg = err instanceof Error ? err.message : String(err);
15
+ process.stderr.write(`ContentGrapher MCP Server: fatal startup error: ${msg}\n`);
16
+ process.exit(1);
17
+ });
@@ -0,0 +1,21 @@
1
+ const KEY_RE = /^cgk_[A-Za-z0-9_-]{43}$/;
2
+ export function validateKeyFormat(key) {
3
+ return KEY_RE.test(key);
4
+ }
5
+ export const KEY_FORMAT_ERROR = 'The ContentGrapher API key is malformed. Expected format: "cgk_" followed by 43 base64url characters (letters, digits, hyphens, and underscores), total 47 characters. Verify CONTENTGRAPHER_API_KEY in your MCP configuration. Generate a key at https://contentgrapher.io/account.';
6
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
7
+ export function validateAnalysisId(id) {
8
+ return UUID_RE.test(id);
9
+ }
10
+ const URL_RE = /^https?:\/\/[^\s]+$/i;
11
+ export function validateUrlFormat(url) {
12
+ if (!URL_RE.test(url))
13
+ return false;
14
+ try {
15
+ const parsed = new URL(url);
16
+ return parsed.protocol === "http:" || parsed.protocol === "https:";
17
+ }
18
+ catch {
19
+ return false;
20
+ }
21
+ }
@@ -0,0 +1,40 @@
1
+ export function startProgressTicker(opts) {
2
+ if (opts.progressToken === undefined || opts.progressToken === null) {
3
+ return () => { };
4
+ }
5
+ const intervalMs = opts.intervalMs ?? 15_000;
6
+ const startedAt = Date.now();
7
+ let progress = 0;
8
+ const interval = setInterval(() => {
9
+ progress += 1;
10
+ const elapsed = Math.round((Date.now() - startedAt) / 1000);
11
+ void Promise.resolve((async () => {
12
+ try {
13
+ await opts.send({
14
+ progressToken: opts.progressToken,
15
+ progress,
16
+ message: opts.message(elapsed),
17
+ });
18
+ }
19
+ catch {
20
+ // notification failure must not abort the tool call
21
+ }
22
+ })());
23
+ }, intervalMs);
24
+ return () => {
25
+ clearInterval(interval);
26
+ if (opts.doneMessage !== undefined) {
27
+ void sendProgressNow(opts.send, opts.progressToken, opts.doneMessage, progress + 1);
28
+ }
29
+ };
30
+ }
31
+ export async function sendProgressNow(send, progressToken, message, progress) {
32
+ if (progressToken === undefined || progressToken === null)
33
+ return;
34
+ try {
35
+ await send({ progressToken, progress, message });
36
+ }
37
+ catch {
38
+ // ignore
39
+ }
40
+ }
@@ -0,0 +1,42 @@
1
+ import { SemaphoreSaturatedError } from "./errors.js";
2
+ export class Semaphore {
3
+ max;
4
+ inFlight = 0;
5
+ draining = false;
6
+ constructor(max) {
7
+ this.max = max;
8
+ }
9
+ tryAcquire() {
10
+ if (this.draining)
11
+ return false;
12
+ if (this.inFlight >= this.max)
13
+ return false;
14
+ this.inFlight += 1;
15
+ return true;
16
+ }
17
+ release() {
18
+ if (this.inFlight > 0)
19
+ this.inFlight -= 1;
20
+ }
21
+ count() {
22
+ return this.inFlight;
23
+ }
24
+ startDraining() {
25
+ this.draining = true;
26
+ }
27
+ isDraining() {
28
+ return this.draining;
29
+ }
30
+ }
31
+ export async function withSemaphore(sem, fn) {
32
+ if (!sem.tryAcquire()) {
33
+ throw new SemaphoreSaturatedError();
34
+ }
35
+ try {
36
+ return await fn();
37
+ }
38
+ finally {
39
+ sem.release();
40
+ }
41
+ }
42
+ export const sharedSemaphore = new Semaphore(4);
package/dist/server.js ADDED
@@ -0,0 +1,220 @@
1
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
2
+ import { CallToolRequestSchema, ListResourceTemplatesRequestSchema, ListToolsRequestSchema, ReadResourceRequestSchema, } from "@modelcontextprotocol/sdk/types.js";
3
+ import { ApiClient } from "./api-client.js";
4
+ import { runAnalyzeUrl } from "./tools/analyze-url.js";
5
+ import { runAnalyzeUrlPhase1 } from "./tools/analyze-url-phase1.js";
6
+ import { runCheckCredits } from "./tools/check-credits.js";
7
+ import { runCompleteAnalysis } from "./tools/complete-analysis.js";
8
+ import { runGetAnalysis } from "./tools/get-analysis.js";
9
+ const SERVER_INFO = {
10
+ name: "contentgrapher",
11
+ version: "1.1.0",
12
+ };
13
+ const INSTRUCTIONS = `ContentGrapher analyzes web pages for structural concept completeness: whether a page covers the right concepts at the right depth for its audience. Use \`check_credits\` to see your balance before running paid analysis. Use \`analyze_url\` to run a full analysis (costs 1 credit, typically 70-150 seconds). Use \`analyze_url_phase1\` for a free concept map only. Each call creates a new independent analysis with a new ID. Use \`complete_analysis\` to run Phase 2 on an existing analysis ID. Use \`get_analysis\` to retrieve a previous result by ID. Analyses run sequentially; the MCP server allows up to 4 concurrent analyses per key (reserving one REST API slot for direct access). For batch analysis across multiple URLs, call \`analyze_url\` once per URL in sequence.`;
14
+ const CHECK_CREDITS_DESC = "Check your ContentGrapher credit balance and API key status. Returns purchased credits remaining, total credits purchased, number of active keys, and total analyses run. Use this before running a batch of Phase 2 analyses or when troubleshooting a 402 error. Note: only purchased credits count toward API access. Gift or admin credits cannot be debited via the API, though they may appear as a non-zero balance in the ContentGrapher web UI.";
15
+ const ANALYZE_URL_PHASE1_DESC = "Analyze a web page's structural concept map using ContentGrapher Phase 1. Returns the observed concept map, question coverage across 8 diagnostic dimensions, and quality signals. Free, no credit cost. Returns an analysisId that can be passed to complete_analysis to run Phase 2. Each call creates a new independent analysis with a new ID; if you have already run Phase 1 on a URL, use get_analysis with the prior analysisId rather than re-running Phase 1. The concept map flags weakly-integrated and underexplained concepts (`observedMap.concepts[].integrationState`) that the user may want to strengthen in the page's source content.";
16
+ const COMPLETE_ANALYSIS_DESC = "Run Phase 2 analysis on an existing ContentGrapher analysis ID. Returns a coverage score (0-1), a prioritized list of writing recommendations with specific instructions, an explanation framework, writing guidance, and page architecture decisions. Costs 1 purchased credit per call. If this call is interrupted or times out, the analysis may still complete on the server: call get_analysis with the same analysisId to check before retrying. Calling complete_analysis on an analysisId that already has a complete result will return the stored result without debiting a second credit (MCP idempotency guard). Each recommendation includes a `concept`, `section`, `type` (`add`/`clarify`/`restructure`), and an actionable `instruction` suitable for editing the source file behind this URL; `pageArchitecture` may propose splitting the page into multiple URLs with per-page concept assignments.";
17
+ const ANALYZE_URL_DESC = "Analyze a web page for structural content completeness in one step. Runs Phase 1 (concept mapping, free) followed by Phase 2 (coverage score and prioritized writing recommendations, costs 1 credit). Use this when you want a complete content audit without separately inspecting the Phase 1 concept map. If interrupted, call get_analysis with the returned analysisId to retrieve results: do not call analyze_url again on the same URL without checking first, as the credit was already debited. Typical runtime: 70-150 seconds. Worst case: approximately 10 minutes for large pages on slow LLM responses. Each recommendation includes a `concept`, `section`, `type` (`add`/`clarify`/`restructure`), and an actionable `instruction` suitable for editing the source file behind this URL.";
18
+ const GET_ANALYSIS_DESC = "Retrieve a stored ContentGrapher analysis result by ID. Returns the full analysis if Phase 2 is complete, or the Phase 1 concept map if only Phase 1 has run. No credit cost. Use this to recover from an interrupted analyze_url or complete_analysis call before retrying, retrieve a previous analysis result by ID, or check whether a Phase 2 call that timed out has since completed on the server.";
19
+ const URL_PROP = {
20
+ type: "string",
21
+ description: "The full URL of the page to analyze. Must be publicly accessible. Example: https://example.com/docs/getting-started",
22
+ };
23
+ const AUDIENCE_PROP_PHASE1 = {
24
+ type: "string",
25
+ maxLength: 500,
26
+ description: "Who this content is written for. This value is accepted and stored for use by Phase 2 if you pass the same analysisId to complete_analysis. Phase 1 concept mapping is audience-agnostic: providing audience here does not affect the Phase 1 output. Pass audience to complete_analysis for targeted Phase 2 recommendations. Examples: 'senior software engineers evaluating monitoring tools', 'marketing managers new to content strategy'.",
27
+ };
28
+ const AUDIENCE_PROP_PHASE2 = {
29
+ type: "string",
30
+ maxLength: 500,
31
+ description: "Audience for Phase 2 analysis. Phase 1 concept mapping is audience-agnostic; this value is used only by Phase 2 framework generation. Optional: if omitted, Phase 2 generates a general explanation framework without audience targeting.",
32
+ };
33
+ const ANALYSIS_ID_PROP_FOR_COMPLETE = {
34
+ type: "string",
35
+ description: "The analysis ID returned by analyze_url_phase1 or analyze_url. Must be a UUID from an analysis belonging to your account.",
36
+ };
37
+ const ANALYSIS_ID_PROP_FOR_GET = {
38
+ type: "string",
39
+ description: "The UUID returned by a previous analyze_url, analyze_url_phase1, or complete_analysis call.",
40
+ };
41
+ const TOOLS = [
42
+ {
43
+ name: "check_credits",
44
+ description: CHECK_CREDITS_DESC,
45
+ inputSchema: { type: "object", properties: {}, required: [] },
46
+ annotations: {
47
+ readOnlyHint: true,
48
+ destructiveHint: false,
49
+ idempotentHint: true,
50
+ openWorldHint: true,
51
+ },
52
+ },
53
+ {
54
+ name: "analyze_url_phase1",
55
+ description: ANALYZE_URL_PHASE1_DESC,
56
+ inputSchema: {
57
+ type: "object",
58
+ properties: { url: URL_PROP, audience: AUDIENCE_PROP_PHASE1 },
59
+ required: ["url"],
60
+ },
61
+ annotations: {
62
+ readOnlyHint: false,
63
+ destructiveHint: false,
64
+ idempotentHint: false,
65
+ openWorldHint: true,
66
+ },
67
+ },
68
+ {
69
+ name: "complete_analysis",
70
+ description: COMPLETE_ANALYSIS_DESC,
71
+ inputSchema: {
72
+ type: "object",
73
+ properties: {
74
+ analysisId: ANALYSIS_ID_PROP_FOR_COMPLETE,
75
+ audience: AUDIENCE_PROP_PHASE2,
76
+ },
77
+ required: ["analysisId"],
78
+ },
79
+ annotations: {
80
+ readOnlyHint: false,
81
+ destructiveHint: false,
82
+ idempotentHint: false,
83
+ openWorldHint: true,
84
+ },
85
+ },
86
+ {
87
+ name: "analyze_url",
88
+ description: ANALYZE_URL_DESC,
89
+ inputSchema: {
90
+ type: "object",
91
+ properties: { url: URL_PROP, audience: AUDIENCE_PROP_PHASE2 },
92
+ required: ["url"],
93
+ },
94
+ annotations: {
95
+ readOnlyHint: false,
96
+ destructiveHint: false,
97
+ idempotentHint: false,
98
+ openWorldHint: true,
99
+ },
100
+ },
101
+ {
102
+ name: "get_analysis",
103
+ description: GET_ANALYSIS_DESC,
104
+ inputSchema: {
105
+ type: "object",
106
+ properties: { analysisId: ANALYSIS_ID_PROP_FOR_GET },
107
+ required: ["analysisId"],
108
+ },
109
+ annotations: {
110
+ readOnlyHint: true,
111
+ destructiveHint: false,
112
+ idempotentHint: true,
113
+ openWorldHint: true,
114
+ },
115
+ },
116
+ ];
117
+ const RESOURCE_URI_RE = /^contentgrapher:\/\/analyses\/([0-9a-f-]+)$/i;
118
+ export function createServer(opts) {
119
+ const client = new ApiClient({ apiKey: opts.apiKey });
120
+ const server = new Server(SERVER_INFO, {
121
+ capabilities: {
122
+ tools: { listChanged: false },
123
+ resources: { subscribe: false, listChanged: false },
124
+ logging: {},
125
+ },
126
+ instructions: INSTRUCTIONS,
127
+ });
128
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({
129
+ tools: TOOLS,
130
+ }));
131
+ server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
132
+ const name = request.params.name;
133
+ const args = (request.params.arguments ?? {});
134
+ const progressToken = request.params._meta?.progressToken;
135
+ const sendProgress = async (params) => {
136
+ try {
137
+ await extra.sendNotification({
138
+ method: "notifications/progress",
139
+ params: {
140
+ progressToken: params.progressToken,
141
+ progress: params.progress,
142
+ ...(params.total !== undefined ? { total: params.total } : {}),
143
+ ...(params.message !== undefined ? { message: params.message } : {}),
144
+ },
145
+ });
146
+ }
147
+ catch {
148
+ // notification failure must not abort the tool call
149
+ }
150
+ };
151
+ const ctx = { client, sendProgress, progressToken };
152
+ let result;
153
+ switch (name) {
154
+ case "check_credits":
155
+ result = await runCheckCredits(ctx);
156
+ break;
157
+ case "analyze_url_phase1":
158
+ result = await runAnalyzeUrlPhase1({
159
+ url: String(args.url ?? ""),
160
+ audience: typeof args.audience === "string" ? args.audience : undefined,
161
+ }, ctx);
162
+ break;
163
+ case "complete_analysis":
164
+ result = await runCompleteAnalysis({
165
+ analysisId: String(args.analysisId ?? ""),
166
+ audience: typeof args.audience === "string" ? args.audience : undefined,
167
+ }, ctx);
168
+ break;
169
+ case "analyze_url":
170
+ result = await runAnalyzeUrl({
171
+ url: String(args.url ?? ""),
172
+ audience: typeof args.audience === "string" ? args.audience : undefined,
173
+ }, ctx);
174
+ break;
175
+ case "get_analysis":
176
+ result = await runGetAnalysis({ analysisId: String(args.analysisId ?? "") }, ctx);
177
+ break;
178
+ default:
179
+ result = {
180
+ content: [
181
+ {
182
+ type: "text",
183
+ text: `Unknown tool: ${name}. Available tools: check_credits, analyze_url_phase1, complete_analysis, analyze_url, get_analysis.`,
184
+ },
185
+ ],
186
+ isError: true,
187
+ };
188
+ }
189
+ return result;
190
+ });
191
+ server.setRequestHandler(ListResourceTemplatesRequestSchema, async () => ({
192
+ resourceTemplates: [
193
+ {
194
+ uriTemplate: "contentgrapher://analyses/{id}",
195
+ name: "ContentGrapher Analysis",
196
+ description: "Stored content analysis result. Readable directly by URI or retrieved via the get_analysis tool.",
197
+ mimeType: "application/json",
198
+ },
199
+ ],
200
+ }));
201
+ server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
202
+ const uri = request.params.uri;
203
+ const match = RESOURCE_URI_RE.exec(uri);
204
+ if (!match) {
205
+ throw new Error(`Unsupported resource URI: ${uri}. Expected contentgrapher://analyses/{id}.`);
206
+ }
207
+ const id = match[1];
208
+ const data = await client.getAnalysis(id, "get_analysis");
209
+ return {
210
+ contents: [
211
+ {
212
+ uri,
213
+ mimeType: "application/json",
214
+ text: JSON.stringify(data),
215
+ },
216
+ ],
217
+ };
218
+ });
219
+ return server;
220
+ }
@@ -0,0 +1,26 @@
1
+ import { sharedSemaphore } from "./semaphore.js";
2
+ const DRAIN_WINDOW_MS = 5_000;
3
+ let registered = false;
4
+ export function registerSignalHandlers() {
5
+ if (registered)
6
+ return;
7
+ registered = true;
8
+ const onSignal = (signal) => {
9
+ sharedSemaphore.startDraining();
10
+ const drainStart = Date.now();
11
+ const poll = setInterval(() => {
12
+ if (sharedSemaphore.count() === 0) {
13
+ clearInterval(poll);
14
+ process.stderr.write(`ContentGrapher MCP Server: received ${signal}, drained cleanly.\n`);
15
+ process.exit(0);
16
+ }
17
+ if (Date.now() - drainStart >= DRAIN_WINDOW_MS) {
18
+ clearInterval(poll);
19
+ process.stderr.write(`ContentGrapher MCP Server: received ${signal}, drain window expired with ${sharedSemaphore.count()} in-flight calls. Exiting.\n`);
20
+ process.exit(0);
21
+ }
22
+ }, 100);
23
+ };
24
+ process.on("SIGTERM", () => onSignal("SIGTERM"));
25
+ process.on("SIGINT", () => onSignal("SIGINT"));
26
+ }
@@ -0,0 +1,50 @@
1
+ import { ApiError, DESCRIBE_SEMAPHORE_SATURATED, NetworkError, SemaphoreSaturatedError, TimeoutError, describeApiError, describePhase1Timeout, describePhase2Timeout, describePhase2NetworkError, } from "./errors.js";
2
+ export function textItem(text) {
3
+ return { type: "text", text };
4
+ }
5
+ export function analysisResource(analysisId, json) {
6
+ return {
7
+ type: "resource",
8
+ resource: {
9
+ uri: `contentgrapher://analyses/${analysisId}`,
10
+ mimeType: "application/json",
11
+ text: JSON.stringify(json),
12
+ },
13
+ };
14
+ }
15
+ export function errorResult(text) {
16
+ return {
17
+ content: [textItem(text)],
18
+ isError: true,
19
+ };
20
+ }
21
+ export function toolErrorFromException(err, ctx = {}) {
22
+ if (err instanceof SemaphoreSaturatedError) {
23
+ return errorResult(DESCRIBE_SEMAPHORE_SATURATED);
24
+ }
25
+ if (err instanceof ApiError) {
26
+ return errorResult(describeApiError(err, {
27
+ analysisId: ctx.analysisId,
28
+ phase1Complete: ctx.phase1Complete,
29
+ }));
30
+ }
31
+ if (err instanceof TimeoutError) {
32
+ const phase = ctx.timeoutCtx?.phase;
33
+ if (phase === "phase1")
34
+ return errorResult(describePhase1Timeout());
35
+ if (phase === "phase2" && ctx.timeoutCtx?.analysisId) {
36
+ return errorResult(describePhase2Timeout(ctx.timeoutCtx.analysisId));
37
+ }
38
+ return errorResult(`Request to ContentGrapher timed out after ${err.seconds} seconds. Try again or check status with get_analysis.`);
39
+ }
40
+ if (err instanceof NetworkError) {
41
+ if (ctx.networkCtx?.analysisId) {
42
+ return errorResult(describePhase2NetworkError(ctx.networkCtx.analysisId));
43
+ }
44
+ return errorResult("The connection to ContentGrapher was interrupted. Wait 30 seconds and retry. If the problem persists, check your network connection and the ContentGrapher status page.");
45
+ }
46
+ if (err instanceof Error) {
47
+ return errorResult(`Unexpected error: ${err.message}. If this persists, contact support.`);
48
+ }
49
+ return errorResult("An unexpected error occurred.");
50
+ }
@@ -0,0 +1,47 @@
1
+ import { buildPhase1Text } from "../formatters/analysis-text.js";
2
+ import { validateUrlFormat } from "../key-validation.js";
3
+ import { startProgressTicker } from "../progress.js";
4
+ import { sharedSemaphore, withSemaphore } from "../semaphore.js";
5
+ import { analysisResource, errorResult, textItem, toolErrorFromException, } from "../tool-runtime.js";
6
+ const URL_INVALID = "The url field is missing, empty, or not a valid http(s) URL. Provide a publicly accessible URL such as https://example.com/docs/getting-started.";
7
+ const AUDIENCE_TOO_LONG = "The audience parameter exceeds 500 characters. Shorten it and try again.";
8
+ export async function runAnalyzeUrlPhase1(args, ctx) {
9
+ if (!args.url || !validateUrlFormat(args.url)) {
10
+ return errorResult(URL_INVALID);
11
+ }
12
+ if (args.audience !== undefined && args.audience.length > 500) {
13
+ return errorResult(AUDIENCE_TOO_LONG);
14
+ }
15
+ try {
16
+ return await withSemaphore(sharedSemaphore, async () => {
17
+ const stop = startProgressTicker({
18
+ progressToken: ctx.progressToken,
19
+ send: ctx.sendProgress,
20
+ message: (s) => `Phase 1 in progress — building concept map. Elapsed: ${s}s. Typical: 30-60s, worst case: ~290s.`,
21
+ doneMessage: "Phase 1 complete.",
22
+ });
23
+ try {
24
+ const phase1 = await ctx.client.createPhase1({
25
+ url: args.url,
26
+ audience: args.audience,
27
+ }, "analyze_url_phase1");
28
+ const text = buildPhase1Text({
29
+ url: args.url,
30
+ audience: args.audience,
31
+ resource: phase1,
32
+ });
33
+ return {
34
+ content: [textItem(text), analysisResource(phase1.analysisId, phase1)],
35
+ };
36
+ }
37
+ finally {
38
+ stop();
39
+ }
40
+ });
41
+ }
42
+ catch (err) {
43
+ return toolErrorFromException(err, {
44
+ timeoutCtx: { phase: "phase1" },
45
+ });
46
+ }
47
+ }