@maelitop/mention-mcp-server 1.3.0 → 1.4.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.
Files changed (100) hide show
  1. package/CHANGELOG.md +101 -0
  2. package/README.md +21 -19
  3. package/dist/api-client.js +17 -15
  4. package/dist/config.js +10 -4
  5. package/dist/index.js +1 -2
  6. package/dist/logger.js +20 -55
  7. package/dist/prompts/base.js +0 -1
  8. package/dist/prompts/build-boolean-query.js +0 -1
  9. package/dist/prompts/index.js +0 -1
  10. package/dist/tools/base.js +0 -1
  11. package/dist/tools/create_advanced_alert.js +0 -1
  12. package/dist/tools/create_basic_alert.js +0 -1
  13. package/dist/tools/fetch_alert_stats.js +94 -0
  14. package/dist/tools/fetch_mentions.js +5 -4
  15. package/dist/tools/get_account_info.js +0 -1
  16. package/dist/tools/get_alert.js +2 -2
  17. package/dist/tools/get_app_data.js +0 -1
  18. package/dist/tools/index.js +2 -1
  19. package/dist/tools/list_alerts.js +0 -1
  20. package/dist/tools/pause_alert.js +3 -3
  21. package/dist/tools/unpause_alert.js +3 -3
  22. package/dist/tools/update_alert.js +18 -18
  23. package/dist/types.js +74 -13
  24. package/package.json +9 -13
  25. package/dist/__tests__/api-client.test.d.ts +0 -2
  26. package/dist/__tests__/api-client.test.d.ts.map +0 -1
  27. package/dist/__tests__/api-client.test.js +0 -132
  28. package/dist/__tests__/api-client.test.js.map +0 -1
  29. package/dist/__tests__/config.test.d.ts +0 -2
  30. package/dist/__tests__/config.test.d.ts.map +0 -1
  31. package/dist/__tests__/config.test.js +0 -48
  32. package/dist/__tests__/config.test.js.map +0 -1
  33. package/dist/__tests__/tools.test.d.ts +0 -2
  34. package/dist/__tests__/tools.test.d.ts.map +0 -1
  35. package/dist/__tests__/tools.test.js +0 -228
  36. package/dist/__tests__/tools.test.js.map +0 -1
  37. package/dist/__tests__/types.test.d.ts +0 -2
  38. package/dist/__tests__/types.test.d.ts.map +0 -1
  39. package/dist/__tests__/types.test.js +0 -179
  40. package/dist/__tests__/types.test.js.map +0 -1
  41. package/dist/api-client.d.ts +0 -14
  42. package/dist/api-client.d.ts.map +0 -1
  43. package/dist/api-client.js.map +0 -1
  44. package/dist/config.d.ts +0 -10
  45. package/dist/config.d.ts.map +0 -1
  46. package/dist/config.js.map +0 -1
  47. package/dist/index.d.ts +0 -3
  48. package/dist/index.d.ts.map +0 -1
  49. package/dist/index.js.map +0 -1
  50. package/dist/logger.d.ts +0 -6
  51. package/dist/logger.d.ts.map +0 -1
  52. package/dist/logger.js.map +0 -1
  53. package/dist/prompts/base.d.ts +0 -25
  54. package/dist/prompts/base.d.ts.map +0 -1
  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.map +0 -1
  65. package/dist/tools/create_advanced_alert.d.ts +0 -3
  66. package/dist/tools/create_advanced_alert.d.ts.map +0 -1
  67. package/dist/tools/create_advanced_alert.js.map +0 -1
  68. package/dist/tools/create_basic_alert.d.ts +0 -3
  69. package/dist/tools/create_basic_alert.d.ts.map +0 -1
  70. package/dist/tools/create_basic_alert.js.map +0 -1
  71. package/dist/tools/fetch_mentions.d.ts +0 -3
  72. package/dist/tools/fetch_mentions.d.ts.map +0 -1
  73. package/dist/tools/fetch_mentions.js.map +0 -1
  74. package/dist/tools/get_account_info.d.ts +0 -3
  75. package/dist/tools/get_account_info.d.ts.map +0 -1
  76. package/dist/tools/get_account_info.js.map +0 -1
  77. package/dist/tools/get_alert.d.ts +0 -3
  78. package/dist/tools/get_alert.d.ts.map +0 -1
  79. package/dist/tools/get_alert.js.map +0 -1
  80. package/dist/tools/get_app_data.d.ts +0 -3
  81. package/dist/tools/get_app_data.d.ts.map +0 -1
  82. package/dist/tools/get_app_data.js.map +0 -1
  83. package/dist/tools/index.d.ts +0 -14
  84. package/dist/tools/index.d.ts.map +0 -1
  85. package/dist/tools/index.js.map +0 -1
  86. package/dist/tools/list_alerts.d.ts +0 -3
  87. package/dist/tools/list_alerts.d.ts.map +0 -1
  88. package/dist/tools/list_alerts.js.map +0 -1
  89. package/dist/tools/pause_alert.d.ts +0 -3
  90. package/dist/tools/pause_alert.d.ts.map +0 -1
  91. package/dist/tools/pause_alert.js.map +0 -1
  92. package/dist/tools/unpause_alert.d.ts +0 -3
  93. package/dist/tools/unpause_alert.d.ts.map +0 -1
  94. package/dist/tools/unpause_alert.js.map +0 -1
  95. package/dist/tools/update_alert.d.ts +0 -3
  96. package/dist/tools/update_alert.d.ts.map +0 -1
  97. package/dist/tools/update_alert.js.map +0 -1
  98. package/dist/types.d.ts +0 -389
  99. package/dist/types.d.ts.map +0 -1
  100. package/dist/types.js.map +0 -1
