ebay-mcp 1.13.2 → 1.14.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 (169) hide show
  1. package/README.de.md +3 -3
  2. package/README.es.md +3 -3
  3. package/README.fr.md +3 -3
  4. package/README.ja.md +3 -3
  5. package/README.ko.md +3 -3
  6. package/README.md +163 -41
  7. package/README.pt-BR.md +3 -3
  8. package/README.ru.md +3 -3
  9. package/README.zh-CN.md +3 -3
  10. package/build/api/account-management/account.js +633 -297
  11. package/build/api/analytics-and-report/analytics.js +111 -65
  12. package/build/api/client.js +199 -140
  13. package/build/api/clientRequestError.js +23 -0
  14. package/build/api/clientTrading.js +213 -0
  15. package/build/api/clientTradingError.js +4 -0
  16. package/build/api/communication/feedback.js +147 -59
  17. package/build/api/communication/message.js +134 -81
  18. package/build/api/communication/negotiation.js +65 -53
  19. package/build/api/communication/notification.js +458 -164
  20. package/build/api/developer/developer.js +99 -45
  21. package/build/api/index.js +23 -8
  22. package/build/api/listing-management/inventory.js +884 -338
  23. package/build/api/listing-metadata/metadata.js +416 -170
  24. package/build/api/listing-metadata/taxonomy.js +187 -42
  25. package/build/api/marketing-and-promotions/marketing.js +1392 -598
  26. package/build/api/marketing-and-promotions/recommendation.js +49 -24
  27. package/build/api/order-management/dispute.js +226 -45
  28. package/build/api/order-management/fulfillment.js +144 -71
  29. package/build/api/order-management/orderIssueHelpers.js +61 -0
  30. package/build/api/other/compliance.js +50 -38
  31. package/build/api/other/edelivery.js +603 -159
  32. package/build/api/other/finding.js +280 -0
  33. package/build/api/other/identity.js +30 -15
  34. package/build/api/other/translation.js +29 -14
  35. package/build/api/other/vero.js +113 -27
  36. package/build/api/rateLimitTracker.js +55 -0
  37. package/build/api/shared/request.js +189 -98
  38. package/build/api/trading/trading.js +154 -87
  39. package/build/auth/credentialSession.js +250 -0
  40. package/build/auth/oauth.js +298 -171
  41. package/build/auth/{oauth-metadata.js → oauthMetadata.js} +22 -6
  42. package/build/auth/oauthMiddleware.js +104 -0
  43. package/build/auth/{scope-utils.js → scopeUtils.js} +101 -28
  44. package/build/auth/tokenVerifier.js +243 -0
  45. package/build/auth/tokenVerifierError.js +21 -0
  46. package/build/config/environment.js +148 -113
  47. package/build/config/{tool-families.js → toolFamilies.js} +30 -14
  48. package/build/index.js +25 -19
  49. package/build/mcp/{http-transport.js → httpTransport.js} +102 -52
  50. package/build/mcp/readOnlyFilter.js +67 -0
  51. package/build/mcp/runtime.js +31 -13
  52. package/build/mcp/{tool-gating.js → toolGating.js} +77 -49
  53. package/build/mcp/{ui-bridge.js → uiBridge.js} +80 -23
  54. package/build/schemas/account-management/account.js +144 -6
  55. package/build/schemas/analytics/analytics.js +33 -19
  56. package/build/schemas/communication/messages.js +12 -42
  57. package/build/schemas/developer/developer.js +135 -0
  58. package/build/schemas/fulfillment/orders.js +183 -21
  59. package/build/schemas/index.js +27 -19
  60. package/build/schemas/inventory-management/inventory.js +17 -9
  61. package/build/schemas/marketing/marketing.js +480 -25
  62. package/build/schemas/metadata/metadata.js +11 -6
  63. package/build/schemas/other/finding.js +27 -0
  64. package/build/schemas/other/otherApis.js +424 -0
  65. package/build/schemas/taxonomy/taxonomy.js +11 -5
  66. package/build/scripts/{auto-setup.js → autoSetup.js} +87 -74
  67. package/build/scripts/{build-ui.js → buildUi.js} +6 -1
  68. package/build/scripts/{dev-sync.js → devSync.js} +169 -110
  69. package/build/scripts/diagnostics.js +52 -44
  70. package/build/scripts/{download-specs.js → downloadSpecs.js} +29 -21
  71. package/build/scripts/{interactive-setup.js → interactiveSetup.js} +84 -78
  72. package/build/scripts/setup.js +241 -178
  73. package/build/scripts/{setup-shared.js → setupShared.js} +29 -7
  74. package/build/scripts/skills.js +35 -27
  75. package/build/scripts/updateApiStatusDoc.js +71 -0
  76. package/build/serverHttp.js +90 -0
  77. package/build/skills/content.js +124 -118
  78. package/build/skills/index.js +22 -10
  79. package/build/skills/install.js +21 -10
  80. package/build/skills/markers.js +50 -15
  81. package/build/skills/{registry-snapshot.js → registrySnapshot.js} +8 -2
  82. package/build/skills/render.js +41 -14
  83. package/build/skills/targets.js +49 -17
  84. package/build/tools/categories/account.js +166 -264
  85. package/build/tools/categories/analytics.js +11 -22
  86. package/build/tools/categories/browse.js +17 -0
  87. package/build/tools/categories/communication.js +124 -399
  88. package/build/tools/categories/connector.js +23 -20
  89. package/build/tools/categories/developer.js +46 -159
  90. package/build/tools/categories/fulfillment.js +84 -215
  91. package/build/tools/categories/index.js +6 -14
  92. package/build/tools/categories/inventory.js +238 -293
  93. package/build/tools/categories/marketing.js +677 -39
  94. package/build/tools/categories/metadata.js +190 -117
  95. package/build/tools/categories/other.js +81 -208
  96. package/build/tools/categories/taxonomy.js +29 -20
  97. package/build/tools/categories/{token-management.js → tokenManagement.js} +187 -192
  98. package/build/tools/categories/trading.js +16 -47
  99. package/build/tools/contracts.js +34 -24
  100. package/build/tools/{define-tool.js → defineTool.js} +44 -29
  101. package/build/tools/registry.js +87 -29
  102. package/build/tools/schemas.js +3 -57
  103. package/build/tools/ui/archetypes.js +1 -0
  104. package/build/tools/ui/{map-helpers.js → mapHelpers.js} +69 -19
  105. package/build/tools/ui/maps.js +294 -80
  106. package/build/types/index.js +1 -1
  107. package/build/ui/card.html +14 -14
  108. package/build/ui/chart.html +14 -14
  109. package/build/ui/stat.html +87 -0
  110. package/build/ui/table.html +14 -14
  111. package/build/utils/apiStatusFeed.js +95 -0
  112. package/build/utils/cliOutput.js +15 -0
  113. package/build/utils/cliUi.js +108 -0
  114. package/build/utils/communication/feedback.js +57 -77
  115. package/build/utils/communication/message.js +69 -98
  116. package/build/utils/communication/negotiation.js +30 -57
  117. package/build/utils/communication/notification.js +112 -252
  118. package/build/utils/{date-converter.js → dateConverter.js} +62 -30
  119. package/build/utils/effectSchema.js +203 -0
  120. package/build/utils/effectSchemaAdapter.js +121 -0
  121. package/build/utils/effectSchemaChainMethods.js +146 -0
  122. package/build/utils/effectSchemaRefinements.js +104 -0
  123. package/build/utils/effectSchemaStringMethods.js +63 -0
  124. package/build/utils/effectSchemaTypes.js +47 -0
  125. package/build/utils/{env-parser.js → envParser.js} +10 -2
  126. package/build/utils/errors.js +7 -3
  127. package/build/utils/http.js +148 -89
  128. package/build/utils/{llm-client-detector.js → llmClientDetector.js} +295 -274
  129. package/build/utils/logger.js +127 -51
  130. package/build/utils/{oauth-helper.js → oauthHelper.js} +127 -90
  131. package/build/utils/other/compliance.js +18 -38
  132. package/build/utils/other/identity.js +2 -2
  133. package/build/utils/other/translation.js +4 -4
  134. package/build/utils/other/vero.js +36 -20
  135. package/build/utils/schemaHelpers.js +22 -0
  136. package/build/utils/scopeHelper.js +270 -0
  137. package/build/utils/securityChecker.js +316 -0
  138. package/build/utils/{setup-validator.js → setupValidator.js} +113 -94
  139. package/build/utils/{setup-wizard.js → setupWizard.js} +57 -46
  140. package/build/utils/{token-utils.js → tokenUtils.js} +2 -2
  141. package/build/utils/trading/trading.js +35 -0
  142. package/build/utils/typeGuards.js +12 -0
  143. package/build/utils/version.js +65 -29
  144. package/package.json +10 -8
  145. package/build/api/client-trading.js +0 -124
  146. package/build/api/communication/shared.js +0 -59
  147. package/build/api/shared/query-params.js +0 -16
  148. package/build/auth/credential-session.js +0 -166
  149. package/build/auth/oauth-middleware.js +0 -100
  150. package/build/auth/token-verifier.js +0 -186
  151. package/build/schemas/other/other-apis.js +0 -390
  152. package/build/scripts/update-api-status-doc.js +0 -44
  153. package/build/server-http.js +0 -85
  154. package/build/tools/definitions/marketing.js +0 -1381
  155. package/build/tools/tool-handlers/marketing.js +0 -312
  156. package/build/utils/account-management/account.js +0 -818
  157. package/build/utils/api-status-feed.js +0 -84
  158. package/build/utils/cli-ui.js +0 -47
  159. package/build/utils/order-management/dispute.js +0 -369
  160. package/build/utils/order-management/fulfillment.js +0 -205
  161. package/build/utils/other/edelivery.js +0 -235
  162. package/build/utils/schema-helpers.js +0 -13
  163. package/build/utils/scope-helper.js +0 -207
  164. package/build/utils/security-checker.js +0 -248
  165. package/build/utils/type-guards.js +0 -6
  166. /package/build/auth/{oauth-types.js → oauthTypes.js} +0 -0
  167. /package/build/{server-http.d.ts → serverHttp.d.ts} +0 -0
  168. /package/build/tools/ui/{view-models.js → viewModels.js} +0 -0
  169. /package/build/types/{ebay-enums.js → ebayEnums.js} +0 -0
