@mcp-abap-adt/core 15.1.0 → 16.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/launcher.js CHANGED
@@ -1,50 +1,20 @@
1
1
  "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
2
  Object.defineProperty(exports, "__esModule", { value: true });
36
3
  exports.main = main;
37
- const fs = __importStar(require("node:fs"));
38
- const path = __importStar(require("node:path"));
4
+ exports.effectiveConnectionType = effectiveConnectionType;
5
+ exports.effectiveSystemType = effectiveSystemType;
6
+ exports.promptsOnStderr = promptsOnStderr;
7
+ exports.factoryConfigFrom = factoryConfigFrom;
8
+ exports.launch = launch;
39
9
  const auth_1 = require("@mcp-abap-adt/lib/auth");
40
10
  const config_1 = require("@mcp-abap-adt/lib/config");
41
11
  const handlers_1 = require("@mcp-abap-adt/lib/handlers");
42
12
  const utils_1 = require("@mcp-abap-adt/lib/utils");
43
- const dotenv = __importStar(require("dotenv"));
44
- const AuthBrokerConfig_js_1 = require("./AuthBrokerConfig.js");
13
+ const coreVersion_js_1 = require("./coreVersion.js");
45
14
  const SseServer_js_1 = require("./SseServer.js");
46
15
  const StdioServer_js_1 = require("./StdioServer.js");
47
16
  const StreamableHttpServer_js_1 = require("./StreamableHttpServer.js");