package/CHANGELOG.md ADDED
@@ -0,0 +1,101 @@
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.4.1] - 2026-11-25
11
+
12
+ ### Fixed
13
+ - README documents `MENTION_API_KEY` and `MENTION_API_BASE_URL`, the variable names the server reads
14
+ - 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
15
+ - The server no longer creates a log directory at startup, so a missing or read-only home directory does not crash it
16
+ - `fetch_mentions` sends `tone` and `countries` as `tone[]` and `countries[]`, so every tone value applies and a `countries` filter is no longer rejected
17
+ - `pause_alert` and `unpause_alert` report success with a short confirmation instead of "Network request failed" when the API answers with an empty body
18
+ - Requests send the server's real version in the `User-Agent` header, and `MCP_REQUEST_TIMEOUT` also bounds reading the response body
19
+ - `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
20
+ - `update_alert` accepts any source code returned by `get_app_data` in `sources`
21
+ - 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
22
+ - 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
23
+ - `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
24
+ - `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
25
+
26
+ ### Changed
27
+ - `MCP_LOG_LEVEL` accepts `debug`, `info`, `warn` and `error`; any other value falls back to `info` instead of crashing at startup
28
+ - The package requires Node.js 22 or later (`engines.node`)
29
+ - The published package contains only the compiled server, README, LICENSE and CHANGELOG; tests, type declarations and source maps are no longer shipped
30
+
31
+ ### Removed
32
+ - `MCP_CONSOLE_LOGGING` option and the platform-specific log files
33
+ - `pino` and `pino-pretty` dependencies
34
+ - `languages` parameter of `fetch_mentions`, which the endpoint did not apply
35
+ - `query_type` parameter of `update_alert`, now inferred from the fields passed
36
+ - `noise_detection` parameter of `create_basic_alert`, `create_advanced_alert` and `update_alert`, which the API does not accept
37
+ - Retry-count environment variable and its config field; the server parsed it but never retried requests
38
+ - `main` field of `package.json`; the package is a command-line server with no importable API
39
+ - `important` parameter of `fetch_alert_stats`, which the API does not accept
40
+
41
+ ## [1.4.0] - 2025-06-29
42
+
43
+ ### Added
44
+ - **New Tool**: `fetch_alert_stats` - Retrieve comprehensive alert statistics
45
+ - Flexible date range filtering with `from`, `to`, and `timezone` parameters
46
+ - Aggregation by interval: daily (P1D), weekly (P1W), monthly (P1M)
47
+ - Multi-dimensional filtering by `tones`, `languages`, `sources`, `countries`, `tags`
48
+ - Statistical analysis with `favorite`, `important`, and author influence filtering
49
+ - Geographic insights with configurable `country_stats` (top N countries)
50
+ - Temporal analysis with `week_day_stats` and `week_day_by_hour_stats`
51
+ - Influencer tracking and reach metrics per interval
52
+
53
+ ## [1.3.0] - 2025-06-28
54
+
55
+ ### Added
56
+ - **New Tool**: `fetch_mentions` - Retrieve mentions with comprehensive filtering support
57
+ - Supports pagination with `since_id`, `cursor`, and `limit` parameters
58
+ - Date filtering with `before_date`, `not_before_date`, and `timezone`
59
+ - Content filtering by `source`, `folder`, `tone`, `unread`, `favorite`
60
+ - Geographic and language filtering with `countries` and `languages`
61
+ - Advanced search with `q` parameter and sorting options
62
+ - Support for including child mentions with `include_children`
63
+
64
+ ### Changed
65
+ - **Alert Creation Response**: `create_basic_alert` and `create_advanced_alert` now return only the alert ID instead of the full response for cleaner output
66
+ - **Improved Error Handling**: Enhanced API error logging with full response bodies for better debugging
67
+
68
+ ### Fixed
69
+ - **Boolean Query Validation**: Added better error messages for boolean query syntax errors in advanced alerts
70
+ - **API Response Parsing**: Improved error handling when API responses don't match expected structure
71
+
72
+ ## [1.2.0] - 2025-06-28
73
+
74
+ ### Added
75
+ - **Custom Prompt**: `build-boolean-query` prompt for generating valid Boolean query strings
76
+ - **Enhanced Alert Creation**: Improved validation and error messages for alert creation
77
+
78
+ ### Changed
79
+ - **Response Format**: Streamlined alert creation responses to return essential data only
80
+
81
+ ## 1.0.0
82
+
83
+ ### Added
84
+ - Initial release of the Mention MCP Server
85
+ - Complete implementation of Mention API integration
86
+
87
+ ### Features
88
+ - **Account Management**: Get account info and application data
89
+ - **Alert Creation**: Basic and advanced alert creation with plan detection
90
+ - **Alert Management**: Update, pause/unpause existing alerts
91
+
92
+ ### Tools Available
93
+ - `get_account_info` - Account information and subscription details
94
+ - `get_app_data` - Available languages, countries, sources metadata
95
+ - `list_alerts` - List all monitoring alerts with pagination
96
+ - `get_alert` - Get specific alert details
97
+ - `create_basic_alert` - Create alerts for basic subscription plans
98
+ - `create_advanced_alert` - Create alerts with boolean queries for advanced plans
99
+ - `update_alert` - Update existing alerts
100
+ - `pause_alert` - Temporarily pause monitoring for specific alerts
101
+ - `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
 
