@maelitop/mention-mcp-server 1.4.0 → 1.5.0

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.
Files changed (104) hide show
  1. package/CHANGELOG.md +124 -0
  2. package/README.md +21 -19
  3. package/dist/api-client.js +79 -33
  4. package/dist/config.js +17 -4
  5. package/dist/index.js +6 -58
  6. package/dist/logger.js +20 -55
  7. package/dist/prompts/build-boolean-query.js +16 -34
  8. package/dist/prompts/index.js +4 -3
  9. package/dist/server.js +17 -0
  10. package/dist/tools/create_advanced_alert.js +33 -62
  11. package/dist/tools/create_basic_alert.js +36 -53
  12. package/dist/tools/fetch_alert_stats.js +63 -90
  13. package/dist/tools/fetch_mentions.js +33 -53
  14. package/dist/tools/get_account_info.js +20 -44
  15. package/dist/tools/get_alert.js +15 -35
  16. package/dist/tools/get_app_data.js +20 -44
  17. package/dist/tools/index.js +24 -56
  18. package/dist/tools/list_alerts.js +20 -41
  19. package/dist/tools/pause_alert.js +21 -36
  20. package/dist/tools/unpause_alert.js +21 -36
  21. package/dist/tools/update_alert.js +44 -55
  22. package/dist/types.js +20 -21
  23. package/package.json +11 -16
  24. package/dist/__tests__/api-client.test.d.ts +0 -2
  25. package/dist/__tests__/api-client.test.d.ts.map +0 -1
  26. package/dist/__tests__/api-client.test.js +0 -132
  27. package/dist/__tests__/api-client.test.js.map +0 -1
  28. package/dist/__tests__/config.test.d.ts +0 -2
  29. package/dist/__tests__/config.test.d.ts.map +0 -1
  30. package/dist/__tests__/config.test.js +0 -48
  31. package/dist/__tests__/config.test.js.map +0 -1
  32. package/dist/__tests__/tools.test.d.ts +0 -2
  33. package/dist/__tests__/tools.test.d.ts.map +0 -1
  34. package/dist/__tests__/tools.test.js +0 -316
  35. package/dist/__tests__/tools.test.js.map +0 -1
  36. package/dist/__tests__/types.test.d.ts +0 -2
  37. package/dist/__tests__/types.test.d.ts.map +0 -1
  38. package/dist/__tests__/types.test.js +0 -179
  39. package/dist/__tests__/types.test.js.map +0 -1
  40. package/dist/api-client.d.ts +0 -14
  41. package/dist/api-client.d.ts.map +0 -1
  42. package/dist/api-client.js.map +0 -1
  43. package/dist/config.d.ts +0 -10
  44. package/dist/config.d.ts.map +0 -1
  45. package/dist/config.js.map +0 -1
  46. package/dist/index.d.ts +0 -3
  47. package/dist/index.d.ts.map +0 -1
  48. package/dist/index.js.map +0 -1
  49. package/dist/logger.d.ts +0 -6
  50. package/dist/logger.d.ts.map +0 -1
  51. package/dist/logger.js.map +0 -1
  52. package/dist/prompts/base.d.ts +0 -25
  53. package/dist/prompts/base.d.ts.map +0 -1
  54. package/dist/prompts/base.js +0 -2
  55. package/dist/prompts/base.js.map +0 -1
  56. package/dist/prompts/build-boolean-query.d.ts +0 -3
  57. package/dist/prompts/build-boolean-query.d.ts.map +0 -1
  58. package/dist/prompts/build-boolean-query.js.map +0 -1
  59. package/dist/prompts/index.d.ts +0 -2
  60. package/dist/prompts/index.d.ts.map +0 -1
  61. package/dist/prompts/index.js.map +0 -1
  62. package/dist/tools/base.d.ts +0 -19
  63. package/dist/tools/base.d.ts.map +0 -1
  64. package/dist/tools/base.js +0 -2
  65. package/dist/tools/base.js.map +0 -1
  66. package/dist/tools/create_advanced_alert.d.ts +0 -3
  67. package/dist/tools/create_advanced_alert.d.ts.map +0 -1
  68. package/dist/tools/create_advanced_alert.js.map +0 -1
  69. package/dist/tools/create_basic_alert.d.ts +0 -3
  70. package/dist/tools/create_basic_alert.d.ts.map +0 -1
  71. package/dist/tools/create_basic_alert.js.map +0 -1
  72. package/dist/tools/fetch_alert_stats.d.ts +0 -3
  73. package/dist/tools/fetch_alert_stats.d.ts.map +0 -1
  74. package/dist/tools/fetch_alert_stats.js.map +0 -1
  75. package/dist/tools/fetch_mentions.d.ts +0 -3
  76. package/dist/tools/fetch_mentions.d.ts.map +0 -1
  77. package/dist/tools/fetch_mentions.js.map +0 -1
  78. package/dist/tools/get_account_info.d.ts +0 -3
  79. package/dist/tools/get_account_info.d.ts.map +0 -1
  80. package/dist/tools/get_account_info.js.map +0 -1
  81. package/dist/tools/get_alert.d.ts +0 -3
  82. package/dist/tools/get_alert.d.ts.map +0 -1
  83. package/dist/tools/get_alert.js.map +0 -1
  84. package/dist/tools/get_app_data.d.ts +0 -3
  85. package/dist/tools/get_app_data.d.ts.map +0 -1
  86. package/dist/tools/get_app_data.js.map +0 -1
  87. package/dist/tools/index.d.ts +0 -14
  88. package/dist/tools/index.d.ts.map +0 -1
  89. package/dist/tools/index.js.map +0 -1
  90. package/dist/tools/list_alerts.d.ts +0 -3
  91. package/dist/tools/list_alerts.d.ts.map +0 -1
  92. package/dist/tools/list_alerts.js.map +0 -1
  93. package/dist/tools/pause_alert.d.ts +0 -3
  94. package/dist/tools/pause_alert.d.ts.map +0 -1
  95. package/dist/tools/pause_alert.js.map +0 -1
  96. package/dist/tools/unpause_alert.d.ts +0 -3
  97. package/dist/tools/unpause_alert.d.ts.map +0 -1
  98. package/dist/tools/unpause_alert.js.map +0 -1
  99. package/dist/tools/update_alert.d.ts +0 -3
  100. package/dist/tools/update_alert.d.ts.map +0 -1
  101. package/dist/tools/update_alert.js.map +0 -1
  102. package/dist/types.d.ts +0 -448
  103. package/dist/types.d.ts.map +0 -1
  104. package/dist/types.js.map +0 -1