@@ -1,11 +1,21 @@
1
- import { createAppAccessTokenExpiry, createStoredUserTokens, createStoredUserTokensFromResponse, DotEnvCredentialStore, isTokenExpired, } from '../auth/credential-session.js';
1
+ import { createAppAccessTokenExpiry, createStoredUserTokens, createStoredUserTokensFromResponse, DotEnvCredentialStore, isTokenExpired, } from '../auth/credentialSession.js';
2
2
  import { getBaseUrl, getDefaultScopes } from '../config/environment.js';
3
- import { LocaleEnum } from '../types/ebay-enums.js';
4
- import { describeHttpError, httpRequest, isHttpError } from '../utils/http.js';
3
+ import { LocaleEnum } from '../types/ebayEnums.js';
4
+ import { getErrorMessage } from '../utils/errors.js';
5
+ import { describeHttpError, httpRequestEffect } from '../utils/http.js';
5
6
  import { authLogger } from '../utils/logger.js';
7
+ import { Data, Effect, Either } from 'effect';
8
+ /** Tagged failure returned by migrated OAuth token Effects. */
9
+ export class EbayOAuthError extends Data.TaggedError('EbayOAuthError') {
10
+ }
11
+ const mapCredentialStoreError = (operation, message, cause) => new EbayOAuthError({
12
+ operation,
13
+ message: `${message}: ${cause.message}`,
14
+ cause,
15
+ });
6
16
  /**
7
17
  * Manages eBay OAuth 2.0 authentication
8
- * Loads tokens exclusively from environment variables (.env file)
18
+ * Loads tokens exclusively from validated runtime config
9
19
  * Supports both client credentials (app tokens) and user access tokens with refresh
10
20
  */