@@ -20,6 +20,7 @@ A production-ready [Model Context Protocol (MCP)](https://modelcontextprotocol.i
20
20
  | `pause_alert` | Temporarily pause monitoring for specific alerts |
21
21
  | `unpause_alert` | Resume monitoring for paused alerts |
22
22
  | `fetch_mentions` | Retrieve mentions with advanced filtering |
23
+ | `fetch_alert_stats` | Get comprehensive statistics for alerts |
23
24
 
24
25
  ## Installation & Usage
25
26
 
@@ -34,7 +35,7 @@ Add the following to your Claude Desktop configuration file:
34
35
  "command": "npx",
35
36
  "args": ["-y", "@maelitop/mention-mcp-server"],
36
37
  "env": {
37
- "MCP_MENTION_API_KEY": "your_mention_api_key_here"
38
+ "MENTION_API_KEY": "your_mention_api_key_here"
38
39
  }
39
40
  }
40
41
  }
@@ -45,12 +46,10 @@ Add the following to your Claude Desktop configuration file:
45
46
 
46
47
  | Variable | Description | Default |
47
48
  |----------|-------------|---------|
48
- | `MCP_MENTION_API_KEY` | Your Mention API key (required) | - |
49
- | `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` |
50
51
  | `MCP_LOG_LEVEL` | Logging level (`debug`, `info`, `warn`, `error`) | `info` |
51
- | `MCP_CONSOLE_LOGGING` | Enable console logging (`true`/`false`) | `false` |
52
- | `MCP_REQUEST_TIMEOUT` | Request timeout in milliseconds | `30000` |
53
- | `MCP_MAX_RETRIES` | Maximum retry attempts | `3` |
52
+ | `MCP_REQUEST_TIMEOUT` | Request timeout in milliseconds, a whole number from `1` to `2147483647` | `30000` |
54
53
 
55
54
 
56
55
  ### Development