17
+ const shutdown_js_1 = require("./shutdown.js");
48
18
  const stderrLogger = {
49
19
  info: (...args) => console.error(...args),
50
20
  warn: (...args) => console.error(...args),
@@ -63,36 +33,6 @@ let activeServer;
63
33
  function hasArg(name) {
64
34
  return process.argv.includes(name);
65
35
  }
66
- /**
67
- * In v2 flow, .env can be loaded into auth-broker session storage without
68
- * populating process.env. System context resolver relies on process.env
69
- * for SAP_MASTER_SYSTEM / SAP_RESPONSIBLE, so bridge these values here.
70
- */
71
- function hydrateSystemContextFromEnvFile(envFilePath) {
72
- if (!envFilePath || !fs.existsSync(envFilePath)) {
73
- return;
74
- }
75
- try {
76
- const parsed = dotenv.parse(fs.readFileSync(envFilePath, 'utf8'));
77
- const keys = [
78
- 'SAP_MASTER_SYSTEM',
79
- 'SAP_RESPONSIBLE',
80
- 'SAP_USERNAME',
81
- 'SAP_CLIENT',
82
- 'SAP_CONNECTION_TYPE',
83
- 'SAP_SYSTEM_TYPE',
84
- ];
85
- for (const key of keys) {
86
- const value = parsed[key];
87
- if (!process.env[key] && value) {
88
- process.env[key] = value;
89
- }
90
- }
91
- }
92
- catch {
93
- // Ignore .env parse errors here; auth-broker initialization handles config validation.
94
- }
95
- }
96
36
  /**
97
37
  * This package's own version, read from this package's own manifest.
98
38
  *
@@ -113,9 +53,7 @@ function hydrateSystemContextFromEnvFile(envFilePath) {
113
53
  * should answer with.
114
54
  */
115
55
  function showVersion() {
116
- const packageJsonPath = path.join(__dirname, '..', 'package.json');
117
- const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
118
- console.log(packageJson.version);
56
+ console.log(coreVersion_js_1.CORE_VERSION);
119
57
  process.exit(0);
120
58
  }
121
59
  /**
@@ -131,9 +69,9 @@ ENVIRONMENT VARIABLES:
131
69
  MCP_SSE_HOST SSE server host (default: 127.0.0.1)
132
70
  MCP_SSE_PORT SSE server port (default: 3001)
133
71
  MCP_ENV_PATH Explicit .env file path (same as --env-path)
134
- MCP_UNSAFE Disable connection validation (true|false)
135
- MCP_USE_AUTH_BROKER Force auth-broker usage (true|false)
136
- MCP_BROWSER Browser for OAuth2 flow (e.g., chrome, firefox)
72
+ MCP_UNSAFE Write named destinations' sessions to disk (true|false)
73
+ MCP_BROWSER Browser for a login: chrome|edge|firefox|system|headless|none
74
+ MCP_BROWSER_AUTH_PORT Login callback port, 1-65535 (default: 61001)
137
75
  MCP_TLS_CERT Path to TLS certificate file (PEM)
138
76
  MCP_TLS_KEY Path to TLS private key file (PEM)
139
77
  MCP_TLS_CA Path to TLS CA certificate file (PEM, optional)
@@ -141,9 +79,7 @@ ENVIRONMENT VARIABLES:
141
79
  Auth-Broker:
142
80
  DEBUG_AUTH_LOG Enable debug logging for auth-broker (true|false)
143
81
  DEBUG_AUTH_BROKER Alias for DEBUG_AUTH_LOG
144
- AUTH_BROKER_PATH Custom paths for service keys and sessions
145
- Unix: colon-separated (e.g., /path1:/path2)
146
- Windows: semicolon-separated (e.g., C:\\\\path1;C:\\\\path2)
82
+ AUTH_BROKER_PATH Base directory of service-keys/ and sessions/
147
83
 
148
84
  Debug Options:
149
85
  DEBUG_HANDLERS Enable handler debug logging (true|false)
@@ -151,49 +87,79 @@ ENVIRONMENT VARIABLES:
151
87
  DEBUG_CONNECTION_MANAGER Enable connection manager debug logging (true|false)
152
88
  HANDLER_LOG_SILENT Disable all handler logs (true|false)
153
89
 
154
- SAP CONNECTION (.env file):
90
+ AUTHENTICATIONS (exactly four; a .env or service key stating another is refused):
91
+ basic SAP_AUTH_TYPE=basic user and password, HTTP or RFC
92
+ snc SAP_AUTH_TYPE=snc RFC only, no user, no password
93
+ jwt SAP_AUTH_TYPE=jwt, SAP_GRANT_TYPE=authorization_code browser login
94
+ jwt SAP_AUTH_TYPE=jwt, SAP_GRANT_TYPE=none a token you hold
95
+
96
+ SAP CONNECTION (.env file; secrets and the session live here, never in YAML):
155
97
 
156
98
  Basic Authentication (on-premise):
157
99
  SAP_URL SAP system URL (required)
158
100
  SAP_CLIENT SAP client number (required for basic auth)
159
- SAP_AUTH_TYPE Authentication type: basic|jwt (default: basic)
101
+ SAP_AUTH_TYPE Authentication type: basic|snc|jwt (required)
160
102
  SAP_CONNECTION_TYPE Connection type: http|rfc (default: http)
161
- SAP_SYSTEM_TYPE SAP system type: cloud (default) | onprem | legacy
162
- Controls tool availability (e.g. Programs need onprem)
163
- Set to 'onprem' for on-premise systems
103
+ Precedence: --connection-type, then the environment
104
+ (this file joins it, never over a value set), then YAML
105
+ SAP_SYSTEM_TYPE SAP system type: cloud | onprem | legacy (same as --system-type)
106
+ Tools offered: default cloud (e.g. Programs need onprem)
107
+ Connector and master-system lookup: default cloud for a
108
+ jwt destination, else onprem — never guessed from the URL
164
109
  SAP_USERNAME SAP username (required for basic auth)
165
110
  SAP_PASSWORD SAP password (required for basic auth)
166
111
  SAP_LANGUAGE SAP language (optional, e.g., EN, DE)
167
112
 
168
- JWT/OAuth2 Authentication:
169
- SAP_JWT_TOKEN JWT token (required for jwt auth)
170
- SAP_REFRESH_TOKEN Refresh token for token renewal
171
- SAP_UAA_URL UAA URL for OAuth2 (or UAA_URL)
172
- SAP_UAA_CLIENT_ID UAA Client ID (or UAA_CLIENT_ID)
173
- SAP_UAA_CLIENT_SECRET UAA Client Secret (or UAA_CLIENT_SECRET)
113
+ SNC (passwordless logon over RFC; no SAP_USERNAME, no SAP_PASSWORD):
114
+ SAP_AUTH_TYPE=snc with SAP_CONNECTION_TYPE=rfc (or --connection-type=rfc)
115
+ SAP_SNC_PARTNERNAME The system's SNC name (required)
116
+ SAP_SNC_QOP, SAP_SNC_LIB, SAP_SNC_MYNAME Optional
117
+
118
+ JWT/OAuth2 Authentication (SAP_GRANT_TYPE is required with jwt):
119
+ SAP_GRANT_TYPE authorization_code (browser login) | none (a token you hold)
120
+ SAP_JWT_TOKEN JWT token (with SAP_GRANT_TYPE=none)
121
+ SAP_REFRESH_TOKEN Refresh token (the server stores the one it obtains)
122
+ SAP_UAA_URL UAA URL for OAuth2
123
+ SAP_UAA_CLIENT_ID UAA Client ID
124
+ SAP_UAA_CLIENT_SECRET UAA Client Secret
125
+ An XSUAA service key needs XSUAA_MCP_URL (the system's URL) in sessions/<destination>.env
174
126
 
175
127
  RFC Connection (any system with SAP NW RFC SDK):
176
- SAP_CONNECTION_TYPE=rfc Enables RFC transport via SADT_REST_RFC_ENDPOINT
128
+ --connection-type=rfc Enables RFC transport via SADT_REST_RFC_ENDPOINT
129
+ (or SAP_CONNECTION_TYPE=rfc in the .env or the environment)
177
130
  SAP_URL SAP system URL (host:port used to derive RFC params)
178
131
  SAP_USERNAME SAP username
179
132
  SAP_PASSWORD SAP password
180
133
  SAP_CLIENT SAP client number
181
- Requires: SAP NW RFC SDK + @mcp-abap-adt/sap-rfc-lite package installed
134
+ Requires: SAP NW RFC SDK + @mcp-abap-adt/sap-rfc-lite (an optional dependency)
182
135
 
183
- System Context (on-premise):
184
- SAP_MASTER_SYSTEM SAP system ID (e.g., DEV, QAS). Required for on-prem
185
- create/update — ensures correct transport request binding.
186
- Cloud systems resolve this automatically via API.
187
- SAP_RESPONSIBLE Responsible user (optional, falls back to SAP_USERNAME)
136
+ System Context (per request, first found wins; reads are unaffected):
137
+ SAP_RESPONSIBLE Responsible person of created objects, always sent. First
138
+ found: the tool's argument; x-sap-responsible; SAP_RESPONSIBLE
139
+ in the destination's own .env (--env / --env-path file, or
140
+ sessions/<destination>.env), then in the environment. Else
141
+ the login: on-premise the destination's SAP_USERNAME, the
142
+ x-sap-login of an x-sap-url connection, the environment's
143
+ SAP_USERNAME; on a cloud system only the system's user. A create
144
+ that finds none is refused (SNC, a token). A message class
145
+ takes the system's own default responsible.
146
+ SAP_MASTER_SYSTEM Master system of created objects (no tool takes it as an
147
+ argument). First found: x-sap-master-system; the destination's
148
+ .env; the environment; on a cloud system, the system id.
149
+ Otherwise left out of the request, never refused
150
+ The environment is read once: later changes are not picked up
188
151
 
189
- HTTP/SSE Headers (System Context):
190
- x-sap-master-system Per-request SAP system ID (overrides SAP_MASTER_SYSTEM)
191
- x-sap-responsible Per-request responsible user (overrides SAP_RESPONSIBLE)
192
- x-sap-language Per-request master/original language for created objects (overrides SAP_LANGUAGE)
152
+ HTTP/SSE Headers (System Context; SSE: the session's opening request):
153
+ x-sap-master-system Master system for this request (wins over the .env and env)
154
+ x-sap-responsible Responsible for this request (wins over the .env and env)
155
+ x-sap-login With x-sap-url (on-premise): the login, the responsible when
156
+ none is stated; on a destination request it is not read
157
+ x-sap-language Master/original language for created objects (overrides SAP_LANGUAGE)
193
158
 
194
- GENERATING .ENV FROM SERVICE KEY:
195
- Install the auth broker: npm install -g @mcp-abap-adt/auth-broker
196
- Generate .env: mcp-auth --service-key path/to/service-key.json --output .env
159
+ GENERATING A .ENV:
160
+ Install the CLI: npm install -g @mcp-abap-adt/auth-broker-cli
161
+ Generate .env: mcp-auth generate-env --grant authorization_code (mcp-auth --help lists the other flags)
162
+ A jwt .env must state SAP_GRANT_TYPE.
197
163
  `;
198
164
  function showHelp(options = {}) {
199
165
  console.error(config_1.ServerConfigManager.generateHelp(V2_HELP_SECTIONS, {
@@ -215,11 +181,200 @@ async function main(options = {}) {
215
181
  // Use ServerConfigManager for all config parsing
216
182
  const configManager = new config_1.ServerConfigManager();
217
183
  const config = await configManager.getConfig();
218
- hydrateSystemContextFromEnvFile(config.envFile);
219
- // CLI --connection-type overrides env var
220
- if (config.connectionType && !process.env.SAP_CONNECTION_TYPE) {
221
- process.env.SAP_CONNECTION_TYPE = config.connectionType;
184
+ await launch(config, options, {
185
+ browserStrategy: auth_1.browserCallbackStrategy,
186
+ stderr: (line) => process.stderr.write(`${line}\n`),
187
+ exit: (code) => process.exit(code),
188
+ processLike: process,
189
+ });
190
+ }
191
+ /**
192
+ * The env file and the parameter it came from. `envFilePath` is
193
+ * `IServerConfig`'s alias of `envFile`; ServerConfigManager sets both and
194
+ * states the source. A config made by hand names the field it set.
195
+ */
196
+ function envFileOf(config) {
197
+ const field = config.envFile
198
+ ? 'envFile'
199
+ : config.envFilePath
200
+ ? 'envFilePath'
201
+ : undefined;
202
+ if (!field)
203
+ return {};
204
+ return {
205
+ envFile: {
206
+ path: config[field],
207
+ source: config.envFileSource ?? `IServerConfig.${field}`,
208
+ },
209
+ };
210
+ }
211
+ /**
212
+ * A parameter the env file may state: the CLI, then the process environment
213
+ * — which by now holds what the env file states, never over a value set
214
+ * before — then YAML. A config made by hand, with no source, is taken as it
215
+ * is. A word in the environment that is not one of `values` is refused naming
216
+ * the key, never quoting it: it may come from a file.
217
+ */
218
+ function effectiveFromEnvironment(value, source, key, values, env) {
219
+ const overridable = source === key ||
220
+ (source?.endsWith('(config file)') ?? false) ||
221
+ value === undefined;
222
+ if (!overridable)
223
+ return value;
224
+ const raw = env[key]?.trim().toLowerCase();
225
+ if (!raw)
226
+ return value;
227
+ if (!values.includes(raw)) {
228
+ const words = values.length === 2
229
+ ? values.join(' or ')
230
+ : `${values.slice(0, -1).join(', ')} or ${values[values.length - 1]}`;
231
+ throw new Error(`${key} (environment or env file) must be ${words}`);
222
232
  }
233
+ return raw;
234
+ }
235
+ /** The connection type: see {@link effectiveFromEnvironment}. */
236
+ function effectiveConnectionType(config, env) {
237
+ return effectiveFromEnvironment(config.connectionType, config.connectionTypeSource, 'SAP_CONNECTION_TYPE', ['http', 'rfc'], env);
238
+ }
239
+ /**
240
+ * The system type: see {@link effectiveFromEnvironment}. The parser no longer
241
+ * writes it into the environment, where it used to sit before the env file
242
+ * was read and so beat the file's SAP_SYSTEM_TYPE even from YAML.
243
+ */
244
+ function effectiveSystemType(config, env) {
245
+ return effectiveFromEnvironment(config.systemType, config.systemTypeSource, 'SAP_SYSTEM_TYPE', ['onprem', 'cloud', 'legacy'], env);
246
+ }
247
+ /**
248
+ * The login strategy, with prompts that reach the user. auth-providers'
249
+ * strategy speaks to the user through the request's logger — the URL to open
250
+ * under `--browser=none`/`headless`, or `auto` when it could not open one — and
251
+ * that logger is the broker's, silent unless DEBUG_AUTH_LOG is set. A prompt
252
+ * the user cannot see makes the login impassable: it times out.
253
+ *
254
+ * So the strategy gets its own logger: `info`, the level the strategy prompts
255
+ * at, is a line on stderr always; `warn`, `error` and `debug` stay the
256
+ * broker's — diagnostics, gated, and they may quote an error's message (H4).
257
+ * Not "no logger" (auth-providers then writes prompts to stderr itself): that
258
+ * would also drop those diagnostics under DEBUG_AUTH_LOG. Never stdout (H3).
259
+ */
260
+ function promptsOnStderr(browserStrategy, stderr, diagnostics) {
261
+ const logger = {
262
+ info: (message) => stderr(message),
263
+ warn: (message, meta) => diagnostics.warn(message, meta),
264
+ error: (message, meta) => diagnostics.error(message, meta),
265
+ debug: (message, meta) => diagnostics.debug(message, meta),
266
+ };
267
+ return (options) => {
268
+ const strategy = browserStrategy(options);
269
+ const prompting = {
270
+ authorize: (request) => strategy.authorize({ ...request, logger }),
271
+ };
272
+ if (strategy.dispose) {
273
+ prompting.dispose = () => strategy.dispose?.() ?? Promise.resolve();
274
+ }
275
+ return prompting;
276
+ };
277
+ }
278
+ /** The browser of a login when none is given. */
279
+ const DEFAULT_BROWSER = 'system';
280
+ /**
281
+ * The factory's configuration, read from the parameters alone. The callback
282
+ * port is left to the strategy (61001) when none is given; the env file
283
+ * carries the parameter it came from, as the user gave it.
284
+ */
285
+ function factoryConfigFrom(config, collaborators) {
286
+ return {
287
+ ...envFileOf(config),
288
+ ...(config.mcpDestination && { mcpDestination: config.mcpDestination }),
289
+ ...(config.authBrokerPath && { authBrokerPath: config.authBrokerPath }),
290
+ unsafe: config.unsafe ?? false,
291
+ browser: config.browser ?? DEFAULT_BROWSER,
292
+ ...(config.browserAuthPort !== undefined && {
293
+ browserAuthPort: config.browserAuthPort,
294
+ }),
295
+ ...(config.connectionType && { connectionType: config.connectionType }),
296
+ browserStrategy: collaborators.browserStrategy,
297
+ ...(collaborators.logger && { logger: collaborators.logger }),
298
+ };
299
+ }
300
+ /**
301
+ * The words a startup failure is reported in: the error's own vetted words
302
+ * when the server knows them, else the destination and the error's class —
303
+ * never its message, which may quote a file it could not parse (H4).
304
+ */
305
+ function startupWords(error, destination) {
306
+ return ((0, auth_1.describeAuthError)(error) ??
307
+ `Destination "${destination}" cannot be read: ${(0, auth_1.errorClassOf)(error)}`);
308
+ }
309
+ /**
310
+ * The startup summary: the destination's settings, then what its stores
311
+ * hold, masked as before (H4's one exception). The settings are read first
312
+ * and their failure is the caller's: a destination that cannot be served
313
+ * stops the start.
314
+ */
315
+ async function checkAndSummarise(factory, destination, config, stderr) {
316
+ const settings = await factory.settingsFor(destination);
317
+ try {
318
+ const broker = await factory.getBroker(destination);
319
+ const connConfig = await broker.getConnectionConfig(destination);
320
+ const displayConfig = {
321
+ serviceUrl: settings.url,
322
+ sapClient: settings.client,
323
+ authType: settings.authType,
324
+ username: connConfig?.username,
325
+ password: connConfig?.password,
326
+ jwtToken: connConfig?.authorizationToken,
327
+ };
328
+ try {
329
+ const authConfig = await broker.getAuthorizationConfig(destination);
330
+ if (authConfig) {
331
+ displayConfig.uaaUrl = authConfig.uaaUrl;
332
+ displayConfig.uaaClientId = authConfig.uaaClientId;
333
+ displayConfig.uaaClientSecret = authConfig.uaaClientSecret;
334
+ displayConfig.refreshToken = authConfig.refreshToken;
335
+ }
336
+ }
337
+ catch {
338
+ // The client is optional: a destination without one shows none.
339
+ }
340
+ const source = config.mcpDestination
341
+ ? `service-key: ${config.mcpDestination}`
342
+ : (config.envFile ?? config.envFilePath ?? 'unknown');
343
+ stderr((0, utils_1.formatAuthConfigForDisplay)(displayConfig, source));
344
+ }
345
+ catch (error) {
346
+ // The summary is information: it never stops a start the settings allowed.
347
+ stderr(`[MCP] Warning: Could not display auth config: ${startupWords(error, destination)}`);
348
+ }
349
+ }
350
+ /**
351
+ * Everything after the parameters are read: the tool list, one factory, the
352
+ * destination the process serves checked and summarised, the transport, and
353
+ * the shutdown. A destination that cannot be served stops the start before
354
+ * any transport does.
355
+ */
356
+ async function launch(config, options, deps) {
357
+ // The env file's context joins the process environment first — never over
358
+ // a value already there — so its SAP_CONNECTION_TYPE and SAP_SYSTEM_TYPE
359
+ // count (as in 15.x).
360
+ (0, config_1.hydrateSystemContextFromEnvFile)(config.envFile ?? config.envFilePath);
361
+ let connectionType;
362
+ let systemType;
363
+ try {
364
+ connectionType = effectiveConnectionType(config, process.env);
365
+ systemType = effectiveSystemType(config, process.env);
366
+ }
367
+ catch (error) {
368
+ deps.stderr(`[MCP] ${error instanceof Error ? error.message : 'SAP_CONNECTION_TYPE or SAP_SYSTEM_TYPE: refused'}`);
369
+ deps.exit(1);
370
+ return;
371
+ }
372
+ if (connectionType)
373
+ process.env.SAP_CONNECTION_TYPE = connectionType;
374
+ // The connector reads the system type from the environment.
375
+ if (systemType)
376
+ process.env.SAP_SYSTEM_TYPE = systemType;
377
+ config = { ...config, connectionType, systemType };
223
378
  const baseContext = {
224
379
  connection: undefined,
225
380
  logger: undefined,
@@ -258,108 +413,63 @@ async function main(options = {}) {
258
413
  handlerGroups.push(new handlers_1.SearchHandlersGroup(baseContext));
259
414
  }
260
415
  const handlersRegistry = new handlers_1.CompositeHandlersRegistry(handlerGroups);
261
- // Create auth broker config using adapter
262
- const brokerConfig = AuthBrokerConfig_js_1.AuthBrokerConfig.fromServerConfig(config, loggerForTransport);
263
- const authBrokerFactory = new auth_1.AuthBrokerFactory(brokerConfig);
264
- // Initialize default broker (important for .env file support)
265
- await authBrokerFactory.initializeDefaultBroker();
266
- // Display auth configuration at startup (always show for transparency)
267
- const defaultBroker = authBrokerFactory.getDefaultBroker();
268
- if (defaultBroker) {
416
+ const factory = new auth_1.AuthBrokerFactory(factoryConfigFrom(config, {
417
+ browserStrategy: promptsOnStderr(deps.browserStrategy, deps.stderr, loggerForTransport),
418
+ logger: loggerForTransport,
419
+ }));
420
+ // --mcp=X → X; an --env file → default; neither → none (one destination either way).
421
+ const destination = factory.defaultDestination;
422
+ if (destination) {
269
423
  try {
270
- // Get connection config from broker to display
271
- const connConfig = await defaultBroker.getConnectionConfig(config.mcpDestination || 'default');
272
- if (connConfig) {
273
- const displayConfig = {
274
- serviceUrl: connConfig.serviceUrl,
275
- sapClient: connConfig.sapClient,
276
- authType: connConfig.authType,
277
- username: connConfig.username,
278
- password: connConfig.password,
279
- jwtToken: connConfig.authorizationToken,
280
- };
281
- // Try to get auth config for UAA details
282
- try {
283
- const authConfig = await defaultBroker.sessionStore?.getAuthorizationConfig?.(config.mcpDestination || 'default');
284
- if (authConfig) {
285
- displayConfig.uaaUrl = authConfig.uaaUrl;
286
- displayConfig.uaaClientId = authConfig.uaaClientId;
287
- displayConfig.uaaClientSecret = authConfig.uaaClientSecret;
288
- displayConfig.refreshToken = authConfig.refreshToken;
289
- }
290
- }
291
- catch {
292
- // Ignore - auth config is optional
293
- }
294
- // Determine source
295
- let source = 'unknown';
296
- if (config.mcpDestination) {
297
- source = `service-key: ${config.mcpDestination}`;
298
- }
299
- else if (config.envFile) {
300
- source = config.envFile;
301
- }
302
- console.error((0, utils_1.formatAuthConfigForDisplay)(displayConfig, source));
424
+ if (config.mcpDestination) {
425
+ (0, auth_1.assertDestinationName)(config.mcpDestination, '--mcp');
303
426
  }
427
+ await checkAndSummarise(factory, destination, config, deps.stderr);
304
428
  }
305
429
  catch (error) {
306
- // Don't fail startup if we can't display config
307
- console.error(`[MCP] Warning: Could not display auth config: ${error instanceof Error ? error.message : String(error)}`);
430
+ deps.stderr(`[MCP] ${startupWords(error, destination)}`);
431
+ deps.exit(1);
432
+ return;
308
433
  }
309
434
  }
310
- else if (config.envFile || config.mcpDestination) {
311
- // Broker not created but config was expected
312
- console.error(`[MCP] Warning: Auth broker not initialized. Config source: ${config.envFile || config.mcpDestination}`);
313
- }
314
435
  if (config.transport === 'stdio') {
315
- // For .env file, use 'default' broker; for --mcp, use specified destination
316
- const configuredBrokerKey = config.mcpDestination ?? (config.envFile ? 'default' : undefined);
317
- const configuredBroker = configuredBrokerKey
318
- ? await authBrokerFactory.getOrCreateAuthBroker(configuredBrokerKey)
319
- : undefined;
320
- let broker;
321
- let brokerKey;
322
- if (configuredBroker) {
323
- broker = configuredBroker;
324
- brokerKey = configuredBrokerKey;
436
+ let destinations = factory;
437
+ let served;
438
+ if (destination) {
439
+ served = destination;
325
440
  }
326
441
  else {
327
442
  // Inspection-only mode: no connection parameters provided
328
- const { MockAbapConnection } = await import('@mcp-abap-adt/lib/embeddable');
329
- const mockConnection = new MockAbapConnection();
330
- broker = {
331
- getSession: async () => ({
332
- connection: mockConnection,
333
- client: {},
334
- config: { url: 'http://mock', authType: 'basic' },
335
- getHeaders: () => ({}),
336
- }),
337
- getConnectionConfig: async () => ({
338
- serviceUrl: 'http://mock',
339
- authType: 'basic',
340
- username: 'mock',
341
- password: 'mock',
342
- }),
343
- getToken: async () => undefined,
344
- };
345
- brokerKey = 'mock';
346
- console.error('[MCP] Starting in inspection-only mode (no connection parameters).');
347
- console.error('[MCP] To connect to SAP system, use --mcp=<destination> or --env-path=<path>');
443
+ destinations = (0, StdioServer_js_1.inspectionOnlyDestinations)();
444
+ served = 'mock';
445
+ deps.stderr('[MCP] Starting in inspection-only mode (no connection parameters).');
446
+ deps.stderr('[MCP] To connect to SAP system, use --mcp=<destination> or --env-path=<path>');
348
447
  }
349
- const server = new StdioServer_js_1.StdioServer(handlersRegistry, broker, {
448
+ const server = new StdioServer_js_1.StdioServer(handlersRegistry, destinations, {
449
+ version: options.version,
350
450
  logger: loggerForTransport,
351
451
  });
352
452
  activeServer = server;
353
- await server.start(brokerKey);
453
+ // Under stdio a signal is not the end of input: the factory's gate holds.
454
+ (0, shutdown_js_1.installShutdown)({
455
+ factory,
456
+ servers: [],
457
+ onStdinEnd: true,
458
+ exit: deps.exit,
459
+ stderr: deps.stderr,
460
+ processLike: deps.processLike,
461
+ });
462
+ await server.start(served);
354
463
  return;
355
464
  }
356
465
  if (config.transport === 'sse') {
357
- const server = new SseServer_js_1.SseServer(handlersRegistry, authBrokerFactory, {
466
+ const server = new SseServer_js_1.SseServer(handlersRegistry, factory, {
467
+ version: options.version,
358
468
  host: config.host,
359
469
  port: config.port,
360
470
  ssePath: config.ssePath,
361
471
  postPath: config.postPath,
362
- defaultDestination: config.mcpDestination ?? (config.envFile ? 'default' : undefined),
472
+ defaultDestination: destination,
363
473
  logger: loggerForTransport,
364
474
  tls: config.tls,
365
475
  allowDestinationHeader: config.allowDestinationHeader,
@@ -368,16 +478,24 @@ async function main(options = {}) {
368
478
  enableDnsRebindingProtection: config.enableDnsRebindingProtection,
369
479
  });
370
480
  activeServer = server;
481
+ (0, shutdown_js_1.installShutdown)({
482
+ factory,
483
+ servers: [{ close: () => server.stop() }],
484
+ exit: deps.exit,
485
+ stderr: deps.stderr,
486
+ processLike: deps.processLike,
487
+ });
371
488
  await server.start();
372
489
  return;
373
490
  }
374
491
  // http
375
- const server = new StreamableHttpServer_js_1.StreamableHttpServer(handlersRegistry, authBrokerFactory, {
492
+ const server = new StreamableHttpServer_js_1.StreamableHttpServer(handlersRegistry, factory, {
493
+ version: options.version,
376
494
  host: config.host,
377
495
  port: config.port,
378
496
  enableJsonResponse: config.httpJsonResponse,
379
497
  path: config.httpPath,
380
- defaultDestination: config.mcpDestination ?? (config.envFile ? 'default' : undefined),
498
+ defaultDestination: destination,
381
499
  logger: loggerForTransport,
382
500
  tls: config.tls,
383
501
  allowDestinationHeader: config.allowDestinationHeader,
@@ -386,6 +504,13 @@ async function main(options = {}) {
386
504
  enableDnsRebindingProtection: config.enableDnsRebindingProtection,
387
505
  });
388
506
  activeServer = server;
507
+ (0, shutdown_js_1.installShutdown)({
508
+ factory,
509
+ servers: [{ close: () => server.stop() }],
510
+ exit: deps.exit,
511
+ stderr: deps.stderr,
512
+ processLike: deps.processLike,
513
+ });
389
514
  await server.start();
390
515
  }
391
516
  // Run only when this module is the program. The bin calls `main()` itself, and a