@mcp-abap-adt/core 18.1.0 → 19.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.
Files changed (131) hide show
  1. package/README.md +26 -5
  2. package/bin/mcp-abap-adt.js +15 -15
  3. package/dist/StdioServer.d.ts +68 -14
  4. package/dist/StdioServer.d.ts.map +1 -1
  5. package/dist/StdioServer.js +101 -31
  6. package/dist/StdioServer.js.map +1 -1
  7. package/dist/auth/IAuthBrokerFactory.d.ts +62 -0
  8. package/dist/auth/IAuthBrokerFactory.d.ts.map +1 -0
  9. package/dist/auth/IAuthBrokerFactory.js +8 -0
  10. package/dist/auth/IAuthBrokerFactory.js.map +1 -0
  11. package/dist/auth/IAuthBrokerFactoryConfig.d.ts +90 -0
  12. package/dist/auth/IAuthBrokerFactoryConfig.d.ts.map +1 -0
  13. package/dist/auth/IAuthBrokerFactoryConfig.js +8 -0
  14. package/dist/auth/IAuthBrokerFactoryConfig.js.map +1 -0
  15. package/dist/auth/brokerFactory.d.ts +93 -0
  16. package/dist/auth/brokerFactory.d.ts.map +1 -0
  17. package/dist/auth/brokerFactory.js +341 -0
  18. package/dist/auth/brokerFactory.js.map +1 -0
  19. package/dist/auth/browser.d.ts +60 -0
  20. package/dist/auth/browser.d.ts.map +1 -0
  21. package/dist/auth/browser.js +116 -0
  22. package/dist/auth/browser.js.map +1 -0
  23. package/dist/auth/countedProvider.d.ts +43 -0
  24. package/dist/auth/countedProvider.d.ts.map +1 -0
  25. package/dist/auth/countedProvider.js +105 -0
  26. package/dist/auth/countedProvider.js.map +1 -0
  27. package/dist/auth/destinationFailure.d.ts +69 -0
  28. package/dist/auth/destinationFailure.d.ts.map +1 -0
  29. package/dist/auth/destinationFailure.js +183 -0
  30. package/dist/auth/destinationFailure.js.map +1 -0
  31. package/dist/auth/destinationStores.d.ts +55 -0
  32. package/dist/auth/destinationStores.d.ts.map +1 -0
  33. package/dist/auth/destinationStores.js +158 -0
  34. package/dist/auth/destinationStores.js.map +1 -0
  35. package/dist/auth/handlers/basic.d.ts +3 -0
  36. package/dist/auth/handlers/basic.d.ts.map +1 -0
  37. package/dist/auth/handlers/basic.js +8 -0
  38. package/dist/auth/handlers/basic.js.map +1 -0
  39. package/dist/auth/handlers/index.d.ts +15 -0
  40. package/dist/auth/handlers/index.d.ts.map +1 -0
  41. package/dist/auth/handlers/index.js +32 -0
  42. package/dist/auth/handlers/index.js.map +1 -0
  43. package/dist/auth/handlers/jwtAuthorizationCode.d.ts +8 -0
  44. package/dist/auth/handlers/jwtAuthorizationCode.d.ts.map +1 -0
  45. package/dist/auth/handlers/jwtAuthorizationCode.js +32 -0
  46. package/dist/auth/handlers/jwtAuthorizationCode.js.map +1 -0
  47. package/dist/auth/handlers/snc.d.ts +3 -0
  48. package/dist/auth/handlers/snc.d.ts.map +1 -0
  49. package/dist/auth/handlers/snc.js +14 -0
  50. package/dist/auth/handlers/snc.js.map +1 -0
  51. package/dist/auth/handlers/types.d.ts +30 -0
  52. package/dist/auth/handlers/types.d.ts.map +1 -0
  53. package/dist/auth/handlers/types.js +3 -0
  54. package/dist/auth/handlers/types.js.map +1 -0
  55. package/dist/auth/index.d.ts +15 -0
  56. package/dist/auth/index.d.ts.map +1 -0
  57. package/dist/auth/index.js +38 -0
  58. package/dist/auth/index.js.map +1 -0
  59. package/dist/auth/serverLogin.d.ts +75 -0
  60. package/dist/auth/serverLogin.d.ts.map +1 -0
  61. package/dist/auth/serverLogin.js +138 -0
  62. package/dist/auth/serverLogin.js.map +1 -0
  63. package/dist/auth/serverSentences.d.ts +39 -0
  64. package/dist/auth/serverSentences.d.ts.map +1 -0
  65. package/dist/auth/serverSentences.js +49 -0
  66. package/dist/auth/serverSentences.js.map +1 -0
  67. package/dist/auth/vocabulary.d.ts +28 -0
  68. package/dist/auth/vocabulary.d.ts.map +1 -0
  69. package/dist/auth/vocabulary.js +67 -0
  70. package/dist/auth/vocabulary.js.map +1 -0
  71. package/dist/config/coreParameters.d.ts +125 -0
  72. package/dist/config/coreParameters.d.ts.map +1 -0
  73. package/dist/config/coreParameters.js +331 -0
  74. package/dist/config/coreParameters.js.map +1 -0
  75. package/dist/config/envFileContext.d.ts +26 -0
  76. package/dist/config/envFileContext.d.ts.map +1 -0
  77. package/dist/config/envFileContext.js +90 -0
  78. package/dist/config/envFileContext.js.map +1 -0
  79. package/dist/config/envResolver.d.ts +6 -0
  80. package/dist/config/envResolver.d.ts.map +1 -0
  81. package/dist/config/envResolver.js +81 -0
  82. package/dist/config/envResolver.js.map +1 -0
  83. package/dist/config/platformPaths.d.ts +28 -0
  84. package/dist/config/platformPaths.d.ts.map +1 -0
  85. package/dist/config/platformPaths.js +152 -0
  86. package/dist/config/platformPaths.js.map +1 -0
  87. package/dist/destinationSource.d.ts +26 -0
  88. package/dist/destinationSource.d.ts.map +1 -0
  89. package/dist/destinationSource.js +43 -0
  90. package/dist/destinationSource.js.map +1 -0
  91. package/dist/index.d.ts +9 -5
  92. package/dist/index.d.ts.map +1 -1
  93. package/dist/index.js +16 -11
  94. package/dist/index.js.map +1 -1
  95. package/dist/launcher.d.ts +102 -59
  96. package/dist/launcher.d.ts.map +1 -1
  97. package/dist/launcher.js +419 -286
  98. package/dist/launcher.js.map +1 -1
  99. package/dist/shutdown.d.ts +76 -24
  100. package/dist/shutdown.d.ts.map +1 -1
  101. package/dist/shutdown.js +114 -57
  102. package/dist/shutdown.js.map +1 -1
  103. package/package.json +22 -39
  104. package/dist/InstancePool.d.ts +0 -87
  105. package/dist/InstancePool.d.ts.map +0 -1
  106. package/dist/InstancePool.js +0 -240
  107. package/dist/InstancePool.js.map +0 -1
  108. package/dist/SseServer.d.ts +0 -144
  109. package/dist/SseServer.d.ts.map +0 -1
  110. package/dist/SseServer.js +0 -359
  111. package/dist/SseServer.js.map +0 -1
  112. package/dist/StreamableHttpServer.d.ts +0 -143
  113. package/dist/StreamableHttpServer.d.ts.map +0 -1
  114. package/dist/StreamableHttpServer.js +0 -349
  115. package/dist/StreamableHttpServer.js.map +0 -1
  116. package/dist/destinationRequest.d.ts +0 -38
  117. package/dist/destinationRequest.d.ts.map +0 -1
  118. package/dist/destinationRequest.js +0 -85
  119. package/dist/destinationRequest.js.map +0 -1
  120. package/dist/dnsRebindingProtection.d.ts +0 -21
  121. package/dist/dnsRebindingProtection.d.ts.map +0 -1
  122. package/dist/dnsRebindingProtection.js +0 -45
  123. package/dist/dnsRebindingProtection.js.map +0 -1
  124. package/dist/stateClose.d.ts +0 -8
  125. package/dist/stateClose.d.ts.map +0 -1
  126. package/dist/stateClose.js +0 -14
  127. package/dist/stateClose.js.map +0 -1
  128. package/dist/tlsUtils.d.ts +0 -19
  129. package/dist/tlsUtils.d.ts.map +0 -1
  130. package/dist/tlsUtils.js +0 -77
  131. package/dist/tlsUtils.js.map +0 -1