@@ -68,31 +67,34 @@ npm test
68
67
  # Build for production
69
68
  npm run build
70
69
 
71
- # Run linting and type checking
70
+ # Run linting, build and tests
72
71
  npm run ci
73
72
  ```
74
73
 
75
- ## Logging
76
-
77
- Logs are automatically written to platform-specific directories:
78
-
79
- - **macOS**: `~/Library/Logs/mention-mcp-server/mention-mcp-server.log`
80
- - **Windows**: `~/AppData/Local/mention-mcp-server/logs/mention-mcp-server.log`
81
- - **Linux**: `~/.local/share/mention-mcp-server/logs/mention-mcp-server.log`
82
-
83
74
  ## Testing
84
75
 
85
76
  ```bash
86
77
  # Run all tests
87
78
  npm test
88
79
 
89
- # Run tests with coverage
90
- npm run test:coverage
91
-
92
80
  # Run tests in watch mode
93
81
  npm run test -- --watch
94
82
  ```
95
83
 
84
+ ## Releasing
85
+
86
+ 1. On an up-to-date `main`, move the `## [Unreleased]` entries of `CHANGELOG.md` under a heading for the new version and commit.
87
+ 2. Bump the version, commit it and create the `v<version>` tag:
88
+ ```bash
89
+ npm version patch -m "chore(release): %s" # or minor, major
90
+ ```
91
+ 3. Push the commit and the tag:
92
+ ```bash
93
+ git push origin main --follow-tags
94
+ ```
95
+
96
+ 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.
97
+
96
98
  ## License
97
99
 
98
100
  This project is licensed under the [MIT License](LICENSE).
