euparliamentmonitor 0.8.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +1005 -0
- package/SECURITY.md +151 -0
- package/package.json +131 -0
- package/scripts/constants/committee-indicator-map.d.ts +199 -0
- package/scripts/constants/committee-indicator-map.d.ts.map +1 -0
- package/scripts/constants/committee-indicator-map.js +1224 -0
- package/scripts/constants/committee-indicator-map.js.map +1 -0
- package/scripts/constants/config.d.ts +38 -0
- package/scripts/constants/config.d.ts.map +1 -0
- package/scripts/constants/config.js +66 -0
- package/scripts/constants/config.js.map +1 -0
- package/scripts/constants/language-articles.d.ts +84 -0
- package/scripts/constants/language-articles.d.ts.map +1 -0
- package/scripts/constants/language-articles.js +6771 -0
- package/scripts/constants/language-articles.js.map +1 -0
- package/scripts/constants/language-core.d.ts +38 -0
- package/scripts/constants/language-core.d.ts.map +1 -0
- package/scripts/constants/language-core.js +90 -0
- package/scripts/constants/language-core.js.map +1 -0
- package/scripts/constants/language-ui.d.ts +82 -0
- package/scripts/constants/language-ui.d.ts.map +1 -0
- package/scripts/constants/language-ui.js +889 -0
- package/scripts/constants/language-ui.js.map +1 -0
- package/scripts/constants/languages.d.ts +14 -0
- package/scripts/constants/languages.d.ts.map +1 -0
- package/scripts/constants/languages.js +15 -0
- package/scripts/constants/languages.js.map +1 -0
- package/scripts/generators/analysis-builders.d.ts +266 -0
- package/scripts/generators/analysis-builders.d.ts.map +1 -0
- package/scripts/generators/analysis-builders.js +2903 -0
- package/scripts/generators/analysis-builders.js.map +1 -0
- package/scripts/generators/breaking-content.d.ts +45 -0
- package/scripts/generators/breaking-content.d.ts.map +1 -0
- package/scripts/generators/breaking-content.js +530 -0
- package/scripts/generators/breaking-content.js.map +1 -0
- package/scripts/generators/committee-helpers.d.ts +54 -0
- package/scripts/generators/committee-helpers.d.ts.map +1 -0
- package/scripts/generators/committee-helpers.js +154 -0
- package/scripts/generators/committee-helpers.js.map +1 -0
- package/scripts/generators/dashboard-content.d.ts +95 -0
- package/scripts/generators/dashboard-content.d.ts.map +1 -0
- package/scripts/generators/dashboard-content.js +630 -0
- package/scripts/generators/dashboard-content.js.map +1 -0
- package/scripts/generators/deep-analysis-content.d.ts +23 -0
- package/scripts/generators/deep-analysis-content.d.ts.map +1 -0
- package/scripts/generators/deep-analysis-content.js +831 -0
- package/scripts/generators/deep-analysis-content.js.map +1 -0
- package/scripts/generators/mindmap-content.d.ts +55 -0
- package/scripts/generators/mindmap-content.d.ts.map +1 -0
- package/scripts/generators/mindmap-content.js +512 -0
- package/scripts/generators/mindmap-content.js.map +1 -0
- package/scripts/generators/motions-content.d.ts +50 -0
- package/scripts/generators/motions-content.d.ts.map +1 -0
- package/scripts/generators/motions-content.js +391 -0
- package/scripts/generators/motions-content.js.map +1 -0
- package/scripts/generators/news-enhanced.d.ts +14 -0
- package/scripts/generators/news-enhanced.d.ts.map +1 -0
- package/scripts/generators/news-enhanced.js +169 -0
- package/scripts/generators/news-enhanced.js.map +1 -0
- package/scripts/generators/news-indexes.d.ts +31 -0
- package/scripts/generators/news-indexes.d.ts.map +1 -0
- package/scripts/generators/news-indexes.js +410 -0
- package/scripts/generators/news-indexes.js.map +1 -0
- package/scripts/generators/pipeline/fetch-stage.d.ts +352 -0
- package/scripts/generators/pipeline/fetch-stage.d.ts.map +1 -0
- package/scripts/generators/pipeline/fetch-stage.js +1522 -0
- package/scripts/generators/pipeline/fetch-stage.js.map +1 -0
- package/scripts/generators/pipeline/generate-stage.d.ts +43 -0
- package/scripts/generators/pipeline/generate-stage.d.ts.map +1 -0
- package/scripts/generators/pipeline/generate-stage.js +204 -0
- package/scripts/generators/pipeline/generate-stage.js.map +1 -0
- package/scripts/generators/pipeline/output-stage.d.ts +48 -0
- package/scripts/generators/pipeline/output-stage.d.ts.map +1 -0
- package/scripts/generators/pipeline/output-stage.js +145 -0
- package/scripts/generators/pipeline/output-stage.js.map +1 -0
- package/scripts/generators/pipeline/transform-stage.d.ts +57 -0
- package/scripts/generators/pipeline/transform-stage.d.ts.map +1 -0
- package/scripts/generators/pipeline/transform-stage.js +111 -0
- package/scripts/generators/pipeline/transform-stage.js.map +1 -0
- package/scripts/generators/propositions-content.d.ts +29 -0
- package/scripts/generators/propositions-content.d.ts.map +1 -0
- package/scripts/generators/propositions-content.js +90 -0
- package/scripts/generators/propositions-content.js.map +1 -0
- package/scripts/generators/sankey-content.d.ts +45 -0
- package/scripts/generators/sankey-content.d.ts.map +1 -0
- package/scripts/generators/sankey-content.js +227 -0
- package/scripts/generators/sankey-content.js.map +1 -0
- package/scripts/generators/sitemap.d.ts +66 -0
- package/scripts/generators/sitemap.d.ts.map +1 -0
- package/scripts/generators/sitemap.js +562 -0
- package/scripts/generators/sitemap.js.map +1 -0
- package/scripts/generators/strategies/article-strategy.d.ts +146 -0
- package/scripts/generators/strategies/article-strategy.d.ts.map +1 -0
- package/scripts/generators/strategies/article-strategy.js +4 -0
- package/scripts/generators/strategies/article-strategy.js.map +1 -0
- package/scripts/generators/strategies/breaking-news-strategy.d.ts +64 -0
- package/scripts/generators/strategies/breaking-news-strategy.d.ts.map +1 -0
- package/scripts/generators/strategies/breaking-news-strategy.js +246 -0
- package/scripts/generators/strategies/breaking-news-strategy.js.map +1 -0
- package/scripts/generators/strategies/committee-reports-strategy.d.ts +93 -0
- package/scripts/generators/strategies/committee-reports-strategy.d.ts.map +1 -0
- package/scripts/generators/strategies/committee-reports-strategy.js +447 -0
- package/scripts/generators/strategies/committee-reports-strategy.js.map +1 -0
- package/scripts/generators/strategies/month-ahead-strategy.d.ts +60 -0
- package/scripts/generators/strategies/month-ahead-strategy.d.ts.map +1 -0
- package/scripts/generators/strategies/month-ahead-strategy.js +175 -0
- package/scripts/generators/strategies/month-ahead-strategy.js.map +1 -0
- package/scripts/generators/strategies/monthly-review-strategy.d.ts +66 -0
- package/scripts/generators/strategies/monthly-review-strategy.d.ts.map +1 -0
- package/scripts/generators/strategies/monthly-review-strategy.js +204 -0
- package/scripts/generators/strategies/monthly-review-strategy.js.map +1 -0
- package/scripts/generators/strategies/motions-strategy.d.ts +61 -0
- package/scripts/generators/strategies/motions-strategy.d.ts.map +1 -0
- package/scripts/generators/strategies/motions-strategy.js +215 -0
- package/scripts/generators/strategies/motions-strategy.js.map +1 -0
- package/scripts/generators/strategies/propositions-strategy.d.ts +60 -0
- package/scripts/generators/strategies/propositions-strategy.d.ts.map +1 -0
- package/scripts/generators/strategies/propositions-strategy.js +257 -0
- package/scripts/generators/strategies/propositions-strategy.js.map +1 -0
- package/scripts/generators/strategies/week-ahead-strategy.d.ts +57 -0
- package/scripts/generators/strategies/week-ahead-strategy.d.ts.map +1 -0
- package/scripts/generators/strategies/week-ahead-strategy.js +178 -0
- package/scripts/generators/strategies/week-ahead-strategy.js.map +1 -0
- package/scripts/generators/strategies/weekly-review-strategy.d.ts +63 -0
- package/scripts/generators/strategies/weekly-review-strategy.d.ts.map +1 -0
- package/scripts/generators/strategies/weekly-review-strategy.js +211 -0
- package/scripts/generators/strategies/weekly-review-strategy.js.map +1 -0
- package/scripts/generators/swot-content.d.ts +42 -0
- package/scripts/generators/swot-content.d.ts.map +1 -0
- package/scripts/generators/swot-content.js +366 -0
- package/scripts/generators/swot-content.js.map +1 -0
- package/scripts/generators/week-ahead-content.d.ts +103 -0
- package/scripts/generators/week-ahead-content.d.ts.map +1 -0
- package/scripts/generators/week-ahead-content.js +610 -0
- package/scripts/generators/week-ahead-content.js.map +1 -0
- package/scripts/index.d.ts +40 -0
- package/scripts/index.d.ts.map +1 -0
- package/scripts/index.js +53 -0
- package/scripts/index.js.map +1 -0
- package/scripts/mcp/ep-mcp-client.d.ts +471 -0
- package/scripts/mcp/ep-mcp-client.d.ts.map +1 -0
- package/scripts/mcp/ep-mcp-client.js +734 -0
- package/scripts/mcp/ep-mcp-client.js.map +1 -0
- package/scripts/mcp/mcp-connection.d.ts +264 -0
- package/scripts/mcp/mcp-connection.d.ts.map +1 -0
- package/scripts/mcp/mcp-connection.js +790 -0
- package/scripts/mcp/mcp-connection.js.map +1 -0
- package/scripts/mcp/mcp-health.d.ts +75 -0
- package/scripts/mcp/mcp-health.d.ts.map +1 -0
- package/scripts/mcp/mcp-health.js +78 -0
- package/scripts/mcp/mcp-health.js.map +1 -0
- package/scripts/mcp/mcp-retry.d.ts +94 -0
- package/scripts/mcp/mcp-retry.d.ts.map +1 -0
- package/scripts/mcp/mcp-retry.js +127 -0
- package/scripts/mcp/mcp-retry.js.map +1 -0
- package/scripts/mcp/wb-mcp-client.d.ts +38 -0
- package/scripts/mcp/wb-mcp-client.d.ts.map +1 -0
- package/scripts/mcp/wb-mcp-client.js +112 -0
- package/scripts/mcp/wb-mcp-client.js.map +1 -0
- package/scripts/templates/article-template.d.ts +9 -0
- package/scripts/templates/article-template.d.ts.map +1 -0
- package/scripts/templates/article-template.js +378 -0
- package/scripts/templates/article-template.js.map +1 -0
- package/scripts/templates/section-builders.d.ts +28 -0
- package/scripts/templates/section-builders.d.ts.map +1 -0
- package/scripts/templates/section-builders.js +142 -0
- package/scripts/templates/section-builders.js.map +1 -0
- package/scripts/types/analysis.d.ts +115 -0
- package/scripts/types/analysis.d.ts.map +1 -0
- package/scripts/types/analysis.js +4 -0
- package/scripts/types/analysis.js.map +1 -0
- package/scripts/types/common.d.ts +584 -0
- package/scripts/types/common.d.ts.map +1 -0
- package/scripts/types/common.js +96 -0
- package/scripts/types/common.js.map +1 -0
- package/scripts/types/generation.d.ts +104 -0
- package/scripts/types/generation.d.ts.map +1 -0
- package/scripts/types/generation.js +4 -0
- package/scripts/types/generation.js.map +1 -0
- package/scripts/types/index.d.ts +24 -0
- package/scripts/types/index.d.ts.map +1 -0
- package/scripts/types/index.js +16 -0
- package/scripts/types/index.js.map +1 -0
- package/scripts/types/intelligence.d.ts +129 -0
- package/scripts/types/intelligence.d.ts.map +1 -0
- package/scripts/types/intelligence.js +4 -0
- package/scripts/types/intelligence.js.map +1 -0
- package/scripts/types/mcp.d.ts +418 -0
- package/scripts/types/mcp.d.ts.map +1 -0
- package/scripts/types/mcp.js +4 -0
- package/scripts/types/mcp.js.map +1 -0
- package/scripts/types/parliament.d.ts +388 -0
- package/scripts/types/parliament.d.ts.map +1 -0
- package/scripts/types/parliament.js +4 -0
- package/scripts/types/parliament.js.map +1 -0
- package/scripts/types/quality.d.ts +114 -0
- package/scripts/types/quality.d.ts.map +1 -0
- package/scripts/types/quality.js +4 -0
- package/scripts/types/quality.js.map +1 -0
- package/scripts/types/stakeholder.d.ts +88 -0
- package/scripts/types/stakeholder.d.ts.map +1 -0
- package/scripts/types/stakeholder.js +16 -0
- package/scripts/types/stakeholder.js.map +1 -0
- package/scripts/types/visualization.d.ts +708 -0
- package/scripts/types/visualization.d.ts.map +1 -0
- package/scripts/types/visualization.js +4 -0
- package/scripts/types/visualization.js.map +1 -0
- package/scripts/types/world-bank.d.ts +85 -0
- package/scripts/types/world-bank.d.ts.map +1 -0
- package/scripts/types/world-bank.js +4 -0
- package/scripts/types/world-bank.js.map +1 -0
- package/scripts/utils/article-category.d.ts +18 -0
- package/scripts/utils/article-category.d.ts.map +1 -0
- package/scripts/utils/article-category.js +49 -0
- package/scripts/utils/article-category.js.map +1 -0
- package/scripts/utils/article-quality-scorer.d.ts +87 -0
- package/scripts/utils/article-quality-scorer.d.ts.map +1 -0
- package/scripts/utils/article-quality-scorer.js +1048 -0
- package/scripts/utils/article-quality-scorer.js.map +1 -0
- package/scripts/utils/content-metadata.d.ts +34 -0
- package/scripts/utils/content-metadata.d.ts.map +1 -0
- package/scripts/utils/content-metadata.js +249 -0
- package/scripts/utils/content-metadata.js.map +1 -0
- package/scripts/utils/content-validator.d.ts +94 -0
- package/scripts/utils/content-validator.d.ts.map +1 -0
- package/scripts/utils/content-validator.js +489 -0
- package/scripts/utils/content-validator.js.map +1 -0
- package/scripts/utils/copy-test-reports.d.ts +9 -0
- package/scripts/utils/copy-test-reports.d.ts.map +1 -0
- package/scripts/utils/copy-test-reports.js +508 -0
- package/scripts/utils/copy-test-reports.js.map +1 -0
- package/scripts/utils/file-utils.d.ts +144 -0
- package/scripts/utils/file-utils.d.ts.map +1 -0
- package/scripts/utils/file-utils.js +374 -0
- package/scripts/utils/file-utils.js.map +1 -0
- package/scripts/utils/fix-articles.d.ts +27 -0
- package/scripts/utils/fix-articles.d.ts.map +1 -0
- package/scripts/utils/fix-articles.js +510 -0
- package/scripts/utils/fix-articles.js.map +1 -0
- package/scripts/utils/generate-docs-index.d.ts +8 -0
- package/scripts/utils/generate-docs-index.d.ts.map +1 -0
- package/scripts/utils/generate-docs-index.js +275 -0
- package/scripts/utils/generate-docs-index.js.map +1 -0
- package/scripts/utils/html-sanitize.d.ts +18 -0
- package/scripts/utils/html-sanitize.d.ts.map +1 -0
- package/scripts/utils/html-sanitize.js +57 -0
- package/scripts/utils/html-sanitize.js.map +1 -0
- package/scripts/utils/intelligence-analysis.d.ts +173 -0
- package/scripts/utils/intelligence-analysis.d.ts.map +1 -0
- package/scripts/utils/intelligence-analysis.js +936 -0
- package/scripts/utils/intelligence-analysis.js.map +1 -0
- package/scripts/utils/intelligence-index.d.ts +126 -0
- package/scripts/utils/intelligence-index.d.ts.map +1 -0
- package/scripts/utils/intelligence-index.js +731 -0
- package/scripts/utils/intelligence-index.js.map +1 -0
- package/scripts/utils/metadata-utils.d.ts +14 -0
- package/scripts/utils/metadata-utils.d.ts.map +1 -0
- package/scripts/utils/metadata-utils.js +18 -0
- package/scripts/utils/metadata-utils.js.map +1 -0
- package/scripts/utils/news-metadata.d.ts +47 -0
- package/scripts/utils/news-metadata.d.ts.map +1 -0
- package/scripts/utils/news-metadata.js +259 -0
- package/scripts/utils/news-metadata.js.map +1 -0
- package/scripts/utils/validate-articles.d.ts +2 -0
- package/scripts/utils/validate-articles.d.ts.map +1 -0
- package/scripts/utils/validate-articles.js +284 -0
- package/scripts/utils/validate-articles.js.map +1 -0
- package/scripts/utils/validate-ep-api.d.ts +51 -0
- package/scripts/utils/validate-ep-api.d.ts.map +1 -0
- package/scripts/utils/validate-ep-api.js +160 -0
- package/scripts/utils/validate-ep-api.js.map +1 -0
- package/scripts/utils/world-bank-data.d.ts +84 -0
- package/scripts/utils/world-bank-data.d.ts.map +1 -0
- package/scripts/utils/world-bank-data.js +311 -0
- package/scripts/utils/world-bank-data.js.map +1 -0
|
@@ -0,0 +1,790 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2024-2026 Hack23 AB
|
|
2
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
/**
|
|
4
|
+
* @module MCP/MCPConnection
|
|
5
|
+
* @description Base MCP client — JSON-RPC 2.0 transport over stdio or HTTP gateway.
|
|
6
|
+
* Supports two transport modes:
|
|
7
|
+
* - **stdio**: Spawns the EP MCP server binary as a child process (default)
|
|
8
|
+
* - **gateway**: Connects to an MCP Gateway via HTTP (for agentic workflow environments)
|
|
9
|
+
*
|
|
10
|
+
* Gateway mode is activated when `EP_MCP_GATEWAY_URL` env var is set or
|
|
11
|
+
* `gatewayUrl` is provided in options.
|
|
12
|
+
*/
|
|
13
|
+
import { spawn } from 'child_process';
|
|
14
|
+
import { resolve, dirname } from 'path';
|
|
15
|
+
import { fileURLToPath } from 'url';
|
|
16
|
+
/** npm binary name for the European Parliament MCP server */
|
|
17
|
+
const BINARY_NAME = 'european-parliament-mcp-server';
|
|
18
|
+
/** Platform-specific binary filename (Windows uses .cmd shim) */
|
|
19
|
+
const BINARY_FILE = process.platform === 'win32' ? `${BINARY_NAME}.cmd` : BINARY_NAME;
|
|
20
|
+
/** Default binary resolved from node_modules/.bin relative to this file's compiled location */
|
|
21
|
+
const DEFAULT_SERVER_BINARY = resolve(dirname(fileURLToPath(import.meta.url)), `../../node_modules/.bin/${BINARY_FILE}`);
|
|
22
|
+
/** Request timeout in milliseconds — EU Parliament API responses commonly take 30+ seconds */
|
|
23
|
+
const REQUEST_TIMEOUT_MS = 60000;
|
|
24
|
+
/** Connection startup delay in milliseconds */
|
|
25
|
+
const CONNECTION_STARTUP_DELAY_MS = 500;
|
|
26
|
+
/** Maximum reconnect back-off delay in milliseconds */
|
|
27
|
+
const RECONNECT_MAX_DELAY_MS = 30000;
|
|
28
|
+
/** HTTP header for API rate-limit retry delay */
|
|
29
|
+
const RETRY_AFTER_HEADER = 'X-Retry-After';
|
|
30
|
+
/** Log prefix for rate-limit warnings */
|
|
31
|
+
const RATE_LIMIT_MSG = 'Rate limited. Retry after';
|
|
32
|
+
/**
|
|
33
|
+
* Typed error thrown when the MCP gateway returns 401 (session expired).
|
|
34
|
+
* Callers can detect this with `instanceof MCPSessionExpiredError` to trigger re-authentication.
|
|
35
|
+
*/
|
|
36
|
+
export class MCPSessionExpiredError extends Error {
|
|
37
|
+
constructor(statusText) {
|
|
38
|
+
super(`MCP session expired (401): ${statusText}`);
|
|
39
|
+
this.name = 'MCPSessionExpiredError';
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Typed error thrown when the MCP gateway returns 429 (rate limited).
|
|
44
|
+
* Carries the parsed `retryAfterMs` delay so callers can honour the back-off period.
|
|
45
|
+
* `retryAfterMs` is 0 when no Retry-After / X-Retry-After header was present.
|
|
46
|
+
*/
|
|
47
|
+
export class MCPRateLimitError extends Error {
|
|
48
|
+
retryAfterMs;
|
|
49
|
+
constructor(retryAfterMs, message) {
|
|
50
|
+
super(message);
|
|
51
|
+
this.name = 'MCPRateLimitError';
|
|
52
|
+
this.retryAfterMs = retryAfterMs;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Parse a `Retry-After` or `X-Retry-After` header value into milliseconds.
|
|
57
|
+
* Accepts delta-seconds ("30"), numeric-with-suffix ("30s"), or an HTTP-date string.
|
|
58
|
+
* Returns 0 when the value is empty or unparseable.
|
|
59
|
+
*
|
|
60
|
+
* @param retryAfter - Raw Retry-After / X-Retry-After header value
|
|
61
|
+
* @returns Delay in milliseconds, or 0 if the value cannot be parsed
|
|
62
|
+
*/
|
|
63
|
+
function parseRetryAfterMs(retryAfter) {
|
|
64
|
+
const normalized = retryAfter.trim().replace(/s$/i, '');
|
|
65
|
+
if (!normalized)
|
|
66
|
+
return 0;
|
|
67
|
+
const numericDelay = Number(normalized);
|
|
68
|
+
if (!Number.isNaN(numericDelay))
|
|
69
|
+
return numericDelay * 1000;
|
|
70
|
+
const retryDate = new Date(retryAfter);
|
|
71
|
+
if (!Number.isNaN(retryDate.getTime())) {
|
|
72
|
+
return Math.max(0, retryDate.getTime() - Date.now());
|
|
73
|
+
}
|
|
74
|
+
return 0;
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Returns true only for transient, retriable failures: request timeouts,
|
|
78
|
+
* network-level connection-closed/reset errors, and "not connected" states.
|
|
79
|
+
*
|
|
80
|
+
* Uses an allow-list of known transient error patterns so that unknown or
|
|
81
|
+
* server-level errors (e.g., tool runtime failures) are NOT retried:
|
|
82
|
+
* - timeout — AbortSignal timeout or custom timeout message
|
|
83
|
+
* - connection closed / reset / refused — network-level transport failures
|
|
84
|
+
* - not connected — local "not yet connected" guard error
|
|
85
|
+
* - socket hang up — Node.js HTTP socket-level disconnection
|
|
86
|
+
*
|
|
87
|
+
* Everything else (MCPSessionExpiredError, TypeError, rate-limit errors,
|
|
88
|
+
* unknown errors) returns false so `callToolWithRetry` surfaces them immediately.
|
|
89
|
+
*
|
|
90
|
+
* @param error - The caught error to classify
|
|
91
|
+
* @returns `true` if the error is safe to retry
|
|
92
|
+
*/
|
|
93
|
+
export function isRetriableError(error) {
|
|
94
|
+
// Never retry session expiry or programmer errors — these require intervention
|
|
95
|
+
if (error instanceof MCPSessionExpiredError || error instanceof TypeError) {
|
|
96
|
+
return false;
|
|
97
|
+
}
|
|
98
|
+
const msg = error.message?.toLowerCase() ?? '';
|
|
99
|
+
// Never retry rate-limit errors — callers must honour the Retry-After delay.
|
|
100
|
+
// `instanceof MCPRateLimitError` is the primary guard for typed errors;
|
|
101
|
+
// the string prefix fallback handles any legacy plain Error with a rate-limit message.
|
|
102
|
+
if (error instanceof MCPRateLimitError || msg.startsWith(RATE_LIMIT_MSG.toLowerCase())) {
|
|
103
|
+
return false;
|
|
104
|
+
}
|
|
105
|
+
return (msg.includes('timeout') ||
|
|
106
|
+
msg.includes('connection closed') ||
|
|
107
|
+
msg.includes('connection reset') ||
|
|
108
|
+
msg.includes('not connected') ||
|
|
109
|
+
msg.includes('econnreset') ||
|
|
110
|
+
msg.includes('econnrefused') ||
|
|
111
|
+
msg.includes('socket hang up'));
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Parse a `Retry-After` or `X-Retry-After` header value (which may be either a
|
|
115
|
+
* delay-in-seconds number, a numeric string with an optional trailing "s" suffix
|
|
116
|
+
* (e.g. "30s"), or an HTTP-date string) into a human-readable message.
|
|
117
|
+
*
|
|
118
|
+
* @param retryAfter - Raw header value
|
|
119
|
+
* @returns Formatted string describing the delay (e.g. "30s" or "45s (until Thu, 01 Jan 2026 …)")
|
|
120
|
+
*/
|
|
121
|
+
export function formatRetryAfter(retryAfter) {
|
|
122
|
+
// Accept both bare numbers ("30") and numeric-with-suffix ("30s")
|
|
123
|
+
const normalized = retryAfter.trim().replace(/s$/i, '');
|
|
124
|
+
if (!normalized) {
|
|
125
|
+
return retryAfter;
|
|
126
|
+
}
|
|
127
|
+
const numericDelay = Number(normalized);
|
|
128
|
+
if (!Number.isNaN(numericDelay)) {
|
|
129
|
+
return `${numericDelay}s`;
|
|
130
|
+
}
|
|
131
|
+
const retryDate = new Date(retryAfter);
|
|
132
|
+
if (Number.isNaN(retryDate.getTime())) {
|
|
133
|
+
return retryAfter;
|
|
134
|
+
}
|
|
135
|
+
const delayMs = retryDate.getTime() - Date.now();
|
|
136
|
+
if (delayMs > 0) {
|
|
137
|
+
const delaySeconds = Math.ceil(delayMs / 1000);
|
|
138
|
+
return `${delaySeconds}s (until ${retryDate.toUTCString()})`;
|
|
139
|
+
}
|
|
140
|
+
return retryDate.toUTCString();
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Parse an SSE (Server-Sent Events) response body to extract the first valid JSON-RPC message.
|
|
144
|
+
*
|
|
145
|
+
* The MCP Streamable HTTP protocol sends JSON-RPC responses as SSE `data:` lines.
|
|
146
|
+
* This function returns the **first** successfully parsed JSON-RPC message; any
|
|
147
|
+
* subsequent `data:` lines are ignored. This matches the MCP protocol expectation
|
|
148
|
+
* of one JSON-RPC response per HTTP request/response cycle.
|
|
149
|
+
*
|
|
150
|
+
* @param body - Raw SSE response text (may contain multiple lines including `event:` and `data:`)
|
|
151
|
+
* @returns The first valid JSON-RPC response found, or null if no valid message exists
|
|
152
|
+
*/
|
|
153
|
+
export function parseSSEResponse(body) {
|
|
154
|
+
const lines = body.split('\n');
|
|
155
|
+
for (const line of lines) {
|
|
156
|
+
const trimmed = line.trim();
|
|
157
|
+
if (trimmed.startsWith('data:')) {
|
|
158
|
+
const jsonStr = trimmed.slice(5).trim();
|
|
159
|
+
if (jsonStr) {
|
|
160
|
+
try {
|
|
161
|
+
return JSON.parse(jsonStr);
|
|
162
|
+
}
|
|
163
|
+
catch {
|
|
164
|
+
// Continue to next data line
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
return null;
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* Base MCP connection managing JSON-RPC 2.0 transport over stdio or HTTP gateway.
|
|
173
|
+
* Extended by domain-specific clients to add tool wrapper methods.
|
|
174
|
+
*/
|
|
175
|
+
export class MCPConnection {
|
|
176
|
+
serverPath;
|
|
177
|
+
connected;
|
|
178
|
+
process;
|
|
179
|
+
requestId;
|
|
180
|
+
pendingRequests;
|
|
181
|
+
connectionAttempts;
|
|
182
|
+
maxConnectionAttempts;
|
|
183
|
+
connectionRetryDelay;
|
|
184
|
+
maxRetries;
|
|
185
|
+
reconnectingPromise;
|
|
186
|
+
timeoutCount;
|
|
187
|
+
reconnectCount;
|
|
188
|
+
/** Gateway URL for HTTP transport mode */
|
|
189
|
+
gatewayUrl;
|
|
190
|
+
/** API key for gateway authentication */
|
|
191
|
+
gatewayApiKey;
|
|
192
|
+
/** MCP session ID returned by the gateway */
|
|
193
|
+
mcpSessionId;
|
|
194
|
+
/** Human-readable server name for log messages */
|
|
195
|
+
serverLabel;
|
|
196
|
+
constructor(options = {}) {
|
|
197
|
+
this.serverPath =
|
|
198
|
+
options.serverPath ?? process.env['EP_MCP_SERVER_PATH'] ?? DEFAULT_SERVER_BINARY;
|
|
199
|
+
this.connected = false;
|
|
200
|
+
this.process = null;
|
|
201
|
+
this.requestId = 0;
|
|
202
|
+
this.pendingRequests = new Map();
|
|
203
|
+
this.connectionAttempts = 0;
|
|
204
|
+
this.maxConnectionAttempts = Math.max(1, options.maxConnectionAttempts ?? 3);
|
|
205
|
+
this.connectionRetryDelay = options.connectionRetryDelay ?? 1000;
|
|
206
|
+
this.maxRetries = options.maxRetries ?? 2;
|
|
207
|
+
this.reconnectingPromise = null;
|
|
208
|
+
this.timeoutCount = 0;
|
|
209
|
+
this.reconnectCount = 0;
|
|
210
|
+
this.serverLabel = options.serverLabel ?? 'European Parliament MCP Server';
|
|
211
|
+
const rawGatewayUrl = (options.gatewayUrl ?? process.env['EP_MCP_GATEWAY_URL'] ?? '').trim();
|
|
212
|
+
this.gatewayUrl = rawGatewayUrl || null;
|
|
213
|
+
this.gatewayApiKey = options.gatewayApiKey ?? process.env['EP_MCP_GATEWAY_API_KEY'] ?? null;
|
|
214
|
+
this.mcpSessionId = null;
|
|
215
|
+
}
|
|
216
|
+
/**
|
|
217
|
+
* Check if client is connected
|
|
218
|
+
*
|
|
219
|
+
* @returns Connection status
|
|
220
|
+
*/
|
|
221
|
+
isConnected() {
|
|
222
|
+
return this.connected;
|
|
223
|
+
}
|
|
224
|
+
/**
|
|
225
|
+
* Check if using gateway HTTP transport
|
|
226
|
+
*
|
|
227
|
+
* @returns True if gateway mode is active
|
|
228
|
+
*/
|
|
229
|
+
isGatewayMode() {
|
|
230
|
+
return Boolean(this.gatewayUrl);
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* Get the configured gateway URL
|
|
234
|
+
*
|
|
235
|
+
* @returns Gateway URL or null if using stdio transport
|
|
236
|
+
*/
|
|
237
|
+
getGatewayUrl() {
|
|
238
|
+
return this.gatewayUrl;
|
|
239
|
+
}
|
|
240
|
+
/**
|
|
241
|
+
* Get the configured gateway API key
|
|
242
|
+
*
|
|
243
|
+
* @returns Gateway API key or null if not set
|
|
244
|
+
*/
|
|
245
|
+
getGatewayApiKey() {
|
|
246
|
+
return this.gatewayApiKey;
|
|
247
|
+
}
|
|
248
|
+
/**
|
|
249
|
+
* Get the current MCP session ID
|
|
250
|
+
*
|
|
251
|
+
* @returns Session ID returned by the gateway, or null if not yet connected
|
|
252
|
+
*/
|
|
253
|
+
getMcpSessionId() {
|
|
254
|
+
return this.mcpSessionId;
|
|
255
|
+
}
|
|
256
|
+
/**
|
|
257
|
+
* Get connection health metrics for telemetry
|
|
258
|
+
*
|
|
259
|
+
* @returns Object with timeout count, reconnection count, and current connection status
|
|
260
|
+
*/
|
|
261
|
+
getConnectionHealth() {
|
|
262
|
+
return {
|
|
263
|
+
timeoutCount: this.timeoutCount,
|
|
264
|
+
reconnectCount: this.reconnectCount,
|
|
265
|
+
connected: this.connected,
|
|
266
|
+
};
|
|
267
|
+
}
|
|
268
|
+
/**
|
|
269
|
+
* Compute the delay before the next connection attempt.
|
|
270
|
+
* Respects `Retry-After` carried by {@link MCPRateLimitError}; otherwise uses
|
|
271
|
+
* exponential back-off (`connectionRetryDelay * 2^(attempt - 1)`).
|
|
272
|
+
*
|
|
273
|
+
* @param error - The error from the failed attempt
|
|
274
|
+
* @param attempt - Number of attempts made so far (1-indexed)
|
|
275
|
+
* @returns Delay in milliseconds
|
|
276
|
+
*/
|
|
277
|
+
_computeConnectionDelay(error, attempt) {
|
|
278
|
+
if (error instanceof MCPRateLimitError && error.retryAfterMs > 0) {
|
|
279
|
+
return error.retryAfterMs;
|
|
280
|
+
}
|
|
281
|
+
return this.connectionRetryDelay * Math.pow(2, attempt - 1);
|
|
282
|
+
}
|
|
283
|
+
/**
|
|
284
|
+
* Handle a single connection attempt error: re-throw immediately for non-retriable errors
|
|
285
|
+
* (e.g. session expiry), increment the attempt counter, and return the delay to wait
|
|
286
|
+
* before the next attempt. Throws when the maximum attempts have been exhausted.
|
|
287
|
+
*
|
|
288
|
+
* @param error - The error from the failed attempt
|
|
289
|
+
* @returns Delay in milliseconds to wait before the next attempt
|
|
290
|
+
*/
|
|
291
|
+
_handleConnectionAttemptError(error) {
|
|
292
|
+
if (error instanceof MCPSessionExpiredError) {
|
|
293
|
+
throw error;
|
|
294
|
+
}
|
|
295
|
+
this.connectionAttempts++;
|
|
296
|
+
if (this.connectionAttempts >= this.maxConnectionAttempts) {
|
|
297
|
+
console.error('❌ Failed to connect to MCP server after', this.maxConnectionAttempts, 'attempts');
|
|
298
|
+
throw error;
|
|
299
|
+
}
|
|
300
|
+
return this._computeConnectionDelay(error, this.connectionAttempts);
|
|
301
|
+
}
|
|
302
|
+
/**
|
|
303
|
+
* Connect to the MCP server with retry logic
|
|
304
|
+
*/
|
|
305
|
+
async connect() {
|
|
306
|
+
if (this.connected) {
|
|
307
|
+
return;
|
|
308
|
+
}
|
|
309
|
+
if (this.gatewayUrl) {
|
|
310
|
+
console.log(`🔌 Connecting to ${this.serverLabel} via gateway...`);
|
|
311
|
+
console.log(` Gateway URL: ${this.gatewayUrl}`);
|
|
312
|
+
}
|
|
313
|
+
else {
|
|
314
|
+
console.log(`🔌 Connecting to ${this.serverLabel}...`);
|
|
315
|
+
}
|
|
316
|
+
this.connectionAttempts = 0;
|
|
317
|
+
while (this.connectionAttempts < this.maxConnectionAttempts) {
|
|
318
|
+
try {
|
|
319
|
+
if (this.gatewayUrl) {
|
|
320
|
+
await this._attemptGatewayConnection();
|
|
321
|
+
}
|
|
322
|
+
else {
|
|
323
|
+
await this._attemptConnection();
|
|
324
|
+
}
|
|
325
|
+
this.connectionAttempts = 0; // Reset on success
|
|
326
|
+
return;
|
|
327
|
+
}
|
|
328
|
+
catch (error) {
|
|
329
|
+
const delay = this._handleConnectionAttemptError(error);
|
|
330
|
+
console.warn(`⚠️ Connection attempt ${this.connectionAttempts} failed. Retrying in ${delay}ms...`);
|
|
331
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
/**
|
|
336
|
+
* Validate a gateway response body, throwing on JSON-RPC errors.
|
|
337
|
+
*
|
|
338
|
+
* @param contentType - Response content-type header
|
|
339
|
+
* @param body - Raw response body text
|
|
340
|
+
*/
|
|
341
|
+
_validateGatewayResponseBody(contentType, body) {
|
|
342
|
+
if (contentType.includes('text/event-stream')) {
|
|
343
|
+
const parsed = parseSSEResponse(body);
|
|
344
|
+
if (parsed?.error) {
|
|
345
|
+
throw new Error(parsed.error.message ?? 'MCP gateway initialization error');
|
|
346
|
+
}
|
|
347
|
+
return;
|
|
348
|
+
}
|
|
349
|
+
if (!body) {
|
|
350
|
+
return;
|
|
351
|
+
}
|
|
352
|
+
try {
|
|
353
|
+
const jsonResponse = JSON.parse(body);
|
|
354
|
+
if (jsonResponse.error) {
|
|
355
|
+
throw new Error(jsonResponse.error.message ?? 'MCP gateway initialization error');
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
catch (e) {
|
|
359
|
+
// Non-JSON body is acceptable for init — some gateways return empty/plain text
|
|
360
|
+
if (e instanceof Error && e.message.includes('MCP gateway')) {
|
|
361
|
+
throw e;
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
/**
|
|
366
|
+
* Build the Authorization header value for gateway requests.
|
|
367
|
+
* Keys that already contain a valid RFC 7235 scheme token followed by
|
|
368
|
+
* whitespace (e.g. "Bearer …", "Token …", "AWS4-HMAC-SHA256 …") are passed
|
|
369
|
+
* through unchanged. Otherwise the raw key is sent directly unless
|
|
370
|
+
* EP_MCP_GATEWAY_AUTH_SCHEME is set to a valid token, in which case that
|
|
371
|
+
* scheme prefix is prepended. The EP MCP gateway expects raw-token auth by
|
|
372
|
+
* default (no "Bearer " prefix).
|
|
373
|
+
*
|
|
374
|
+
* @param apiKey - Raw or pre-prefixed gateway API key
|
|
375
|
+
* @returns The full Authorization header value, or empty string for empty keys
|
|
376
|
+
* @throws {Error} When the API key contains CR or LF characters (header injection risk)
|
|
377
|
+
*/
|
|
378
|
+
_buildAuthorizationHeader(apiKey) {
|
|
379
|
+
const trimmedKey = apiKey.trim();
|
|
380
|
+
if (!trimmedKey) {
|
|
381
|
+
return '';
|
|
382
|
+
}
|
|
383
|
+
// Reject CR/LF in the key to prevent HTTP header injection.
|
|
384
|
+
if (/[\r\n]/.test(trimmedKey)) {
|
|
385
|
+
throw new Error('Invalid gateway API key: control characters (CR/LF) are not allowed in Authorization header values.');
|
|
386
|
+
}
|
|
387
|
+
// RFC 7235 tchar token pattern for scheme validation.
|
|
388
|
+
// This regex exclusively allows valid tchar characters, which by definition
|
|
389
|
+
// excludes control characters — no separate control-char check is needed
|
|
390
|
+
// for the scheme token itself.
|
|
391
|
+
const tokenRegex = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
|
|
392
|
+
// If the key already starts with a valid RFC 7235 scheme token followed
|
|
393
|
+
// by whitespace, treat it as a fully formed Authorization value and pass
|
|
394
|
+
// it through unchanged.
|
|
395
|
+
const firstSpaceIndex = trimmedKey.indexOf(' ');
|
|
396
|
+
if (firstSpaceIndex > 0) {
|
|
397
|
+
const possibleScheme = trimmedKey.slice(0, firstSpaceIndex);
|
|
398
|
+
if (tokenRegex.test(possibleScheme)) {
|
|
399
|
+
return trimmedKey;
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
const rawScheme = typeof process !== 'undefined' && process.env && process.env['EP_MCP_GATEWAY_AUTH_SCHEME'];
|
|
403
|
+
const scheme = typeof rawScheme === 'string' ? rawScheme.trim() : '';
|
|
404
|
+
if (scheme && tokenRegex.test(scheme)) {
|
|
405
|
+
return `${scheme} ${trimmedKey}`;
|
|
406
|
+
}
|
|
407
|
+
return trimmedKey;
|
|
408
|
+
}
|
|
409
|
+
/**
|
|
410
|
+
* Attempt a single connection via MCP Gateway (HTTP transport)
|
|
411
|
+
*/
|
|
412
|
+
async _attemptGatewayConnection() {
|
|
413
|
+
try {
|
|
414
|
+
const headers = {
|
|
415
|
+
'Content-Type': 'application/json',
|
|
416
|
+
Accept: 'application/json, text/event-stream',
|
|
417
|
+
};
|
|
418
|
+
if (this.gatewayApiKey) {
|
|
419
|
+
headers['Authorization'] = this._buildAuthorizationHeader(this.gatewayApiKey);
|
|
420
|
+
}
|
|
421
|
+
const initRequest = {
|
|
422
|
+
jsonrpc: '2.0',
|
|
423
|
+
id: ++this.requestId,
|
|
424
|
+
method: 'initialize',
|
|
425
|
+
params: {
|
|
426
|
+
protocolVersion: '2024-11-05',
|
|
427
|
+
capabilities: {},
|
|
428
|
+
clientInfo: { name: 'ep-mcp-client', version: '1.0.0' },
|
|
429
|
+
},
|
|
430
|
+
};
|
|
431
|
+
const response = await fetch(this.gatewayUrl, {
|
|
432
|
+
method: 'POST',
|
|
433
|
+
headers,
|
|
434
|
+
body: JSON.stringify(initRequest),
|
|
435
|
+
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
|
436
|
+
});
|
|
437
|
+
if (!response.ok) {
|
|
438
|
+
this._throwGatewayResponseError(response);
|
|
439
|
+
}
|
|
440
|
+
const sessionId = response.headers.get('mcp-session-id');
|
|
441
|
+
if (sessionId) {
|
|
442
|
+
this.mcpSessionId = sessionId;
|
|
443
|
+
}
|
|
444
|
+
// Parse and validate the initialization response body
|
|
445
|
+
const contentType = response.headers.get('content-type') ?? '';
|
|
446
|
+
const body = await response.text();
|
|
447
|
+
this._validateGatewayResponseBody(contentType, body);
|
|
448
|
+
this.connected = true;
|
|
449
|
+
console.log(`✅ Connected to ${this.serverLabel} via gateway`);
|
|
450
|
+
}
|
|
451
|
+
catch (error) {
|
|
452
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
453
|
+
console.error('❌ Failed to connect to MCP gateway:', message);
|
|
454
|
+
throw error;
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
/**
|
|
458
|
+
* Attempt a single connection via stdio (spawns server binary)
|
|
459
|
+
*/
|
|
460
|
+
async _attemptConnection() {
|
|
461
|
+
try {
|
|
462
|
+
const isJavaScriptFile = this.serverPath.toLowerCase().endsWith('.js');
|
|
463
|
+
const command = isJavaScriptFile ? process.execPath : this.serverPath;
|
|
464
|
+
const args = isJavaScriptFile ? [this.serverPath] : [];
|
|
465
|
+
this.process = spawn(command, args, {
|
|
466
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
467
|
+
});
|
|
468
|
+
let buffer = '';
|
|
469
|
+
let startupError = null;
|
|
470
|
+
this.process.stdout?.on('data', (data) => {
|
|
471
|
+
buffer += data.toString();
|
|
472
|
+
const lines = buffer.split('\n');
|
|
473
|
+
buffer = lines.pop() ?? '';
|
|
474
|
+
for (const line of lines) {
|
|
475
|
+
if (line.trim()) {
|
|
476
|
+
this.handleMessage(line);
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
});
|
|
480
|
+
this.process.stderr?.on('data', (data) => {
|
|
481
|
+
const message = data.toString().trim();
|
|
482
|
+
if (message) {
|
|
483
|
+
console.error(`MCP Server: ${message}`);
|
|
484
|
+
}
|
|
485
|
+
});
|
|
486
|
+
this.process.on('close', (code) => {
|
|
487
|
+
console.log(`MCP Server exited with code ${code}`);
|
|
488
|
+
this.connected = false;
|
|
489
|
+
for (const [id, { reject }] of this.pendingRequests.entries()) {
|
|
490
|
+
reject(new Error('MCP server connection closed'));
|
|
491
|
+
this.pendingRequests.delete(id);
|
|
492
|
+
}
|
|
493
|
+
});
|
|
494
|
+
this.process.on('error', (err) => {
|
|
495
|
+
startupError = err;
|
|
496
|
+
this.connected = false;
|
|
497
|
+
});
|
|
498
|
+
await new Promise((resolve) => setTimeout(resolve, CONNECTION_STARTUP_DELAY_MS));
|
|
499
|
+
if (startupError) {
|
|
500
|
+
throw startupError;
|
|
501
|
+
}
|
|
502
|
+
this.connected = true;
|
|
503
|
+
console.log(`✅ Connected to ${this.serverLabel}`);
|
|
504
|
+
}
|
|
505
|
+
catch (error) {
|
|
506
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
507
|
+
console.error('❌ Failed to spawn MCP server:', message);
|
|
508
|
+
throw error;
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
/**
|
|
512
|
+
* Disconnect from the MCP server
|
|
513
|
+
*/
|
|
514
|
+
disconnect() {
|
|
515
|
+
if (this.process) {
|
|
516
|
+
this.process.kill();
|
|
517
|
+
this.process = null;
|
|
518
|
+
}
|
|
519
|
+
this.connected = false;
|
|
520
|
+
this.mcpSessionId = null;
|
|
521
|
+
}
|
|
522
|
+
/**
|
|
523
|
+
* Handle incoming messages from MCP server (stdio mode only)
|
|
524
|
+
*
|
|
525
|
+
* @param line - JSON message line from server
|
|
526
|
+
*/
|
|
527
|
+
handleMessage(line) {
|
|
528
|
+
try {
|
|
529
|
+
const message = JSON.parse(line);
|
|
530
|
+
if (message.id && this.pendingRequests.has(message.id)) {
|
|
531
|
+
const pending = this.pendingRequests.get(message.id);
|
|
532
|
+
this.pendingRequests.delete(message.id);
|
|
533
|
+
if (message.error) {
|
|
534
|
+
pending.reject(new Error(message.error.message ?? 'MCP server error'));
|
|
535
|
+
}
|
|
536
|
+
else {
|
|
537
|
+
pending.resolve(message.result);
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
else if (!message.id && message.method) {
|
|
541
|
+
console.log(`MCP Notification: ${message.method}`);
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
catch (error) {
|
|
545
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
546
|
+
console.error('Error parsing MCP message:', errorMessage);
|
|
547
|
+
console.error('Problematic line:', line);
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
/**
|
|
551
|
+
* Throw an appropriate error for a non-OK gateway response.
|
|
552
|
+
* Extracted to keep `_sendGatewayRequest` within cognitive-complexity limits.
|
|
553
|
+
*
|
|
554
|
+
* @param response - The non-OK fetch Response
|
|
555
|
+
*/
|
|
556
|
+
_throwGatewayResponseError(response) {
|
|
557
|
+
if (response.status === 401) {
|
|
558
|
+
this.mcpSessionId = null;
|
|
559
|
+
this.connected = false;
|
|
560
|
+
throw new MCPSessionExpiredError(response.statusText);
|
|
561
|
+
}
|
|
562
|
+
if (response.status === 429) {
|
|
563
|
+
const rawRetryAfter = response.headers.get(RETRY_AFTER_HEADER) ?? response.headers.get('Retry-After');
|
|
564
|
+
const retryAfter = (rawRetryAfter ?? '').trim();
|
|
565
|
+
if (retryAfter !== '') {
|
|
566
|
+
const retryMessage = formatRetryAfter(retryAfter);
|
|
567
|
+
const retryAfterMs = parseRetryAfterMs(retryAfter);
|
|
568
|
+
console.warn(`⏳ ${RATE_LIMIT_MSG} ${retryMessage}`);
|
|
569
|
+
throw new MCPRateLimitError(retryAfterMs, `${RATE_LIMIT_MSG} ${retryMessage}`);
|
|
570
|
+
}
|
|
571
|
+
const statusText = response.statusText || 'Too Many Requests';
|
|
572
|
+
throw new MCPRateLimitError(0, `${RATE_LIMIT_MSG} (status ${response.status} ${statusText}; ${RETRY_AFTER_HEADER}/Retry-After header missing)`);
|
|
573
|
+
}
|
|
574
|
+
throw new Error(`Gateway error ${response.status}: ${response.statusText}`);
|
|
575
|
+
}
|
|
576
|
+
/**
|
|
577
|
+
* Send a request via MCP Gateway (HTTP transport)
|
|
578
|
+
*
|
|
579
|
+
* @param method - RPC method name
|
|
580
|
+
* @param params - Method parameters
|
|
581
|
+
* @returns Server response
|
|
582
|
+
*/
|
|
583
|
+
async _sendGatewayRequest(method, params = {}) {
|
|
584
|
+
const id = ++this.requestId;
|
|
585
|
+
const request = {
|
|
586
|
+
jsonrpc: '2.0',
|
|
587
|
+
id,
|
|
588
|
+
method,
|
|
589
|
+
params,
|
|
590
|
+
};
|
|
591
|
+
const headers = {
|
|
592
|
+
'Content-Type': 'application/json',
|
|
593
|
+
Accept: 'application/json, text/event-stream',
|
|
594
|
+
};
|
|
595
|
+
if (this.gatewayApiKey) {
|
|
596
|
+
headers['Authorization'] = this._buildAuthorizationHeader(this.gatewayApiKey);
|
|
597
|
+
}
|
|
598
|
+
if (this.mcpSessionId) {
|
|
599
|
+
headers['Mcp-Session-Id'] = this.mcpSessionId;
|
|
600
|
+
}
|
|
601
|
+
const response = await fetch(this.gatewayUrl, {
|
|
602
|
+
method: 'POST',
|
|
603
|
+
headers,
|
|
604
|
+
body: JSON.stringify(request),
|
|
605
|
+
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
|
606
|
+
});
|
|
607
|
+
if (!response.ok) {
|
|
608
|
+
this._throwGatewayResponseError(response);
|
|
609
|
+
}
|
|
610
|
+
const sessionId = response.headers.get('mcp-session-id');
|
|
611
|
+
if (sessionId) {
|
|
612
|
+
this.mcpSessionId = sessionId;
|
|
613
|
+
}
|
|
614
|
+
const contentType = response.headers.get('content-type') ?? '';
|
|
615
|
+
const body = await response.text();
|
|
616
|
+
if (contentType.includes('text/event-stream')) {
|
|
617
|
+
const parsed = parseSSEResponse(body);
|
|
618
|
+
if (!parsed) {
|
|
619
|
+
throw new Error('Failed to parse SSE response from gateway');
|
|
620
|
+
}
|
|
621
|
+
if (parsed.error) {
|
|
622
|
+
throw new Error(parsed.error.message ?? 'MCP gateway error');
|
|
623
|
+
}
|
|
624
|
+
return parsed.result;
|
|
625
|
+
}
|
|
626
|
+
const jsonResponse = JSON.parse(body);
|
|
627
|
+
if (jsonResponse.error) {
|
|
628
|
+
throw new Error(jsonResponse.error.message ?? 'MCP gateway error');
|
|
629
|
+
}
|
|
630
|
+
return jsonResponse.result;
|
|
631
|
+
}
|
|
632
|
+
/**
|
|
633
|
+
* Send a request to the MCP server
|
|
634
|
+
*
|
|
635
|
+
* @param method - RPC method name
|
|
636
|
+
* @param params - Method parameters
|
|
637
|
+
* @returns Server response
|
|
638
|
+
*/
|
|
639
|
+
async sendRequest(method, params = {}) {
|
|
640
|
+
if (!this.connected) {
|
|
641
|
+
throw new Error('Not connected to MCP server');
|
|
642
|
+
}
|
|
643
|
+
if (this.gatewayUrl) {
|
|
644
|
+
return await this._sendGatewayRequest(method, params);
|
|
645
|
+
}
|
|
646
|
+
const id = ++this.requestId;
|
|
647
|
+
const request = {
|
|
648
|
+
jsonrpc: '2.0',
|
|
649
|
+
id,
|
|
650
|
+
method,
|
|
651
|
+
params,
|
|
652
|
+
};
|
|
653
|
+
return await new Promise((resolve, reject) => {
|
|
654
|
+
this.pendingRequests.set(id, { resolve, reject });
|
|
655
|
+
const message = JSON.stringify(request) + '\n';
|
|
656
|
+
this.process?.stdin?.write(message);
|
|
657
|
+
setTimeout(() => {
|
|
658
|
+
if (this.pendingRequests.has(id)) {
|
|
659
|
+
this.pendingRequests.delete(id);
|
|
660
|
+
reject(new Error('Request timeout'));
|
|
661
|
+
}
|
|
662
|
+
}, REQUEST_TIMEOUT_MS);
|
|
663
|
+
});
|
|
664
|
+
}
|
|
665
|
+
/**
|
|
666
|
+
* List available MCP tools
|
|
667
|
+
*
|
|
668
|
+
* @returns List of available tools
|
|
669
|
+
*/
|
|
670
|
+
async listTools() {
|
|
671
|
+
return await this.sendRequest('tools/list');
|
|
672
|
+
}
|
|
673
|
+
/**
|
|
674
|
+
* Call an MCP tool
|
|
675
|
+
*
|
|
676
|
+
* @param name - Tool name
|
|
677
|
+
* @param args - Tool arguments (must be a plain object, non-null, not an array)
|
|
678
|
+
* @returns Tool execution result
|
|
679
|
+
*/
|
|
680
|
+
async callTool(name, args = {}) {
|
|
681
|
+
if (args === null || Array.isArray(args) || typeof args !== 'object') {
|
|
682
|
+
throw new TypeError('MCP tool arguments must be a plain object (non-null object, not an array or function)');
|
|
683
|
+
}
|
|
684
|
+
return (await this.sendRequest('tools/call', { name, arguments: args }));
|
|
685
|
+
}
|
|
686
|
+
/**
|
|
687
|
+
* Attempt to reconnect to the MCP server with exponential back-off.
|
|
688
|
+
* Concurrent callers await the same in-flight reconnect instead of no-oping,
|
|
689
|
+
* ensuring the connection is re-established before all waiting callers continue.
|
|
690
|
+
*
|
|
691
|
+
* @returns Promise that resolves when reconnection succeeds or all attempts are exhausted
|
|
692
|
+
*/
|
|
693
|
+
async reconnect() {
|
|
694
|
+
if (this.reconnectingPromise !== null) {
|
|
695
|
+
return this.reconnectingPromise;
|
|
696
|
+
}
|
|
697
|
+
this.reconnectCount++;
|
|
698
|
+
console.log(`🔄 Reconnecting to ${this.serverLabel} (attempt ${this.reconnectCount})...`);
|
|
699
|
+
this.reconnectingPromise = this._doReconnect();
|
|
700
|
+
try {
|
|
701
|
+
await this.reconnectingPromise;
|
|
702
|
+
}
|
|
703
|
+
finally {
|
|
704
|
+
this.reconnectingPromise = null;
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
/**
|
|
708
|
+
* Internal reconnect helper.
|
|
709
|
+
*
|
|
710
|
+
* Waits for an exponential back-off delay derived from the current
|
|
711
|
+
* `reconnectCount`, then delegates to `connect()` which handles its own
|
|
712
|
+
* retry loop. This avoids composing N×N attempts.
|
|
713
|
+
*
|
|
714
|
+
* @returns Promise that resolves when reconnection succeeds or logs on failure
|
|
715
|
+
*/
|
|
716
|
+
async _doReconnect() {
|
|
717
|
+
// Derive a single outer back-off delay from reconnectCount so successive
|
|
718
|
+
// reconnect bursts are spaced further apart, capped at RECONNECT_MAX_DELAY_MS.
|
|
719
|
+
// Normalize maxConnectionAttempts to ≥1 to avoid a negative upper bound when
|
|
720
|
+
// the user configures 0 attempts (which would give 2^-1 = 0.5 s backoff).
|
|
721
|
+
const normalizedMaxAttempts = Math.max(1, this.maxConnectionAttempts);
|
|
722
|
+
// Clamp to [0, normalizedMaxAttempts - 1]: first floor to ≥0, then ceil to ≤max.
|
|
723
|
+
const attemptIndex = Math.min(Math.max(0, this.reconnectCount - 1), normalizedMaxAttempts - 1);
|
|
724
|
+
const delay = Math.min(this.connectionRetryDelay * Math.pow(2, attemptIndex), RECONNECT_MAX_DELAY_MS);
|
|
725
|
+
await new Promise((r) => setTimeout(r, delay));
|
|
726
|
+
try {
|
|
727
|
+
this.connected = false;
|
|
728
|
+
await this.connect();
|
|
729
|
+
}
|
|
730
|
+
catch (error) {
|
|
731
|
+
console.error(`❌ Reconnection to ${this.serverLabel} failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
/**
|
|
735
|
+
* Log a retry warning and, if disconnected, attempt to reconnect before waiting.
|
|
736
|
+
*
|
|
737
|
+
* @param lastError - The error from the failed attempt
|
|
738
|
+
* @param attempt - Zero-based current attempt index
|
|
739
|
+
* @param retries - Total retry count
|
|
740
|
+
* @returns Promise that resolves after logging, optional reconnect, and inter-retry delay
|
|
741
|
+
*/
|
|
742
|
+
async _handleRetryAttempt(lastError, attempt, retries) {
|
|
743
|
+
if (lastError.message.toLowerCase().includes('timeout')) {
|
|
744
|
+
this.timeoutCount++;
|
|
745
|
+
console.warn(`⏱️ Request timeout (total: ${this.timeoutCount}), retrying ${attempt + 1}/${retries}...`);
|
|
746
|
+
}
|
|
747
|
+
else {
|
|
748
|
+
console.warn(`⚠️ Request failed, retrying ${attempt + 1}/${retries}: ${lastError.message}`);
|
|
749
|
+
}
|
|
750
|
+
if (!this.connected) {
|
|
751
|
+
await this.reconnect();
|
|
752
|
+
}
|
|
753
|
+
await new Promise((r) => setTimeout(r, this.connectionRetryDelay * (attempt + 1)));
|
|
754
|
+
}
|
|
755
|
+
/**
|
|
756
|
+
* Call an MCP tool with automatic retry on timeout or connection loss.
|
|
757
|
+
* Reconnects automatically if the connection was lost between attempts.
|
|
758
|
+
*
|
|
759
|
+
* Only transient failures are retried (see `isRetriableError`). Non-retriable
|
|
760
|
+
* errors — rate-limit (429), session-expired (401), and programmer errors such
|
|
761
|
+
* as `TypeError` — are re-thrown immediately without consuming any retry budget.
|
|
762
|
+
*
|
|
763
|
+
* @param name - Tool name
|
|
764
|
+
* @param args - Tool arguments (plain object, non-null, not an array)
|
|
765
|
+
* @param maxRetries - Override the default retry count from options
|
|
766
|
+
* @returns Tool execution result
|
|
767
|
+
*/
|
|
768
|
+
async callToolWithRetry(name, args = {}, maxRetries) {
|
|
769
|
+
const retries = maxRetries ?? this.maxRetries;
|
|
770
|
+
if (retries < 0) {
|
|
771
|
+
throw new RangeError(`maxRetries must be >= 0, received ${retries}`);
|
|
772
|
+
}
|
|
773
|
+
let lastError = new Error(`Failed to call tool '${name}' after ${retries} retries`);
|
|
774
|
+
for (let attempt = 0; attempt <= retries; attempt++) {
|
|
775
|
+
try {
|
|
776
|
+
return await this.callTool(name, args);
|
|
777
|
+
}
|
|
778
|
+
catch (error) {
|
|
779
|
+
lastError = error instanceof Error ? error : new Error(String(error));
|
|
780
|
+
if (!isRetriableError(lastError))
|
|
781
|
+
throw lastError;
|
|
782
|
+
if (attempt === retries)
|
|
783
|
+
break;
|
|
784
|
+
await this._handleRetryAttempt(lastError, attempt, retries);
|
|
785
|
+
}
|
|
786
|
+
}
|
|
787
|
+
throw lastError;
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
//# sourceMappingURL=mcp-connection.js.map
|