@jadchene/mcp-gateway-service 0.1.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.
@@ -0,0 +1,193 @@
1
+ import { EventEmitter } from "node:events";
2
+ /**
3
+ * Provides a framed MCP stdio message reader compatible with both line-delimited and Content-Length transports.
4
+ */
5
+ export class McpMessageReader extends EventEmitter {
6
+ /**
7
+ * Stores raw bytes that have not yet formed a complete frame.
8
+ */
9
+ buffer = Buffer.alloc(0);
10
+ /**
11
+ * Stores the configured framing preference.
12
+ */
13
+ preferredMode;
14
+ /**
15
+ * Stores the framing mode detected from the incoming stream.
16
+ */
17
+ detectedMode = null;
18
+ /**
19
+ * Starts reading from the provided stream immediately.
20
+ */
21
+ constructor(stream, preferredMode = "auto") {
22
+ super();
23
+ this.preferredMode = preferredMode;
24
+ stream.on("data", (chunk) => {
25
+ const next = typeof chunk === "string" ? Buffer.from(chunk, "utf8") : chunk;
26
+ this.buffer = Buffer.concat([this.buffer, next]);
27
+ this.consumeFrames();
28
+ });
29
+ stream.on("error", (error) => this.emit("error", error));
30
+ stream.on("close", () => this.emit("close"));
31
+ }
32
+ /**
33
+ * Returns the currently selected framing mode when known.
34
+ */
35
+ get framingMode() {
36
+ return this.preferredMode === "auto" ? this.detectedMode : this.preferredMode;
37
+ }
38
+ /**
39
+ * Attempts to parse as many complete frames as possible from the current buffer.
40
+ */
41
+ consumeFrames() {
42
+ while (true) {
43
+ const framingMode = this.resolveFramingMode();
44
+ if (!framingMode) {
45
+ return;
46
+ }
47
+ try {
48
+ const payload = framingMode === "content-length"
49
+ ? this.readContentLengthPayload()
50
+ : this.readLinePayload();
51
+ if (payload === null) {
52
+ return;
53
+ }
54
+ const message = JSON.parse(payload);
55
+ this.emit("message", message);
56
+ }
57
+ catch (error) {
58
+ this.emit("error", error);
59
+ }
60
+ }
61
+ }
62
+ /**
63
+ * Resolves the framing mode using the configured preference or buffered bytes.
64
+ */
65
+ resolveFramingMode() {
66
+ if (this.preferredMode !== "auto") {
67
+ return this.preferredMode;
68
+ }
69
+ if (this.detectedMode) {
70
+ return this.detectedMode;
71
+ }
72
+ const sample = this.buffer.toString("utf8");
73
+ const trimmed = sample.trimStart();
74
+ if (trimmed.startsWith("Content-Length:")) {
75
+ this.detectedMode = "content-length";
76
+ return this.detectedMode;
77
+ }
78
+ if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
79
+ this.detectedMode = "line";
80
+ return this.detectedMode;
81
+ }
82
+ return null;
83
+ }
84
+ /**
85
+ * Reads one Content-Length framed payload when available.
86
+ */
87
+ readContentLengthPayload() {
88
+ const headerEnd = this.buffer.indexOf("\r\n\r\n");
89
+ if (headerEnd < 0) {
90
+ return null;
91
+ }
92
+ const headerText = this.buffer.subarray(0, headerEnd).toString("utf8");
93
+ const lengthMatch = /Content-Length:\s*(\d+)/i.exec(headerText);
94
+ if (!lengthMatch) {
95
+ throw new Error("Missing Content-Length header.");
96
+ }
97
+ const contentLength = Number(lengthMatch[1]);
98
+ const frameStart = headerEnd + 4;
99
+ const frameEnd = frameStart + contentLength;
100
+ if (this.buffer.length < frameEnd) {
101
+ return null;
102
+ }
103
+ const payload = this.buffer.subarray(frameStart, frameEnd).toString("utf8");
104
+ this.buffer = this.buffer.subarray(frameEnd);
105
+ return payload;
106
+ }
107
+ /**
108
+ * Reads one newline-delimited JSON payload when available.
109
+ */
110
+ readLinePayload() {
111
+ const lineEnd = this.buffer.indexOf("\n");
112
+ if (lineEnd < 0) {
113
+ return null;
114
+ }
115
+ const payload = this.buffer.toString("utf8", 0, lineEnd).replace(/\r$/, "");
116
+ this.buffer = this.buffer.subarray(lineEnd + 1);
117
+ return payload;
118
+ }
119
+ }
120
+ /**
121
+ * Provides a framed MCP stdio message writer compatible with line-delimited and Content-Length transports.
122
+ */
123
+ export class McpMessageWriter {
124
+ /**
125
+ * Stores the target writable stream.
126
+ */
127
+ stream;
128
+ /**
129
+ * Stores the active framing mode used for outbound messages.
130
+ */
131
+ mode;
132
+ /**
133
+ * Creates a writer bound to one writable stream.
134
+ */
135
+ constructor(stream, mode = "line") {
136
+ this.stream = stream;
137
+ this.mode = mode;
138
+ }
139
+ /**
140
+ * Updates the framing mode used for future outbound messages.
141
+ */
142
+ setFramingMode(mode) {
143
+ this.mode = mode;
144
+ }
145
+ /**
146
+ * Writes one framed JSON-RPC message to the target stream.
147
+ */
148
+ write(message) {
149
+ const payload = Buffer.from(JSON.stringify(message), "utf8");
150
+ if (this.mode === "content-length") {
151
+ const header = Buffer.from(`Content-Length: ${payload.length}\r\n\r\n`, "utf8");
152
+ this.stream.write(Buffer.concat([header, payload]));
153
+ return;
154
+ }
155
+ this.stream.write(Buffer.concat([payload, Buffer.from("\n", "utf8")]));
156
+ }
157
+ }
158
+ /**
159
+ * Creates a typed message reader.
160
+ */
161
+ export function createMessageReader(stream, preferredMode = "auto") {
162
+ return new McpMessageReader(stream, preferredMode);
163
+ }
164
+ /**
165
+ * Creates a typed message writer.
166
+ */
167
+ export function createMessageWriter(stream, mode = "line") {
168
+ return new McpMessageWriter(stream, mode);
169
+ }
170
+ /**
171
+ * Builds one JSON-RPC success response.
172
+ */
173
+ export function jsonRpcResult(id, result) {
174
+ return {
175
+ jsonrpc: "2.0",
176
+ id,
177
+ result
178
+ };
179
+ }
180
+ /**
181
+ * Builds one JSON-RPC error response.
182
+ */
183
+ export function jsonRpcError(id, code, message, data) {
184
+ return {
185
+ jsonrpc: "2.0",
186
+ id,
187
+ error: {
188
+ code,
189
+ message,
190
+ data
191
+ }
192
+ };
193
+ }
@@ -0,0 +1,250 @@
1
+ import { resolve } from "node:path";
2
+ import { StdioMcpClient } from "./mcp/client.js";
3
+ /**
4
+ * Maintains the active service pool, client instances, and cached metadata.
5
+ */
6
+ export class ServiceRegistry {
7
+ /**
8
+ * Stores the config file path currently managed by the registry.
9
+ */
10
+ configPath;
11
+ /**
12
+ * Stores the loader used to parse and validate config files.
13
+ */
14
+ configLoader;
15
+ /**
16
+ * Stores the shared logger instance.
17
+ */
18
+ logger;
19
+ /**
20
+ * Stores the last valid config snapshot.
21
+ */
22
+ currentConfig = { services: [] };
23
+ /**
24
+ * Stores the current immutable runtime view used by request handlers.
25
+ */
26
+ snapshots = new Map();
27
+ /**
28
+ * Stores reusable downstream clients keyed by service identifier.
29
+ */
30
+ clients = new Map();
31
+ /**
32
+ * Prevents overlapping config reload operations.
33
+ */
34
+ reloadPromise = Promise.resolve();
35
+ /**
36
+ * Creates a registry bound to one config file path.
37
+ */
38
+ constructor(configPath, configLoader, logger) {
39
+ this.configPath = configPath;
40
+ this.configLoader = configLoader;
41
+ this.logger = logger;
42
+ }
43
+ /**
44
+ * Loads the initial config snapshot.
45
+ */
46
+ async initialize() {
47
+ await this.reload();
48
+ }
49
+ /**
50
+ * Reloads the config file and atomically swaps the runtime snapshot on success.
51
+ */
52
+ async reload() {
53
+ this.reloadPromise = this.reloadPromise.catch(() => undefined).then(async () => {
54
+ const absolutePath = resolve(this.configPath);
55
+ this.logger.info("config.reload.started", { configPath: absolutePath });
56
+ const nextConfig = await this.configLoader.load(absolutePath);
57
+ const nextSnapshots = new Map();
58
+ const nextClients = new Map();
59
+ try {
60
+ for (const service of nextConfig.services) {
61
+ const snapshot = await this.buildServiceSnapshot(service, nextClients);
62
+ nextSnapshots.set(service.serviceId, snapshot);
63
+ }
64
+ }
65
+ catch (error) {
66
+ this.logger.error("config.reload.failed", {
67
+ configPath: absolutePath,
68
+ message: error instanceof Error ? error.message : String(error)
69
+ });
70
+ await disposeClientMap(nextClients);
71
+ throw error;
72
+ }
73
+ await disposeRemovedClients(this.clients, nextClients);
74
+ this.currentConfig = nextConfig;
75
+ this.snapshots = nextSnapshots;
76
+ this.clients = nextClients;
77
+ this.logger.info("config.reload.succeeded", {
78
+ configPath: absolutePath,
79
+ serviceCount: nextConfig.services.length
80
+ });
81
+ });
82
+ try {
83
+ await this.reloadPromise;
84
+ }
85
+ catch {
86
+ /**
87
+ * Keeps the last valid snapshot active while surfacing the error through logs.
88
+ */
89
+ }
90
+ }
91
+ /**
92
+ * Returns a sorted list of runtime service snapshots.
93
+ */
94
+ listServices() {
95
+ return [...this.snapshots.values()].sort((left, right) => left.config.serviceId.localeCompare(right.config.serviceId));
96
+ }
97
+ /**
98
+ * Returns one runtime snapshot by service identifier.
99
+ */
100
+ getService(serviceId) {
101
+ return this.snapshots.get(serviceId) ?? null;
102
+ }
103
+ /**
104
+ * Lists tools for one logical service.
105
+ */
106
+ listTools(serviceId) {
107
+ return this.requireService(serviceId).metadata.tools;
108
+ }
109
+ /**
110
+ * Returns one tool definition for a service.
111
+ */
112
+ getTool(serviceId, toolName) {
113
+ return this.requireService(serviceId).metadata.tools.find((tool) => tool.name === toolName) ?? null;
114
+ }
115
+ /**
116
+ * Calls one downstream tool using the only configured service process.
117
+ */
118
+ async callTool(serviceId, toolName, args) {
119
+ const snapshot = this.requireService(serviceId);
120
+ const client = this.clients.get(serviceId);
121
+ if (!client) {
122
+ throw new Error(`Service '${serviceId}' is unavailable.`);
123
+ }
124
+ const startedAt = Date.now();
125
+ try {
126
+ const result = await client.callTool(toolName, args);
127
+ this.markServiceAvailable(serviceId, client.restartCount);
128
+ return {
129
+ result,
130
+ durationMs: Date.now() - startedAt,
131
+ restartAttempts: client.restartCount
132
+ };
133
+ }
134
+ catch (error) {
135
+ const message = error instanceof Error ? error.message : String(error);
136
+ this.markServiceUnavailable(serviceId, message, client.restartCount);
137
+ if (client.isUnavailable) {
138
+ throw new Error(`Service '${serviceId}' is unavailable. ${client.unavailableMessage ?? message}`);
139
+ }
140
+ throw error;
141
+ }
142
+ }
143
+ /**
144
+ * Disposes all downstream clients during shutdown.
145
+ */
146
+ async dispose() {
147
+ await disposeClientMap(this.clients);
148
+ this.clients.clear();
149
+ }
150
+ /**
151
+ * Builds one runtime snapshot and initializes required metadata.
152
+ */
153
+ async buildServiceSnapshot(service, nextClients) {
154
+ const reusedClient = this.clients.get(service.serviceId);
155
+ const client = reusedClient && reusedClient.matchesConfig(service)
156
+ ? reusedClient
157
+ : new StdioMcpClient(service, this.logger);
158
+ nextClients.set(service.serviceId, client);
159
+ let metadata = {
160
+ protocolVersion: null,
161
+ serverInfo: null,
162
+ tools: [],
163
+ refreshedAt: null
164
+ };
165
+ let available = false;
166
+ let lastError = null;
167
+ let lastConnectedAt = null;
168
+ try {
169
+ metadata = await client.getMetadata();
170
+ available = true;
171
+ lastConnectedAt = new Date().toISOString();
172
+ }
173
+ catch (error) {
174
+ lastError = error instanceof Error ? error.message : String(error);
175
+ this.logger.warn("service.metadata.refresh_failed", {
176
+ serviceId: service.serviceId,
177
+ message: lastError
178
+ });
179
+ }
180
+ return {
181
+ config: service,
182
+ metadata,
183
+ runtime: {
184
+ available,
185
+ lastError,
186
+ lastConnectedAt,
187
+ restartAttempts: client.restartCount
188
+ }
189
+ };
190
+ }
191
+ /**
192
+ * Returns one existing service snapshot or throws a descriptive error.
193
+ */
194
+ requireService(serviceId) {
195
+ const snapshot = this.snapshots.get(serviceId);
196
+ if (!snapshot) {
197
+ throw new Error(`Unknown service '${serviceId}'.`);
198
+ }
199
+ return snapshot;
200
+ }
201
+ /**
202
+ * Marks one service as available after a successful request.
203
+ */
204
+ markServiceAvailable(serviceId, restartAttempts) {
205
+ const snapshot = this.snapshots.get(serviceId);
206
+ if (!snapshot) {
207
+ return;
208
+ }
209
+ snapshot.runtime = {
210
+ available: true,
211
+ lastError: null,
212
+ lastConnectedAt: new Date().toISOString(),
213
+ restartAttempts
214
+ };
215
+ }
216
+ /**
217
+ * Marks one service as unavailable after a failed request.
218
+ */
219
+ markServiceUnavailable(serviceId, message, restartAttempts) {
220
+ const snapshot = this.snapshots.get(serviceId);
221
+ if (!snapshot) {
222
+ return;
223
+ }
224
+ snapshot.runtime = {
225
+ available: false,
226
+ lastError: message,
227
+ lastConnectedAt: snapshot.runtime.lastConnectedAt,
228
+ restartAttempts
229
+ };
230
+ }
231
+ }
232
+ /**
233
+ * Disposes all clients in one map.
234
+ */
235
+ async function disposeClientMap(clientMap) {
236
+ await Promise.all([...clientMap.values()].map((client) => client.dispose().catch(() => undefined)));
237
+ }
238
+ /**
239
+ * Disposes clients that no longer exist after a config swap.
240
+ */
241
+ async function disposeRemovedClients(previous, next) {
242
+ const removed = [];
243
+ for (const [key, client] of previous.entries()) {
244
+ const nextClient = next.get(key);
245
+ if (!nextClient || nextClient !== client) {
246
+ removed.push(client);
247
+ }
248
+ }
249
+ await Promise.all(removed.map((client) => client.dispose().catch(() => undefined)));
250
+ }
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,8 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { dirname, resolve } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ const __dirname = dirname(fileURLToPath(import.meta.url));
5
+ const packageJsonPath = resolve(__dirname, "../package.json");
6
+ const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf8"));
7
+ export const NAME = packageJson.name ?? "mcp-gateway-service";
8
+ export const VERSION = packageJson.version ?? "0.0.0";
package/package.json ADDED
@@ -0,0 +1,44 @@
1
+ {
2
+ "name": "@jadchene/mcp-gateway-service",
3
+ "version": "0.1.0",
4
+ "description": "A token-efficient MCP gateway that provides one unified entry point for multiple downstream MCP services.",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "bin": {
8
+ "mcp-gateway-service": "dist/index.js"
9
+ },
10
+ "license": "MIT",
11
+ "author": "jadchene",
12
+ "scripts": {
13
+ "build": "tsc -p tsconfig.build.json",
14
+ "dev": "node --experimental-strip-types src/index.ts",
15
+ "start": "node dist/index.js",
16
+ "test": "node --test --experimental-strip-types test/**/*.test.ts",
17
+ "version": "node dist/index.js --version",
18
+ "prepare": "npm run build",
19
+ "prepublishOnly": "npm run build"
20
+ },
21
+ "files": [
22
+ "dist",
23
+ "skills",
24
+ "config.example.json",
25
+ "README.md",
26
+ "README_zh.md",
27
+ "LICENSE",
28
+ "scripts"
29
+ ],
30
+ "keywords": [
31
+ "mcp",
32
+ "gateway",
33
+ "model context protocol",
34
+ "agent",
35
+ "token-efficient"
36
+ ],
37
+ "engines": {
38
+ "node": ">=24.0.0"
39
+ },
40
+ "devDependencies": {
41
+ "@types/node": "^24.0.0",
42
+ "typescript": "^5.8.0"
43
+ }
44
+ }
@@ -0,0 +1,111 @@
1
+ [CmdletBinding(SupportsShouldProcess = $true)]
2
+ param(
3
+ [string]$ProjectRoot = (Split-Path -Parent $PSScriptRoot),
4
+ [string]$ExampleConfigPath = "",
5
+ [switch]$KeepTarball
6
+ )
7
+
8
+ $ErrorActionPreference = "Stop"
9
+
10
+ function Invoke-Step {
11
+ param(
12
+ [string]$FilePath,
13
+ [string[]]$Arguments,
14
+ [string]$Description
15
+ )
16
+
17
+ $argumentText = if ($Arguments.Count -gt 0) { $Arguments -join " " } else { "" }
18
+ $target = if ($argumentText) { "$FilePath $argumentText" } else { $FilePath }
19
+
20
+ if ($PSCmdlet.ShouldProcess($target, $Description)) {
21
+ & $FilePath @Arguments
22
+ if ($LASTEXITCODE -ne 0) {
23
+ throw "Command failed with exit code ${LASTEXITCODE}: $target"
24
+ }
25
+ }
26
+ }
27
+
28
+ function Invoke-CaptureStep {
29
+ param(
30
+ [string]$FilePath,
31
+ [string[]]$Arguments,
32
+ [string]$Description
33
+ )
34
+
35
+ $argumentText = if ($Arguments.Count -gt 0) { $Arguments -join " " } else { "" }
36
+ $target = if ($argumentText) { "$FilePath $argumentText" } else { $FilePath }
37
+
38
+ if ($PSCmdlet.ShouldProcess($target, $Description)) {
39
+ $output = & $FilePath @Arguments
40
+ if ($LASTEXITCODE -ne 0) {
41
+ throw "Command failed with exit code ${LASTEXITCODE}: $target"
42
+ }
43
+
44
+ return $output
45
+ }
46
+
47
+ return @()
48
+ }
49
+
50
+ $resolvedProjectRoot = (Resolve-Path $ProjectRoot).Path
51
+ $packageJsonPath = Join-Path $resolvedProjectRoot "package.json"
52
+ $defaultConfigPath = Join-Path $resolvedProjectRoot "config.example.json"
53
+ $resolvedConfigPath = if ($ExampleConfigPath) { $ExampleConfigPath } else { $defaultConfigPath }
54
+ $packageName = "mcp-gateway-service"
55
+
56
+ if (-not (Test-Path $packageJsonPath)) {
57
+ throw "package.json not found under project root: $resolvedProjectRoot"
58
+ }
59
+
60
+ $packageInfo = Get-Content -Raw $packageJsonPath | ConvertFrom-Json
61
+
62
+ Push-Location $resolvedProjectRoot
63
+ try {
64
+ Invoke-Step -FilePath "npm" -Arguments @("install") -Description "Install project dependencies"
65
+ Invoke-Step -FilePath "npm" -Arguments @("run", "build") -Description "Build the MCP gateway"
66
+ $packOutput = Invoke-CaptureStep -FilePath "npm" -Arguments @("pack", "--json") -Description "Create a package tarball for global installation"
67
+ if ($packOutput.Count -gt 0) {
68
+ $packInfo = ($packOutput -join "`n" | ConvertFrom-Json)[0]
69
+ $tarballPath = Join-Path $resolvedProjectRoot $packInfo.filename
70
+ } else {
71
+ $tarballPath = Join-Path $resolvedProjectRoot "$($packageInfo.name)-$($packageInfo.version).tgz"
72
+ }
73
+
74
+ try {
75
+ Invoke-Step -FilePath "npm" -Arguments @("uninstall", "-g", $packageName) -Description "Remove any previous global installation of mcp-gateway-service"
76
+ }
77
+ catch {
78
+ Write-Host "Previous global installation was not removed cleanly. Continuing with fresh install."
79
+ }
80
+
81
+ Invoke-Step -FilePath "npm" -Arguments @("install", "-g", $tarballPath) -Description "Install the packaged mcp-gateway-service tarball globally"
82
+
83
+ if (-not $KeepTarball -and (Test-Path $tarballPath)) {
84
+ Remove-Item $tarballPath -Force
85
+ }
86
+ }
87
+ finally {
88
+ Pop-Location
89
+ }
90
+
91
+ Write-Host ""
92
+ Write-Host "Global installation completed."
93
+ Write-Host "Command: mcp-gateway-service"
94
+ Write-Host "Example start command:"
95
+ Write-Host " mcp-gateway-service"
96
+ Write-Host ""
97
+ Write-Host "Example MCP server configuration:"
98
+
99
+ $example = @{
100
+ mcpServers = @{
101
+ gateway = @{
102
+ command = "mcp-gateway-service"
103
+ args = @()
104
+ env = @{
105
+ MCP_GATEWAY_CONFIG = $resolvedConfigPath
106
+ }
107
+ }
108
+ }
109
+ } | ConvertTo-Json -Depth 6
110
+
111
+ Write-Host $example