11
21
  export class EbayOAuthClient {
@@ -19,41 +29,65 @@ export class EbayOAuthClient {
19
29
  this.credentialStore = credentialStore;
20
30
  }
21
31
  /**
22
- * Initialize user tokens from environment variables only
23
- * If EBAY_USER_REFRESH_TOKEN exists, automatically refresh to get a valid access token
32
+ * Execute an OAuth token endpoint request and map HTTP failures once.
33
+ */
34
+ requestOAuthToken(operation, failureMessage, options) {
35
+ return httpRequestEffect(options).pipe(Effect.map((response) => response.data), Effect.mapError((cause) => new EbayOAuthError({
36
+ operation,
37
+ message: `${failureMessage}: ${describeHttpError(cause)}`,
38
+ cause,
39
+ })));
40
+ }
41
+ /**
42
+ * Initialize user tokens from validated runtime config.
43
+ *
44
+ * @returns An Effect that completes after loading and refreshing configured tokens.
45
+ *
46
+ * @example
47
+ * ```ts
48
+ * await Effect.runPromise(oauthClient.initialize());
49
+ * ```
24
50
  */
25
- async initialize() {
26
- const envRefreshToken = process.env.EBAY_USER_REFRESH_TOKEN;
27
- const envAccessToken = process.env.EBAY_USER_ACCESS_TOKEN;
28
- const envAppToken = process.env.EBAY_APP_ACCESS_TOKEN ?? '';
51
+ initialize = () => Effect.gen(this, function* () {
52
+ const configRefreshToken = this.config.refreshToken;
53
+ const configAccessToken = this.config.accessToken ?? '';
54
+ const configAppToken = this.config.appAccessToken ?? '';
29
55
  const locale = this.config?.locale || LocaleEnum.en_US;
30
- if (envRefreshToken) {
31
- authLogger.info('Loading tokens from environment variables');
56
+ if (configRefreshToken) {
57
+ authLogger.info('Loading tokens from runtime config');
32
58
  this.userTokens = createStoredUserTokens({
33
59
  config: { ...this.config, locale },
34
- envAppToken,
35
- accessToken: envAccessToken || '',
36
- refreshToken: envRefreshToken,
60
+ envAppToken: configAppToken,
61
+ accessToken: configAccessToken,
62
+ refreshToken: configRefreshToken,
37
63
  });
38
64
  // Immediately refresh to get a valid access token and scopes
39
65
  authLogger.info('Refreshing access token using refresh token from .env');
40
- try {
41
- await this.refreshUserToken();
66
+ const refreshed = yield* Effect.either(Effect.gen(this, function* () {
67
+ yield* this.refreshUserToken();
42
68
  authLogger.info('Access token refreshed successfully');
43
- await this.getOrRefreshAppAccessToken();
44
- }
45
- catch (error) {
69
+ yield* this.getOrRefreshAppAccessToken();
70
+ }));
71
+ if (Either.isLeft(refreshed)) {
72
+ const error = refreshed.left;
46
73
  authLogger.error('Failed to refresh access token', {
47
- error: error instanceof Error ? error.message : String(error),
48
- hint: 'The EBAY_USER_REFRESH_TOKEN in .env may be invalid or expired',
74
+ error: getErrorMessage(error, String(error)),
75
+ hint: 'The configured EBAY_USER_REFRESH_TOKEN may be invalid or expired',
49
76
  });
50
77
  // Clear invalid tokens
51
78
  this.userTokens = null;
52
79
  }
53
80
  }
54
- }
81
+ });
55
82
  /**
56
- * Check if user tokens are available
83
+ * Check if user tokens are available.
84
+ *
85
+ * @returns True when user tokens are currently loaded in memory.
86
+ *
87
+ * @example
88
+ * ```ts
89
+ * const hasTokens = oauthClient.hasUserTokens();
90
+ * ```
57
91
  */
58
92
  hasUserTokens() {
59
93
  return this.userTokens !== null;
@@ -74,8 +108,15 @@ export class EbayOAuthClient {
74
108
  * Get a valid access token, with priority order:
75
109
  * 1. User access token (if available and valid, or refreshable)
76
110
  * 2. App access token from client credentials (fallback)
111
+ *
112
+ * @returns An Effect that succeeds with the token used for eBay API requests.
113
+ *
114
+ * @example
115
+ * ```ts
116
+ * const token = await Effect.runPromise(oauthClient.getAccessToken());
117
+ * ```
77
118
  */
78
- async getAccessToken() {
119
+ getAccessToken = () => Effect.gen(this, function* () {
79
120
  // Try to use user token first
80
121
  if (this.userTokens) {
81
122
  // Check if access token is still valid
@@ -83,38 +124,50 @@ export class EbayOAuthClient {
83
124
  return this.userTokens.userAccessToken;
84
125
  }
85
126
  // Try to refresh if refresh token is valid
86
- if (!this.isUserRefreshTokenExpired(this.userTokens)) {
87
- try {
88
- await this.refreshUserToken();
89
- return this.userTokens.userAccessToken;
90
- }
91
- catch (error) {
92
- authLogger.error('Failed to refresh user token, falling back to app access token', {
93
- error: error instanceof Error ? error.message : String(error),
94
- });
95
- // Clear invalid tokens
96
- this.userTokens = null;
97
- }
98
- }
99
- else {
127
+ if (this.isUserRefreshTokenExpired(this.userTokens)) {
100
128
  // Refresh token expired
101
129
  authLogger.error('User refresh token expired. User needs to re-authorize.');
102
130
  this.userTokens = null;
103
- throw new Error('User authorization expired. Please update EBAY_USER_REFRESH_TOKEN in .env with a new refresh token.');
131
+ return yield* Effect.fail(new EbayOAuthError({
132
+ operation: 'getAccessToken',
133
+ message: 'User authorization expired. Please update EBAY_USER_REFRESH_TOKEN in .env with a new refresh token.',
134
+ }));
135
+ }
136
+ const refreshed = yield* Effect.either(this.refreshUserToken());
137
+ if (Either.isLeft(refreshed)) {
138
+ authLogger.error('Failed to refresh user token, falling back to app access token', {
139
+ error: getErrorMessage(refreshed.left, String(refreshed.left)),
140
+ });
141
+ // Clear invalid tokens
142
+ this.userTokens = null;
143
+ }
144
+ else if (this.userTokens) {
145
+ return this.userTokens.userAccessToken;
104
146
  }
105
147
  }
106
148
  // Fallback to app access token (client credentials)
107
149
  if (this.appAccessToken && !isTokenExpired(this.appAccessTokenExpiry)) {
108
150
  return this.appAccessToken;
109
151
  }
110
- await this.getOrRefreshAppAccessToken();
111
- return this.appAccessToken;
112
- }
152
+ return yield* this.getOrRefreshAppAccessToken();
153
+ });
113
154
  /**
114
- * Set user access token and refresh token
115
- * Stores tokens in memory and updates .env file for persistence
155
+ * Set user access token and refresh token.
156
+ *
157
+ * Stores tokens in memory and updates `.env` for persistence.
158
+ *
159
+ * @param accessToken - User access token returned by eBay OAuth.
160
+ * @param refreshToken - User refresh token returned by eBay OAuth.
161
+ * @param accessTokenExpiry - Optional access-token expiry timestamp in milliseconds.
162
+ * @param refreshTokenExpiry - Optional refresh-token expiry timestamp in milliseconds.
163
+ * @returns An Effect that completes after the tokens are stored and persisted.
164
+ *
165
+ * @example
166
+ * ```ts
167
+ * await Effect.runPromise(oauthClient.setUserTokens(accessToken, refreshToken));
168
+ * ```
116
169
  */
117
- setUserTokens(accessToken, refreshToken, accessTokenExpiry, refreshTokenExpiry) {
170
+ setUserTokens = (accessToken, refreshToken, accessTokenExpiry, refreshTokenExpiry) => Effect.gen(this, function* () {
118
171
  this.userTokens = createStoredUserTokens({
119
172
  config: this.config,
120
173
  accessToken,
@@ -122,18 +175,26 @@ export class EbayOAuthClient {
122
175
  accessTokenExpiry,
123
176
  refreshTokenExpiry,
124
177
  });
125
- // Update .env file with new tokens
126
- this.credentialStore.write({
178
+ yield* this.credentialStore
179
+ .write({
127
180
  EBAY_USER_ACCESS_TOKEN: accessToken,
128
181
  EBAY_USER_REFRESH_TOKEN: refreshToken,
129
- });
130
- }
182
+ })
183
+ .pipe(Effect.mapError((cause) => mapCredentialStoreError('setUserTokens', 'Failed to persist user tokens', cause)));
184
+ });
131
185
  /**
132
186
  * Get or refresh the app access token using the client credentials flow.
133
187
  * This method ensures that a valid app access token is always available.
134
188
  * Rate limit: 1,000 requests/day
189
+ *
190
+ * @returns An Effect that succeeds with a cached or newly minted app access token.
191
+ *
192
+ * @example
193
+ * ```ts
194
+ * const appToken = await Effect.runPromise(oauthClient.getOrRefreshAppAccessToken());
195
+ * ```
135
196
  */
136
- async getOrRefreshAppAccessToken() {
197
+ getOrRefreshAppAccessToken = () => Effect.gen(this, function* () {
137
198
  // Return cached token if still valid
138
199
  if (this.appAccessToken && !isTokenExpired(this.appAccessTokenExpiry)) {
139
200
  return this.appAccessToken;
@@ -143,131 +204,155 @@ export class EbayOAuthClient {
143
204
  // Client credentials flow only supports basic scope
144
205
  // User authorization flows can request additional scopes
145
206
  const scopeParam = 'https://api.ebay.com/oauth/api_scope';
146
- try {
147
- const response = await httpRequest({
148
- method: 'POST',
149
- url: authUrl,
150
- body: new URLSearchParams({
151
- grant_type: 'client_credentials',
152
- scope: scopeParam,
153
- }),
154
- headers: {
155
- 'Content-Type': 'application/x-www-form-urlencoded',
156
- Authorization: `Basic ${credentials}`,
157
- },
158
- });
159
- this.appAccessToken = response.data.access_token;
160
- this.appAccessTokenExpiry = createAppAccessTokenExpiry(response.data.expires_in);
161
- // Update .env file with app access token
162
- this.credentialStore.write({
163
- EBAY_APP_ACCESS_TOKEN: this.appAccessToken,
164
- });
165
- return this.appAccessToken;
166
- }
167
- catch (error) {
168
- if (isHttpError(error)) {
169
- throw new Error(`Failed to get app access token: ${describeHttpError(error)}`);
170
- }
171
- throw error;
172
- }
173
- }
207
+ const tokenData = yield* this.requestOAuthToken('getOrRefreshAppAccessToken', 'Failed to get app access token', {
208
+ method: 'POST',
209
+ url: authUrl,
210
+ body: new URLSearchParams({
211
+ grant_type: 'client_credentials',
212
+ scope: scopeParam,
213
+ }),
214
+ headers: {
215
+ 'Content-Type': 'application/x-www-form-urlencoded',
216
+ Authorization: `Basic ${credentials}`,
217
+ },
218
+ });
219
+ this.appAccessToken = tokenData.access_token;
220
+ this.appAccessTokenExpiry = createAppAccessTokenExpiry(tokenData.expires_in);
221
+ // Update .env file with app access token
222
+ yield* this.credentialStore
223
+ .write({
224
+ EBAY_APP_ACCESS_TOKEN: this.appAccessToken ?? '',
225
+ })
226
+ .pipe(Effect.mapError((cause) => mapCredentialStoreError('getOrRefreshAppAccessToken', 'Failed to persist app access token', cause)));
227
+ this.config = {
228
+ ...this.config,
229
+ appAccessToken: this.appAccessToken,
230
+ };
231
+ return this.appAccessToken;
232
+ });
174
233
  /**
175
- * Exchange authorization code for user access token
176
- * Persists received tokens to .env automatically
234
+ * Exchange authorization code for user access token.
235
+ *
236
+ * Persists received tokens to `.env` automatically.
237
+ *
238
+ * @param code - Authorization code received from eBay's OAuth redirect.
239
+ * @returns An Effect that succeeds with eBay's user token response.
240
+ *
241
+ * @example
242
+ * ```ts
243
+ * const token = await Effect.runPromise(oauthClient.exchangeCodeForToken(code));
244
+ * ```
177
245
  */
178
- async exchangeCodeForToken(code) {
246
+ exchangeCodeForToken = (code) => Effect.gen(this, function* () {
179
247
  if (!this.config.redirectUri) {
180
- throw new Error('Redirect URI is required for authorization code exchange');
248
+ return yield* Effect.fail(new EbayOAuthError({
249
+ operation: 'exchangeCodeForToken',
250
+ message: 'Redirect URI is required for authorization code exchange',
251
+ }));
181
252
  }
182
253
  const tokenUrl = `${getBaseUrl(this.config.environment, this.config.apiBaseUrl)}/identity/v1/oauth2/token`;
183
254
  const credentials = Buffer.from(`${this.config.clientId}:${this.config.clientSecret}`).toString('base64');
184
- try {
185
- const response = await httpRequest({
186
- method: 'POST',
187
- url: tokenUrl,
188
- body: new URLSearchParams({
189
- grant_type: 'authorization_code',
190
- code,
191
- redirect_uri: this.config.redirectUri,
192
- }),
193
- headers: {
194
- 'Content-Type': 'application/x-www-form-urlencoded',
195
- Authorization: `Basic ${credentials}`,
196
- },
197
- });
198
- const tokenData = response.data;
199
- this.userTokens = createStoredUserTokensFromResponse({
200
- config: this.config,
201
- tokenData,
202
- });
203
- // Persist tokens to .env so they survive process restarts.
204
- this.credentialStore.write({
205
- EBAY_USER_ACCESS_TOKEN: tokenData.access_token,
206
- EBAY_USER_REFRESH_TOKEN: tokenData.refresh_token,
207
- });
208
- return tokenData;
209
- }
210
- catch (error) {
211
- if (isHttpError(error)) {
212
- throw new Error(`Failed to exchange code for token: ${describeHttpError(error)}`);
213
- }
214
- throw error;
215
- }
216
- }
255
+ const tokenData = yield* this.requestOAuthToken('exchangeCodeForToken', 'Failed to exchange code for token', {
256
+ method: 'POST',
257
+ url: tokenUrl,
258
+ body: new URLSearchParams({
259
+ grant_type: 'authorization_code',
260
+ code,
261
+ redirect_uri: this.config.redirectUri,
262
+ }),
263
+ headers: {
264
+ 'Content-Type': 'application/x-www-form-urlencoded',
265
+ Authorization: `Basic ${credentials}`,
266
+ },
267
+ });
268
+ this.userTokens = createStoredUserTokensFromResponse({
269
+ config: this.config,
270
+ tokenData,
271
+ });
272
+ // Persist tokens to .env so they survive process restarts.
273
+ yield* this.credentialStore
274
+ .write({
275
+ EBAY_USER_ACCESS_TOKEN: tokenData.access_token,
276
+ EBAY_USER_REFRESH_TOKEN: tokenData.refresh_token,
277
+ })
278
+ .pipe(Effect.mapError((cause) => mapCredentialStoreError('exchangeCodeForToken', 'Failed to persist exchanged user tokens', cause)));
279
+ this.config = {
280
+ ...this.config,
281
+ accessToken: tokenData.access_token,
282
+ refreshToken: tokenData.refresh_token,
283
+ };
284
+ return tokenData;
285
+ });
217
286
  /**
218
- * Refresh user access token using refresh token from .env
219
- * This method is public and can be called by LLMs when encountering authentication errors
287
+ * Refresh user access token using the stored refresh token.
288
+ *
289
+ * This method is public so tools can recover from authentication errors.
290
+ *
291
+ * @returns An Effect that completes after the user token is refreshed and persisted.
292
+ *
293
+ * @example
294
+ * ```ts
295
+ * await Effect.runPromise(oauthClient.refreshUserToken());
296
+ * ```
220
297
  */
221
- async refreshUserToken() {
298
+ refreshUserToken = () => Effect.gen(this, function* () {
222
299
  if (!this.userTokens) {
223
- throw new Error('No user tokens available to refresh');
300
+ return yield* Effect.fail(new EbayOAuthError({
301
+ operation: 'refreshUserToken',
302
+ message: 'No user tokens available to refresh',
303
+ }));
224
304
  }
225
305
  // Use the token endpoint, not the authorization endpoint
226
306
  const authUrl = `${getBaseUrl(this.config.environment, this.config.apiBaseUrl)}/identity/v1/oauth2/token`;
227
307
  const credentials = Buffer.from(`${this.config.clientId}:${this.config.clientSecret}`).toString('base64');
228
- try {
229
- // Prepare refresh token request parameters
230
- // Note: We do NOT include scopes in refresh requests as eBay will return
231
- // the scopes that were originally granted to the refresh token
232
- const params = {
233
- grant_type: 'refresh_token',
234
- refresh_token: this.userTokens.userRefreshToken,
235
- };
236
- const response = await httpRequest({
237
- method: 'POST',
238
- url: authUrl,
239
- body: new URLSearchParams(params),
240
- headers: {
241
- 'Content-Type': 'application/x-www-form-urlencoded',
242
- Authorization: `Basic ${credentials}`,
243
- },
244
- });
245
- const tokenData = response.data;
246
- this.userTokens = createStoredUserTokensFromResponse({
247
- config: this.config,
248
- previousTokens: this.userTokens,
249
- tokenData,
250
- });
251
- // Update .env file with new tokens
252
- const envUpdates = {
253
- EBAY_USER_ACCESS_TOKEN: tokenData.access_token,
254
- };
255
- // Reconcile .env with the authoritative in-memory refresh token.
256
- if (this.userTokens.userRefreshToken !== process.env.EBAY_USER_REFRESH_TOKEN) {
257
- envUpdates.EBAY_USER_REFRESH_TOKEN = this.userTokens.userRefreshToken;
258
- }
259
- // Write updates to .env file
260
- this.credentialStore.write(envUpdates);
261
- }
262
- catch (error) {
263
- if (isHttpError(error)) {
264
- throw new Error(`Failed to refresh token: ${describeHttpError(error)}`);
265
- }
266
- throw error;
308
+ // Prepare refresh token request parameters
309
+ // Note: We do NOT include scopes in refresh requests as eBay will return
310
+ // the scopes that were originally granted to the refresh token
311
+ const params = {
312
+ grant_type: 'refresh_token',
313
+ refresh_token: this.userTokens.userRefreshToken,
314
+ };
315
+ const tokenData = yield* this.requestOAuthToken('refreshUserToken', 'Failed to refresh token', {
316
+ method: 'POST',
317
+ url: authUrl,
318
+ body: new URLSearchParams(params),
319
+ headers: {
320
+ 'Content-Type': 'application/x-www-form-urlencoded',
321
+ Authorization: `Basic ${credentials}`,
322
+ },
323
+ });
324
+ this.userTokens = createStoredUserTokensFromResponse({
325
+ config: this.config,
326
+ previousTokens: this.userTokens,
327
+ tokenData,
328
+ });
329
+ // Update .env file with new tokens
330
+ const envUpdates = {
331
+ EBAY_USER_ACCESS_TOKEN: tokenData.access_token,
332
+ };
333
+ // Reconcile persisted config with the authoritative in-memory refresh token.
334
+ if (this.userTokens.userRefreshToken !== this.config.refreshToken) {
335
+ envUpdates.EBAY_USER_REFRESH_TOKEN = this.userTokens.userRefreshToken;
267
336
  }
268
- }
337
+ // Write updates to .env file
338
+ yield* this.credentialStore
339
+ .write(envUpdates)
340
+ .pipe(Effect.mapError((cause) => mapCredentialStoreError('refreshUserToken', 'Failed to persist refreshed user token', cause)));
341
+ this.config = {
342
+ ...this.config,
343
+ accessToken: tokenData.access_token,
344
+ refreshToken: this.userTokens.userRefreshToken,
345
+ };
346
+ });
269
347
  /**
270
- * Check if currently authenticated (either user or app credentials)
348
+ * Check if currently authenticated with user or app credentials.
349
+ *
350
+ * @returns True when a non-expired user token or app token is available.
351
+ *
352
+ * @example
353
+ * ```ts
354
+ * const authenticated = oauthClient.isAuthenticated();
355
+ * ```
271
356
  */
272
357
  isAuthenticated() {
273
358
  if (this.userTokens && !this.isUserAccessTokenExpired(this.userTokens)) {
@@ -276,8 +361,16 @@ export class EbayOAuthClient {
276
361
  return this.appAccessToken !== null && !isTokenExpired(this.appAccessTokenExpiry);
277
362
  }
278
363
  /**
279
- * Clear all authentication tokens from memory
280
- * Note: To persist this change, remove EBAY_USER_REFRESH_TOKEN from .env
364
+ * Clear all authentication tokens from memory.
365
+ *
366
+ * To persist this change, remove `EBAY_USER_REFRESH_TOKEN` from `.env`.
367
+ *
368
+ * @returns Nothing; the in-memory token cache is cleared synchronously.
369
+ *
370
+ * @example
371
+ * ```ts
372
+ * oauthClient.clearAllTokens();
373
+ * ```
281
374
  */
282
375
  clearAllTokens() {
283
376
  this.appAccessToken = null;
@@ -285,7 +378,14 @@ export class EbayOAuthClient {
285
378
  this.userTokens = null;
286
379
  }
287
380
  /**
288
- * Get current token info for debugging
381
+ * Get current token info for debugging and status tools.
382
+ *
383
+ * @returns Token availability and scope comparison details.
384
+ *
385
+ * @example
386
+ * ```ts
387
+ * const tokenInfo = oauthClient.getTokenInfo();
388
+ * ```
289
389
  */
290
390
  getTokenInfo() {
291
391
  const info = {
@@ -298,30 +398,57 @@ export class EbayOAuthClient {
298
398
  const environmentScopes = getDefaultScopes(this.config.environment);
299
399
  const tokenScopeSet = new Set(tokenScopes);
300
400
  const missingScopes = environmentScopes.filter((scope) => !tokenScopeSet.has(scope));
301
- info.scopeInfo = {
302
- tokenScopes,
303
- environmentScopes,
304
- missingScopes,
401
+ return {
402
+ ...info,
403
+ scopeInfo: {
404
+ tokenScopes,
405
+ environmentScopes,
406
+ missingScopes,
407
+ },
305
408
  };
306
409
  }
307
410
  return info;
308
411
  }
309
412
  /**
310
- * Get internal user tokens (for debugging/status tools)
413
+ * Get internal user tokens for debugging and status tools.
414
+ *
415
+ * @returns The loaded user token data, or null when no user token is available.
416
+ *
417
+ * @example
418
+ * ```ts
419
+ * const tokens = oauthClient.getUserTokens();
420
+ * ```
421
+ *
311
422
  * @internal
312
423
  */
313
424
  getUserTokens() {
314
425
  return this.userTokens;
315
426
  }
316
427
  /**
317
- * Get internal app access token cached value (for debugging/status tools)
428
+ * Get internal app access token cached value for debugging and status tools.
429
+ *
430
+ * @returns The cached app access token, or null when no token is cached.
431
+ *
432
+ * @example
433
+ * ```ts
434
+ * const appToken = oauthClient.getCachedAppAccessToken();
435
+ * ```
436
+ *
318
437
  * @internal
319
438
  */
320
439
  getCachedAppAccessToken() {
321
440
  return this.appAccessToken;
322
441
  }
323
442
  /**
324
- * Get internal app access token expiry (for debugging/status tools)
443
+ * Get internal app access token expiry for debugging and status tools.
444
+ *
445
+ * @returns The cached app access token expiry timestamp in milliseconds.
446
+ *
447
+ * @example
448
+ * ```ts
449
+ * const expiresAt = oauthClient.getCachedAppAccessTokenExpiry();
450
+ * ```
451
+ *
325
452
  * @internal
326
453
  */
327
454
  getCachedAppAccessTokenExpiry() {
@@ -5,12 +5,20 @@
5
5
  import { Router as createRouter } from 'express';
6
6
  /**
7
7
  * Create Express router with OAuth metadata endpoints
8
+ *
9
+ * @param config - Protected resource metadata and optional eBay context.
10
+ * @returns Express router exposing OAuth protected-resource metadata endpoints.
11
+ *
12
+ * @example
13
+ * ```ts
14
+ * const router = createMetadataRouter({ resourceServerUrl, authServerMetadata, scopesSupported });
15
+ * ```
8
16
  */
9
- export function createMetadataRouter(config) {
17
+ export const createMetadataRouter = (config) => {
10
18
  const router = createRouter();
11
19
  // RFC 9728: Protected Resource Metadata endpoint
12
20
  // Path: /.well-known/oauth-protected-resource
13
- router.get('/.well-known/oauth-protected-resource', (req, res) => {
21
+ router.get('/.well-known/oauth-protected-resource', (_req, res) => {
14
22
  const authServers = typeof config.authServerMetadata === 'string'
15
23
  ? [config.authServerMetadata]
16
24
  : [config.authServerMetadata.issuer];
@@ -25,7 +33,7 @@ export function createMetadataRouter(config) {
25
33
  res.json(metadata);
26
34
  });
27
35
  // Optional: Server info endpoint for debugging
28
- router.get('/.well-known/mcp-server-info', (req, res) => {
36
+ router.get('/.well-known/mcp-server-info', (_req, res) => {
29
37
  const serverInfo = {
30
38
  name: config.resourceName || 'MCP Resource Server',
31
39
  version: '1.0.0',
@@ -48,12 +56,20 @@ export function createMetadataRouter(config) {
48
56
  res.json(serverInfo);
49
57
  });
50
58
  return router;
51
- }
59
+ };
52
60
  /**
53
61
  * Helper to get Protected Resource Metadata URL from server URL
62
+ *
63
+ * @param serverUrl - Public HTTP server URL.
64
+ * @returns URL for the RFC 9728 protected-resource metadata endpoint.
65
+ *
66
+ * @example
67
+ * ```ts
68
+ * const url = getProtectedResourceMetadataUrl('http://localhost:3000');
69
+ * ```
54
70
  */
55
- export function getProtectedResourceMetadataUrl(serverUrl) {
71
+ export const getProtectedResourceMetadataUrl = (serverUrl) => {
56
72
  const url = new URL(serverUrl);
57
73
  url.pathname = '/.well-known/oauth-protected-resource';
58
74
  return url.toString();
59
- }
75
+ };