package/dist/launcher.js CHANGED
@@ -1,23 +1,33 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.stateLoggerForTransport = void 0;
3
+ exports.stateLoggerForTransport = exports.AUTH_DEBUG_WARNING = void 0;
4
+ exports.coreHelp = coreHelp;
4
5
  exports.main = main;
5
6
  exports.effectiveConnectionType = effectiveConnectionType;
7
+ exports.effectiveMessageServer = effectiveMessageServer;
6
8
  exports.effectiveSystemType = effectiveSystemType;
7
- exports.promptsOnStderr = promptsOnStderr;
8
9
  exports.factoryConfigFrom = factoryConfigFrom;
10
+ exports.startLookupFailedWords = startLookupFailedWords;
11
+ exports.startSystemTypeRequiredWords = startSystemTypeRequiredWords;
12
+ exports.startCloudWithoutSystemInformationWords = startCloudWithoutSystemInformationWords;
13
+ exports.startSystemUserUnknownWords = startSystemUserUnknownWords;
14
+ exports.startConnectionWords = startConnectionWords;
9
15
  exports.launch = launch;
16
+ exports.launcherFailedLine = launcherFailedLine;
17
+ const auth_errors_1 = require("@mcp-abap-adt/auth-errors");
18
+ const background_runs_memory_1 = require("@mcp-abap-adt/background-runs-memory");
10
19
  const auth_1 = require("@mcp-abap-adt/lib/auth");
11
20
  const config_1 = require("@mcp-abap-adt/lib/config");
12
- const handlers_1 = require("@mcp-abap-adt/lib/handlers");
21
+ const embeddable_1 = require("@mcp-abap-adt/lib/embeddable");
13
22
  const state_1 = require("@mcp-abap-adt/lib/state");
23
+ const tool_set_1 = require("@mcp-abap-adt/lib/tool-set");
14
24
  const utils_1 = require("@mcp-abap-adt/lib/utils");
15
- const coreVersion_js_1 = require("./coreVersion.js");
16
- const SseServer_js_1 = require("./SseServer.js");
25
+ const auth_2 = require("./auth");
26
+ const coreParameters_1 = require("./config/coreParameters");
27
+ const envFileContext_1 = require("./config/envFileContext");
28
+ const platformPaths_1 = require("./config/platformPaths");
17
29
  const StdioServer_js_1 = require("./StdioServer.js");
18
- const StreamableHttpServer_js_1 = require("./StreamableHttpServer.js");
19
30
  const shutdown_js_1 = require("./shutdown.js");