package/CHANGELOG.md ADDED
@@ -0,0 +1,124 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [Unreleased]
9
+
10
+ ## [1.5.0] - 2026-11-25
11
+
12
+ ### Added
13
+ - Every tool has a `title` and `annotations`: the read tools are marked `readOnlyHint`, `pause_alert` and `unpause_alert` `idempotentHint`, and `update_alert` `destructiveHint`, so clients no longer have to treat every tool as destructive
14
+ - The server returns `instructions` at initialisation; the advice to call `get_account_info` first moved there from that tool's description, which now lists what the tool returns
15
+ - `MENTION_READ_ONLY=true` registers only the read-only tools, so the model cannot create, update, pause or unpause alerts; `false`, an empty value or leaving it unset keeps every tool, and any other value stops the server at startup with an error naming the variable
16
+
17
+ ### Changed
18
+ - `@modelcontextprotocol/sdk` upgraded from 1.12 to 1.32; the server now accepts MCP protocol version `2025-11-25`
19
+ - A failed tool call, such as a missing or invalid argument, an API error or an unknown tool name, returns a result with `isError: true` and a readable message instead of a JSON-RPC error, so the model can see what went wrong
20
+ - An unknown prompt name or invalid `build-boolean-query` arguments return an "Invalid params" error naming the problem instead of an internal error
21
+
22
+ ### Removed
23
+ - `resources` capability, which listed no resources
24
+ - `zod-to-json-schema` dependency
25
+ - Log lines for each tool call (started, completed, failed); failed API requests are still logged
26
+
27
+ ### Fixed
28
+ - A 403 keeps the reason the API gives, such as a plan without access to a feature, after "Access denied" instead of dropping it
29
+ - A 400 or other API error whose body carries a message shows that message and the HTTP status instead of the raw response body: form errors become one `field: message` line each, and an invalid Boolean query in `create_advanced_alert` lists each error with its line and column, one per line, instead of generic tips and an example query. A 401 and a 429 keep their fixed messages
30
+ - `fetch_alert_stats` describes `from` and `to` as calendar days in `timezone`, both included, whose time of day and trailing `Z` are ignored; `interval` says that `P1W` and `P1M` widen the range to whole weeks (Monday to Sunday) or months, and `timezone` that it defaults to UTC
31
+ - `update_alert` states that an alert's query type cannot change: the keyword fields apply only to basic alerts and `query_string` only to advanced ones, and a field of the other type rejects the whole update. It also states that a keyword list left out is kept and that an empty `required_keywords` clears it
32
+
33
+ ## [1.4.1] - 2026-11-25
34
+
35
+ ### Fixed
36
+ - README documents `MENTION_API_KEY` and `MENTION_API_BASE_URL`, the variable names the server reads
37
+ - Logs are written as JSON lines to stderr, so a startup failure such as a missing `MENTION_API_KEY` is reported before the process exits and stdout carries only MCP messages
38
+ - The server no longer creates a log directory at startup, so a missing or read-only home directory does not crash it
39
+ - `fetch_mentions` sends `tone` and `countries` as `tone[]` and `countries[]`, so every tone value applies and a `countries` filter is no longer rejected
40
+ - `pause_alert` and `unpause_alert` report success with a short confirmation instead of "Network request failed" when the API answers with an empty body
41
+ - Requests send the server's real version in the `User-Agent` header, and `MCP_REQUEST_TIMEOUT` also bounds reading the response body
42
+ - `update_alert` applies keyword and `query_string` changes without `query_type`: a keyword field sends a basic query, `query_string` an advanced one, and passing both is rejected
43
+ - `update_alert` accepts any source code returned by `get_app_data` in `sources`
44
+ - An `MCP_REQUEST_TIMEOUT` that is not a whole number of milliseconds between 1 and 2147483647 stops the server at startup with an error naming the variable, instead of making requests fail; a value with a unit suffix such as `60000ms` is now rejected rather than truncated
45
+ - Requests send `Accept-Version: 1.21`, so every user gets the same API behaviour whatever version their API application was created with; alerts returned by `get_alert`, `list_alerts` and `update_alert` now have an empty `stats` field
46
+ - `get_alert`, `update_alert`, `pause_alert`, `unpause_alert` and `fetch_mentions` URL-encode `alert_id` and reject an empty, `.` or `..` value, so an `alert_id` can no longer send the request to another endpoint
47
+ - `fetch_alert_stats` requires `from`, `to` and `interval`, since the API returns 400 without them, and sends `from` and `to` in the `2026-11-01T00:00:00.0` form the API accepts: each takes a date (`from` starts at 00:00:00, `to` ends at 23:59:59) or a date-time read in `timezone`, whose fractional seconds and trailing `Z` are ignored
48
+
49
+ ### Changed
50
+ - `MCP_LOG_LEVEL` accepts `debug`, `info`, `warn` and `error`; any other value falls back to `info` instead of crashing at startup
51
+ - The package requires Node.js 22 or later (`engines.node`)
52
+ - The published package contains only the compiled server, README, LICENSE and CHANGELOG; tests, type declarations and source maps are no longer shipped
53
+
54
+ ### Removed
55
+ - `MCP_CONSOLE_LOGGING` option and the platform-specific log files
56
+ - `pino` and `pino-pretty` dependencies
57
+ - `languages` parameter of `fetch_mentions`, which the endpoint did not apply
58
+ - `query_type` parameter of `update_alert`, now inferred from the fields passed
59
+ - `noise_detection` parameter of `create_basic_alert`, `create_advanced_alert` and `update_alert`, which the API does not accept
60
+ - Retry-count environment variable and its config field; the server parsed it but never retried requests
61
+ - `main` field of `package.json`; the package is a command-line server with no importable API
62
+ - `important` parameter of `fetch_alert_stats`, which the API does not accept
63
+
64
+ ## [1.4.0] - 2025-06-29
65
+
66
+ ### Added
67
+ - **New Tool**: `fetch_alert_stats` - Retrieve comprehensive alert statistics
68
+ - Flexible date range filtering with `from`, `to`, and `timezone` parameters
69
+ - Aggregation by interval: daily (P1D), weekly (P1W), monthly (P1M)
70
+ - Multi-dimensional filtering by `tones`, `languages`, `sources`, `countries`, `tags`
71
+ - Statistical analysis with `favorite`, `important`, and author influence filtering
72
+ - Geographic insights with configurable `country_stats` (top N countries)
73
+ - Temporal analysis with `week_day_stats` and `week_day_by_hour_stats`
74
+ - Influencer tracking and reach metrics per interval
75
+
76
+ ## [1.3.0] - 2025-06-28
77
+
78
+ ### Added
79
+ - **New Tool**: `fetch_mentions` - Retrieve mentions with comprehensive filtering support
80
+ - Supports pagination with `since_id`, `cursor`, and `limit` parameters
81
+ - Date filtering with `before_date`, `not_before_date`, and `timezone`
82
+ - Content filtering by `source`, `folder`, `tone`, `unread`, `favorite`
83
+ - Geographic and language filtering with `countries` and `languages`
84
+ - Advanced search with `q` parameter and sorting options
85
+ - Support for including child mentions with `include_children`
86
+
87
+ ### Changed
88
+ - **Alert Creation Response**: `create_basic_alert` and `create_advanced_alert` now return only the alert ID instead of the full response for cleaner output
89
+ - **Improved Error Handling**: Enhanced API error logging with full response bodies for better debugging
90
+
91
+ ### Fixed
92
+ - **Boolean Query Validation**: Added better error messages for boolean query syntax errors in advanced alerts
93
+ - **API Response Parsing**: Improved error handling when API responses don't match expected structure
94
+
95
+ ## [1.2.0] - 2025-06-28
96
+
97
+ ### Added
98
+ - **Custom Prompt**: `build-boolean-query` prompt for generating valid Boolean query strings
99
+ - **Enhanced Alert Creation**: Improved validation and error messages for alert creation
100
+
101
+ ### Changed
102
+ - **Response Format**: Streamlined alert creation responses to return essential data only
103
+
104
+ ## 1.0.0
105
+
106
+ ### Added
107
+ - Initial release of the Mention MCP Server
108
+ - Complete implementation of Mention API integration
109
+
110
+ ### Features
111
+ - **Account Management**: Get account info and application data
112
+ - **Alert Creation**: Basic and advanced alert creation with plan detection
113
+ - **Alert Management**: Update, pause/unpause existing alerts
114
+
115
+ ### Tools Available
116
+ - `get_account_info` - Account information and subscription details
117
+ - `get_app_data` - Available languages, countries, sources metadata
118
+ - `list_alerts` - List all monitoring alerts with pagination
119
+ - `get_alert` - Get specific alert details
120
+ - `create_basic_alert` - Create alerts for basic subscription plans
121
+ - `create_advanced_alert` - Create alerts with boolean queries for advanced plans
122
+ - `update_alert` - Update existing alerts
123
+ - `pause_alert` - Temporarily pause monitoring for specific alerts
124
+ - `unpause_alert` - Resume monitoring for paused alerts
package/README.md CHANGED
@@ -4,7 +4,7 @@
4
4
  [![NPM Version](https://img.shields.io/npm/v/@maelitop/mention-mcp-server.svg)](https://www.npmjs.com/package/@maelitop/mention-mcp-server)
5
5
  [![NPM Downloads](https://img.shields.io/npm/dm/@maelitop/mention-mcp-server.svg)](https://www.npmjs.com/package/@MaelitoP/mention-mcp-server)
6
6
 
7
- A production-ready [Model Context Protocol (MCP)](https://modelcontextprotocol.io/introduction) server for social listening and monitoring through the Mention API. Built with TypeScript, comprehensive error handling, structured logging, and modular architecture.
7
+ A [Model Context Protocol (MCP)](https://modelcontextprotocol.io/introduction) server for social listening and monitoring through the Mention API. Built with TypeScript, comprehensive error handling, structured logging, and modular architecture.
8
8
 
9
9
  ## Supported Tools
10
10
 
@@ -35,7 +35,7 @@ Add the following to your Claude Desktop configuration file:
35
35
  "command": "npx",
36
36
  "args": ["-y", "@maelitop/mention-mcp-server"],
37
37
  "env": {
38
- "MCP_MENTION_API_KEY": "your_mention_api_key_here"
38
+ "MENTION_API_KEY": "your_mention_api_key_here"
39
39
  }
40
40
  }
41
41
  }
@@ -46,12 +46,11 @@ Add the following to your Claude Desktop configuration file:
46
46
 
47
47
  | Variable | Description | Default |
48
48
  |----------|-------------|---------|
49
- | `MCP_MENTION_API_KEY` | Your Mention API key (required) | - |
50
- | `MCP_MENTION_API_BASE_URL` | Custom API base URL | `https://web.mention.com/api` |
49
+ | `MENTION_API_KEY` | Your Mention API key (required) | - |
50
+ | `MENTION_API_BASE_URL` | Custom API base URL | `https://web.mention.com/api` |
51
51
  | `MCP_LOG_LEVEL` | Logging level (`debug`, `info`, `warn`, `error`) | `info` |
52
- | `MCP_CONSOLE_LOGGING` | Enable console logging (`true`/`false`) | `false` |
53
- | `MCP_REQUEST_TIMEOUT` | Request timeout in milliseconds | `30000` |
54
- | `MCP_MAX_RETRIES` | Maximum retry attempts | `3` |
52
+ | `MCP_REQUEST_TIMEOUT` | Request timeout in milliseconds, a whole number from `1` to `2147483647` | `30000` |
53
+ | `MENTION_READ_ONLY` | `true` registers only the read-only tools (`get_account_info`, `get_app_data`, `list_alerts`, `get_alert`, `fetch_mentions`, `fetch_alert_stats`), so alerts cannot be created, updated, paused or unpaused; `false`, an empty value or leaving it unset registers every tool. Any other value stops the server at startup | `false` |
55
54
 
56
55
 
57
56
  ### Development
@@ -69,31 +68,34 @@ npm test
69
68
  # Build for production
70
69
  npm run build
71
70
 
72
- # Run linting and type checking
71
+ # Run linting, build and tests
73
72
  npm run ci
74
73
  ```
75
74
 
76
- ## Logging
77
-
78
- Logs are automatically written to platform-specific directories:
79
-
80
- - **macOS**: `~/Library/Logs/mention-mcp-server/mention-mcp-server.log`
81
- - **Windows**: `~/AppData/Local/mention-mcp-server/logs/mention-mcp-server.log`
82
- - **Linux**: `~/.local/share/mention-mcp-server/logs/mention-mcp-server.log`
83
-
84
75
  ## Testing
85
76
 
86
77
  ```bash
87
78
  # Run all tests
88
79
  npm test
89
80
 
90
- # Run tests with coverage
91
- npm run test:coverage
92
-
93
81
  # Run tests in watch mode
94
82
  npm run test -- --watch
95
83
  ```
96
84
 
85
+ ## Releasing
86
+
87
+ 1. On an up-to-date `main`, move the `## [Unreleased]` entries of `CHANGELOG.md` under a heading for the new version and commit.
88
+ 2. Bump the version, commit it and create the `v<version>` tag:
89
+ ```bash
90
+ npm version patch -m "chore(release): %s" # or minor, major
91
+ ```
92
+ 3. Push the commit and the tag:
93
+ ```bash
94
+ git push origin main --follow-tags
95
+ ```
96
+
97
+ Pushing a `v*` tag runs the Publish workflow: it checks, builds and tests the package, publishes it to npm through trusted publishing (no npm token) and creates the GitHub release with generated notes.
98
+
97
99
  ## License
98
100
 
99
101
  This project is licensed under the [MIT License](LICENSE).
@@ -1,35 +1,98 @@
1
1
  import { ErrorCode, McpError } from "@modelcontextprotocol/sdk/types.js";
2
2
  import { logDebug, logError } from "./logger.js";
3
3
  import { AccountResponseSchema } from "./types.js";
4
+ export function apiPath(strings, ...segments) {
5
+ for (const segment of segments) {
6
+ if (segment === "" || segment === "." || segment === "..") {
7
+ throw new McpError(ErrorCode.InvalidParams, `Invalid path segment: "${segment}"`);
8
+ }
9
+ }
10
+ return String.raw({ raw: strings }, ...segments.map(encodeURIComponent));
11
+ }
12
+ function isRecord(value) {
13
+ return typeof value === "object" && value !== null;
14
+ }
15
+ function asText(value) {
16
+ return typeof value === "string" ? value : JSON.stringify(value);
17
+ }
18
+ function formErrors(node, path = "") {
19
+ if (!isRecord(node)) {
20
+ return [];
21
+ }
22
+ const own = Array.isArray(node.errors)
23
+ ? node.errors.map((message) => path ? `${path}: ${asText(message)}` : asText(message))
24
+ : [];
25
+ const children = isRecord(node.children)
26
+ ? Object.entries(node.children).flatMap(([name, child]) => formErrors(child, path ? `${path}.${name}` : name))
27
+ : [];
28
+ return [...own, ...children];
29
+ }
30
+ function formatBooleanError(error) {
31
+ if (!isRecord(error) || typeof error.message !== "string") {
32
+ return asText(error);
33
+ }
34
+ const bounds = Array.isArray(error.bounds) ? error.bounds : [];
35
+ const positions = bounds.flatMap((bound) => isRecord(bound) &&
36
+ isRecord(bound.from) &&
37
+ typeof bound.from.row === "number" &&
38
+ typeof bound.from.column === "number"
39
+ ? [`line ${bound.from.row + 1}, column ${bound.from.column + 1}`]
40
+ : []);
41
+ return positions.length > 0 ? `${error.message} (at ${positions.join("; ")})` : error.message;
42
+ }
43
+ function errorReason(body) {
44
+ if (!isRecord(body)) {
45
+ return undefined;
46
+ }
47
+ const booleanErrors = Array.isArray(body.boolean_errors)
48
+ ? body.boolean_errors.map(formatBooleanError)
49
+ : [];
50
+ const formLines = formErrors(body.form).filter((line) => booleanErrors.length === 0 || !line.startsWith("query.query_string: "));
51
+ const lines = [...booleanErrors, ...formLines];
52
+ if (lines.length > 0) {
53
+ return lines.join("\n");
54
+ }
55
+ if (typeof body.message === "string") {
56
+ return body.message;
57
+ }
58
+ if (typeof body.error === "string") {
59
+ return body.error;
60
+ }
61
+ if (isRecord(body.error) && typeof body.error.message === "string") {
62
+ return typeof body.error.details === "string"
63
+ ? `${body.error.message} - ${body.error.details}`
64
+ : body.error.message;
65
+ }
66
+ return undefined;
67
+ }
4
68
  export class MentionAPIClient {
5
69
  config;
70
+ userAgent;
6
71
  accountCache = null;
7
72
  accountCacheExpiry = 0;
8
73
  accountCacheTTL = 5 * 60 * 1000; // 5 minutes
9
- constructor(config) {
74
+ constructor(config, serverVersion) {
10
75
  this.config = config;
76
+ this.userAgent = `mention-mcp-server/${serverVersion}`;
11
77
  }
12
78
  async makeRequest(endpoint, options = {}) {
13
79
  const url = `${this.config.apiBaseUrl}${endpoint}`;
14
80
  const requestId = Math.random().toString(36).substring(7);
15
81
  logDebug("Making API request", { requestId, endpoint, method: options.method || "GET" });
16
- const controller = new AbortController();
17
- const timeoutId = setTimeout(() => controller.abort(), this.config.requestTimeout);
18
82
  try {
19
83
  const response = await fetch(url, {
20
84
  ...options,
21
- signal: controller.signal,
85
+ signal: AbortSignal.timeout(this.config.requestTimeout),
22
86
  headers: {
23
87
  Authorization: `Bearer ${this.config.apiKey}`,
24
88
  "Content-Type": "application/json",
25
- "User-Agent": "mention-mcp-server/1.0.0",
89
+ "User-Agent": this.userAgent,
90
+ "Accept-Version": "1.21",
26
91
  ...options.headers,
27
92
  },
28
93
  });
29
- clearTimeout(timeoutId);
30
94
  if (!response.ok) {
31
95
  let rawErrorData;
32
- let errorMsg;
33
96
  try {
34
97
  rawErrorData = await response.json();
35
98
  logError("API response error", {
@@ -41,7 +104,6 @@ export class MentionAPIClient {
41
104
  });
42
105
  }
43
106
  catch (parseError) {
44
- errorMsg = `HTTP ${response.status}: ${response.statusText}`;
45
107
  logError("Mention API request failed - could not parse error response", {
46
108
  requestId,
47
109
  endpoint,
@@ -49,42 +111,32 @@ export class MentionAPIClient {
49
111
  statusText: response.statusText,
50
112
  parseError: parseError instanceof Error ? parseError.message : String(parseError),
51
113
  });
52
- throw new McpError(ErrorCode.InternalError, errorMsg);
53
- }
54
- // Try to extract error message from the response
55
- if (rawErrorData && typeof rawErrorData === "object" && "error" in rawErrorData) {
56
- const errorData = rawErrorData;
57
- if (errorData.error?.message) {
58
- errorMsg = `Mention API Error: ${errorData.error.message}${errorData.error.details ? ` - ${errorData.error.details}` : ""}`;
59
- }
60
- else {
61
- errorMsg = `HTTP ${response.status}: ${response.statusText} - ${JSON.stringify(rawErrorData)}`;
62
- }
63
- }
64
- else {
65
- errorMsg = `HTTP ${response.status}: ${response.statusText} - ${JSON.stringify(rawErrorData)}`;
114
+ throw new McpError(ErrorCode.InternalError, `HTTP ${response.status}: ${response.statusText}`);
66
115
  }
67
116
  if (response.status === 401) {
68
117
  throw new McpError(ErrorCode.InvalidRequest, "Invalid API key");
69
118
  }
119
+ const reason = errorReason(rawErrorData);
70
120
  if (response.status === 403) {
71
- throw new McpError(ErrorCode.InvalidRequest, "Access denied");
121
+ throw new McpError(ErrorCode.InvalidRequest, reason ? `Access denied: ${reason}` : "Access denied");
72
122
  }
73
123
  if (response.status === 429) {
74
124
  throw new McpError(ErrorCode.InternalError, "Rate limit exceeded - please try again later");
75
125
  }
76
- throw new McpError(ErrorCode.InternalError, errorMsg);
126
+ throw new McpError(ErrorCode.InternalError, reason
127
+ ? `Mention API Error (HTTP ${response.status}): ${reason}`
128
+ : `HTTP ${response.status}: ${response.statusText} - ${JSON.stringify(rawErrorData)}`);
77
129
  }
78
- const responseData = await response.json();
130
+ const responseText = await response.text();
131
+ const responseData = responseText ? JSON.parse(responseText) : null;
79
132
  logDebug("API request successful", { requestId, endpoint });
80
133
  return responseData;
81
134
  }
82
135
  catch (error) {
83
- clearTimeout(timeoutId);
84
136
  if (error instanceof McpError) {
85
137
  throw error;
86
138
  }
87
- if (error instanceof Error && error.name === "AbortError") {
139
+ if (error instanceof Error && error.name === "TimeoutError") {
88
140
  const errorMsg = "Request timeout";
89
141
  logError(errorMsg, error, { requestId, endpoint, timeout: this.config.requestTimeout });
90
142
  throw new McpError(ErrorCode.InternalError, errorMsg);
@@ -117,10 +169,4 @@ export class MentionAPIClient {
117
169
  const accountInfo = await this.getAccountInfo();
118
170
  return accountInfo.account.id;
119
171
  }
120
- clearAccountCache() {
121
- this.accountCache = null;
122
- this.accountCacheExpiry = 0;
123
- logDebug("Account cache cleared");
124
- }
125
172
  }
126
- //# sourceMappingURL=api-client.js.map
package/dist/config.js CHANGED
@@ -1,3 +1,18 @@
1
+ // AbortSignal.timeout uses Node timers, which fire after 1 ms above a signed 32-bit delay.
2
+ const MAX_TIMER_DELAY_MS = 2_147_483_647;
3
+ function parseRequestTimeout(value) {
4
+ const timeout = Number(value);
5
+ if (!Number.isInteger(timeout) || timeout < 1 || timeout > MAX_TIMER_DELAY_MS) {
6
+ throw new Error(`MCP_REQUEST_TIMEOUT must be a whole number of milliseconds between 1 and ${MAX_TIMER_DELAY_MS}, got "${value}"`);
7
+ }
8
+ return timeout;
9
+ }
10
+ function parseReadOnly(value) {
11
+ if (value !== "true" && value !== "false") {
12
+ throw new Error(`MENTION_READ_ONLY must be "true" or "false", got "${value}"`);
13
+ }
14
+ return value === "true";
15
+ }
1
16
  export function loadConfig() {
2
17
  const apiKey = process.env.MENTION_API_KEY;
3
18
  if (!apiKey) {
@@ -7,9 +22,7 @@ export function loadConfig() {
7
22
  apiKey,
8
23
  apiBaseUrl: process.env.MENTION_API_BASE_URL || "https://web.mention.com/api",
9
24
  logLevel: process.env.MCP_LOG_LEVEL || "info",
10
- enableConsoleLogging: process.env.MCP_CONSOLE_LOGGING === "true",
11
- requestTimeout: Number.parseInt(process.env.MCP_REQUEST_TIMEOUT || "30000", 10),
12
- maxRetries: Number.parseInt(process.env.MCP_MAX_RETRIES || "3", 10),
25
+ requestTimeout: parseRequestTimeout(process.env.MCP_REQUEST_TIMEOUT || "30000"),
26
+ readOnly: parseReadOnly(process.env.MENTION_READ_ONLY || "false"),
13
27
  };
14
28
  }
15
- //# sourceMappingURL=config.js.map
package/dist/index.js CHANGED
@@ -2,14 +2,11 @@
2
2
  import { readFileSync } from "node:fs";
3
3
  import { dirname, join } from "node:path";
4
4
  import { fileURLToPath } from "node:url";
5
- import { Server } from "@modelcontextprotocol/sdk/server/index.js";
6
5
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
7
- import { CallToolRequestSchema, GetPromptRequestSchema, ListPromptsRequestSchema, ListResourcesRequestSchema, ListToolsRequestSchema, } from "@modelcontextprotocol/sdk/types.js";
8
6
  import { MentionAPIClient } from "./api-client.js";
9
7
  import { loadConfig } from "./config.js";
10
8
  import { logError, logInfo } from "./logger.js";
11
- import { prompts } from "./prompts/index.js";
12
- import { ToolHandlers, getToolDefinitions } from "./tools/index.js";
9
+ import { createServer } from "./server.js";
13
10
  const __filename = fileURLToPath(import.meta.url);
14
11
  const __dirname = dirname(__filename);
15
12
  function getPackageVersion() {
@@ -23,62 +20,14 @@ function getPackageVersion() {
23
20
  return "1.0.0";
24
21
  }
25
22
  }
26
- async function createServer() {
27
- let config;
28
- try {
29
- config = loadConfig();
30
- }
31
- catch (error) {
32
- logError("Failed to load configuration", error);
33
- throw error;
34
- }
35
- const version = getPackageVersion();
36
- const apiClient = new MentionAPIClient(config);
37
- const toolHandlers = new ToolHandlers(apiClient);
38
- const server = new Server({
39
- name: "mention-mcp-server",
40
- version,
41
- }, {
42
- capabilities: {
43
- tools: {},
44
- resources: {},
45
- prompts: {},
46
- },
47
- });
48
- server.setRequestHandler(ListToolsRequestSchema, async () => {
49
- return {
50
- tools: getToolDefinitions(),
51
- };
52
- });
53
- server.setRequestHandler(ListResourcesRequestSchema, async () => {
54
- return {
55
- resources: [],
56
- };
57
- });
58
- server.setRequestHandler(ListPromptsRequestSchema, async () => {
59
- return {
60
- prompts: prompts.map((prompt) => prompt.getDefinition()),
61
- };
62
- });
63
- server.setRequestHandler(GetPromptRequestSchema, async (request) => {
64
- const { name, arguments: args } = request.params;
65
- const prompt = prompts.find((p) => p.getDefinition().name === name);
66
- if (!prompt) {
67
- throw new Error(`Unknown prompt: ${name}`);
68
- }
69
- const handler = prompt.createHandler();
70
- return await handler.handle(args);
71
- });
72
- server.setRequestHandler(CallToolRequestSchema, async (request) => {
73
- const { name, arguments: args } = request.params;
74
- return await toolHandlers.handleTool(name, args);
75
- });
76
- return server;
77
- }
78
23
  async function main() {
79
24
  try {
80
25
  logInfo("Starting MCP server");
81
- const server = await createServer();
26
+ const version = getPackageVersion();
27
+ const config = loadConfig();
28
+ const server = createServer(new MentionAPIClient(config, version), version, {
29
+ readOnly: config.readOnly,
30
+ });
82
31
  const transport = new StdioServerTransport();
83
32
  await server.connect(transport);
84
33
  }
@@ -99,4 +48,3 @@ main().catch((error) => {
99
48
  logError("Fatal error in main", error);
100
49
  process.exit(1);
101
50
  });
102
- //# sourceMappingURL=index.js.map
package/dist/logger.js CHANGED
@@ -1,71 +1,36 @@
1
- import { existsSync, mkdirSync } from "node:fs";
2
- import { homedir } from "node:os";
3
- import { join } from "node:path";
4
- import pino from "pino";
5
- function getLogDirectory() {
6
- const platform = process.platform;
7
- let logDir;
8
- if (platform === "darwin") {
9
- logDir = join(homedir(), "Library", "Logs", "mention-mcp-server");
10
- }
11
- else if (platform === "win32") {
12
- logDir = join(homedir(), "AppData", "Local", "mention-mcp-server", "logs");
1
+ const severity = { debug: 0, info: 1, warn: 2, error: 3 };
2
+ function isLevel(value) {
3
+ return value !== undefined && Object.hasOwn(severity, value);
4
+ }
5
+ function serialize(time, level, msg, fields) {
6
+ try {
7
+ return JSON.stringify({ time, level, msg, ...fields });
13
8
  }
14
- else {
15
- logDir = join(homedir(), ".local", "share", "mention-mcp-server", "logs");
9
+ catch (error) {
10
+ return JSON.stringify({ time, level, msg, serializationError: String(error) });
16
11
  }
17
- if (!existsSync(logDir)) {
18
- mkdirSync(logDir, { recursive: true });
12
+ }
13
+ function write(level, msg, fields) {
14
+ const configured = process.env.MCP_LOG_LEVEL;
15
+ if (severity[level] < severity[isLevel(configured) ? configured : "info"]) {
16
+ return;
19
17
  }
20
- return logDir;
18
+ process.stderr.write(`${serialize(new Date().toISOString(), level, msg, fields)}\n`);
21
19
  }
22
- const logLevel = process.env.MCP_LOG_LEVEL || "info";
23
- const enableConsoleLogging = process.env.MCP_CONSOLE_LOGGING === "true";
24
- const logDir = getLogDirectory();
25
- const logFile = join(logDir, "mention-mcp-server.log");
26
- export const logger = pino({
27
- level: logLevel,
28
- timestamp: pino.stdTimeFunctions.isoTime,
29
- formatters: {
30
- level: (label) => {
31
- return { level: label };
32
- },
33
- },
34
- }, pino.multistream([
35
- {
36
- stream: pino.destination({
37
- dest: logFile,
38
- sync: false,
39
- }),
40
- },
41
- ...(enableConsoleLogging
42
- ? [
43
- {
44
- stream: pino.destination({
45
- dest: 1,
46
- sync: false,
47
- }),
48
- },
49
- ]
50
- : []),
51
- ]));
52
20
  export function logError(message, error, context) {
53
- const errorData = {
54
- message,
21
+ write("error", message, {
55
22
  context,
56
23
  error: error instanceof Error
57
24
  ? { name: error.name, message: error.message, stack: error.stack }
58
25
  : error,
59
- };
60
- logger.error(errorData, message);
26
+ });
61
27
  }
62
28
  export function logInfo(message, context) {
63
- logger.info({ context }, message);
29
+ write("info", message, { context });
64
30
  }
65
31
  export function logWarn(message, context) {
66
- logger.warn({ context }, message);
32
+ write("warn", message, { context });
67
33
  }
68
34
  export function logDebug(message, context) {
69
- logger.debug({ context }, message);
35
+ write("debug", message, { context });
70
36
  }
71
- //# sourceMappingURL=logger.js.map
@@ -1,29 +1,15 @@
1
1
  import { BuildBooleanQueryPromptArgsSchema } from "../types.js";
2
- export const buildBooleanQueryPrompt = {
3
- getDefinition() {
4
- return {
5
- name: "build-boolean-query",
6
- description: "Generate a valid Boolean query string using Boolean operators, quoted terms, proximity, and field selectors",
7
- arguments: [
8
- {
9
- name: "instructions",
10
- description: "What the Boolean query should match, e.g., 'Mentions about NASA in English from the US or Canada'",
11
- required: true,
12
- },
13
- ],
14
- };
15
- },
16
- createHandler() {
17
- return {
18
- async handle(args) {
19
- const parsedArgs = BuildBooleanQueryPromptArgsSchema.parse(args);
20
- return {
21
- messages: [
22
- {
23
- role: "user",
24
- content: {
25
- type: "text",
26
- text: `You are generating a valid Boolean query string using the following rules:
2
+ export function registerBuildBooleanQueryPrompt(server) {
3
+ server.registerPrompt("build-boolean-query", {
4
+ description: "Generate a valid Boolean query string using Boolean operators, quoted terms, proximity, and field selectors",
5
+ argsSchema: BuildBooleanQueryPromptArgsSchema.shape,
6
+ }, ({ instructions }) => ({
7
+ messages: [
8
+ {
9
+ role: "user",
10
+ content: {
11
+ type: "text",
12
+ text: `You are generating a valid Boolean query string using the following rules:
27
13
  1. Combine clauses using AND, OR, and NOT. Wrap mixed clauses in parentheses.
28
14
  2. A clause can be:
29
15
  - A term: single word (e.g. NASA)
@@ -50,14 +36,10 @@ export const buildBooleanQueryPrompt = {
50
36
  - Stop words alone not allowed in OR
51
37
  - Max term length: 128 chars
52
38
  Generate a Boolean query for the following:
53
- ${parsedArgs.instructions}
39
+ ${instructions}
54
40
  `,
55
- },
56
- },
57
- ],
58
- };
41
+ },
59
42
  },
60
- };
61
- },
62
- };
63
- //# sourceMappingURL=build-boolean-query.js.map
43
+ ],
44
+ }));
45
+ }
@@ -1,3 +1,4 @@
1
- import { buildBooleanQueryPrompt } from "./build-boolean-query.js";
2
- export const prompts = [buildBooleanQueryPrompt];
3
- //# sourceMappingURL=index.js.map
1
+ import { registerBuildBooleanQueryPrompt } from "./build-boolean-query.js";
2
+ export function registerPrompts(server) {
3
+ registerBuildBooleanQueryPrompt(server);
4
+ }