@@ -1,32 +1,40 @@
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
+ }
4
12
  export class MentionAPIClient {
5
13
  config;
14
+ userAgent;
6
15
  accountCache = null;
7
16
  accountCacheExpiry = 0;
8
17
  accountCacheTTL = 5 * 60 * 1000; // 5 minutes
9
- constructor(config) {
18
+ constructor(config, serverVersion) {
10
19
  this.config = config;
20
+ this.userAgent = `mention-mcp-server/${serverVersion}`;
11
21
  }
12
22
  async makeRequest(endpoint, options = {}) {
13
23
  const url = `${this.config.apiBaseUrl}${endpoint}`;
14
24
  const requestId = Math.random().toString(36).substring(7);
15
25
  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
26
  try {
19
27
  const response = await fetch(url, {
20
28
  ...options,
21
- signal: controller.signal,
29
+ signal: AbortSignal.timeout(this.config.requestTimeout),
22
30
  headers: {
23
31
  Authorization: `Bearer ${this.config.apiKey}`,
24
32
  "Content-Type": "application/json",
25
- "User-Agent": "mention-mcp-server/1.0.0",
33
+ "User-Agent": this.userAgent,
34
+ "Accept-Version": "1.21",
26
35
  ...options.headers,
27
36
  },
28
37
  });
29
- clearTimeout(timeoutId);
30
38
  if (!response.ok) {
31
39
  let rawErrorData;
32
40
  let errorMsg;
@@ -75,16 +83,16 @@ export class MentionAPIClient {
75
83
  }
76
84
  throw new McpError(ErrorCode.InternalError, errorMsg);
77
85
  }
78
- const responseData = await response.json();
86
+ const responseText = await response.text();
87
+ const responseData = responseText ? JSON.parse(responseText) : null;
79
88
  logDebug("API request successful", { requestId, endpoint });
80
89
  return responseData;
81
90
  }
82
91
  catch (error) {
83
- clearTimeout(timeoutId);
84
92
  if (error instanceof McpError) {
85
93
  throw error;
86
94
  }
87
- if (error instanceof Error && error.name === "AbortError") {
95
+ if (error instanceof Error && error.name === "TimeoutError") {
88
96
  const errorMsg = "Request timeout";
89
97
  logError(errorMsg, error, { requestId, endpoint, timeout: this.config.requestTimeout });
90
98
  throw new McpError(ErrorCode.InternalError, errorMsg);
@@ -117,10 +125,4 @@ export class MentionAPIClient {
117
125
  const accountInfo = await this.getAccountInfo();
118
126
  return accountInfo.account.id;
119
127
  }
120
- clearAccountCache() {
121
- this.accountCache = null;
122
- this.accountCacheExpiry = 0;
123
- logDebug("Account cache cleared");
124
- }
125
128
  }
126
- //# sourceMappingURL=api-client.js.map
package/dist/config.js CHANGED
@@ -1,3 +1,12 @@
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
+ }
1
10
  export function loadConfig() {
2
11
  const apiKey = process.env.MENTION_API_KEY;
3
12
  if (!apiKey) {
@@ -7,9 +16,6 @@ export function loadConfig() {
7
16
  apiKey,
8
17
  apiBaseUrl: process.env.MENTION_API_BASE_URL || "https://web.mention.com/api",
9
18
  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),
19
+ requestTimeout: parseRequestTimeout(process.env.MCP_REQUEST_TIMEOUT || "30000"),
13
20
  };
14
21
  }
15
- //# sourceMappingURL=config.js.map
package/dist/index.js CHANGED
@@ -33,7 +33,7 @@ async function createServer() {
33
33
  throw error;
34
34
  }
35
35
  const version = getPackageVersion();
36
- const apiClient = new MentionAPIClient(config);
36
+ const apiClient = new MentionAPIClient(config, version);
37
37
  const toolHandlers = new ToolHandlers(apiClient);
38
38
  const server = new Server({
39
39
  name: "mention-mcp-server",
@@ -99,4 +99,3 @@ main().catch((error) => {
99
99
  logError("Fatal error in main", error);
100
100
  process.exit(1);
101
101
  });
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,2 +1 @@
1
1
  export {};
2
- //# sourceMappingURL=base.js.map
@@ -60,4 +60,3 @@ export const buildBooleanQueryPrompt = {
60
60
  };
61
61
  },
62
62
  };
63
- //# sourceMappingURL=build-boolean-query.js.map
@@ -1,3 +1,2 @@
1
1
  import { buildBooleanQueryPrompt } from "./build-boolean-query.js";
2
2
  export const prompts = [buildBooleanQueryPrompt];
3
- //# sourceMappingURL=index.js.map
@@ -1,2 +1 @@
1
1
  export {};
2
- //# sourceMappingURL=base.js.map
@@ -63,4 +63,3 @@ export const createAdvancedAlertTool = {
63
63
  },
64
64
  createHandler: createAdvancedAlertHandler,
65
65
  };
66
- //# sourceMappingURL=create_advanced_alert.js.map
@@ -54,4 +54,3 @@ export const createBasicAlertTool = {
54
54
  },
55
55
  createHandler: createBasicAlertHandler,
56
56
  };
57
- //# sourceMappingURL=create_basic_alert.js.map
@@ -0,0 +1,94 @@
1
+ import { zodToJsonSchema } from "zod-to-json-schema";
2
+ import { logError, logInfo } from "../logger.js";
3
+ import { FetchAlertStatsArgsSchema } from "../types.js";
4
+ function createFetchAlertStatsHandler(apiClient) {
5
+ return {
6
+ async handle(args) {
7
+ try {
8
+ const validated = FetchAlertStatsArgsSchema.parse(args);
9
+ const accountId = await apiClient.getAccountId();
10
+ // Build query parameters
11
+ const searchParams = new URLSearchParams();
12
+ // Handle the required alerts array
13
+ for (const alertId of validated.alerts) {
14
+ searchParams.append("alerts[]", alertId);
15
+ }
16
+ searchParams.append("from", validated.from);
17
+ searchParams.append("to", validated.to);
18
+ searchParams.append("interval", validated.interval);
19
+ // Handle optional parameters
20
+ const optionalParams = {
21
+ timezone: validated.timezone,
22
+ favorite: validated.favorite,
23
+ week_day_stats: validated.week_day_stats,
24
+ week_day_by_hour_stats: validated.week_day_by_hour_stats,
25
+ influencers: validated.influencers,
26
+ reach_per_interval_stats: validated.reach_per_interval_stats,
27
+ "author_influence.score": validated["author_influence.score"],
28
+ };
29
+ for (const [key, value] of Object.entries(optionalParams)) {
30
+ if (value !== undefined && value !== null) {
31
+ searchParams.append(key, String(value));
32
+ }
33
+ }
34
+ // Handle array parameters
35
+ const arrayParams = {
36
+ "tones[]": validated.tones,
37
+ "languages[]": validated.languages,
38
+ "sources[]": validated.sources,
39
+ "countries[]": validated.countries,
40
+ "tags[]": validated.tags,
41
+ };
42
+ for (const [key, values] of Object.entries(arrayParams)) {
43
+ if (values && Array.isArray(values)) {
44
+ for (const value of values) {
45
+ searchParams.append(key, String(value));
46
+ }
47
+ }
48
+ }
49
+ // Handle special country_stats parameter
50
+ if (validated.country_stats !== undefined) {
51
+ if (typeof validated.country_stats === "boolean") {
52
+ searchParams.append("country_stats", validated.country_stats ? "10" : "0");
53
+ }
54
+ else {
55
+ searchParams.append("country_stats", String(validated.country_stats));
56
+ }
57
+ }
58
+ const queryString = searchParams.toString();
59
+ const endpoint = `/accounts/${accountId}/stats${queryString ? `?${queryString}` : ""}`;
60
+ const data = await apiClient.makeRequest(endpoint);
61
+ logInfo("Alert statistics fetched successfully", {
62
+ accountId,
63
+ alertIds: validated.alerts,
64
+ endpoint,
65
+ from: validated.from,
66
+ to: validated.to,
67
+ partial: data?.partial || false,
68
+ });
69
+ return {
70
+ content: [
71
+ {
72
+ type: "text",
73
+ text: JSON.stringify(data, null, 2),
74
+ },
75
+ ],
76
+ };
77
+ }
78
+ catch (error) {
79
+ logError("Failed to fetch alert statistics", error);
80
+ throw error;
81
+ }
82
+ },
83
+ };
84
+ }
85
+ export const fetchAlertStatsTool = {
86
+ getDefinition() {
87
+ return {
88
+ name: "fetch_alert_stats",
89
+ description: "Retrieve comprehensive statistics for one or more alerts including mentions per interval, tones, influencers, geographical data, and reach metrics. Supports flexible date ranges, filtering, and aggregation options.",
90
+ inputSchema: zodToJsonSchema(FetchAlertStatsArgsSchema),
91
+ };
92
+ },
93
+ createHandler: createFetchAlertStatsHandler,
94
+ };
@@ -1,4 +1,5 @@
1
1
  import { zodToJsonSchema } from "zod-to-json-schema";
2
+ import { apiPath } from "../api-client.js";
2
3
  import { logError, logInfo } from "../logger.js";
3
4
  import { FetchMentionsArgsSchema } from "../types.js";
4
5
  function createFetchMentionsHandler(apiClient) {
@@ -13,7 +14,7 @@ function createFetchMentionsHandler(apiClient) {
13
14
  if (value !== undefined && value !== null) {
14
15
  if (Array.isArray(value)) {
15
16
  for (const item of value) {
16
- searchParams.append(key, String(item));
17
+ searchParams.append(`${key}[]`, String(item));
17
18
  }
18
19
  }
19
20
  else {
@@ -22,7 +23,8 @@ function createFetchMentionsHandler(apiClient) {
22
23
  }
23
24
  }
24
25
  const queryString = searchParams.toString();
25
- const endpoint = `/accounts/${accountId}/alerts/${alert_id}/mentions${queryString ? `?${queryString}` : ""}`;
26
+ const path = apiPath `/accounts/${accountId}/alerts/${alert_id}/mentions`;
27
+ const endpoint = queryString ? `${path}?${queryString}` : path;
26
28
  const data = await apiClient.makeRequest(endpoint);
27
29
  logInfo("Mentions fetched successfully", {
28
30
  accountId,
@@ -50,10 +52,9 @@ export const fetchMentionsTool = {
50
52
  getDefinition() {
51
53
  return {
52
54
  name: "fetch_mentions",
53
- description: "Retrieve mentions associated with a specific alert. Supports various filters like source, folder, tone, countries, languages, and advanced search queries.",
55
+ description: "Retrieve mentions associated with a specific alert. Supports various filters like source, folder, tone, countries, and advanced search queries.",
54
56
  inputSchema: zodToJsonSchema(FetchMentionsArgsSchema),
55
57
  };
56
58
  },
57
59
  createHandler: createFetchMentionsHandler,
58
60
  };
59
- //# sourceMappingURL=fetch_mentions.js.map
@@ -43,4 +43,3 @@ export const getAccountInfoTool = {
43
43
  },
44
44
  createHandler: createGetAccountInfoHandler,
45
45
  };
46
- //# sourceMappingURL=get_account_info.js.map
@@ -1,4 +1,5 @@
1
1
  import { zodToJsonSchema } from "zod-to-json-schema";
2
+ import { apiPath } from "../api-client.js";
2
3
  import { logError, logInfo } from "../logger.js";
3
4
  import { GetAlertArgsSchema } from "../types.js";
4
5
  function createGetAlertHandler(apiClient) {
@@ -7,7 +8,7 @@ function createGetAlertHandler(apiClient) {
7
8
  try {
8
9
  const { alert_id } = GetAlertArgsSchema.parse(args);
9
10
  const accountId = await apiClient.getAccountId();
10
- const data = await apiClient.makeRequest(`/accounts/${accountId}/alerts/${alert_id}`);
11
+ const data = await apiClient.makeRequest(apiPath `/accounts/${accountId}/alerts/${alert_id}`);
11
12
  logInfo("Alert retrieved", { accountId, alertId: alert_id });
12
13
  return {
13
14
  content: [
@@ -35,4 +36,3 @@ export const getAlertTool = {
35
36
  },
36
37
  createHandler: createGetAlertHandler,
37
38
  };
38
- //# sourceMappingURL=get_alert.js.map
@@ -44,4 +44,3 @@ export const getAppDataTool = {
44
44
  },
45
45
  createHandler: createGetAppDataHandler,
46
46
  };
47
- //# sourceMappingURL=get_app_data.js.map
@@ -2,6 +2,7 @@ import { ErrorCode, McpError } from "@modelcontextprotocol/sdk/types.js";
2
2
  import { logError, logInfo } from "../logger.js";
3
3
  import { createAdvancedAlertTool } from "./create_advanced_alert.js";
4
4
  import { createBasicAlertTool } from "./create_basic_alert.js";
5
+ import { fetchAlertStatsTool } from "./fetch_alert_stats.js";
5
6
  import { fetchMentionsTool } from "./fetch_mentions.js";
6
7
  import { getAccountInfoTool } from "./get_account_info.js";
7
8
  import { getAlertTool } from "./get_alert.js";
@@ -21,6 +22,7 @@ const tools = [
21
22
  pauseAlertTool,
22
23
  unpauseAlertTool,
23
24
  fetchMentionsTool,
25
+ fetchAlertStatsTool,
24
26
  ];
25
27
  export function getToolDefinitions() {
26
28
  return tools.map((tool) => tool.getDefinition());
@@ -53,4 +55,3 @@ export class ToolHandlers {
53
55
  }
54
56
  }
55
57
  }
56
- //# sourceMappingURL=index.js.map
@@ -41,4 +41,3 @@ export const listAlertsTool = {
41
41
  },
42
42
  createHandler: createListAlertsHandler,
43
43
  };
44
- //# sourceMappingURL=list_alerts.js.map
@@ -1,4 +1,5 @@
1
1
  import { zodToJsonSchema } from "zod-to-json-schema";
2
+ import { apiPath } from "../api-client.js";
2
3
  import { logError, logInfo } from "../logger.js";
3
4
  import { PauseAlertArgsSchema } from "../types.js";
4
5
  function createPauseAlertHandler(apiClient) {
@@ -7,7 +8,7 @@ function createPauseAlertHandler(apiClient) {
7
8
  try {
8
9
  const { alert_id } = PauseAlertArgsSchema.parse(args);
9
10
  const accountId = await apiClient.getAccountId();
10
- const data = await apiClient.makeRequest(`/accounts/${accountId}/alerts/${alert_id}/pause`, {
11
+ await apiClient.makeRequest(apiPath `/accounts/${accountId}/alerts/${alert_id}/pause`, {
11
12
  method: "POST",
12
13
  });
13
14
  logInfo("Alert paused", { accountId, alertId: alert_id });
@@ -15,7 +16,7 @@ function createPauseAlertHandler(apiClient) {
15
16
  content: [
16
17
  {
17
18
  type: "text",
18
- text: JSON.stringify(data, null, 2),
19
+ text: `Alert ${alert_id} paused.`,
19
20
  },
20
21
  ],
21
22
  };
@@ -37,4 +38,3 @@ export const pauseAlertTool = {
37
38
  },
38
39
  createHandler: createPauseAlertHandler,
39
40
  };
40
- //# sourceMappingURL=pause_alert.js.map