20
- const stateClose_js_1 = require("./stateClose.js");
21
31
  const stderrLogger = {
22
32
  info: (...args) => console.error(...args),
23
33
  warn: (...args) => console.error(...args),
@@ -31,6 +41,8 @@ const silentLogger = {
31
41
  debug: () => { },
32
42
  };
33
43
  const loggerForTransport = process.env.DEBUG_AUTH_LOG === 'true' ? stderrLogger : silentLogger;
44
+ /** The one line `--auth-debug` prints at the start. */
45
+ exports.AUTH_DEBUG_WARNING = "[MCP] --auth-debug is on: a refused token request's debug line on stderr names the first and last four characters of each secret it sent";
34
46
  /**
35
47
  * The state's lifecycle lines — the idle bound's end of a state, a cleanup
36
48
  * that failed — on stderr whatever DEBUG_AUTH_LOG says: they are what an
@@ -39,32 +51,6 @@ const loggerForTransport = process.env.DEBUG_AUTH_LOG === 'true' ? stderrLogger
39
51
  exports.stateLoggerForTransport = state_1.stderrStateLogger;
40
52
  // Keep strong reference to running server instance to avoid premature GC/exit
41
53
  let activeServer;
42
- function hasArg(name) {
43
- return process.argv.includes(name);
44
- }
45
- /**
46
- * This package's own version, read from this package's own manifest.
47
- *
48
- * **It was two levels up, and that only works inside the repository.** From
49
- * `server/dist/` two steps reach the repo root, whose `package.json` is
50
- * `@mcp-abap-adt/lib` — so `--version` printed the LIBRARY's version, and only
51
- * because a checkout happens to have a manifest there. From an installed
52
- * package the same two steps land on `node_modules/@mcp-abap-adt/`, which is the
53
- * scope DIRECTORY and never has a `package.json`: every `mcp-abap-adt --version`
54
- * from npm died with `ENOENT … node_modules/@mcp-abap-adt/package.json`.
55
- * Measured on 13.0.0 by installing the published tarball into an empty directory
56
- * — the check `bin-smoke.test.ts` now performs, because the three other bins in
57
- * this family were fixed for the same class of defect one release earlier and
58
- * nothing here would have caught ours.
59
- *
60
- * One step up is `server/` in a checkout and the package root when installed,
61
- * and in both it is `@mcp-abap-adt/core`'s manifest — which is what this CLI
62
- * should answer with.
63
- */
64
- function showVersion() {
65
- console.log(coreVersion_js_1.CORE_VERSION);
66
- process.exit(0);
67
- }
68
54
  /**
69
55
  * Additional help sections specific to v2 server
70
56
  */
@@ -72,20 +58,14 @@ const V2_HELP_SECTIONS = `
72
58
  ENVIRONMENT VARIABLES:
73
59
 
74
60
  MCP Server Configuration:
75
- MCP_TRANSPORT Transport type: stdio|http|sse (default: stdio)
76
- MCP_HTTP_HOST HTTP server host (default: 127.0.0.1)
77
- MCP_HTTP_PORT HTTP server port (default: 3000)
78
- MCP_SSE_HOST SSE server host (default: 127.0.0.1)
79
- MCP_SSE_PORT SSE server port (default: 3001)
80
61
  MCP_ENV_PATH Explicit .env file path (same as --env-path)
81
62
  MCP_UNSAFE Write named destinations' sessions to disk (true|false)
82
- MCP_BROWSER Browser for a login: chrome|edge|firefox|system|headless|none
63
+ MCP_BROWSER Browser for a login: system|auto|chrome|edge|firefox|none|headless
64
+ MCP_BROWSER_PROGRAM The program that opens the login URL (excludes MCP_BROWSER)
65
+ MCP_RENEWAL refresh-then-login (default) | refresh-only (never a login)
83
66
  MCP_BROWSER_AUTH_PORT Login callback port, 1-65535 (default: 61001)
84
67
  MCP_STATE_IDLE_MINUTES Held state (a debug session) ends after this many minutes
85
68
  without a tool call: at least 30 (default: 30)
86
- MCP_TLS_CERT Path to TLS certificate file (PEM)
87
- MCP_TLS_KEY Path to TLS private key file (PEM)
88
- MCP_TLS_CA Path to TLS CA certificate file (PEM, optional)
89
69
 
90
70
  Auth-Broker:
91
71
  DEBUG_AUTH_LOG Enable debug logging for auth-broker (true|false)
@@ -98,11 +78,13 @@ ENVIRONMENT VARIABLES:
98
78
  DEBUG_CONNECTION_MANAGER Enable connection manager debug logging (true|false)
99
79
  HANDLER_LOG_SILENT Disable all handler logs (true|false)
100
80
 
101
- AUTHENTICATIONS (exactly four; a .env or service key stating another is refused):
81
+ AUTHENTICATIONS (exactly three; a .env or service key stating another is refused):
102
82
  basic SAP_AUTH_TYPE=basic user and password, HTTP or RFC
103
83
  snc SAP_AUTH_TYPE=snc RFC only, no user, no password
104
84
  jwt SAP_AUTH_TYPE=jwt, SAP_GRANT_TYPE=authorization_code browser login
105
- jwt SAP_AUTH_TYPE=jwt, SAP_GRANT_TYPE=none a token you hold
85
+ A token you hold (SAP_GRANT_TYPE=none) is not served over stdio: send it in the
86
+ x-sap-jwt-token header to mcp-abap-adt-http or mcp-abap-adt-sse, or create the
87
+ session with mcp-auth.
106
88
 
107
89
  SAP CONNECTION (.env file; secrets and the session live here, never in YAML):
108
90
 
@@ -114,9 +96,10 @@ SAP CONNECTION (.env file; secrets and the session live here, never in YAML):
114
96
  Precedence: --connection-type, then the environment
115
97
  (this file joins it, never over a value set), then YAML
116
98
  SAP_SYSTEM_TYPE SAP system type: cloud | onprem | legacy (same as --system-type)
117
- Tools offered: default cloud (e.g. Programs need onprem)
118
- Connector and master-system lookup: default cloud for a
119
- jwt destination, else onprem — never guessed from the URL
99
+ Required for a destination: no default, never guessed (not
100
+ from the auth type, not from the URL); it decides the tools
101
+ offered (e.g. Programs need onprem), the connector and how
102
+ the system's answers are read
120
103
  SAP_USERNAME SAP username (required for basic auth)
121
104
  SAP_PASSWORD SAP password (required for basic auth)
122
105
  SAP_LANGUAGE SAP language (optional, e.g., EN, DE)
@@ -127,8 +110,8 @@ SAP CONNECTION (.env file; secrets and the session live here, never in YAML):
127
110
  SAP_SNC_QOP, SAP_SNC_LIB, SAP_SNC_MYNAME Optional
128
111
 
129
112
  JWT/OAuth2 Authentication (SAP_GRANT_TYPE is required with jwt):
130
- SAP_GRANT_TYPE authorization_code (browser login) | none (a token you hold)
131
- SAP_JWT_TOKEN JWT token (with SAP_GRANT_TYPE=none)
113
+ SAP_GRANT_TYPE authorization_code (browser login)
114
+ SAP_JWT_TOKEN The session's token (written by mcp-auth or the server)
132
115
  SAP_REFRESH_TOKEN Refresh token (the server stores the one it obtains)
133
116
  SAP_UAA_URL UAA URL for OAuth2
134
117
  SAP_UAA_CLIENT_ID UAA Client ID
@@ -142,82 +125,120 @@ SAP CONNECTION (.env file; secrets and the session live here, never in YAML):
142
125
  SAP_USERNAME SAP username
143
126
  SAP_PASSWORD SAP password
144
127
  SAP_CLIENT SAP client number
128
+ Through a message server and a logon group (load-balanced logon); each also
129
+ --mshost, --msserv, --sysid, --group, --saprouter, or the YAML key of that name.
130
+ Precedence: the CLI, then the environment (this file joins it), then YAML:
131
+ SAP_MSHOST Message server host. With it, the URL gives no RFC host
132
+ and no system number (SAP_SYSNR is not read)
133
+ SAP_MSSERV Message server service (name or port)
134
+ SAP_SYSID System id; SAP_MSSERV or SAP_SYSID is required with
135
+ SAP_MSHOST (refused naming both otherwise)
136
+ SAP_GROUP Logon group (connection default: PUBLIC)
137
+ SAP_SAPROUTER SAProuter string, with either addressing
145
138
  Requires: SAP NW RFC SDK + @mcp-abap-adt/sap-rfc-lite (an optional dependency,
146
139
  compiled by npm install: SAPNWRFC_HOME and a C++ toolchain must be there before it;
147
140
  npm ls -g @mcp-abap-adt/sap-rfc-lite shows (empty) when it was left out)
148
141
 
149
- System Context (per request, first found wins; reads are unaffected):
142
+ System Context (first found wins; reads are unaffected):
150
143
  SAP_RESPONSIBLE Responsible person of created objects, always sent. First
151
- found: the tool's argument; x-sap-responsible; SAP_RESPONSIBLE
152
- in the destination's own .env (--env / --env-path file, or
144
+ found: the tool's argument; SAP_RESPONSIBLE in the
145
+ destination's own .env (--env / --env-path file, or
153
146
  sessions/<destination>.env), then in the environment. Else
154
147
  the login: on-premise the destination's SAP_USERNAME, the
155
- x-sap-login of an x-sap-url connection, the environment's
156
- SAP_USERNAME; on a cloud system only the system's user. A create
157
- that finds none is refused (SNC, a token), a message class
158
- included.
148
+ environment's SAP_USERNAME; on a cloud system only the
149
+ system's user. A create that finds none is refused (SNC, a
150
+ token), a message class included.
159
151
  SAP_MASTER_SYSTEM Master system of created objects (no tool takes it as an
160
- argument). First found: x-sap-master-system; the destination's
161
- .env; the environment; on a cloud system, the system id.
152
+ argument). First found: the destination's .env; the
153
+ environment; on a cloud system, the system id.
162
154
  Otherwise left out of the request, never refused
163
155
  The environment is read once: later changes are not picked up
164
- SAP_DEBUG_TERMINAL_ID The debugger's terminal id and IDE id (with --exposition=...,debug),
165
- SAP_DEBUG_IDE_ID each on its own. First found: x-sap-debug-terminal-id /
166
- x-sap-debug-ide-id; the destination's .env; the environment.
167
- Else random per instance. A shared IDE id shares the user's
168
- catches without the system's listener conflict
156
+ SAP_DEBUG_TERMINAL_ID The debugger's terminal id and IDE id (where the debugger is served),
157
+ SAP_DEBUG_IDE_ID each on its own. First found: the destination's .env; the
158
+ environment. Else random per instance. A shared IDE id shares
159
+ the user's catches without the system's listener conflict
169
160
  SAP_DEBUG_BREAKPOINT_CONFLICT replace (default) or refuse-if-held: whether a take-over of
170
161
  the debugger, and every later change of its breakpoints, first
171
162
  asks if another debugger listens for the same SAP user, and
172
163
  refuses if so (a start without take-over always asks). First
173
- found: x-sap-debug-breakpoint-conflict; the destination's .env;
174
- the environment
164
+ found: the destination's .env; the environment
175
165
 
176
- HTTP/SSE Headers (System Context; SSE: the session's opening request):
177
- x-sap-master-system Master system for this request (wins over the .env and env)
178
- x-sap-responsible Responsible for this request (wins over the .env and env)
179
- x-sap-login With x-sap-url (on-premise): the login, the responsible when
180
- none is stated; on a destination request it is not read
181
- x-sap-language Master/original language for created objects (overrides SAP_LANGUAGE)
182
- x-sap-debug-terminal-id The debugger's terminal id (wins over the .env and env)
183
- x-sap-debug-ide-id The debugger's IDE id (wins over the .env and env)
184
- x-sap-debug-breakpoint-conflict The debugger's breakpoint conflict (wins over the .env and env)
166
+ Streamable HTTP and SSE are served by mcp-abap-adt-http (@mcp-abap-adt/http) and
167
+ mcp-abap-adt-sse (@mcp-abap-adt/sse), with credentials from each request's x-sap-* headers.
185
168
 
186
169
  GENERATING A .ENV:
187
170
  Install the CLI: npm install -g @mcp-abap-adt/auth-broker-cli
188
- Generate .env: mcp-auth generate-env --grant authorization_code (mcp-auth --help lists the other flags)
171
+ Generate .env: mcp-auth --service-key <key.json> --output <file.env> --type abap|xsuaa
172
+ or: mcp-auth --destination <name> --type abap|xsuaa (mcp-auth --help lists the rest)
189
173
  A jwt .env must state SAP_GRANT_TYPE.
190
174
  `;
191
- function showHelp(options = {}) {
192
- console.error(config_1.ServerConfigManager.generateHelp(V2_HELP_SECTIONS, {
193
- program: options.program,
194
- // A sibling command documents its OWN exposition vocabulary, not this one's.
195
- expositionSection: options.helpExposition,
196
- }));
175
+ /** The examples of core's help: stdio only, under the command's own name. */
176
+ function examples(program) {
177
+ return `
178
+ EXAMPLES:
179
+ # A named destination (for MCP clients)
180
+ ${program} --mcp=TRIAL
181
+
182
+ # An env file by destination name, from the sessions store
183
+ ${program} --env=trial
184
+
185
+ # An explicit env file (a .env in the working directory is read only when named)
186
+ ${program} --env-path=./.env
187
+
188
+ # RFC connection (any system with SAP NW RFC SDK)
189
+ # (or SAP_CONNECTION_TYPE=rfc in the .env file)
190
+ ${program} --env-path=my-system.env --connection-type=rfc
191
+
192
+ # RFC through a message server and a logon group
193
+ ${program} --env-path=my-system.env --connection-type=rfc --mshost=<host> --sysid=<SID> --group=<group>
194
+
195
+ # Explicit system type (required: onprem, cloud or legacy)
196
+ ${program} --env-path=<system>.env --system-type=onprem
197
+
198
+ # A YAML config file (a template is written when it does not exist)
199
+ ${program} --conf=my-config.yaml
200
+ `;
197
201
  }
198
- async function main(options = {}) {
199
- // Check for --version first
200
- if (hasArg('--version') || hasArg('-v')) {
201
- showVersion();
202
- }
203
- // Check for --help
204
- if (hasArg('--help') || hasArg('-h')) {
205
- showHelp(options);
206
- process.exit(0);
202
+ /**
203
+ * core's help: its own table (no HTTP or SSE option), the set's TOOLS
204
+ * section, the environment. A sibling command (`mcp-abap-adt-ro`,
205
+ * `mcp-abap-adt-compact`, `mcp-abap-adt-compact-ro`) passes its own set and
206
+ * name.
207
+ */
208
+ function coreHelp(options = {}) {
209
+ const toolSet = options.toolSet ?? tool_set_1.fullToolSet;
210
+ const program = options.program ?? 'mcp-abap-adt';
211
+ return (0, config_1.generateHelp)((0, coreParameters_1.coreParameters)(toolSet, program), {
212
+ description: ' MCP server for SAP ABAP systems via ADT (ABAP Development Tools), over stdio:\n' +
213
+ ' one destination through the auth broker. Streamable HTTP is mcp-abap-adt-http,\n' +
214
+ ' SSE mcp-abap-adt-sse; a binary is its transport.',
215
+ sections: [toolSet.toolsHelp('stdio'), V2_HELP_SECTIONS, examples(program)],
216
+ });
217
+ }
218
+ async function main(options, edges = (0, config_1.processEdges)()) {
219
+ const { argv, stderr, exit } = edges;
220
+ if ((0, config_1.answerVersionOrHelp)(edges, {
221
+ version: options.version,
222
+ help: () => coreHelp(options),
223
+ })) {
224
+ return;
207
225
  }
208
- // Use ServerConfigManager for all config parsing
209
- const configManager = new config_1.ServerConfigManager();
210
- const config = await configManager.getConfig();
226
+ // core's own table: an option of another binary, --transport, or the
227
+ // removed --exposition stops here.
228
+ const config = (0, config_1.readStartupConfig)((0, coreParameters_1.coreParameters)(options.toolSet, options.program), argv, process.env, { stderr, exit }, (args, env, yaml) => (0, coreParameters_1.readCoreConfig)(args, env, yaml, options.toolSet));
229
+ if (config === undefined)
230
+ return;
211
231
  await launch(config, options, {
212
232
  browserStrategy: auth_1.browserCallbackStrategy,
213
- stderr: (line) => process.stderr.write(`${line}\n`),
214
- exit: (code) => process.exit(code),
215
- processLike: process,
233
+ stderr,
234
+ exit,
235
+ processLike: edges.processLike,
236
+ ...(edges.transport !== undefined && { transport: edges.transport }),
216
237
  });
217
238
  }
218
239
  /**
219
240
  * The env file and the parameter it came from. `envFilePath` is
220
- * `IServerConfig`'s alias of `envFile`; ServerConfigManager sets both and
241
+ * `CoreConfig`'s alias of `envFile`; `readCoreConfig` sets both and
221
242
  * states the source. A config made by hand names the field it set.
222
243
  */
223
244
  function envFileOf(config) {
@@ -231,10 +252,19 @@ function envFileOf(config) {
231
252
  return {
232
253
  envFile: {
233
254
  path: config[field],
234
- source: config.envFileSource ?? `IServerConfig.${field}`,
255
+ source: config.envFileSource ?? `CoreConfig.${field}`,
235
256
  },
236
257
  };
237
258
  }
259
+ /** A start the launcher refuses, in words that name parameters only. */
260
+ class LauncherRefusal extends Error {
261
+ words;
262
+ constructor(words) {
263
+ super(words);
264
+ this.name = 'LauncherRefusal';
265
+ this.words = words;
266
+ }
267
+ }
238
268
  /**
239
269
  * A parameter the env file may state: the CLI, then the process environment
240
270
  * — which by now holds what the env file states, never over a value set
@@ -255,14 +285,52 @@ function effectiveFromEnvironment(value, source, key, values, env) {
255
285
  const words = values.length === 2
256
286
  ? values.join(' or ')
257
287
  : `${values.slice(0, -1).join(', ')} or ${values[values.length - 1]}`;
258
- throw new Error(`${key} (environment or env file) must be ${words}`);
288
+ throw new LauncherRefusal(`${key} (environment or env file) must be ${words}`);
259
289
  }
260
290
  return raw;
261
291
  }
292
+ /** `config` without its message-server fields: they are read again after the env file. */
293
+ function withoutMessageServer(config) {
294
+ const rest = { ...config };
295
+ for (const field of config_1.MESSAGE_SERVER_FIELDS)
296
+ delete rest[field];
297
+ return rest;
298
+ }
262
299
  /** The connection type: see {@link effectiveFromEnvironment}. */
263
300
  function effectiveConnectionType(config, env) {
264
301
  return effectiveFromEnvironment(config.connectionType, config.connectionTypeSource, 'SAP_CONNECTION_TYPE', ['http', 'rfc'], env);
265
302
  }
303
+ /**
304
+ * The message server's fields (RFC, connection 18), each as
305
+ * {@link effectiveFromEnvironment} reads the connection type: the CLI, then
306
+ * the process environment — which by now holds what the env file states,
307
+ * never over a value set before — then YAML. Taken as given, trimmed; no
308
+ * default, no check: connection refuses what it cannot dial.
309
+ */
310
+ function effectiveMessageServer(config, env) {
311
+ const out = {};
312
+ for (const field of config_1.MESSAGE_SERVER_FIELDS) {
313
+ const value = config[field];
314
+ const source = config.messageServerSource?.[field];
315
+ const fromCli = value !== undefined && (source?.startsWith('--') ?? true);
316
+ const stated = fromCli
317
+ ? value
318
+ : env[config_1.MESSAGE_SERVER_ENV[field]]?.trim() || value;
319
+ if (stated)
320
+ out[field] = stated;
321
+ }
322
+ return out;
323
+ }
324
+ /** The message-server fields set on `config`, as `SapConfig` takes them. */
325
+ function messageServerOf(config) {
326
+ const out = {};
327
+ for (const field of config_1.MESSAGE_SERVER_FIELDS) {
328
+ const value = config[field];
329
+ if (value !== undefined)
330
+ out[field] = value;
331
+ }
332
+ return out;
333
+ }
266
334
  /**
267
335
  * The system type: see {@link effectiveFromEnvironment}. The parser no longer
268
336
  * writes it into the environment, where it used to sit before the env file
@@ -272,42 +340,10 @@ function effectiveSystemType(config, env) {
272
340
  return effectiveFromEnvironment(config.systemType, config.systemTypeSource, 'SAP_SYSTEM_TYPE', ['onprem', 'cloud', 'legacy'], env);
273
341
  }
274
342
  /**
275
- * The login strategy, with prompts that reach the user. auth-providers'
276
- * strategy speaks to the user through the request's logger — the URL to open
277
- * under `--browser=none`/`headless`, or `auto` when it could not open one — and
278
- * that logger is the broker's, silent unless DEBUG_AUTH_LOG is set. A prompt
279
- * the user cannot see makes the login impassable: it times out.
280
- *
281
- * So the strategy gets its own logger: `info`, the level the strategy prompts
282
- * at, is a line on stderr always; `warn`, `error` and `debug` stay the
283
- * broker's — diagnostics, gated, and they may quote an error's message (H4).
284
- * Not "no logger" (auth-providers then writes prompts to stderr itself): that
285
- * would also drop those diagnostics under DEBUG_AUTH_LOG. Never stdout (H3).
286
- */
287
- function promptsOnStderr(browserStrategy, stderr, diagnostics) {
288
- const logger = {
289
- info: (message) => stderr(message),
290
- warn: (message, meta) => diagnostics.warn(message, meta),
291
- error: (message, meta) => diagnostics.error(message, meta),
292
- debug: (message, meta) => diagnostics.debug(message, meta),
293
- };
294
- return (options) => {
295
- const strategy = browserStrategy(options);
296
- const prompting = {
297
- authorize: (request) => strategy.authorize({ ...request, logger }),
298
- };
299
- if (strategy.dispose) {
300
- prompting.dispose = () => strategy.dispose?.() ?? Promise.resolve();
301
- }
302
- return prompting;
303
- };
304
- }
305
- /** The browser of a login when none is given. */
306
- const DEFAULT_BROWSER = 'system';
307
- /**
308
- * The factory's configuration, read from the parameters alone. The callback
309
- * port is left to the strategy (61001) when none is given; the env file
310
- * carries the parameter it came from, as the user gave it.
343
+ * The factory's configuration, read from the parameters and the browser the
344
+ * launcher mapped (`browserFor`). The callback port is left to the strategy
345
+ * (61001) when none is given; the env file carries the parameter it came
346
+ * from, as the user gave it.
311
347
  */
312
348
  function factoryConfigFrom(config, collaborators) {
313
349
  return {
@@ -315,32 +351,116 @@ function factoryConfigFrom(config, collaborators) {
315
351
  ...(config.mcpDestination && { mcpDestination: config.mcpDestination }),
316
352
  ...(config.authBrokerPath && { authBrokerPath: config.authBrokerPath }),
317
353
  unsafe: config.unsafe ?? false,
318
- browser: config.browser ?? DEFAULT_BROWSER,
354
+ ...(collaborators.browser !== undefined && {
355
+ browser: collaborators.browser,
356
+ }),
357
+ ...(collaborators.browserUnavailable !== undefined && {
358
+ browserUnavailable: collaborators.browserUnavailable,
359
+ }),
319
360
  ...(config.browserAuthPort !== undefined && {
320
361
  browserAuthPort: config.browserAuthPort,
321
362
  }),
322
363
  ...(config.connectionType && { connectionType: config.connectionType }),
364
+ ...messageServerOf(config),
365
+ ...(config.renewal && { renewal: config.renewal }),
366
+ ...(config.authDebug === true && { authDebug: true }),
367
+ ...(config.loginTimeout !== undefined && {
368
+ loginTimeoutMs: config.loginTimeout * 1000,
369
+ loginTimeoutStated: (0, coreParameters_1.statedLoginTimeout)(config.loginTimeout, config.loginTimeoutSource),
370
+ }),
323
371
  browserStrategy: collaborators.browserStrategy,
372
+ promptLogger: collaborators.promptLogger,
324
373
  ...(collaborators.logger && { logger: collaborators.logger }),
325
374
  };
326
375
  }
327
376
  /**
328
- * The words a startup failure is reported in: the error's own vetted words
329
- * when the server knows them, else the destination and the error's class —
330
- * never its message, which may quote a file it could not parse (H4).
377
+ * The words a startup failure is reported in: what the failure reader makes
378
+ * of it (`destinationFailureWords`: the failure message, its hint, the server's
379
+ * sentence), else the destination and the error's class — never its
380
+ * message, which may quote a file it could not parse.
381
+ */
382
+ function startupWords(error, destination, factory, platform) {
383
+ return (0, auth_2.destinationFailureWords)(error, destination, {
384
+ platform,
385
+ sentenceFor: (e) => factory.sentenceFor(e),
386
+ });
387
+ }
388
+ /**
389
+ * The start's words for a system that gave no information where it must
390
+ * (ABAP Cloud): a problem of the ABAP system with a valid configuration.
391
+ */
392
+ function startLookupFailedWords(destination) {
393
+ return `Destination "${destination}": the ABAP system gave no session user and system id: systeminformation answered without them or with an error, a problem of the ABAP system with a valid configuration; the server did not start`;
394
+ }
395
+ /**
396
+ * The start's words for a destination whose system kind no parameter states.
397
+ */
398
+ function startSystemTypeRequiredWords(destination) {
399
+ return `Destination "${destination}": the SAP system type is required — set --system-type, SAP_SYSTEM_TYPE (the environment or the --env file) or system-type (YAML) to onprem, cloud or legacy; the server did not start`;
400
+ }
401
+ /**
402
+ * The start's words for an ABAP Cloud destination whose system has no
403
+ * systeminformation endpoint (`404`): the configuration is inconsistent.
404
+ */
405
+ function startCloudWithoutSystemInformationWords(destination) {
406
+ return `Destination "${destination}": the destination is stated as ABAP Cloud, but its system has no systeminformation endpoint, which every ABAP Cloud system has: the configuration is inconsistent; the server did not start`;
407
+ }
408
+ /**
409
+ * The start's words for an on-premise system that gave no information
410
+ * whose destination states no user.
411
+ */
412
+ function startSystemUserUnknownWords(destination) {
413
+ return `Destination "${destination}": the system gave no session user (systeminformation) and the destination states no user: set SAP_RESPONSIBLE or SAP_USERNAME in the destination or the environment, so the session user is known; the server did not start`;
414
+ }
415
+ /**
416
+ * The words the connection at start failed in: what the failure reader
417
+ * makes of it (a chain failure, the server's own refusal — a system lookup
418
+ * that failed — or the destination layer's), else the destination, the
419
+ * error's class and the status SAP answered — never its message.
331
420
  */
332
- function startupWords(error, destination) {
333
- return ((0, auth_1.describeAuthError)(error) ??
334
- `Destination "${destination}" cannot be read: ${(0, auth_1.errorClassOf)(error)}`);
421
+ function startConnectionWords(error, destination, factory, platform) {
422
+ const options = {
423
+ platform,
424
+ sentenceFor: (e) => factory.sentenceFor(e),
425
+ };
426
+ const read = (0, auth_2.destinationFailureOf)(error, { ...options, destination });
427
+ if (read?.error === 'system_lookup_failed') {
428
+ return startLookupFailedWords(destination);
429
+ }
430
+ if (read?.error === 'cloud_without_systeminformation') {
431
+ return startCloudWithoutSystemInformationWords(destination);
432
+ }
433
+ if (read?.error === 'system_user_unknown') {
434
+ return startSystemUserUnknownWords(destination);
435
+ }
436
+ if (read !== undefined) {
437
+ return (0, auth_2.destinationFailureWords)(error, destination, options);
438
+ }
439
+ // connection's refusal of an RFC address it cannot dial (a message server
440
+ // with neither msserv nor sysid): its own fixed words, as it came.
441
+ const address = (0, config_1.rfcAddressRefusalOf)(error);
442
+ if (address !== undefined) {
443
+ return `Destination "${destination}" could not be connected at start: ${address}`;
444
+ }
445
+ const sap = (0, embeddable_1.sapAnswerOf)(error);
446
+ return `Destination "${destination}" could not be connected at start: ${(0, auth_1.errorClassOf)(error)}${sap === undefined ? '' : `, SAP answered ${sap.status}`}`;
335
447
  }
336
448
  /**
337
- * The startup summary: the destination's settings, then what its stores
338
- * hold, masked as before (H4's one exception). The settings are read first
339
- * and their failure is the caller's: a destination that cannot be served
340
- * stops the start.
449
+ * The startup check, then the summary. The destination's settings are
450
+ * read and its provider is built — `getProvider(destination, { signal })`
451
+ * with the start's own signal, aborted once the check ends — so a
452
+ * destination the broker refuses stops the start; building sends nothing.
453
+ * Then what its stores hold, masked as before (H4's one exception).
341
454
  */
342
- async function checkAndSummarise(factory, destination, config, stderr) {
455
+ async function checkAndSummarise(factory, destination, config, stderr, platform) {
343
456
  const settings = await factory.settingsFor(destination);
457
+ const startup = new AbortController();
458
+ try {
459
+ await factory.getProvider(destination, { signal: startup.signal });
460
+ }
461
+ finally {
462
+ startup.abort();
463
+ }
344
464
  try {
345
465
  const broker = await factory.getBroker(destination);
346
466
  const connConfig = await broker.getConnectionConfig(destination);
@@ -371,20 +491,40 @@ async function checkAndSummarise(factory, destination, config, stderr) {
371
491
  }
372
492
  catch (error) {
373
493
  // The summary is information: it never stops a start the settings allowed.
374
- stderr(`[MCP] Warning: Could not display auth config: ${startupWords(error, destination)}`);
494
+ stderr(`[MCP] Warning: Could not display auth config: ${startupWords(error, destination, factory, platform)}`);
375
495
  }
376
496
  }
377
497
  /**
378
498
  * Everything after the parameters are read: the tool list, one factory, the
379
- * destination the process serves checked and summarised, the transport, and
380
- * the shutdown. A destination that cannot be served stops the start before
381
- * any transport does.
499
+ * destination the process serves checked and summarised, the shutdown, the
500
+ * connection born (`connectAtStart`: the destination's one leftover session
501
+ * taken up, or a logon — a browser login included — with the system
502
+ * information), and only then the transport. A destination that cannot be
503
+ * served, a logon or resume that fails, a system lookup that fails: each
504
+ * ends the process with exit `1` and the failure's words on stderr, before
505
+ * any transport opens.
506
+ *
507
+ * No exit and no rejection comes before the logoffs are answered: a start
508
+ * that fails after its logon exits `1` only once SAP answered the logoff
509
+ * (`logOffAtOnce`: every connection the process owns logged off, each
510
+ * logoff followed to its answer, no timer), and a launch that rejects — the
511
+ * bin's exit follows — rejects only then. SAP ends a security session only
512
+ * once it received the logoff whole.
382
513
  */
383
514
  async function launch(config, options, deps) {
515
+ try {
516
+ await launchStdio(config, options, deps);
517
+ }
518
+ catch (error) {
519
+ await (0, state_1.logOffAtOnce)();
520
+ throw error;
521
+ }
522
+ }
523
+ async function launchStdio(config, options, deps) {
384
524
  // The env file's context joins the process environment first — never over
385
525
  // a value already there — so its SAP_CONNECTION_TYPE and SAP_SYSTEM_TYPE
386
526
  // count (as in 15.x).
387
- (0, config_1.hydrateSystemContextFromEnvFile)(config.envFile ?? config.envFilePath);
527
+ (0, envFileContext_1.hydrateSystemContextFromEnvFile)(config.envFile ?? config.envFilePath);
388
528
  let connectionType;
389
529
  let systemType;
390
530
  try {
@@ -392,7 +532,7 @@ async function launch(config, options, deps) {
392
532
  systemType = effectiveSystemType(config, process.env);
393
533
  }
394
534
  catch (error) {
395
- deps.stderr(`[MCP] ${error instanceof Error ? error.message : 'SAP_CONNECTION_TYPE or SAP_SYSTEM_TYPE: refused'}`);
535
+ deps.stderr(`[MCP] ${error instanceof LauncherRefusal ? error.words : 'SAP_CONNECTION_TYPE or SAP_SYSTEM_TYPE: refused'}`);
396
536
  deps.exit(1);
397
537
  return;
398
538
  }
@@ -401,52 +541,68 @@ async function launch(config, options, deps) {
401
541
  // The connector reads the system type from the environment.
402
542
  if (systemType)
403
543
  process.env.SAP_SYSTEM_TYPE = systemType;
404
- config = { ...config, connectionType, systemType };
405
- const baseContext = {
406
- connection: undefined,
407
- logger: undefined,
544
+ config = {
545
+ ...withoutMessageServer(config),
546
+ connectionType,
547
+ systemType,
548
+ ...effectiveMessageServer(config, process.env),
408
549
  };
409
- // Build handlers based on exposition config (default to readonly,high)
410
- const exposition = options.exposition ??
411
- config.exposition ?? ['readonly', 'high'];
412
- (0, config_1.validateExposition)(exposition);
413
- // Non-readonly groups are built first so that their tool names can be fed
414
- // into ReadOnlyHandlersGroup for duplicate suppression (e.g. hide
415
- // ReadFunctionModule when GetFunctionModule is also exposed).
416
- const overridingGroups = [];
417
- if (exposition.includes('high')) {
418
- overridingGroups.push(new handlers_1.HighLevelHandlersGroup(baseContext));
419
- }
420
- if (exposition.includes('low')) {
421
- overridingGroups.push(new handlers_1.LowLevelHandlersGroup(baseContext));
422
- }
423
- if (exposition.includes('debug')) {
424
- overridingGroups.push(new handlers_1.DebugHandlersGroup(baseContext));
425
- }
426
- for (const group of options.extraGroups?.(baseContext) ?? []) {
427
- overridingGroups.push(group);
428
- }
429
- const overridingToolNames = new Set();
430
- for (const g of overridingGroups) {
431
- for (const e of g.getHandlers()) {
432
- overridingToolNames.add(e.toolDefinition.name);
550
+ // The command's tool set: fixed by the command, never by a flag.
551
+ const handlersRegistry = (0, tool_set_1.registryOf)(options.toolSet, 'stdio');
552
+ // The browser of a login, mapped by the platform; a choice that
553
+ // cannot be served stops the start before anything is read.
554
+ let browser;
555
+ let browserUnavailable;
556
+ try {
557
+ const mapping = (0, auth_2.browserFor)({ browser: config.browser, program: config.browserProgram }, deps.platform ?? process.platform);
558
+ // No browser on this platform refuses only a destination that logs in,
559
+ // at the startup check; the others start.
560
+ if (mapping.unavailable !== undefined) {
561
+ browserUnavailable = mapping.unavailable;
562
+ }
563
+ else {
564
+ browser = (0, auth_2.browserOf)(mapping);
433
565
  }
434
566
  }
435
- const handlerGroups = [];
436
- if (exposition.includes('readonly')) {
437
- handlerGroups.push(new handlers_1.ReadOnlyHandlersGroup(baseContext, overridingToolNames, new handlers_1.ReadVsGetDedupStrategy()));
438
- handlerGroups.push(new handlers_1.SystemHandlersGroup(baseContext));
567
+ catch (error) {
568
+ if (!(error instanceof auth_2.BrowserChoiceError))
569
+ throw error;
570
+ deps.stderr(`[MCP] ${error.words}`);
571
+ deps.exit(1);
572
+ return;
439
573
  }
440
- handlerGroups.push(...overridingGroups);
441
- // Search joins every list but a fixed one — see LauncherOptions.includeSearch.
442
- if (options.includeSearch !== false) {
443
- handlerGroups.push(new handlers_1.SearchHandlersGroup(baseContext));
574
+ if (config.authDebug === true) {
575
+ deps.stderr(exports.AUTH_DEBUG_WARNING);
444
576
  }
445
- const handlersRegistry = new handlers_1.CompositeHandlersRegistry(handlerGroups);
446
- const factory = new auth_1.AuthBrokerFactory(factoryConfigFrom(config, {
447
- browserStrategy: promptsOnStderr(deps.browserStrategy, deps.stderr, loggerForTransport),
448
- logger: loggerForTransport,
577
+ const factory = new auth_2.AuthBrokerFactory(factoryConfigFrom(config, {
578
+ browserStrategy: deps.browserStrategy,
579
+ browser,
580
+ browserUnavailable,
581
+ // A login prompts on stderr whatever DEBUG_AUTH_LOG says; the broker's
582
+ // diagnostics stay gated.
583
+ promptLogger: (0, auth_2.promptLogger)(deps.stderr, loggerForTransport),
584
+ // --auth-debug routes the providers' debug lines to stderr.
585
+ logger: config.authDebug === true ? stderrLogger : loggerForTransport,
449
586
  }));
587
+ // The start is tracked, and the shutdown installed, before anything
588
+ // is read: a signal or the client closing stdin during the startup check
589
+ // is latched like one later — latch, every owned connection logged off at
590
+ // once and the running tools interrupted, the MCP server closed (none yet
591
+ // is nothing to close), then the gate, the logins, the drain and the
592
+ // flush. A shutdown during the start ends it with exit 1.
593
+ const birth = (0, shutdown_js_1.startBirth)();
594
+ (0, shutdown_js_1.installShutdown)({
595
+ factory,
596
+ instance: { close: async () => activeServer?.close() },
597
+ onStdinEnd: true,
598
+ exit: deps.exit,
599
+ stderr: deps.stderr,
600
+ processLike: deps.processLike,
601
+ shutdownTimeoutMs: config.shutdownTimeout === undefined
602
+ ? undefined
603
+ : config.shutdownTimeout * 1000,
604
+ birth,
605
+ });
450
606
  // --mcp=X → X; an --env file → default; neither → none (one destination either way).
451
607
  const destination = factory.defaultDestination;
452
608
  if (destination) {
@@ -454,114 +610,91 @@ async function launch(config, options, deps) {
454
610
  if (config.mcpDestination) {
455
611
  (0, auth_1.assertDestinationName)(config.mcpDestination, '--mcp');
456
612
  }
457
- await checkAndSummarise(factory, destination, config, deps.stderr);
613
+ await checkAndSummarise(factory, destination, config, deps.stderr, deps.platform ?? process.platform);
458
614
  }
459
615
  catch (error) {
460
- deps.stderr(`[MCP] ${startupWords(error, destination)}`);
616
+ // A shutdown began meanwhile: its exit 1 is the process's one exit.
617
+ if (birth.shutdownBegan())
618
+ return;
619
+ deps.stderr(`[MCP] ${startupWords(error, destination, factory, deps.platform ?? process.platform)}`);
461
620
  deps.exit(1);
462
621
  return;
463
622
  }
464
623
  }
465
- if (config.transport === 'stdio') {
466
- let destinations = factory;
467
- let served;
468
- if (destination) {
469
- served = destination;
470
- }
471
- else {
472
- // Inspection-only mode: no connection parameters provided
473
- destinations = (0, StdioServer_js_1.inspectionOnlyDestinations)();
474
- served = 'mock';
475
- deps.stderr('[MCP] Starting in inspection-only mode (no connection parameters).');
476
- deps.stderr('[MCP] To connect to SAP system, use --mcp=<destination> or --env-path=<path>');
477
- }
478
- const server = new StdioServer_js_1.StdioServer(handlersRegistry, destinations, {
479
- version: options.version,
480
- stateIdleMinutes: config.stateIdleMinutes,
481
- stateLogger: exports.stateLoggerForTransport,
482
- logger: loggerForTransport,
483
- });
484
- activeServer = server;
485
- // Under stdio a signal is not the end of input: the factory's gate holds.
486
- (0, shutdown_js_1.installShutdown)({
487
- factory,
488
- servers: [
489
- {
490
- // The instance owns what it holds (a listener, a session) until it is
491
- // gone; the close waits for that and reports what was left.
492
- close: () => (0, stateClose_js_1.closeInstanceState)(server),
493
- },
494
- ],
495
- onStdinEnd: true,
496
- exit: deps.exit,
497
- stderr: deps.stderr,
498
- processLike: deps.processLike,
499
- });
500
- await server.start(served);
624
+ // The shutdown began during the check: no connector is born, no transport
625
+ // opens.
626
+ if (birth.shutdownBegan())
501
627
  return;
502
- }
503
- if (config.transport === 'sse') {
504
- const server = new SseServer_js_1.SseServer(handlersRegistry, factory, {
505
- version: options.version,
506
- stateIdleMinutes: config.stateIdleMinutes,
507
- stateLogger: exports.stateLoggerForTransport,
508
- host: config.host,
509
- port: config.port,
510
- ssePath: config.ssePath,
511
- postPath: config.postPath,
512
- defaultDestination: destination,
513
- logger: loggerForTransport,
514
- tls: config.tls,
515
- allowDestinationHeader: config.allowDestinationHeader,
516
- allowedHosts: config.allowedHosts,
517
- allowedOrigins: config.allowedOrigins,
518
- enableDnsRebindingProtection: config.enableDnsRebindingProtection,
519
- });
520
- activeServer = server;
521
- (0, shutdown_js_1.installShutdown)({
522
- factory,
523
- servers: [{ close: () => server.stop() }],
524
- exit: deps.exit,
525
- stderr: deps.stderr,
526
- processLike: deps.processLike,
527
- });
528
- await server.start();
628
+ // A destination's system kind is required: never guessed. After the
629
+ // destination's own check (which sends nothing), the start ends here
630
+ // without it — before anything is sent and before the transport.
631
+ if (destination && systemType === undefined) {
632
+ deps.stderr(`[MCP] ${startSystemTypeRequiredWords(destination)}`);
633
+ deps.exit(1);
529
634
  return;
530
635
  }
531
- // http
532
- const server = new StreamableHttpServer_js_1.StreamableHttpServer(handlersRegistry, factory, {
636
+ if (!destination) {
637
+ // Inspection-only mode: no connection parameters provided
638
+ deps.stderr('[MCP] Starting in inspection-only mode (no connection parameters).');
639
+ deps.stderr('[MCP] To connect to SAP system, use --mcp=<destination> or --env-path=<path>');
640
+ }
641
+ const server = new StdioServer_js_1.StdioServer(handlersRegistry, destination ? factory : undefined, {
533
642
  version: options.version,
643
+ // The process's runtime session files, beside the destination's
644
+ // sessions (`--auth-broker-path` moves both).
645
+ leftoverSessions: new embeddable_1.LeftoverSessions({
646
+ directory: (0, embeddable_1.runtimeDirectory)((0, platformPaths_1.getPlatformPaths)(config.authBrokerPath)[0]),
647
+ }),
648
+ // Background runs of the run tools, kept in this process's memory;
649
+ // they end with the process. Only where the set serves them: a -ro
650
+ // command has none, so a run's `background: true` is refused.
651
+ ...(options.toolSet.backgroundRuns && {
652
+ backgroundRuns: new background_runs_memory_1.InMemoryBackgroundRuns(),
653
+ }),
654
+ // Batch mode: the one instance's batch state, owned here.
655
+ batch: new embeddable_1.InstanceBatch({
656
+ keepRawParts: config.batchKeepRawParts === true,
657
+ }),
534
658
  stateIdleMinutes: config.stateIdleMinutes,
535
659
  stateLogger: exports.stateLoggerForTransport,
536
- host: config.host,
537
- port: config.port,
538
- enableJsonResponse: config.httpJsonResponse,
539
- path: config.httpPath,
540
- defaultDestination: destination,
541
660
  logger: loggerForTransport,
542
- tls: config.tls,
543
- allowDestinationHeader: config.allowDestinationHeader,
544
- allowedHosts: config.allowedHosts,
545
- allowedOrigins: config.allowedOrigins,
546
- enableDnsRebindingProtection: config.enableDnsRebindingProtection,
661
+ sentenceFor: (error) => factory.sentenceFor(error),
547
662
  });
548
663
  activeServer = server;
549
- (0, shutdown_js_1.installShutdown)({
550
- factory,
551
- servers: [{ close: () => server.stop() }],
552
- exit: deps.exit,
553
- stderr: deps.stderr,
554
- processLike: deps.processLike,
555
- });
556
- await server.start();
664
+ // The connection is born before the transport opens: nothing to retry,
665
+ // the process ends with what failed. A shutdown during the birth (stdin
666
+ // closed, a signal) ends it, and its exit — 1, the start failed — is the
667
+ // process's one exit.
668
+ if (destination) {
669
+ try {
670
+ await birth.joining(server.connectAtStart(destination));
671
+ }
672
+ catch (error) {
673
+ deps.stderr(`[MCP] ${startConnectionWords(error, destination, factory, deps.platform ?? process.platform)}`);
674
+ // The birth logged off what it logged on; the exit waits for SAP's
675
+ // answer to that logoff, so the session ends with the process.
676
+ if (!birth.shutdownBegan())
677
+ await (0, state_1.logOffAtOnce)();
678
+ if (!birth.shutdownBegan())
679
+ deps.exit(1);
680
+ return;
681
+ }
682
+ }
683
+ // The shutdown began meanwhile: the transport never opens.
684
+ if (!birth.open())
685
+ return;
686
+ // stdio unless the edges carry a transport of their own (a test's).
687
+ await (deps.transport === undefined
688
+ ? server.start(destination)
689
+ : server.start(destination, deps.transport));
557
690
  }
558
- // Run only when this module is the program. The bin calls `main()` itself, and a
559
- // sibling command imports it — neither wants a server started by an import.
560
- if (require.main === module) {
561
- void main().catch((err) => {
562
- // eslint-disable-next-line no-console
563
- console.error('[MCP] launcher failed:', err instanceof Error ? err.message : String(err));
564
- process.exit(1);
565
- });
691
+ /**
692
+ * The launcher's last line when `main()` rejects: fixed words and auth-errors'
693
+ * `logFields` of what the value classifies as — never its message.
694
+ */
695
+ function launcherFailedLine(thrown) {
696
+ return `[MCP] launcher failed: ${JSON.stringify((0, auth_errors_1.logFields)((0, auth_errors_1.classify)(thrown, 'unfamiliar-error')))}`;
566
697
  }
698
+ // The bin calls `main({ toolSet: fullToolSet, … })` itself, and a sibling
699
+ // command imports it with its own set — nothing starts a server on import.
567
700
  //# sourceMappingURL=launcher.js.map