@jadchene/mcp-gateway-service 0.7.0 → 0.8.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.
package/README.md CHANGED
@@ -116,6 +116,8 @@ Stdio remains available when `--http` is enabled.
116
116
  {
117
117
  "serviceId": "local-tools",
118
118
  "name": "Local Tools",
119
+ "confirmationRequiredTools": ["delete_*", "deploy_?"],
120
+ "disabledTools": ["internal_*", "legacy_tool"],
119
121
  "transport": {
120
122
  "type": "stdio",
121
123
  "command": "your-mcp-service",
@@ -142,6 +144,8 @@ Stdio remains available when `--http` is enabled.
142
144
  | `description` | Optional service description. |
143
145
  | `enable` | Optional; defaults to `true`. |
144
146
  | `callTimeoutMs` | Optional downstream tool-call timeout; defaults to 120 seconds. |
147
+ | `confirmationRequiredTools` | Optional unique array of case-sensitive full-name glob patterns. `*` matches zero or more characters and `?` matches one character. The gateway asks the upstream user for form elicitation confirmation before calling a matching tool. |
148
+ | `disabledTools` | Optional unique array using the same glob syntax. Matching tools are hidden from tool listing and schema lookup, and calls are rejected before reaching the downstream service. |
145
149
  | `transport.type` | `stdio` or `http`. |
146
150
  | `transport.command` | Required command for a stdio service. |
147
151
  | `transport.args` | Optional command arguments for a stdio service. |
@@ -170,7 +174,9 @@ The config file is watched for changes. Invalid updates are rejected and the las
170
174
 
171
175
  The usual flow is `gateway_list_services` → `gateway_list_tools` → `gateway_get_tool_schema` when needed → `gateway_call_tool`. Pass `{}` to `gateway_call_tool` when the downstream tool has no arguments.
172
176
 
173
- Calls keep the downstream tool's original side effects and confirmation rules. An uncertain `gateway_call_tool` failure is never replayed automatically. Enabling or disabling a service with `gateway_manage_service` atomically updates the config file.
177
+ Calls keep the downstream tool's original side effects and confirmation rules. Tools matching `confirmationRequiredTools` are never invoked until the current MCP session reviews the exact service, tool, and arguments and answers `yes` to the form elicitation; sessions without form elicitation support receive an error. A `no`, decline, or cancel returns an explicit rejection without invoking the downstream tool. An uncertain `gateway_call_tool` failure is never replayed automatically. Enabling or disabling a service with `gateway_manage_service` atomically updates the config file.
178
+
179
+ `disabledTools` takes precedence over `confirmationRequiredTools` when both match. A disabled tool is hidden and rejected immediately without asking for confirmation.
174
180
 
175
181
  Agents with Skills support can use the included [MCP Gateway Skill](./skills/mcp-gateway/SKILL.md) for the discovery and calling workflow.
176
182
 
package/README_zh.md CHANGED
@@ -116,6 +116,8 @@ claude mcp add --transport http gateway http://127.0.0.1:3000/mcp
116
116
  {
117
117
  "serviceId": "local-tools",
118
118
  "name": "Local Tools",
119
+ "confirmationRequiredTools": ["delete_*", "deploy_?"],
120
+ "disabledTools": ["internal_*", "legacy_tool"],
119
121
  "transport": {
120
122
  "type": "stdio",
121
123
  "command": "your-mcp-service",
@@ -142,6 +144,8 @@ claude mcp add --transport http gateway http://127.0.0.1:3000/mcp
142
144
  | `description` | 可选,服务说明。 |
143
145
  | `enable` | 可选,默认为 `true`。 |
144
146
  | `callTimeoutMs` | 可选,下游工具调用超时;默认 120 秒。 |
147
+ | `confirmationRequiredTools` | 可选,填写区分大小写的完整工具名 glob 模式;`*` 匹配零个或多个字符,`?` 匹配一个字符。数组项必须唯一且非空,网关在调用匹配的工具前会向上游用户发起表单 elicitation。 |
148
+ | `disabledTools` | 可选,使用相同 glob 语法。匹配的工具不会出现在工具列表和 schema 查询中,调用也会在到达下游服务前被拒绝。 |
145
149
  | `transport.type` | `stdio` 或 `http`。 |
146
150
  | `transport.command` | stdio 服务必填,启动命令。 |
147
151
  | `transport.args` | stdio 服务的可选命令参数。 |
@@ -170,7 +174,9 @@ claude mcp add --transport http gateway http://127.0.0.1:3000/mcp
170
174
 
171
175
  通常按 `gateway_list_services` → `gateway_list_tools` → 按需调用 `gateway_get_tool_schema` → `gateway_call_tool` 的顺序使用。下游工具没有参数时,`gateway_call_tool` 的 `arguments` 传 `{}`。
172
176
 
173
- 工具调用会保留下游工具原有的副作用和确认规则。状态不确定的 `gateway_call_tool` 失败不会自动重放。通过 `gateway_manage_service` 启用或禁用服务会原子更新配置文件。
177
+ 工具调用会保留下游工具原有的副作用和确认规则。匹配 `confirmationRequiredTools` 模式的工具会展示实际服务、工具和完整参数,只有当前 MCP 会话在表单 elicitation 中选择 `yes` 后才会调用;会话不支持表单 elicitation,或用户选择 `no`、拒绝、取消时,网关会返回明确的拒绝结果且不会调用下游工具。状态不确定的 `gateway_call_tool` 失败不会自动重放。通过 `gateway_manage_service` 启用或禁用服务会原子更新配置文件。
178
+
179
+ 当一个工具同时匹配 `disabledTools` 和 `confirmationRequiredTools` 时,`disabledTools` 优先:工具会被隐藏并直接拒绝,不会发起确认。
174
180
 
175
181
  支持 Skills 的 Agent 可以使用仓库内置的 [MCP Gateway Skill](./skills/mcp-gateway/SKILL.md) 完成工具发现和调用。
176
182
 
@@ -11,6 +11,12 @@
11
11
  "name": "Demo Echo Service",
12
12
  "description": "Sample echo MCP service.",
13
13
  "callTimeoutMs": 120000,
14
+ "confirmationRequiredTools": [
15
+ "echo*"
16
+ ],
17
+ "disabledTools": [
18
+ "echo_debug*"
19
+ ],
14
20
  "transport": {
15
21
  "type": "stdio",
16
22
  "command": "node",
package/dist/config.js CHANGED
@@ -88,13 +88,17 @@ function validateServiceConfig(input) {
88
88
  const name = requireNonEmptyString(input.name, `service '${serviceId}' name`);
89
89
  const description = optionalString(input.description, `service '${serviceId}' description`);
90
90
  const callTimeoutMs = optionalInteger(input.callTimeoutMs, `service '${serviceId}' callTimeoutMs`, 1, 24 * 60 * 60 * 1000);
91
+ const confirmationRequiredTools = optionalUniqueStringArray(input.confirmationRequiredTools, `service '${serviceId}' confirmationRequiredTools`);
92
+ const disabledTools = optionalUniqueStringArray(input.disabledTools, `service '${serviceId}' disabledTools`);
91
93
  return {
92
94
  serviceId,
93
95
  enable,
94
96
  name,
95
97
  description,
96
98
  transport: validateTransportConfig(serviceId, input.transport),
97
- ...(callTimeoutMs === undefined ? {} : { callTimeoutMs })
99
+ ...(callTimeoutMs === undefined ? {} : { callTimeoutMs }),
100
+ ...(confirmationRequiredTools === undefined ? {} : { confirmationRequiredTools }),
101
+ ...(disabledTools === undefined ? {} : { disabledTools })
98
102
  };
99
103
  }
100
104
  /**
@@ -1,3 +1,5 @@
1
+ import { ToolConfirmationInterceptor } from "./mcp/tool-confirmation.js";
2
+ import { matchesAnyToolNamePattern } from "./tool-name-pattern.js";
1
3
  /**
2
4
  * Handles MCP JSON-RPC requests independently of the outer transport.
3
5
  */
@@ -10,6 +12,10 @@ export class McpGatewayEngine {
10
12
  * Stores the startup barrier that must resolve before gateway tools can use the registry.
11
13
  */
12
14
  startupBarrier = Promise.resolve();
15
+ /**
16
+ * Stores pending and approved confirmation continuation state.
17
+ */
18
+ toolConfirmation = new ToolConfirmationInterceptor();
13
19
  /**
14
20
  * Creates the transport-neutral gateway engine.
15
21
  */
@@ -113,8 +119,19 @@ export class McpGatewayEngine {
113
119
  const serviceId = requireString(args.serviceId, "The 'serviceId' argument must be a string.");
114
120
  const toolName = requireString(args.toolName, "The 'toolName' argument must be a string.");
115
121
  const toolArgs = toObject(args.arguments, "The 'arguments' field must be an object.");
116
- const call = await this.registry.callTool(serviceId, toolName, toolArgs, context);
117
- return call.result;
122
+ const snapshot = this.registry.getService(serviceId);
123
+ const invoke = async (callContext) => {
124
+ const call = await this.registry.callTool(serviceId, toolName, toolArgs, callContext);
125
+ return call.result;
126
+ };
127
+ if (matchesAnyToolNamePattern(toolName, snapshot?.config.disabledTools)) {
128
+ throw new Error(`Tool '${toolName}' in service '${serviceId}' is disabled by gateway configuration.`);
129
+ }
130
+ if (this.toolConfirmation.handlesState(context.requestState)
131
+ || matchesAnyToolNamePattern(toolName, snapshot?.config.confirmationRequiredTools)) {
132
+ return this.toolConfirmation.execute(serviceId, toolName, toolArgs, context, invoke);
133
+ }
134
+ return invoke(context);
118
135
  }
119
136
  /**
120
137
  * Applies one compact service management action.
@@ -1,15 +1,20 @@
1
1
  import http from "node:http";
2
- import { timingSafeEqual } from "node:crypto";
3
- import { createMcpHandler } from "@modelcontextprotocol/server";
2
+ import { randomUUID, timingSafeEqual } from "node:crypto";
3
+ import { createMcpHandler, isLegacyRequest, WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/server";
4
4
  import { hostHeaderValidation, originValidation, toNodeHandler } from "@modelcontextprotocol/node";
5
5
  import { createGatewayMcpServer } from "./mcp/server.js";
6
+ const LEGACY_SESSION_IDLE_TIMEOUT_MS = 30 * 60 * 1_000;
7
+ const LEGACY_SESSION_SWEEP_INTERVAL_MS = 60 * 1_000;
6
8
  /**
7
9
  * Exposes the gateway through SDK v2 Streamable HTTP.
8
10
  */
9
11
  export class StreamableHttpGatewayServer {
10
12
  config;
13
+ engine;
11
14
  logger;
12
15
  handler;
16
+ legacySessions = new Map();
17
+ legacySessionSweepTimer = null;
13
18
  server = null;
14
19
  /**
15
20
  * Returns the current endpoint URL after the server starts.
@@ -24,11 +29,12 @@ export class StreamableHttpGatewayServer {
24
29
  */
25
30
  constructor(config, engine, logger) {
26
31
  this.config = config;
32
+ this.engine = engine;
27
33
  this.logger = logger;
28
34
  this.handler = createMcpHandler(() => createGatewayMcpServer(engine, {
29
35
  includeAdminTools: config.enableAdminTools ?? false
30
36
  }), {
31
- legacy: "stateless",
37
+ legacy: "reject",
32
38
  onerror: (error) => {
33
39
  this.logger.error("gateway.http_protocol_error", { message: error.message });
34
40
  }
@@ -50,7 +56,9 @@ export class StreamableHttpGatewayServer {
50
56
  const allowedHosts = allowedHostnames(this.config.host);
51
57
  const validateHost = hostHeaderValidation(allowedHosts);
52
58
  const validateOrigin = originValidation(allowedHosts);
53
- const handleMcp = toNodeHandler(this.handler, {
59
+ const handleMcp = toNodeHandler({
60
+ fetch: (request) => this.handleMcpRequest(request)
61
+ }, {
54
62
  onerror: (error) => this.logger.error("gateway.http_adapter_error", { message: error.message })
55
63
  });
56
64
  const maxConcurrentRequests = this.config.maxConcurrentRequests ?? 64;
@@ -91,6 +99,8 @@ export class StreamableHttpGatewayServer {
91
99
  resolveListen();
92
100
  });
93
101
  });
102
+ this.legacySessionSweepTimer = setInterval(() => void this.closeExpiredLegacySessions(), LEGACY_SESSION_SWEEP_INTERVAL_MS);
103
+ this.legacySessionSweepTimer.unref();
94
104
  this.logger.info("gateway.http_started", {
95
105
  host: this.config.host,
96
106
  port: this.config.port,
@@ -101,6 +111,12 @@ export class StreamableHttpGatewayServer {
101
111
  * Stops accepting requests and closes all in-flight SDK exchanges.
102
112
  */
103
113
  async stop() {
114
+ if (this.legacySessionSweepTimer) {
115
+ clearInterval(this.legacySessionSweepTimer);
116
+ this.legacySessionSweepTimer = null;
117
+ }
118
+ await Promise.all([...this.legacySessions.values()].map((session) => session.server.close().catch(() => undefined)));
119
+ this.legacySessions.clear();
104
120
  await this.handler.close();
105
121
  const server = this.server;
106
122
  this.server = null;
@@ -112,6 +128,83 @@ export class StreamableHttpGatewayServer {
112
128
  server.closeAllConnections();
113
129
  });
114
130
  }
131
+ /**
132
+ * Routes modern requests to the per-request handler and preserves 2025 sessions.
133
+ */
134
+ async handleMcpRequest(request) {
135
+ if (!(await isLegacyRequest(request))) {
136
+ return this.handler.fetch(request);
137
+ }
138
+ const sessionId = request.headers.get("mcp-session-id");
139
+ if (sessionId) {
140
+ const session = this.legacySessions.get(sessionId);
141
+ if (!session) {
142
+ return sessionNotFoundResponse();
143
+ }
144
+ session.lastAccessedAt = Date.now();
145
+ return session.transport.handleRequest(request);
146
+ }
147
+ return this.handleLegacyInitialization(request);
148
+ }
149
+ /**
150
+ * Creates a stateful 2025 transport for an initialize request.
151
+ */
152
+ async handleLegacyInitialization(request) {
153
+ let session;
154
+ const transport = new WebStandardStreamableHTTPServerTransport({
155
+ sessionIdGenerator: randomUUID,
156
+ onsessioninitialized: (sessionId) => {
157
+ this.legacySessions.set(sessionId, session);
158
+ },
159
+ onsessionclosed: (sessionId) => {
160
+ this.legacySessions.delete(sessionId);
161
+ }
162
+ });
163
+ const server = createGatewayMcpServer(this.engine, {
164
+ includeAdminTools: this.config.enableAdminTools ?? false
165
+ });
166
+ session = { server, transport, lastAccessedAt: Date.now() };
167
+ await server.connect(transport);
168
+ try {
169
+ const response = await transport.handleRequest(request);
170
+ if (!transport.sessionId) {
171
+ await server.close().catch(() => undefined);
172
+ }
173
+ return response;
174
+ }
175
+ catch (error) {
176
+ if (transport.sessionId) {
177
+ this.legacySessions.delete(transport.sessionId);
178
+ }
179
+ await server.close().catch(() => undefined);
180
+ throw error;
181
+ }
182
+ }
183
+ /**
184
+ * Releases abandoned legacy sessions without touching active modern requests.
185
+ */
186
+ async closeExpiredLegacySessions() {
187
+ const expiresBefore = Date.now() - LEGACY_SESSION_IDLE_TIMEOUT_MS;
188
+ const expired = [...this.legacySessions.entries()]
189
+ .filter(([, session]) => session.lastAccessedAt < expiresBefore);
190
+ for (const [sessionId, session] of expired) {
191
+ this.legacySessions.delete(sessionId);
192
+ await session.server.close().catch(() => undefined);
193
+ }
194
+ }
195
+ }
196
+ /**
197
+ * Returns the standard status for a missing or expired MCP session.
198
+ */
199
+ function sessionNotFoundResponse() {
200
+ return Response.json({
201
+ jsonrpc: "2.0",
202
+ error: {
203
+ code: -32001,
204
+ message: "Session not found"
205
+ },
206
+ id: null
207
+ }, { status: 404 });
115
208
  }
116
209
  /**
117
210
  * Compares a supplied bearer credential without leaking a useful timing signal.
@@ -53,6 +53,9 @@ function toDownstreamContext(context, mcp2025ClientCapabilities) {
53
53
  const clientCapabilities = isRecord(envelopeCapabilities)
54
54
  ? envelopeCapabilities
55
55
  : mcp2025ClientCapabilities;
56
+ if (!context.mcpReq.envelope) {
57
+ normalizeLegacyFormElicitationCapability(clientCapabilities);
58
+ }
56
59
  return {
57
60
  signal: context.mcpReq.signal,
58
61
  ...(clientCapabilities ? { clientCapabilities } : {}),
@@ -60,11 +63,25 @@ function toDownstreamContext(context, mcp2025ClientCapabilities) {
60
63
  ...(context.mcpReq.requestState() ? { requestState: context.mcpReq.requestState() } : {}),
61
64
  ...(!context.mcpReq.envelope
62
65
  ? {
63
- elicitForm: (params, signal) => context.mcpReq.elicitInput(params, { signal })
66
+ elicitForm: (params, signal) => context.mcpReq.elicitInput(params, {
67
+ signal,
68
+ relatedRequestId: context.mcpReq.id
69
+ })
64
70
  }
65
71
  : {})
66
72
  };
67
73
  }
74
+ /**
75
+ * MCP 2025 clients may advertise form elicitation as the legacy shorthand
76
+ * `elicitation: {}`. The SDK's request helper expects the later explicit
77
+ * `elicitation.form` shape, so normalize the negotiated capability in place.
78
+ */
79
+ export function normalizeLegacyFormElicitationCapability(clientCapabilities) {
80
+ const elicitation = clientCapabilities?.elicitation;
81
+ if (isRecord(elicitation) && !("form" in elicitation)) {
82
+ elicitation.form = {};
83
+ }
84
+ }
68
85
  /**
69
86
  * Checks whether a value is a plain record.
70
87
  */
@@ -0,0 +1,215 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { isDeepStrictEqual } from "node:util";
3
+ const CONFIRMATION_STATE_PREFIX = "mcp-gateway-tool-confirmation-v1.";
4
+ const APPROVED_STATE_PREFIX = "mcp-gateway-approved-tool-continuation-v1.";
5
+ const CONFIRMATION_RESPONSE_KEY = "confirm";
6
+ const DEFAULT_STATE_TTL_MS = 10 * 60_000;
7
+ const DEFAULT_MAX_STATES = 1024;
8
+ /**
9
+ * Gates configured downstream tools behind one upstream form elicitation round.
10
+ */
11
+ export class ToolConfirmationInterceptor {
12
+ stateTtlMs;
13
+ maxStates;
14
+ pending = new Map();
15
+ approvedContinuations = new Map();
16
+ activeInvocations = 0;
17
+ constructor(options = {}) {
18
+ this.stateTtlMs = options.stateTtlMs ?? DEFAULT_STATE_TTL_MS;
19
+ this.maxStates = options.maxStates ?? DEFAULT_MAX_STATES;
20
+ if (!Number.isInteger(this.maxStates) || this.maxStates < 1) {
21
+ throw new Error("Tool confirmation maxStates must be a positive integer.");
22
+ }
23
+ }
24
+ /**
25
+ * Checks whether a request state belongs to this interceptor.
26
+ */
27
+ handlesState(requestState) {
28
+ return requestState?.startsWith(CONFIRMATION_STATE_PREFIX) === true
29
+ || requestState?.startsWith(APPROVED_STATE_PREFIX) === true;
30
+ }
31
+ /**
32
+ * Confirms a fresh invocation or resumes a previously approved downstream round.
33
+ */
34
+ async execute(serviceId, toolName, args, context, invoke) {
35
+ const requestState = context.requestState;
36
+ if (requestState?.startsWith(APPROVED_STATE_PREFIX)) {
37
+ const approved = this.consumeState(this.approvedContinuations, requestState, serviceId, toolName, args);
38
+ if (!approved?.downstreamRequestState) {
39
+ throw new Error("Tool confirmation state is invalid or has expired.");
40
+ }
41
+ return this.invokeReserved(serviceId, toolName, args, { ...context, requestState: approved.downstreamRequestState }, invoke);
42
+ }
43
+ if (requestState?.startsWith(CONFIRMATION_STATE_PREFIX)) {
44
+ return this.resumeConfirmation(requestState, serviceId, toolName, args, context, invoke);
45
+ }
46
+ if (requestState) {
47
+ throw new Error("Tool confirmation state is invalid or has expired.");
48
+ }
49
+ if (!supportsFormElicitation(context.clientCapabilities)) {
50
+ throw new Error(`Tool '${toolName}' in service '${serviceId}' requires confirmation, but the current MCP session does not support form elicitation.`);
51
+ }
52
+ if (this.stateCount() >= this.maxStates) {
53
+ throw new Error(`Tool confirmation state capacity of ${this.maxStates} has been reached.`);
54
+ }
55
+ const state = this.createState(serviceId, toolName, args);
56
+ this.pending.set(state.requestState, state);
57
+ return buildConfirmationRequest(state);
58
+ }
59
+ /**
60
+ * Consumes the upstream answer before invoking the downstream tool.
61
+ */
62
+ async resumeConfirmation(requestState, serviceId, toolName, args, context, invoke) {
63
+ const pending = this.consumeState(this.pending, requestState, serviceId, toolName, args);
64
+ if (!pending) {
65
+ throw new Error("Tool confirmation state is invalid or has expired.");
66
+ }
67
+ const response = context.inputResponses?.[CONFIRMATION_RESPONSE_KEY];
68
+ if (!isConfirmed(response)) {
69
+ throw new Error(`Tool '${toolName}' in service '${serviceId}' was not called because the user rejected the confirmation request.`);
70
+ }
71
+ return this.invokeReserved(serviceId, toolName, args, withoutConfirmationContinuation(context), invoke);
72
+ }
73
+ /**
74
+ * Keeps a consumed state slot reserved while a downstream round is active.
75
+ */
76
+ async invokeReserved(serviceId, toolName, args, context, invoke) {
77
+ this.activeInvocations += 1;
78
+ try {
79
+ return await this.invokeAndTrack(serviceId, toolName, args, context, invoke);
80
+ }
81
+ finally {
82
+ this.activeInvocations -= 1;
83
+ }
84
+ }
85
+ /**
86
+ * Records downstream MRTR state so later rounds do not ask for confirmation again.
87
+ */
88
+ async invokeAndTrack(serviceId, toolName, args, context, invoke) {
89
+ const result = await invoke(context);
90
+ if (isInputRequiredResult(result) && typeof result.requestState === "string") {
91
+ const state = this.createState(serviceId, toolName, args, `${APPROVED_STATE_PREFIX}${randomUUID()}`, result.requestState);
92
+ this.approvedContinuations.set(state.requestState, state);
93
+ return { ...result, requestState: state.requestState };
94
+ }
95
+ return result;
96
+ }
97
+ /**
98
+ * Creates an expiring state record with an unguessable token when needed.
99
+ */
100
+ createState(serviceId, toolName, args, requestState = `${CONFIRMATION_STATE_PREFIX}${randomUUID()}`, downstreamRequestState) {
101
+ const state = {
102
+ serviceId,
103
+ toolName,
104
+ args: structuredClone(args),
105
+ requestState,
106
+ ...(downstreamRequestState ? { downstreamRequestState } : {}),
107
+ expiryTimer: setTimeout(() => {
108
+ this.pending.delete(requestState);
109
+ this.approvedContinuations.delete(requestState);
110
+ }, this.stateTtlMs)
111
+ };
112
+ state.expiryTimer.unref();
113
+ return state;
114
+ }
115
+ /**
116
+ * Atomically consumes a matching state record.
117
+ */
118
+ consumeState(states, requestState, serviceId, toolName, args) {
119
+ const state = states.get(requestState);
120
+ if (!state
121
+ || state.serviceId !== serviceId
122
+ || state.toolName !== toolName
123
+ || !isDeepStrictEqual(state.args, args)) {
124
+ return null;
125
+ }
126
+ states.delete(requestState);
127
+ clearTimeout(state.expiryTimer);
128
+ return state;
129
+ }
130
+ /**
131
+ * Counts parked and currently executing confirmation-protected invocations.
132
+ */
133
+ stateCount() {
134
+ return this.pending.size + this.approvedContinuations.size + this.activeInvocations;
135
+ }
136
+ }
137
+ /**
138
+ * Creates the modern continuation result; the SDK bridges it for legacy clients.
139
+ */
140
+ function buildConfirmationRequest(state) {
141
+ return {
142
+ resultType: "input_required",
143
+ inputRequests: {
144
+ [CONFIRMATION_RESPONSE_KEY]: {
145
+ method: "elicitation/create",
146
+ params: {
147
+ mode: "form",
148
+ message: buildConfirmationMessage(state),
149
+ requestedSchema: {
150
+ type: "object",
151
+ properties: {
152
+ decision: {
153
+ type: "string",
154
+ title: "Run this tool call?",
155
+ description: "Choose yes to execute the displayed call or no to reject it.",
156
+ enum: ["yes", "no"]
157
+ }
158
+ },
159
+ required: ["decision"],
160
+ additionalProperties: false
161
+ }
162
+ }
163
+ }
164
+ },
165
+ requestState: state.requestState
166
+ };
167
+ }
168
+ /**
169
+ * Shows the exact protected invocation so the user can make an informed decision.
170
+ */
171
+ function buildConfirmationMessage(state) {
172
+ return [
173
+ "Review this gateway-protected tool call before execution.",
174
+ `Service: ${JSON.stringify(state.serviceId)}`,
175
+ `Tool: ${JSON.stringify(state.toolName)}`,
176
+ "Risk: Gateway policy requires explicit confirmation.",
177
+ "Arguments:",
178
+ JSON.stringify(state.args, null, 2),
179
+ "Choose yes to execute it or no to reject it."
180
+ ].join("\n");
181
+ }
182
+ /**
183
+ * Checks the explicit capability instead of relying on a later SDK failure.
184
+ */
185
+ function supportsFormElicitation(capabilities) {
186
+ const elicitation = capabilities?.elicitation;
187
+ return isRecord(elicitation) && isRecord(elicitation.form);
188
+ }
189
+ /**
190
+ * Treats cancel, decline, malformed content, and a no decision as refusal.
191
+ */
192
+ function isConfirmed(response) {
193
+ return response?.action === "accept"
194
+ && isRecord(response.content)
195
+ && response.content.decision === "yes";
196
+ }
197
+ /**
198
+ * Removes the gateway's private confirmation continuation before the first call.
199
+ */
200
+ function withoutConfirmationContinuation(context) {
201
+ const { inputResponses: _inputResponses, requestState: _requestState, ...rest } = context;
202
+ return rest;
203
+ }
204
+ /**
205
+ * Detects a modern input-required tool result without depending on SDK internals.
206
+ */
207
+ function isInputRequiredResult(result) {
208
+ return "resultType" in result && result.resultType === "input_required";
209
+ }
210
+ /**
211
+ * Checks whether a value is a plain record.
212
+ */
213
+ function isRecord(value) {
214
+ return typeof value === "object" && value !== null && !Array.isArray(value);
215
+ }
@@ -3,6 +3,7 @@ import { dirname, resolve } from "node:path";
3
3
  import { randomUUID } from "node:crypto";
4
4
  import { StdioMcpClient } from "./mcp/client.js";
5
5
  import { StreamableHttpClient } from "./mcp/http-client.js";
6
+ import { matchesAnyToolNamePattern } from "./tool-name-pattern.js";
6
7
  /**
7
8
  * Maintains the active service pool, client instances, and cached metadata.
8
9
  */
@@ -125,7 +126,8 @@ export class ServiceRegistry {
125
126
  * Lists tools for one logical service, optionally matching name or description keywords.
126
127
  */
127
128
  listTools(serviceId, toolName, desc) {
128
- const tools = this.requireService(serviceId).metadata.tools;
129
+ const snapshot = this.requireService(serviceId);
130
+ const tools = snapshot.metadata.tools.filter((tool) => !matchesAnyToolNamePattern(tool.name, snapshot.config.disabledTools));
129
131
  const nameKeywords = normalizeKeywords(toolName);
130
132
  const descriptionKeywords = normalizeKeywords(desc);
131
133
  if (nameKeywords.length === 0 && descriptionKeywords.length === 0) {
@@ -142,13 +144,20 @@ export class ServiceRegistry {
142
144
  * Returns one tool definition for a service.
143
145
  */
144
146
  getTool(serviceId, toolName) {
145
- return this.requireService(serviceId).metadata.tools.find((tool) => tool.name === toolName) ?? null;
147
+ const snapshot = this.requireService(serviceId);
148
+ if (matchesAnyToolNamePattern(toolName, snapshot.config.disabledTools)) {
149
+ return null;
150
+ }
151
+ return snapshot.metadata.tools.find((tool) => tool.name === toolName) ?? null;
146
152
  }
147
153
  /**
148
154
  * Calls one downstream tool using the only configured service process.
149
155
  */
150
156
  async callTool(serviceId, toolName, args, context = {}) {
151
157
  const snapshot = this.requireService(serviceId);
158
+ if (matchesAnyToolNamePattern(toolName, snapshot.config.disabledTools)) {
159
+ throw new Error(`Tool '${toolName}' in service '${serviceId}' is disabled by gateway configuration.`);
160
+ }
152
161
  const client = this.clients.get(serviceId);
153
162
  if (!client) {
154
163
  throw new Error(`Service '${serviceId}' is unavailable.`);
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Matches one complete, case-sensitive tool name against a compact glob pattern.
3
+ * `*` matches zero or more characters and `?` matches exactly one character.
4
+ */
5
+ export function matchesToolNamePattern(toolName, pattern) {
6
+ const nameCharacters = [...toolName];
7
+ const patternCharacters = [...pattern];
8
+ let nameIndex = 0;
9
+ let patternIndex = 0;
10
+ let starIndex = -1;
11
+ let starNameIndex = -1;
12
+ while (nameIndex < nameCharacters.length) {
13
+ const patternCharacter = patternCharacters[patternIndex];
14
+ if (patternCharacter === "?" || patternCharacter === nameCharacters[nameIndex]) {
15
+ nameIndex += 1;
16
+ patternIndex += 1;
17
+ continue;
18
+ }
19
+ if (patternCharacter === "*") {
20
+ starIndex = patternIndex;
21
+ starNameIndex = nameIndex;
22
+ patternIndex += 1;
23
+ continue;
24
+ }
25
+ if (starIndex >= 0) {
26
+ patternIndex = starIndex + 1;
27
+ starNameIndex += 1;
28
+ nameIndex = starNameIndex;
29
+ continue;
30
+ }
31
+ return false;
32
+ }
33
+ while (patternCharacters[patternIndex] === "*") {
34
+ patternIndex += 1;
35
+ }
36
+ return patternIndex === patternCharacters.length;
37
+ }
38
+ /**
39
+ * Checks whether a tool name matches any configured pattern.
40
+ */
41
+ export function matchesAnyToolNamePattern(toolName, patterns) {
42
+ return patterns?.some((pattern) => matchesToolNamePattern(toolName, pattern)) ?? false;
43
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jadchene/mcp-gateway-service",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "description": "A token-efficient MCP gateway that provides one unified entry point for multiple downstream MCP services.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",